<?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 (Universal Multi-Category Event Composer)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'create_universal') {
        $category_tab = strtolower(trim((string)($_POST['category_tab'] ?? 'task')));
        
        if ($category_tab === 'task') {
            $title = trim((string)($_POST['task_title'] ?? ''));
            $project = trim((string)($_POST['task_project'] ?? ''));
            $category = trim((string)($_POST['task_category'] ?? ''));
            $due_date = trim((string)($_POST['task_due_date'] ?? ''));
            $start_date = trim((string)($_POST['task_start_date'] ?? date('Y-m-d')));
            $end_date = trim((string)($_POST['task_end_date'] ?? $start_date));
            $start_time = trim((string)($_POST['task_start_time'] ?? '09:00'));
            $end_time = trim((string)($_POST['task_end_time'] ?? '11:00'));
            $priority = strtolower(trim((string)($_POST['task_priority'] ?? 'medium')));
            $priority = in_array($priority, ['low', 'medium', 'high'], true) ? $priority : 'medium';
            $remark = trim((string)($_POST['task_remark'] ?? ''));

            if ($title !== '') {
                $start_at = "$start_date $start_time:00";
                $end_at = "$end_date $end_time:00";
                $due = !empty($due_date) ? $due_date : $end_date;
                $manday = max(1, (int)round((strtotime($end_at) - strtotime($start_at)) / 86400));

                $combined_desc = $remark;
                if ($project !== '' || $category !== '') {
                    $meta_tags = [];
                    if ($project !== '') $meta_tags[] = "Projek: $project";
                    if ($category !== '') $meta_tags[] = "Kategori: $category";
                    $combined_desc = implode(' | ', $meta_tags) . ($remark !== '' ? "\n\n$remark" : '');
                }

                $stmt = mysqli_prepare($conn, "INSERT INTO calendar_events (user_id, event_type, title, description, location, start_at, end_at, due_date, manday, priority, status, created_by, updated_by) VALUES (?, 'task', ?, ?, ?, ?, ?, ?, ?, ?, 'Pending', ?, ?)");
                if ($stmt) {
                    mysqli_stmt_bind_param($stmt, 'issssssisii', $user_id, $title, $combined_desc, $category, $start_at, $end_at, $due, $manday, $priority, $user_id, $user_id);
                    if (mysqli_stmt_execute($stmt)) {
                        $flash_msg = 'Tugasan berjaya ditambah ke jadual!';
                        $flash_type = 'success';
                    }
                }
            }
        } elseif ($category_tab === 'leave') {
            $leave_sub_type = strtolower(trim((string)($_POST['leave_sub_type'] ?? 'leave')));
            $is_leave = ($leave_sub_type === 'leave');
            $event_type = $is_leave ? 'leave' : 'time_off';
            $doc_title = $is_leave ? 'Cuti Rehat' : 'Time Off';
            $date = trim((string)($_POST['leave_date'] ?? date('Y-m-d')));
            $start_time = trim((string)($_POST['leave_start_time'] ?? '09:00'));
            $end_time = trim((string)($_POST['leave_end_time'] ?? '11:00'));
            $reason = trim((string)($_POST['leave_reason'] ?? ''));
            $notify_all = !empty($_POST['leave_notify_all']);

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

            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, $event_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 ke jadual!";
                        $flash_type = 'success';

                        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) {
                                    $date_str = date('d/m/Y', strtotime($date));
                                    $push_title = "Makluman $doc_title Bahagian";
                                    $push_body = "$user_fullname mendaftar $doc_title pada $date_str ($reason).";
                                    while ($r = mysqli_fetch_assoc($dept_res)) {
                                        if (function_exists('sendMainppPush')) {
                                            @sendMainppPush($conn, (int)$r['id'], $push_title, $push_body, ['type' => 'leave']);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } elseif ($category_tab === 'meeting' || $category_tab === 'kursus') {
            $category = ($category_tab === 'kursus') ? 'kursus' : 'meeting';
            $title = trim((string)($_POST['meet_title'] ?? ''));
            $date = trim((string)($_POST['meet_date'] ?? date('Y-m-d')));
            $start_time = trim((string)($_POST['meet_start_time'] ?? '09:00'));
            $end_time = trim((string)($_POST['meet_end_time'] ?? '11:00'));
            $location = trim((string)($_POST['meet_location'] ?? ''));
            $notes = trim((string)($_POST['meet_notes'] ?? ''));

            $participants_arr = isset($_POST['meet_participants']) && is_array($_POST['meet_participants']) ? $_POST['meet_participants'] : [];
            $ext_participants = trim((string)($_POST['meet_ext_participants'] ?? ''));
            if ($ext_participants !== '') {
                $exts = array_map('trim', explode(',', $ext_participants));
                $participants_arr = array_merge($participants_arr, $exts);
            }
            $participants_json = json_encode(array_values(array_filter($participants_arr)), JSON_UNESCAPED_UNICODE);

            if ($title !== '') {
                $start_at = "$date $start_time:00";
                $end_at = "$date $end_time:00";
                $stmt = mysqli_prepare($conn, "INSERT INTO calendar_events (user_id, event_type, title, description, location, start_at, end_at, priority, status, participants, created_by, updated_by) VALUES (?, ?, ?, ?, ?, ?, ?, 'Normal', 'Scheduled', ?, ?, ?)");
                if ($stmt) {
                    mysqli_stmt_bind_param($stmt, 'isssssssii', $user_id, $category, $title, $notes, $location, $start_at, $end_at, $participants_json, $user_id, $user_id);
                    if (mysqli_stmt_execute($stmt)) {
                        $label = ($category === 'kursus') ? 'Kursus / Latihan' : 'Mesyuarat';
                        $flash_msg = "$label berjaya dijadualkan!";
                        $flash_type = 'success';
                    }
                }
            }
        }
    } elseif ($action === 'delete_event') {
        $event_id = (int) ($_POST['event_id'] ?? 0);
        if ($event_id > 0) {
            $stmt = mysqli_prepare($conn, "DELETE FROM calendar_events WHERE id = ? AND user_id = ?");
            if ($stmt) {
                mysqli_stmt_bind_param($stmt, 'ii', $event_id, $user_id);
                if (mysqli_stmt_execute($stmt)) {
                    $flash_msg = 'Acara berjaya dipadam.';
                    $flash_type = 'success';
                }
            }
        }
    }
}

// Fetch all events for current user
$sql = "SELECT * FROM calendar_events WHERE user_id = ? AND deleted_at IS NULL ORDER BY start_at ASC";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'i', $user_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$events = $result ? mysqli_fetch_all($result, MYSQLI_ASSOC) : [];

// Filter tasks for task completion donut
$total_tasks = 0;
$completed_tasks = 0;
$in_progress_tasks = 0;
$pending_tasks = 0;

$upcoming_events = [];
$now = date('Y-m-d H:i:s');

foreach ($events as $ev) {
    $ev_type = strtolower($ev['event_type'] ?? '');
    if ($ev_type === 'task') {
        $total_tasks++;
        $st = strtolower(trim($ev['status'] ?? ''));
        if ($st === 'completed' || $st === 'selesai' || $st === 'done') {
            $completed_tasks++;
        } elseif ($st === 'in progress' || $st === 'dalam proses' || $st === 'ongoing') {
            $in_progress_tasks++;
        } else {
            $pending_tasks++;
        }
    }

    if ($ev['start_at'] >= $now || (isset($ev['due_date']) && $ev['due_date'] >= $now)) {
        $upcoming_events[] = $ev;
    }
}

$upcoming_events = array_slice($upcoming_events, 0, 6);
$task_completion_pct = $total_tasks > 0 ? round(($completed_tasks / $total_tasks) * 100) : 0;

// Fetch department colleagues for participant picker
$dept_members = [];
if ($user_department !== '') {
    $dm_stmt = mysqli_prepare($conn, "SELECT id, fullname, short_name, position FROM users WHERE LOWER(TRIM(department)) = LOWER(TRIM(?)) AND status = 'approved' AND id <> ? ORDER BY fullname ASC");
    if ($dm_stmt) {
        mysqli_stmt_bind_param($dm_stmt, 'si', $user_department, $user_id);
        mysqli_stmt_execute($dm_stmt);
        $dm_res = mysqli_stmt_get_result($dm_stmt);
        $dept_members = $dm_res ? mysqli_fetch_all($dm_res, MYSQLI_ASSOC) : [];
    }
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Schedule | 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); }

        /* Action bar */
        .schedule-action-bar {
            background: var(--glass-strong); padding: 16px 24px; border-radius: 20px;
            box-shadow: var(--shadow-soft); margin-bottom: 24px; 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;
        }
        .search-box {
            position: relative; width: 320px;
        }
        .search-box input {
            width: 100%; padding: 10px 16px 10px 42px; border-radius: 14px; border: 1px solid rgba(0, 119, 182, 0.20);
            background: rgba(240, 249, 255, 0.50); font-size: 0.88rem; outline: none; transition: all 0.2s ease;
        }
        .search-box input:focus { background: #fff; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(0, 119, 182, 0.12); }
        .search-box i { position: absolute; left: 15px; top: 50%; transform: translateY(-50%); color: var(--text-muted); }

        .btn-add-event {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            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(0, 119, 182, 0.30); transition: all 0.2s ease;
        }
        .btn-add-event:hover { transform: translateY(-2px); box-shadow: 0 12px 25px rgba(0, 119, 182, 0.40); }

        /* 2-Column Schedule Grid */
        .schedule-container {
            display: grid; grid-template-columns: 320px 1fr; gap: 24px;
        }
        @media (max-width: 1024px) {
            .schedule-container { grid-template-columns: 1fr; }
        }

        /* Left Side Widgets */
        .schedule-sidebar { display: flex; flex-direction: column; gap: 24px; }
        
        .mini-cal-card {
            background: var(--glass-strong); border-radius: 24px; border: 1px solid var(--border);
            padding: 22px; box-shadow: var(--shadow-card); backdrop-filter: blur(18px); -webkit-backdrop-filter: blur(18px);
        }
        .mini-calendar-nav {
            display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;
        }
        .mini-calendar-nav span { font-weight: 800; font-size: 0.95rem; color: var(--deep-blue); }
        .mini-cal-btn {
            width: 28px; height: 28px; border-radius: 8px;
            border: 1px solid rgba(0, 119, 182, 0.15); background: #fff;
            display: flex; align-items: center; justify-content: center;
            color: var(--deep-blue); cursor: pointer; transition: all 0.2s ease;
        }
        .mini-cal-btn:hover { background: var(--primary); color: #fff; }
        .mini-cal-grid {
            display: grid; grid-template-columns: repeat(7, 1fr); gap: 4px; text-align: center;
        }
        .mini-cal-day-name { font-size: 0.72rem; font-weight: 700; color: var(--text-muted); padding: 4px 0; }
        .mini-cal-cell {
            aspect-ratio: 1; display: flex; align-items: center; justify-content: center;
            font-size: 0.8rem; font-weight: 600; border-radius: 8px; cursor: pointer;
            transition: all 0.15s ease; color: var(--text-main); position: relative;
        }
        .mini-cal-cell:hover { background: rgba(0, 119, 182, 0.12); color: var(--primary); }
        .mini-cal-cell.today {
            background: linear-gradient(135deg, #f43f5e, #e11d48);
            color: #fff; font-weight: 800; box-shadow: 0 4px 10px rgba(244, 63, 94, 0.35);
        }

        /* Task Donut Ring Card */
        .donut-card {
            background: var(--glass-strong); border-radius: 24px; border: 1px solid var(--border);
            padding: 22px; box-shadow: var(--shadow-card); backdrop-filter: blur(18px); -webkit-backdrop-filter: blur(18px);
        }
        .donut-header {
            display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;
        }
        .donut-header h4 { font-size: 0.92rem; font-weight: 800; color: var(--deep-blue); }
        .donut-container {
            display: flex; align-items: center; gap: 20px;
        }
        .donut-svg-box {
            position: relative; width: 100px; height: 100px; flex-shrink: 0;
        }
        .donut-pct-text {
            position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
            font-size: 1.25rem; font-weight: 850; color: var(--deep-blue);
        }
        .donut-legend { display: flex; flex-direction: column; gap: 6px; flex: 1; }
        .donut-legend-item { display: flex; align-items: center; justify-content: space-between; font-size: 0.78rem; font-weight: 700; }
        .donut-legend-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; margin-right: 6px; }

        /* Upcoming Activities Card */
        .upcoming-card {
            background: var(--glass-strong); border-radius: 24px; border: 1px solid var(--border);
            padding: 22px; box-shadow: var(--shadow-card); backdrop-filter: blur(18px); -webkit-backdrop-filter: blur(18px);
        }
        .upcoming-card h4 { font-size: 0.92rem; font-weight: 800; color: var(--deep-blue); margin-bottom: 16px; display: flex; align-items: center; gap: 8px; }
        .upcoming-list { display: flex; flex-direction: column; gap: 12px; }
        .upcoming-item {
            display: flex; align-items: flex-start; gap: 12px; padding: 10px 12px; border-radius: 14px;
            background: rgba(255, 255, 255, 0.65); border: 1px solid rgba(0, 119, 182, 0.10);
            transition: all 0.2s ease;
        }
        .upcoming-item:hover { background: #fff; transform: translateX(3px); box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
        .upcoming-icon {
            width: 32px; height: 32px; border-radius: 10px; display: flex; align-items: center; justify-content: center;
            font-size: 0.85rem; flex-shrink: 0;
        }
        .upcoming-info h5 { font-size: 0.82rem; font-weight: 800; color: var(--deep-blue); line-height: 1.2; }
        .upcoming-info p { font-size: 0.72rem; font-weight: 600; color: var(--text-muted); margin-top: 2px; }

        /* Main Calendar Viewport */
        .main-calendar-box {
            background: var(--glass-strong); border-radius: 24px; border: 1px solid var(--border);
            padding: 24px 28px; box-shadow: var(--shadow-card); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
            display: flex; flex-direction: column; gap: 20px;
        }
        .main-cal-controls {
            display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 14px;
        }
        .cal-nav-group { display: flex; align-items: center; gap: 12px; }
        .cal-title-header { font-size: 1.45rem; font-weight: 850; color: var(--deep-blue); }
        .cal-btn-pill {
            padding: 6px 14px; border-radius: 10px; font-weight: 750; font-size: 0.82rem;
            background: #fff; border: 1px solid rgba(0, 119, 182, 0.20); color: var(--deep-blue);
            cursor: pointer; transition: all 0.2s ease;
        }
        .cal-btn-pill:hover { background: var(--deep-blue); color: #fff; }

        .view-switcher-group {
            display: flex; align-items: center; background: rgba(0, 119, 182, 0.08); padding: 4px; border-radius: 12px; gap: 4px;
        }
        .view-btn {
            border: none; background: transparent; padding: 6px 14px; border-radius: 9px;
            font-size: 0.8rem; font-weight: 750; color: var(--text-muted); cursor: pointer; transition: all 0.2s ease;
        }
        .view-btn.active {
            background: #fff; color: var(--deep-blue); box-shadow: 0 4px 10px rgba(0,0,0,0.06);
        }

        /* Month Grid */
        .month-grid-table { width: 100%; border-collapse: separate; border-spacing: 6px; }
        .month-grid-table th {
            text-align: center; padding: 10px 4px; font-size: 0.8rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase;
        }
        .month-cell {
            height: 110px; width: 14.28%; vertical-align: top; background: rgba(255, 255, 255, 0.65);
            border-radius: 14px; border: 1px solid rgba(0, 119, 182, 0.10); padding: 8px; transition: all 0.2s ease;
        }
        .month-cell:hover { background: #fff; box-shadow: 0 6px 18px rgba(0, 119, 182, 0.12); }
        .month-cell.is-other-month { opacity: 0.35; }
        .month-cell.is-today { border: 2px solid var(--primary); background: #f0fdfa; }
        .month-cell-num { font-size: 0.85rem; font-weight: 800; color: var(--deep-blue); margin-bottom: 6px; }
        .month-cell-events { display: flex; flex-direction: column; gap: 3px; overflow-y: auto; max-height: 70px; }
        .cal-event-pill {
            font-size: 0.7rem; font-weight: 750; padding: 3px 6px; border-radius: 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer;
        }
        .pill-meeting { background: #e0f2fe; color: #0284c7; border-left: 3px solid #0284c7; }
        .pill-kursus { background: #f3e8ff; color: #9333ea; border-left: 3px solid #9333ea; }
        .pill-leave { background: #fef3c7; color: #d97706; border-left: 3px solid #d97706; }
        .pill-timeoff { background: #e0e7ff; color: #4338ca; border-left: 3px solid #4338ca; }
        .pill-task { background: #ccfbf1; color: #0f766e; border-left: 3px solid #0f766e; }

        /* Week Grid */
        .week-view-container {
            display: flex; flex-direction: column; border: 1px solid rgba(0, 119, 182, 0.14);
            border-radius: 16px; overflow: hidden; background: #fff; margin-top: 10px;
        }
        .week-grid-header {
            display: grid; grid-template-columns: 80px repeat(7, 1fr);
            background: rgba(240, 249, 255, 0.85); border-bottom: 1px solid rgba(0, 119, 182, 0.14);
        }
        .week-col-time { padding: 10px 6px; text-align: center; font-size: 0.75rem; font-weight: 750; color: var(--text-muted); }
        .week-col-day {
            padding: 10px 4px; text-align: center; font-size: 0.8rem; font-weight: 800; color: var(--deep-blue);
            border-left: 1px solid rgba(0, 119, 182, 0.10);
        }
        .week-col-day.active-today { background: #ecfdf5; color: #047857; }
        .week-grid-body { max-height: 520px; overflow-y: auto; position: relative; }
        .week-hour-row {
            display: grid; grid-template-columns: 80px repeat(7, 1fr);
            min-height: 60px; border-bottom: 1px solid rgba(0, 119, 182, 0.08); position: relative;
        }
        .hour-label {
            font-size: 0.72rem; font-weight: 700; color: var(--text-muted);
            display: flex; align-items: flex-start; justify-content: center; padding-top: 4px;
        }
        .hour-day-slot { border-left: 1px solid rgba(0, 119, 182, 0.08); padding: 3px; position: relative; }
        
        /* Live Current-Time Line */
        .live-time-indicator {
            position: absolute; left: 80px; right: 0; height: 2px; background: #10b981; z-index: 10; pointer-events: none;
        }
        .live-time-tag {
            position: absolute; left: -75px; top: -10px; background: #10b981; color: #fff; font-size: 0.68rem; font-weight: 800; padding: 2px 6px; border-radius: 4px;
        }

        /* ================= UNIVERSAL MODAL COMPOSER ================= */
        .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: 580px;
            box-shadow: 0 25px 60px rgba(0,0,0,0.25); overflow: hidden; animation: modalPop 0.25s ease;
            max-height: 92vh; 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 14px; 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.2rem; font-weight: 850; color: var(--deep-blue); display: flex; align-items: center; gap: 8px; }
        .modal-body { padding: 20px 24px; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; }
        
        /* Modal Category Tabs (4 Tabs) */
        .composer-category-nav {
            display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px;
            background: rgba(0, 119, 182, 0.07); padding: 5px; border-radius: 14px;
        }
        .cat-nav-btn {
            border: none; background: transparent; padding: 9px 4px; border-radius: 10px;
            font-size: 0.78rem; font-weight: 800; color: var(--text-muted); cursor: pointer;
            transition: all 0.2s ease; display: flex; flex-direction: column; align-items: center; gap: 4px;
        }
        .cat-nav-btn i { font-size: 1rem; }
        .cat-nav-btn.active {
            background: #fff; color: var(--deep-blue); box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }
        .cat-nav-btn.active[data-cat="task"] { color: #0d9488; }
        .cat-nav-btn.active[data-cat="leave"] { color: #7c3aed; }
        .cat-nav-btn.active[data-cat="meeting"] { color: #0284c7; }
        .cat-nav-btn.active[data-cat="kursus"] { color: #9333ea; }

        .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); }

        .priority-options { display: flex; gap: 8px; }
        .priority-opt {
            flex: 1; text-align: center; padding: 8px 10px; border-radius: 12px; border: 1.5px solid rgba(0,119,182,0.18);
            font-size: 0.82rem; font-weight: 800; cursor: pointer; transition: all 0.2s ease;
            background: #fff; color: var(--text-muted);
        }
        .priority-opt.active[data-val="low"] { background: #e0f2fe; border-color: #0284c7; color: #0284c7; }
        .priority-opt.active[data-val="medium"] { background: #fef3c7; border-color: #d97706; color: #d97706; }
        .priority-opt.active[data-val="high"] { background: #fee2e2; border-color: #dc2626; color: #dc2626; }

        /* Cuti Sub-Type Segment */
        .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: 14px; padding: 10px 14px;
            cursor: pointer; display: flex; align-items: center; gap: 10px; 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: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 0.95rem;
        }
        .type-card-opt.active .type-icon-box { background: #7c3aed; color: #fff; }
        .type-card-opt:not(.active) .type-icon-box { background: #f1f5f9; color: #64748b; }

        .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, var(--primary), var(--secondary)); 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_schedule.php'); ?>
        </ul>
    </aside>

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

        <!-- Top Bar matching Dashboard -->
        <div class="top-bar">
            <h2><i class="fa-regular fa-calendar-days"></i> My Schedule</h2>
            <?php renderTopBarUserMenu($conn, $role, 'my_schedule.php'); ?>
        </div>

        <?php
        renderBreadcrumb([
            ['label' => 'Dashboard', 'url' => 'dashboard.php'],
            ['label' => 'Modul Peribadi', 'url' => '#'],
            ['label' => 'My Schedule', 'url' => 'my_schedule.php', 'current' => true]
        ]);
        ?>

        <!-- Search and Action Bar with '+ Tambah' -->
        <div class="schedule-action-bar">
            <div class="search-box">
                <i class="fa-solid fa-magnifying-glass"></i>
                <input type="text" id="scheduleSearchInput" placeholder="Cari acara, tugasan, mesyuarat...">
            </div>

            <div style="display: flex; align-items: center; gap: 12px;">
                <a href="my_team_schedule.php" class="cal-btn-pill" style="padding: 10px 18px; text-decoration: none;">
                    <i class="fa-solid fa-users text-primary"></i> Jadual Pasukan
                </a>
                <button class="btn-add-event" onclick="openAddEventModal()">
                    <i class="fa-solid fa-plus"></i>
                    <span>+ Tambah</span>
                </button>
            </div>
        </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; ?>

        <!-- 2-Column Workspace Grid -->
        <div class="schedule-container">

            <!-- Left Sidebar Controls -->
            <div class="schedule-sidebar">

                <!-- Interactive Mini Calendar -->
                <div class="mini-cal-card">
                    <div class="mini-calendar-nav">
                        <span id="miniCalTitle">Ogos 2026</span>
                        <div style="display: flex; gap: 4px;">
                            <button class="mini-cal-btn" onclick="prevMiniMonth()"><i class="fa-solid fa-chevron-left"></i></button>
                            <button class="mini-cal-btn" onclick="nextMiniMonth()"><i class="fa-solid fa-chevron-right"></i></button>
                        </div>
                    </div>
                    <div class="mini-cal-grid" id="miniCalGrid">
                        <div class="mini-cal-day-name">A</div>
                        <div class="mini-cal-day-name">I</div>
                        <div class="mini-cal-day-name">S</div>
                        <div class="mini-cal-day-name">R</div>
                        <div class="mini-cal-day-name">K</div>
                        <div class="mini-cal-day-name">J</div>
                        <div class="mini-cal-day-name">S</div>
                    </div>
                </div>

                <!-- Task Progress Donut Card -->
                <div class="donut-card">
                    <div class="donut-header">
                        <h4>Prestasi Tugasan</h4>
                        <span style="font-size: 0.75rem; font-weight: 800; color: var(--primary);"><?php echo $total_tasks; ?> Tugasan</span>
                    </div>
                    <div class="donut-container">
                        <div class="donut-svg-box">
                            <svg viewBox="0 0 36 36" style="transform: rotate(-90deg); width: 100%; height: 100%;">
                                <circle cx="18" cy="18" r="15.9" fill="none" stroke="rgba(0,119,182,0.12)" stroke-width="3.8"></circle>
                                <circle cx="18" cy="18" r="15.9" fill="none" stroke="url(#donutGrad)" stroke-width="3.8" stroke-dasharray="<?php echo $task_completion_pct; ?>, 100" stroke-linecap="round"></circle>
                                <defs>
                                    <linearGradient id="donutGrad" x1="0%" y1="0%" x2="100%" y2="100%">
                                        <stop offset="0%" stop-color="#0077b6" />
                                        <stop offset="100%" stop-color="#00b4d8" />
                                    </linearGradient>
                                </defs>
                            </svg>
                            <div class="donut-pct-text"><?php echo $task_completion_pct; ?>%</div>
                        </div>
                        <div class="donut-legend">
                            <div class="donut-legend-item">
                                <span><span class="donut-legend-dot" style="background: #10b981;"></span> Selesai</span>
                                <strong><?php echo $completed_tasks; ?></strong>
                            </div>
                            <div class="donut-legend-item">
                                <span><span class="donut-legend-dot" style="background: #f59e0b;"></span> Dalam Proses</span>
                                <strong><?php echo $in_progress_tasks; ?></strong>
                            </div>
                            <div class="donut-legend-item">
                                <span><span class="donut-legend-dot" style="background: #8b5cf6;"></span> Menunggu</span>
                                <strong><?php echo $pending_tasks; ?></strong>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Upcoming Activities List -->
                <div class="upcoming-card">
                    <h4><i class="fa-solid fa-bolt-lightning text-warning"></i> Aktiviti Akan Datang</h4>
                    <div class="upcoming-list">
                        <?php if (empty($upcoming_events)): ?>
                            <p style="font-size: 0.8rem; color: var(--text-muted); text-align: center; padding: 10px 0;">Tiada aktiviti akan datang.</p>
                        <?php else: ?>
                            <?php foreach ($upcoming_events as $ue): 
                                $ue_type = strtolower($ue['event_type'] ?? 'task');
                                $icon_color = '#0077b6';
                                $icon_class = 'fa-list-check';
                                $bg_icon = '#e0f2fe';
                                if ($ue_type === 'meeting') { $icon_color = '#0284c7'; $icon_class = 'fa-video'; $bg_icon = '#e0f2fe'; }
                                elseif ($ue_type === 'kursus') { $icon_color = '#9333ea'; $icon_class = 'fa-graduation-cap'; $bg_icon = '#f3e8ff'; }
                                elseif ($ue_type === 'leave') { $icon_color = '#d97706'; $icon_class = 'fa-umbrella-beach'; $bg_icon = '#fef3c7'; }
                                elseif ($ue_type === 'time_off' || $ue_type === 'timeoff') { $icon_color = '#4338ca'; $icon_class = 'fa-hourglass-start'; $bg_icon = '#e0e7ff'; }
                            ?>
                                <div class="upcoming-item">
                                    <div class="upcoming-icon" style="background: <?php echo $bg_icon; ?>; color: <?php echo $icon_color; ?>;">
                                        <i class="fa-solid <?php echo $icon_class; ?>"></i>
                                    </div>
                                    <div class="upcoming-info">
                                        <h5><?php echo htmlspecialchars($ue['title']); ?></h5>
                                        <p><?php echo date('d M Y, h:i A', strtotime($ue['start_at'])); ?></p>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

            </div>

            <!-- Right Main Calendar -->
            <div class="main-calendar-box">

                <!-- Controls Bar -->
                <div class="main-cal-controls">
                    <div class="cal-nav-group">
                        <span class="cal-title-header" id="calMonthTitle">Ogos 2026</span>
                        <div style="display: flex; gap: 4px;">
                            <button class="mini-cal-btn" onclick="prevMainCalendar()"><i class="fa-solid fa-chevron-left"></i></button>
                            <button class="mini-cal-btn" onclick="nextMainCalendar()"><i class="fa-solid fa-chevron-right"></i></button>
                            <button class="cal-btn-pill" onclick="goToToday()">Hari Ini</button>
                        </div>
                    </div>

                    <div class="view-switcher-group">
                        <button class="view-btn active" id="viewMonthBtn" onclick="switchCalendarView('month')">Bulan</button>
                        <button class="view-btn" id="viewWeekBtn" onclick="switchCalendarView('week')">Minggu</button>
                        <button class="view-btn" id="viewDayBtn" onclick="switchCalendarView('day')">Hari</button>
                    </div>
                </div>

                <!-- VIEW 1: MONTH GRID VIEW -->
                <div id="monthViewContainer">
                    <table class="month-grid-table">
                        <thead>
                            <tr>
                                <th>Ahad</th>
                                <th>Isnin</th>
                                <th>Selasa</th>
                                <th>Rabu</th>
                                <th>Khamis</th>
                                <th>Jumaat</th>
                                <th>Sabtu</th>
                            </tr>
                        </thead>
                        <tbody id="monthGridBody">
                            <!-- Populated via JavaScript -->
                        </tbody>
                    </table>
                </div>

                <!-- VIEW 2: WEEK GRID VIEW -->
                <div id="weekViewContainer" style="display: none;">
                    <div class="week-view-container">
                        <div class="week-grid-header" id="weekGridHeader">
                            <div class="week-col-time">Masa</div>
                            <!-- Days populated via JS -->
                        </div>
                        <div class="week-grid-body" id="weekGridBody">
                            <div class="live-time-indicator" id="liveTimeIndicator" style="display: none;">
                                <div class="live-time-tag" id="liveTimeTag">10:30</div>
                            </div>
                            <!-- 08:00 to 18:00 rows -->
                            <?php for ($hour = 8; $hour <= 18; $hour++): 
                                $time_str = sprintf('%02d:00', $hour);
                                $display_time = date('h:i A', strtotime("$time_str"));
                            ?>
                                <div class="week-hour-row" data-hour="<?php echo $hour; ?>">
                                    <div class="hour-label"><?php echo $display_time; ?></div>
                                    <?php for ($d = 0; $d < 7; $d++): ?>
                                        <div class="hour-day-slot" data-day-index="<?php echo $d; ?>" data-hour="<?php echo $hour; ?>"></div>
                                    <?php endfor; ?>
                                </div>
                            <?php endfor; ?>
                        </div>
                    </div>
                </div>

                <!-- VIEW 3: DAY VIEW -->
                <div id="dayViewContainer" style="display: none;">
                    <div style="border: 1px solid rgba(0,119,182,0.14); border-radius: 16px; overflow: hidden; background: #fff; padding: 16px;">
                        <h4 id="dayViewColTitle" style="font-size: 1.1rem; font-weight: 850; color: var(--deep-blue); margin-bottom: 16px;">Hari Ini</h4>
                        <div style="display: flex; flex-direction: column; gap: 10px;">
                            <?php for ($hour = 8; $hour <= 18; $hour++): 
                                $time_str = sprintf('%02d:00', $hour);
                                $display_time = date('h:i A', strtotime("$time_str"));
                            ?>
                                <div style="display: grid; grid-template-columns: 80px 1fr; border-bottom: 1px solid rgba(0,119,182,0.08); padding-bottom: 8px;">
                                    <span style="font-size: 0.78rem; font-weight: 750; color: var(--text-muted);"><?php echo $display_time; ?></span>
                                    <div id="daySlot_<?php echo $hour; ?>" style="display: flex; flex-direction: column; gap: 4px;"></div>
                                </div>
                            <?php endfor; ?>
                        </div>
                    </div>
                </div>

            </div>

        </div>

    </main>

    <!-- ================= UNIVERSAL COMPOSER MODAL (Grouped by Category) ================= -->
    <div class="modal-overlay" id="addEventModal">
        <div class="modal-card">
            <div class="modal-header">
                <div>
                    <h3><i class="fa-solid fa-circle-plus text-primary mr-1"></i> Tambah ke Jadual</h3>
                    <p style="font-size: 0.78rem; color: var(--text-muted); margin-top: 2px;">Pilih kategori dan lengkapkan butiran anda.</p>
                </div>
                <button style="background: none; border: none; font-size: 1.2rem; cursor: pointer;" onclick="closeAddEventModal()"><i class="fa-solid fa-xmark"></i></button>
            </div>

            <!-- Category Switcher Navigation Tabs -->
            <div style="padding: 14px 24px 0;">
                <div class="composer-category-nav">
                    <button type="button" class="cat-nav-btn active" data-cat="task" onclick="switchModalCategory('task')">
                        <i class="fa-solid fa-list-check"></i>
                        <span>My Task</span>
                    </button>
                    <button type="button" class="cat-nav-btn" data-cat="leave" onclick="switchModalCategory('leave')">
                        <i class="fa-solid fa-umbrella-beach"></i>
                        <span>Cuti / Time Off</span>
                    </button>
                    <button type="button" class="cat-nav-btn" data-cat="meeting" onclick="switchModalCategory('meeting')">
                        <i class="fa-solid fa-video"></i>
                        <span>Mesyuarat</span>
                    </button>
                    <button type="button" class="cat-nav-btn" data-cat="kursus" onclick="switchModalCategory('kursus')">
                        <i class="fa-solid fa-graduation-cap"></i>
                        <span>Kursus</span>
                    </button>
                </div>
            </div>

            <form action="my_schedule.php" method="POST">
                <input type="hidden" name="action" value="create_universal">
                <input type="hidden" name="category_tab" id="modalCategoryTab" value="task">

                <div class="modal-body">
                    
                    <!-- ================= 1. MY TASK FORM FIELDS ================= -->
                    <div id="formSection_task" class="category-form-section">
                        <input type="hidden" name="task_priority" id="taskPriorityInput" value="medium">
                        
                        <div class="form-group">
                            <label>Task Name *</label>
                            <input type="text" name="task_title" class="form-control" placeholder="Contoh: Sediakan laporan bulanan">
                        </div>

                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                            <div class="form-group">
                                <label>Project</label>
                                <select name="task_project" class="form-control">
                                    <option value="">-- Pilih Projek --</option>
                                    <option value="Projek Pengurusan Fail">Projek Pengurusan Fail</option>
                                    <option value="Sistem Surat & Draf">Sistem Surat & Draf</option>
                                    <option value="Latihan & Pembangunan">Latihan & Pembangunan</option>
                                    <option value="Operasi Pejabat">Operasi Pejabat</option>
                                    <option value="Audit & Akaun">Audit & Akaun</option>
                                    <option value="Teknologi Maklumat">Teknologi Maklumat</option>
                                    <option value="Lain-lain">Lain-lain</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Category</label>
                                <select name="task_category" class="form-control">
                                    <option value="">-- Pilih Kategori --</option>
                                    <option value="Laporan">Laporan</option>
                                    <option value="Dokumentasi">Dokumentasi</option>
                                    <option value="Semakan">Semakan</option>
                                    <option value="Kewangan">Kewangan</option>
                                    <option value="Mesyuarat">Mesyuarat</option>
                                    <option value="Sokongan">Sokongan</option>
                                    <option value="Operasi">Operasi</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label>Due Date</label>
                            <input type="date" name="task_due_date" class="form-control" value="<?php echo date('Y-m-d', strtotime('+1 day')); ?>">
                        </div>

                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                            <div class="form-group">
                                <label>Start Date</label>
                                <input type="date" name="task_start_date" id="schTaskStart" class="form-control" value="<?php echo date('Y-m-d'); ?>" onchange="calcSchManday()">
                            </div>
                            <div class="form-group">
                                <label>End Date</label>
                                <input type="date" name="task_end_date" id="schTaskEnd" class="form-control" value="<?php echo date('Y-m-d', strtotime('+1 day')); ?>" onchange="calcSchManday()">
                            </div>
                        </div>

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

                        <div style="display: flex; align-items: center; justify-content: space-between; background: rgba(0, 119, 182, 0.06); padding: 10px 14px; border-radius: 12px;">
                            <span style="font-size: 0.82rem; font-weight: 750; color: var(--deep-blue);"><i class="fa-solid fa-calculator text-primary mr-2"></i> Tempoh Masa (Manday):</span>
                            <span id="schMandayBadge" style="background: #7c3aed; color: #fff; padding: 3px 12px; border-radius: 999px; font-size: 0.78rem; font-weight: 850;">1 Day</span>
                        </div>

                        <div class="form-group">
                            <label>Priority Status</label>
                            <div class="priority-options">
                                <div class="priority-opt" data-val="low" onclick="setSchPriority('low')">Low</div>
                                <div class="priority-opt active" data-val="medium" onclick="setSchPriority('medium')">Medium</div>
                                <div class="priority-opt" data-val="high" onclick="setSchPriority('high')">High</div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label>Remark</label>
                            <textarea name="task_remark" class="form-control" rows="2" placeholder="Masukkan catatan tugasan..."></textarea>
                        </div>
                    </div>

                    <!-- ================= 2. MY CUTI & TIME OFF FORM FIELDS ================= -->
                    <div id="formSection_leave" class="category-form-section" style="display: none;">
                        <input type="hidden" name="leave_sub_type" id="schLeaveSubType" value="leave">

                        <div class="type-selector-grid">
                            <div class="type-card-opt active" id="schOptLeave" onclick="selectSchLeaveType('leave')">
                                <div class="type-icon-box"><i class="fa-solid fa-umbrella-beach"></i></div>
                                <div>
                                    <strong style="font-size: 0.84rem;">Cuti Rehat</strong>
                                    <span style="font-size: 0.72rem; color: var(--text-muted);">Sepenuh Hari</span>
                                </div>
                            </div>
                            <div class="type-card-opt" id="schOptTimeOff" onclick="selectSchLeaveType('time_off')">
                                <div class="type-icon-box"><i class="fa-solid fa-hourglass-start"></i></div>
                                <div>
                                    <strong style="font-size: 0.84rem;">Time Off</strong>
                                    <span style="font-size: 0.72rem; color: var(--text-muted);">Beberapa Jam</span>
                                </div>
                            </div>
                        </div>

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

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

                        <div class="form-group">
                            <label>Sebab Permohonan</label>
                            <textarea name="leave_reason" id="schLeaveReason" class="form-control" rows="2" placeholder="Contoh: Urusan keluarga"></textarea>
                        </div>

                        <div style="display: flex; align-items: center; gap: 10px; background: rgba(124, 58, 237, 0.06); padding: 10px 14px; border-radius: 12px; border: 1px solid rgba(124, 58, 237, 0.12);">
                            <input type="checkbox" name="leave_notify_all" id="schNotifyAll" checked style="width: 18px; height: 18px; accent-color: #7c3aed;">
                            <label for="schNotifyAll" 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>

                    <!-- ================= 3 & 4. MEETING & KURSUS FORM FIELDS ================= -->
                    <div id="formSection_meeting" class="category-form-section" style="display: none;">
                        <div class="form-group">
                            <label id="meetTitleLabel">Tajuk Mesyuarat *</label>
                            <input type="text" name="meet_title" id="meetTitleInput" class="form-control" placeholder="Contoh: Mesyuarat Penyelarasan Sistem">
                        </div>

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

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

                        <div class="form-group">
                            <label>Lokasi / Pautan Maya</label>
                            <input type="text" name="meet_location" class="form-control" placeholder="Contoh: Bilik Mesyuarat Utama / Google Meet URL">
                        </div>

                        <?php if (!empty($dept_members)): ?>
                            <div class="form-group" id="meetParticipantsPickerGroup">
                                <label>Pilih Peserta Bahagian</label>
                                <div style="max-height: 110px; overflow-y: auto; border: 1px solid rgba(0,119,182,0.15); border-radius: 12px; padding: 8px 12px; background: rgba(240, 249, 255, 0.40); display: flex; flex-direction: column; gap: 6px;">
                                    <?php foreach ($dept_members as $dm): ?>
                                        <label style="display: flex; align-items: center; gap: 8px; font-size: 0.8rem; cursor: pointer;">
                                            <input type="checkbox" name="meet_participants[]" value="<?php echo htmlspecialchars($dm['fullname']); ?>" style="accent-color: var(--primary);">
                                            <span><?php echo htmlspecialchars($dm['fullname']); ?> (<?php echo htmlspecialchars($dm['position'] ?: 'Staf'); ?>)</span>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <div class="form-group" id="meetExtParticipantsGroup">
                            <label>Peserta Luar (Pilihan)</label>
                            <input type="text" name="meet_ext_participants" class="form-control" placeholder="Contoh: En. Ahmad (JPS), Pn. Sarah">
                        </div>

                        <div class="form-group">
                            <label>Catatan / Agenda</label>
                            <textarea name="meet_notes" class="form-control" rows="2" placeholder="Masukkan agenda atau catatan ringkas..."></textarea>
                        </div>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="cal-btn-pill" style="padding: 10px 18px;" onclick="closeAddEventModal()">Batal</button>
                    <button type="submit" class="btn-save" id="btnUniversalSubmit">SIMPAN TUGASAN</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const allEvents = <?php echo json_encode($events, JSON_UNESCAPED_UNICODE); ?>;
        let activeDate = new Date();
        let miniCalDate = new Date();
        let currentView = 'month';

        const monthNamesMalay = [
            "Januari", "Februari", "Mac", "April", "Mei", "Jun", 
            "Julai", "Ogos", "September", "Oktober", "November", "Disember"
        ];

        function renderMiniCalendar() {
            const year = miniCalDate.getFullYear();
            const month = miniCalDate.getMonth();

            document.getElementById('miniCalTitle').innerText = `${monthNamesMalay[month]} ${year}`;

            const grid = document.getElementById('miniCalGrid');
            const existingCells = grid.querySelectorAll('.mini-cal-cell');
            existingCells.forEach(cell => cell.remove());

            const firstDayIndex = new Date(year, month, 1).getDay();
            const daysInMonth = new Date(year, month + 1, 0).getDate();
            const today = new Date();

            for (let i = 0; i < firstDayIndex; i++) {
                const emptyCell = document.createElement('div');
                emptyCell.className = 'mini-cal-cell';
                emptyCell.style.opacity = '0.3';
                grid.appendChild(emptyCell);
            }

            for (let day = 1; day <= daysInMonth; day++) {
                const cell = document.createElement('div');
                cell.className = 'mini-cal-cell';
                cell.innerText = day;

                const isToday = (today.getFullYear() === year && today.getMonth() === month && today.getDate() === day);
                if (isToday) cell.classList.add('today');

                cell.onclick = () => {
                    activeDate = new Date(year, month, day);
                    renderCalendar();
                };

                grid.appendChild(cell);
            }
        }

        function prevMiniMonth() {
            miniCalDate.setMonth(miniCalDate.getMonth() - 1);
            renderMiniCalendar();
        }

        function nextMiniMonth() {
            miniCalDate.setMonth(miniCalDate.getMonth() + 1);
            renderMiniCalendar();
        }

        function renderCalendar() {
            const year = activeDate.getFullYear();
            const month = activeDate.getMonth();

            document.getElementById('calMonthTitle').innerText = `${monthNamesMalay[month]} ${year}`;

            if (currentView === 'month') {
                renderMonthView(year, month);
            } else if (currentView === 'week') {
                renderWeekView();
            } else if (currentView === 'day') {
                renderDayView();
            }
        }

        function renderMonthView(year, month) {
            const tbody = document.getElementById('monthGridBody');
            tbody.innerHTML = '';

            const firstDayIndex = new Date(year, month, 1).getDay();
            const daysInMonth = new Date(year, month + 1, 0).getDate();
            const prevMonthDays = new Date(year, month, 0).getDate();

            let dayCount = 1;
            let nextMonthDay = 1;
            const today = new Date();

            for (let row = 0; row < 6; row++) {
                const tr = document.createElement('tr');

                for (let col = 0; col < 7; col++) {
                    const td = document.createElement('td');
                    td.className = 'month-cell';

                    const cellIndex = row * 7 + col;
                    let displayDay = 0;
                    let isOtherMonth = false;
                    let dateStr = '';

                    if (cellIndex < firstDayIndex) {
                        displayDay = prevMonthDays - firstDayIndex + cellIndex + 1;
                        isOtherMonth = true;
                        td.classList.add('is-other-month');
                        const prevMonth = month === 0 ? 11 : month - 1;
                        const prevYear = month === 0 ? year - 1 : year;
                        dateStr = `${prevYear}-${String(prevMonth+1).padStart(2,'0')}-${String(displayDay).padStart(2,'0')}`;
                    } else if (dayCount <= daysInMonth) {
                        displayDay = dayCount;
                        dateStr = `${year}-${String(month+1).padStart(2,'0')}-${String(displayDay).padStart(2,'0')}`;
                        if (today.getFullYear() === year && today.getMonth() === month && today.getDate() === displayDay) {
                            td.classList.add('is-today');
                        }
                        dayCount++;
                    } else {
                        displayDay = nextMonthDay;
                        isOtherMonth = true;
                        td.classList.add('is-other-month');
                        const nextMonth = month === 11 ? 0 : month + 1;
                        const nextYear = month === 11 ? year + 1 : year;
                        dateStr = `${nextYear}-${String(nextMonth+1).padStart(2,'0')}-${String(displayDay).padStart(2,'0')}`;
                        nextMonthDay++;
                    }

                    if (displayDay > 0) {
                        const matchingEvents = allEvents.filter(ev => {
                            return ev.start_at && ev.start_at.startsWith(dateStr);
                        });

                        let eventsHtml = '';
                        matchingEvents.forEach(ev => {
                            const type = (ev.event_type || 'task').toLowerCase();
                            let pillClass = 'pill-task';
                            if (type === 'meeting') pillClass = 'pill-meeting';
                            else if (type === 'kursus') pillClass = 'pill-kursus';
                            else if (type === 'leave' || type === 'cuti') pillClass = 'pill-leave';
                            else if (type === 'time_off' || type === 'timeoff') pillClass = 'pill-timeoff';

                            eventsHtml += `<div class="cal-event-pill ${pillClass}" title="${escapeHtml(ev.title)}">${escapeHtml(ev.title)}</div>`;
                        });

                        td.innerHTML = `
                            <div class="month-cell-num">${displayDay}</div>
                            <div class="month-cell-events">${eventsHtml}</div>
                        `;
                    }
                    tr.appendChild(td);
                }
                tbody.appendChild(tr);
                if (dayCount > daysInMonth && row >= 4) break;
            }
        }

        function renderWeekView() {
            const headerRow = document.getElementById('weekGridHeader');
            const dayNames = ["Ahad", "Isnin", "Selasa", "Rabu", "Khamis", "Jumaat", "Sabtu"];

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

            const existingHeaders = headerRow.querySelectorAll('.week-col-day');
            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 = `week-col-day ${isToday ? 'active-today' : ''}`;
                colHeader.innerHTML = `${dayNames[i]} <strong style="font-size: 0.95rem;">${d.getDate()}</strong>`;
                headerRow.appendChild(colHeader);
            }

            const slots = document.querySelectorAll('.hour-day-slot');
            slots.forEach(slot => {
                slot.innerHTML = '';
                const dayIndex = parseInt(slot.getAttribute('data-day-index'));
                const hour = parseInt(slot.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 matchingEvents = allEvents.filter(ev => {
                    if (!ev.start_at || !ev.start_at.startsWith(targetDateStr)) return false;
                    const evHour = new Date(ev.start_at).getHours();
                    return evHour === hour;
                });

                matchingEvents.forEach(ev => {
                    const type = (ev.event_type || 'task').toLowerCase();
                    let pillClass = 'pill-task';
                    if (type === 'meeting') pillClass = 'pill-meeting';
                    else if (type === 'kursus') pillClass = 'pill-kursus';
                    else if (type === 'leave' || type === 'cuti') pillClass = 'pill-leave';
                    else if (type === 'time_off' || type === 'timeoff') pillClass = 'pill-timeoff';

                    const pill = document.createElement('div');
                    pill.className = `cal-event-pill ${pillClass}`;
                    pill.innerText = ev.title;
                    slot.appendChild(pill);
                });
            });

            updateLiveTimeIndicator();
        }

        function renderDayView() {
            const today = new Date();
            const isToday = (activeDate.toDateString() === today.toDateString());
            document.getElementById('dayViewColTitle').innerHTML = `${monthNamesMalay[activeDate.getMonth()]} ${activeDate.getDate()}, ${activeDate.getFullYear()}`;

            const targetDateStr = `${activeDate.getFullYear()}-${String(activeDate.getMonth()+1).padStart(2,'0')}-${String(activeDate.getDate()).padStart(2,'0')}`;

            for (let hour = 8; hour <= 18; hour++) {
                const slot = document.getElementById(`daySlot_${hour}`);
                if (!slot) continue;
                slot.innerHTML = '';

                const matchingEvents = allEvents.filter(ev => {
                    if (!ev.start_at || !ev.start_at.startsWith(targetDateStr)) return false;
                    const evHour = new Date(ev.start_at).getHours();
                    return evHour === hour;
                });

                matchingEvents.forEach(ev => {
                    const pill = document.createElement('div');
                    pill.className = 'cal-event-pill pill-task';
                    pill.style.padding = '8px 12px';
                    pill.innerHTML = `<strong>${escapeHtml(ev.title)}</strong> - <span style="font-size: 0.72rem;">${escapeHtml(ev.location || '')}</span>`;
                    slot.appendChild(pill);
                });
            }
        }

        function updateLiveTimeIndicator() {
            const now = new Date();
            const currentHour = now.getHours();
            const currentMin = now.getMinutes();

            const indicator = document.getElementById('liveTimeIndicator');
            const tag = document.getElementById('liveTimeTag');
            if (!indicator || !tag) return;

            if (currentHour >= 8 && currentHour <= 18) {
                indicator.style.display = 'block';
                const totalMinutes = (currentHour - 8) * 60 + currentMin;
                const totalSlotsMinutes = 11 * 60;
                const topPercent = (totalMinutes / totalSlotsMinutes) * 100;
                indicator.style.top = `${topPercent}%`;
                tag.innerText = `${String(currentHour).padStart(2,'0')}:${String(currentMin).padStart(2,'0')}`;
            } else {
                indicator.style.display = 'none';
            }
        }

        function switchCalendarView(view) {
            currentView = view;
            document.querySelectorAll('.view-btn').forEach(b => b.classList.remove('active'));

            document.getElementById('monthViewContainer').style.display = (view === 'month') ? 'block' : 'none';
            document.getElementById('weekViewContainer').style.display = (view === 'week') ? 'block' : 'none';
            document.getElementById('dayViewContainer').style.display = (view === 'day') ? 'block' : 'none';

            if (view === 'month') document.getElementById('viewMonthBtn').classList.add('active');
            else if (view === 'week') document.getElementById('viewWeekBtn').classList.add('active');
            else if (view === 'day') document.getElementById('viewDayBtn').classList.add('active');

            renderCalendar();
        }

        function prevMainCalendar() {
            if (currentView === 'month') {
                activeDate.setMonth(activeDate.getMonth() - 1);
            } else if (currentView === 'week') {
                activeDate.setDate(activeDate.getDate() - 7);
            } else {
                activeDate.setDate(activeDate.getDate() - 1);
            }
            renderCalendar();
        }

        function nextMainCalendar() {
            if (currentView === 'month') {
                activeDate.setMonth(activeDate.getMonth() + 1);
            } else if (currentView === 'week') {
                activeDate.setDate(activeDate.getDate() + 7);
            } else {
                activeDate.setDate(activeDate.getDate() + 1);
            }
            renderCalendar();
        }

        function goToToday() {
            activeDate = new Date();
            miniCalDate = new Date();
            renderCalendar();
            renderMiniCalendar();
        }

        /* Modal Category Switcher */
        function switchModalCategory(cat) {
            document.getElementById('modalCategoryTab').value = cat;

            document.querySelectorAll('.cat-nav-btn').forEach(btn => {
                btn.classList.toggle('active', btn.getAttribute('data-cat') === cat);
            });

            document.getElementById('formSection_task').style.display = (cat === 'task') ? 'block' : 'none';
            document.getElementById('formSection_leave').style.display = (cat === 'leave') ? 'block' : 'none';
            document.getElementById('formSection_meeting').style.display = (cat === 'meeting' || cat === 'kursus') ? 'block' : 'none';

            const submitBtn = document.getElementById('btnUniversalSubmit');

            if (cat === 'task') {
                submitBtn.innerText = 'SIMPAN TUGASAN';
            } else if (cat === 'leave') {
                const subType = document.getElementById('schLeaveSubType').value;
                submitBtn.innerText = subType === 'leave' ? 'SIMPAN CUTI REHAT' : 'SIMPAN TIME OFF';
            } else if (cat === 'meeting') {
                document.getElementById('meetTitleLabel').innerText = 'Tajuk Mesyuarat *';
                document.getElementById('meetTitleInput').placeholder = 'Contoh: Mesyuarat Penyelarasan Sistem';
                submitBtn.innerText = 'SIMPAN MESYUARAT';
            } else if (cat === 'kursus') {
                document.getElementById('meetTitleLabel').innerText = 'Tajuk Kursus / Latihan *';
                document.getElementById('meetTitleInput').placeholder = 'Contoh: Kursus Keselamatan Siber & ICT';
                submitBtn.innerText = 'SIMPAN KURSUS';
            }
        }

        function setSchPriority(val) {
            document.getElementById('taskPriorityInput').value = val;
            document.querySelectorAll('.priority-opt').forEach(opt => {
                opt.classList.toggle('active', opt.getAttribute('data-val') === val);
            });
        }

        function calcSchManday() {
            const startVal = document.getElementById('schTaskStart').value;
            const endVal = document.getElementById('schTaskEnd').value;
            if (startVal && endVal) {
                const s = new Date(startVal);
                const e = new Date(endVal);
                const diffTime = Math.abs(e - s);
                const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
                const days = diffDays < 1 ? 1 : diffDays;
                document.getElementById('schMandayBadge').innerText = days + (days === 1 ? ' Day' : ' Days');
            }
        }

        function selectSchLeaveType(type) {
            document.getElementById('schLeaveSubType').value = type;
            const isLeave = (type === 'leave');

            document.getElementById('schOptLeave').classList.toggle('active', isLeave);
            document.getElementById('schOptTimeOff').classList.toggle('active', !isLeave);

            const timeFields = document.getElementById('schLeaveTimeRow');
            const reasonInput = document.getElementById('schLeaveReason');
            const submitBtn = document.getElementById('btnUniversalSubmit');

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

        function openAddEventModal() {
            document.getElementById('addEventModal').classList.add('active');
            switchModalCategory('task');
        }

        function closeAddEventModal() {
            document.getElementById('addEventModal').classList.remove('active');
        }

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

        // Live Search Filter
        document.getElementById('scheduleSearchInput').addEventListener('input', function(e) {
            const query = e.target.value.toLowerCase();
            document.querySelectorAll('.cal-event-pill, .upcoming-item').forEach(item => {
                const text = item.innerText.toLowerCase();
                item.style.display = text.includes(query) ? '' : 'none';
            });
        });

        document.addEventListener('DOMContentLoaded', () => {
            renderMiniCalendar();
            renderCalendar();
            setInterval(updateLiveTimeIndicator, 60000);
        });

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