<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn);

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

// Query events exclusively for logged in user
$sql = "SELECT c.*, u.fullname, u.short_name 
        FROM calendar_events c 
        JOIN users u ON u.id = c.user_id 
        WHERE c.user_id = ? 
        ORDER BY c.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) : [];

// Group events by Date string (Y-m-d)
$grouped_events = [];
foreach ($events as $ev) {
    $date_key = date('Y-m-d', strtotime($ev['start_at']));
    $grouped_events[$date_key][] = $ev;
}
ksort($grouped_events);

$total_events = count($events);
?>
<!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 renderAppShellAssets(); ?>
    <style>
        :root {
            --primary: #0077b6; --primary-dark: #005f99; --secondary: #00b4d8;
            --deep-blue: #023e5f;
            --superadmin: #6c5ce7; --superadmin-dark: #5b4cdb;
            --bg-light: rgba(245, 250, 253, 0.72); --bg-card: rgba(255, 255, 255, 0.68); --text-main: #163447;
            --text-muted: #2d5367; --border: rgba(255, 255, 255, 0.48); --sidebar-width: 280px;
            --success: #1a9955; --danger: #dc3545; --warning: #ffc107;
            --glass: rgba(255, 255, 255, 0.58);
            --glass-strong: rgba(255, 255, 255, 0.76);
            --shadow-soft: 0 24px 70px rgba(2, 62, 95, 0.16);
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', 'Inter', Tahoma, Geneva, Verdana, sans-serif; }
        body {
            min-height: 100vh;
            display: flex;
            color: var(--text-main);
            background:
                linear-gradient(135deg, rgba(245, 250, 253, 0.90), rgba(222, 246, 252, 0.76)),
                url('assets/auth-bg.png') center/cover no-repeat fixed;
            overflow-x: hidden;
        }

        body::before,
        body::after {
            content: "";
            position: fixed;
            pointer-events: none;
            z-index: 0;
        }

        body::before {
            width: 42vw;
            height: 42vw;
            right: -16vw;
            top: -18vw;
            border-radius: 50%;
            background: radial-gradient(circle, rgba(0, 180, 216, 0.24), transparent 62%);
            filter: blur(4px);
        }

        body::after {
            width: 48vw;
            height: 48vw;
            left: 120px;
            bottom: -30vw;
            border-radius: 46px;
            background:
                linear-gradient(155deg, rgba(255, 255, 255, 0.20), rgba(255, 255, 255, 0.03)),
                repeating-linear-gradient(0deg, transparent 0 34px, rgba(0, 119, 182, 0.08) 35px 36px);
            border: 1px solid rgba(255, 255, 255, 0.32);
            transform: rotate(-9deg);
        }

        /* Sidebar Theme Fix */
        .sidebar {
            width: var(--sidebar-width) !important;
            background:
                linear-gradient(180deg, rgba(2, 62, 95, 0.94), rgba(0, 119, 182, 0.84)),
                radial-gradient(circle at 22% 8%, rgba(0, 180, 216, 0.28), transparent 32%) !important;
            border-right: 1px solid rgba(255, 255, 255, 0.22) !important;
            position: fixed;
            height: 100vh;
            padding: 20px 0 !important;
            overflow-y: auto;
            overflow-x: hidden;
            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(18px) saturate(1.25);
            -webkit-backdrop-filter: blur(18px) saturate(1.25);
        }
        .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;
            white-space: nowrap;
            overflow: hidden;
            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; transition: margin 0.3s ease; filter: drop-shadow(0 10px 18px rgba(0,0,0,0.25)); }
        .sidebar-header h3 { font-size: 1rem !important; font-weight: 800 !important; color: #fff !important; margin-bottom: 4px !important; letter-spacing: 0.01em; }
        .sidebar-header p { font-size: 0.75rem !important; color: rgba(255,255,255,0.72) !important; }
        
        .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; white-space: nowrap; }
        .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-menu .dropdown { position: relative; }
        .sidebar-menu .dropdown-toggle { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: 12px 18px; color: rgba(255,255,255,0.88) !important; background: none; border: none; border-radius: 10px; cursor: pointer; font-size: 0.9rem; text-align: left; transition: all 0.2s ease; }
        .sidebar-menu .dropdown-toggle:hover, .sidebar-menu .dropdown-toggle.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 .dropdown-toggle i.chevron { transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); font-size: 0.8rem; }
        .sidebar-menu .dropdown.active .dropdown-toggle i.chevron { transform: rotate(180deg); }
        .sidebar-menu .dropdown-menu { display: flex; flex-direction: column; padding-left: 36px; margin-top: 4px; max-height: 0; opacity: 0; overflow: hidden; transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.25s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu { max-height: 320px; opacity: 1; padding-bottom: 8px; }
        .sidebar-menu .dropdown-menu a { padding: 8px 16px; color: rgba(255,255,255,0.78) !important; text-decoration: none; border-radius: 8px; font-size: 0.85rem; display: flex; align-items: center; gap: 8px; opacity: 0; transform: translateY(-5px); transition: opacity 0.2s ease, transform 0.2s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu a { opacity: 1; transform: translateY(0); }
        .sidebar-menu .dropdown-menu a:hover, .sidebar-menu .dropdown-menu a.active { background: rgba(255,255,255,0.16) !important; color: #fff !important; }

        .sidebar::-webkit-scrollbar { width: 6px !important; }
        .sidebar::-webkit-scrollbar-track { background: rgba(0, 0, 0, 0.12) !important; }
        .sidebar::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.32) !important; border-radius: 999px !important; }
        .sidebar::-webkit-scrollbar-thumb:hover { background: rgba(255, 255, 255, 0.55) !important; }
        
        .sidebar-toggle { position: absolute !important; right: 10px !important; top: 18px !important; width: 28px !important; height: 28px !important; min-width: 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; box-shadow: 0 10px 22px rgba(0,0,0,0.14) !important; transition: transform 0.3s ease !important; z-index: 1300 !important; }
        .sidebar.collapsed .sidebar-toggle { transform: rotate(180deg) !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 Header */
        .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(--deep-blue); font-size: 1.35rem; font-weight: 850; display: flex; align-items: center; gap: 10px; }
        .top-bar h2 i { color: var(--secondary); }

        /* Timeline */
        .timeline-container { display: flex; flex-direction: column; gap: 24px; }
        .date-group-card { background: rgba(255,255,255,0.70); border-radius: 20px; border: 1px solid rgba(255,255,255,0.58); padding: 24px; box-shadow: 0 14px 30px rgba(2,62,95,0.10); backdrop-filter: blur(18px) saturate(1.18); -webkit-backdrop-filter: blur(18px) saturate(1.18); }
        .date-header { font-size: 1.1rem; font-weight: 850; color: var(--deep-blue); display: flex; align-items: center; gap: 10px; padding-bottom: 14px; border-bottom: 2px solid rgba(0,119,182,0.12); margin-bottom: 16px; }

        .timeline-events { display: flex; flex-direction: column; gap: 12px; }
        .event-row { display: flex; align-items: center; gap: 16px; background: rgba(255,255,255,0.75); padding: 14px 18px; border-radius: 14px; border: 1px solid rgba(0,119,182,0.10); transition: transform 0.2s ease; }
        .event-row:hover { transform: translateX(4px); background: #fff; }

        .event-icon { width: 44px; height: 44px; border-radius: 12px; display: inline-flex; align-items: center; justify-content: center; font-size: 1.2rem; flex-shrink: 0; }
        .event-icon.task { background: #dbeafe; color: #1d4ed8; }
        .event-icon.leave { background: #d1fae5; color: #047857; }
        .event-icon.time_off { background: #ede9fe; color: #6d28d9; }
        .event-icon.meeting { background: #fef3c7; color: #b45309; }

        .event-details { flex: 1; }
        .event-title { font-size: 0.95rem; font-weight: 800; color: var(--text-main); margin-bottom: 2px; }
        .event-desc { font-size: 0.84rem; color: var(--text-muted); }

        .event-time { font-size: 0.85rem; font-weight: 750; color: var(--deep-blue); background: rgba(0,119,182,0.08); padding: 6px 12px; border-radius: 8px; white-space: nowrap; }
    </style>
</head>
<body class="role-<?= htmlspecialchars($role) ?>">

    <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 class="main">
        <div class="top-bar">
            <h2><i class="fas fa-user-clock"></i> My Schedule & Timeline</h2>
            <?php renderTopBarUserMenu($conn, $role, 'my_schedule.php'); ?>
        </div>

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

        <?php if (empty($grouped_events)): ?>
            <div style="text-align:center; padding:50px; background:var(--glass); border-radius:18px; border:1px solid var(--border); box-shadow: var(--shadow-soft);">
                <i class="fas fa-calendar-times" style="font-size:3rem; color:var(--text-muted); opacity:0.5; margin-bottom:15px;"></i>
                <h4 style="color:var(--text-muted);">Tiada Rekod Jadual Ditemui</h4>
                <p style="font-size:0.85rem; color:var(--text-muted); margin-top:5px;">Jadual akan dipaparkan secara automatik mengikut tugasan, cuti, dan mesyuarat peribadi anda.</p>
            </div>
        <?php else: ?>
            <div class="timeline-container">
                <?php foreach ($grouped_events as $date_str => $day_events): 
                    $formatted_date = date('l, d F Y', strtotime($date_str));
                ?>
                    <div class="date-group-card">
                        <div class="date-header">
                            <i class="far fa-calendar-alt"></i> <?= $formatted_date ?>
                        </div>
                        <div class="timeline-events">
                            <?php foreach ($day_events as $ev): 
                                $ev_type = strtolower(trim($ev['event_type']));
                                $icon_class = 'fa-calendar-event';
                                $type_label = 'Aktiviti';
                                if ($ev_type === 'task') {
                                    $icon_class = 'fa-tasks';
                                    $type_label = 'Tugasan';
                                } elseif ($ev_type === 'leave') {
                                    $icon_class = 'fa-umbrella-beach';
                                    $type_label = 'Cuti Rehat';
                                } elseif ($ev_type === 'time_off') {
                                    $icon_class = 'fa-clock';
                                    $type_label = 'Time Off';
                                } elseif ($ev_type === 'meeting') {
                                    $icon_class = 'fa-users';
                                    $type_label = 'Mesyuarat / Kursus';
                                }

                                $time_display = (int) ($ev['is_full_day'] ?? 0) === 1 ? 'Sepanjang Hari' : date('g:i A', strtotime($ev['start_at']));
                            ?>
                                <div class="event-row">
                                    <div class="event-icon <?= $ev_type ?>">
                                        <i class="fas <?= $icon_class ?>"></i>
                                    </div>
                                    <div class="event-details">
                                        <div class="event-title"><?= htmlspecialchars($ev['title']) ?></div>
                                        <div class="event-desc"><?= htmlspecialchars($ev['description'] ?? $ev['reason'] ?? 'Tiada penerangan.') ?></div>
                                    </div>
                                    <div class="event-time">
                                        <?= $time_display ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

    </main>
</body>
</html>
