<?php
/**
 * Add Prescription
 * Add remedy prescription to case
 */

require_once '../../config/config.php';
require_once '../../includes/functions.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; }

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $remedyId = $_POST['remedy_id'];
    $potency = $_POST['potency'];
    $followUpDate = $_POST['follow_up_date'];
    
    $stmt = $pdo->prepare("UPDATE cases SET prescribed_remedy_id=?, prescription_potency=?, follow_up_date=?, status='follow-up' WHERE id=? AND user_id=?");
    $stmt->execute([$remedyId, $potency, $followUpDate, $caseId, $userId]);
    header("Location: view.php?id=$caseId&msg=Prescription added successfully");
    exit;
}

$remedies = $pdo->query("SELECT id, name FROM remedies ORDER BY name")->fetchAll();
$repertorization = json_decode($case['repertorization_result'], true) ?: [];
?>
<!DOCTYPE html>
<html>
<head><title>Prescribe Remedy</title><link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"></head>
<body>
<div class="container mt-5"><div class="row"><div class="col-md-6 mx-auto"><div class="card"><div class="card-header bg-success text-white"><h4>Prescribe Remedy for <?php echo escape($case['patient_name']); ?></h4></div>
<div class="card-body">
<?php if(!empty($repertorization)): ?><div class="alert alert-info"><strong>Top Indicated Remedies:</strong><br><?php foreach(array_slice($repertorization,0,5) as $r): echo $r['remedy_name'] . " (Score: " . $r['score'] . ")<br>"; endforeach; ?></div><?php endif; ?>
<form method="POST"><div class="mb-3"><label>Select Remedy</label><select name="remedy_id" class="form-control" required><option value="">Select Remedy</option><?php foreach($remedies as $r): ?><option value="<?php echo $r['id']; ?>"><?php echo escape($r['name']); ?></option><?php endforeach; ?></select></div>
<div class="mb-3"><label>Potency</label><select name="potency" class="form-control" required><option value="30C">30C</option><option value="200C">200C</option><option value="1M">1M</option><option value="10M">10M</option><option value="CM">CM</option><option value="Q">Q (LM)</option></select></div>
<div class="mb-3"><label>Follow-up Date</label><input type="date" name="follow_up_date" class="form-control" value="<?php echo date('Y-m-d', strtotime('+14 days')); ?>" required></div>
<button type="submit" class="btn btn-primary">Save Prescription</button><a href="view.php?id=<?php echo $caseId; ?>" class="btn btn-secondary">Cancel</a></form></div></div></div></div></div>
</body>
</html>