<?php
// Filename: admin_holidays.php (MULTI-EVENT SUPPORT + SWIPE)
require 'config.php';
requireLogin();

// --- 1. PERMISSION CHECK ---
$uid = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
$allowed_roles = ['admin', 'timetable_coord', 'principal', 'assistant'];

if (empty(array_intersect($user_roles, $allowed_roles))) {
    header("Location: dashboard.php"); exit;
}

// --- 2. CACHE HELPER FUNCTION ---
function clearCalendarCache() {
    $cache_file = __DIR__ . '/cache/calendar_data.json';
    if (file_exists($cache_file)) {
        @unlink($cache_file);
    }
}

// --- 3. EXPORT ICS ACTION ---
if (isset($_GET['action']) && $_GET['action'] === 'export_ics') {
    $export_year = intval($_GET['export_year'] ?? date('Y'));
    
    $stmt = $pdo->prepare("SELECT * FROM school_holidays WHERE YEAR(start_date) = ?");
    $stmt->execute([$export_year]);
    $events = $stmt->fetchAll();

    header('Content-Type: text/calendar; charset=utf-8');
    header('Content-Disposition: attachment; filename=school_holidays_' . $export_year . '.ics');

    echo "BEGIN:VCALENDAR\r\n";
    echo "VERSION:2.0\r\n";
    echo "PRODID:-//SchoolSystem//Holidays//EN\r\n";
    echo "CALSCALE:GREGORIAN\r\n";
    
    foreach($events as $e) {
        echo "BEGIN:VEVENT\r\n";
        echo "UID:" . md5($e['id'] . $e['start_date']) . "@schoolsystem.local\r\n";
        echo "DTSTAMP:" . date('Ymd\THis\Z') . "\r\n";
        echo "DTSTART;VALUE=DATE:" . date('Ymd', strtotime($e['start_date'])) . "\r\n";
        $ics_end = date('Ymd', strtotime($e['end_date'] . ' +1 day'));
        echo "DTEND;VALUE=DATE:" . $ics_end . "\r\n";
        echo "SUMMARY:" . $e['description'] . "\r\n";
        echo "END:VEVENT\r\n";
    }
    
    echo "END:VCALENDAR";
    exit;
}

// --- 4. SECURITY & HELPERS ---
header("X-Frame-Options: DENY");
header("X-XSS-Protection: 1; mode=block");
header("X-Content-Type-Options: nosniff");

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$msg = ''; $msg_type = '';

function parseIcsDate($icsDate) {
    $icsDate = trim(explode(';', $icsDate)[0]); 
    $icsDate = trim(explode('T', $icsDate)[0]); 
    if (strlen($icsDate) === 8 && is_numeric($icsDate)) {
        return substr($icsDate, 0, 4) . '-' . substr($icsDate, 4, 2) . '-' . substr($icsDate, 6, 2);
    }
    if (strlen($icsDate) === 10 && strpos($icsDate, '-') !== false) {
         return $icsDate;
    }
    return null;
}

function fetchUrl($url) {
    $context = stream_context_create(["http" => ["method" => "GET", "header" => "User-Agent: Mozilla/5.0"]]);
    return @file_get_contents($url, false, $context);
}

// --- 5. HANDLE POST ACTIONS ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        die("Security Alert: Invalid Request.");
    }

    // A. CLEANUP DUPLICATES
    if (isset($_POST['action']) && $_POST['action'] === 'cleanup_duplicates') {
        try {
            $all = $pdo->query("SELECT id, description, start_date FROM school_holidays ORDER BY id ASC")->fetchAll();
            $seen = [];
            $ids_to_delete = [];
            
            foreach ($all as $row) {
                $key = strtolower(trim($row['description'])) . '|' . $row['start_date'];
                if (isset($seen[$key])) {
                    $ids_to_delete[] = $row['id'];
                } else {
                    $seen[$key] = true;
                }
            }

            if (!empty($ids_to_delete)) {
                $in = str_repeat('?,', count($ids_to_delete) - 1) . '?';
                $del = $pdo->prepare("DELETE FROM school_holidays WHERE id IN ($in)");
                $del->execute($ids_to_delete);
                clearCalendarCache(); // CACHE CLEARED
                $msg = "Removed " . count($ids_to_delete) . " duplicate events."; 
                $msg_type = "success";
            } else {
                $msg = "No duplicates found."; $msg_type = "info";
            }
        } catch (Exception $e) {
            $msg = "Error cleaning up: " . $e->getMessage(); $msg_type = "danger";
        }
    }

    // B. DELETE SINGLE HOLIDAY
    if (isset($_POST['action']) && $_POST['action'] === 'delete') {
        try {
            $pdo->prepare("DELETE FROM school_holidays WHERE id=?")->execute([$_POST['id']]);
            clearCalendarCache(); // CACHE CLEARED
            $msg = "Holiday deleted."; $msg_type = "warning";
        } catch (Exception $e) {
            $msg = "Error deleting holiday."; $msg_type = "danger";
        }
    }

    // C. SAVE / UPDATE HOLIDAY
    if (isset($_POST['action']) && $_POST['action'] === 'save_holiday') {
        $id = $_POST['holiday_id'] ?? null;
        $desc = trim($_POST['description']);
        $start = $_POST['start_date']; 
        $end = $_POST['end_date']; 
        $type = $_POST['type'];
        
        if ($end < $start) { 
            $msg = "End date cannot be before start date."; $msg_type = "danger"; 
        } else {
            try {
                if ($id) {
                    $stmt = $pdo->prepare("UPDATE school_holidays SET description=?, start_date=?, end_date=?, type=? WHERE id=?");
                    $stmt->execute([$desc, $start, $end, $type, $id]); 
                } else {
                    $check = $pdo->prepare("SELECT id FROM school_holidays WHERE description = ? AND start_date = ?");
                    $check->execute([$desc, $start]);
                    
                    if($check->rowCount() > 0) {
                        $msg = "Skipped: This event already exists."; $msg_type = "warning";
                    } else {
                        $stmt = $pdo->prepare("INSERT INTO school_holidays (description, start_date, end_date, type) VALUES (?, ?, ?, ?)");
                        $stmt->execute([$desc, $start, $end, $type]); 
                    }
                }

                if (empty($msg)) {
                    clearCalendarCache(); // CACHE CLEARED
                    $msg = "Holiday saved successfully."; $msg_type = "success";
                }
            } catch (Exception $e) { $msg = "Database Error."; $msg_type = "danger"; }
        }
    }
    
    // D. IMPORT ICS
    if (isset($_POST['action']) && $_POST['action'] === 'import_ics') {
        $content = null; 
        $default_type = $_POST['default_type'] ?? 'national';
        
        if (!empty($_POST['ics_url'])) { 
            if (filter_var($_POST['ics_url'], FILTER_VALIDATE_URL)) $content = fetchUrl($_POST['ics_url']); 
        } elseif (isset($_FILES['ics_file']) && $_FILES['ics_file']['error'] == 0) { 
            $content = file_get_contents($_FILES['ics_file']['tmp_name']); 
        }

        if ($content) {
            try {
                preg_match_all('/BEGIN:VEVENT(.*?)END:VEVENT/s', $content, $events); 
                $count = 0;
                $stmt = $pdo->prepare("INSERT INTO school_holidays (description, start_date, end_date, type) VALUES (?, ?, ?, ?)");
                
                foreach ($events[1] as $event) {
                    $summary = ''; $dtstart = ''; $dtend = '';
                    if (preg_match('/SUMMARY:(.*?)\r?\n/', $event, $matches)) $summary = trim($matches[1]);
                    if (preg_match('/DTSTART(?:;VALUE=DATE)?:(.*?)\r?\n/', $event, $matches)) $dtstart = parseIcsDate($matches[1]);
                    if (preg_match('/DTEND(?:;VALUE=DATE)?:(.*?)\r?\n/', $event, $matches)) $dtend = parseIcsDate($matches[1]);
                    
                    if ($summary && $dtstart) {
                        if (!$dtend) $dtend = $dtstart;
                        if ($dtend > $dtstart) $dtend = date('Y-m-d', strtotime($dtend . ' -1 day'));
                        
                        $dupCheck = $pdo->prepare("SELECT id FROM school_holidays WHERE description = ? AND start_date = ?");
                        $dupCheck->execute([$summary, $dtstart]);
                        if (!$dupCheck->fetch()) {
                             $stmt->execute([$summary, $dtstart, $dtend, $default_type]); 
                             $count++;
                        }
                    }
                }
                clearCalendarCache(); // CACHE CLEARED
                $msg = "Imported $count holidays successfully."; $msg_type = "success";
            } catch (Exception $e) { $msg = "Import Failed: " . $e->getMessage(); $msg_type = "danger"; }
        } else {
            $msg = "No file or URL provided."; $msg_type = "warning";
        }
    }

    // E. DELETE ENTIRE YEAR
    if (isset($_POST['action']) && $_POST['action'] === 'delete_year_data') {
        try {
            $pdo->prepare("DELETE FROM school_holidays WHERE YEAR(start_date) = ?")->execute([$_POST['target_year']]);
            clearCalendarCache(); // CACHE CLEARED
            $msg = "All holidays for " . $_POST['target_year'] . " cleared."; $msg_type = "warning";
        } catch (Exception $e) {
             $msg = "Error clearing holidays."; $msg_type = "danger";
        }
    }
}

// --- 6. FETCH DATA FOR VIEW ---
$year = isset($_GET['year']) ? intval($_GET['year']) : intval(date('Y'));
$month = isset($_GET['month']) ? intval($_GET['month']) : intval(date('m'));
$highlight = $_GET['highlight'] ?? null; 

// Navigator Logic
$prev_month = $month - 1; $prev_year = $year;
if ($prev_month < 1) { $prev_month = 12; $prev_year--; }

$next_month = $month + 1; $next_year = $year;
if ($next_month > 12) { $next_month = 1; $next_year++; }

// Fetch All Holidays for the Selected Year
$holidays = $pdo->prepare("SELECT * FROM school_holidays WHERE YEAR(start_date) = ? ORDER BY start_date ASC");
$holidays->execute([$year]);
$list = $holidays->fetchAll();

// Group holidays by month (For List View)
$holidays_by_month = [];
foreach ($list as $h) {
    $m_num = date('n', strtotime($h['start_date']));
    $holidays_by_month[$m_num][] = $h;
}

// Build Calendar Events Map (UPDATED FOR MULTIPLE EVENTS)
$calendar_events = [];
foreach ($list as $h) {
    $current = strtotime($h['start_date']); 
    $last = strtotime($h['end_date']);
    $safety = 0;
    while ($current <= $last && $safety < 366) {
        $date_key = date('Y-m-d', $current);
        
        // Initialize if not exists
        if (!isset($calendar_events[$date_key])) {
            $calendar_events[$date_key] = [];
        }
        
        // Append event info
        $calendar_events[$date_key][] = [
            'id' => $h['id'],
            'type' => $h['type'], 
            'desc' => $h['description'],
            'start_date' => $h['start_date'],
            'end_date' => $h['end_date']
        ];
        
        $current = strtotime('+1 day', $current);
        $safety++;
    }
}

// Calendar View Calculation
$first_day = mktime(0,0,0,$month,1,$year);
$days_in_month = date('t', $first_day);
$month_name = date('F', $first_day);

if (function_exists('getSetting')) {
    $week_start_day = intval(getSetting('week_start_day', 1));
} else {
    $week_start_day = 1; 
}
$header_theme = 'linear-gradient(135deg, #6366f1 0%, #a855f7 100%)';
if (function_exists('getHeaderTheme')) {
    $header_theme = getHeaderTheme();
}

$start_dow = date('N', $first_day);
$offset = ($week_start_day == 1) ? ($start_dow - 1) : ($start_dow % 7);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Holidays</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    
    <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 rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>

    <style>
       :root { --primary-grad: <?= $header_theme ?>; --bg-color: #f8f9fd; --text-dark: #1e293b; --text-gray: #64748b; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }

        /* HEADER */
        .app-header {
            background: var(--primary-grad); padding: 30px 20px 80px 20px;
            border-radius: 0 0 35px 35px; color: white; text-align: center;
        }

        /* FLOATING CARD */
        .floating-card {
            background: white; margin: -60px 20px 20px 20px;
            border-radius: 24px; padding: 20px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.08);
            position: relative; z-index: 10;
        }

        /* CALENDAR GRID */
        .cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 5px; text-align: center; margin-bottom: 10px; }
        .cal-day-name { font-size: 0.7rem; color: #94a3b8; font-weight: 700; padding: 5px 0; text-transform: uppercase; }
        
        /* UPDATED CAL-DAY for stacking dots */
        .cal-day { 
            background: #f8fafc; 
            aspect-ratio: 1/1; 
            display: flex; 
            flex-direction: column; 
            align-items: center; 
            justify-content: flex-start; /* Align date top */
            padding-top: 5px;
            font-size: 0.85rem; 
            font-weight: 600; 
            color: var(--text-dark); 
            border-radius: 12px; 
            cursor: pointer; 
            border: 1px solid transparent; 
            transition: 0.2s; 
            position: relative;
            overflow: hidden;
        }
        .cal-day:hover { border-color: #8B5CF6; z-index: 2; transform: scale(1.05); }
        .cal-day.empty { background: transparent; cursor: default; }
        
        /* HOLIDAY TYPES (Backgrounds) */
        .bg-national { background-color: #fee2e2; color: #ef4444; border: 1px solid #fecaca; }
        .bg-term { background-color: #e0f2fe; color: #0ea5e9; border: 1px solid #bae6fd; }
        .bg-cuti_peristiwa { background-color: #ffedd5; color: #f97316; border: 1px solid #fed7aa; }
        .bg-cuti_ganti { background-color: #dcfce7; color: #10b981; border: 1px solid #bbf7d0; }
        .bg-school_event { background-color: #f3e8ff; color: #8B5CF6; border: 1px solid #d8b4fe; }
        .bg-special { background-color: #ccfbf1; color: #14b8a6; border: 1px solid #99f6e4; }
        
        /* EVENT DOTS (New) */
        .event-dots {
            display: flex; gap: 3px; margin-top: auto; margin-bottom: 5px;
            flex-wrap: wrap; justify-content: center; width: 100%; padding: 0 2px;
        }
        .dot {
            width: 5px; height: 5px; border-radius: 50%;
            box-shadow: 0 1px 1px rgba(0,0,0,0.1);
        }
        .dot-national { background-color: #ef4444; } 
        .dot-term { background-color: #0ea5e9; } 
        .dot-cuti_peristiwa { background-color: #f97316; } 
        .dot-cuti_ganti { background-color: #10b981; }
        .dot-school_event { background-color: #8B5CF6; }
        .dot-special { background-color: #14b8a6; }

        .highlight-date { box-shadow: 0 0 0 2px #f59e0b, 0 4px 15px rgba(0,0,0,0.1) !important; transform: scale(1.1); z-index: 10; }

        /* LIST ITEM */
        .holiday-item { 
            background: white; border-radius: 12px; padding: 12px; margin-bottom: 8px; 
            box-shadow: 0 2px 5px rgba(0,0,0,0.02); border-left: 5px solid #ccc; 
            display: flex; justify-content: space-between; align-items: center; 
            transition: transform 0.2s; cursor: pointer;
        }
        .holiday-item:active { transform: scale(0.98); }
        
        .type-national { border-left-color: #ef4444; } 
        .type-term { border-left-color: #0ea5e9; } 
        .type-cuti_peristiwa { border-left-color: #f97316; } 
        .type-cuti_ganti { border-left-color: #10b981; }
        .type-school_event { border-left-color: #8B5CF6; }

        .date-box { background: #f8fafc; border-radius: 8px; padding: 4px 10px; text-align: center; min-width: 50px; margin-right: 12px; border: 1px solid #f1f5f9; }
        .date-box .day { font-size: 1.1rem; font-weight: 800; line-height: 1; color: var(--text-dark); }
        .date-box .month { font-size: 0.6rem; text-transform: uppercase; font-weight: 700; color: var(--text-gray); }

        /* CONTROLS */
        .form-select, .form-control { border-radius: 12px; border: 1px solid #e2e8f0; background: #f8fafc; font-weight: 600; font-size: 0.9rem; }
        .form-select:focus, .form-control:focus { border-color: #8B5CF6; background: white; box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1); }

        /* ACCORDION CUSTOM */
        .accordion-item { overflow: hidden; border: none; box-shadow: 0 2px 10px rgba(0,0,0,0.03); margin-bottom: 10px; border-radius: 16px !important; }
        .accordion-button { font-weight: 700; color: #475569; background: white; padding: 15px 20px; box-shadow: none !important; }
        .accordion-button:not(.collapsed) { background: #f1f5f9; color: #0f172a; }
        .accordion-body { background: #f8fafc; padding: 10px; }
    </style>
</head>
<body>

    <div class="app-header" id="topAnchor">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="admin_dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">Holidays</div>
            <div style="width: 24px;"></div>
        </div>
        <div class="opacity-75 small">Manage Academic Calendar</div>
    </div>

    <div class="floating-card">
        <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> border-0 shadow-sm rounded-3 text-center small mb-3 animate__animated animate__fadeIn"><?= $msg ?></div><?php endif; ?>

        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="fw-bold text-dark m-0">Calendar View</h6>
            <div class="d-flex gap-2">
                <a href="?action=export_ics&export_year=<?= $year ?>" class="btn btn-warning btn-sm rounded-pill fw-bold shadow-sm" title="Backup to ICS"><i class="bi bi-cloud-arrow-down me-1"></i> Export</a>
                <button class="btn btn-success btn-sm rounded-pill fw-bold shadow-sm" onclick="openImport()"><i class="bi bi-cloud-arrow-up me-1"></i> ICS</button>
                <button class="btn btn-primary btn-sm rounded-pill fw-bold shadow-sm" onclick="openModal()">+ Add</button>
            </div>
        </div>

        <form method="GET" class="row g-1 align-items-center mb-3">
            <div class="col-auto">
                <a href="?month=<?= $prev_month ?>&year=<?= $prev_year ?>" id="btn-prev" class="btn btn-light btn-sm rounded-circle border shadow-sm text-secondary"><i class="bi bi-chevron-left"></i></a>
            </div>
            <div class="col">
                <select name="month" class="form-select form-select-sm" onchange="this.form.submit()">
                    <?php for($m=1; $m<=12; $m++): ?><option value="<?= $m ?>" <?= $m==$month ? 'selected':'' ?>><?= date('F', mktime(0,0,0,$m,1)) ?></option><?php endfor; ?>
                </select>
            </div>
            <div class="col-auto">
                <select name="year" class="form-select form-select-sm" onchange="this.form.submit()">
                    <?php for($y=date('Y')-1; $y<=2030; $y++): ?><option value="<?= $y ?>" <?= $y==$year ? 'selected':'' ?>><?= $y ?></option><?php endfor; ?>
                </select>
            </div>
            <div class="col-auto">
                <a href="?month=<?= $next_month ?>&year=<?= $next_year ?>" id="btn-next" class="btn btn-light btn-sm rounded-circle border shadow-sm text-secondary"><i class="bi bi-chevron-right"></i></a>
            </div>
            <div class="col text-end">
                <button type="button" class="btn btn-outline-warning btn-sm rounded-circle shadow-sm me-1" onclick="confirmCleanup()" title="Fix Duplicates"><i class="bi bi-magic"></i></button>
                <?php if(!empty($list)): ?>
                    <button type="button" class="btn btn-outline-danger btn-sm rounded-circle shadow-sm" onclick="confirmClearYear()" title="Clear Year"><i class="bi bi-trash"></i></button>
                <?php endif; ?>
            </div>
        </form>

        <div class="cal-grid">
            <?php $days = ($week_start_day==7) ? ['S','M','T','W','T','F','S'] : ['M','T','W','T','F','S','S']; foreach($days as $d) echo "<div class='cal-day-name'>$d</div>"; ?>
            <?php
            for ($i=0; $i<$offset; $i++) echo "<div class='cal-day empty'></div>";
            for ($d=1; $d<=$days_in_month; $d++) {
                $date_str = sprintf("%04d-%02d-%02d", $year, $month, $d);
                
                // Get events array for this day (may be empty, 1 event, or multiple)
                $day_events = $calendar_events[$date_str] ?? [];
                
                $bg_class = "";
                $onclick = "onclick=\"openModal('$date_str')\"";
                $tooltip = "";
                $dots_html = "";

                if (!empty($day_events)) {
                    // Use the background color of the first event (or you could prioritize them)
                    $bg_class = "bg-" . $day_events[0]['type'];
                    
                    // Create tooltip with all event descriptions
                    $desc_array = array_map(function($e) { return "• " . $e['desc']; }, $day_events);
                    $tooltip = htmlspecialchars(implode("\n", $desc_array));
                    
                    // Logic for clicking:
                    // If 1 event -> Edit normally.
                    // If >1 event -> Show dots, click prompts to check list.
                    $onclick = "onclick=\"editHolidayFromCal('$date_str')\"";

                    // Build Dots HTML
                    $dots_html = '<div class="event-dots">';
                    foreach($day_events as $ev) {
                        $dots_html .= '<div class="dot dot-'.$ev['type'].'"></div>';
                    }
                    $dots_html .= '</div>';
                }

                $hl_class = ($date_str == $highlight) ? "highlight-date" : "";
                
                echo "<div class='cal-day $bg_class $hl_class' $onclick title='$tooltip'>
                        <span>$d</span>
                        $dots_html
                      </div>";
            }
            ?>
        </div>
    </div>

    <div class="px-3 pb-4">
        <h6 class="text-muted fw-bold small text-uppercase mb-3 px-1">Events List (<?= $year ?>)</h6>

        <?php if(empty($list)): ?>
            <div class="text-center py-5 text-muted small opacity-50">
                <i class="bi bi-calendar-event display-1"></i><br>No holidays found.
            </div>
        <?php else: ?>
            <div class="accordion" id="holidayAccordion">
                <?php for($m=1; $m<=12; $m++): 
                    if(empty($holidays_by_month[$m])) continue; 
                    $monthName = date('F', mktime(0,0,0,$m, 1));
                    $is_open = ($m == $month); // Open the currently selected month
                ?>
                <div class="accordion-item">
                    <h2 class="accordion-header">
                        <button class="accordion-button <?= $is_open ? '':'collapsed' ?>" type="button" data-bs-toggle="collapse" data-bs-target="#collapseMonth<?= $m ?>">
                            <?= $monthName ?>
                            <span class="badge bg-primary-subtle text-primary ms-2 rounded-pill small" style="font-size: 0.75em;"><?= count($holidays_by_month[$m]) ?></span>
                        </button>
                    </h2>
                    <div id="collapseMonth<?= $m ?>" class="accordion-collapse collapse <?= $is_open ? 'show':'' ?>" data-bs-parent="#holidayAccordion">
                        <div class="accordion-body">
                            <?php foreach($holidays_by_month[$m] as $h): 
                                $start = strtotime($h['start_date']); 
                                $end = strtotime($h['end_date']);
                                $is_range = ($h['start_date'] != $h['end_date']);
                                $link = "?month=".date('n', $start)."&year=".date('Y', $start)."&highlight={$h['start_date']}#topAnchor";
                            ?>
                            <div class="holiday-item type-<?= $h['type'] ?>">
                                <div class="d-flex align-items-center flex-grow-1" onclick="window.location='<?= $link ?>'">
                                    <div class="date-box">
                                        <div class="day"><?= date('d', $start) ?></div>
                                        <div class="month"><?= date('M', $start) ?></div>
                                    </div>
                                    <div class="overflow-hidden">
                                        <div class="fw-bold text-dark text-truncate" style="max-width: 180px;"><?= htmlspecialchars($h['description']) ?></div>
                                        <div class="small text-muted"><?= ($is_range) ? "Until " . date('d M', $end) : date('l') ?></div>
                                    </div>
                                </div>
                                <div class="d-flex gap-1 ms-2">
                                    <button class="btn btn-light border btn-sm rounded-circle text-primary" onclick='editHoliday(<?= json_encode($h) ?>)'><i class="bi bi-pencil-fill"></i></button>
                                    <button class="btn btn-light border btn-sm rounded-circle text-danger" onclick="confirmDelete(<?= $h['id'] ?>)"><i class="bi bi-trash-fill"></i></button>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <?php endfor; ?>
            </div>
        <?php endif; ?>
    </div>

    <form id="deleteForm" method="POST" style="display:none">
        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
        <input type="hidden" name="action" value="delete">
        <input type="hidden" name="id" id="delete_id">
    </form>

    <form id="cleanupForm" method="POST" style="display:none">
        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
        <input type="hidden" name="action" value="cleanup_duplicates">
    </form>

    <form id="clearYearForm" method="POST" style="display:none;">
        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
        <input type="hidden" name="action" value="delete_year_data">
        <input type="hidden" name="target_year" value="<?= $year ?>">
    </form>

    <div class="modal fade" id="holidayModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow rounded-4">
                <div class="modal-header border-0 bg-primary text-white">
                    <h6 class="modal-title fw-bold" id="modalTitle">Add Holiday</h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                    <input type="hidden" name="action" value="save_holiday">
                    <input type="hidden" name="holiday_id" id="ed_id">
                    
                    <div class="modal-body p-4">
                        <div class="mb-3">
                            <label class="form-label small fw-bold text-muted">Description</label>
                            <input type="text" name="description" id="ed_desc" class="form-control" placeholder="e.g. Labour Day" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label small fw-bold text-muted">Type</label>
                            <select name="type" id="ed_type" class="form-select">
                                <option value="national">National Holiday (Red)</option>
                                <option value="term">Term Break (Blue)</option>
                                <option value="cuti_peristiwa">Cuti Peristiwa (Orange)</option>
                                <option value="cuti_ganti">Cuti Ganti (Green)</option>
                                <option value="school_event">School Event (Purple)</option>
                                <option value="special">Special Holiday (Teal)</option>
                            </select>
                        </div>
                        <div class="row g-2">
                            <div class="col-6">
                                <label class="form-label small fw-bold text-muted">Start Date</label>
                                <input type="date" name="start_date" id="ed_start" class="form-control" required>
                            </div>
                            <div class="col-6">
                                <label class="form-label small fw-bold text-muted">End Date</label>
                                <input type="date" name="end_date" id="ed_end" class="form-control" required>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer border-0 pt-0">
                        <button type="submit" class="btn btn-primary w-100 rounded-pill fw-bold">Save Event</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="importModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow rounded-4">
                <div class="modal-header border-0 bg-success text-white">
                    <h6 class="modal-title fw-bold">Import Calendar</h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                    <input type="hidden" name="action" value="import_ics">
                    
                    <div class="modal-body p-4">
                        <div class="mb-3">
                            <label class="form-label small fw-bold text-success">Option A: Upload .ICS</label>
                            <input type="file" name="ics_file" class="form-control" accept=".ics">
                        </div>
                        <div class="text-center small text-muted mb-3 fw-bold">- OR -</div>
                        <div class="mb-3">
                            <label class="form-label small fw-bold text-primary">Option B: ICS URL</label>
                            <input type="url" name="ics_url" class="form-control" placeholder="https://calendar.google.com/...">
                        </div>
                        <div class="mb-2">
                            <label class="form-label small fw-bold text-muted">Import As</label>
                            <select name="default_type" class="form-select">
                                <option value="national">National Holiday</option>
                                <option value="term">Term Break</option>
                                <option value="school_event">School Event</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer border-0 pt-0">
                        <button class="btn btn-success w-100 rounded-pill fw-bold">Start Import</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'menu.php'; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const holidayModal = new bootstrap.Modal(document.getElementById('holidayModal'));
        const importModal = new bootstrap.Modal(document.getElementById('importModal'));
        const holidays = <?= json_encode($list) ?>;

        function openModal(date = '') {
            document.getElementById('modalTitle').innerText = "Add Holiday";
            document.getElementById('ed_id').value = "";
            document.getElementById('ed_desc').value = "";
            document.getElementById('ed_type').value = "national";
            
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('ed_start').value = date || today;
            document.getElementById('ed_end').value = date || today;
            
            holidayModal.show();
        }

        function openImport() { importModal.show(); }

        function editHoliday(h) {
            document.getElementById('modalTitle').innerText = "Edit Holiday";
            document.getElementById('ed_id').value = h.id;
            document.getElementById('ed_desc').value = h.description;
            document.getElementById('ed_type').value = h.type;
            document.getElementById('ed_start').value = h.start_date;
            document.getElementById('ed_end').value = h.end_date;
            holidayModal.show();
        }
        
        function editHolidayFromCal(dateStr) {
            // Find ALL holidays on this date
            const foundEvents = holidays.filter(h => dateStr >= h.start_date && dateStr <= h.end_date);
            
            if (foundEvents.length === 1) {
                // Only 1 event? Edit it directly.
                editHoliday(foundEvents[0]);
            } else if (foundEvents.length > 1) {
                // Multiple events? Alert user to use list view.
                let msg = "📅 Multiple events found on this date:\n";
                foundEvents.forEach((e, index) => {
                    msg += (index+1) + ". " + e.description + "\n";
                });
                msg += "\nPlease use the 'Events List' below to edit specific overlapping events.";
                alert(msg);
                
                // Optional: Scroll to list
                const listEl = document.getElementById('holidayAccordion');
                if(listEl) listEl.scrollIntoView({behavior: 'smooth'});
            } else {
                openModal(dateStr);
            }
        }

        function confirmDelete(id) {
            if(confirm("Delete this holiday?")) {
                document.getElementById('delete_id').value = id;
                document.getElementById('deleteForm').submit();
            }
        }

        function confirmClearYear() {
            if(confirm('WARNING: Delete ALL holidays for <?= $year ?>? This cannot be undone.')) {
                document.getElementById('clearYearForm').submit();
            }
        }

        function confirmCleanup() {
            if(confirm('Auto-remove duplicate events? This will keep only one instance of any event with the same name and start date.')) {
                document.getElementById('cleanupForm').submit();
            }
        }

        // --- SWIPE GESTURE SUPPORT ---
        let touchStartX = 0;
        let touchStartY = 0;

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

        document.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;
            // 50px Threshold, horizontal must be greater than vertical
            if (Math.abs(xDiff) > Math.abs(yDiff) + 30 && Math.abs(xDiff) > 50) {
                if (xDiff > 0) {
                    // Right swipe -> Prev
                    document.getElementById('btn-prev')?.click();
                } else {
                    // Left swipe -> Next
                    document.getElementById('btn-next')?.click();
                }
            }
        }
    </script>
</body>
</html>