<?php
/**
 * Save Case - POST Handler
 * Save new case to database
 */

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

requireLogin();

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

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    header('Location: new.php');
    exit;
}

// Get form data
$patientName = trim($_POST['patient_name']);
$patientMobile = trim($_POST['patient_mobile']);
$patientAge = $_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)) {
    $_SESSION['case_errors'] = $errors;
    header('Location: new.php');
    exit;
}

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

// Save top 20 remedies
$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) 
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')");

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

if ($result) {
    $caseId = $pdo->lastInsertId();
    header("Location: view.php?id=$caseId&msg=Case saved successfully");
} else {
    header("Location: new.php?error=Failed to save case");
}
exit;
?>