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

// Pull inside all context processing logic from the script sheet directly
require 'leave_script.php'; 

// Safety fallbacks if definitions get changed inside script sheets
if (!isset($requests) || !is_array($requests)) { $requests = []; }
if (!isset($globalEmployees) || !is_array($globalEmployees)) { $globalEmployees = []; }
if (!isset($leaveTypes) || !is_array($leaveTypes)) { $leaveTypes = []; }

// --- AJAX INTERCEPTOR LAYER ---
if (isset($_GET['ajax']) || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')) {
    header('Content-Type: application/json');
    
    ob_start();
    ?>
    <table class="w-full min-w-[1050px] border-collapse table-fixed">
        <thead>
            <tr class="bg-stone-50 text-slate-500 uppercase text-[9px] font-black tracking-wider border-b border-slate-300/80">
                <th class="w-[280px] text-left p-3 bg-stone-50 sticky left-0 z-20 border-r border-slate-200 shadow-[2px_0_5px_rgba(0,0,0,0.02)]">
                    Employee Schedule
                </th>
                <?php foreach ($timelineDates as $dateData): ?>
                <th class="p-3 text-center border-r border-slate-200 last:border-r-0 min-w-[120px] <?= $dateData['is_today'] ? 'bg-indigo-50/40' : '' ?>">
                    <div class="flex flex-col items-center justify-center">
                        <span class="text-xs font-black text-slate-950 font-mono"><?= $dateData['day_num'] ?></span>
                        <span class="text-[9px] font-black text-slate-400 uppercase tracking-wider mt-0.5"><?= $dateData['day_name'] ?></span>
                    </div>
                </th>
                <?php endforeach; ?>
            </tr>
        </thead>
        <tbody class="divide-y divide-slate-200/80 text-xs font-bold">
            <?php if (empty($groupedRequests)): ?>
            <tr>
                <td colspan="<?= count($timelineDates) + 1 ?>" class="text-center py-12 bg-white">
                    <div class="flex flex-col items-center justify-center space-y-2">
                        <div class="text-3xl">📭</div>
                        <h4 class="text-xs font-extrabold text-slate-800">No Tracking Matrix Found</h4>
                        <p class="text-[10px] text-slate-600 max-w-xs">There are no active leave schedules matching this configuration path.</p>
                    </div>
                </td>
            </tr>
            <?php endif; ?>

            <?php 
            $datesArray = array_values($timelineDates);
            $totalDates = count($datesArray);

            foreach ($groupedRequests as $employeeName => $empLeaves): 
            ?>
            <tr class="hover:bg-stone-50/50 transition text-slate-800">
                <td class="p-3 bg-white sticky left-0 z-10 border-r border-slate-200 shadow-[4px_0_10px_-3px_rgba(0,0,0,0.04)]">
                    <div class="flex items-center gap-3">
                        <div class="w-8 h-8 rounded-lg bg-stone-100 border border-slate-300 text-slate-700 flex items-center justify-center font-black text-xs select-none uppercase">
                            <?= substr($employeeName, 0, 2) ?>
                        </div>
                        <div class="space-y-0.5 truncate w-full">
                            <p class="font-extrabold text-slate-900 leading-tight truncate"><?= htmlspecialchars($employeeName) ?></p>
                            <p class="text-[9px] text-slate-500 uppercase tracking-wider font-black">Workflow Tracking Matrix</p>
                        </div>
                    </div>
                </td>

                <?php 
                for ($i = 0; $i < $totalDates; $i++):
                    $dateData = $datesArray[$i];
                    $activeCellDate = $dateData['date_string'];
                    $foundLeave = null;

                    foreach ($empLeaves as $leave) {
                        if ($activeCellDate >= $leave['start_date'] && $activeCellDate <= $leave['end_date']) {
                            $foundLeave = $leave;
                            break;
                        }
                    }

                    if ($foundLeave): 
                        $colspan = 0;
                        for ($j = $i; $j < $totalDates; $j++) {
                            $checkDate = $datesArray[$j]['date_string'];
                            if ($checkDate >= $foundLeave['start_date'] && $checkDate <= $foundLeave['end_date']) {
                                $colspan++;
                            } else {
                                break;
                            }
                        }

                        $ltNameLower = strtolower(trim($foundLeave['leave_type'] ?? ''));
                        $styleConfig = $colorMap[$ltNameLower] ?? $defaultColor;
                        $isApprovedGlobally = (strtolower($foundLeave['hr_status'] ?? '') === 'approved');
                ?>
                    <td colspan="<?= $colspan ?>" class="p-2 border-r border-slate-200 last:border-r-0 relative <?= $dateData['is_today'] ? 'bg-indigo-50/10' : '' ?>">
                        <div class="w-full border p-2 rounded-xl shadow-xs text-left transition hover:scale-[1.01] <?= $styleConfig['bg'] ?> <?= !$isApprovedGlobally ? 'opacity-75 border-dashed bg-stone-50/60 text-slate-600' : '' ?>" title="Reason: <?= htmlspecialchars($foundLeave['reason'] ?? '') ?>">
                            <div class="text-[9px] font-black truncate tracking-tight uppercase leading-none mb-1.5">
                                <?= htmlspecialchars($foundLeave['leave_type'] ?? 'Leave Block') ?>
                            </div>
                            
                            <div class="space-y-1 text-[9px] font-mono font-bold">
                                <?php foreach ($activeWorkflowStages as $colKey => $stageLabel): 
                                    $stageStatus = trim($foundLeave[$colKey] ?? 'Pending');
                                    $badgeColor = 'text-amber-700';
                                    if ($stageStatus === 'Approved') $badgeColor = 'text-emerald-700';
                                    if ($stageStatus === 'Rejected') $badgeColor = 'text-rose-700';
                                ?>
                                <div class="flex items-center justify-between border-t border-slate-300/40 pt-1 leading-none">
                                    <span class="text-slate-500 font-sans font-extrabold"><?= htmlspecialchars($stageLabel) ?>:</span>
                                    <span class="<?= $badgeColor ?>"><?= $stageStatus ?></span>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </td>
                <?php 
                        $i += ($colspan - 1);
                    else: 
                ?>
                    <td class="p-2 border-r border-slate-200 last:border-r-0 relative <?= $dateData['is_today'] ? 'bg-indigo-50/10' : '' ?>">
                    </td>
                <?php 
                    endif;
                endfor; 
                ?>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php
    $tableHtml = ob_get_clean();

    echo json_encode([
        'success' => true,
        'monthLabel' => $monthLabel,
        'prevQuery' => $prevQuery,
        'nextQuery' => $nextQuery,
        'tableHtml' => $tableHtml
    ]);
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Leave Track Horizon - Timeline Panel</title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Mulish:ital,wght=0,200..1000;1,200..1000&display=swap" rel="stylesheet">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Mulish', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <link rel="stylesheet" href="../components/sidebar.css">
    <style>
        .custom-scrollbar::-webkit-scrollbar { width: 4px; height: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 20px; }
    </style>
</head>
<body class="bg-stone-100/60 min-h-screen text-slate-800 antialiased selection:bg-indigo-600 selection:text-white font-sans">

    <div class="flex">
        
        <?php include '../components/sidebar.php'; ?>

        <div id="sidebar-overlay" class="fixed inset-0 bg-slate-900/40 hidden z-40 transition-opacity duration-300" onclick="toggleSidebar()"></div>

        <div id="main-content" class="flex-1 min-w-0 md:pl-60 transition-all duration-300 min-h-screen flex flex-col">
            
            <header class="sticky top-0 bg-white/90 backdrop-blur-md border-b border-slate-300/80 h-14 flex items-center justify-between px-4 sm:px-6 z-30 shadow-xs">
                <div class="flex items-center gap-3">
                    <button onclick="toggleSidebar()" class="p-1.5 rounded-lg text-slate-600 hover:bg-slate-200/80 transition active:scale-95" aria-label="Toggle Side Area Menu">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16"></path>
                        </svg>
                    </button>
                    <div>
                        <h1 class="text-sm font-black tracking-tight text-slate-950">Leave Track Horizon</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Timeline Panel</p>
                    </div>
                </div>
                
                <div class="flex items-center gap-4">
                    <div class="hidden sm:flex flex-col text-right">
                        <span class="text-[11px] font-extrabold text-slate-950 Arial leading-tight"><?= htmlspecialchars($username); ?></span>
                        <span class="text-[9px] text-indigo-700 uppercase font-black tracking-wider leading-none mt-0.5"><?= htmlspecialchars($role ?: 'Staff'); ?></span>
                    </div>
                    <div class="w-7 h-7 bg-slate-200 border border-slate-300 rounded-lg flex items-center justify-center font-black text-xs text-slate-700 select-none uppercase">
                        <?= strtoupper(substr($username, 0, 1)); ?>
                    </div>
                </div>
            </header>

            <main class="flex-1 p-4 sm:p-6 max-w-7xl w-full mx-auto space-y-6">

                <?php if (!empty($_GET['success'])): ?>
                <div class="bg-emerald-50 border border-emerald-300 text-emerald-900 p-4 rounded-xl shadow-xs flex items-start gap-3 transition">
                    <div class="text-base leading-none mt-0.5">✅</div>
                    <div class="space-y-0.5">
                        <h3 class="font-black text-xs text-emerald-950">Record Committed</h3>
                        <p class="text-[11px] text-emerald-700 font-semibold leading-tight"><?= htmlspecialchars($_GET['success']) ?></p>
                    </div>
                </div>
                <?php endif; ?>

                <?php if (!empty($_GET['err'])): ?>
                <div class="bg-rose-50 border border-rose-300 text-rose-900 p-4 rounded-xl shadow-xs flex items-start gap-3 transition">
                    <div class="text-base leading-none mt-0.5">❌</div>
                    <div class="space-y-0.5">
                        <h3 class="font-black text-xs text-rose-950">Execution Halted</h3>
                        <p class="text-[11px] text-rose-700 font-semibold leading-tight"><?= htmlspecialchars($_GET['err']) ?></p>
                    </div>
                </div>
                <?php endif; ?>

                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div>
                        <h2 class="text-sm font-black tracking-tight text-slate-950 uppercase">Leave Applications</h2>
                        <p class="text-[10px] text-slate-600 font-semibold">Track and orchestrate strategic organization resource exceptions.</p>
                    </div>
                    <div class="flex items-center gap-2">
                        <a href="leave_approval_config.php" class="bg-white border border-slate-300 hover:border-slate-400 text-slate-800 font-bold py-2 px-3 rounded-lg text-xs shadow-xs transition active:scale-[0.98]">
                            Configure Matrix Workflow
                        </a>
                        <button onclick="toggleLeaveModal(true)" class="bg-slate-900 hover:bg-slate-800 active:scale-[0.98] transition text-white rounded-lg font-bold py-2 px-3 text-xs shadow-xs border border-slate-950 flex items-center gap-1.5">
                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"/></svg>
                            Add Leave Application
                        </button>
                    </div>
                </div>

                <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm flex flex-col sm:flex-row items-center justify-between gap-4">
                    <div class="flex items-center gap-2">
                        <button id="nav-prev-btn" data-query="<?= htmlspecialchars($prevQuery) ?>" onclick="navigateTimeline(this)" class="border border-slate-300 bg-stone-50 text-slate-700 hover:bg-slate-100 w-7 h-7 rounded-lg flex items-center justify-center transition text-xs font-black">‹</button>
                        <span id="timeline-month-label" class="text-xs font-black text-slate-950 tracking-tight min-w-[110px] text-center uppercase"><?= $monthLabel ?></span>
                        <button id="nav-next-btn" data-query="<?= htmlspecialchars($nextQuery) ?>" onclick="navigateTimeline(this)" class="border border-slate-300 bg-stone-50 text-slate-700 hover:bg-slate-100 w-7 h-7 rounded-lg flex items-center justify-center transition text-xs font-black">›</button>
                    </div>

                    <div class="flex items-center gap-2 w-full sm:w-auto justify-end">
                        <span class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Employee</span>
                        <select class="border border-slate-300 bg-stone-50 rounded-lg px-3 py-1.5 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-bold min-w-[180px]">
                            <option>All Employees</option>
                        </select>
                    </div>
                </div>

                <div class="bg-white border border-slate-300/80 rounded-xl shadow-sm overflow-hidden">
                    <div id="timeline-table-container" class="overflow-x-auto custom-scrollbar w-full">
                        <table class="w-full min-w-[1050px] border-collapse table-fixed">
                            <thead>
                                <tr class="bg-stone-50 text-slate-500 uppercase text-[9px] font-black tracking-wider border-b border-slate-300/80">
                                    <th class="w-[280px] text-left p-3 bg-stone-50 sticky left-0 z-20 border-r border-slate-200 shadow-[2px_0_5px_rgba(0,0,0,0.02)]">
                                        Employee Schedule
                                    </th>
                                    <?php foreach ($timelineDates as $dateData): ?>
                                    <th class="p-3 text-center border-r border-slate-200 last:border-r-0 min-w-[120px] <?= $dateData['is_today'] ? 'bg-indigo-50/40' : '' ?>">
                                        <div class="flex flex-col items-center justify-center">
                                            <span class="text-xs font-black text-slate-950 font-mono"><?= $dateData['day_num'] ?></span>
                                            <span class="text-[9px] font-black text-slate-400 uppercase tracking-wider mt-0.5"><?= $dateData['day_name'] ?></span>
                                        </div>
                                    </th>
                                    <?php endforeach; ?>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-200/80 text-xs font-bold">
                                <?php if (empty($groupedRequests)): ?>
                                <tr>
                                    <td colspan="<?= count($timelineDates) + 1 ?>" class="text-center py-12 bg-white">
                                        <div class="flex flex-col items-center justify-center space-y-2">
                                            <div class="text-3xl">📭</div>
                                            <h4 class="text-xs font-extrabold text-slate-800">No Tracking Matrix Found</h4>
                                            <p class="text-[10px] text-slate-600 max-w-xs">There are no active leave schedules matching this configuration path.</p>
                                        </div>
                                    </td>
                                </tr>
                                <?php endif; ?>

                                <?php 
                                $datesArray = array_values($timelineDates);
                                $totalDates = count($datesArray);

                                foreach ($groupedRequests as $employeeName => $empLeaves): 
                                ?>
                                <tr class="hover:bg-stone-50/50 transition text-slate-800">
                                    <td class="p-3 bg-white sticky left-0 z-10 border-r border-slate-200 shadow-[4px_0_10px_-3px_rgba(0,0,0,0.04)]">
                                        <div class="flex items-center gap-3">
                                            <div class="w-8 h-8 rounded-lg bg-stone-100 border border-slate-300 text-slate-700 flex items-center justify-center font-black text-xs select-none uppercase">
                                                <?= substr($employeeName, 0, 2) ?>
                                            </div>
                                            <div class="space-y-0.5 truncate w-full">
                                                <p class="font-extrabold text-slate-900 leading-tight truncate"><?= htmlspecialchars($employeeName) ?></p>
                                                <p class="text-[9px] text-slate-500 uppercase tracking-wider font-black">Workflow Tracking Matrix</p>
                                            </div>
                                        </div>
                                    </td>

                                    <?php 
                                    for ($i = 0; $i < $totalDates; $i++):
                                        $dateData = $datesArray[$i];
                                        $activeCellDate = $dateData['date_string'];
                                        $foundLeave = null;

                                        foreach ($empLeaves as $leave) {
                                            if ($activeCellDate >= $leave['start_date'] && $activeCellDate <= $leave['end_date']) {
                                                $foundLeave = $leave;
                                                break;
                                            }
                                        }

                                        if ($foundLeave): 
                                            $colspan = 0;
                                            for ($j = $i; $j < $totalDates; $j++) {
                                                $checkDate = $datesArray[$j]['date_string'];
                                                if ($checkDate >= $foundLeave['start_date'] && $checkDate <= $foundLeave['end_date']) {
                                                    $colspan++;
                                                } else {
                                                    break;
                                                }
                                            }

                                            $ltNameLower = strtolower(trim($foundLeave['leave_type'] ?? ''));
                                            $styleConfig = $colorMap[$ltNameLower] ?? $defaultColor;
                                            $isApprovedGlobally = (strtolower($foundLeave['hr_status'] ?? '') === 'approved');
                                    ?>
                                        <td colspan="<?= $colspan ?>" class="p-2 border-r border-slate-200 last:border-r-0 relative <?= $dateData['is_today'] ? 'bg-indigo-50/10' : '' ?>">
                                            <div class="w-full border p-2 rounded-xl shadow-xs text-left transition hover:scale-[1.01] <?= $styleConfig['bg'] ?> <?= !$isApprovedGlobally ? 'opacity-75 border-dashed bg-stone-50/60 text-slate-600' : '' ?>" title="Reason: <?= htmlspecialchars($foundLeave['reason'] ?? '') ?>">
                                                <div class="text-[9px] font-black truncate tracking-tight uppercase leading-none mb-1.5">
                                                    <?= htmlspecialchars($foundLeave['leave_type'] ?? 'Leave Block') ?>
                                                </div>
                                                
                                                <div class="space-y-1 text-[9px] font-mono font-bold">
                                                    <?php foreach ($activeWorkflowStages as $colKey => $stageLabel): 
                                                        $stageStatus = trim($foundLeave[$colKey] ?? 'Pending');
                                                        $badgeColor = 'text-amber-700';
                                                        if ($stageStatus === 'Approved') $badgeColor = 'text-emerald-700';
                                                        if ($stageStatus === 'Rejected') $badgeColor = 'text-rose-700';
                                                    ?>
                                                    <div class="flex items-center justify-between border-t border-slate-300/40 pt-1 leading-none">
                                                        <span class="text-slate-500 font-sans font-extrabold"><?= htmlspecialchars($stageLabel) ?>:</span>
                                                        <span class="<?= $badgeColor ?>"><?= $stageStatus ?></span>
                                                    </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            </div>
                                        </td>
                                    <?php 
                                            $i += ($colspan - 1);
                                        else: 
                                    ?>
                                        <td class="p-2 border-r border-slate-200 last:border-r-0 relative <?= $dateData['is_today'] ? 'bg-indigo-50/10' : '' ?>">
                                        </td>
                                    <?php 
                                        endif;
                                    endfor; 
                                    ?>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm">
                    <div class="flex flex-wrap items-center gap-x-5 gap-y-3 text-[10px] font-black text-slate-500 uppercase tracking-wider">
                        <span class="text-slate-400 font-black">Legend:</span>
                        <div class="flex items-center gap-1.5 normal-case tracking-normal font-bold text-slate-700"><span class="w-2.5 h-2.5 rounded-md border border-slate-300 bg-indigo-50/60 ring-2 ring-indigo-100"></span> Today</div>
                        <div class="flex items-center gap-1.5 normal-case tracking-normal font-bold text-slate-700"><span class="w-2.5 h-2.5 border-2 border-dashed border-slate-300 rounded-md bg-stone-50"></span> Pending Clearances</div>
                        
                        <?php 
                        if (!empty($leaveTypes)):
                            foreach($leaveTypes as $type): 
                                $typeName = $type['name'] ?? 'Custom';
                                $typeKey = strtolower(trim($typeName));
                                $styles = $colorMap[$typeKey] ?? $defaultColor;
                        ?>
                        <div class="flex items-center gap-1.5 normal-case tracking-normal font-bold text-slate-700">
                            <span class="w-2.5 h-2.5 rounded-md <?= $styles['dot'] ?>"></span> 
                            <?= htmlspecialchars($typeName) ?>
                        </div>
                        <?php 
                            endforeach;
                        else:
                            foreach(['Annual', 'Sick', 'Emergency', 'Maternity', 'Paternity'] as $fallbackName):
                                $styles = $colorMap[strtolower($fallbackName)] ?? $defaultColor;
                        ?>
                        <div class="flex items-center gap-1.5 normal-case tracking-normal font-bold text-slate-700">
                            <span class="w-2.5 h-2.5 rounded-md <?= $styles['dot'] ?>"></span> 
                            <?= $fallbackName ?>
                        </div>
                        <?php 
                            endforeach;
                        endif; 
                        ?>
                    </div>
                </div>

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

            </main>

            <footer class="mt-auto border-t border-slate-300 bg-white px-6 py-4 text-center">
                <p class="text-[9px] text-slate-500 font-mono tracking-wider">&copy; 2026 Core HR Engine System Platform • Dynamic Secure Architecture Protocol.</p>
            </footer>
        </div>
    </div>

    <!-- Leave Request Modal Box Layout -->
    <div id="leave-request-modal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/40 backdrop-blur-md hidden opacity-0 transition-all duration-300">
        <div id="leave-modal-container" class="bg-white rounded-xl shadow-xl border border-slate-300 max-w-md w-full overflow-hidden transform scale-95 transition-all duration-300">
            <div class="px-4 py-3 border-b border-slate-200/80 bg-stone-50 flex justify-between items-center">
                <div>
                    <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">Provision Leave Exception</h3>
                </div>
                <button onclick="toggleLeaveModal(false)" class="p-1 rounded-lg text-slate-500 hover:bg-slate-200/80 transition font-bold text-xs active:scale-95">✕</button>
            </div>
            <form action="leave_script.php" method="POST" class="p-4 space-y-4">
                <input type="hidden" name="action" value="submit_leave">
                
                <?php if (isset($_SESSION['role']) && in_array(strtolower($_SESSION['role']), ['hr', 'admin', 'superadmin'])): ?>
                <div class="flex flex-col space-y-1">
                    <label class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Apply On Behalf Of</label>
                    <select name="override_employee_id" required class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-bold">
                        <option value="">Select Employee...</option>
                        <?php foreach ($globalEmployees as $emp): ?>
                            <option value="<?= $emp['id'] ?>"><?= htmlspecialchars($emp['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>

                <div class="flex flex-col space-y-1">
                    <label class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Leave Classification Schema</label>
                    <select name="leave_type_id" required class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-bold">
                        <option value="">Select category...</option>
                        <?php foreach ($leaveTypes as $id => $type): ?>
                            <option value="<?= $id ?>"><?= htmlspecialchars($type['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="grid grid-cols-2 gap-3">
                    <div class="flex flex-col space-y-1">
                        <label class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Start Date</label>
                        <input type="date" name="start_date" required class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-mono font-bold">
                    </div>
                    <div class="flex flex-col space-y-1">
                        <label class="text-[10px] font-black text-slate-500 uppercase tracking-wider">End Date</label>
                        <input type="date" name="end_date" required class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-mono font-bold">
                    </div>
                </div>

                <div class="flex flex-col space-y-1">
                    <label class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Reason / Description</label>
                    <textarea name="reason" required rows="3" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-bold placeholder-slate-500" placeholder="Provide context for this leave exception..."></textarea>
                </div>

                <div class="flex justify-end gap-2 pt-2">
                    <button type="button" onclick="toggleLeaveModal(false)" class="bg-white border border-slate-300 hover:border-slate-400 text-slate-800 font-bold py-2 px-4 rounded-lg text-xs shadow-xs transition active:scale-[0.98]">Cancel</button>
                    <button type="submit" class="bg-slate-900 hover:bg-slate-800 active:scale-[0.98] transition text-white rounded-lg font-bold py-2 px-4 text-xs shadow-xs border border-slate-950">Commit Record</button>
                </div>
            </form>
        </div>
    </div>

    <script src="../components/sidebar.js"></script>
    <script>
    function toggleLeaveModal(show) {
        const modal = document.getElementById('leave-request-modal');
        const container = document.getElementById('leave-modal-container');
        if (show) {
            modal.classList.remove('hidden');
            setTimeout(() => {
                modal.classList.remove('opacity-0');
                container.classList.remove('scale-95');
            }, 20);
        } else {
            modal.classList.add('opacity-0');
            container.classList.add('scale-95');
            setTimeout(() => {
                modal.classList.add('hidden');
            }, 300);
        }
    }

    // --- WORKING AJAX TIMELINE NAVIGATION ENGINE ---
    function navigateTimeline(element) {
        const queryString = element.getAttribute('data-query');
        if (!queryString) return;

        const container = document.getElementById('timeline-table-container');
        container.classList.add('opacity-50', 'pointer-events-none');

        // Dynamically evaluate path syntax correctly
        const fetchUrl = window.location.pathname + '?' + queryString + '&ajax=1';

        fetch(fetchUrl, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => {
            if (!response.ok) throw new Error('Network dispatch exception failed.');
            return response.json();
        })
        .then(data => {
            if (data.success) {
                document.getElementById('timeline-month-label').textContent = data.monthLabel;
                container.innerHTML = data.tableHtml;
                
                document.getElementById('nav-prev-btn').setAttribute('data-query', data.prevQuery);
                document.getElementById('nav-next-btn').setAttribute('data-query', data.nextQuery);
                
                window.history.pushState({ path: '?' + queryString }, '', '?' + queryString);
            }
        })
        .catch(error => console.error('Timeline dispatch synchronization failed:', error))
        .finally(() => {
            container.classList.remove('opacity-50', 'pointer-events-none');
        });
    }

    window.addEventListener('popstate', function() {
        const urlParams = window.location.search.substring(1);
        if (urlParams) {
            const dummyEl = document.createElement('div');
            dummyEl.setAttribute('data-query', urlParams);
            navigateTimeline(dummyEl);
        }
    });
    </script>
</body>
</html>