<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['doctor'])) {
    header('Location: login.php');
    exit;
}

$doctor_id = $_SESSION['doctor'];
$msg = '';
$appt_id = (int)($_GET['appt_id'] ?? 0);

$appt = $conn->query("SELECT a.*, p.name AS patient_name, p.id AS patient_id 
    FROM opd_appointments a JOIN opd_patients p ON a.patient_id = p.id 
    WHERE a.id = $appt_id AND a.doctor_id = $doctor_id")->fetch_assoc();

if (!$appt) {
    echo "<div style='padding:20px;font-family:sans-serif;'><h3>❌ অ্যাপয়েন্টমেন্ট পাওয়া যায়নি</h3>
    <a href='dashboard.php'>← ফিরুন</a></div>";
    exit;
}

if (isset($_POST['save'])) {
    $rx = $conn->real_escape_string($_POST['prescription_text']);
    $adv = $conn->real_escape_string($_POST['advice']);
    $next = $_POST['next_visit'] ? "'{$_POST['next_visit']}'" : "NULL";
    $sql = "INSERT INTO opd_prescriptions (appointment_id, patient_id, doctor_id, prescription_text, advice, next_visit) 
            VALUES ($appt_id, {$appt['patient_id']}, $doctor_id, '$rx', '$adv', $next)";
    if ($conn->query($sql)) {
        $conn->query("UPDATE opd_appointments SET status='completed' WHERE id=$appt_id");
        $msg = '<div class="alert alert-success">✅ Prescription saved!</div>';
    } else {
        $msg = '<div class="alert alert-danger">❌ '.$conn->error.'</div>';
    }
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8"><title>Prescription</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-4">
<div class="container" style="max-width:600px">
    <a href="dashboard.php" class="btn btn-secondary mb-3">← ফিরুন</a>
    <?=$msg?>
    <div class="card">
        <div class="card-header bg-success text-white"><h5>📝 Prescription - <?=$appt['patient_name']?></h5></div>
        <div class="card-body">
            <form method="POST">
                <textarea name="prescription_text" class="form-control mb-2" rows="5" placeholder="Prescription..." required></textarea>
                <input name="advice" class="form-control mb-2" placeholder="Advice">
                <input type="date" name="next_visit" class="form-control mb-3">
                <button type="submit" name="save" class="btn btn-success w-100">Save</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>