<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

// Access Control: Ensure user is a Patient
if (!isset($_SESSION['user_id']) || $_SESSION['role_code'] !== 'PATIENT') {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Get Patient ID from user_id
$stmt = $conn->prepare("SELECT patient_id, full_name, patient_number FROM patients WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$pat_res = $stmt->get_result()->fetch_assoc();

if (!$pat_res) {
    die("Patient profile not found.");
}
$patient_id = $pat_res['patient_id'];

// Fetch Appointment History
$sql = "SELECT a.*, d.specialization, u.full_name as doctor_name 
        FROM appointments a 
        JOIN doctors d ON a.doctor_id = d.doctor_id 
        JOIN users u ON d.user_id = u.user_id 
        WHERE a.patient_id = ? 
        ORDER BY a.appointment_date DESC, a.appointment_time DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$result = $stmt->get_result();
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Appointment History')); ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">My Appointment History</h4>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <table id="appointmentsTable"
                                        class="table table-bordered dt-responsive nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Reference</th>
                                                <th>Date & Time</th>
                                                <th>Doctor</th>
                                                <th>Type</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while ($row = $result->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo $row['appointment_number']; ?></td>
                                                    <td><?php echo date('M d, Y', strtotime($row['appointment_date'])) . ' ' . date('H:i', strtotime($row['appointment_time'])); ?>
                                                    </td>
                                                    <td>
                                                        Dr. <?php echo htmlspecialchars($row['doctor_name']); ?>
                                                        <small
                                                            class="d-block text-muted"><?php echo $row['specialization']; ?></small>
                                                    </td>
                                                    <td><?php echo str_replace('_', ' ', $row['appointment_type']); ?></td>
                                                    <td>
                                                        <?php
                                                        $statusClass = match ($row['status']) {
                                                            'SCHEDULED' => 'bg-primary',
                                                            'COMPLETED' => 'bg-success',
                                                            'CANCELLED' => 'bg-danger',
                                                            'NOSHOW' => 'bg-warning',
                                                            default => 'bg-secondary'
                                                        };
                                                        ?>
                                                        <span
                                                            class="badge <?php echo $statusClass; ?>"><?php echo $row['status']; ?></span>
                                                    </td>
                                                    <td>
                                                        <a href="patient_visit_reports.php?appt_id=<?php echo $row['appointment_id']; ?>"
                                                            class="btn btn-sm btn-soft-info">View Report</a>
                                                    </td>
                                                </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#appointmentsTable').DataTable({
                order: [[1, 'desc']]
            });
        });
    </script>
</body>

</html>