<?php
require_once 'auth.php';
require_once 'db.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_task') {
        $title = trim((string) ($_POST['title'] ?? ''));
        $project = trim((string) ($_POST['project'] ?? ''));
        $category = trim((string) ($_POST['category'] ?? ''));
        $due_date = trim((string) ($_POST['due_date'] ?? ''));
        $start_date = trim((string) ($_POST['start_date'] ?? ''));
        $end_date = trim((string) ($_POST['end_date'] ?? ''));
        $start_time = trim((string) ($_POST['start_time'] ?? '09:00'));
        $end_time = trim((string) ($_POST['end_time'] ?? '11:00'));
        $priority = strtolower(trim((string) ($_POST['priority'] ?? 'medium')));
        $priority = in_array($priority, ['low', 'medium', 'high'], true) ? $priority : 'medium';
        $remark = trim((string) ($_POST['description'] ?? ''));
        $initial_stage = trim((string) ($_POST['stage'] ?? 'dump'));
        $initial_status = ($initial_stage === 'ongoing') ? 'In Progress' : (($initial_stage === 'completed') ? 'Completed' : 'Pending');

        if ($title !== '') {
            $start_at = !empty($start_date) ? "$start_date $start_time:00" : date('Y-m-d 09:00:00');
            $end_at = !empty($end_date) ? "$end_date $end_time:00" : "$start_date 11:00:00";
            $due = !empty($due_date) ? $due_date : (!empty($end_date) ? $end_date : date('Y-m-d'));

            $start_ts = strtotime($start_at);
            $end_ts = strtotime($end_at);
            $diff_days = round(($end_ts - $start_ts) / 86400);
            $manday = max(1, (int)$diff_days);

            $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', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
            );

            if ($stmt) {
                mysqli_stmt_bind_param($stmt, 'issssssissii', $user_id, $title, $combined_desc, $category, $start_at, $end_at, $due, $manday, $priority, $initial_status, $user_id, $user_id);
                if (mysqli_stmt_execute($stmt)) {
                    $flash_msg = 'Tugasan baharu berjaya dicipta!';
                    $flash_type = 'success';
                }
            }
        }
    } elseif ($action === 'update_task') {
        $task_id = (int) ($_POST['task_id'] ?? 0);
        $title = trim((string) ($_POST['title'] ?? ''));
        $project = trim((string) ($_POST['project'] ?? ''));
        $category = trim((string) ($_POST['category'] ?? ''));
        $due_date = trim((string) ($_POST['due_date'] ?? ''));
        $start_date = trim((string) ($_POST['start_date'] ?? ''));
        $end_date = trim((string) ($_POST['end_date'] ?? ''));
        $start_time = trim((string) ($_POST['start_time'] ?? '09:00'));
        $end_time = trim((string) ($_POST['end_time'] ?? '11:00'));
        $priority = strtolower(trim((string) ($_POST['priority'] ?? 'medium')));
        $priority = in_array($priority, ['low', 'medium', 'high'], true) ? $priority : 'medium';
        $status = trim((string) ($_POST['status'] ?? 'Pending'));
        $remark = trim((string) ($_POST['description'] ?? ''));

        if ($task_id > 0 && $title !== '') {
            $start_at = !empty($start_date) ? "$start_date $start_time:00" : date('Y-m-d 09:00:00');
            $end_at = !empty($end_date) ? "$end_date $end_time:00" : "$start_date 11:00:00";
            $due = !empty($due_date) ? $due_date : (!empty($end_date) ? $end_date : date('Y-m-d'));

            $start_ts = strtotime($start_at);
            $end_ts = strtotime($end_at);
            $diff_days = round(($end_ts - $start_ts) / 86400);
            $manday = max(1, (int)$diff_days);

            $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,
                "UPDATE calendar_events 
                 SET title = ?, description = ?, location = ?, start_at = ?, end_at = ?, due_date = ?, manday = ?, priority = ?, status = ?, updated_by = ?, updated_at = NOW() 
                 WHERE id = ? AND user_id = ? AND event_type = 'task'"
            );

            if ($stmt) {
                mysqli_stmt_bind_param($stmt, 'ssssssissiii', $title, $combined_desc, $category, $start_at, $end_at, $due, $manday, $priority, $status, $user_id, $task_id, $user_id);
                if (mysqli_stmt_execute($stmt)) {
                    $flash_msg = 'Tugasan berjaya dikemaskini!';
                    $flash_type = 'success';
                }
            }
        }
    } elseif ($action === 'advance_stage' || $action === 'toggle_status') {
        $task_id = (int) ($_POST['task_id'] ?? 0);
        $next_status = trim((string) ($_POST['next_status'] ?? ''));

        $allowed_statuses = ['Pending', 'In Progress', 'Completed'];
        if ($task_id > 0 && in_array($next_status, $allowed_statuses, true)) {
            $stmt = mysqli_prepare($conn, "UPDATE calendar_events SET status = ?, updated_by = ?, updated_at = NOW() WHERE id = ? AND user_id = ? AND event_type = 'task'");
            if ($stmt) {
                mysqli_stmt_bind_param($stmt, 'siii', $next_status, $user_id, $task_id, $user_id);
                if (mysqli_stmt_execute($stmt)) {
                    $status_label = ($next_status === 'In Progress') ? 'Dalam Proses (On Going)' : (($next_status === 'Completed') ? 'Selesai (Completed)' : 'Menunggu (Dump)');
                    $flash_msg = "Tugasan dipindahkan ke: $status_label";
                    $flash_type = 'success';
                }
            }
        }
    } elseif ($action === 'delete_task') {
        $task_id = (int) ($_POST['task_id'] ?? 0);
        if ($task_id > 0) {
            $stmt = mysqli_prepare($conn, "DELETE FROM calendar_events WHERE id = ? AND user_id = ? AND event_type = 'task'");
            if ($stmt) {
                mysqli_stmt_bind_param($stmt, 'ii', $task_id, $user_id);
                if (mysqli_stmt_execute($stmt)) {
                    $flash_msg = 'Tugasan berjaya dipadam.';
                    $flash_type = 'success';
                }
            }
        }
    }
}

// Fetch user tasks ONLY
$sql = "SELECT * FROM calendar_events WHERE user_id = ? AND event_type = 'task' AND deleted_at IS NULL ORDER BY created_at DESC, 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);
$tasks = $result ? mysqli_fetch_all($result, MYSQLI_ASSOC) : [];

$dump_tasks = [];
$ongoing_tasks = [];
$completed_tasks = [];

foreach ($tasks as $t) {
    $st = strtolower(trim($t['status'] ?? ''));
    if ($st === 'completed' || $st === 'selesai' || $st === 'done') {
        $completed_tasks[] = $t;
    } elseif ($st === 'in progress' || $st === 'dalam proses' || $st === 'ongoing') {
        $ongoing_tasks[] = $t;
    } else {
        $dump_tasks[] = $t;
    }
}

$total_tasks = count($tasks);
$count_dump = count($dump_tasks);
$count_ongoing = count($ongoing_tasks);
$count_completed = count($completed_tasks);
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Task | 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 Mode 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-task {
            background: linear-gradient(135deg, #0d9488, #0f766e);
            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(13, 148, 136, 0.30); transition: all 0.2s ease;
        }
        .btn-add-task:hover { transform: translateY(-2px); box-shadow: 0 12px 25px rgba(13, 148, 136, 0.40); }

        /* ================= 3-STAGE WORKFLOW TABS (APP FLOW) ================= */
        .stage-nav-container {
            display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 20px;
        }
        .stage-tab-btn {
            background: var(--glass-strong); border: 1.5px solid var(--border); border-radius: 18px;
            padding: 16px 20px; cursor: pointer; display: flex; align-items: center; justify-content: space-between;
            transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); box-shadow: var(--shadow-card);
            text-align: left;
        }
        .stage-tab-btn:hover { transform: translateY(-2px); border-color: var(--primary); }
        .stage-tab-btn.active {
            background: #fff; border-color: var(--primary); box-shadow: 0 10px 25px rgba(0, 119, 182, 0.16);
        }
        .stage-tab-left { display: flex; align-items: center; gap: 14px; }
        .stage-icon-box {
            width: 44px; height: 44px; border-radius: 12px; display: flex; align-items: center; justify-content: center;
            font-size: 1.25rem; flex-shrink: 0;
        }
        .stage-tab-btn[data-stage="dump"] .stage-icon-box { background: #e0e7ff; color: #4338ca; }
        .stage-tab-btn[data-stage="ongoing"] .stage-icon-box { background: #fef3c7; color: #d97706; }
        .stage-tab-btn[data-stage="completed"] .stage-icon-box { background: #d1fae5; color: #059669; }
        
        .stage-tab-btn.active[data-stage="dump"] { border-left: 5px solid #4338ca; }
        .stage-tab-btn.active[data-stage="ongoing"] { border-left: 5px solid #d97706; }
        .stage-tab-btn.active[data-stage="completed"] { border-left: 5px solid #059669; }

        .stage-title-text strong { display: block; font-size: 0.95rem; font-weight: 850; color: var(--deep-blue); }
        .stage-title-text span { font-size: 0.74rem; color: var(--text-muted); font-weight: 600; }
        .stage-count-badge {
            font-size: 1.15rem; font-weight: 900; padding: 4px 14px; border-radius: 999px;
            background: rgba(0, 119, 182, 0.08); color: var(--deep-blue);
        }
        .stage-tab-btn.active .stage-count-badge { background: var(--deep-blue); color: #fff; }

        /* Search & Filter Toolbar */
        .task-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;
        }
        .task-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;
        }
        .task-search-box input {
            border: none; outline: none; width: 100%; font-size: 0.85rem; color: var(--text-main); font-weight: 600;
        }
        .priority-filter-pills { display: flex; gap: 6px; align-items: center; }
        .prio-pill-btn {
            border: 1px solid rgba(0, 119, 182, 0.16); 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;
        }
        .prio-pill-btn.active { background: var(--deep-blue); color: #fff; border-color: var(--deep-blue); }

        /* Modern World-Class Task Cards Grid */
        .task-grid-container {
            display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 20px;
        }
        .world-task-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-task-card:hover { transform: translateY(-3px); box-shadow: 0 18px 38px rgba(2, 62, 95, 0.10); border-color: rgba(0, 119, 182, 0.25); }
        
        .card-top-meta { display: flex; justify-content: space-between; align-items: center; }
        .card-priority-pill {
            font-size: 0.7rem; font-weight: 850; padding: 3px 10px; border-radius: 999px; text-transform: uppercase;
            letter-spacing: 0.04em;
        }
        .prio-high { background: #fee2e2; color: #dc2626; border: 1px solid #fca5a5; }
        .prio-medium { background: #fef3c7; color: #d97706; border: 1px solid #fde68a; }
        .prio-low { background: #e0f2fe; color: #0284c7; border: 1px solid #bae6fd; }

        .card-task-title {
            font-size: 1.05rem; font-weight: 850; color: var(--deep-blue); line-height: 1.35;
        }
        .card-task-title.completed-title {
            text-decoration: line-through; opacity: 0.65;
        }

        .card-tags-row { display: flex; flex-wrap: wrap; gap: 6px; }
        .card-meta-badge {
            font-size: 0.72rem; font-weight: 750; padding: 3px 10px; border-radius: 8px;
            display: inline-flex; align-items: center; gap: 5px;
        }
        .badge-project { background: #f1f5f9; color: #334155; }
        .badge-category { background: rgba(0, 119, 182, 0.08); color: var(--primary); }
        .badge-manday { background: #f5f3ff; color: #7c3aed; }
        .badge-duedate { background: #fff7ed; color: #c2410c; }
        .badge-duedate.urgent { background: #fef2f2; color: #b91c1c; font-weight: 850; }

        .card-desc-box {
            font-size: 0.82rem; color: #475569; background: #f8fafc; padding: 10px 14px;
            border-radius: 12px; line-height: 1.45; border: 1px solid rgba(0,0,0,0.04);
            white-space: pre-line;
        }

        .card-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-advance-stage {
            border: none; padding: 8px 16px; border-radius: 12px; font-size: 0.8rem; font-weight: 850;
            display: inline-flex; align-items: center; gap: 7px; cursor: pointer; transition: all 0.2s ease;
        }
        .btn-advance-dump { background: #e0e7ff; color: #4338ca; }
        .btn-advance-dump:hover { background: #4338ca; color: #fff; }
        .btn-advance-ongoing { background: #d1fae5; color: #059669; }
        .btn-advance-ongoing:hover { background: #059669; color: #fff; }
        .btn-advance-reopen { background: #f1f5f9; color: #475569; }
        .btn-advance-reopen:hover { background: #334155; color: #fff; }

        .btn-edit-action {
            background: rgba(0, 119, 182, 0.08); color: var(--primary); border: 1px solid rgba(0, 119, 182, 0.18);
            padding: 8px 12px; 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-action:hover { background: var(--primary); color: #fff; }

        /* ================= CALENDAR SECTION ================= */
        .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-task-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-task-card:hover { transform: translateY(-2px); box-shadow: 0 10px 24px rgba(0,0,0,0.12); z-index: 40 !important; }
        .task-theme-teal { background: #e6fffa; border-top: 3px solid #0d9488; }
        .task-theme-blue { background: #e0f2fe; border-top: 3px solid #0284c7; }
        .task-theme-orange { background: #fff7ed; border-top: 3px solid #ea580c; }
        .task-theme-purple { background: #f5f3ff; border-top: 3px solid #7c3aed; }
        .task-theme-rose { background: #fff1f2; border-top: 3px solid #e11d48; }

        /* Modal Overlay & Card */
        .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: 560px;
            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); }

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

        .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, #0d9488, #0f766e); 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_task.php'); ?>
        </ul>
    </aside>

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

        <!-- Top Bar matching Dashboard -->
        <div class="top-bar">
            <h2><i class="fa-solid fa-list-check"></i> My Task</h2>
            <?php renderTopBarUserMenu($conn, $role, 'my_task.php'); ?>
        </div>

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

        <!-- Master View Switcher & Add Task -->
        <div class="view-mode-bar">
            <div class="view-toggle-pills">
                <button class="view-pill-btn active" id="btnViewList" onclick="switchTaskMasterView('list')">
                    <i class="fa-solid fa-list-check"></i>
                    <span>Senarai Kad Tugasan (<?php echo $total_tasks; ?>)</span>
                </button>
                <button class="view-pill-btn" id="btnViewCalendar" onclick="switchTaskMasterView('calendar')">
                    <i class="fa-solid fa-calendar-days"></i>
                    <span>Paparan Kalendar</span>
                </button>
            </div>

            <button class="btn-add-task" onclick="openAddTaskModal()">
                <i class="fa-solid fa-plus"></i>
                <span>+ Cipta Task</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: 3-STAGE WORKFLOW & TASK LIST ================= -->
        <div id="taskListSection">
            
            <!-- 3 Stages Workflow Selector (Dump -> On Going -> Completed) -->
            <div class="stage-nav-container">
                <div class="stage-tab-btn active" data-stage="dump" onclick="selectTaskStage('dump')">
                    <div class="stage-tab-left">
                        <div class="stage-icon-box"><i class="fa-solid fa-inbox"></i></div>
                        <div class="stage-title-text">
                            <strong>Dump / Menunggu</strong>
                            <span>Tugasan belum dimulakan</span>
                        </div>
                    </div>
                    <span class="stage-count-badge"><?php echo $count_dump; ?></span>
                </div>

                <div class="stage-tab-btn" data-stage="ongoing" onclick="selectTaskStage('ongoing')">
                    <div class="stage-tab-left">
                        <div class="stage-icon-box"><i class="fa-solid fa-person-running"></i></div>
                        <div class="stage-title-text">
                            <strong>On Going</strong>
                            <span>Sedang aktif berjalan</span>
                        </div>
                    </div>
                    <span class="stage-count-badge"><?php echo $count_ongoing; ?></span>
                </div>

                <div class="stage-tab-btn" data-stage="completed" onclick="selectTaskStage('completed')">
                    <div class="stage-tab-left">
                        <div class="stage-icon-box"><i class="fa-solid fa-circle-check"></i></div>
                        <div class="stage-title-text">
                            <strong>Completed</strong>
                            <span>Telah siap diselesaikan</span>
                        </div>
                    </div>
                    <span class="stage-count-badge"><?php echo $count_completed; ?></span>
                </div>
            </div>

            <!-- Search & Priority Filter Toolbar -->
            <div class="task-toolbar">
                <div class="task-search-box">
                    <i class="fa-solid fa-magnifying-glass text-muted"></i>
                    <input type="text" id="taskSearchInput" placeholder="Cari nama tugasan, projek, atau catatan..." onkeyup="filterTasksLive()">
                </div>

                <div class="priority-filter-pills">
                    <span style="font-size: 0.76rem; font-weight: 800; color: var(--deep-blue); margin-right: 4px;">Keutamaan:</span>
                    <button class="prio-pill-btn active" data-prio="all" onclick="filterPriority('all', this)">Semua</button>
                    <button class="prio-pill-btn" data-prio="high" onclick="filterPriority('high', this)"><i class="fa-solid fa-fire text-danger mr-1"></i> High</button>
                    <button class="prio-pill-btn" data-prio="medium" onclick="filterPriority('medium', this)">Med</button>
                    <button class="prio-pill-btn" data-prio="low" onclick="filterPriority('low', this)">Low</button>
                </div>
            </div>

            <!-- Stage Task Grids -->
            <?php
            $renderStageGrid = function($stage_name, $stage_items, $is_active) {
            ?>
                <div class="task-stage-grid" id="grid_<?php echo $stage_name; ?>" style="<?php echo $is_active ? '' : 'display: none;'; ?>">
                    <?php if (empty($stage_items)): ?>
                        <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-clipboard-list" style="font-size: 3.2rem; color: var(--accent-teal); opacity: 0.35; margin-bottom: 12px;"></i>
                            <h3 style="font-size: 1.1rem; font-weight: 800; color: var(--deep-blue);">Tiada Tugasan di Peringkat Ini</h3>
                            <p style="font-size: 0.85rem; color: var(--text-muted); margin-top: 4px;">Klik "+ Cipta Task" untuk menambah tugasan baharu anda.</p>
                        </div>
                    <?php else: ?>
                        <div class="task-grid-container">
                            <?php foreach ($stage_items as $t): 
                                $prio = strtolower(trim($t['priority'] ?? 'medium'));
                                $prio_class = ($prio === 'high') ? 'prio-high' : (($prio === 'low') ? 'prio-low' : 'prio-medium');
                                
                                $desc = $t['description'] ?? '';
                                $project = '';
                                if (preg_match('/Projek:\s*([^\|\n]+)/', $desc, $m)) {
                                    $project = trim($m[1]);
                                }
                                $clean_desc = trim(preg_replace('/Projek:[^\|\n]+\s*\|\s*Kategori:[^\|\n]+\s*/', '', $desc));
                                $category = $t['location'] ?: 'Umum';

                                $due_str = !empty($t['due_date']) ? $t['due_date'] : $t['start_at'];
                                $is_urgent = false;
                                if ($due_str) {
                                    $due_time = strtotime($due_str);
                                    $is_urgent = ($due_time <= strtotime('+1 day'));
                                }
                            ?>
                                <div class="world-task-card" data-prio="<?php echo $prio; ?>" data-title="<?php echo htmlspecialchars(strtolower($t['title'] . ' ' . $desc . ' ' . $project)); ?>">
                                    <div class="card-top-meta">
                                        <span class="card-priority-pill <?php echo $prio_class; ?>">
                                            <i class="fa-solid fa-flag mr-1"></i> <?php echo strtoupper($prio); ?>
                                        </span>
                                        <span style="font-size: 0.75rem; font-weight: 750; color: var(--text-muted);">
                                            #<?php echo $t['id']; ?>
                                        </span>
                                    </div>

                                    <div class="card-task-title <?php echo ($stage_name === 'completed') ? 'completed-title' : ''; ?>">
                                        <?php echo htmlspecialchars($t['title']); ?>
                                    </div>

                                    <div class="card-tags-row">
                                        <?php if ($project !== ''): ?>
                                            <span class="card-meta-badge badge-project">
                                                <i class="fa-solid fa-folder-open text-muted"></i> <?php echo htmlspecialchars($project); ?>
                                            </span>
                                        <?php endif; ?>

                                        <?php if ($category !== ''): ?>
                                            <span class="card-meta-badge badge-category">
                                                <i class="fa-solid fa-tag"></i> <?php echo htmlspecialchars($category); ?>
                                            </span>
                                        <?php endif; ?>

                                        <?php if (!empty($t['manday'])): ?>
                                            <span class="card-meta-badge badge-manday">
                                                <i class="fa-solid fa-clock"></i> <?php echo (int)$t['manday']; ?> Day<?php echo (int)$t['manday'] > 1 ? 's' : ''; ?>
                                            </span>
                                        <?php endif; ?>

                                        <?php if ($due_str): ?>
                                            <span class="card-meta-badge badge-duedate <?php echo $is_urgent ? 'urgent' : ''; ?>">
                                                <i class="fa-regular fa-calendar-check"></i> Due: <?php echo date('d M Y', strtotime($due_str)); ?>
                                            </span>
                                        <?php endif; ?>
                                    </div>

                                    <?php if ($clean_desc !== ''): ?>
                                        <div class="card-desc-box"><?php echo htmlspecialchars($clean_desc); ?></div>
                                    <?php endif; ?>

                                    <div class="card-bottom-actions">
                                        <div style="display: flex; align-items: center; gap: 8px;">
                                            <!-- Advance Stage 1-Tap Form -->
                                            <form action="my_task.php" method="POST" style="margin: 0;">
                                                <input type="hidden" name="action" value="advance_stage">
                                                <input type="hidden" name="task_id" value="<?php echo $t['id']; ?>">
                                                <?php if ($stage_name === 'dump'): ?>
                                                    <input type="hidden" name="next_status" value="In Progress">
                                                    <button type="submit" class="btn-advance-stage btn-advance-dump">
                                                        <i class="fa-solid fa-play"></i> Mulakan
                                                    </button>
                                                <?php elseif ($stage_name === 'ongoing'): ?>
                                                    <input type="hidden" name="next_status" value="Completed">
                                                    <button type="submit" class="btn-advance-stage btn-advance-ongoing">
                                                        <i class="fa-solid fa-check"></i> Selesai
                                                    </button>
                                                <?php else: ?>
                                                    <input type="hidden" name="next_status" value="In Progress">
                                                    <button type="submit" class="btn-advance-stage btn-advance-reopen">
                                                        <i class="fa-solid fa-rotate-left"></i> Buka Semula
                                                    </button>
                                                <?php endif; ?>
                                            </form>

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

                                        <form action="my_task.php" method="POST" onsubmit="return confirm('Adakah anda pasti mahu memadam tugasan ini?');" style="margin: 0;">
                                            <input type="hidden" name="action" value="delete_task">
                                            <input type="hidden" name="task_id" value="<?php echo $t['id']; ?>">
                                            <button type="submit" style="background: none; border: none; color: #dc2626; cursor: pointer; font-size: 0.95rem;" title="Padam Tugasan">
                                                <i class="fa-solid fa-trash-can"></i>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php
            };
            $renderStageGrid('dump', $dump_tasks, true);
            $renderStageGrid('ongoing', $ongoing_tasks, false);
            $renderStageGrid('completed', $completed_tasks, false);
            ?>

        </div>

        <!-- ================= VIEW 2: MODERN CALENDAR SECTION ================= -->
        <div id="taskCalendarSection" class="calendar-app-card" style="display: none;">
            <div class="cal-header-row">
                <div class="cal-title-nav">
                    <div class="cal-title-month" id="taskCalMonthTitle">Ogos 2026</div>
                    <div class="cal-arrows">
                        <button class="cal-arrow-btn" onclick="prevTaskWeek()"><i class="fa-solid fa-chevron-left"></i></button>
                        <button class="cal-arrow-btn" onclick="nextTaskWeek()"><i class="fa-solid fa-chevron-right"></i></button>
                        <button class="btn-cal-today" onclick="goToTodayTask()">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-primary mr-1"></i> Klik mana-mana kad untuk edit detail
                </div>
            </div>

            <div class="cal-week-board">
                <div class="cal-week-head" id="taskWeekHeaderRow">
                    <div style="padding: 14px 6px; text-align: center; font-size: 0.78rem; font-weight: 800; color: var(--text-muted);">Masa</div>
                    <!-- Days generated dynamically -->
                </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: + Cipta Task -->
    <div class="modal-overlay" id="addTaskModal">
        <div class="modal-card">
            <div class="modal-header">
                <div>
                    <h3><i class="fa-solid fa-list-check text-primary"></i> Cipta Task</h3>
                    <p style="font-size: 0.78rem; color: var(--text-muted); margin-top: 2px;">Rancang tugasan kerja anda dengan teratur.</p>
                </div>
                <button style="background: none; border: none; font-size: 1.2rem; cursor: pointer;" onclick="closeAddTaskModal()"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <form action="my_task.php" method="POST">
                <input type="hidden" name="action" value="create_task">
                <input type="hidden" name="priority" id="taskPriorityInput" value="medium">
                
                <div class="modal-body">
                    <div class="form-group">
                        <label>Task Name *</label>
                        <input type="text" name="title" class="form-control" placeholder="Contoh: Sediakan laporan bulanan" required>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                        <div class="form-group">
                            <label>Peringkat Permulaan</label>
                            <select name="stage" class="form-control">
                                <option value="dump">Dump (Menunggu)</option>
                                <option value="ongoing">On Going (Dalam Proses)</option>
                                <option value="completed">Completed (Selesai)</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Kategori</label>
                            <select name="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 style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                        <div class="form-group">
                            <label>Projek</label>
                            <select name="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>Tarikh Akhir (Due Date) *</label>
                            <input type="date" name="due_date" id="taskDueDate" class="form-control" value="<?php echo date('Y-m-d', strtotime('+1 day')); ?>" required>
                        </div>
                    </div>

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

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                        <div class="form-group">
                            <label>Start Time</label>
                            <input type="time" name="start_time" class="form-control" value="09:00">
                        </div>
                        <div class="form-group">
                            <label>End Time</label>
                            <input type="time" name="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="mandayBadge" 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="setPriority('low', 'create')">Low</div>
                            <div class="priority-opt active" data-val="medium" onclick="setPriority('medium', 'create')">Medium</div>
                            <div class="priority-opt" data-val="high" onclick="setPriority('high', 'create')">High</div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Remark / Catatan</label>
                        <textarea name="description" class="form-control" rows="3" placeholder="Masukkan catatan atau hasil tugasan..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-status-reopen" style="padding: 10px 18px;" onclick="closeAddTaskModal()">Batal</button>
                    <button type="submit" class="btn-save">+ CIPTA TASK</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal 2: ✏️ Edit Task Detail Modal -->
    <div class="modal-overlay" id="editTaskModal">
        <div class="modal-card">
            <div class="modal-header">
                <div>
                    <h3><i class="fa-solid fa-pen-to-square text-primary"></i> Kemaskini Tugasan</h3>
                    <p style="font-size: 0.78rem; color: var(--text-muted); margin-top: 2px;">Ubah maklumat dan status tugasan.</p>
                </div>
                <button style="background: none; border: none; font-size: 1.2rem; cursor: pointer;" onclick="closeEditTaskModal()"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <form action="my_task.php" method="POST">
                <input type="hidden" name="action" value="update_task">
                <input type="hidden" name="task_id" id="editTaskId">
                <input type="hidden" name="priority" id="editTaskPriorityInput" value="medium">
                
                <div class="modal-body">
                    <div class="form-group">
                        <label>Task Name *</label>
                        <input type="text" name="title" id="editTaskTitle" class="form-control" required>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                        <div class="form-group">
                            <label>Status / Peringkat</label>
                            <select name="status" id="editTaskStatus" class="form-control">
                                <option value="Pending">Dump (Menunggu)</option>
                                <option value="In Progress">On Going (Dalam Proses)</option>
                                <option value="Completed">Completed (Selesai)</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Kategori</label>
                            <select name="category" id="editTaskCategory" 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 style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                        <div class="form-group">
                            <label>Projek</label>
                            <select name="project" id="editTaskProject" 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>Tarikh Akhir (Due Date)</label>
                            <input type="date" name="due_date" id="editTaskDueDate" class="form-control">
                        </div>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                        <div class="form-group">
                            <label>Start Date</label>
                            <input type="date" name="start_date" id="editTaskStartDate" class="form-control" onchange="calcManday('edit')">
                        </div>
                        <div class="form-group">
                            <label>End Date</label>
                            <input type="date" name="end_date" id="editTaskEndDate" class="form-control" onchange="calcManday('edit')">
                        </div>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                        <div class="form-group">
                            <label>Start Time</label>
                            <input type="time" name="start_time" id="editTaskStartTime" class="form-control" value="09:00">
                        </div>
                        <div class="form-group">
                            <label>End Time</label>
                            <input type="time" name="end_time" id="editTaskEndTime" 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="editMandayBadge" 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 edit-prio" data-val="low" onclick="setPriority('low', 'edit')">Low</div>
                            <div class="priority-opt edit-prio" data-val="medium" onclick="setPriority('medium', 'edit')">Medium</div>
                            <div class="priority-opt edit-prio" data-val="high" onclick="setPriority('high', 'edit')">High</div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Remark / Catatan</label>
                        <textarea name="description" id="editTaskDesc" class="form-control" rows="3" placeholder="Catatan tugasan..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-status-reopen" style="padding: 10px 18px;" onclick="closeEditTaskModal()">Batal</button>
                    <button type="submit" class="btn-save">SIMPAN PERUBAHAN</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const myTasks = <?php echo json_encode($tasks, JSON_UNESCAPED_UNICODE); ?>;
        let calCurrentDate = new Date();
        let currentSelectedStage = 'dump';
        let currentSelectedPriority = 'all';

        function switchTaskMasterView(mode) {
            document.getElementById('btnViewList').classList.toggle('active', mode === 'list');
            document.getElementById('btnViewCalendar').classList.toggle('active', mode === 'calendar');
            document.getElementById('taskListSection').style.display = (mode === 'list') ? 'block' : 'none';
            document.getElementById('taskCalendarSection').style.display = (mode === 'calendar') ? 'block' : 'none';
            if (mode === 'calendar') {
                renderTaskCalendarWeek();
            }
        }

        function selectTaskStage(stage) {
            currentSelectedStage = stage;
            document.querySelectorAll('.stage-tab-btn').forEach(btn => {
                btn.classList.toggle('active', btn.getAttribute('data-stage') === stage);
            });

            document.querySelectorAll('.task-stage-grid').forEach(grid => {
                grid.style.display = (grid.id === `grid_${stage}`) ? 'block' : 'none';
            });

            filterTasksLive();
        }

        function filterPriority(prio, btn) {
            currentSelectedPriority = prio;
            document.querySelectorAll('.prio-pill-btn').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            filterTasksLive();
        }

        function filterTasksLive() {
            const query = document.getElementById('taskSearchInput').value.toLowerCase().trim();
            const activeGrid = document.getElementById(`grid_${currentSelectedStage}`);
            if (!activeGrid) return;

            const cards = activeGrid.querySelectorAll('.world-task-card');
            cards.forEach(card => {
                const cardPrio = card.getAttribute('data-prio') || '';
                const cardText = card.getAttribute('data-title') || '';

                const matchesPrio = (currentSelectedPriority === 'all' || cardPrio === currentSelectedPriority);
                const matchesQuery = (query === '' || cardText.includes(query));

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

        function renderTaskCalendarWeek() {
            const headerRow = document.getElementById('taskWeekHeaderRow');
            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('taskCalMonthTitle').innerText = `${monthNames[calCurrentDate.getMonth()]} ${calCurrentDate.getFullYear()}`;

            const currentDayOfWeek = calCurrentDate.getDay();
            const sunday = new Date(calCurrentDate);
            sunday.setDate(calCurrentDate.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 matchingTasks = myTasks.filter(t => {
                    if (!t.start_at || !t.start_at.startsWith(targetDateStr)) return false;
                    const tHour = new Date(t.start_at).getHours();
                    return tHour === hour;
                });

                matchingTasks.forEach((t, idx) => {
                    const startDate = new Date(t.start_at);
                    const endDate = t.end_at ? new Date(t.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 = `${formatShortTime(startDate)} - ${formatShortTime(endDate)}`;
                    const themes = ['task-theme-teal', 'task-theme-blue', 'task-theme-orange', 'task-theme-purple', 'task-theme-rose'];
                    const colorIndex = (t.id || idx) % themes.length;
                    const themeClass = themes[colorIndex];

                    const categoryName = t.location || 'Umum';

                    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-task-card ${themeClass}`;
                    card.style.height = `${cardHeight}px`;
                    card.style.position = 'relative';
                    card.style.zIndex = '15';
                    card.onclick = () => openEditTaskModal(t);
                    card.innerHTML = `
                        <div style="font-size: 0.7rem; font-weight: 750; color: #0284c7;">${timeRange}</div>
                        <div style="font-size: 0.84rem; font-weight: 850; color: #1e293b; line-height: 1.25;">${escapeHtml(t.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>${escapeHtml(categoryName)}</span>
                        </div>
                    `;
                    cell.appendChild(card);
                });
            });
        }

        function prevTaskWeek() {
            calCurrentDate.setDate(calCurrentDate.getDate() - 7);
            renderTaskCalendarWeek();
        }

        function nextTaskWeek() {
            calCurrentDate.setDate(calCurrentDate.getDate() + 7);
            renderTaskCalendarWeek();
        }

        function goToTodayTask() {
            calCurrentDate = new Date();
            renderTaskCalendarWeek();
        }

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

        function openAddTaskModal() {
            document.getElementById('addTaskModal').classList.add('active');
            calcManday('create');
        }
        function closeAddTaskModal() {
            document.getElementById('addTaskModal').classList.remove('active');
        }

        function openEditTaskModal(t) {
            document.getElementById('editTaskId').value = t.id || '';
            document.getElementById('editTaskTitle').value = t.title || '';
            
            const st = (t.status || 'Pending').toLowerCase();
            let statusVal = 'Pending';
            if (st === 'completed' || st === 'selesai') statusVal = 'Completed';
            else if (st === 'in progress' || st === 'ongoing' || st === 'dalam proses') statusVal = 'In Progress';
            document.getElementById('editTaskStatus').value = statusVal;

            document.getElementById('editTaskCategory').value = t.location || '';
            
            let desc = t.description || '';
            let project = '';
            if (desc.includes('Projek:')) {
                const match = desc.match(/Projek:\s*([^\|\n]+)/);
                if (match) project = match[1].trim();
            }
            document.getElementById('editTaskProject').value = project;
            document.getElementById('editTaskDesc').value = desc;

            if (t.due_date) {
                document.getElementById('editTaskDueDate').value = t.due_date.substring(0, 10);
            }
            if (t.start_at) {
                document.getElementById('editTaskStartDate').value = t.start_at.substring(0, 10);
                document.getElementById('editTaskStartTime').value = t.start_at.substring(11, 16);
            }
            if (t.end_at) {
                document.getElementById('editTaskEndDate').value = t.end_at.substring(0, 10);
                document.getElementById('editTaskEndTime').value = t.end_at.substring(11, 16);
            }

            const prio = (t.priority || 'medium').toLowerCase();
            setPriority(prio, 'edit');
            calcManday('edit');

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

        function closeEditTaskModal() {
            document.getElementById('editTaskModal').classList.remove('active');
        }

        function setPriority(val, mode) {
            if (mode === 'edit') {
                document.getElementById('editTaskPriorityInput').value = val;
                document.querySelectorAll('.edit-prio').forEach(opt => {
                    opt.classList.toggle('active', opt.getAttribute('data-val') === val);
                });
            } else {
                document.getElementById('taskPriorityInput').value = val;
                document.querySelectorAll('.priority-options .priority-opt:not(.edit-prio)').forEach(opt => {
                    opt.classList.toggle('active', opt.getAttribute('data-val') === val);
                });
            }
        }

        function calcManday(mode) {
            const isEdit = (mode === 'edit');
            const startVal = document.getElementById(isEdit ? 'editTaskStartDate' : 'taskStartDate').value;
            const endVal = document.getElementById(isEdit ? 'editTaskEndDate' : 'taskEndDate').value;
            const badge = document.getElementById(isEdit ? 'editMandayBadge' : 'mandayBadge');

            if (startVal && endVal && badge) {
                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;
                badge.innerText = days + (days === 1 ? ' Day' : ' Days');
            }
        }

        document.addEventListener('DOMContentLoaded', () => {
            selectTaskStage('dump');
        });

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