<?php
// Filename: calendar.php (ADMIN STYLE COLORS)
require 'config.php';
requireLogin();

header('Cache-Control: private, max-age=60'); 

$current_year = (int)date('Y');
$year = intval($_GET['year'] ?? $current_year);
$month = intval($_GET['month'] ?? date('n'));
$year = max(2000, min(2050, $year));
$month = max(1, min(12, $month));

// --- DATA LOADING ---
$cache_file = __DIR__ . '/cache/calendar_data.json';
$all_holidays = [];

if (file_exists($cache_file)) {
    $raw = @file_get_contents($cache_file);
    $all_holidays = $raw ? (json_decode($raw, true) ?: []) : [];
} else {
    $stmt = $pdo->prepare("SELECT type, start_date, end_date FROM school_holidays WHERE start_date <= ? AND end_date >= ?");
    $stmt->execute([sprintf('%04d-12-31', $year), sprintf('%04d-01-01', $year)]);
    $all_holidays = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// --- VISUAL MAP ---
$day_map = []; 
$m_start = sprintf('%04d-%02d-01', $year, $month);
$m_end   = date('Y-m-t', strtotime($m_start));

foreach ($all_holidays as $h) {
    if ($h['start_date'] <= $m_end && $h['end_date'] >= $m_start) {
        $s = max($h['start_date'], $m_start);
        $e = min($h['end_date'], $m_end);
        $curr = strtotime($s);
        $end  = strtotime($e);
        
        while ($curr <= $end) {
            $k = date('Y-m-d', $curr);
            if (!isset($day_map[$k])) $day_map[$k] = [];
            if (!in_array($h['type'], $day_map[$k])) $day_map[$k][] = $h['type'];
            $curr = strtotime('+1 day', $curr);
        }
    }
}

// Sort priority: National (Red) > Term (Blue) > School Event (Purple)
foreach ($day_map as $k => $types) {
    usort($day_map[$k], function($a, $b) {
        $pA = match($a){'national'=>1, 'term'=>2, 'cuti_peristiwa'=>3, 'cuti_ganti'=>4, 'school_event'=>5, default=>6};
        $pB = match($b){'national'=>1, 'term'=>2, 'cuti_peristiwa'=>3, 'cuti_ganti'=>4, 'school_event'=>5, default=>6};
        return $pA <=> $pB;
    });
}

// --- VIEW SETTINGS ---
$week_start = 1; 
$header_theme = 'linear-gradient(135deg, #6366f1 0%, #a855f7 100%)'; 
if (function_exists('getSetting')) $week_start = intval(getSetting('week_start_day', 1));
if (function_exists('getHeaderTheme')) $header_theme = getHeaderTheme();

$first_day = mktime(0, 0, 0, $month, 1, $year);
$days_in_month = date('t', $first_day);
$month_name = date('F', $first_day);
$offset = ($week_start == 1) ? (date('N', $first_day) - 1) : (date('N', $first_day) % 7);
?>
<!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, viewport-fit=cover">
    <title>Academic Calendar</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&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">
    <style>
        :root { --primary-grad: <?= htmlspecialchars($header_theme) ?>; --bg-color: #f1f5f9; }
        
        body { 
            font-family: 'Plus Jakarta Sans', sans-serif; 
            background-color: var(--bg-color); 
            padding-bottom: 90px; 
            overflow-x: hidden;
            background-image: radial-gradient(#cbd5e1 1.5px, transparent 1.5px);
            background-size: 24px 24px;
        }
        
        .app-header { background: var(--primary-grad); padding: 30px 20px 80px 20px; border-radius: 0 0 35px 35px; color: white; text-align: center; box-shadow: 0 10px 30px rgba(99, 102, 241, 0.2); }
        .floating-card { background: white; margin: -60px 20px 20px 20px; border-radius: 24px; padding: 20px; box-shadow: 0 20px 40px rgba(0,0,0,0.08); position: relative; z-index: 10; }
        
        .cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 6px; text-align: center; margin-top: 10px; }
        .cal-day-name { font-size: 0.7rem; color: #94a3b8; font-weight: 700; padding-bottom: 5px; text-transform: uppercase; letter-spacing: 0.5px; }
        
        /* --- ADMIN STYLE COLORS --- */
        .cal-day { 
            aspect-ratio: 1/1; display: flex; flex-direction: column; align-items: center; justify-content: flex-start; 
            padding-top: 6px; font-size: 0.95rem; font-weight: 700; 
            color: #334155; border-radius: 12px; border: 1px solid #f1f5f9; background: #fff; 
            transition: 0.2s; position: relative; 
        }
        .cal-day.empty { border: none; background: transparent; }
        .cal-day:not(.empty):active { transform: scale(0.95); }
        .cal-day.has-event { cursor: pointer; border-color: transparent; }

        /* Full Background Colors */
        .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; }
        
        /* Dots for multiple events */
        .event-dots { display: flex; gap: 3px; margin-top: auto; margin-bottom: 6px; flex-wrap: wrap; justify-content: center; width: 100%; padding: 0 3px; }
        .dot { width: 5px; height: 5px; border-radius: 50%; box-shadow: 0 1px 1px rgba(0,0,0,0.1); }
        /* Dot colors need to be solid to show up on colored backgrounds */
        .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; }

        /* Modal Styles */
        .modal-loader { display: flex; justify-content: center; padding: 40px; }
        .spinner-border { width: 3rem; height: 3rem; }
        .modal-content { border-radius: 32px; border: none; overflow: hidden; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); }
        .modal-header-hero { padding: 40px 30px 30px 30px; color: white; position: relative; z-index: 1; transition: background 0.3s; }
        .date-display { display: flex; flex-direction: column; text-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .big-day { font-size: 4rem; font-weight: 800; line-height: 0.9; letter-spacing: -2px; }
        .big-month { font-size: 1.2rem; font-weight: 600; text-transform: uppercase; letter-spacing: 2px; opacity: 0.9; margin-bottom: 5px; }
        .modal-body-custom { background: #f8f9fd; padding: 25px; min-height: 200px; }
        .event-card { background: white; border-radius: 20px; padding: 18px; margin-bottom: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); display: flex; align-items: center; gap: 15px; border: 1px solid #f1f5f9; }
        .icon-box { width: 48px; height: 48px; border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 1.4rem; flex-shrink: 0; }
        .modal-close-btn { position: absolute; top: 20px; right: 20px; background: rgba(255,255,255,0.2); border: none; color: white; width: 32px; height: 32px; border-radius: 50%; backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; cursor: pointer; z-index: 10; }
        .nav-btn-top { background: rgba(255,255,255,0.2); color: white; border: none; width: 36px; height: 36px; border-radius: 12px; display: flex; align-items: center; justify-content: center; text-decoration: none; backdrop-filter: blur(4px); }
        .month-select { background: rgba(255,255,255,0.2); border: 1px solid rgba(255,255,255,0.3); color: white; border-radius: 20px; font-weight: 600; text-align: center; cursor: pointer; }
        .month-select option { color: #333; }
        
        /* Modal Header Gradients (Solid/Bright) */
        .header-national { background: linear-gradient(135deg, #ef4444 0%, #f87171 100%); }
        .header-term { background: linear-gradient(135deg, #3b82f6 0%, #60a5fa 100%); }
        .header-school_event { background: linear-gradient(135deg, #8B5CF6 0%, #a78bfa 100%); }
        .header-cuti_peristiwa { background: linear-gradient(135deg, #f97316 0%, #fb923c 100%); }
        .header-cuti_ganti { background: linear-gradient(135deg, #10b981 0%, #34d399 100%); }
        .header-secondary { background: #64748b; }
        
        /* Icons */
        .icon-national { color: #ef4444; background: #fee2e2; }
        .icon-term { color: #3b82f6; background: #dbeafe; }
        .icon-school_event { color: #8B5CF6; background: #f3e8ff; }
        .icon-cuti_peristiwa { color: #f97316; background: #ffedd5; }
        .icon-cuti_ganti { color: #10b981; background: #dcfce7; }
    </style>
</head>
<body>
    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <a href="dashboard.php" class="nav-btn-top"><i class="bi bi-arrow-left"></i></a>
            <div class="fw-bold fs-5">Academic Calendar</div>
            <div style="width: 36px;"></div>
        </div>
        <form method="GET" class="d-flex justify-content-center align-items-center gap-2 mb-2">
            <?php
                $prev_m = $month - 1; $prev_y = $year; if($prev_m < 1) { $prev_m = 12; $prev_y--; }
                $next_m = $month + 1; $next_y = $year; if($next_m > 12) { $next_m = 1; $next_y++; }
            ?>
            <a href="?month=<?=$prev_m?>&year=<?=$prev_y?>" id="btn-prev" class="nav-btn-top"><i class="bi bi-chevron-left"></i></a>
            <select name="month" class="form-select form-select-sm month-select" style="width: auto;" 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>
            <select name="year" class="form-select form-select-sm month-select" style="width: auto;" onchange="this.form.submit()">
                <?php for($y=2020; $y<=2030; $y++): ?><option value="<?= $y ?>" <?= $y==$year?'selected':'' ?>><?= $y ?></option><?php endfor; ?>
            </select>
            <a href="?month=<?=$next_m?>&year=<?=$next_y?>" id="btn-next" class="nav-btn-top"><i class="bi bi-chevron-right"></i></a>
        </form>
    </div>

    <div class="floating-card">
        <h6 class="fw-bold text-center text-primary mb-3"><?= htmlspecialchars($month_name) ?> <?= $year ?></h6>
        <div class="cal-grid">
            <?php
                $days = ($week_start==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'>" . htmlspecialchars($d) . "</div>";
                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);
                    $types = $day_map[$date_str] ?? [];
                    
                    $has_event = !empty($types);
                    $onclick = $has_event ? "onclick=\"openEventModal('$date_str')\"" : "";
                    
                    // --- CHANGED LOGIC: PRIMARY BACKGROUND ---
                    // If multiple events, the FIRST type (highest priority due to sort above) sets the background.
                    // Additional events appear as dots.
                    $bg_class = "";
                    if ($has_event) {
                        $primary_type = $types[0];
                        $bg_class = "bg-" . $primary_type . " has-event";
                    }

                    $dots_html = "";
                    if($has_event && count($types) > 0) {
                        $dots_html = '<div class="event-dots">';
                        foreach($types as $t) {
                            $dots_html .= '<div class="dot dot-'.$t.'"></div>';
                        }
                        $dots_html .= '</div>';
                    }

                    echo "<div class='cal-day $bg_class' $onclick>
                            <span>$d</span>
                            $dots_html
                          </div>";
                }
            ?>
        </div>
    </div>
    
    <?php include 'menu.php'; ?>

    <div class="modal fade" id="eventModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div id="modalHeader" class="modal-header-hero header-secondary">
                    <button type="button" class="modal-close-btn" data-bs-dismiss="modal"><i class="bi bi-x-lg"></i></button>
                    <div class="date-display">
                        <span id="modalMonth" class="big-month">...</span>
                        <span id="modalDay" class="big-day">..</span>
                        <span id="modalDayName" class="day-name">Loading...</span>
                    </div>
                </div>
                <div class="modal-body-custom">
                    <div id="modalLoader" class="modal-loader"><div class="spinner-border text-primary"></div></div>
                    <div id="modalEventsList" style="display:none;"></div>
                </div>
                <div class="p-3 bg-white border-top text-center">
                    <small class="text-muted">Tap anywhere outside to close</small>
                </div>
            </div>
        </div>
    </div>

    <script defer src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const monthNames = ["January","February","March","April","May","June","July","August","September","October","November","December"];
        const daysOfWeek = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
        let eventModal;
        document.addEventListener('DOMContentLoaded', function() { eventModal = new bootstrap.Modal(document.getElementById('eventModal')); });

        async function openEventModal(dateStr) {
            const dateObj = new Date(dateStr + 'T00:00:00');
            document.getElementById('modalDay').innerText = dateObj.getDate();
            document.getElementById('modalMonth').innerText = monthNames[dateObj.getMonth()];
            document.getElementById('modalDayName').innerText = daysOfWeek[dateObj.getDay()];
            document.getElementById('modalHeader').className = `modal-header-hero header-secondary`; 
            document.getElementById('modalLoader').style.display = 'flex';
            document.getElementById('modalEventsList').style.display = 'none';
            eventModal.show();

            try {
                const response = await fetch(`api_calendar.php?date=${dateStr}`, { cache: "no-store" });
                const result = await response.json();

                if (!result.ok || !result.events || result.events.length === 0) {
                      document.getElementById('modalEventsList').innerHTML = '<div class="text-muted text-center pt-3">No events found.</div>';
                } else {
                    const events = result.events;
                    const primaryEvent = events[0];
                    const safeType = (primaryEvent.type || '').toLowerCase();
                    
                    document.getElementById('modalHeader').className = `modal-header-hero header-${safeType}`;

                    const html = events.map((event) => {
                        const t = (event.type || '').toLowerCase();
                        const displayType = (event.type || '').replace('_',' ').toUpperCase();
                        
                        return `
                        <div class="event-card">
                            <div class="icon-box icon-${t}"><i class="${getEventIcon(t)}"></i></div>
                            <div class="flex-grow-1">
                                <div class="fw-bold text-dark" style="font-size:1.05rem;">${escapeHtml(event.desc)}</div>
                                <div class="small text-muted fw-bold mt-1" style="font-size:0.75rem;">${escapeHtml(displayType)}</div>
                            </div>
                        </div>`;
                    }).join('');
                    document.getElementById('modalEventsList').innerHTML = html;
                }
                document.getElementById('modalLoader').style.display = 'none';
                document.getElementById('modalEventsList').style.display = 'block';
            } catch (error) {
                console.error(error);
                document.getElementById('modalEventsList').innerHTML = '<div class="text-danger text-center">Error.</div>';
            }
        }
        function getEventIcon(type) {
            switch(type) {
                case 'national': return 'bi bi-flag-fill';
                case 'term': return 'bi bi-airplane-fill';
                case 'school_event': return 'bi bi-calendar-check-fill';
                case 'cuti_peristiwa': return 'bi bi-star-fill';
                case 'cuti_ganti': return 'bi bi-arrow-repeat';
                default: return 'bi bi-info-circle';
            }
        }
        function escapeHtml(text) { const d = document.createElement('div'); d.textContent = text || ''; return d.innerHTML; }
        
        let touchStartX = 0, touchStartY = 0;
        document.addEventListener('touchstart', e => { touchStartX = e.changedTouches[0].screenX; touchStartY = e.changedTouches[0].screenY; }, {passive: true});
        document.addEventListener('touchend', e => {
            let xDiff = e.changedTouches[0].screenX - touchStartX;
            let yDiff = e.changedTouches[0].screenY - touchStartY;
            if (Math.abs(xDiff) > Math.abs(yDiff) + 30 && Math.abs(xDiff) > 50) {
                if (xDiff > 0) document.getElementById('btn-prev')?.click();
                else document.getElementById('btn-next')?.click();
            }
        }, {passive: true});
    </script>
</body>
</html>