<!DOCTYPE html>
<html lang="ar" dir="rtl">
<?php
// =========================================================
// AutomationEngine — proactive rule execution (once per layout)
// =========================================================
if (!empty($_SESSION['user_id'])) {
    require_once __DIR__ . '/../../../core/Services/AutomationEngine.php';
    \Core\Services\AutomationEngine::getInstance()->run((int)$_SESSION['user_id']);
}

// =========================================================
// Notification Logic — load from DB + Calendar events
// =========================================================

$calendarNotifications = [];
$systemNotifications   = [];
$unreadCount = 0;

// Load today's calendar events (for toast reminders)
if (file_exists(__DIR__ . '/../../Modules/Calendar/Models/CalendarModel.php')) {
    require_once __DIR__ . '/../../Modules/Calendar/Models/CalendarModel.php';
    if (class_exists('CalendarModel')) {
        $cModel = new \CalendarModel();
        $calendarNotifications = $cModel->getEventsByDate($_SESSION['user_id'] ?? 1, date('Y-m-d'));
    }
}

// Load system notifications from DB (unread only for toasts, count for badge)
if (class_exists('Core\Database')) {
    try {
        $db = \Core\Database::getInstance();
        $notifRows = $db->query(
            "SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5",
            [$_SESSION['user_id'] ?? 1]
        )->fetchAll();
        $systemNotifications = $notifRows;
        $unreadCount = count($notifRows);

        // Mark them as read now that they've been shown
        if ($unreadCount > 0) {
            $db->query("UPDATE notifications SET is_read = 1 WHERE user_id = ? AND is_read = 0", [$_SESSION['user_id'] ?? 1]);
        }
    } catch (\Exception $e) {
        // Graceful fallback — DB might not be ready
        $systemNotifications = [];
    }
}

$calCount  = count($calendarNotifications);
$totalBadge = $unreadCount + $calCount;

$smartReminders = [];
if (file_exists(__DIR__ . '/../../../../core/Services/ReminderService.php')) {
    require_once __DIR__ . '/../../../../core/Services/ReminderService.php';
    if (class_exists('Core\Services\ReminderService')) {
        try {
            $rService = new \Core\Services\ReminderService();
            $smartReminders = $rService->getPendingReminders($_SESSION['user_id'] ?? 1);
        } catch (\Exception $e) {}
    }
}
$srCount = count($smartReminders);
$totalBadge += $srCount;

// DES: Global Discipline Score
$disciplineScore = 100;
$identityNarrative = "";
if (file_exists(__DIR__ . '/../../../../core/Services/BehaviorIntelligenceService.php')) {
    require_once __DIR__ . '/../../../../core/Services/BehaviorIntelligenceService.php';
    if (class_exists('Core\Services\BehaviorIntelligenceService')) {
        try {
            $biService = new \Core\Services\BehaviorIntelligenceService();
            $disciplineScore = $biService->getUnifiedDisciplineScore($_SESSION['user_id'] ?? 1);
            $identityNarrative = $biService->getIdentityNarrative($disciplineScore);
        } catch (\Exception $e) {}
    }
}

// Gamification Engine
$gamificationProfile = null;
if (file_exists(__DIR__ . '/../../../../core/Services/GamificationEngine.php')) {
    require_once __DIR__ . '/../../../../core/Services/GamificationEngine.php';
    if (class_exists('Core\Services\GamificationEngine')) {
        try {
            $gEngine = \Core\Services\GamificationEngine::getInstance();
            $gamificationProfile = $gEngine->getProfile($_SESSION['user_id'] ?? 1);
        } catch (\Exception $e) {}
    }
}

// ── Load theme & settings (once per session) ──────────────────
if (isset($_SESSION['user_id']) && !isset($_SESSION['theme'])) {
    if (class_exists('Core\Database')) {
        try {
            $db  = \Core\Database::getInstance();
            $set = $db->query("SELECT theme, currency, timezone, onboarding_done FROM user_settings WHERE user_id = ?", [$_SESSION['user_id']])->fetch();
            if ($set) {
                $_SESSION['theme']           = $set->theme;
                $_SESSION['currency']        = $set->currency;
                $_SESSION['timezone']        = $set->timezone;
                $_SESSION['onboarding_done'] = (bool)($set->onboarding_done ?? false);
            } else {
                $_SESSION['theme']           = 'light';
                $_SESSION['currency']        = 'EGP';
                $_SESSION['timezone']        = 'Africa/Cairo';
                $_SESSION['onboarding_done'] = false;
            }
        } catch (\Exception $e) {}
    }
}

// ── Independently load onboarding_done if missing from session ─────────
// Runs when theme is already loaded but onboarding_done never got set
if (isset($_SESSION['user_id']) && !isset($_SESSION['onboarding_done'])) {
    if (class_exists('Core\Database')) {
        try {
            $db  = \Core\Database::getInstance();
            $val = $db->query(
                "SELECT onboarding_done FROM user_settings WHERE user_id = ?",
                [$_SESSION['user_id']]
            )->fetchColumn();
            $_SESSION['onboarding_done'] = (bool)$val;
        } catch (\Exception $e) {
            $_SESSION['onboarding_done'] = true; // Fail open: hide modal on DB error
        }
    }
}

$userTheme      = $_SESSION['theme'] ?? 'light';
$showOnboarding = isset($_SESSION['user_id']) && empty($_SESSION['onboarding_done']);
?>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- PWA Manifest & Theme -->
    <link rel="manifest" href="<?= BASE_URL ?>/public/manifest.json">
    <meta name="theme-color" content="#0f172a">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="OTIS">
    <link rel="apple-touch-icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 192 192'%3E%3Crect width='192' height='192' rx='24' fill='%230d6efd'/%3E%3Ctext x='50%25' y='58%25' dominant-baseline='middle' text-anchor='middle' font-size='110' font-family='sans-serif' fill='white'%3E%E2%88%9E%3C/text%3E%3C/svg%3E">
    <title><?= htmlspecialchars($title ?? 'OTIS Life System') ?></title>
    
    <!-- Google Fonts: Tajawal & Cairo for Arabic -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;500;600;700;800&family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
    
    <!-- Bootstrap 5 RTL -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.rtl.min.css">
    <!-- FontAwesome for Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.2/dist/chart.umd.min.js"></script>
    
    <!-- Custom CSS -->
    <link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/style-rtl.css">
    <link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/mobile.css">
    <style>
    /* Dark Mode Global Overrides */
    body.dark-mode { background-color: #0f172a !important; color: #e2e8f0 !important; }
    body.dark-mode h1, body.dark-mode h2, body.dark-mode h3, body.dark-mode h4, body.dark-mode h5, body.dark-mode h6, 
    body.dark-mode .text-dark, body.dark-mode .card-title { color: #f8fafc !important; }
    body.dark-mode .bg-white, body.dark-mode .bg-light, body.dark-mode .card.bg-white, body.dark-mode .card, body.dark-mode .spiritual-card, body.dark-mode .card-saas { background-color: #1e293b !important; border-color: #334155 !important; box-shadow: 0 4px 15px rgba(0,0,0,0.3) !important;}
    body.dark-mode .table { --bs-table-bg: transparent; --bs-table-color: #e2e8f0; border-color: #334155; }
    body.dark-mode .table-light, body.dark-mode thead.table-light tr th { background-color: #334155 !important; color: #cbd5e1 !important; border-color: #475569 !important; }
    body.dark-mode td { border-color: #334155 !important; }
    body.dark-mode .text-muted, body.dark-mode .text-secondary { color: #94a3b8 !important; }
    body.dark-mode .border-bottom, body.dark-mode .border-top { border-color: #334155 !important; }
    body.dark-mode .offcanvas-md { background-color: #020617 !important; border-color: #1e293b !important; }
    body.dark-mode .modal-content { background-color: #1e293b !important; border: 1px solid #334155 !important; }
    body.dark-mode input, body.dark-mode input.bg-light, body.dark-mode select, body.dark-mode textarea { background-color: #334155 !important; color: #f8fafc !important; border-color: #475569 !important; }
    body.dark-mode .form-control:focus, body.dark-mode .form-select:focus { background-color: #475569 !important; color: #fff !important; }
    body.dark-mode .dropdown-menu { background-color: #1e293b !important; border: 1px solid #334155; }
    body.dark-mode .dropdown-item { color: #e2e8f0 !important; }
    body.dark-mode .dropdown-item:hover { background-color: #334155 !important; }
    body.dark-mode .footer { background-color: #1e293b !important; border-color: #334155 !important; }
    body.dark-mode .content-wrapper, body.dark-mode .bg-light { background-color: #0f172a !important; }
    </style>
</head>
<body class="<?= $userTheme === 'dark' ? 'dark-mode' : '' ?>">
    <script>
        // JS Fallback Sync - Not needed anymore but good for instant flicker fix
        if (localStorage.getItem('theme') === 'dark' && !document.body.classList.contains('dark-mode')) {
            document.body.classList.add('dark-mode');
        }
    </script>

    <!-- Mobile Topbar -->
    <nav class="navbar navbar-dark bg-primary d-md-none px-3 fixed-top d-flex justify-content-between align-items-center shadow-sm" style="height: 56px; z-index: 1030;">
        <div class="d-flex gap-2 align-items-center">
            <?php if ($totalBadge > 0): ?>
            <span class="badge bg-danger rounded-pill"><?= $totalBadge ?></span>
            <?php endif; ?>
            
            <!-- DES Global Mobile Badge -->
            <div class="px-2 py-1 rounded-pill bg-white bg-opacity-25 text-white small fw-bold" title="<?= $identityNarrative ?>">
                <i class="fa-solid fa-gauge-high"></i> <?= $disciplineScore ?>%
            </div>
        </div>
        <a class="navbar-brand fw-bold m-0" href="<?= BASE_URL ?>/">OTIS</a>
    </nav>

    <div class="d-flex">
        
        <!-- Sidebar (Desktop Fixed Only) -->
        <div class="bg-dark text-white sidebar-wrapper shadow d-none d-md-flex flex-column" id="sidebarDesktop">
            
            <div class="sidebar-content d-flex flex-column p-3 h-100">
                <a href="<?= BASE_URL ?>/" class="d-none d-md-flex align-items-center mb-4 text-white text-decoration-none border-bottom border-secondary pb-3">
                    <span class="fs-4 fw-bold"><i class="fa-solid fa-infinity me-2"></i> OTIS Life System</span>
                </a>

                <!-- DES Global Score Card in Sidebar -->
                <div class="card bg-primary bg-opacity-10 border-0 mb-3 rounded-4 shadow-sm">
                    <div class="card-body p-3 text-center">
                        <small class="text-secondary fw-bold text-uppercase d-block mb-1" style="font-size: 10px;">الانضباط الكلي</small>
                        <div class="d-flex align-items-center justify-content-center gap-2">
                            <span class="fs-2 fw-bold text-white"><?= $disciplineScore ?>%</span>
                            <div class="progress flex-grow-1" style="height: 6px; max-width: 60px; direction: ltr;">
                                <div class="progress-bar bg-primary" role="progressbar" style="width: <?= $disciplineScore ?>%;"></div>
                            </div>
                        </div>
                        <small class="text-info d-block mt-1 fw-bold" style="font-size: 11px;"><?= $identityNarrative ?></small>
                    </div>
                </div>

                <!-- Gamification Widget in Sidebar -->
                <?php if ($gamificationProfile): ?>
                <a href="<?= BASE_URL ?>/gamification" class="text-decoration-none">
                    <div class="card border-1 border-secondary mb-4 rounded-4 shadow-sm" style="background: linear-gradient(145deg, #1e293b, #0f172a); transition: transform 0.2s; cursor: pointer;" onmouseover="this.style.transform='scale(1.02)'" onmouseout="this.style.transform='scale(1)'">
                        <div class="card-body p-3 text-center position-relative overflow-hidden">
                            <i class="fa-solid fa-star position-absolute text-warning opacity-10" style="font-size: 60px; top: -10px; left: -10px;"></i>
                            <small class="text-warning fw-bold text-uppercase d-block mb-1" style="font-size: 10px; letter-spacing: 1px;"><i class="fa-solid fa-shield-halved me-1"></i> <?= $gamificationProfile['title'] ?></small>
                            <div class="d-flex align-items-center justify-content-center gap-2 position-relative z-1 mb-1">
                                <span class="fs-4 fw-bold text-white">Lvl <?= $gamificationProfile['level'] ?></span>
                            </div>
                            <div class="progress mt-1 position-relative z-1 rounded-pill" style="height: 5px; direction: ltr; background: rgba(255,255,255,0.1);">
                                <div class="progress-bar bg-warning" role="progressbar" style="width: <?= $gamificationProfile['progress_pct'] ?>%; transition: width 1.5s cubic-bezier(0.4, 0, 0.2, 1); box-shadow: 0 0 8px #ffc107;"></div>
                            </div>
                            <small class="d-block mt-1 text-white-50" style="font-size: 10px;"><?= number_format($gamificationProfile['xp']) ?> / <?= number_format($gamificationProfile['next_xp']) ?> XP</small>
                        </div>
                    </div>
                </a>
                <?php endif; ?>
                
                <?php $uri = $_SERVER['REQUEST_URI'] ?? ''; ?>
                <ul class="nav nav-pills flex-column mb-auto dashboard-nav" data-no-pjax="true">
                    <!-- 1. الرئيسية -->
                    <li class="nav-item mb-2">
                        <a data-no-pjax="true" href="<?= BASE_URL ?>/" class="nav-link text-white <?= ($uri == BASE_URL . '/' || $uri == BASE_URL) ? 'active' : '' ?>">
                            <i class="fa-solid fa-house fa-fw me-2"></i> الرئيسية
                        </a>
                    </li>
                    <!-- 2. اليومية -->
                    <li class="nav-item mb-2">
                        <a data-no-pjax="true" href="<?= BASE_URL ?>/journal" class="nav-link text-white <?= (strpos($uri, '/journal') !== false) ? 'active' : '' ?>">
                            <i class="fa-solid fa-book-open fa-fw me-2 text-primary"></i> اليومية
                        </a>
                    </li>
                    <!-- 3. خطة الشهر -->
                    <li class="nav-item mb-2">
                        <a data-no-pjax="true" href="<?= BASE_URL ?>/monthlyplan" class="nav-link text-white <?= (strpos($uri, '/monthlyplan') !== false) ? 'active' : '' ?>">
                            <i class="fa-solid fa-calendar-check fa-fw me-2 text-warning"></i> خطة الشهر
                        </a>
                    </li>
                    <!-- 4. الإدارة المالية -->
                    <li class="nav-item mb-2">
                        <a data-no-pjax="true" href="<?= BASE_URL ?>/finance" class="nav-link text-white <?= (strpos($uri, '/finance') !== false) ? 'active' : '' ?>">
                            <i class="fa-solid fa-wallet fa-fw me-2"></i> الإدارة المالية
                        </a>
                    </li>
                    <!-- 5. To-Do -->
                    <li class="nav-item mb-2">
                        <a data-no-pjax="true" href="<?= BASE_URL ?>/todo" class="nav-link text-white d-flex align-items-center <?= (strpos($uri, '/todo') !== false) ? 'active' : '' ?>">
                            <i class="fa-solid fa-list-check fa-fw me-2"></i> To-Do
                        </a>
                    </li>
                    <!-- 6. Calendar -->
                    <li class="nav-item mb-2">
                        <a data-no-pjax="true" href="<?= BASE_URL ?>/calendar" class="nav-link text-white d-flex align-items-center <?= (strpos($uri, '/calendar') !== false) ? 'active' : '' ?>">
                            <i class="fa-regular fa-calendar-days fa-fw me-2"></i> Calendar
                            <?php if($calCount > 0): ?>
                                <span class="badge bg-warning text-dark rounded-pill ms-auto"><?= $calCount ?></span>
                            <?php endif; ?>
                        </a>
                    </li>
                    <!-- 7. الروحانيات -->
                    <li class="nav-item mb-2">
                        <a data-no-pjax="true" href="<?= BASE_URL ?>/spiritual" class="nav-link text-white d-flex align-items-center <?= (strpos($uri, '/spiritual') !== false) ? 'active' : '' ?>">
                            <i class="fa-solid fa-kaaba fa-fw me-2"></i> الروحانيات
                        </a>
                    </li>
                    <!-- 8. السلوكيات -->
                    <li class="nav-item mb-2">
                        <a data-no-pjax="true" href="<?= BASE_URL ?>/behavior" class="nav-link text-white d-flex align-items-center <?= (strpos($uri, '/behavior') !== false) ? 'active' : '' ?>">
                            <i class="fa-solid fa-brain fa-fw me-2 text-warning"></i> السلوكيات
                        </a>
                    </li>
                    <!-- 9. Edu & Skills -->
                    <li class="nav-item mb-2">
                        <a data-no-pjax="true" href="<?= BASE_URL ?>/education" class="nav-link text-white <?= (strpos($uri, '/education') !== false) ? 'active' : '' ?>">
                            <i class="fa-solid fa-graduation-cap fa-fw me-2"></i> Edu & Skills
                        </a>
                    </li>
                    <!-- 10. إدارة الصحة -->
                    <li class="nav-item mb-2">
                        <a data-no-pjax="true" href="<?= BASE_URL ?>/health" class="nav-link text-white <?= (strpos($uri, '/health') !== false) ? 'active' : '' ?>">
                            <i class="fa-solid fa-heart-pulse fa-fw me-2"></i> إدارة الصحة
                        </a>
                    </li>
                    

                    <!-- 11. الخزنة السرية (AT THE END AS REQUESTED) -->
                    <li class="nav-item mb-2 mt-4 text-center pb-2 border-bottom border-dark">
                        <small class="text-secondary fw-bold text-uppercase" style="letter-spacing:2px; font-size:10px;"><i class="fa-solid fa-shield-halved text-success"></i> Secure Zone</small>
                    </li>
                    <li class="nav-item mb-2">
                        <a data-no-pjax="true" href="<?= BASE_URL ?>/vault" class="nav-link <?= (strpos($uri, '/vault') !== false) ? 'active bg-success text-white fw-bold' : 'text-success fw-bold opacity-75' ?>">
                            <i class="fa-solid fa-fingerprint fa-fw me-2"></i> الخزنة السرية
                        </a>
                    </li>
                    
                    <!-- Analytics -->
                    <li class="nav-item mt-4 pt-3 border-top border-secondary mb-2">
                        <a data-no-pjax="true" href="<?= BASE_URL ?>/analytics" class="nav-link text-white <?= (strpos($uri, '/analytics') !== false) ? 'active' : '' ?>">
                            <i class="fa-solid fa-chart-line fa-fw me-2 text-info"></i> التحليلات
                        </a>
                    </li>

                    <!-- System -->
                    <li class="nav-item mt-3 pt-3 border-top border-secondary">
                        <a data-no-pjax="true" href="<?= BASE_URL ?>/system/notifications" class="nav-link text-white d-flex align-items-center <?= (strpos($uri, '/system/notifications') !== false) ? 'active' : '' ?>">
                            <i class="fa-solid fa-bell fa-fw me-2"></i> الإشعارات
                            <?php if($unreadCount > 0): ?>
                                <span class="badge bg-danger rounded-pill ms-auto"><?= $unreadCount ?></span>
                            <?php endif; ?>
                        </a>
                    </li>
                    <li class="nav-item mb-2">
                        <a data-no-pjax="true" href="<?= BASE_URL ?>/system/logs" class="nav-link text-white <?= (strpos($uri, '/system/logs') !== false) ? 'active' : '' ?>">
                            <i class="fa-solid fa-gear fa-fw me-2"></i> النظام والسجلات
                        </a>
                    </li>
                </ul>
                
                <hr class="border-secondary">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <span class="text-secondary small">المظهر</span>
                    <a href="#" class="text-white text-decoration-none bg-secondary bg-opacity-25 rounded-circle p-2 d-flex align-items-center justify-content-center" id="themeToggleBtn" style="width: 36px; height: 36px; transition: all 0.3s;" data-theme="<?= $userTheme ?>">
                        <?= $userTheme === 'dark' ? '<i class="fa-solid fa-sun text-warning"></i>' : '<i class="fa-solid fa-moon"></i>' ?>
                    </a>
                </div>
                <div class="dropdown">
                    <a href="#" class="d-flex align-items-center text-white text-decoration-none dropdown-toggle" data-bs-toggle="dropdown">
                        <?php $displayName = $_SESSION['username'] ?? 'User'; ?>
                        <img src="https://ui-avatars.com/api/?name=<?= urlencode($displayName) ?>&background=0D8ABC&color=fff" alt="" width="32" height="32" class="rounded-circle me-2">
                        <strong><?= htmlspecialchars($displayName) ?></strong>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-dark text-small shadow">
                        <li><a class="dropdown-item" href="<?= BASE_URL ?>/system/settings"><i class="fa-solid fa-sliders fa-fw me-2 text-warning"></i> الإعدادات والتفضيلات</a></li>
                        <li><a class="dropdown-item" href="<?= BASE_URL ?>/system/profile"><i class="fa-solid fa-user-shield fa-fw me-2 text-info"></i> أمان الحساب</a></li>
                        <li><hr class="dropdown-divider border-secondary opacity-50"></li>
                        <li><a class="dropdown-item text-danger" href="<?= BASE_URL ?>/auth/logout"><i class="fa-solid fa-arrow-right-from-bracket fa-fw me-2"></i> تسجيل الخروج</a></li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- Main Content Area -->
        <div class="content-wrapper flex-grow-1 bg-light">
            <!-- Flash Messages -->
            <?php if(isset($_SESSION['flash'])): ?>
                <div class="container-fluid pt-3 px-4">
                    <?php foreach($_SESSION['flash'] as $key => $msg): ?>
                        <div class="alert alert-<?= $msg['type'] ?> alert-dismissible fade show shadow-sm" role="alert">
                            <?= $msg['message'] ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endforeach; unset($_SESSION['flash']); ?>
                </div>
            <?php endif; ?>

            <main class="container-fluid py-4 px-md-4">
                <?= $content ?? '' ?>
            </main>
            
            <footer class="footer mt-auto py-3 bg-white border-top text-center text-muted">
                <div class="container-fluid">
                    <small>&copy; <?= date('Y') ?> <b>OTIS Life System</b>. تصميم وإدارة بنظام متكامل ومحكم.</small>
                </div>
            </footer>
        </div>
        
    </div>

    <!-- Mobile Bottom Navigation Bar -->
    <nav class="mobile-bottom-nav d-md-none position-fixed bottom-0 w-100 bg-white border-top shadow-lg d-flex justify-content-around align-items-center" style="z-index: 1040; height: 65px; padding-bottom: env(safe-area-inset-bottom);">
        <a data-no-pjax="true" href="<?= BASE_URL ?>/" class="nav-item text-center text-decoration-none d-flex flex-column align-items-center justify-content-center h-100 flex-grow-1 <?= ($uri == BASE_URL . '/' || $uri == BASE_URL) ? 'text-primary' : 'text-secondary' ?>">
            <i class="fa-solid fa-house mb-1 fs-5"></i>
            <span style="font-size: 11px; font-weight: 600;">الرئيسية</span>
        </a>
        <a data-no-pjax="true" href="<?= BASE_URL ?>/journal" class="nav-item text-center text-decoration-none d-flex flex-column align-items-center justify-content-center h-100 flex-grow-1 <?= (strpos($uri, '/journal') !== false) ? 'text-primary' : 'text-secondary' ?>">
            <i class="fa-solid fa-book-open mb-1 fs-5"></i>
            <span style="font-size: 11px; font-weight: 600;">اليومية</span>
        </a>
        <a data-no-pjax="true" href="<?= BASE_URL ?>/health" class="nav-item text-center text-decoration-none d-flex flex-column align-items-center justify-content-center h-100 flex-grow-1 <?= (strpos($uri, '/health') !== false) ? 'text-primary' : 'text-secondary' ?>">
            <i class="fa-solid fa-heart-pulse mb-1 fs-5"></i>
            <span style="font-size: 11px; font-weight: 600;">الصحة</span>
        </a>
        <a data-no-pjax="true" href="<?= BASE_URL ?>/finance" class="nav-item text-center text-decoration-none d-flex flex-column align-items-center justify-content-center h-100 flex-grow-1 <?= (strpos($uri, '/finance') !== false) ? 'text-primary' : 'text-secondary' ?>">
            <i class="fa-solid fa-wallet mb-1 fs-5"></i>
            <span style="font-size: 11px; font-weight: 600;">المال</span>
        </a>
        <a data-no-pjax="true" href="<?= BASE_URL ?>/menu" class="nav-item text-center text-decoration-none d-flex flex-column align-items-center justify-content-center h-100 flex-grow-1 <?= (strpos($uri, '/menu') !== false) ? 'text-primary' : 'text-secondary' ?>">
            <i class="fa-solid fa-bars mb-1 fs-5"></i>
            <span style="font-size: 11px; font-weight: 600;">المزيد</span>
        </a>
    </nav>

    <!-- Toast Container: System Notifications -->
    <div class="toast-container position-fixed bottom-0 start-0 p-3" style="z-index: 1090;">
        <!-- System DB Notifications -->
        <?php foreach($systemNotifications as $idx => $notif): ?>
            <?php
                $bgColor = match($notif->type) {
                    'success' => '#198754',
                    'warning' => '#ffc107',
                    'danger'  => '#dc3545',
                    default   => '#0d6efd'
                };
                $textColor = ($notif->type === 'warning') ? '#000' : '#fff';
            ?>
            <div id="toast-sys-<?= $idx ?>" class="toast align-items-center border-0 shadow-lg" role="alert" aria-live="assertive" aria-atomic="true" style="background-color:<?= $bgColor ?>; color:<?= $textColor ?>;">
                <div class="d-flex">
                    <div class="toast-body">
                        <strong><?= htmlspecialchars($notif->title) ?></strong><br>
                        <small><?= htmlspecialchars($notif->message) ?></small>
                    </div>
                    <button type="button" class="btn-close <?= $notif->type === 'warning' ? '' : 'btn-close-white' ?> me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            </div>
        <?php endforeach; ?>

        <!-- Calendar Event Reminders -->
        <?php foreach($calendarNotifications as $idx => $ev): ?>
            <div id="toast-cal-<?= $idx ?>" class="toast align-items-center text-white border-0 shadow-lg" role="alert" aria-live="assertive" aria-atomic="true" style="background-color: <?= htmlspecialchars($ev->color_hex ?: '#0d6efd') ?>;">
                <div class="d-flex">
                    <div class="toast-body fw-bold">
                        <i class="fa-solid fa-calendar-check me-2"></i>
                        حدث اليوم: <?= htmlspecialchars($ev->title) ?>
                        <?= $ev->start_time ? ' الساعة ' . date('H:i', strtotime($ev->start_time)) : '' ?>
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            </div>
        <?php endforeach; ?>

        <!-- Smart Reminders -->
        <?php foreach($smartReminders as $idx => $sr): ?>
            <?php
                if ($sr['priority'] === 'high') { $bgColor = '#dc3545'; $icon = 'fa-triangle-exclamation'; }
                elseif ($sr['priority'] === 'medium') { $bgColor = '#fd7e14'; $icon = 'fa-bell'; }
                else { $bgColor = '#0dcaf0'; $icon = 'fa-circle-info'; }
                
                $mIcon = match($sr['module_type']) {
                    'health' => 'fa-heart-pulse',
                    'productivity' => 'fa-list-check',
                    'spiritual' => 'fa-kaaba',
                    'finance' => 'fa-wallet',
                    'education' => 'fa-graduation-cap',
                    default => 'fa-bell'
                };
            ?>
            <div id="toast-sr-<?= $idx ?>" class="toast border-0 shadow-lg text-white" data-bs-autohide="false" role="alert" aria-live="assertive" aria-atomic="true" style="background-color: <?= $bgColor ?>; min-width: 300px;">
                <div class="toast-header bg-transparent text-white border-bottom border-light border-opacity-25 pb-2 pt-2">
                    <i class="fa-solid <?= $mIcon ?> me-2 fs-5"></i>
                    <strong class="me-auto fs-6">تنبيه ذكي</strong>
                    <button type="button" class="btn-close btn-close-white ms-auto mt-1" data-bs-dismiss="toast" aria-label="Close" onclick="resolveSmartReminder(<?= $sr['id'] ?>, 'ignored')"></button>
                </div>
                <div class="toast-body p-3">
                    <div class="d-flex align-items-start mb-3">
                        <i class="fa-solid <?= $icon ?> fa-2x opacity-50 me-3 mt-1"></i>
                        <p class="mb-0 fw-bold fs-6 lh-base"><?= htmlspecialchars($sr['message']) ?></p>
                    </div>
                    <div class="d-flex justify-content-end">
                        <button class="btn btn-sm btn-light text-dark fw-bold rounded shadow-sm px-3 py-1" onclick="resolveSmartReminder(<?= $sr['id'] ?>, 'done'); $(this).closest('.toast').toast('hide');"><i class="fa-solid fa-check text-success me-1"></i> قمت بذلك</button>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- Bootstrap & JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="<?= BASE_URL ?>/assets/js/main.js?v=1.0.5"></script>
    <script src="<?= BASE_URL ?>/assets/js/push-notifications.js?v=1.0.1"></script>
    <script src="<?= BASE_URL ?>/assets/js/offline-sync.js?v=1.0.1"></script>

    <!-- ── Onboarding Modal ────────────────────────────────── -->
    <?php if (!empty($showOnboarding)): ?>
    <div class="modal fade" id="onboardingModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
      <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content border-0 rounded-4 shadow-lg" style="background: linear-gradient(135deg,#0f172a,#1e3a5f);color:#fff;">
          <div class="modal-body text-center p-5">
            <div class="display-3 mb-3">∞</div>
            <h2 class="fw-bold mb-2">أهلاً وسهلاً في OTIS</h2>
            <p class="text-white-50 fs-5 mb-4">نظام حياة متكامل لتتبع صحتك، مالك، روحانياتك وإنتاجيتك في مكان واحد.</p>
            <div class="row g-3 mb-4 text-start">
              <div class="col-md-4"><div class="card bg-white bg-opacity-10 border-0 rounded-3 p-3"><i class="fa-solid fa-heart text-danger fs-3 mb-2 d-block"></i><strong>الصحة</strong><br><small class="text-white-50">تتبع مؤشراتك اليومية</small></div></div>
              <div class="col-md-4"><div class="card bg-white bg-opacity-10 border-0 rounded-3 p-3"><i class="fa-solid fa-wallet text-success fs-3 mb-2 d-block"></i><strong>المال</strong><br><small class="text-white-50">راقب دخلك ومصروفاتك</small></div></div>
              <div class="col-md-4"><div class="card bg-white bg-opacity-10 border-0 rounded-3 p-3"><i class="fa-solid fa-kaaba text-warning fs-3 mb-2 d-block"></i><strong>الروحانيات</strong><br><small class="text-white-50">سجّل صلواتك وأذكارك</small></div></div>
            </div>
            <div class="d-flex gap-2 justify-content-center flex-wrap mb-3">
              <span class="badge bg-white bg-opacity-20 px-3 py-2 rounded-pill"><i class="fa-solid fa-keyboard me-1"></i> G → الرئيسية</span>
              <span class="badge bg-white bg-opacity-20 px-3 py-2 rounded-pill"><i class="fa-solid fa-keyboard me-1"></i> H → الصحة</span>
              <span class="badge bg-white bg-opacity-20 px-3 py-2 rounded-pill"><i class="fa-solid fa-keyboard me-1"></i> F → المال</span>
              <span class="badge bg-white bg-opacity-20 px-3 py-2 rounded-pill"><i class="fa-solid fa-keyboard me-1"></i> S → الروحانيات</span>
              <span class="badge bg-white bg-opacity-20 px-3 py-2 rounded-pill"><i class="fa-solid fa-keyboard me-1"></i> T → المهام</span>
            </div>
            <button class="btn btn-primary btn-lg rounded-pill fw-bold px-5" id="startOtisBtn">
              <i class="fa-solid fa-rocket me-2"></i> ابدأ رحلتك مع OTIS
            </button>
          </div>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // Init OTIS JS
            if (typeof OTIS !== 'undefined') {
                OTIS.init('<?= BASE_URL ?>');
            }

            var toastElList = [].slice.call(document.querySelectorAll('.toast'));
            toastElList.map(function (toastEl) {
                return new bootstrap.Toast(toastEl, { delay: 8000 });
            }).forEach(t => t.show());

            // ── Onboarding Modal ──────────────────────────────────
            <?php if (!empty($showOnboarding)): ?>
            const onboardModal = new bootstrap.Modal(document.getElementById('onboardingModal'));
            onboardModal.show();
            document.getElementById('startOtisBtn')?.addEventListener('click', () => {
                fetch('<?= BASE_URL ?>/system/completeOnboarding', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({})
                }).then(() => { onboardModal.hide(); });
            });
            <?php endif; ?>

            // ── Dark Mode DB Persistence ──────────────────────────
            const themeToggle = document.getElementById('themeToggle');
            if (themeToggle) {
                themeToggle.addEventListener('change', function() {
                    const newTheme = this.checked ? 'dark' : 'light';
                    fetch('<?= BASE_URL ?>/system/saveTheme', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({ theme: newTheme })
                    });
                });
            }
        });

        function resolveSmartReminder(id, status) {
            fetch('<?= BASE_URL ?>/system/resolveReminder', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id: id, status: status })
            });
        }
    </script>

    <!-- ── Global Keyboard Shortcuts ─────────────────────────── -->
    <script>
    (function() {
        const BASE = '<?= BASE_URL ?>';
        const shortcuts = {
            'g': '/',
            'h': '/health',
            'f': '/finance',
            's': '/spiritual',
            't': '/todo',
            'j': '/journal',
            'c': '/calendar',
            'b': '/behavior',
            'e': '/education',
            'a': '/advisor',
            'v': '/vault',
            '?': null  // Show help
        };

        document.addEventListener('keydown', function(e) {
            // Ignore if typing in input/textarea/contenteditable
            if (['INPUT','TEXTAREA','SELECT'].includes(e.target.tagName)) return;
            if (e.target.isContentEditable) return;
            if (e.ctrlKey || e.altKey || e.metaKey) return;

            const key = e.key.toLowerCase();
            if (key === '?') {
                showShortcutHelp();
                return;
            }
            if (shortcuts[key] !== undefined && shortcuts[key] !== null) {
                e.preventDefault();
                window.location.href = BASE + shortcuts[key];
            }
        });

        function showShortcutHelp() {
            const existing = document.getElementById('shortcutHelp');
            if (existing) { existing.remove(); return; }
            const box = document.createElement('div');
            box.id = 'shortcutHelp';
            box.style.cssText = 'position:fixed;bottom:80px;left:50%;transform:translateX(-50%);z-index:9999;background:rgba(15,23,42,0.95);color:#fff;border-radius:16px;padding:20px 30px;backdrop-filter:blur(10px);direction:ltr;min-width:340px;box-shadow:0 10px 40px rgba(0,0,0,0.4);';
            box.innerHTML = `<div style="text-align:center;margin-bottom:12px;font-weight:700;font-size:1rem;">⌨️ Keyboard Shortcuts</div>
              <div style="display:grid;grid-template-columns:1fr 1fr;gap:6px 20px;font-size:0.85rem;">
                <span><kbd>G</kbd> Home</span><span><kbd>H</kbd> Health</span>
                <span><kbd>F</kbd> Finance</span><span><kbd>S</kbd> Spiritual</span>
                <span><kbd>T</kbd> Tasks</span><span><kbd>J</kbd> Journal</span>
                <span><kbd>C</kbd> Calendar</span><span><kbd>B</kbd> Behavior</span>
                <span><kbd>E</kbd> Education</span><span><kbd>A</kbd> Advisor</span>
                <span><kbd>V</kbd> Vault</span><span><kbd>?</kbd> This Help</span>
              </div>`;
            document.body.appendChild(box);
            setTimeout(() => box.remove(), 4000);
        }
    })();
    </script>
</body>
</html>
