<?php
/**
 * Edit Case Information
 * Update case details and repertorization
 */

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

requireLogin();

$pdo = getDB();
$caseId = (int)($_GET['id'] ?? 0);
$userId = $_SESSION['user_id'];

$stmt = $pdo->prepare("SELECT * FROM cases WHERE id = ? AND user_id = ?");
$stmt->execute([$caseId, $userId]);
$case = $stmt->fetch();

if (!$case) { header('Location: list.php?error=Case not found'); exit; }

$selectedRubrics = json_decode($case['selected_rubrics'], true) ?: [];
$_SESSION['temp_rubrics'] = $selectedRubrics;

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $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) ?: [];
    
    $stmt = $pdo->prepare("UPDATE cases SET patient_name=?, patient_mobile=?, patient_age=?, patient_gender=?,
                          chief_complaint=?, case_history=?, physical_generals=?, mental_emotional=?, modalities=?,
                          selected_rubrics=? WHERE id=? AND user_id=?");
    $stmt->execute([$patientName, $patientMobile, $patientAge, $patientGender, $chiefComplaint, 
                   $caseHistory, $physicalGenerals, $mentalEmotional, $modalities, 
                   json_encode($selectedRubrics), $caseId, $userId]);
    
    header("Location: view.php?id=$caseId&msg=Case updated successfully");
    exit;
}

$remedies = $pdo->query("SELECT id, name FROM remedies ORDER BY name")->fetchAll();
?>
<!DOCTYPE html>
<html>
<head><title>Edit Case</title><link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
<style>
.sidebar { min-height: 100vh; background: linear-gradient(135deg, #1a472a 0%, #0d2818 100%); position: fixed; left: 0; top: 0; width: 260px; }
.sidebar .nav-link { color: rgba(255,255,255,0.8); padding: 12px 20px; }
.main-content { margin-left: 260px; padding: 20px; }
.rubric-browser, .selected-rubrics { height: 70vh; overflow-y: auto; }
.selected-rubric-item { background: #e8f4f8; padding: 8px; margin-bottom: 5px; border-radius: 5px; display: flex; justify-content: space-between; }
@media (max-width: 768px) { .sidebar { width: 70px; } .main-content { margin-left: 70px; } }
</style>
</head>
<body>
<div class="sidebar"><div class="text-center py-4"><h4 class="text-white">🏥 Homoeopathy</h4></div>
    <nav class="nav flex-column"><a class="nav-link" href="../dashboard.php">Dashboard</a><a class="nav-link" href="list.php">Cases</a><a class="nav-link" href="../profile.php">Profile</a><hr><a class="nav-link" href="../../logout.php">Logout</a></nav>
</div>
<div class="main-content">
    <div class="d-flex justify-content-between"><h4>Edit Case: <?php echo escape($case['patient_name']); ?></h4><a href="view.php?id=<?php echo $caseId; ?>" class="btn btn-secondary">Back</a></div>
    <form method="POST">
        <div class="row">
            <div class="col-md-4 rubric-browser"><h5>Repertory</h5><div id="rubricTree"><?php echo getRubricTreeHTML(); ?></div></div>
            <div class="col-md-3 selected-rubrics"><h5>Selected Symptoms</h5><div id="selectedList"><?php foreach($selectedRubrics as $rid): $r = $pdo->prepare("SELECT full_path FROM rubrics WHERE id=?"); $r->execute([$rid]); $rub = $r->fetch(); if($rub): ?><div class="selected-rubric-item" data-id="<?php echo $rid; ?>"><?php echo escape($rub['full_path']); ?><button type="button" onclick="removeRubric(<?php echo $rid; ?>)" class="btn-remove">×</button></div><?php endif; endforeach; ?></div>
            <input type="hidden" name="selected_rubrics" id="selectedRubricsJson" value='<?php echo json_encode($selectedRubrics); ?>'></div>
            <div class="col-md-5"><h5>Patient Details</h5>
                <input type="text" name="patient_name" class="form-control mb-2" value="<?php echo escape($case['patient_name']); ?>" required>
                <input type="tel" name="patient_mobile" class="form-control mb-2" value="<?php echo $case['patient_mobile']; ?>" required>
                <input type="number" name="patient_age" class="form-control mb-2" placeholder="Age" value="<?php echo $case['patient_age']; ?>">
                <select name="patient_gender" class="form-control mb-2"><option value="">Gender</option><option value="M" <?php echo $case['patient_gender']=='M'?'selected':''; ?>>Male</option><option value="F" <?php echo $case['patient_gender']=='F'?'selected':''; ?>>Female</option><option value="Other" <?php echo $case['patient_gender']=='Other'?'selected':''; ?>>Other</option></select>
                <textarea name="chief_complaint" class="form-control mb-2" rows="2" placeholder="Chief Complaint" required><?php echo escape($case['chief_complaint']); ?></textarea>
                <textarea name="case_history" class="form-control mb-2" rows="2" placeholder="Case History"><?php echo escape($case['case_history']); ?></textarea>
                <textarea name="physical_generals" class="form-control mb-2" rows="2" placeholder="Physical Generals"><?php echo escape($case['physical_generals']); ?></textarea>
                <textarea name="mental_emotional" class="form-control mb-2" rows="2" placeholder="Mental/Emotional"><?php echo escape($case['mental_emotional']); ?></textarea>
                <textarea name="modalities" class="form-control mb-2" rows="2" placeholder="Modalities"><?php echo escape($case['modalities']); ?></textarea>
                <button type="submit" class="btn btn-primary">Update Case</button></div>
        </div>
    </form>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function selectRubric(id, path) { let selected = JSON.parse($('#selectedRubricsJson').val()); if(!selected.includes(id)){ selected.push(id); $('#selectedList').append(`<div class="selected-rubric-item" data-id="${id}">${path}<button type="button" onclick="removeRubric(${id})">×</button></div>`); $('#selectedRubricsJson').val(JSON.stringify(selected)); } }
function removeRubric(id) { let selected = JSON.parse($('#selectedRubricsJson').val()); selected = selected.filter(i => i != id); $(`.selected-rubric-item[data-id="${id}"]`).remove(); $('#selectedRubricsJson').val(JSON.stringify(selected)); }
$(document).on('click', '.rubric-name', function() { selectRubric($(this).data('id'), $(this).data('path')); });
</script>
</body>
</html>