<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../dripend/includes/db.php';

if (!isset($conn) || !$conn) {
    die("<div style='padding:20px; background:#fee2e2; color:#991b1b;'>Fatal Error: Database connection failed.</div>");
}

// ==============================================================================
// 1. CAPTURE FILTERS 
// ==============================================================================
$filter_date_from = $_GET['date_from'] ?? date('Y-m-d');
$filter_date_to = $_GET['date_to'] ?? date('Y-m-d');
$filter_doctor = $_GET['doctor_id'] ?? '';
$filter_department = $_GET['department_id'] ?? '';
$filter_status = $_GET['status'] ?? '';

// ==============================================================================
// 2. FETCH LIVE KPIs 
// ==============================================================================
$kpi_total = 0;
$kpi_pending = 0;
$kpi_completed = 0;
$kpi_male = 0;
$kpi_female = 0;

$kpiSql = "
    SELECT 
        vm.status, 
        g.gender_name, 
        COUNT(*) as count 
    FROM visit_master vm
    JOIN patient p ON vm.patient_no = p.patient_no
    LEFT JOIN gender g ON p.gender_id = g.id
    WHERE vm.visit_date BETWEEN ? AND ?
    GROUP BY vm.status, g.gender_name
";
$kpiStmt = $conn->prepare($kpiSql);
$kpiStmt->bind_param("ss", $filter_date_from, $filter_date_to);
$kpiStmt->execute();
$kpiRes = $kpiStmt->get_result();

while ($row = $kpiRes->fetch_assoc()) {
    $count = (int)$row['count'];
    $kpi_total += $count;
    
    if (in_array($row['status'], ['Scheduled', 'Pending', 'In Progress'])) {
        $kpi_pending += $count;
    } elseif ($row['status'] === 'Completed') {
        $kpi_completed += $count;
    }
    
    $gender = strtolower(trim($row['gender_name'] ?? ''));
    if ($gender === 'male') {
        $kpi_male += $count;
    } elseif ($gender === 'female') {
        $kpi_female += $count;
    }
}
$kpiStmt->close();

// ==============================================================================
// 3. FETCH APPOINTMENTS (Grouped by Patient and Date to combine same-day requests)
// ==============================================================================
$query = "
    SELECT 
        MAX(vm.id) AS visit_id, 
        MAX(vm.appointment_no) AS appointment_no, 
        vm.visit_date, 
        MIN(vm.visit_time) AS visit_time, 
        MAX(vm.status) AS status, 
        SUM(vm.total_billed) AS total_billed,
        p.patient_no, p.first_name, p.last_name, p.gender_id, p.mobile,
        TIMESTAMPDIFF(YEAR, p.dob, CURDATE()) AS age,
        g.gender_name,
        MAX(s.first_name) AS doc_first, MAX(s.last_name) AS doc_last,
        (
            SELECT GROUP_CONCAT(CONCAT('• ', sc.service_name, ' <span style=\"color:#94a3b8; font-size:10px;\">(@', TIME_FORMAT(v2.visit_time, '%h:%i %p'), ')</span>') ORDER BY v2.visit_time ASC SEPARATOR '<br>')
            FROM visit_master v2
            JOIN visit_details vd ON vd.visit_master_id = v2.id
            JOIN service_catalog sc ON vd.service_id = sc.id
            WHERE v2.patient_no = vm.patient_no AND v2.visit_date = vm.visit_date
        ) AS requested_services
    FROM visit_master vm
    JOIN patient p ON vm.patient_no = p.patient_no
    LEFT JOIN gender g ON p.gender_id = g.id
    LEFT JOIN staff s ON vm.primary_doctor_id = s.staff_id
    WHERE vm.visit_date BETWEEN ? AND ?
";

$params = [$filter_date_from, $filter_date_to];
$types = "ss";

if (!empty($filter_doctor)) {
    $query .= " AND vm.primary_doctor_id = ?";
    $params[] = $filter_doctor;
    $types .= "i";
}

if (!empty($filter_department)) {
    $query .= " AND s.department_id = ?"; 
    $params[] = $filter_department;
    $types .= "i";
}

if (!empty($filter_status)) {
    if ($filter_status === 'Pending') {
        $query .= " AND vm.status IN ('Scheduled', 'Pending', 'In Progress')";
    } else {
        $query .= " AND vm.status = ?";
        $params[] = $filter_status;
        $types .= "s";
    }
}

// Group to aggregate multiple requests into a single appointment card for the day
$query .= " GROUP BY vm.patient_no, vm.visit_date, p.first_name, p.last_name, p.gender_id, p.mobile, p.dob, g.gender_name";
$query .= " ORDER BY vm.visit_date ASC, MIN(vm.visit_time) ASC";

$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$appointments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Fetch Dropdowns
$doctors = [];
$docRes = $conn->query("SELECT staff_id AS id, CONCAT('Dr. ', first_name, ' ', last_name) AS name FROM staff WHERE is_doctor_id = 1 AND status_id = 1");
if ($docRes) while ($row = $docRes->fetch_assoc()) $doctors[] = $row;

$departments = [];
$deptRes = $conn->query("SELECT id, department_name AS name FROM departments WHERE is_active = 1");
if ($deptRes) while ($row = $deptRes->fetch_assoc()) $departments[] = $row;

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Appointment Calendar | DripDental</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>
:root {
    --sidebar-width: 300px;
    --e-blue: #1e3a8a;
    --e-blue-light: #eff6ff;
    --e-green: #10b981;
    --e-red: #ef4444;
    --e-orange: #f59e0b;
    --bg-color: #f8fafc;
    --card-bg: #ffffff;
    --border-color: #e2e8f0;
    --text-main: #0f172a;
    --text-muted: #64748b;
}

* { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', system-ui, sans-serif; }
body { background: var(--bg-color); color: var(--text-main); overflow-x: hidden; }

.page-wrapper {
    margin-left: var(--sidebar-width);
    width: calc(100% - var(--sidebar-width));
    min-height: 100vh; 
    padding: 20px 40px; 
    background: var(--bg-color); 
    display: block;
    transition: margin-left 0.35s ease, width 0.35s ease;
}

.page-wrapper.expanded {
    margin-left: 0;
    width: 100%;
}

/* Common Badges & Buttons */
.ac-status-badge { font-size: 12px; font-weight: 800; text-transform: uppercase; padding: 6px 10px; border-radius: 6px; }
.badge-pending { background: #fef3c7; color: #b45309; }
.badge-completed { background: #d1fae5; color: #047857; }
.badge-cancelled { background: #fee2e2; color: #b91c1c; }

.btn-view { display:flex; align-items:center; justify-content:center; gap:8px; background: #fff; color: var(--e-blue); text-decoration: none; padding: 10px 18px; border-radius: 8px; font-size: 13px; font-weight: 700; transition: 0.2s; border: 1px solid var(--e-blue); white-space: nowrap;}
.btn-view:hover { background: var(--e-blue); color: #fff; }

/* ACTION ICONS */
.ac-action-icons { display: flex; gap: 6px; }
.icon-action { display: inline-flex; align-items: center; justify-content: center; width: 34px; height: 34px; border-radius: 8px; background: #f1f5f9; color: #64748b; text-decoration: none; transition: all 0.2s ease; font-size: 14px; }
.icon-action:hover { transform: translateY(-2px); }
.action-view:hover { background: #dbeafe; color: #1d4ed8; }
.action-vitals:hover { background: #fce7f3; color: #be185d; }
.action-edit:hover { background: #fef3c7; color: #b45309; }
.action-cancel:hover { background: #fee2e2; color: #b91c1c; }

/* Custom Link Hover */
.hover-link { transition: 0.2s ease; cursor: pointer; }
.hover-link:hover { color: var(--e-blue) !important; text-decoration: underline !important; }

/* =========================================================
   TILES VIEW (Default)
   ========================================================= */
.calendar-grid { 
    display: grid; 
    grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); 
    gap: 24px; 
}

.app-card { 
    background: var(--card-bg); 
    border: 1px solid var(--border-color); 
    border-radius: 16px; 
    box-shadow: 0 4px 10px rgba(0,0,0,0.02); 
    transition: all 0.2s ease; 
    display: flex; 
    flex-direction: column; 
    position: relative; 
}
.app-card:hover { transform: translateY(-4px); box-shadow: 0 12px 24px rgba(0,0,0,0.06); border-color: #cbd5e1; }

.app-number {
    position: absolute; top: -12px; left: -12px;
    background: var(--e-blue); color: #fff; width: 34px; height: 34px; border-radius: 50%;
    display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 800;
    border: 3px solid var(--bg-color); box-shadow: 0 4px 8px rgba(30, 58, 138, 0.3); z-index: 10;
}

.status-bar { height: 6px; width: 100%; border-radius: 16px 16px 0 0; }
.app-card.pending .status-bar { background: var(--e-orange); }
.app-card.completed .status-bar { background: var(--e-green); }
.app-card.cancelled .status-bar { background: var(--e-red); }

.ac-header { padding: 20px 24px; border-bottom: 1px solid #f1f5f9; display: flex; justify-content: space-between; align-items: center; }
.ac-patient-info { display: flex; align-items: center; gap: 14px; min-width: 0; }
.ac-avatar { width: 48px; height: 48px; border-radius: 50%; background: var(--e-blue-light); color: var(--e-blue); display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 18px; flex-shrink: 0; }
.ac-name { font-size: 16px; font-weight: 800; color: var(--text-main); margin-bottom: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display:block; }
.ac-id { font-size: 12px; font-weight: 700; color: var(--text-muted); }

.ac-body { padding: 20px 24px; display: flex; flex-direction: column; gap: 16px; flex: 1; }
.ac-schedule-row { display: flex; gap: 10px; background: #f8fafc; padding: 10px 12px; border-radius: 8px; border: 1px solid #e2e8f0; }
.ac-time-block { display: flex; flex-direction: column; gap: 2px; }
.ac-time-block strong { font-size: 14px; color: var(--text-main); font-weight: 800; display: flex; align-items: center; gap: 6px; }
.ac-time-block span { font-size: 12px; color: var(--text-muted); font-weight: 600; }

.ac-detail-row { display: flex; align-items: flex-start; gap: 12px; font-size: 13px; line-height: 1.4; }
.ac-icon { width: 16px; color: var(--text-muted); text-align: center; margin-top: 2px; }
.ac-text { flex:1; }
.ac-text strong { color: var(--text-main); font-weight: 700; display: block; margin-bottom: 2px; text-transform: uppercase; font-size: 11px; letter-spacing: 0.5px; }

.ac-footer { background: #f8fafc; padding: 16px 24px; border-top: 1px solid #f1f5f9; border-radius: 0 0 16px 16px; display: flex; flex-direction: column; align-items: stretch; gap: 16px; }

/* =========================================================
   EXPANDABLE LIST VIEW (Hidden by Default)
   ========================================================= */
.list-view-container {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.list-item {
    background: #fff;
    border: 1px solid var(--border-color);
    border-radius: 12px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.02);
    overflow: hidden;
    transition: all 0.3s ease;
}

.list-item:hover {
    border-color: #cbd5e1;
}

/* Colored side-border based on status */
.list-item.pending { border-left: 5px solid var(--e-orange); }
.list-item.completed { border-left: 5px solid var(--e-green); }
.list-item.cancelled { border-left: 5px solid var(--e-red); }

.li-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 24px;
    cursor: pointer;
    background: #fff;
    transition: background 0.2s;
    user-select: none;
}
.li-header:hover { background: #f8fafc; }

.li-left { display: flex; align-items: center; gap: 24px; flex: 1; min-width: 0;}
.li-time { font-size: 15px; font-weight: 800; color: var(--text-main); width: 80px; flex-shrink: 0;}
.li-patient { display: flex; align-items: center; gap: 12px; min-width: 0;}
.li-patient-name { font-size: 16px; font-weight: 800; color: var(--text-main); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display:block;}
.li-patient-id { font-size: 13px; font-weight: 700; color: var(--e-blue); background: var(--e-blue-light); padding: 4px 10px; border-radius: 8px;}

.li-right { display: flex; align-items: center; gap: 24px; flex-shrink: 0;}
.li-chevron { color: var(--text-muted); transition: transform 0.3s ease; font-size: 14px;}

/* When expanded */
.list-item.expanded .li-chevron { transform: rotate(180deg); color: var(--e-blue); }
.list-item.expanded .li-header { border-bottom: 1px solid var(--border-color); background: #f8fafc;}

.li-body {
    padding: 24px;
    background: #ffffff;
    display: none; /* Toggled via JS */
}

.li-body-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 24px;
}

.li-data { display: flex; flex-direction: column; gap: 4px; }
.li-data-lbl { font-size: 11px; font-weight: 800; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px;}
.li-data-val { font-size: 14px; font-weight: 600; color: var(--text-main); }

.li-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    padding-top: 16px;
    border-top: 1px solid #f1f5f9;
}


.empty-state { text-align:center; padding: 80px 20px; background:#fff; border-radius:16px; border:1px dashed #cbd5e1; grid-column: 1 / -1; }

@media (max-width: 1024px) {
    .page-wrapper { margin-left: 0; width: 100%; padding: 30px 20px; }
}
@media (max-width: 768px) {
    /* Responsive List Adjustments */
    .li-header { padding: 16px; flex-direction: column; align-items: flex-start; gap: 12px; position: relative;}
    .li-left { flex-direction: column; align-items: flex-start; gap: 8px; width: 100%;}
    .li-time { width: auto; font-size: 14px; color: var(--e-blue);}
    .li-right { width: 100%; justify-content: space-between;}
    .li-chevron { position: absolute; top: 16px; right: 16px; }
    .li-actions { flex-direction: column; align-items: stretch; }
    .li-actions .ac-action-icons { justify-content: center; margin-bottom: 10px; }
}
@media (max-width: 600px) {
    .calendar-grid { grid-template-columns: 1fr; }
    .ac-header { flex-direction: column; align-items: flex-start; gap: 12px; }
    .ac-status-badge { text-align: center; }
    .btn-view { width: 100%; text-align: center; justify-content: center; }
    .ac-action-icons { justify-content: center; margin-top: 10px; }
}
</style>
</head>
<body>

<?php include('../../dripend/statpages/sidebar.php'); ?>

<div class="page-wrapper" id="mainWrapper">
    
    <?php include('../../dripend/statpages/appointmentCalendarHeader.php'); ?>

    <div id="tilesView" class="calendar-grid">
        <?php if (count($appointments) > 0): ?>
            <?php 
            $counter = 1;
            foreach ($appointments as $app): 
                $card_class = 'pending';
                if ($app['status'] === 'Completed') $card_class = 'completed';
                if ($app['status'] === 'Cancelled') $card_class = 'cancelled';
                
                $badge_class = 'badge-pending';
                if ($app['status'] === 'Completed') $badge_class = 'badge-completed';
                if ($app['status'] === 'Cancelled') $badge_class = 'badge-cancelled';

                $initial = strtoupper(substr($app['first_name'], 0, 1));
                
                // Allow HTML output for grouped services and times
                $services_display = !empty($app['requested_services']) ? $app['requested_services'] : '• General Consultation';
            ?>
            <div class="app-card <?php echo $card_class; ?>">
                <div class="app-number"><?php echo $counter; ?></div>
                <div class="status-bar"></div>
                
                <div class="ac-header">
                    <div class="ac-patient-info">
                        <div class="ac-avatar"><?php echo $initial; ?></div>
                        <div style="min-width: 0;">
                            <a href="../patient/patientMedicalRecords.php?patient_id=<?php echo urlencode($app['patient_no']); ?>" class="ac-name hover-link" style="text-decoration:none;">
                                <?php echo htmlspecialchars($app['first_name'] . ' ' . $app['last_name']); ?>
                            </a>
                            <div class="ac-id">#<?php echo htmlspecialchars($app['patient_no']); ?></div>
                        </div>
                    </div>
                </div>
                
                <div class="ac-body">
                    <div class="ac-schedule-row">
                        <i class="fa-regular fa-calendar-check" style="color: var(--e-blue); font-size: 18px; margin-top: 4px;"></i>
                        <div class="ac-time-block">
                            <strong><?php echo date('h:i A', strtotime($app['visit_time'])); ?> <span style="font-size:11px;font-weight:normal;color:var(--text-muted);">(First Arrival)</span></strong>
                            <span><?php echo date('l, d M Y', strtotime($app['visit_date'])); ?></span>
                        </div>
                    </div>

                    <div class="ac-detail-row">
                        <i class="fa-solid fa-notes-medical ac-icon"></i>
                        <div class="ac-text">
                            <strong>Requested Services (Today)</strong>
                            <div style="font-size:12px; margin-top:4px; line-height:1.6; color:#334155;"><?php echo $services_display; ?></div>
                        </div>
                    </div>

                    <div class="ac-detail-row">
                        <i class="fa-solid fa-hospital-user ac-icon"></i>
                        <div class="ac-text">
                            <strong>Demographics</strong>
                            <span style="color:#475569; font-weight:500; font-size:13px;"><?php echo htmlspecialchars($app['gender_name'] ?? 'Unknown'); ?> • <?php echo htmlspecialchars($app['age']); ?> Yrs</span>
                        </div>
                    </div>
                    <div class="ac-detail-row">
                        <i class="fa-solid fa-user-doctor ac-icon"></i>
                        <div class="ac-text">
                            <strong>Assigned Provider</strong>
                            <span style="color:#475569; font-weight:500; font-size:13px;"><?php echo !empty($app['doc_first']) ? 'Dr. ' . htmlspecialchars($app['doc_first'] . ' ' . $app['doc_last']) : 'Unassigned'; ?></span>
                        </div>
                    </div>
                </div>

                <div class="ac-footer">
                    <div style="display:flex; justify-content:space-between; align-items:center; width:100%; flex-wrap:wrap; gap:10px;">
                        <div class="ac-status-badge <?php echo $badge_class; ?>"><?php echo htmlspecialchars($app['status']); ?></div>
                        <div class="ac-action-icons">
                            <a href="viewAppointment.php?visit_id=<?php echo urlencode($app['visit_id']); ?>" class="icon-action action-view" title="View Details"><i class="fa-solid fa-eye"></i></a>
                            <a href="../vitals/opdTriageVitals.php?visit_id=<?php echo urlencode($app['visit_id']); ?>" class="icon-action action-vitals" title="Record Vitals"><i class="fa-solid fa-heart-pulse"></i></a>
                            
                            <?php if (in_array($app['status'], ['Scheduled', 'Pending', 'In Progress'])): ?>
                                <a href="updateAppointment.php?visit_id=<?php echo urlencode($app['visit_id']); ?>" class="icon-action action-edit" title="Edit Appointment"><i class="fa-solid fa-pen"></i></a>
                                <a href="cancelAppointment.php?visit_id=<?php echo urlencode($app['visit_id']); ?>" class="icon-action action-cancel" title="Cancel Appointment"><i class="fa-solid fa-xmark"></i></a>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div style="width: 100%;">
                        <a href="../patient/patientMedicalRecords.php?patient_id=<?php echo urlencode($app['patient_no']); ?>" class="btn-view" style="width:100%; text-align:center;">
                            <i class="fa-solid fa-folder-open"></i> View Clinical Record
                        </a>
                    </div>
                </div>
            </div>
            <?php 
            $counter++;
            endforeach; 
            ?>
        <?php else: ?>
            <div class="empty-state">
                <i class="fa-solid fa-calendar-xmark" style="font-size:48px; color:#cbd5e1; margin-bottom:16px;"></i>
                <h3 style="color:var(--text-main); font-size: 20px; font-weight: 800; margin-bottom:8px;">No Appointments Found</h3>
                <p style="color:var(--text-muted); font-size:15px;">There are no records matching your current filter criteria.</p>
            </div>
        <?php endif; ?>
    </div>

    <div id="detailedView" class="list-view-container" style="display: none;">
        <?php if (count($appointments) > 0): ?>
            <?php 
            $counter = 1;
            foreach ($appointments as $app): 
                $card_class = 'pending';
                if ($app['status'] === 'Completed') $card_class = 'completed';
                if ($app['status'] === 'Cancelled') $card_class = 'cancelled';
                
                $badge_class = 'badge-pending';
                if ($app['status'] === 'Completed') $badge_class = 'badge-completed';
                if ($app['status'] === 'Cancelled') $badge_class = 'badge-cancelled';

                $initial = strtoupper(substr($app['first_name'], 0, 1));
                
                $services_display = !empty($app['requested_services']) ? $app['requested_services'] : '• General Consultation';
            ?>
            <div class="list-item <?php echo $card_class; ?>">
                
                <div class="li-header" onclick="toggleListItem(this)">
                    <div class="li-left">
                        <div class="li-time">
                            <?php echo date('h:i A', strtotime($app['visit_time'])); ?>
                        </div>
                        <div class="li-patient">
                            <div class="ac-avatar" style="width:36px; height:36px; font-size:14px;"><?php echo $initial; ?></div>
                            <a href="../patient/patientMedicalRecords.php?patient_id=<?php echo urlencode($app['patient_no']); ?>" class="li-patient-name hover-link" style="text-decoration:none;" onclick="event.stopPropagation();">
                                <?php echo htmlspecialchars($app['first_name'] . ' ' . $app['last_name']); ?>
                            </a>
                            <span class="li-patient-id">#<?php echo htmlspecialchars($app['patient_no']); ?></span>
                        </div>
                    </div>
                    <div class="li-right">
                        <div class="ac-status-badge <?php echo $badge_class; ?>"><?php echo htmlspecialchars($app['status']); ?></div>
                        <i class="fa-solid fa-chevron-down li-chevron"></i>
                    </div>
                </div>

                <div class="li-body">
                    <div class="li-body-grid">
                        <div class="li-data">
                            <span class="li-data-lbl">Appointment Date</span>
                            <span class="li-data-val"><?php echo date('l, d M Y', strtotime($app['visit_date'])); ?></span>
                        </div>
                        <div class="li-data">
                            <span class="li-data-lbl">Requested Services (Today)</span>
                            <div class="li-data-val" style="font-size:12px; line-height:1.6; margin-top:4px;"><?php echo $services_display; ?></div>
                        </div>
                        <div class="li-data">
                            <span class="li-data-lbl">Demographics</span>
                            <span class="li-data-val"><?php echo htmlspecialchars($app['gender_name'] ?? 'Unknown'); ?> • <?php echo htmlspecialchars($app['age']); ?> Yrs</span>
                        </div>
                        <div class="li-data">
                            <span class="li-data-lbl">Contact Number</span>
                            <span class="li-data-val"><?php echo htmlspecialchars($app['mobile'] ?? 'N/A'); ?></span>
                        </div>
                        <div class="li-data">
                            <span class="li-data-lbl">Assigned Provider</span>
                            <span class="li-data-val"><?php echo !empty($app['doc_first']) ? 'Dr. ' . htmlspecialchars($app['doc_first'] . ' ' . $app['doc_last']) : 'Unassigned'; ?></span>
                        </div>
                    </div>

                    <div class="li-actions">
                        <div class="ac-action-icons">
                            <a href="viewAppointment.php?visit_id=<?php echo urlencode($app['visit_id']); ?>" class="icon-action action-view" title="View Details"><i class="fa-solid fa-eye"></i></a>
                            <a href="patientVitals.php?visit_id=<?php echo urlencode($app['visit_id']); ?>" class="icon-action action-vitals" title="Record Vitals"><i class="fa-solid fa-heart-pulse"></i></a>
                            
                            <?php if (in_array($app['status'], ['Scheduled', 'Pending', 'In Progress'])): ?>
                                <a href="updateAppointment.php?visit_id=<?php echo urlencode($app['visit_id']); ?>" class="icon-action action-edit" title="Edit Appointment"><i class="fa-solid fa-pen"></i></a>
                                <a href="cancelAppointment.php?visit_id=<?php echo urlencode($app['visit_id']); ?>" class="icon-action action-cancel" title="Cancel Appointment"><i class="fa-solid fa-xmark"></i></a>
                            <?php endif; ?>
                        </div>
                        
                        <div>
                            <a href="../patient/patientMedicalRecords.php?patient_id=<?php echo urlencode($app['patient_no']); ?>" class="btn-view">
                                <i class="fa-solid fa-folder-open"></i> View Clinical Record
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <?php 
            $counter++;
            endforeach; 
            ?>
        <?php else: ?>
             <div class="empty-state">
                <i class="fa-solid fa-calendar-xmark" style="font-size:48px; color:#cbd5e1; margin-bottom:16px;"></i>
                <h3 style="color:var(--text-main); font-size: 20px; font-weight: 800; margin-bottom:8px;">No Appointments Found</h3>
                <p style="color:var(--text-muted); font-size:15px;">There are no records matching your current filter criteria.</p>
            </div>
        <?php endif; ?>
    </div>

</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const sidebar = document.getElementById('sidebar');
    const mainContent = document.getElementById('mainWrapper');

    // 1. Sidebar Sync Logic
    if (sidebar && mainContent) {
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.attributeName === "class") {
                    syncLayout();
                }
            });
        });
        observer.observe(sidebar, { attributes: true });

        function syncLayout() {
            if (sidebar.classList.contains('vanished') || window.innerWidth <= 1024) {
                mainContent.classList.add('expanded');
            } else {
                mainContent.classList.remove('expanded');
            }
        }
        window.addEventListener('resize', syncLayout);
        syncLayout();
    }
});

// 2. Client-Side View Toggle Logic
function switchCalendarView(viewType) {
    const btnTiles = document.getElementById('btnViewTiles');
    const btnDetailed = document.getElementById('btnViewDetailed');
    const viewTiles = document.getElementById('tilesView');
    const viewDetailed = document.getElementById('detailedView');

    if (viewType === 'tiles') {
        btnTiles.classList.add('active');
        btnDetailed.classList.remove('active');
        viewTiles.style.display = 'grid';
        viewDetailed.style.display = 'none';
    } else {
        btnDetailed.classList.add('active');
        btnTiles.classList.remove('active');
        viewTiles.style.display = 'none';
        viewDetailed.style.display = 'flex';
    }
}

// 3. Expandable List Item Logic
function toggleListItem(headerElement) {
    const parentItem = headerElement.closest('.list-item');
    const bodyElement = parentItem.querySelector('.li-body');
    
    // Toggle the 'expanded' class for styling
    parentItem.classList.toggle('expanded');
    
    // Toggle the display of the body
    if (parentItem.classList.contains('expanded')) {
        bodyElement.style.display = 'block';
    } else {
        bodyElement.style.display = 'none';
    }
}
</script>

</body>
</html>