<?php
session_start();
if (!isset($_SESSION['doctor_id'])) {
    header("Location: login.php");
    exit();
}
include '../include/config.php';
$doctor_id = $_SESSION['doctor_id'];

// Get patients of this doctor
$patients = $conn->query("SELECT DISTINCT p.patient_id, p.first_name, p.last_name 
                          FROM patients p 
                          JOIN appointments a ON p.patient_id = a.patient_id 
                          WHERE a.doctor_id = $doctor_id");

$msg = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $patient_id = $_POST['patient_id'];
    $medication = $conn->real_escape_string($_POST['medication']);
    $dosage = $conn->real_escape_string($_POST['dosage']);
    $instructions = $conn->real_escape_string($_POST['instructions']);
    $stmt = $conn->prepare("INSERT INTO prescriptions (patient_id, doctor_id, medication, dosage, instructions) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("iisss", $patient_id, $doctor_id, $medication, $dosage, $instructions);
    if ($stmt->execute()) $msg = "Prescription added successfully!";
    else $msg = "Error: " . $conn->error;
}
?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Add Prescription</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
<style>body{background:#0a3d2f;}.navbar{background:#064e3b;}.card{border-radius:20px;background:rgba(255,255,255,0.95);}</style>
</head>
<body>
<nav class="navbar navbar-dark"><div class="container"><span class="navbar-brand"><i class="fas fa-prescription-bottle"></i> Add Prescription</span><a href="dashboard.php" class="btn btn-light btn-sm">Back</a></div></nav>
<div class="container mt-4"><div class="card"><div class="card-header bg-success text-white">New Prescription</div><div class="card-body">
<?php if($msg) echo "<div class='alert alert-success'>$msg</div>"; ?>
<form method="POST"><div class="mb-3"><label>Patient</label><select name="patient_id" class="form-control" required><?php while($p=$patients->fetch_assoc()) echo "<option value='{$p['patient_id']}'>{$p['first_name']} {$p['last_name']}</option>"; ?></select></div>
<div class="mb-3"><label>Medication</label><input type="text" name="medication" class="form-control" required></div>
<div class="mb-3"><label>Dosage</label><input type="text" name="dosage" class="form-control" required></div>
<div class="mb-3"><label>Instructions</label><textarea name="instructions" class="form-control" rows="3"></textarea></div>
<button type="submit" class="btn btn-primary w-100">Save Prescription</button></form>
</div></div></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>