<?php
session_start();
include '../layouts/dbconn.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SESSION['role_code'] !== 'RESIDENT_DOCTOR') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

try {
    $resident_doctor_id = (int)$_POST['resident_doctor_id'];
    $case_title = mysqli_real_escape_string($conn, $_POST['case_title']);
    $case_date = mysqli_real_escape_string($conn, $_POST['case_date']);
    $case_category = mysqli_real_escape_string($conn, $_POST['case_category']);
    $chief_complaint = mysqli_real_escape_string($conn, $_POST['chief_complaint'] ?? '');
    $diagnosis = mysqli_real_escape_string($conn, $_POST['diagnosis'] ?? '');
    $key_learnings = mysqli_real_escape_string($conn, $_POST['key_learnings'] ?? '');

    // Generate case number
    $year = date('Y');
    $count_sql = "SELECT COUNT(*) as count FROM resident_case_studies WHERE resident_doctor_id = ? AND YEAR(case_date) = ?";
    $count_stmt = $conn->prepare($count_sql);
    $count_stmt->bind_param('ii', $resident_doctor_id, $year);
    $count_stmt->execute();
    $count = $count_stmt->get_result()->fetch_assoc()['count'];
    $case_number = "CASE-{$year}-RES{$resident_doctor_id}-" . str_pad($count + 1, 4, '0', STR_PAD_LEFT);

    // Insert case study
    $sql = "INSERT INTO resident_case_studies (
                case_number, resident_doctor_id, case_title, case_date,
                case_category, chief_complaint, diagnosis, key_learnings, status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'DRAFT')";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param(
        'sissssss',
        $case_number, $resident_doctor_id, $case_title, $case_date,
        $case_category, $chief_complaint, $diagnosis, $key_learnings
    );

    if ($stmt->execute()) {
        $case_id = $stmt->insert_id;
        
        // Log activity
        $activity_desc = "Created case study: " . $case_title;
        $activity_sql = "INSERT INTO activity_logs (user_id, activity_type, activity_description) VALUES (?, 'CASE_STUDY', ?)";
        $activity_stmt = $conn->prepare($activity_sql);
        $activity_stmt->bind_param('is', $_SESSION['user_id'], $activity_desc);
        $activity_stmt->execute();

        echo json_encode([
            'success' => true,
            'message' => 'Case study created successfully!',
            'case_id' => $case_id,
            'case_number' => $case_number
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to create case study: ' . $stmt->error]);
    }

    $stmt->close();
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

mysqli_close($conn);
?>