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

if (session_status() === PHP_SESSION_NONE && !headers_sent()) {
    session_start();
    session_write_close();
}

require '../config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

$userId = intval($_SESSION['user_id']);
$userRole = strtolower($_SESSION['role'] ?? 'staff');

$stmt = $conn->prepare("SELECT id, name, department_id FROM employees WHERE user_id = ? LIMIT 1");
$stmt->bind_param("i", $userId);
$stmt->execute();
$employee = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$employee) {
    die("Core Exception: Employee baseline record linkage context missing.");
}
$employeeId = $employee['id'];
$employeeRealName = $employee['name'];
$departmentId = !empty($employee['department_id']) ? intval($employee['department_id']) : null;

// Fetch department staff if manager (including self for quick selection)
$departmentStaff = [];
if ($userRole === 'manager' && !is_null($departmentId)) {
    $staffStmt = $conn->prepare("SELECT id, name FROM employees WHERE department_id = ? ORDER BY name ASC");
    $staffStmt->bind_param("i", $departmentId);
    $staffStmt->execute();
    $staffRes = $staffStmt->get_result();
    while ($sRow = $staffRes->fetch_assoc()) {
        $departmentStaff[] = $sRow;
    }
    $staffStmt->close();
}

$leaveTypes = [];
$ltRes = $conn->query("SELECT id, name, days_allowed FROM leave_types ORDER BY name ASC");
while ($ltRes && $ltRow = $ltRes->fetch_assoc()) { 
    $leaveTypes[] = $ltRow; 
}

$rows = [];
if ($userRole === 'manager' && !is_null($departmentId)) {
    $stmt = $conn->prepare("
        SELECT lr.*, lt.name AS leave_type, emp.name AS employee_name, emp.user_id as applicant_user_id
        FROM leave_requests lr
        LEFT JOIN leave_types lt ON lt.id = lr.leave_type_id
        LEFT JOIN employees emp ON emp.id = lr.employee_id
        WHERE lr.employee_id = ? OR emp.department_id = ?
        ORDER BY CASE WHEN lr.manager_status = 'Pending' THEN 0 ELSE 1 END, lr.created_at DESC
    ");
    $stmt->bind_param("ii", $employeeId, $departmentId);
} else {
    $stmt = $conn->prepare("
        SELECT lr.*, lt.name AS leave_type, emp.name AS employee_name, emp.user_id as applicant_user_id 
        FROM leave_requests lr
        LEFT JOIN leave_types lt ON lt.id = lr.leave_type_id
        LEFT JOIN employees emp ON emp.id = lr.employee_id
        WHERE lr.employee_id = ?
        ORDER BY lr.created_at DESC
    ");
    $stmt->bind_param("i", $employeeId);
}

$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) { 
    $rows[] = $row; 
}
$stmt->close();

$currentYear = intval(date('Y'));
$personalBalances = [];
$balanceStmt = $conn->prepare("
        SELECT 
            lt.name AS leave_type,
            COALESCE(lb.allocated_days, 0.00) AS allocated_days,
            COALESCE(lb.carry_forward, 0.00) AS carry_forward,
            COALESCE(lb.used_days, 0.00) AS used_days,
            (COALESCE(lb.allocated_days, 0.00) + COALESCE(lb.carry_forward, 0.00) - COALESCE(lb.used_days, 0.00)) AS remaining_days
        FROM leave_types lt
        LEFT JOIN leave_balances lb ON lb.leave_type_id = lt.id 
            AND lb.employee_id = ? 
            AND lb.year = ?
        ORDER BY lt.name ASC
    ");
$balanceStmt->bind_param("ii", $employeeId, $currentYear);
$balanceStmt->execute();
$balanceRes = $balanceStmt->get_result();
while ($bRow = $balanceRes->fetch_assoc()) {
    $personalBalances[] = $bRow;
}
$balanceStmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Leave Management - HR System</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">
</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 Workspace</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Allocation & Schedules</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 leading-tight"><?= htmlspecialchars($employeeRealName); ?></span>
                        <span class="text-[9px] text-indigo-700 uppercase font-black tracking-wider leading-none mt-0.5"><?= htmlspecialchars(ucfirst($userRole)); ?></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($employeeRealName, 0, 1)); ?>
                    </div>
                </div>
            </header>

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

                <div id="ajax-alert-box" class="hidden border p-4 rounded-xl shadow-xs flex items-start gap-3 transition"></div>

                <?php if (isset($_GET['msg'])): ?>
                <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">Application Logged</h3>
                        <p class="text-[11px] text-emerald-700 font-semibold leading-tight">Application filed and successfully recorded into the engine database.</p>
                    </div>
                </div>
                <?php endif; ?>

                <?php if (isset($_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">System Fault</h3>
                        <p class="text-[11px] text-rose-700 font-semibold leading-tight"><?= htmlspecialchars($_GET['err']) ?></p>
                    </div>
                </div>
                <?php endif; ?>

                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                    <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm hover:border-indigo-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-1">
                                <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Logged Requests</p>
                                <h4 class="text-2xl font-black tracking-tight text-slate-950"><?php echo count($rows); ?></h4>
                                <p class="text-[10px] text-slate-600 font-semibold">Total status items under management filter scope.</p>
                            </div>
                            <div class="w-8 h-8 rounded-lg bg-indigo-50 border border-indigo-200 flex items-center justify-center text-sm shrink-0">📊</div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm hover:border-slate-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-1">
                                <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Current Period Date</p>
                                <h4 class="text-xl font-black tracking-tight text-slate-950 mt-0.5"><?php echo date('d M Y'); ?></h4>
                                <p class="text-[10px] text-slate-600 font-semibold">Current localized active processing server date.</p>
                            </div>
                            <div class="w-8 h-8 rounded-lg bg-stone-100 border border-slate-300 flex items-center justify-center text-sm shrink-0">🕒</div>
                        </div>
                    </div>

                    <div class="bg-gradient-to-br from-slate-900 to-indigo-950 border border-slate-800 rounded-xl p-4 shadow-sm text-white sm:col-span-2 lg:col-span-1 flex flex-col justify-between">
                        <div class="flex items-center justify-between gap-4">
                            <div class="space-y-0.5">
                                <p class="text-[9px] font-black text-indigo-300 uppercase tracking-widest">Time-Off Allocation</p>
                                <h4 class="text-xs font-bold text-slate-100">File New Operational Boundary</h4>
                            </div>
                            <div class="text-lg">⚡</div>
                        </div>
                        <div class="mt-3.5">
                            <button onclick="toggleLeaveModal(true)" class="w-full bg-white/10 hover:bg-white/15 transition px-3 py-2 rounded-lg font-bold text-xs flex items-center justify-center gap-2 border border-white/10 active:scale-[0.98]">
                                Request Time Off
                            </button>
                        </div>
                    </div>
                </div>

                <div class="bg-white border border-slate-300/80 rounded-xl shadow-sm overflow-hidden">
                    <div class="px-4 py-3 bg-stone-50/50 border-b border-slate-300/80 flex items-center justify-between">
                        <div>
                            <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">Time-off Request Logs</h3>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Real-time status tracking pipeline.</p>
                        </div>
                        <span class="bg-indigo-50 text-indigo-800 border border-indigo-200 px-2.5 py-1 rounded-md font-extrabold text-[10px] font-mono shadow-xs">
                            <?= count($rows) ?> Found
                        </span>
                    </div>

                    <div class="overflow-x-auto w-full">
                        <table class="w-full min-w-[800px] border-collapse">
                            <thead>
                                <tr class="bg-stone-50 text-slate-500 uppercase text-[9px] font-black tracking-wider border-b border-slate-300/80">
                                    <th class="p-3 text-left w-[220px]">Resource Applicant</th>
                                    <th class="p-3 text-center">Classification</th>
                                    <th class="p-3 text-center">Start Framework</th>
                                    <th class="p-3 text-center">End Framework</th>
                                    <th class="p-3 text-center">Duration</th>
                                    <th class="p-3 text-center">Manager Review</th>
                                    <th class="p-3 text-center">HR Status</th>
                                    <th class="p-3 text-right pr-4">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-200/80 text-xs font-bold">
                                <?php if (empty($rows)): ?>
                                <tr>
                                    <td colspan="8" class="text-center py-12">
                                        <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 History Discovered</h4>
                                            <p class="text-[10px] text-slate-600 max-w-xs">There are currently no active or historic leave items under this profile context.</p>
                                        </div>
                                    </td>
                                </tr>
                                <?php else: ?>
                                    <?php foreach($rows as $row): 
                                        $isOwnRecord = (intval($row['applicant_user_id'] ?? 0) === $userId);
                                        $mStatus = $row['manager_status'] ?? 'Pending';
                                        $mBadge = $mStatus === 'Approved' ? 'bg-emerald-50 text-emerald-900 border-emerald-300' : ($mStatus === 'Pending' ? 'bg-amber-50 text-amber-900 border-amber-300' : 'bg-rose-50 text-rose-900 border-rose-300');
                                        
                                        $hStatus = $row['hr_status'] ?? 'Pending';
                                        $hBadge = $hStatus === 'Approved' ? 'bg-emerald-50 text-emerald-900 border-emerald-300' : ($hStatus === 'Pending' ? 'bg-amber-50 text-amber-900 border-amber-300' : 'bg-rose-50 text-rose-900 border-rose-300');
                                    ?>
                                    <tr class="hover:bg-stone-50/50 transition text-slate-800">
                                        <td class="p-3 whitespace-nowrap">
                                            <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">
                                                    <?= strtoupper(substr($row['employee_name'] ?? 'R', 0, 1)); ?>
                                                </div>
                                                <div class="space-y-0.5">
                                                    <p class="font-extrabold text-slate-900 leading-tight">
                                                        <?= htmlspecialchars($row['employee_name'] ?? 'Resource Member') ?>
                                                    </p>
                                                    <p class="text-[9px] text-slate-500 uppercase tracking-wider font-black">
                                                        <?= $isOwnRecord ? '<span class="text-indigo-700 font-black">Personal Context</span>' : 'Team Member Context' ?>
                                                    </p>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="p-3 text-center whitespace-nowrap">
                                            <span class="bg-stone-100 text-slate-700 border border-slate-300 px-2.5 py-0.5 rounded font-black text-[10px]">
                                                <?= htmlspecialchars($row['leave_type'] ?? 'General') ?>
                                            </span>
                                        </td>
                                        <td class="p-3 text-center font-mono text-[10px] text-slate-700 whitespace-nowrap">
                                            <?= date('d M Y', strtotime($row['start_date'])) ?>
                                        </td>
                                        <td class="p-3 text-center font-mono text-[10px] text-slate-700 whitespace-nowrap">
                                            <?= date('d M Y', strtotime($row['end_date'])) ?>
                                        </td>
                                        <td class="p-3 text-center whitespace-nowrap">
                                            <span class="bg-indigo-50 text-indigo-800 border border-indigo-200 px-2 py-0.5 rounded font-black text-[10px] font-mono">
                                                <?= $row['total_days'] ?> Days
                                            </span>
                                        </td>
                                        <td class="p-3 text-center whitespace-nowrap">
                                            <span class="<?= $mBadge ?> border px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center"><?= $mStatus ?></span>
                                        </td>
                                        <td class="p-3 text-center whitespace-nowrap">
                                            <span class="<?= $hBadge ?> border px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center"><?= $hStatus ?></span>
                                        </td>
                                        <td class="p-3 text-right pr-4 whitespace-nowrap">
                                            <?php if ($userRole === 'manager' && !$isOwnRecord && $mStatus === 'Pending'): ?>
                                                <div class="inline-flex items-center justify-end gap-1.5">
                                                    <button onclick="processManagerAction(<?= $row['id'] ?>, 'Approved')" class="bg-slate-900 hover:bg-slate-800 active:scale-[0.95] transition text-white rounded-lg font-bold px-2.5 py-1.5 text-[10px] border border-slate-950">Approve</button>
                                                    <button onclick="processManagerAction(<?= $row['id'] ?>, 'Rejected')" class="bg-white hover:bg-stone-50 border border-slate-300 text-slate-700 font-bold px-2.5 py-1.5 rounded-lg text-[10px] active:scale-[0.95] transition">Reject</button>
                                                </div>
                                            <?php else: ?>
                                                <span class="text-xs font-normal text-slate-400 font-mono">—</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="space-y-3">
                    <div class="flex items-center justify-between border-b border-slate-200 pb-2">
                        <h3 class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Personal Matrix Allocations</h3>
                        <span class="text-[9px] font-bold text-indigo-700 uppercase">Summary ledger maps FY <?= $currentYear ?></span>
                    </div>

                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                        <?php foreach ($personalBalances as $balance): ?>
                            <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm flex flex-col justify-between hover:border-slate-400 transition-all">
                                <div class="flex justify-between items-start gap-4">
                                    <div class="space-y-0.5">
                                        <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Classification</p>
                                        <h4 class="text-sm font-black tracking-tight text-slate-950"><?= htmlspecialchars($balance['leave_type']) ?></h4>
                                    </div>
                                    <span class="px-2 py-0.5 rounded text-[10px] font-mono font-black border <?= $balance['remaining_days'] > 0 ? 'bg-emerald-50 text-emerald-800 border-emerald-200' : 'bg-stone-100 text-slate-600 border-slate-300' ?>">
                                        <?= number_format($balance['remaining_days'], 1) ?> Left
                                    </span>
                                </div>

                                <div class="grid grid-cols-3 gap-2 text-center mt-4">
                                    <div class="bg-stone-50 p-2 border border-slate-200 rounded-lg">
                                        <div class="text-[9px] font-black text-slate-400 uppercase tracking-wider">Allocated</div>
                                        <div class="text-xs font-black text-slate-700 mt-0.5"><?= number_format($balance['allocated_days'], 1) ?></div>
                                    </div>
                                    <div class="bg-stone-50 p-2 border border-slate-200 rounded-lg">
                                        <div class="text-[9px] font-black text-slate-400 uppercase tracking-wider">Carry Fwd</div>
                                        <div class="text-xs font-black text-amber-700 mt-0.5"><?= number_format($balance['carry_forward'], 1) ?></div>
                                    </div>
                                    <div class="bg-stone-50 p-2 border border-slate-200 rounded-lg">
                                        <div class="text-[9px] font-black text-slate-400 uppercase tracking-wider">Consumed</div>
                                        <div class="text-xs font-black text-rose-700 mt-0.5"><?= number_format($balance['used_days'], 1) ?></div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

            </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>

    <!-- Application Request Modal Frame -->
    <div id="leave-request-modal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/40 backdrop-blur-xs hidden opacity-0 transition-opacity duration-200">
        <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-transform duration-200">
            <div class="px-4 py-3 bg-stone-50/50 border-b border-slate-300/80 flex justify-between items-center">
                <div>
                    <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">File Leave Request</h3>
                    <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Provide operational parameters for evaluation review</p>
                </div>
                <button onclick="toggleLeaveModal(false)" class="text-slate-400 hover:text-slate-600 font-bold text-sm p-1 transition">✕</button>
            </div>
            
            <form action="../leave_managment/leave_script.php" method="POST" class="p-4 space-y-4 text-xs font-bold">
                <input type="hidden" name="action" value="file_leave">
                
                <?php if ($userRole === 'manager' && !empty($departmentStaff)): ?>
                    <div class="flex flex-col space-y-1">
                        <label class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Apply For</label>
                        <select name="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 font-bold text-slate-800">
                            <option value="<?= $employeeId ?>">Myself (<?= htmlspecialchars($employeeRealName) ?>)</option>
                            <optgroup label="Department Team Members">
                                <?php foreach ($departmentStaff as $staff): ?>
                                    <?php if ($staff['id'] != $employeeId): ?>
                                        <option value="<?= $staff['id'] ?>"><?= htmlspecialchars($staff['name']) ?></option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </optgroup>
                        </select>
                    </div>
                <?php else: ?>
                    <input type="hidden" name="employee_id" value="<?= $employeeId ?>">
                <?php endif; ?>

                <div class="flex flex-col space-y-1">
                    <label class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Leave Classification</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 font-bold text-slate-800">
                        <option value="">Select scope target matrix...</option>
                        <?php foreach ($leaveTypes as $lt): ?>
                            <option value="<?= $lt['id'] ?>"><?= htmlspecialchars($lt['name']) ?> (Max: <?= $lt['days_allowed'] ?> Days)</option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div class="flex flex-col space-y-1">
                        <label class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Start Framework 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 font-mono font-bold text-slate-800">
                    </div>
                    <div class="flex flex-col space-y-1">
                        <label class="text-[10px] font-black text-slate-500 uppercase tracking-wider">End Framework 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 font-mono font-bold text-slate-800">
                    </div>
                </div>

                <div class="flex flex-col space-y-1">
                    <label class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Justification Reason Statement</label>
                    <textarea name="reason" rows="3" required placeholder="State clear operational context reasons detailing missing window parameters..." 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 font-bold text-slate-800 resize-none"></textarea>
                </div>

                <div class="flex justify-end gap-2 pt-2">
                    <button type="button" onclick="toggleLeaveModal(false)" class="bg-white hover:bg-stone-50 border border-slate-300 text-slate-700 px-4 py-2 rounded-lg transition">Cancel</button>
                    <button type="submit" class="bg-slate-900 hover:bg-slate-800 active:scale-[0.99] transition text-white rounded-lg px-4 py-2 shadow-sm border border-slate-950">File Record</button>
                </div>
            </form>
        </div>
    </div>

    <script src="../components/sidebar.js"></script>
    <script>
    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebar-overlay');
        if(sidebar) sidebar.classList.toggle('-translate-x-full');
        if(overlay) overlay.classList.toggle('hidden');
    }

    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');
            }, 10);
        } else {
            modal.classList.add('opacity-0');
            container.classList.add('scale-95');
            setTimeout(() => {
                modal.classList.add('hidden');
            }, 200);
        }
    }

    function processManagerAction(requestId, statusValue) {
        const alertBox = document.getElementById('ajax-alert-box');
        const formData = new FormData();
        formData.append('action', 'manager_evaluate');
        formData.append('request_id', requestId);
        formData.append('status_value', statusValue);

        fetch('../leave_managment/leave_script.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                alertBox.className = "bg-emerald-50 border border-emerald-300 text-emerald-900 p-4 rounded-xl shadow-xs flex items-start gap-3 block transition";
                alertBox.innerHTML = `<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">Action Success</h3><p class="text-[11px] text-emerald-700 font-semibold leading-tight">\${data.message}</p></div>`;
                setTimeout(() => { window.location.reload(); }, 1000);
            } else {
                alertBox.className = "bg-rose-50 border border-rose-300 text-rose-900 p-4 rounded-xl shadow-xs flex items-start gap-3 block transition";
                alertBox.innerHTML = `<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">Action Evaluation Failed</h3><p class="text-[11px] text-rose-700 font-semibold leading-tight">\${data.message}</p></div>`;
            }
        })
        .catch(error => {
            alertBox.className = "bg-rose-50 border border-rose-300 text-rose-900 p-4 rounded-xl shadow-xs flex items-start gap-3 block transition";
            alertBox.innerHTML = `<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">Transmission Failure</h3><p class="text-[11px] text-rose-700 font-semibold leading-tight">Internal transmission routing failure.</p></div>`;
        });
    }
    </script>
</body>
</html>