<?php
/**
 * AJAX: Save Case
 * Save case from repertorization page
 * Method: POST
 */

require_once '../config/config.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';
require_once '../includes/repertory-engine.php';

session_start();
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit;
}

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

$pdo = getDB();
$userId = $_SESSION['user_id'];

// Get form data
$patientName = trim($_POST['patient_name'] ?? '');
$patientMobile = trim($_POST['patient_mobile'] ?? '');
$patientAge = !empty($_POST['patient_age']) ? (int)$_POST['patient_age'] : null;
$patientGender = $_POST['patient_gender'] ?? null;
$chiefComplaint = trim($_POST['chief_complaint'] ?? '');
$caseHistory = trim($_POST['case_history'] ?? '');
$physicalGenerals = trim($_POST['physical_generals'] ?? '');
$mentalEmotional = trim($_POST['mental_emotional'] ?? '');
$modalities = trim($_POST['modalities'] ?? '');
$selectedRubrics = json_decode($_POST['selected_rubrics'] ?? '[]', true);

// Validation
$errors = [];
if (empty($patientName)) $errors[] = "Patient name is required";
if (empty($patientMobile)) $errors[] = "Mobile number is required";
if (empty($chiefComplaint)) $errors[] = "Chief complaint is required";

if (!empty($errors)) {
    echo json_encode(['success' => false, 'errors' => $errors]);
    exit;
}

// Perform repertorization
$rubricsWithWeights = [];
foreach ($selectedRubrics as $rubricId) {
    $rubricsWithWeights[$rubricId] = ['weight' => 1];
}
$scores = repertorize($rubricsWithWeights);

$topRemedies = [];
$count = 0;
foreach ($scores as $remedyId => $data) {
    if ($count++ >= 20) break;
    $topRemedies[] = [
        'remedy_id' => $remedyId,
        'remedy_name' => $data['name'],
        'score' => $data['score']
    ];
}

// Insert case
$stmt = $pdo->prepare("INSERT INTO cases (user_id, patient_name, patient_mobile, patient_age, patient_gender, 
                      chief_complaint, case_history, physical_generals, mental_emotional, modalities, 
                      selected_rubrics, repertorization_result, status, created_at) 
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW())");

$result = $stmt->execute([
    $userId, $patientName, $patientMobile, $patientAge, $patientGender,
    $chiefComplaint, $caseHistory, $physicalGenerals, $mentalEmotional, $modalities,
    json_encode($selectedRubrics), json_encode($topRemedies)
]);

if ($result) {
    $caseId = $pdo->lastInsertId();
    
    // Clear temporary rubrics from session
    unset($_SESSION['temp_rubrics']);
    
    echo json_encode([
        'success' => true,
        'message' => 'Case saved successfully',
        'case_id' => $caseId,
        'redirect' => "../doctor/cases/view.php?id=$caseId"
    ]);
} else {
    echo json_encode(['success' => false, 'error' => 'Failed to save case']);
}
?>