<!DOCTYPE html>
<html lang="id" data-bs-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="<?= csrf_hash() ?>">
    <meta name="csrf-name" content="<?= csrf_token() ?>">
    <title><?= $title ?? 'SIMAK' ?> | Sistem Informasi Manajemen Akademik</title>
    <?php helper('logo'); ?>
    <link rel="icon" type="image/png" href="<?= getLogo('sekolah') ?>">

    <!-- PWA Meta -->
    <meta name="theme-color" content="#0d6efd">
    <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="default">
    <meta name="apple-mobile-web-app-title" content="SIMAK PPDS">
    <link rel="apple-touch-icon" href="/assets/img/icons/icon-192x192.png">
    <link rel="manifest" href="/manifest.json">
    <link rel="stylesheet" href="/css/pwa.css">

    <!-- Bootstrap 5 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css">
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <style>
        :root {
            --sidebar-width: 250px;
            --navbar-height: 56px;
            --primary: #0d6efd;
            --bg-body: #f4f6fb;
            --sidebar-bg: #1e2a3a;
            --sidebar-text: #c8d6e5;
            --sidebar-active: #ffffff;
            --sidebar-hover: rgba(255,255,255,0.08);
            --border-color: #e0e6ef;
        }
        [data-bs-theme="dark"] {
            --bg-body: #12181f;
            --sidebar-bg: #161d27;
            --border-color: #2a3447;
        }
        body { background: var(--bg-body); font-size: 0.9rem; }

        /* NAVBAR */
        .navbar {
            height: var(--navbar-height);
            background: #fff;
            border-bottom: 1px solid var(--border-color);
            padding: 0 1rem;
            z-index: 1040;
        }
        [data-bs-theme="dark"] .navbar { background: #1a2233; }
        .navbar-brand img { height: 32px; }
        .nav-icon-btn {
            background: none; border: none;
            width: 36px; height: 36px;
            border-radius: 8px;
            display: flex; align-items: center; justify-content: center;
            color: #555; font-size: 1.1rem; cursor: pointer;
        }
        .nav-icon-btn:hover { background: var(--bg-body); }
        .nav-user-btn {
            background: none; border: none;
            border-radius: 10px; padding: 4px 8px;
            display: flex; align-items: center;
        }
        .nav-user-btn:hover { background: var(--bg-body); }
        .user-avatar {
            width: 32px; height: 32px;
            border-radius: 50%;
            background: #e8f0fe;
            display: flex; align-items: center; justify-content: center;
            color: var(--primary); font-size: 1.2rem;
        }
        .user-name { font-size: .82rem; font-weight: 600; line-height: 1.2; color: #333; }
        .user-role { font-size: .72rem; color: #888; }
        [data-bs-theme="dark"] .user-name { color: #e0e6ef; }

        /* SIDEBAR */
        .sidebar {
            position: fixed;
            top: var(--navbar-height);
            left: 0;
            width: var(--sidebar-width);
            height: calc(100vh - var(--navbar-height));
            background: var(--sidebar-bg);
            overflow-y: auto;
            transition: transform .3s ease, width .3s ease;
            z-index: 1030;
        }
        .sidebar-inner { padding: .5rem 0 1rem; }
        .sidebar-header {
            padding: .75rem 1.25rem;
            font-size: .75rem;
            font-weight: 600;
            color: #7a92ab;
            text-transform: uppercase;
            letter-spacing: .06em;
            border-bottom: 1px solid rgba(255,255,255,0.06);
            margin-bottom: .25rem;
        }
        .sidebar-menu { list-style: none; padding: 0; margin: 0; }
        .sidebar-item { margin: 1px 8px; }
        .sidebar-link {
            display: flex; align-items: center; gap: 10px;
            padding: 9px 14px;
            color: var(--sidebar-text);
            text-decoration: none;
            border-radius: 8px;
            font-size: .855rem;
            transition: all .2s;
        }
        .sidebar-link:hover { background: var(--sidebar-hover); color: #fff; }
        .sidebar-item.active > .sidebar-link { background: var(--primary); color: #fff; }
        .sidebar-link i { font-size: 1rem; width: 20px; text-align: center; }
        .submenu { list-style: none; padding: 0; margin: 2px 0 2px 20px; }
        .submenu li a {
            display: flex; align-items: center; gap: 8px;
            padding: 7px 14px;
            color: var(--sidebar-text);
            text-decoration: none;
            border-radius: 6px;
            font-size: .835rem;
            transition: all .2s;
        }
        .submenu li a:hover { background: var(--sidebar-hover); color: #fff; }
        .submenu li.active a { color: #fff; font-weight: 500; }
        .submenu-arrow { font-size: .65rem !important; transition: transform .2s; }
        .sidebar-link[aria-expanded="true"] .submenu-arrow { transform: rotate(180deg); }
        .sidebar-section {
            padding: .5rem 1.25rem .25rem;
            font-size: .7rem;
            font-weight: 600;
            color: #4a6278;
            text-transform: uppercase;
            letter-spacing: .07em;
            margin-top: .5rem;
        }
        /* Collapse toggle dalam sidebar-section */
        .sidebar-collapse-toggle {
            color: #4a6278;
            font-size: .7rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: .07em;
            padding: 0;
        }
        .sidebar-collapse-toggle:hover { color: #94a3b8; }
        .sidebar-collapse-toggle .submenu-arrow { font-size: .65rem !important; transition: transform .2s; margin-left:4px; }
        .sidebar-collapse-toggle[aria-expanded="false"] .submenu-arrow { transform: rotate(-90deg); }

        /* MAIN */
        .wrapper { display: flex; padding-top: var(--navbar-height); }
        .main-content {
            margin-left: var(--sidebar-width);
            flex: 1;
            min-height: calc(100vh - var(--navbar-height));
            transition: margin-left .3s ease;
            display: flex; flex-direction: column;
        }
        .page-header {
            padding: 1.25rem 1.5rem .75rem;
            background: #fff;
            border-bottom: 1px solid var(--border-color);
        }
        [data-bs-theme="dark"] .page-header { background: #1a2233; }
        .page-title { font-size: 1.15rem; font-weight: 600; }
        .content-area { padding: 1.5rem; flex: 1; }
        .main-footer {
            padding: .75rem 1.5rem;
            border-top: 1px solid var(--border-color);
            font-size: .8rem;
            color: #888;
            background: #fff;
        }
        [data-bs-theme="dark"] .main-footer { background: #1a2233; }

        /* STAT CARDS */
        .stat-card {
            border-radius: 12px;
            padding: 1.1rem 1.25rem;
            position: relative;
            overflow: hidden;
            color: #fff;
            min-height: 90px;
        }
        .stat-value { font-size: 1.8rem; font-weight: 700; line-height: 1; }
        .stat-label { font-size: .78rem; opacity: .88; margin-top: 4px; }
        .stat-icon {
            position: absolute; right: 12px; top: 50%;
            transform: translateY(-50%);
            font-size: 2.5rem; opacity: .2;
        }
        .bg-stat-1 { background: linear-gradient(135deg,#0d6efd,#3d8bfd); }
        .bg-stat-2 { background: linear-gradient(135deg,#6f42c1,#a06ee1); }
        .bg-stat-3 { background: linear-gradient(135deg,#20c997,#48dba4); }
        .bg-stat-4 { background: linear-gradient(135deg,#fd7e14,#ffa04d); }
        .bg-stat-5 { background: linear-gradient(135deg,#dc3545,#f06574); }
        .bg-stat-6 { background: linear-gradient(135deg,#198754,#28b473); }

        /* SIDEBAR COLLAPSED */
        .sidebar-collapsed .sidebar { width: 64px; }
        .sidebar-collapsed .sidebar .sidebar-header,
        .sidebar-collapsed .sidebar .sidebar-section,
        .sidebar-collapsed .sidebar span,
        .sidebar-collapsed .sidebar .submenu-arrow { display: none; }
        .sidebar-collapsed .sidebar-item { margin: 2px 6px; }
        .sidebar-collapsed .sidebar-link { justify-content: center; padding: 10px; }
        .sidebar-collapsed .main-content { margin-left: 64px; }

        /* MOBILE */
        .sidebar-overlay {
            display: none; position: fixed;
            inset: 0; background: rgba(0,0,0,.5);
            z-index: 1025;
        }
        @media (max-width: 991px) {
            .sidebar { transform: translateX(-100%); }
            .sidebar-open .sidebar { transform: translateX(0); }
            .sidebar-open .sidebar-overlay { display: block; }
            .main-content { margin-left: 0 !important; }
        }
    </style>
</head>
<body>

<!-- NAVBAR -->
<nav class="navbar fixed-top" id="mainNavbar">
    <div class="container-fluid">
        <button class="nav-icon-btn me-1 d-lg-none" id="sidebarToggleMobile">
            <i class="bi bi-list fs-4"></i>
        </button>
        <button class="nav-icon-btn me-1 d-none d-lg-flex" id="sidebarToggleDesktop">
            <i class="bi bi-layout-sidebar fs-5"></i>
        </button>
        <a class="navbar-brand d-flex align-items-center gap-2" href="/dashboard">
            <img src="<?= getLogo('sekolah') ?>" alt="Logo" style="width: auto; height: 32px; object-fit: contain;">
            <span class="fw-bold" style="font-size:.95rem">SIMAK</span>
        </a>
        <div class="ms-auto d-flex align-items-center gap-1">
            <?php
            $activePeriodModel = new \App\Models\AcademicPeriodModel();
            $activePeriod = $activePeriodModel->getActive();
            $activeYearName = $activePeriod ? $activePeriod['year_name'] : '2025/2026';
            ?>
            <span class="badge bg-primary bg-opacity-10 text-primary" style="font-size:.75rem">
                <i class="bi bi-calendar3 me-1"></i><?= esc($activeYearName) ?>
            </span>
            <button class="nav-icon-btn" id="darkModeToggle" title="Dark Mode">
                <i class="bi bi-moon-stars-fill" id="darkModeIcon"></i>
            </button>
            <div style="width:1px;height:28px;background:var(--border-color);margin:0 4px"></div>
            <div class="dropdown">
                <button class="nav-user-btn dropdown-toggle" type="button"
                    data-bs-toggle="dropdown">
                    <div class="d-flex align-items-center gap-2">
                        <div class="user-avatar">
                            <i class="bi bi-person-circle"></i>
                        </div>
                        <div class="d-none d-md-block text-start">
                            <div class="user-name"><?= session('user_name') ?></div>
                            <div class="user-role"><?= ucfirst(session('user_role')) ?></div>
                        </div>
                        <i class="bi bi-chevron-down" style="font-size:.65rem;color:#aaa"></i>
                    </div>
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                    <li>
                        <div class="dropdown-header">
                            <div class="fw-semibold"><?= session('user_name') ?></div>
                            <small class="text-muted"><?= ucfirst(session('user_role')) ?></small>
                        </div>
                    </li>
                    <li><hr class="dropdown-divider my-1"></li>
                    <li>
                        <a class="dropdown-item text-danger" href="/logout">
                            <i class="bi bi-box-arrow-right me-2"></i>Logout
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</nav>

<!-- WRAPPER -->
<div class="wrapper" id="wrapper">
    <!-- SIDEBAR -->
    <?php
    $userRole = session()->get('user_role');
    $isAdmin  = in_array($userRole, ['superadmin', 'admin']);
    $isGuru   = ($userRole == 'guru');
    $isTU     = ($userRole == 'tata_usaha');

    $isBk       = false;
    $isTeaching = false;
    $isHomeroom = false;

    if ($isGuru) {
        $sidebarCache = session()->get('sidebar_cache');

        if ($sidebarCache === null) {
            $userId = session()->get('user_id');
            $db     = \Config\Database::connect();

            $teacher = $db->table('teachers')
                          ->select('id')
                          ->where('user_id', $userId)
                          ->limit(1)
                          ->get()
                          ->getRowArray();

            $isBkResult       = false;
            $isTeachingResult = false;
            $isHomeroomResult = false;
            $isTahfidzResult  = false;

            if ($teacher) {
                $activePeriod = $db->table('academic_periods')
                                   ->where('is_active', 1)
                                   ->limit(1)
                                   ->get()
                                   ->getRowArray();

                if ($activePeriod) {
                    $bkResult = $db->table('bk_assignments')
                                   ->select('id')
                                   ->where('teacher_id', $teacher['id'])
                                   ->where('academic_period_id', $activePeriod['id'])
                                   ->limit(1)
                                   ->get()
                                   ->getRowArray();
                    $isBkResult = !empty($bkResult);

                    $teachingResult = $db->table('teaching_assignments')
                                        ->select('id')
                                        ->where('teacher_id', $teacher['id'])
                                        ->where('academic_period_id', $activePeriod['id'])
                                        ->limit(1)
                                        ->get()
                                        ->getRowArray();
                    $isTeachingResult = !empty($teachingResult);

                    $homeroomResult = $db->table('homeroom_assignments')
                                         ->select('homeroom_assignments.classroom_id, classrooms.name as classroom_name')
                                         ->join('classrooms', 'classrooms.id = homeroom_assignments.classroom_id')
                                         ->where('homeroom_assignments.teacher_id', $teacher['id'])
                                         ->where('homeroom_assignments.academic_period_id', $activePeriod['id'])
                                         ->limit(1)
                                         ->get()
                                         ->getRowArray();
                    $isHomeroomResult = !empty($homeroomResult);
                    $homeroomClassroomName = $isHomeroomResult ? $homeroomResult['classroom_name'] : null;

                    // Ambil program tahfidz yang diampu guru
                    $tahfidzPrograms = $db->query("
                        SELECT tp.id, tp.name, tp.type
                        FROM tahfidz_programs tp
                        JOIN tahfidz_program_teachers tpt ON tpt.program_id = tp.id
                        WHERE tpt.teacher_id = ?
                          AND tp.academic_period_id = ?
                          AND tp.deleted_at IS NULL
                          AND tp.is_active = 1
                    ", [$teacher['id'], $activePeriod['id']])->getResultArray();
                }
            }

            session()->set('sidebar_cache', [
                'is_bk'                  => $isBkResult,
                'is_teaching'            => $isTeachingResult,
                'is_homeroom'            => $isHomeroomResult,
                'homeroom_classroom_name'=> $homeroomClassroomName ?? null,
                'tahfidz_programs'       => $tahfidzPrograms ?? [],
            ]);

            $isBk              = $isBkResult;
            $isTeaching        = $isTeachingResult;
            $isHomeroom        = $isHomeroomResult;
        } else {
            $isBk             = (bool) ($sidebarCache['is_bk']              ?? false);
            $isTeaching       = (bool) ($sidebarCache['is_teaching']         ?? false);
            $isHomeroom       = (bool) ($sidebarCache['is_homeroom']         ?? false);
            $homeroomClassroomName = $sidebarCache['homeroom_classroom_name'] ?? null;
        }

        // Ambil program tahfidz yang diampu guru secara real-time (tanpa cache) agar menu langsung ter-update
        $db = $db ?? \Config\Database::connect();
        $userId = session()->get('user_id');
        $teacher = $db->table('teachers')->select('id')->where('user_id', $userId)->limit(1)->get()->getRowArray();
        $myTahfidzPrograms = [];
        if ($teacher) {
            $activePeriod = $db->table('academic_periods')->where('is_active', 1)->limit(1)->get()->getRowArray();
            if ($activePeriod) {
                $myTahfidzPrograms = $db->query("
                    SELECT tp.id, tp.name, tp.type
                    FROM tahfidz_programs tp
                    JOIN tahfidz_program_teachers tpt ON tpt.program_id = tp.id
                    WHERE tpt.teacher_id = ?
                      AND tp.academic_period_id = ?
                      AND tp.deleted_at IS NULL
                      AND tp.is_active = 1
                ", [$teacher['id'], $activePeriod['id']])->getResultArray();
            }
        }
    }

    $settingsCache = session()->get('sidebar_settings_cache');

    if ($settingsCache === null) {
        $db            = $db ?? \Config\Database::connect();
        $bkActiveRow   = $db->table('settings')->select('setting_value')->where('setting_key', 'bk_manual_active')->limit(1)->get()->getRowArray();
        $qrActiveRow   = $db->table('settings')->select('setting_value')->where('setting_key', 'qr_scan_active')->limit(1)->get()->getRowArray();
        $sourceRow     = $db->table('settings')->select('setting_value')->where('setting_key', 'schedule_source')->limit(1)->get()->getRowArray();
        $attModeRow    = $db->table('settings')->select('setting_value')->where('setting_key', 'attendance_mode')->limit(1)->get()->getRowArray();

        $settingsCache = [
            'bk_active'       => $bkActiveRow['setting_value']  ?? '1',
            'qr_active'       => $qrActiveRow['setting_value']  ?? '1',
            'schedule_source' => $sourceRow['setting_value']    ?? 'local',
            'attendance_mode' => $attModeRow['setting_value']   ?? 'manual',
        ];
        session()->set('sidebar_settings_cache', $settingsCache);
    }

    $isBkActive     = ($settingsCache['bk_active'] ?? '1') === '1';
    $isQrActive     = ($settingsCache['qr_active'] ?? '1') === '1';
    $scheduleSource = $settingsCache['schedule_source'] ?? 'local';
    ?>

    <nav class="sidebar" id="sidebar">
        <div class="sidebar-inner">
            <div class="sidebar-header">Menu Utama</div>
            <ul class="sidebar-menu">
                <?php
                helper('menu');
                $userContext = [
                    'role'                    => $userRole,
                    'is_bk'                   => $isBk,
                    'is_teaching'             => $isTeaching,
                    'is_homeroom'             => $isHomeroom,
                    'my_tahfidz_programs'     => $myTahfidzPrograms ?? [],
                    'bk_active'               => $isBkActive,
                    'qr_active'               => $isQrActive,
                    'schedule_source'         => $scheduleSource,
                    'attendance_mode'         => $settingsCache['attendance_mode'] ?? 'manual',
                    'homeroom_classroom_name' => $homeroomClassroomName ?? null,
                ];
                echo render_sidebar_menu($userContext);
                ?>
            </ul>
        </div>
    </nav>

    <!-- OVERLAY -->
    <div class="sidebar-overlay" id="sidebarOverlay"></div>

    <!-- MAIN CONTENT -->
    <div class="main-content" id="mainContent">
        <!-- Page Header -->
        <div class="page-header">
            <h4 class="page-title mb-0"><?= $title ?? 'Dashboard' ?></h4>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-0 small">
                    <li class="breadcrumb-item"><a href="/dashboard">Home</a></li>
                    <li class="breadcrumb-item active"><?= $title ?? 'Dashboard' ?></li>
                </ol>
            </nav>
        </div>

        <!-- Flash Messages -->
        <?php if (session()->getFlashdata('success')): ?>
        <div class="alert alert-success alert-dismissible fade show m-3 mb-0" role="alert">
            <i class="bi bi-check-circle me-2"></i><?= session()->getFlashdata('success') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show m-3 mb-0" role="alert">
            <i class="bi bi-exclamation-circle me-2"></i><?= session()->getFlashdata('error') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <!-- Content -->
        <div class="content-area">
            <?= $this->renderSection('content') ?>
        </div>

        <!-- Footer -->
        <footer class="main-footer">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                <span>
                    <i class="bi bi-mortarboard-fill me-1 text-primary"></i>
                    <strong>SIMAK</strong> &copy; <?= date('Y') ?>
                </span>
                <span class="text-muted small">Sistem Informasi Manajemen Akademik &bull; V<?= get_app_version() ?></span>
            </div>
        </footer>
    </div>
</div>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    // Dark Mode
    const html = document.documentElement;
    const icon = document.getElementById('darkModeIcon');
    if (localStorage.getItem('darkMode') === 'true') {
        html.setAttribute('data-bs-theme', 'dark');
        icon.className = 'bi bi-sun-fill';
    }
    document.getElementById('darkModeToggle').addEventListener('click', () => {
        const isDark = html.getAttribute('data-bs-theme') === 'dark';
        html.setAttribute('data-bs-theme', isDark ? 'light' : 'dark');
        icon.className = isDark ? 'bi bi-moon-stars-fill' : 'bi bi-sun-fill';
        localStorage.setItem('darkMode', !isDark);
    });

    // Sidebar Desktop Toggle
    document.getElementById('sidebarToggleDesktop').addEventListener('click', () => {
        document.getElementById('wrapper').classList.toggle('sidebar-collapsed');
    });

    // Sidebar Mobile Toggle
    document.getElementById('sidebarToggleMobile').addEventListener('click', () => {
        document.getElementById('wrapper').classList.toggle('sidebar-open');
    });
    document.getElementById('sidebarOverlay').addEventListener('click', () => {
        document.getElementById('wrapper').classList.remove('sidebar-open');
    });

</script>
<?= $this->renderSection('scripts') ?>

<!-- PWA -->
<script src="/js/pwa.js"></script>
</body>
</html>