<?php
session_start();
include '../config/db.php';

// Check if user is logged in
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

// Get the patient ID
$patient_id = $_GET['patient_id'];

// Fetch patient details
$stmt = $pdo->prepare("SELECT * FROM patients WHERE id = ?");
$stmt->execute([$patient_id]);
$patient = $stmt->fetch();

// Handle form submission to add a prescription
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $drug_name = $_POST['drug_name'];
    $dosage = $_POST['dosage'];
    $frequency = $_POST['frequency'];
    $duration = $_POST['duration'];
    $prescribed_by = $_SESSION['username'];

    // Insert prescription into the database
    $stmt = $pdo->prepare("INSERT INTO prescriptions (patient_id, drug_name, dosage, frequency, duration, prescribed_by) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([$patient_id, $drug_name, $dosage, $frequency, $duration, $prescribed_by]);

    echo "<div class='alert alert-success'>Prescription added successfully!</div>";
}

// Date filter
$dateFilter = '';
if (!empty($_GET['start_date']) && !empty($_GET['end_date'])) {
    $start_date = $_GET['start_date'];
    $end_date = $_GET['end_date'];
    $dateFilter = "AND prescribed_date BETWEEN '$start_date' AND '$end_date'";
}

// Fetch all prescriptions for the patient with date filter
$stmt = $pdo->prepare("SELECT * FROM prescriptions WHERE patient_id = ? $dateFilter ORDER BY prescribed_date DESC");
$stmt->execute([$patient_id]);
$prescriptions = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Prescriptions</title>
    <link rel="stylesheet" href="..\libs\bootsrtap\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    <script src="..\libs\bootsrtap\js\bootstrap.bundle.min.js"></script>
    <script src="..\libs\popper\popper.min.js"></script>
    <script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
    <script src="..\libs\jquery\jquery-3.3.1.slim.min.js"></script>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
    <h2 class="mb-4">Prescriptions for <?= htmlspecialchars($patient['patient_name']) ?></h2>
    <a href="view_patients.php" class="btn btn-secondary btn-dashboard">Back to Patients List</a>

    <!-- Date Filter Form -->
    <form method="get" class="row g-3 mt-3">
        <input type="hidden" name="patient_id" value="<?= $patient_id ?>">
        <div class="col-auto">
            <label for="start_date" class="form-label">Start Date</label>
            <input type="date" class="form-control" id="start_date" name="start_date" required>
        </div>
        <div class="col-auto">
            <label for="end_date" class="form-label">End Date</label>
            <input type="date" class="form-control" id="end_date" name="end_date" required>
        </div>
        <div class="col-auto">
            <label>&nbsp;</label>
            <button type="submit" class="btn btn-primary">Filter</button>
        </div>
    </form>

    <!-- Add Prescription Form -->
    <?php if ($_SESSION['role'] !== 'staff'): ?>
<!-- Add Prescription Form -->
<form method="post" class="mt-4">
    <div class="mb-3">
        <label for="drug_name" class="form-label">Drug Name</label>
        <input type="text" class="form-control" id="drug_name" name="drug_name" required>
    </div>
    <div class="mb-3">
        <label for="dosage" class="form-label">Dosage</label>
        <input type="text" class="form-control" id="dosage" name="dosage" required>
    </div>
    <div class="mb-3">
        <label for="frequency" class="form-label">Frequency</label>
        <input type="text" class="form-control" id="frequency" name="frequency" required>
    </div>
    <div class="mb-3">
        <label for="duration" class="form-label">Duration</label>
        <input type="text" class="form-control" id="duration" name="duration" required>
    </div>
    <button type="submit" class="btn btn-primary">Add Prescription</button>
</form>
<?php endif; ?>


    <!-- Table of All Prescriptions Grouped by Date -->
    <h3 class="mt-5">Prescription History</h3>
    <?php if (count($prescriptions) > 0): ?>
        <?php 
        $currentDate = null;
        foreach ($prescriptions as $index => $prescription): 
            $prescribedDate = date("Y-m-d", strtotime($prescription['prescribed_date']));
            if ($currentDate !== $prescribedDate) {
                if ($currentDate !== null) {
                    echo '</tbody></table>';
                }
                $currentDate = $prescribedDate;
                echo "<h4 class='mt-4'>Date: " . htmlspecialchars($prescribedDate) . "</h4>";
                echo '<table class="table table-bordered table-striped">
                    <thead class="table-dark">
                        <tr>
                            <th>#</th>
                            <th>Drug Name</th>
                            <th>Dosage</th>
                            <th>Frequency</th>
                            <th>Duration</th>
                            <th>Prescribed By</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>';
            }
            ?>
            <tr>
                <td><?= $index + 1 ?></td>
                <td><?= htmlspecialchars($prescription['drug_name']) ?></td>
                <td><?= htmlspecialchars($prescription['dosage']) ?></td>
                <td><?= htmlspecialchars($prescription['frequency']) ?></td>
                <td><?= htmlspecialchars($prescription['duration']) ?></td>
                <td><?= htmlspecialchars($prescription['prescribed_by']) ?></td>
                <td><?= htmlspecialchars($prescription['prescribed_date']) ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
        </table>
    <?php else: ?>
        <p class="text-center">No prescriptions found</p>
    <?php endif; ?>
</div>
</body>
</html>
