<?php
require_once 'auth.php';
require_once 'db.php';
require_once 'includes/push_service.php';
requireLogin($conn);

$user_email = $_SESSION['email'] ?? '';
$user_id = (int) ($_SESSION['user_id'] ?? 0);
$role = $_SESSION['role'] ?? 'user';
$user_fullname = $_SESSION['fullname'] ?? 'Pengguna';
$user_department = currentUserDepartment($conn);

$flash_msg = '';
$flash_type = '';

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'create_cuti') {
        $type = strtolower(trim((string) ($_POST['type'] ?? 'leave')));
        $type = ($type === 'time_off') ? 'time_off' : 'leave';
        $reason = trim((string) ($_POST['reason'] ?? ''));
        $date = trim((string) ($_POST['date'] ?? date('Y-m-d')));
        $start_time = trim((string) ($_POST['start_time'] ?? '09:00'));
        $end_time = trim((string) ($_POST['end_time'] ?? '11:00'));
        $notify_all = !empty($_POST['notify_all']);

        $is_leave = ($type === 'leave');
        $doc_title = $is_leave ? 'Cuti Rehat' : 'Time Off';
        $full_day_int = $is_leave ? 1 : 0;

        $start_at = $is_leave ? "$date 08:00:00" : "$date $start_time:00";
        $end_at = $is_leave ? "$date 17:00:00" : "$date $end_time:00";

        if ($reason !== '') {
            $stmt = mysqli_prepare(
                $conn,
                "INSERT INTO calendar_events
                    (user_id, event_type, title, description, location, start_at, end_at, is_full_day, priority, status, reason, created_by, updated_by)
                 VALUES (?, ?, ?, ?, '', ?, ?, ?, 'Normal', 'Approved', ?, ?, ?)"
            );

            if ($stmt) {
                mysqli_stmt_bind_param($stmt, 'isssssisii', $user_id, $type, $doc_title, $reason, $start_at, $end_at, $full_day_int, $reason, $user_id, $user_id);
                if (mysqli_stmt_execute($stmt)) {
                    $flash_msg = "$doc_title berjaya didaftarkan!";
                    $flash_type = 'success';

                    // Dispatch push notifications to department colleagues
                    if ($notify_all && $user_department !== '') {
                        $dept_stmt = mysqli_prepare($conn, "SELECT id FROM users WHERE LOWER(TRIM(department)) = LOWER(TRIM(?)) AND id <> ? AND status = 'approved'");
                        if ($dept_stmt) {
                            mysqli_stmt_bind_param($dept_stmt, 'si', $user_department, $user_id);
                            mysqli_stmt_execute($dept_stmt);
                            $dept_res = mysqli_stmt_get_result($dept_stmt);
                            if ($dept_res) {
                                $sender_name = $user_fullname;
                                $date_str = date('d/m/Y', strtotime($date));
                                $push_title = "Makluman $doc_title Bahagian";
                                $push_body = "$sender_name mendaftar $doc_title pada $date_str ($reason). Sila semak jadual pasukan.";

                                while ($r = mysqli_fetch_assoc($dept_res)) {
                                    $target_id = (int) $r['id'];
                                    if (function_exists('sendMainppPush')) {
                                        @sendMainppPush($conn, $target_id, $push_title, $push_body, ['type' => 'leave', 'applicant_id' => (string)$user_id]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } elseif ($action === 'update_cuti') {
        $event_id = (int) ($_POST['event_id'] ?? 0);
        $type = strtolower(trim((string) ($_POST['type'] ?? 'leave')));
        $type = ($type === 'time_off') ? 'time_off' : 'leave';
        $reason = trim((string) ($_POST['reason'] ?? ''));
        $date = trim((string) ($_POST['date'] ?? date('Y-m-d')));
        $start_time = trim((string) ($_POST['start_time'] ?? '09:00'));
        $end_time = trim((string) ($_POST['end_time'] ?? '11:00'));

        $is_leave = ($type === 'leave');
        $doc_title = $is_leave ? 'Cuti Rehat' : 'Time Off';
        $full_day_int = $is_leave ? 1 : 0;

        $start_at = $is_leave ? "$date 08:00:00" : "$date $start_time:00";
        $end_at = $is_leave ? "$date 17:00:00" : "$date $end_time:00";

        if ($event_id > 0 && $reason !== '') {
            $stmt = mysqli_prepare(
                $conn,
                "UPDATE calendar_events
                 SET event_type = ?, title = ?, description = ?, start_at = ?, end_at = ?, is_full_day = ?, reason = ?, updated_by = ?, updated_at = NOW()
                 WHERE id = ? AND user_id = ?"
            );

            if ($stmt) {
                mysqli_stmt_bind_param($stmt, 'sssssisiii', $type, $doc_title, $reason, $start_at, $end_at, $full_day_int, $reason, $user_id, $event_id, $user_id);
                if (mysqli_stmt_execute($stmt)) {
                    $flash_msg = "Maklumat $doc_title berjaya dikemaskini!";
                    $flash_type = 'success';
                }
            }
        }
    } elseif ($action === 'delete_cuti') {
        $event_id = (int) ($_POST['event_id'] ?? 0);
        if ($event_id > 0) {
            $stmt = mysqli_prepare($conn, "DELETE FROM calendar_events WHERE id = ? AND user_id = ? AND (event_type = 'leave' OR event_type = 'time_off' OR event_type = 'cuti')");
            if ($stmt) {
                mysqli_stmt_bind_param($stmt, 'ii', $event_id, $user_id);
                if (mysqli_stmt_execute($stmt)) {
                    $flash_msg = 'Rekod cuti/time off berjaya dipadam.';
                    $flash_type = 'success';
                }
            }
        }
    }
}

// Fetch user leaves & time off ONLY
$sql = "SELECT * FROM calendar_events WHERE user_id = ? AND (event_type = 'leave' OR event_type = 'time_off' OR event_type = 'cuti') AND deleted_at IS NULL ORDER BY start_at DESC";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'i', $user_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$leaves = $result ? mysqli_fetch_all($result, MYSQLI_ASSOC) : [];

$upcoming_records = [];
$today_records = [];
$past_records = [];

$today_date_str = date('Y-m-d');
$total_leaves_taken = 0;
$total_time_off_taken = 0;

foreach ($leaves as $l) {
    $type = strtolower($l['event_type'] ?? 'leave');
    if ($type === 'time_off' || $type === 'timeoff') {
        $total_time_off_taken++;
    } else {
        $total_leaves_taken++;
    }

    $event_start_date = date('Y-m-d', strtotime($l['start_at']));
    if ($event_start_date === $today_date_str) {
        $today_records[] = $l;
    } elseif ($event_start_date > $today_date_str) {
        $upcoming_records[] = $l;
    } else {
        $past_records[] = $l;
    }
}

$total_all = count($leaves);
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Cuti & Time Off | MAINPP WORKSPACE</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <?php if (function_exists('renderAppShellAssets')) { renderAppShellAssets(); } ?>
    <style>
        :root {
            --primary: #0077b6; --primary-dark: #005f99; --secondary: #00b4d8;
            --accent-teal: #0d9488; --deep-blue: #023e5f;
            --bg-light: rgba(245, 250, 253, 0.85); --bg-card: rgba(255, 255, 255, 0.78);
            --text-main: #163447; --text-muted: #486581; --border: rgba(255, 255, 255, 0.55);
            --sidebar-width: 280px;
            --success: #10b981; --danger: #ef4444; --warning: #f59e0b; --info: #3b82f6; --purple: #8b5cf6;
            --glass: rgba(255, 255, 255, 0.65);
            --glass-strong: rgba(255, 255, 255, 0.88);
            --shadow-soft: 0 16px 40px rgba(2, 62, 95, 0.08);
            --shadow-card: 0 10px 30px rgba(2, 62, 95, 0.06);
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
        body {
            min-height: 100vh; display: flex; color: var(--text-main);
            background: linear-gradient(135deg, rgba(240, 249, 255, 0.95), rgba(224, 242, 254, 0.85)),
                        url('assets/auth-bg.png') center/cover no-repeat fixed;
            overflow-x: hidden;
        }

        .sidebar {
            width: var(--sidebar-width) !important;
            background: linear-gradient(180deg, rgba(2, 62, 95, 0.96), rgba(0, 119, 182, 0.88)) !important;
            border-right: 1px solid rgba(255, 255, 255, 0.22) !important;
            position: fixed; height: 100vh; padding: 20px 0 !important;
            overflow-y: auto; z-index: 1000; box-shadow: 18px 0 44px rgba(2, 38, 60, 0.20);
            transition: width 0.3s ease; display: flex; flex-direction: column;
            backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
        }
        .sidebar.collapsed { width: 70px !important; }
        .sidebar-header {
            text-align: center; padding: 0 20px 20px !important;
            border-bottom: 1px solid rgba(255, 255, 255, 0.16) !important; margin-bottom: 20px !important;
            background: transparent !important;
        }
        .sidebar.collapsed .sidebar-header h3, .sidebar.collapsed .sidebar-header p, .sidebar.collapsed .menu-text { display: none !important; }
        .sidebar-header img { width: 54px !important; margin: 0 auto 10px !important; filter: drop-shadow(0 10px 18px rgba(0,0,0,0.25)); }
        .sidebar-menu { list-style: none; padding: 0 10px !important; display: flex; flex-direction: column; flex: 1; }
        .sidebar-section { padding: 10px 18px 6px !important; color: rgba(255,255,255,0.58) !important; font-size: 0.72rem !important; font-weight: 800 !important; text-transform: uppercase; letter-spacing: 0.06em; }
        .sidebar-menu li a { display: flex; align-items: center; gap: 12px; padding: 12px 18px; color: rgba(255,255,255,0.88) !important; text-decoration: none; border-radius: 10px; margin-bottom: 5px; transition: all 0.2s ease; font-size: 0.9rem; }
        .sidebar-menu li a:hover, .sidebar-menu li a.active { background: rgba(255,255,255,0.18) !important; color: #fff !important; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18); }
        .sidebar-menu li a i { width: 20px; text-align: center; font-size: 1.1rem; }
        .sidebar-toggle { position: absolute !important; right: 10px !important; top: 18px !important; width: 28px !important; height: 28px !important; background: rgba(255,255,255,0.20) !important; color: #fff !important; border: 1px solid rgba(255,255,255,0.28) !important; border-radius: 50% !important; cursor: pointer !important; display: flex !important; align-items: center !important; justify-content: center !important; font-size: 0.75rem !important; transition: transform 0.3s ease !important; z-index: 1300 !important; }
        .sidebar.collapsed .sidebar-toggle { transform: rotate(180deg) !important; }
        .sidebar.collapsed + .main { margin-left: 70px !important; }

        .main {
            position: relative; z-index: 1; margin-left: var(--sidebar-width); flex: 1; padding: 28px 32px; transition: margin-left 0.3s ease;
        }

        /* Top Bar matching dashboard */
        .top-bar {
            background: var(--glass); padding: 18px 24px; border-radius: 18px;
            box-shadow: var(--shadow-soft); margin-bottom: 18px; display: flex; justify-content: space-between; align-items: center; border: 1px solid var(--border);
            backdrop-filter: blur(22px) saturate(1.25); -webkit-backdrop-filter: blur(22px) saturate(1.25);
        }
        .top-bar h2 { color: var(--primary-dark); font-size: 1.35rem; font-weight: 850; display: flex; align-items: center; gap: 10px; }
        .top-bar h2 i { color: var(--secondary); }

        /* Master View Switcher Bar */
        .view-mode-bar {
            background: var(--glass-strong); padding: 12px 20px; border-radius: 20px;
            box-shadow: var(--shadow-soft); margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; border: 1px solid var(--border);
            backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); flex-wrap: wrap; gap: 14px;
        }
        .view-toggle-pills {
            display: flex; align-items: center; background: rgba(0, 119, 182, 0.08); padding: 4px; border-radius: 14px; gap: 4px;
        }
        .view-pill-btn {
            border: none; background: transparent; padding: 8px 18px; border-radius: 10px;
            font-size: 0.84rem; font-weight: 800; color: var(--text-muted); cursor: pointer; transition: all 0.2s ease;
            display: flex; align-items: center; gap: 8px;
        }
        .view-pill-btn.active {
            background: #fff; color: var(--deep-blue); box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }
        .btn-add-leave {
            background: linear-gradient(135deg, #7c3aed, #6d28d9);
            color: #fff; border: none; padding: 10px 22px; border-radius: 14px;
            font-weight: 800; font-size: 0.88rem; display: flex; align-items: center; gap: 8px;
            cursor: pointer; box-shadow: 0 8px 20px rgba(124, 58, 237, 0.30); transition: all 0.2s ease;
        }
        .btn-add-leave:hover { transform: translateY(-2px); box-shadow: 0 12px 25px rgba(124, 58, 237, 0.40); }

        /* KPI Cards Grid */
        .leave-kpi-grid {
            display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 16px; margin-bottom: 20px;
        }
        .leave-kpi-card {
            background: var(--glass-strong); border-radius: 20px; border: 1px solid var(--border);
            padding: 18px 20px; box-shadow: var(--shadow-card); backdrop-filter: blur(18px); -webkit-backdrop-filter: blur(18px);
            display: flex; align-items: center; gap: 16px;
        }
        .kpi-icon-box {
            width: 48px; height: 48px; border-radius: 14px; display: flex; align-items: center; justify-content: center;
            font-size: 1.3rem; flex-shrink: 0;
        }
        .kpi-total { background: #f3e8ff; color: #7c3aed; }
        .kpi-leave { background: #fef3c7; color: #d97706; }
        .kpi-timeoff { background: #e0e7ff; color: #4338ca; }
        .kpi-info h4 { font-size: 0.76rem; font-weight: 750; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; }
        .kpi-info .kpi-number { font-size: 1.5rem; font-weight: 850; color: var(--deep-blue); line-height: 1.1; margin-top: 2px; }

        /* Timeline Navigation Tabs (Akan Datang, Hari Ini, Lepas) */
        .timeline-tabs-container {
            display: flex; gap: 8px; margin-bottom: 20px; background: var(--glass-strong); padding: 6px; border-radius: 16px;
            border: 1px solid var(--border); width: fit-content;
        }
        .timeline-tab-btn {
            border: none; background: transparent; padding: 10px 22px; border-radius: 12px;
            font-size: 0.85rem; font-weight: 800; color: var(--text-muted); cursor: pointer; transition: all 0.2s ease;
            display: flex; align-items: center; gap: 8px;
        }
        .timeline-tab-btn.active {
            background: var(--deep-blue); color: #fff; box-shadow: 0 4px 14px rgba(2, 62, 95, 0.20);
        }

        /* Filter Toolbar */
        .leave-toolbar {
            background: var(--glass-strong); padding: 12px 18px; border-radius: 16px; border: 1px solid var(--border);
            margin-bottom: 22px; display: flex; justify-content: space-between; align-items: center; gap: 14px; flex-wrap: wrap;
        }
        .leave-search-box {
            display: flex; align-items: center; gap: 10px; background: #fff; padding: 8px 16px; border-radius: 12px;
            border: 1px solid rgba(0, 119, 182, 0.18); flex: 1; min-width: 240px;
        }
        .leave-search-box input { border: none; outline: none; width: 100%; font-size: 0.85rem; color: var(--text-main); font-weight: 600; }
        .category-filter-pills { display: flex; gap: 6px; align-items: center; }
        .cat-pill-btn {
            border: 1px solid rgba(124, 58, 237, 0.20); background: #fff; padding: 6px 14px; border-radius: 10px;
            font-size: 0.76rem; font-weight: 800; color: var(--text-muted); cursor: pointer; transition: all 0.2s ease;
        }
        .cat-pill-btn.active { background: #7c3aed; color: #fff; border-color: #7c3aed; }

        /* World Class Leave Cards Grid */
        .leave-grid-container {
            display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 20px;
        }
        .world-leave-card {
            background: #fff; border-radius: 20px; border: 1px solid rgba(0, 119, 182, 0.12);
            padding: 20px; box-shadow: var(--shadow-card); display: flex; flex-direction: column; gap: 12px;
            position: relative; transition: all 0.25s ease;
        }
        .world-leave-card:hover { transform: translateY(-3px); box-shadow: 0 18px 38px rgba(2, 62, 95, 0.10); }

        .leave-badge-type {
            font-size: 0.72rem; font-weight: 850; padding: 4px 12px; border-radius: 999px; text-transform: uppercase;
        }
        .type-cuti { background: #fef3c7; color: #b45309; border: 1px solid #fde68a; }
        .type-timeoff { background: #e0e7ff; color: #4338ca; border: 1px solid #c7d2fe; }

        .leave-card-title { font-size: 1.05rem; font-weight: 850; color: var(--deep-blue); }
        .leave-date-pill {
            display: inline-flex; align-items: center; gap: 8px; font-size: 0.82rem; font-weight: 750; color: #334155;
            background: #f8fafc; padding: 6px 12px; border-radius: 10px; border: 1px solid #e2e8f0; width: fit-content;
        }
        .leave-reason-text {
            font-size: 0.84rem; color: #475569; background: rgba(240, 249, 255, 0.60); padding: 12px 14px;
            border-radius: 12px; line-height: 1.45; border: 1px solid rgba(0, 119, 182, 0.08);
        }

        .leave-bottom-actions {
            margin-top: auto; padding-top: 14px; border-top: 1px solid rgba(0, 119, 182, 0.08);
            display: flex; justify-content: space-between; align-items: center; gap: 8px; flex-wrap: wrap;
        }
        .btn-edit-leave-action {
            background: rgba(124, 58, 237, 0.08); color: var(--purple); border: 1px solid rgba(124, 58, 237, 0.20);
            padding: 8px 14px; border-radius: 10px; font-size: 0.78rem; font-weight: 800; cursor: pointer; transition: all 0.2s ease;
            display: inline-flex; align-items: center; gap: 5px;
        }
        .btn-edit-leave-action:hover { background: var(--purple); color: #fff; }

        /* Calendar Styling */
        .calendar-app-card {
            background: #fff; border-radius: 24px; border: 1px solid rgba(0, 119, 182, 0.12);
            padding: 24px 28px; box-shadow: var(--shadow-soft); margin-bottom: 24px;
        }
        .cal-header-row {
            display: flex; justify-content: space-between; align-items: center; margin-bottom: 22px; flex-wrap: wrap; gap: 14px;
        }
        .cal-title-nav { display: flex; align-items: center; gap: 16px; }
        .cal-title-month { font-size: 1.45rem; font-weight: 850; color: var(--deep-blue); }
        .cal-arrows { display: flex; align-items: center; gap: 6px; }
        .cal-arrow-btn {
            width: 32px; height: 32px; border-radius: 9px; border: 1px solid rgba(0, 119, 182, 0.16); background: #fff;
            display: flex; align-items: center; justify-content: center; color: var(--deep-blue); cursor: pointer; transition: all 0.2s ease;
        }
        .cal-arrow-btn:hover { background: var(--primary); color: #fff; }
        .btn-cal-today {
            padding: 6px 14px; border-radius: 9px; font-weight: 750; font-size: 0.8rem; background: #fff; border: 1px solid rgba(0, 119, 182, 0.20); color: var(--deep-blue); cursor: pointer;
        }
        .btn-cal-today:hover { background: var(--deep-blue); color: #fff; }

        .cal-week-board {
            display: flex; flex-direction: column; border: 1px solid rgba(0, 119, 182, 0.12); border-radius: 18px; overflow: hidden; background: #fff;
        }
        .cal-week-head {
            display: grid; grid-template-columns: 75px repeat(7, 1fr);
            background: #fafcff; border-bottom: 1px solid rgba(0, 119, 182, 0.12);
        }
        .cal-head-col {
            padding: 14px 6px; text-align: center; font-size: 0.82rem; font-weight: 800; color: var(--deep-blue);
            border-left: 1px solid rgba(0, 119, 182, 0.08); display: flex; flex-direction: column; gap: 2px;
        }
        .cal-head-col.active-day { background: #f0fdf4; color: #166534; }
        .cal-head-col.active-day span::after { content: " •"; color: #10b981; }
        
        .cal-week-body { max-height: 580px; overflow-y: auto; position: relative; }
        .cal-hour-row {
            display: grid; grid-template-columns: 75px repeat(7, 1fr);
            height: 72px; min-height: 72px; border-bottom: 1px solid rgba(0, 119, 182, 0.08); position: relative;
        }
        .cal-hour-time-label {
            font-size: 0.72rem; font-weight: 700; color: var(--text-muted);
            display: flex; align-items: flex-start; justify-content: center; padding-top: 6px;
        }
        .cal-day-cell {
            border-left: 1px solid rgba(0, 119, 182, 0.08); padding: 4px; position: relative; height: 100%;
        }

        .cal-leave-card {
            border-radius: 14px; padding: 10px 12px;
            box-shadow: 0 4px 14px rgba(0,0,0,0.05); border: 1px solid rgba(0, 0, 0, 0.05);
            display: flex; flex-direction: column; gap: 4px; overflow: hidden;
            transition: all 0.2s ease; cursor: pointer;
        }
        .cal-leave-card:hover { transform: translateY(-2px); box-shadow: 0 10px 24px rgba(0,0,0,0.12); z-index: 40 !important; }
        .leave-theme-cuti { background: #fffbeb; border-top: 3px solid #d97706; }
        .leave-theme-timeoff { background: #eef2ff; border-top: 3px solid #4338ca; }

        /* Modal */
        .modal-overlay {
            position: fixed; inset: 0; background: rgba(2, 62, 95, 0.50); backdrop-filter: blur(8px);
            display: none; align-items: center; justify-content: center; z-index: 2000;
        }
        .modal-overlay.active { display: flex; }
        .modal-card {
            background: #fff; border-radius: 24px; width: 100%; max-width: 520px;
            box-shadow: 0 25px 60px rgba(0,0,0,0.25); overflow: hidden; animation: modalPop 0.25s ease;
            max-height: 90vh; display: flex; flex-direction: column;
        }
        @keyframes modalPop { from { transform: scale(0.92); opacity: 0; } to { transform: scale(1); opacity: 1; } }
        .modal-header { padding: 20px 24px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(0,119,182,0.12); }
        .modal-header h3 { font-size: 1.15rem; font-weight: 850; color: var(--deep-blue); display: flex; align-items: center; gap: 8px; }
        .modal-body { padding: 22px 24px; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; }
        .form-group { display: flex; flex-direction: column; gap: 6px; }
        .form-group label { font-size: 0.82rem; font-weight: 750; color: var(--deep-blue); }
        .form-control {
            padding: 10px 14px; border-radius: 12px; border: 1px solid rgba(0, 119, 182, 0.20);
            font-size: 0.88rem; outline: none; background: rgba(240, 249, 255, 0.40);
        }
        .form-control:focus { background: #fff; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(0, 119, 182, 0.12); }

        .type-selector-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
        .type-card-opt {
            border: 2px solid rgba(0,119,182,0.15); border-radius: 16px; padding: 14px 16px;
            cursor: pointer; display: flex; align-items: center; gap: 12px; transition: all 0.2s ease;
            background: #fff;
        }
        .type-card-opt.active {
            border-color: #7c3aed; background: rgba(124, 58, 237, 0.06); box-shadow: 0 4px 14px rgba(124, 58, 237, 0.15);
        }
        .type-icon-box {
            width: 38px; height: 38px; border-radius: 10px; display: flex; align-items: center; justify-content: center;
            font-size: 1.1rem;
        }
        .type-card-opt.active .type-icon-box { background: #7c3aed; color: #fff; }
        .type-card-opt:not(.active) .type-icon-box { background: #f1f5f9; color: #64748b; }
        .type-opt-text strong { display: block; font-size: 0.88rem; color: var(--deep-blue); }
        .type-opt-text span { font-size: 0.72rem; color: var(--text-muted); }

        .modal-footer { padding: 16px 24px 22px; display: flex; justify-content: flex-end; gap: 10px; border-top: 1px solid rgba(0,119,182,0.08); }
        .btn-save { background: linear-gradient(135deg, #7c3aed, #6d28d9); color: #fff; border: none; padding: 10px 24px; border-radius: 12px; font-weight: 800; cursor: pointer; }
    </style>
</head>
<body class="role-<?php echo htmlspecialchars($role); ?>">

    <!-- Sidebar matching Dashboard -->
    <aside class="sidebar" id="sidebar">
        <button class="sidebar-toggle" id="sidebarToggle" title="Tutup/Buka Menu">
            <i class="fas fa-chevron-left"></i>
        </button>
        <div class="sidebar-header">
            <img src="mainpp.png" alt="Logo MAINPP">
            <h3>MAINPP WORKSPACE</h3>
        </div>
        <ul class="sidebar-menu">
            <?php renderUnifiedSidebarMenu($conn, $role, 'my_cuti.php'); ?>
        </ul>
    </aside>

    <!-- Main Workspace -->
    <main class="main">

        <!-- Top Bar matching Dashboard -->
        <div class="top-bar">
            <h2><i class="fa-solid fa-umbrella-beach"></i> My Cuti & Time Off</h2>
            <?php renderTopBarUserMenu($conn, $role, 'my_cuti.php'); ?>
        </div>

        <?php
        renderBreadcrumb([
            ['label' => 'Dashboard', 'url' => 'dashboard.php'],
            ['label' => 'Modul Peribadi', 'url' => '#'],
            ['label' => 'My Cuti & Time Off', 'url' => 'my_cuti.php', 'current' => true]
        ]);
        ?>

        <!-- Master View Switcher & Add Button -->
        <div class="view-mode-bar">
            <div class="view-toggle-pills">
                <button class="view-pill-btn active" id="btnLeaveList" onclick="switchLeaveMasterView('list')">
                    <i class="fa-solid fa-list"></i>
                    <span>Senarai Rekod Permohonan (<?php echo $total_all; ?>)</span>
                </button>
                <button class="view-pill-btn" id="btnLeaveCalendar" onclick="switchLeaveMasterView('calendar')">
                    <i class="fa-solid fa-calendar-days"></i>
                    <span>Paparan Kalendar Cuti</span>
                </button>
            </div>

            <button class="btn-add-leave" onclick="openAddLeaveModal()">
                <i class="fa-solid fa-plus"></i>
                <span>+ Tambah My Cuti</span>
            </button>
        </div>

        <?php if (!empty($flash_msg)): ?>
            <div style="background: <?php echo $flash_type === 'success' ? '#ecfdf5' : '#fef2f2'; ?>; color: <?php echo $flash_type === 'success' ? '#065f46' : '#991b1b'; ?>; padding: 14px 20px; border-radius: 14px; margin-bottom: 20px; border: 1px solid <?php echo $flash_type === 'success' ? '#a7f3d0' : '#fecaca'; ?>; display: flex; align-items: center; gap: 10px; font-weight: 600;">
                <i class="fa-solid <?php echo $flash_type === 'success' ? 'fa-circle-check' : 'fa-circle-exclamation'; ?>"></i>
                <span><?php echo htmlspecialchars($flash_msg); ?></span>
            </div>
        <?php endif; ?>

        <!-- ================= VIEW 1: TIMELINE & LIST SECTION ================= -->
        <div id="leaveListSection">
            
            <!-- KPI Summary Cards -->
            <div class="leave-kpi-grid">
                <div class="leave-kpi-card">
                    <div class="kpi-icon-box kpi-total"><i class="fa-solid fa-umbrella-beach"></i></div>
                    <div class="kpi-info">
                        <h4>Jumlah Rekod</h4>
                        <div class="kpi-number"><?php echo $total_all; ?></div>
                    </div>
                </div>

                <div class="leave-kpi-card">
                    <div class="kpi-icon-box kpi-leave"><i class="fa-solid fa-calendar-check"></i></div>
                    <div class="kpi-info">
                        <h4>Cuti Rehat</h4>
                        <div class="kpi-number"><?php echo $total_leaves_taken; ?> <span style="font-size: 0.82rem; font-weight: 600; color: var(--text-muted);">Sesi</span></div>
                    </div>
                </div>

                <div class="leave-kpi-card">
                    <div class="kpi-icon-box kpi-timeoff"><i class="fa-solid fa-hourglass-half"></i></div>
                    <div class="kpi-info">
                        <h4>Time Off</h4>
                        <div class="kpi-number"><?php echo $total_time_off_taken; ?> <span style="font-size: 0.82rem; font-weight: 600; color: var(--text-muted);">Sesi</span></div>
                    </div>
                </div>
            </div>

            <!-- Timeline Segment Tabs (Akan Datang, Hari Ini, Lepas) -->
            <div class="timeline-tabs-container">
                <button class="timeline-tab-btn active" data-timeline="upcoming" onclick="selectLeaveTimeline('upcoming')">
                    <i class="fa-solid fa-calendar-plus"></i>
                    <span>Akan Datang (<?php echo count($upcoming_records); ?>)</span>
                </button>
                <button class="timeline-tab-btn" data-timeline="today" onclick="selectLeaveTimeline('today')">
                    <i class="fa-solid fa-clock"></i>
                    <span>Hari Ini (<?php echo count($today_records); ?>)</span>
                </button>
                <button class="timeline-tab-btn" data-timeline="past" onclick="selectLeaveTimeline('past')">
                    <i class="fa-solid fa-history"></i>
                    <span>Rekod Lepas (<?php echo count($past_records); ?>)</span>
                </button>
            </div>

            <!-- Search & Type Filter Toolbar -->
            <div class="leave-toolbar">
                <div class="leave-search-box">
                    <i class="fa-solid fa-magnifying-glass text-muted"></i>
                    <input type="text" id="leaveSearchInput" placeholder="Cari sebab atau tarikh permohonan..." onkeyup="filterLeavesLive()">
                </div>

                <div class="category-filter-pills">
                    <span style="font-size: 0.76rem; font-weight: 800; color: var(--deep-blue); margin-right: 4px;">Kategori:</span>
                    <button class="cat-pill-btn active" data-cat="all" onclick="filterLeaveCategory('all', this)">Semua</button>
                    <button class="cat-pill-btn" data-cat="leave" onclick="filterLeaveCategory('leave', this)"><i class="fa-solid fa-umbrella-beach mr-1"></i> Cuti Rehat</button>
                    <button class="cat-pill-btn" data-cat="time_off" onclick="filterLeaveCategory('time_off', this)"><i class="fa-solid fa-hourglass-start mr-1"></i> Time Off</button>
                </div>
            </div>

            <!-- Timeline Sections Rendering -->
            <?php
            $renderLeaveTimelineGrid = function($timeline_name, $records, $is_active) {
            ?>
                <div class="leave-timeline-grid" id="timeline_<?php echo $timeline_name; ?>" style="<?php echo $is_active ? '' : 'display: none;'; ?>">
                    <?php if (empty($records)): ?>
                        <div style="text-align: center; padding: 48px 20px; background: var(--glass-strong); border-radius: 20px; border: 1px solid var(--border);">
                            <i class="fa-solid fa-umbrella-beach" style="font-size: 3.2rem; color: var(--purple); opacity: 0.35; margin-bottom: 12px;"></i>
                            <h3 style="font-size: 1.1rem; font-weight: 800; color: var(--deep-blue);">Tiada Rekod Pada Garis Masa Ini</h3>
                            <p style="font-size: 0.85rem; color: var(--text-muted); margin-top: 4px;">Klik "+ Tambah My Cuti" untuk mendaftarkan permohonan anda.</p>
                        </div>
                    <?php else: ?>
                        <div class="leave-grid-container">
                            <?php foreach ($records as $lv): 
                                $type = strtolower($lv['event_type'] ?? 'leave');
                                $is_time_off = ($type === 'time_off' || $type === 'timeoff');
                                $type_key = $is_time_off ? 'time_off' : 'leave';
                                $reason = $lv['reason'] ?: $lv['description'] ?: 'Tiada alasan dinyatakan';
                            ?>
                                <div class="world-leave-card" data-cat="<?php echo $type_key; ?>" data-title="<?php echo htmlspecialchars(strtolower($lv['title'] . ' ' . $reason . ' ' . $lv['start_at'])); ?>">
                                    <div style="display: flex; justify-content: space-between; align-items: center;">
                                        <span class="leave-badge-type <?php echo $is_time_off ? 'type-timeoff' : 'type-cuti'; ?>">
                                            <i class="fa-solid <?php echo $is_time_off ? 'fa-hourglass-start' : 'fa-umbrella-beach'; ?> mr-1"></i>
                                            <?php echo $is_time_off ? 'Time Off' : 'Cuti Rehat'; ?>
                                        </span>
                                        <span style="font-size: 0.75rem; font-weight: 800; color: var(--success);">
                                            <i class="fa-regular fa-circle-check mr-1"></i> Disahkan
                                        </span>
                                    </div>

                                    <div class="leave-card-title"><?php echo htmlspecialchars($lv['title']); ?></div>

                                    <div class="leave-date-pill">
                                        <i class="fa-regular fa-calendar-days text-primary"></i>
                                        <span><?php echo date('d M Y (l)', strtotime($lv['start_at'])); ?></span>
                                        <?php if ($is_time_off): ?>
                                            <span style="color: #4338ca; font-weight: 850;">• <?php echo date('h:i A', strtotime($lv['start_at'])) . ' - ' . date('h:i A', strtotime($lv['end_at'])); ?></span>
                                        <?php endif; ?>
                                    </div>

                                    <div class="leave-reason-text">
                                        <strong>Sebab:</strong> <?php echo htmlspecialchars($reason); ?>
                                    </div>

                                    <div class="leave-bottom-actions">
                                        <button type="button" class="btn-edit-leave-action" onclick='openEditLeaveModal(<?php echo json_encode($lv, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP); ?>)'>
                                            <i class="fa-regular fa-pen-to-square"></i> Edit
                                        </button>

                                        <form action="my_cuti.php" method="POST" onsubmit="return confirm('Adakah anda pasti mahu memadam rekod ini?');" style="margin: 0;">
                                            <input type="hidden" name="action" value="delete_cuti">
                                            <input type="hidden" name="event_id" value="<?php echo $lv['id']; ?>">
                                            <button type="submit" style="background: none; border: none; color: #dc2626; cursor: pointer; font-size: 0.95rem;" title="Padam Rekod">
                                                <i class="fa-solid fa-trash-can"></i>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php
            };
            $renderLeaveTimelineGrid('upcoming', $upcoming_records, true);
            $renderLeaveTimelineGrid('today', $today_records, false);
            $renderLeaveTimelineGrid('past', $past_records, false);
            ?>

        </div>

        <!-- ================= VIEW 2: MODERN CALENDAR SECTION ================= -->
        <div id="leaveCalendarSection" class="calendar-app-card" style="display: none;">
            <div class="cal-header-row">
                <div class="cal-title-nav">
                    <div class="cal-title-month" id="leaveCalMonthTitle">Ogos 2026</div>
                    <div class="cal-arrows">
                        <button class="cal-arrow-btn" onclick="prevLeaveWeek()"><i class="fa-solid fa-chevron-left"></i></button>
                        <button class="cal-arrow-btn" onclick="nextLeaveWeek()"><i class="fa-solid fa-chevron-right"></i></button>
                        <button class="btn-cal-today" onclick="goToTodayLeave()">Hari Ini</button>
                    </div>
                </div>

                <div style="font-size: 0.82rem; font-weight: 750; color: var(--text-muted);">
                    <i class="fa-solid fa-shield-halved text-purple mr-1"></i> Klik mana-mana kad untuk edit detail
                </div>
            </div>

            <div class="cal-week-board">
                <div class="cal-week-head" id="leaveWeekHeaderRow">
                    <div style="padding: 14px 6px; text-align: center; font-size: 0.78rem; font-weight: 800; color: var(--text-muted);">Masa</div>
                </div>
                <div class="cal-week-body">
                    <?php for ($hour = 7; $hour <= 18; $hour++): 
                        $time_str = sprintf('%02d:00', $hour);
                        $display_time = date('g a', strtotime("$time_str"));
                    ?>
                        <div class="cal-hour-row" data-hour="<?php echo $hour; ?>">
                            <div class="cal-hour-time-label"><?php echo $display_time; ?></div>
                            <?php for ($d = 0; $d < 7; $d++): ?>
                                <div class="cal-day-cell" data-day-index="<?php echo $d; ?>" data-hour="<?php echo $hour; ?>"></div>
                            <?php endfor; ?>
                        </div>
                    <?php endfor; ?>
                </div>
            </div>
        </div>

    </main>

    <!-- Modal 1: + Tambah My Cuti -->
    <div class="modal-overlay" id="addLeaveModal">
        <div class="modal-card">
            <div class="modal-header">
                <div>
                    <h3><i class="fa-solid fa-umbrella-beach text-purple mr-2"></i> Tambah My Cuti</h3>
                    <p style="font-size: 0.78rem; color: var(--text-muted); margin-top: 2px;">Pilih jenis dan lengkapkan maklumat anda.</p>
                </div>
                <button style="background: none; border: none; font-size: 1.2rem; cursor: pointer;" onclick="closeAddLeaveModal()"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <form action="my_cuti.php" method="POST">
                <input type="hidden" name="action" value="create_cuti">
                <input type="hidden" name="type" id="leaveTypeInput" value="leave">

                <div class="modal-body">
                    <div class="type-selector-grid">
                        <div class="type-card-opt active" id="optLeave" onclick="selectLeaveType('leave', 'create')">
                            <div class="type-icon-box"><i class="fa-solid fa-umbrella-beach"></i></div>
                            <div class="type-opt-text">
                                <strong>Cuti Rehat</strong>
                                <span>Sepenuh Hari</span>
                            </div>
                        </div>
                        <div class="type-card-opt" id="optTimeOff" onclick="selectLeaveType('time_off', 'create')">
                            <div class="type-icon-box"><i class="fa-solid fa-hourglass-start"></i></div>
                            <div class="type-opt-text">
                                <strong>Time Off</strong>
                                <span>Beberapa Jam</span>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Tarikh *</label>
                        <input type="date" name="date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>

                    <div id="timeFieldsRow" style="display: none; grid-template-columns: 1fr 1fr; gap: 12px;">
                        <div class="form-group">
                            <label>Masa Mula</label>
                            <input type="time" name="start_time" class="form-control" value="09:00">
                        </div>
                        <div class="form-group">
                            <label>Masa Tamat</label>
                            <input type="time" name="end_time" class="form-control" value="11:00">
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Sebab Permohonan *</label>
                        <textarea name="reason" id="leaveReasonInput" class="form-control" rows="3" placeholder="Contoh: Urusan peribadi / kecemasan..." required></textarea>
                    </div>

                    <div style="display: flex; align-items: center; gap: 10px; background: rgba(124, 58, 237, 0.06); padding: 12px 14px; border-radius: 14px; border: 1px solid rgba(124, 58, 237, 0.12);">
                        <input type="checkbox" name="notify_all" id="notifyAll" checked style="width: 18px; height: 18px; accent-color: #7c3aed;">
                        <label for="notifyAll" style="font-size: 0.82rem; font-weight: 700; color: var(--deep-blue); cursor: pointer;">
                            Maklumkan kepada bahagian (<?php echo htmlspecialchars($user_department !== '' ? $user_department : 'Bahagian Anda'); ?>)
                        </label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-status-reopen" style="padding: 10px 18px;" onclick="closeAddLeaveModal()">Batal</button>
                    <button type="submit" class="btn-save" id="btnSubmitLeave">SIMPAN CUTI REHAT</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal 2: ✏️ Edit Cuti / Time Off Modal -->
    <div class="modal-overlay" id="editLeaveModal">
        <div class="modal-card">
            <div class="modal-header">
                <div>
                    <h3><i class="fa-solid fa-pen-to-square text-purple mr-2"></i> Kemaskini Cuti / Time Off</h3>
                    <p style="font-size: 0.78rem; color: var(--text-muted); margin-top: 2px;">Ubah maklumat permohonan anda.</p>
                </div>
                <button style="background: none; border: none; font-size: 1.2rem; cursor: pointer;" onclick="closeEditLeaveModal()"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <form action="my_cuti.php" method="POST">
                <input type="hidden" name="action" value="update_cuti">
                <input type="hidden" name="event_id" id="editLeaveId">
                <input type="hidden" name="type" id="editLeaveTypeInput" value="leave">

                <div class="modal-body">
                    <div class="type-selector-grid">
                        <div class="type-card-opt" id="editOptLeave" onclick="selectLeaveType('leave', 'edit')">
                            <div class="type-icon-box"><i class="fa-solid fa-umbrella-beach"></i></div>
                            <div class="type-opt-text">
                                <strong>Cuti Rehat</strong>
                                <span>Sepenuh Hari</span>
                            </div>
                        </div>
                        <div class="type-card-opt" id="editOptTimeOff" onclick="selectLeaveType('time_off', 'edit')">
                            <div class="type-icon-box"><i class="fa-solid fa-hourglass-start"></i></div>
                            <div class="type-opt-text">
                                <strong>Time Off</strong>
                                <span>Beberapa Jam</span>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Tarikh *</label>
                        <input type="date" name="date" id="editLeaveDate" class="form-control" required>
                    </div>

                    <div id="editTimeFieldsRow" style="display: none; grid-template-columns: 1fr 1fr; gap: 12px;">
                        <div class="form-group">
                            <label>Masa Mula</label>
                            <input type="time" name="start_time" id="editLeaveStartTime" class="form-control" value="09:00">
                        </div>
                        <div class="form-group">
                            <label>Masa Tamat</label>
                            <input type="time" name="end_time" id="editLeaveEndTime" class="form-control" value="11:00">
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Sebab *</label>
                        <textarea name="reason" id="editLeaveReason" class="form-control" rows="3" placeholder="Sebab permohonan..." required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-status-reopen" style="padding: 10px 18px;" onclick="closeEditLeaveModal()">Batal</button>
                    <button type="submit" class="btn-save" id="btnEditSubmitLeave">SIMPAN PERUBAHAN</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const myLeaves = <?php echo json_encode($leaves, JSON_UNESCAPED_UNICODE); ?>;
        let calCurrentLeaveDate = new Date();
        let currentTimeline = 'upcoming';
        let currentCategory = 'all';

        function switchLeaveMasterView(mode) {
            document.getElementById('btnLeaveList').classList.toggle('active', mode === 'list');
            document.getElementById('btnLeaveCalendar').classList.toggle('active', mode === 'calendar');
            document.getElementById('leaveListSection').style.display = (mode === 'list') ? 'block' : 'none';
            document.getElementById('leaveCalendarSection').style.display = (mode === 'calendar') ? 'block' : 'none';
            if (mode === 'calendar') {
                renderLeaveCalendarWeek();
            }
        }

        function selectLeaveTimeline(timeline) {
            currentTimeline = timeline;
            document.querySelectorAll('.timeline-tab-btn').forEach(btn => {
                btn.classList.toggle('active', btn.getAttribute('data-timeline') === timeline);
            });

            document.querySelectorAll('.leave-timeline-grid').forEach(grid => {
                grid.style.display = (grid.id === `timeline_${timeline}`) ? 'block' : 'none';
            });

            filterLeavesLive();
        }

        function filterLeaveCategory(cat, btn) {
            currentCategory = cat;
            document.querySelectorAll('.cat-pill-btn').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            filterLeavesLive();
        }

        function filterLeavesLive() {
            const query = document.getElementById('leaveSearchInput').value.toLowerCase().trim();
            const activeGrid = document.getElementById(`timeline_${currentTimeline}`);
            if (!activeGrid) return;

            const cards = activeGrid.querySelectorAll('.world-leave-card');
            cards.forEach(card => {
                const cardCat = card.getAttribute('data-cat') || '';
                const cardText = card.getAttribute('data-title') || '';

                const matchesCat = (currentCategory === 'all' || cardCat === currentCategory);
                const matchesQuery = (query === '' || cardText.includes(query));

                card.style.display = (matchesCat && matchesQuery) ? 'flex' : 'none';
            });
        }

        function renderLeaveCalendarWeek() {
            const headerRow = document.getElementById('leaveWeekHeaderRow');
            const dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
            const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
            
            document.getElementById('leaveCalMonthTitle').innerText = `${monthNames[calCurrentLeaveDate.getMonth()]} ${calCurrentLeaveDate.getFullYear()}`;

            const currentDayOfWeek = calCurrentLeaveDate.getDay();
            const sunday = new Date(calCurrentLeaveDate);
            sunday.setDate(calCurrentLeaveDate.getDate() - currentDayOfWeek);

            const existingHeaders = headerRow.querySelectorAll('.cal-head-col');
            existingHeaders.forEach(h => h.remove());

            const today = new Date();

            for (let i = 0; i < 7; i++) {
                const d = new Date(sunday);
                d.setDate(sunday.getDate() + i);

                const isToday = d.toDateString() === today.toDateString();
                const colHeader = document.createElement('div');
                colHeader.className = `cal-head-col ${isToday ? 'active-day' : ''}`;
                colHeader.innerHTML = `
                    <span style="font-size: 0.72rem; color: var(--text-muted);">${dayNames[i]} ${d.getDate()}</span>
                `;
                headerRow.appendChild(colHeader);
            }

            const cells = document.querySelectorAll('.cal-day-cell');
            cells.forEach(cell => {
                cell.innerHTML = '';
                const dayIndex = parseInt(cell.getAttribute('data-day-index'));
                const hour = parseInt(cell.getAttribute('data-hour'));

                const targetDate = new Date(sunday);
                targetDate.setDate(sunday.getDate() + dayIndex);
                const targetDateStr = `${targetDate.getFullYear()}-${String(targetDate.getMonth()+1).padStart(2,'0')}-${String(targetDate.getDate()).padStart(2,'0')}`;

                const matchingLeaves = myLeaves.filter(l => {
                    if (!l.start_at || !l.start_at.startsWith(targetDateStr)) return false;
                    const lHour = new Date(l.start_at).getHours();
                    return lHour === hour;
                });

                matchingLeaves.forEach((l) => {
                    const type = (l.event_type || 'leave').toLowerCase();
                    const isTimeOff = (type === 'time_off' || type === 'timeoff');

                    const startDate = new Date(l.start_at);
                    const endDate = l.end_at ? new Date(l.end_at) : new Date(startDate.getTime() + 60*60*1000);

                    const formatShortTime = (d) => {
                        let h = d.getHours();
                        let m = d.getMinutes();
                        const ampm = h >= 12 ? 'pm' : 'am';
                        h = h % 12 || 12;
                        return m > 0 ? `${h}.${String(m).padStart(2,'0')}${ampm}` : `${h}${ampm}`;
                    };

                    const timeRange = isTimeOff ? `${formatShortTime(startDate)} - ${formatShortTime(endDate)}` : 'Full Day';
                    const themeClass = isTimeOff ? 'leave-theme-timeoff' : 'leave-theme-cuti';
                    const tagLabel = isTimeOff ? 'Time Off' : 'Cuti Rehat';

                    const diffMs = endDate.getTime() - startDate.getTime();
                    const durationHours = Math.max(0.8, diffMs / (1000 * 60 * 60));
                    const slotHeight = 72;
                    const cardHeight = Math.max(60, Math.round(durationHours * slotHeight) - 8);

                    const card = document.createElement('div');
                    card.className = `cal-leave-card ${themeClass}`;
                    card.style.height = `${cardHeight}px`;
                    card.style.position = 'relative';
                    card.style.zIndex = '15';
                    card.onclick = () => openEditLeaveModal(l);
                    card.innerHTML = `
                        <div style="font-size: 0.7rem; font-weight: 750; color: #4338ca;">${timeRange}</div>
                        <div style="font-size: 0.84rem; font-weight: 850; color: #1e293b; line-height: 1.25;">${escapeHtml(l.title)}</div>
                        <div style="margin-top: auto; display: inline-flex; align-items: center; gap: 5px; background: rgba(255,255,255,0.9); padding: 3px 8px; border-radius: 6px; font-size: 0.68rem; font-weight: 800; color: #475569; width: fit-content;">
                            <span>${tagLabel}</span>
                        </div>
                    `;
                    cell.appendChild(card);
                });
            });
        }

        function prevLeaveWeek() {
            calCurrentLeaveDate.setDate(calCurrentLeaveDate.getDate() - 7);
            renderLeaveCalendarWeek();
        }

        function nextLeaveWeek() {
            calCurrentLeaveDate.setDate(calCurrentLeaveDate.getDate() + 7);
            renderLeaveCalendarWeek();
        }

        function goToTodayLeave() {
            calCurrentLeaveDate = new Date();
            renderLeaveCalendarWeek();
        }

        function selectLeaveType(type, mode) {
            const isEdit = (mode === 'edit');
            const typeInput = document.getElementById(isEdit ? 'editLeaveTypeInput' : 'leaveTypeInput');
            typeInput.value = type;

            const isLeave = (type === 'leave');
            document.getElementById(isEdit ? 'editOptLeave' : 'optLeave').classList.toggle('active', isLeave);
            document.getElementById(isEdit ? 'editOptTimeOff' : 'optTimeOff').classList.toggle('active', !isLeave);

            const timeFields = document.getElementById(isEdit ? 'editTimeFieldsRow' : 'timeFieldsRow');
            const reasonInput = document.getElementById(isEdit ? 'editLeaveReason' : 'leaveReasonInput');
            const submitBtn = document.getElementById(isEdit ? 'btnEditSubmitLeave' : 'btnSubmitLeave');

            if (isLeave) {
                timeFields.style.display = 'none';
                reasonInput.placeholder = 'Contoh: Urusan keluarga / rehat';
                submitBtn.innerText = isEdit ? 'SIMPAN PERUBAHAN CUTI' : 'SIMPAN CUTI REHAT';
            } else {
                timeFields.style.display = 'grid';
                reasonInput.placeholder = 'Contoh: Urusan kecemasan peribadi';
                submitBtn.innerText = isEdit ? 'SIMPAN PERUBAHAN TIME OFF' : 'SIMPAN TIME OFF';
            }
        }

        function openAddLeaveModal() {
            document.getElementById('addLeaveModal').classList.add('active');
        }
        function closeAddLeaveModal() {
            document.getElementById('addLeaveModal').classList.remove('active');
        }

        function openEditLeaveModal(lv) {
            document.getElementById('editLeaveId').value = lv.id || '';
            const type = (lv.event_type || 'leave').toLowerCase();
            const isTimeOff = (type === 'time_off' || type === 'timeoff');
            selectLeaveType(isTimeOff ? 'time_off' : 'leave', 'edit');

            if (lv.start_at) {
                document.getElementById('editLeaveDate').value = lv.start_at.substring(0, 10);
                document.getElementById('editLeaveStartTime').value = lv.start_at.substring(11, 16);
            }
            if (lv.end_at) {
                document.getElementById('editLeaveEndTime').value = lv.end_at.substring(11, 16);
            }
            document.getElementById('editLeaveReason').value = lv.reason || lv.description || '';

            document.getElementById('editLeaveModal').classList.add('active');
        }

        function closeEditLeaveModal() {
            document.getElementById('editLeaveModal').classList.remove('active');
        }

        function escapeHtml(text) {
            if (!text) return '';
            return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
        }

        document.addEventListener('DOMContentLoaded', () => {
            selectLeaveTimeline('upcoming');
        });

        // Sidebar behavior
        const sidebar = document.getElementById('sidebar');
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn && sidebar) {
            toggleBtn.addEventListener('click', () => sidebar.classList.toggle('collapsed'));
        }
        if (window.innerWidth < 992 && sidebar) sidebar.classList.add('collapsed');

        document.querySelectorAll('.sidebar-menu .dropdown-toggle, .dropdown-toggle').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                const dropdown = this.parentElement;
                const isActive = dropdown.classList.contains('active');
                document.querySelectorAll('.sidebar-menu .dropdown, .dropdown').forEach(item => {
                    if (item !== dropdown) item.classList.remove('active');
                });
                dropdown.classList.toggle('active', !isActive);
            });
        });
    </script>
</body>
</html>
