<?php
// Filename: public_calendar.php
require 'config.php';

// 1. CHECK IF ENABLED
if (getSetting('public_calendar_enabled', '1') !== '1') {
    die("<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'><meta name='viewport' content='width=device-width,initial-scale=1.0'><title>Calendar Closed</title><link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'></head><body class='bg-light d-flex align-items-center justify-content-center vh-100'><div class='text-center p-5 bg-white shadow rounded-4'><h4>Calendar Unavailable</h4><p class='text-muted small'>This feature is currently disabled.</p><a href='index.php' class='btn btn-primary rounded-pill mt-2'>Back to Login</a></div></body></html>");
 }

$s_name = getSetting('school_name', 'SAS');
$s_logo = getSetting('school_logo', '');

// --- DATA FETCHING (FIXED TYPE ERROR) ---
// Force input to be Integer (int) for PHP 8 compliance
$year = intval($_GET['year'] ?? date('Y'));
$month = intval($_GET['month'] ?? date('m'));
$highlight = $_GET['highlight'] ?? null;

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

// Map for Calendar
$calendar_events = [];
foreach ($list as $h) {
    $current = strtotime($h['start_date']);
    $last = strtotime($h['end_date']);
    while ($current <= $last) {
        $date_key = date('Y-m-d', $current);
        $calendar_events[$date_key] = [
            'type' => $h['type'], 
            'desc' => $h['description'],
            'is_start' => ($current == strtotime($h['start_date'])) // Mark start date
        ];
        $current = strtotime('+1 day', $current);
    }
}

// Calendar Logic
// mktime now receives integers, so this will no longer crash
$first_day = mktime(0,0,0,$month,1,$year);
$days_in_month = date('t', $first_day);
$month_name = date('F', $first_day);
$week_start = intval(getSetting('week_start_day', 1)); 
$start_dow = date('N', $first_day);
$offset = ($week_start == 1) ? ($start_dow - 1) : ($start_dow % 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">
    <title>School Calendar</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
    <style>
        body { font-family: 'Poppins', sans-serif; background-color: #f0f2f5; padding-bottom: 40px; }
        
        /* HEADER */
        .header-card {
            background: linear-gradient(135deg, #0d6efd 0%, #004494 100%);
            color: white; border-radius: 0 0 30px 30px;
            padding: 40px 20px 60px 20px; margin-bottom: -40px; text-align: center;
            box-shadow: 0 4px 20px rgba(13, 110, 253, 0.2);
        }
        .school-logo { 
            width: 90px; height: 90px; object-fit: contain; margin-bottom: 10px; 
            filter: drop-shadow(0 4px 6px rgba(0,0,0,0.2)); 
        }

        /* CALENDAR */
        .cal-card { background: white; border-radius: 20px; padding: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.08); border: 0; margin-bottom: 20px; }
        .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: #adb5bd; font-weight: 700; padding-bottom: 5px; text-transform: uppercase; }
        
        .cal-day { 
            aspect-ratio: 1/1; display: flex; flex-direction: column; align-items: center; justify-content: center;
            font-size: 0.9rem; font-weight: 600; color: #495057; border-radius: 12px;
            position: relative; transition: 0.2s; border: 1px solid #f8f9fa; background: #fff;
        }
        .cal-day:not(.empty):active { transform: scale(0.9); }
        .cal-day.has-event { cursor: pointer; border-width: 0; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        
        /* EVENT COLORS - FIXED WITH !important */
        .bg-national { background: linear-gradient(135deg, #ff5f6d 0%, #ffc371 100%) !important; color: white; }
        .bg-term { background: linear-gradient(135deg, #36d1dc 0%, #5b86e5 100%) !important; color: white; }
        .bg-cuti_peristiwa { background: linear-gradient(135deg, #fce38a 0%, #f38181 100%) !important; color: #856404; }
        .bg-cuti_ganti { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%) !important; color: white; }
        .bg-activity { background: linear-gradient(135deg, #00f260 0%, #0575e6 100%) !important; color: white; }
        .bg-school_event { background: linear-gradient(135deg, #c33764 0%, #1d2671 100%) !important; color: white; }
        .bg-special { background: linear-gradient(135deg, #8e2de2 0%, #4a00e0 100%) !important; color: white; }
        
        /* HIGHLIGHT & ANIMATION */
        .highlight-date { 
            transform: scale(1.15); z-index: 10; 
            box-shadow: 0 0 0 3px #ffc107, 0 10px 20px rgba(0,0,0,0.2);
            animation: pulse 1.5s infinite;
        }
        @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.7); } 70% { box-shadow: 0 0 0 10px rgba(255, 193, 7, 0); } 100% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0); } }

        /* MODAL STYLES */
        .modal-content { border-radius: 25px; border: none; overflow: hidden; box-shadow: 0 15px 40px rgba(0,0,0,0.2); }
        .modal-header-fancy {
            height: 140px; display: flex; align-items: center; justify-content: center;
            position: relative; margin-bottom: 20px;
        }
        .modal-icon {
            font-size: 4.5rem; 
            text-shadow: 0 5px 15px rgba(0,0,0,0.15);
            animation: bounceIn 0.8s;
        }
        .modal-date-badge {
            background: white; color: #333; font-weight: 800; padding: 5px 15px;
            border-radius: 20px; position: absolute; bottom: -15px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.1); font-size: 0.9rem;
        }

        /* LIST ITEMS */
        .holiday-item {
            background: white; border-radius: 15px; padding: 15px; margin-bottom: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.02); border-left: 5px solid #ccc;
            display: flex; align-items: center; cursor: pointer; transition: transform 0.1s;
        }
        .holiday-item:active { transform: scale(0.98); background: #f8f9fa; }
        
        /* Dynamic Borders for List */
        .type-national { border-left-color: #dc3545; } .type-term { border-left-color: #0d6efd; } 
        .type-cuti_peristiwa { border-left-color: #ffc107; } .type-cuti_ganti { border-left-color: #198754; } 
        .type-activity { border-left-color: #0dcaf0; } .type-school_event { border-left-color: #c33764; }
        
        .date-box { background: #f8f9fa; border-radius: 10px; padding: 8px 12px; text-align: center; min-width: 65px; margin-right: 15px; }
        .date-box .day { font-size: 1.2rem; font-weight: 800; line-height: 1; }
        .date-box .month { font-size: 0.7rem; text-transform: uppercase; font-weight: 700; color: #6c757d; }

        /* CONTROLS */
        .nav-btn { background: rgba(255,255,255,0.2); border: none; color: white; border-radius: 50%; width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; text-decoration: none; transition: 0.2s; }
        .nav-btn:active { transform: scale(0.9); background: rgba(255,255,255,0.4); }
        .form-select-transparent { background-color: rgba(255,255,255,0.2); border: 1px solid rgba(255,255,255,0.3); color: white; font-weight: bold; text-align: center; }
        .form-select-transparent option { color: black; }
    </style>
</head>
<body>

    <div class="header-card" id="topAnchor">
        <?php if($s_logo): ?><img src="<?= $s_logo ?>" class="school-logo"><?php endif; ?>
        <h3 class="fw-bold mb-0"><?= htmlspecialchars($s_name) ?></h3>
        <div class="opacity-75 small mb-4">Academic Calendar</div>

        <form method="GET" class="d-flex justify-content-center align-items-center gap-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?>" class="nav-btn"><i class="bi bi-chevron-left"></i></a>
            
            <select name="month" class="form-select form-select-sm form-select-transparent rounded-pill" 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 form-select-transparent rounded-pill" style="width:auto;" onchange="this.form.submit()">
                <?php for($y=date('Y')-1; $y<=date('Y')+2; $y++): ?><option value="<?= $y ?>" <?= $y==$year?'selected':'' ?>><?= $y ?></option><?php endfor; ?>
            </select>
            
            <a href="?month=<?=$next_m?>&year=<?=$next_y?>" class="nav-btn"><i class="bi bi-chevron-right"></i></a>
        </form>
    </div>

    <div class="container px-3">
        
        <div class="cal-card">
            <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'>$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);
                    $event = $calendar_events[$date_str] ?? null;
                    
                    $bg = $event ? "bg-" . $event['type'] . " has-event" : "";
                    $hl = ($date_str == $highlight) ? "highlight-date" : "";
                    $onclick = $event ? "onclick=\"openEventModal('$date_str')\"" : "";
                    
                    echo "<div class='cal-day $bg $hl' $onclick><span>$d</span></div>";
                }
                ?>
            </div>
        </div>

        <h6 class="fw-bold text-secondary mb-3 px-2">Upcoming Events</h6>
        <?php if(empty($list)): ?>
            <div class="text-center py-5 text-muted"><i class="bi bi-calendar-x display-1 opacity-25"></i><p class="mt-2 small">No events found.</p></div>
        <?php else: ?>
            <?php foreach($list as $h): 
                $start = strtotime($h['start_date']); $end = strtotime($h['end_date']);
                $is_range = ($h['start_date'] != $h['end_date']);
                
                // Dynamic Badge & Label
                $is_activity = ($h['type'] === 'activity');
                $badge_cls = match($h['type']) { 
                    'national'=>'bg-danger', 'term'=>'bg-primary', 'cuti_peristiwa'=>'bg-warning text-dark', 
                    'cuti_ganti'=>'bg-success', 'activity'=>'bg-info text-white', 'school_event'=>'bg-school_event', default=>'bg-secondary' 
                };
                $type_label = ucwords(str_replace('_', ' ', $h['type']));
                
                $tgt_mo = date('n', $start); $tgt_yr = date('Y', $start);
                $link = "?month=$tgt_mo&year=$tgt_yr&highlight={$h['start_date']}#topAnchor";
            ?>
                <div class="holiday-item type-<?= $h['type'] ?>" 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="flex-grow-1">
                        <div class="fw-bold text-dark"><?= htmlspecialchars($h['description']) ?></div>
                        <div class="small text-muted text-uppercase" style="font-size:0.65rem; letter-spacing:0.5px;">
                            <span class="badge <?= $badge_cls ?> me-1"><?= $type_label ?></span> 
                            <?= ($is_range) ? "Until ".date('d M', $end) : date('l') ?>
                        </div>
                    </div>
                    <i class="bi bi-chevron-right text-muted small"></i>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>

        <div class="text-center mt-4">
            <a href="index.php" class="text-decoration-none small text-muted fw-bold"><i class="bi bi-lock-fill me-1"></i> Staff Login</a>
        </div>
    </div>

    <div class="modal fade" id="eventModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-sm">
            <div class="modal-content">
                <div id="modalHeader" class="modal-header-fancy">
                    <div id="modalIcon" class="modal-icon">🎉</div>
                    <div id="modalDate" class="modal-date-badge">12 Dec 2025</div>
                </div>
                <div class="modal-body text-center px-4 pb-4 pt-3">
                    <h5 class="fw-bold mb-2" id="modalTitle">Holiday Name</h5>
                    <span class="badge bg-light text-dark border" id="modalType">TYPE</span>
                    <div class="mt-4">
                        <button type="button" class="btn btn-secondary w-100 rounded-pill fw-bold" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const events = <?= json_encode($calendar_events) ?>;
        const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

        const typeConfig = {
            'national': { color: 'bg-national', icon: '🎉', label: 'Public Holiday' },
            'term': { color: 'bg-term', icon: '🏖️', label: 'Term Break' },
            'cuti_peristiwa': { color: 'bg-cuti_peristiwa', icon: '📅', label: 'Cuti Peristiwa' },
            'cuti_ganti': { color: 'bg-cuti_ganti', icon: '🔄', label: 'Replacement Holiday' },
            'activity': { color: 'bg-activity', icon: '⚽', label: 'School Activity' },
            'school_event': { color: 'bg-school_event', icon: '🏫', label: 'School Event' },
            'special': { color: 'bg-special', icon: '✨', label: 'Special Holiday' }
        };

        const eventModal = new bootstrap.Modal(document.getElementById('eventModal'));

        function openEventModal(dateStr) {
            const event = events[dateStr];
            if (!event) return;

            const config = typeConfig[event.type] || { color: 'bg-secondary', icon: '📅', label: 'Event' };
            const dateObj = new Date(dateStr);
            const fancyDate = `${dateObj.getDate()} ${monthNames[dateObj.getMonth()]} ${dateObj.getFullYear()}`;

            const header = document.getElementById('modalHeader');
            header.className = 'modal-header-fancy ' + config.color;
            
            document.getElementById('modalIcon').innerText = config.icon;
            document.getElementById('modalDate').innerText = fancyDate;
            document.getElementById('modalTitle').innerText = event.desc;
            document.getElementById('modalType').innerText = config.label;

            eventModal.show();
        }
    </script>
</body>
</html>