<?php
// Filename: booking/admin/manage.php
include '../../config.php';

// --- 1. SECURITY & ADMIN CHECK ---
requireLogin();
$uid = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
if (empty(array_intersect($user_roles, ['admin', 'admin_booking']))) {
    die("Access Denied.");
}

// Ensure CSRF token exists
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// --- 2. DATA PREPARATION ---
$u_stmt = $pdo->prepare("SELECT full_name, avatar FROM users WHERE id = ?");
$u_stmt->execute([$uid]);
$user_data = $u_stmt->fetch();
$full_name = $user_data['full_name'] ?? 'Admin';
$user_avatar = $user_data['avatar'] ?? '';

// --- FILTER VARIABLES ---
$status_filter = $_GET['status'] ?? 'pending'; // Default to pending
$selected_date = $_GET['filter_date'] ?? null; // Specific date filter

// Logic for "View All" vs "Month View"
if (isset($_GET['view_all'])) {
    $filter_month = '';
} else {
    $filter_month = $_GET['filter_month'] ?? date('Y-m');
}

// If a specific date is selected, use its month/year for the calendar
if ($selected_date) {
    $cal_month = date('n', strtotime($selected_date));
    $cal_year  = date('Y', strtotime($selected_date));
    $is_cal_open = true; 
} else {
    $cal_month = isset($_GET['cal_month']) ? intval($_GET['cal_month']) : date('n');
    $cal_year  = isset($_GET['cal_year']) ? intval($_GET['cal_year']) : date('Y');
    $is_cal_open = isset($_GET['cal_open']); 
}

// ==========================================
// --- MINI CALENDAR LOGIC START ---
// ==========================================

$prev_m = $cal_month - 1; $prev_y = $cal_year;
if ($prev_m < 1) { $prev_m = 12; $prev_y--; }
$next_m = $cal_month + 1; $next_y = $cal_year;
if ($next_m > 12) { $next_m = 1; $next_y++; }

$calendar_data = [];

// A. Fetch Holidays
try {
    $h_stmt = $pdo->prepare("SELECT description, start_date, end_date, type FROM school_holidays 
        WHERE (MONTH(start_date) = ? AND YEAR(start_date) = ?) OR (MONTH(end_date) = ? AND YEAR(end_date) = ?)");
    $h_stmt->execute([$cal_month, $cal_year, $cal_month, $cal_year]);
    while ($row = $h_stmt->fetch()) {
        $curr = strtotime($row['start_date']);
        $end  = strtotime($row['end_date']);
        while ($curr <= $end) {
            if (date('n', $curr) == $cal_month && date('Y', $curr) == $cal_year) {
                $d = date('j', $curr);
                $calendar_data[$d]['holiday'] = ['type' => $row['type'], 'desc' => $row['description']];
            }
            $curr = strtotime('+1 day', $curr);
        }
    }
} catch (Exception $e) { /* Ignore */ }

// B. Fetch Bookings Count
try {
    $b_stmt = $pdo->prepare("SELECT booking_date, COUNT(*) as total FROM bookings 
        WHERE status = 'approved' AND MONTH(booking_date) = ? AND YEAR(booking_date) = ? GROUP BY booking_date");
    $b_stmt->execute([$cal_month, $cal_year]);
    while ($row = $b_stmt->fetch()) {
        $d = date('j', strtotime($row['booking_date']));
        $calendar_data[$d]['bookings'] = $row['total'];
    }
} catch (Exception $e) { /* Ignore */ }

// C. Grid Calculation
$cal_first_day = mktime(0, 0, 0, $cal_month, 1, $cal_year);
$cal_days_in_month = date('t', $cal_first_day);
$cal_month_name = date('F Y', $cal_first_day);
$cal_start_dow = date('N', $cal_first_day);
$cal_offset = $cal_start_dow - 1; 

// ==========================================
// --- MINI CALENDAR LOGIC END ---
// ==========================================

// --- MAIN LIST QUERY ---
$query_parts = ["b.status = ?"];
$params = [$status_filter];

if ($selected_date) {
    // If a date is clicked, show ONLY that date
    $query_parts[] = "b.booking_date = ?";
    $params[] = $selected_date;
} else {
    // If NO date is clicked, check if we are filtering by month
    if(!empty($filter_month)) {
        $query_parts[] = "DATE_FORMAT(b.booking_date, '%Y-%m') = ?";
        $params[] = $filter_month;
    }
}

$search_query = $_GET['search'] ?? '';
if ($search_query) {
    $query_parts[] = "(b.teacher_name LIKE ? OR r.name LIKE ? OR b.purpose LIKE ?)";
    $search_param = "%$search_query%";
    array_push($params, $search_param, $search_param, $search_param);
}

$where_clause = implode(" AND ", $query_parts);

// Fetch Main List
$sql_list = "SELECT b.*, r.name as room_name FROM bookings b 
             JOIN rooms r ON b.room_id = r.id 
             WHERE $where_clause ORDER BY b.booking_date ASC, b.start_time ASC";
$stmt_list = $pdo->prepare($sql_list);
$stmt_list->execute($params);
$bookings_list = $stmt_list->fetchAll();

// Global Stats
$count_pending = $pdo->query("SELECT COUNT(*) FROM bookings WHERE status='pending'")->fetchColumn();
$count_approved = $pdo->query("SELECT COUNT(*) FROM bookings WHERE status='approved'")->fetchColumn();
$count_rejected = $pdo->query("SELECT COUNT(*) FROM bookings WHERE status='rejected'")->fetchColumn();

// --- 3. LIVE MAP LOGIC ---
$now_date = date('Y-m-d');
$now_time = date('H:i:s');
$map_rooms = $pdo->query("SELECT * FROM rooms WHERE status = 'active' ORDER BY location, name ASC")->fetchAll();
$active_stmt = $pdo->prepare("SELECT room_id, teacher_name, end_time FROM bookings 
                              WHERE booking_date = ? AND status = 'approved' 
                              AND ? BETWEEN start_time AND end_time");
$active_stmt->execute([$now_date, $now_time]);
$live_occupied = $active_stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE);

$grouped_map = [];
foreach ($map_rooms as $r) {
    $loc = $r['location'] ?: 'General Block';
    $grouped_map[$loc][] = $r;
}

// --- 4. HANDLE BULK POST ---
if (isset($_POST['bulk_approve']) && !empty($_POST['booking_ids'])) {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) die("CSRF Error");
    $ids = $_POST['booking_ids'];
    $placeholders = str_repeat('?,', count($ids) - 1) . '?';
    $stmt = $pdo->prepare("UPDATE bookings SET status = 'approved' WHERE id IN ($placeholders)");
    $stmt->execute($ids);
    header("Location: manage.php?status=pending&msg=bulk_ok"); exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Booking Manager</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }
        .app-header { background: var(--primary-grad); padding: 20px 20px 40px 20px; border-radius: 0 0 35px 35px; color: white; }
        .avatar-img { width: 50px; height: 50px; border-radius: 50%; object-fit: cover; border: 2px solid rgba(255,255,255,0.3); }
        .floating-filters { background: white; border-radius: 20px; padding: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); margin: -25px 15px 15px 15px; position: relative; z-index: 10; }
        .stat-item { text-align: center; padding: 10px; border-radius: 16px; border: 1px solid transparent; transition: 0.2s; }
        .stat-item.active { background: #eff6ff; border-color: #dbeafe; }
        .search-box { background: white; border-radius: 15px; padding: 12px; margin: 0 15px 15px 15px; border: 1px solid #edf2f7; }
        .dashboard-card { background: white; border: none; border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.05); margin: 0 15px; overflow: hidden; }
        .qa-btn { background: white; border-radius: 12px; padding: 12px; font-weight: 700; font-size: 0.85rem; border: none; transition: 0.2s; box-shadow: 0 4px 10px rgba(0,0,0,0.03); text-decoration: none; color: #333; display: block; text-align: center; }
        .qa-btn:hover { background: #f8f9fa; transform: translateY(-2px); }
        .modal-floor-container { max-height: 65vh; overflow-y: auto; }
        .map-room-box { background: white; border-radius: 10px; padding: 8px; border-left: 3px solid #10b981; }
        .map-room-box.occupied { border-left-color: #ef4444; }

        /* CALENDAR STYLES */
        .mini-cal-card { 
            background: white; border-radius: 16px; padding: 12px; margin: 0 15px 15px 15px; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.02); border: 1px solid #f1f5f9; 
            touch-action: pan-y pinch-zoom; 
        }
        .mini-cal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
        .mini-cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 4px; text-align: center; }
        .mini-day-name { font-size: 0.6rem; font-weight: 700; color: #94a3b8; text-transform: uppercase; margin-bottom: 2px; }
        .mini-day { 
            aspect-ratio: 1/1; border-radius: 8px; font-size: 0.8rem; font-weight: 600; color: #334155; 
            display: flex; flex-direction: column; align-items: center; justify-content: center; 
            position: relative; background: #f8fafc; cursor: pointer; transition: 0.2s;
        }
        .mini-day:hover { background: #e2e8f0; }
        .mini-day.is-selected { background: #334155; color: white; border: 2px solid #94a3b8; }
        
        .mini-holiday-national { background-color: #fee2e2; color: #ef4444; }
        .mini-holiday-term { background-color: #e0f2fe; color: #0ea5e9; }
        .mini-holiday-cuti_peristiwa { background-color: #ffedd5; color: #f97316; }
        .mini-holiday-cuti_ganti { background-color: #dcfce7; color: #10b981; }
        .mini-holiday-school_event { background-color: #f3e8ff; color: #8B5CF6; }
        
        .booking-dot { width: 5px; height: 5px; background-color: #10b981; border-radius: 50%; position: absolute; bottom: 3px; }
    </style>
</head>
<body>

<div class="app-header">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <a href="../../dashboard.php" class="text-white opacity-75"><i class="bi bi-arrow-left fs-4"></i></a>
        <div class="fw-bold">Booking Manager</div>
        <div style="width:24px"></div>
    </div>
    <div class="d-flex align-items-center">
        <?php if(!empty($user_avatar)): ?>
            <img src="../../<?= htmlspecialchars($user_avatar) ?>" class="avatar-img me-3">
        <?php else: ?>
            <div class="avatar-img me-3 bg-white text-primary d-flex align-items-center justify-content-center fw-bold"><?= substr($full_name,0,1) ?></div>
        <?php endif; ?>
        <div>
            <h6 class="mb-0 fw-bold"><?= htmlspecialchars($full_name) ?></h6>
            <span class="small opacity-75 fw-bold" style="border: 1px solid rgba(255,255,255,0.4); padding: 1px 8px; border-radius: 50px;">Administrator</span>
        </div>
    </div>
</div>

<div class="floating-filters">
    <div class="row g-2 text-center">
        <div class="col-4">
            <a href="?status=pending&view_all=1" class="text-decoration-none text-dark">
                <div class="stat-item <?= $status_filter=='pending'?'active':'' ?>">
                    <div class="h5 fw-bold text-warning mb-0"><?= $count_pending ?></div>
                    <div class="small text-muted fw-bold">Pending</div>
                </div>
            </a>
        </div>
        <div class="col-4">
            <a href="?status=approved&filter_month=<?= date('Y-m') ?>" class="text-decoration-none text-dark">
                <div class="stat-item <?= $status_filter=='approved'?'active':'' ?>">
                    <div class="h5 fw-bold text-success mb-0"><?= $count_approved ?></div>
                    <div class="small text-muted fw-bold">Approved</div>
                </div>
            </a>
        </div>
        <div class="col-4">
            <a href="?status=rejected&view_all=1" class="text-decoration-none text-dark">
                <div class="stat-item <?= $status_filter=='rejected'?'active':'' ?>">
                    <div class="h5 fw-bold text-danger mb-0"><?= $count_rejected ?></div>
                    <div class="small text-muted fw-bold">Rejected</div>
                </div>
            </a>
        </div>
    </div>
</div>

<div class="container px-3 mb-2">
    <?php if(!$selected_date && !$is_cal_open): ?>
        <a href="?status=<?= $status_filter ?>&filter_month=<?= $filter_month ?>&cal_open=1" class="btn btn-sm btn-light w-100 border text-muted fw-bold rounded-pill">
            <i class="bi bi-chevron-down me-1"></i> Show Availability Calendar
        </a>
    <?php endif; ?>
</div>

<div class="collapse <?= $is_cal_open ? 'show' : '' ?>" id="calendarCollapse">
    <div class="mini-cal-card" id="swipeCal">
        <div class="mini-cal-header">
            <div class="small fw-bold text-uppercase text-muted">
                <i class="bi bi-calendar-check me-1"></i> Availability
            </div>
            <div class="d-flex align-items-center gap-2">
                <a href="?cal_month=<?= $prev_m ?>&cal_year=<?= $prev_y ?>&status=<?= $status_filter ?>&filter_month=<?= $filter_month ?>&cal_open=1" id="btn-prev-month" class="btn btn-sm btn-light border rounded-circle py-0 px-1"><i class="bi bi-chevron-left small"></i></a>
                <span class="small fw-bold" style="min-width: 80px; text-align: center;"><?= $cal_month_name ?></span>
                <a href="?cal_month=<?= $next_m ?>&cal_year=<?= $next_y ?>&status=<?= $status_filter ?>&filter_month=<?= $filter_month ?>&cal_open=1" id="btn-next-month" class="btn btn-sm btn-light border rounded-circle py-0 px-1"><i class="bi bi-chevron-right small"></i></a>
            </div>
        </div>
        <div class="mini-cal-grid">
            <?php foreach(['M','T','W','T','F','S','S'] as $dn): ?><div class="mini-day-name"><?= $dn ?></div><?php endforeach; ?>
            <?php for($i=0; $i<$cal_offset; $i++): ?><div class="mini-day" style="background:transparent; cursor:default;"></div><?php endfor; ?>
            <?php for($d=1; $d<=$cal_days_in_month; $d++): 
                $data = $calendar_data[$d] ?? [];
                $is_holiday = isset($data['holiday']);
                $has_booking = isset($data['bookings']); 
                
                $cell_date_str = sprintf("%04d-%02d-%02d", $cal_year, $cal_month, $d);
                $is_selected = ($cell_date_str === $selected_date);
                
                $classes = "mini-day";
                if ($is_holiday) $classes .= " mini-holiday-" . $data['holiday']['type'];
                if ($is_selected) $classes .= " is-selected";
                
                $tooltip = ($is_holiday ? $data['holiday']['desc'] : "Available");
                if ($has_booking) $tooltip .= " | " . $data['bookings'] . " Approved";
            ?>
                <a href="?status=<?= $status_filter ?>&filter_date=<?= $cell_date_str ?>&cal_month=<?= $cal_month ?>&cal_year=<?= $cal_year ?>" class="text-decoration-none">
                    <div class="<?= $classes ?>" title="<?= htmlspecialchars($tooltip) ?>" data-bs-toggle="tooltip">
                        <?= $d ?>
                        <?php if($has_booking): ?>
                            <div class="booking-dot"></div>
                        <?php endif; ?>
                    </div>
                </a>
            <?php endfor; ?>
        </div>
        
        <?php if($selected_date): ?>
            <div class="text-center mt-2 border-top pt-2">
                <a href="?status=<?= $status_filter ?>&view_all=1" class="btn btn-sm btn-light border-0 text-danger fw-bold rounded-pill px-3">
                    <i class="bi bi-x-circle me-1"></i> Close Date Filter
                </a>
            </div>
        <?php endif; ?>
    </div>
</div>

<div class="container px-3 mb-3">
    <div class="row g-2">
        <div class="col-12">
            <button class="btn w-100 qa-btn text-white py-3 d-flex align-items-center justify-content-center" style="background: #1e293b;" data-bs-toggle="modal" data-bs-target="#floorPlanModal">
                <i class="bi bi-map-fill me-2 text-warning"></i> VIEW LIVE FLOOR PLANS
            </button>
        </div>
        <div class="col-6">
            <a href="manage_rooms.php" class="qa-btn d-flex flex-column align-items-center justify-content-center gap-1 py-3">
                <i class="bi bi-door-open-fill fs-4 text-primary"></i>
                <span class="small">Manage Rooms</span>
            </a>
        </div>
        <div class="col-6">
            <a href="manage_facilities.php" class="qa-btn d-flex flex-column align-items-center justify-content-center gap-1 py-3">
                <i class="bi bi-tools fs-4 text-info"></i>
                <span class="small">Facilities</span>
            </a>
        </div>
    </div>
</div>

<div class="search-box">
    <form method="GET" class="row g-2 align-items-center">
        <input type="hidden" name="status" value="<?= htmlspecialchars($status_filter) ?>">
        <div class="col-6"><input type="text" name="search" class="form-control form-control-sm" placeholder="Search name/room..." value="<?= htmlspecialchars($search_query) ?>"></div>
        
        <div class="col-6 d-flex gap-1">
            <?php if(empty($filter_month)): ?>
                <a href="?status=<?= $status_filter ?>&filter_month=<?= date('Y-m') ?>" class="btn btn-sm btn-outline-secondary w-100 fw-bold text-truncate" style="border-radius:8px;">
                    Showing: All
                </a>
            <?php else: ?>
                <input type="month" name="filter_month" class="form-control form-control-sm fw-bold" value="<?= $filter_month ?>" onchange="this.form.submit()">
                <a href="?status=<?= $status_filter ?>&view_all=1" class="btn btn-sm btn-light border fw-bold" title="View All" style="border-radius:8px;">All</a>
            <?php endif; ?>
        </div>
    </form>
</div>

<form method="POST">
    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
    <?php if($status_filter == 'pending' && count($bookings_list) > 0): ?>
    <div class="px-4 mb-2 d-flex justify-content-between align-items-center">
        <div class="form-check small fw-bold"><input class="form-check-input" type="checkbox" id="selectAll"> <label class="form-check-label" for="selectAll">SELECT ALL</label></div>
        <button type="submit" name="bulk_approve" class="btn btn-success btn-sm rounded-pill px-3 fw-bold">Bulk Approve</button>
    </div>
    <?php endif; ?>

    <div class="dashboard-card">
        <div class="table-responsive">
            <table class="table mb-0 align-middle">
                <thead><tr><th style="width:40px"></th><th>Details</th><th class="text-end">Action</th></tr></thead>
                <tbody>
                    <?php if(empty($bookings_list)): ?>
                        <tr><td colspan="3" class="text-center py-5 text-muted">
                            <?php if($selected_date): ?>
                                No <?= $status_filter ?> bookings on <strong><?= date('d M Y', strtotime($selected_date)) ?></strong>.
                            <?php else: ?>
                                No <?= $status_filter ?> bookings found.
                            <?php endif; ?>
                        </td></tr>
                    <?php else: ?>
                        <?php foreach($bookings_list as $b): ?>
                        <tr>
                            <td class="ps-3">
                                <?php if($b['status']=='pending'): ?>
                                    <input type="checkbox" name="booking_ids[]" value="<?= $b['id'] ?>" class="chk-b">
                                <?php endif; ?>
                            </td>
                            <td style="line-height:1.2">
                                <a href="?status=<?= $status_filter ?>&filter_date=<?= $b['booking_date'] ?>" class="text-decoration-none text-dark">
                                    <div class="fw-bold small d-flex align-items-center gap-1">
                                        <i class="bi bi-calendar-event text-primary"></i> 
                                        <?= date('d M', strtotime($b['booking_date'])) ?>
                                        <?php if($selected_date == $b['booking_date']): ?>
                                            <span class="badge bg-primary ms-1" style="font-size:0.6rem">Selected</span>
                                        <?php endif; ?>
                                    </div>
                                </a>
                                <div class="small fw-bold mt-1"><?= htmlspecialchars($b['room_name']) ?></div>
                                <div class="text-primary fw-bold" style="font-size:0.7rem"><?= htmlspecialchars($b['teacher_name']) ?></div>
                                <div class="text-muted" style="font-size:0.65rem"><?= date('h:i A', strtotime($b['start_time'])) ?> - <?= date('h:i A', strtotime($b['end_time'])) ?></div>
                            </td>
                            <td class="text-end pe-3">
                                <div class="d-flex gap-2 justify-content-end align-items-center">
                                    <a href="edit_booking.php?id=<?= $b['id'] ?>" class="btn btn-sm btn-outline-primary border-0 p-1">
                                        <i class="bi bi-pencil-square"></i>
                                    </a>

                                    <a href="delete_booking.php?id=<?= $b['id'] ?>&token=<?= $_SESSION['csrf_token'] ?>" class="btn btn-sm btn-outline-danger border-0 p-1" onclick="return confirm('Delete?')"><i class="bi bi-trash"></i></a>
                                    
                                    <?php if($b['status']=='pending'): ?>
                                        <a href="update_status.php?id=<?= $b['id'] ?>&act=approve&token=<?= $_SESSION['csrf_token'] ?>" class="btn btn-sm btn-success p-1"><i class="bi bi-check"></i></a>
                                        <a href="update_status.php?id=<?= $b['id'] ?>&act=reject&token=<?= $_SESSION['csrf_token'] ?>" class="btn btn-sm btn-danger p-1"><i class="bi bi-x"></i></a>
                                    <?php else: ?>
                                        <i class="bi bi-shield-check text-muted"></i>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</form>

<div class="modal fade" id="floorPlanModal" tabindex="-1">
    <div class="modal-dialog modal-fullscreen-sm-down modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-dark text-white">
                <h5 class="modal-title"><i class="bi bi-map"></i> Live Floor Plans</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body bg-light modal-floor-container">
                <?php foreach($grouped_map as $loc => $rooms): ?>
                <div class="mb-3">
                    <h6 class="fw-bold text-muted small text-uppercase mb-2"><?= htmlspecialchars($loc) ?></h6>
                    <div class="row g-2">
                        <?php foreach($rooms as $r): 
                            $is_occ = isset($live_occupied[$r['id']]);
                            $occ_info = $is_occ ? $live_occupied[$r['id']] : null;
                        ?>
                        <div class="col-6 col-md-4">
                            <div class="map-room-box <?= $is_occ ? 'occupied' : '' ?>">
                                <div class="fw-bold small"><?= htmlspecialchars($r['name']) ?></div>
                                <div class="text-muted" style="font-size:0.65rem">
                                    <?= $is_occ ? '<span class="text-danger fw-bold">BUSY</span>' : '<span class="text-success">Avail</span>' ?>
                                </div>
                                <?php if($is_occ): ?>
                                    <div style="font-size:0.6rem; line-height:1.1; margin-top:3px;">
                                        <?= htmlspecialchars($occ_info['teacher_name']) ?><br>
                                        <span class="opacity-75">Until <?= date('h:i A', strtotime($occ_info['end_time'])) ?></span>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    const selAll = document.getElementById('selectAll');
    if(selAll){ selAll.addEventListener('change', function(){ document.querySelectorAll('.chk-b').forEach(c => c.checked = this.checked); }); }
    
    // Initialize Tooltips
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    const tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // --- SWIPE GESTURE LOGIC ---
    const calElement = document.getElementById('swipeCal');
    let touchStartX = 0;
    let touchStartY = 0;

    if(calElement){
        calElement.addEventListener('touchstart', function(e) {
            touchStartX = e.changedTouches[0].screenX;
            touchStartY = e.changedTouches[0].screenY;
        }, {passive: true});

        calElement.addEventListener('touchend', function(e) {
            let touchEndX = e.changedTouches[0].screenX;
            let touchEndY = e.changedTouches[0].screenY;
            handleSwipe(touchStartX, touchEndX, touchStartY, touchEndY);
        }, {passive: true});
    }

    function handleSwipe(sX, eX, sY, eY) {
        const xDiff = eX - sX;
        const yDiff = eY - sY;
        if (Math.abs(xDiff) > Math.abs(yDiff) + 30 && Math.abs(xDiff) > 50) {
            if (xDiff > 0) {
                document.getElementById('btn-prev-month')?.click();
            } else {
                document.getElementById('btn-next-month')?.click();
            }
        }
    }
</script>
<?php include '../../menu.php'; ?>
</body>
</html>