<?php

if (!function_exists('get_dashboard_url')) {
    /**
     * Mendapatkan URL dashboard berdasarkan role pengguna.
     */
    function get_dashboard_url($role) {
        switch ($role) {
            case 'kamad':
                return '/kamad/dashboard';
            case 'guru':
                return '/guru/dashboard';
            case 'tata_usaha':
                return '/tata-usaha/dashboard';
            case 'siswa':
                return '/siswa/dashboard';
            default:
                return '/dashboard';
        }
    }
}

if (!function_exists('check_menu_access')) {
    /**
     * Memeriksa apakah menu/sub-menu dapat diakses oleh user saat ini.
     */
    function check_menu_access($item, $context) {
        // 1. Cek batasan role
        if (isset($item['roles']) && !in_array($context['role'], $item['roles'])) {
            return false;
        }

        // 2. Cek batasan kondisi tambahan
        if (isset($item['conditions'])) {
            foreach ($item['conditions'] as $condition) {
                switch ($condition) {
                    case 'is_teaching':
                        if (!$context['is_teaching']) return false;
                        break;
                    case 'is_bk':
                        if (!$context['is_bk']) return false;
                        break;
                    case 'is_homeroom':
                        if (!isset($context['is_homeroom']) || !$context['is_homeroom']) return false;
                        break;
                    case 'is_tahfidz_teacher':
                        if (empty($context['my_tahfidz_programs'])) return false;
                        break;
                    case 'any_teaching_or_bk':
                        if (!$context['is_teaching'] && !$context['is_bk'] && !($context['is_homeroom'] ?? false)) return false;
                        break;
                    case 'bk_manual_allowed':
                        $isAdmin = in_array($context['role'], ['superadmin', 'admin', 'operator']);
                        $mode = $context['attendance_mode'] ?? 'manual';
                        $isActive = ($mode === 'manual');
                        $isBkAllowed = ($context['is_bk'] && $context['bk_active']);
                        if (!$isAdmin && !$isBkAllowed) return false;
                        if ($isAdmin && !$isActive) return false;
                        break;
                    case 'bk_qr_allowed':
                        $isAdmin = in_array($context['role'], ['superadmin', 'admin', 'operator']);
                        $mode = $context['attendance_mode'] ?? 'manual';
                        $isActive = ($mode === 'qr');
                        $isQrAllowed = ($context['is_bk'] && $context['qr_active']);
                        if (!$isAdmin && !$isQrAllowed) return false;
                        if ($isAdmin && !$isActive) return false;
                        break;
                    case 'local_schedule_only':
                        $source = $context['schedule_source'] ?? 'local';
                        if ($source !== 'local') return false;
                        break;
                    case 'asc_schedule_only':
                        $source = $context['schedule_source'] ?? 'local';
                        if ($source !== 'asc') return false;
                        break;
                    case 'manual_schedule_only':
                        $source = $context['schedule_source'] ?? 'local';
                        if ($source !== 'manual') return false;
                        break;
                }
            }
        }

        return true;
    }
}

if (!function_exists('is_menu_active')) {
    /**
     * Memeriksa apakah menu ini aktif berdasarkan URL saat ini.
     */
    function is_menu_active($item) {
        $currentPath = current_url(true)->getPath();
        if (str_starts_with($currentPath, '/index.php')) {
            $currentPath = substr($currentPath, 10);
            if (empty($currentPath)) {
                $currentPath = '/';
            }
        }
        $url = $item['url'] ?? '';
        $checkType = $item['active_check'] ?? 'exact';

        if ($url === '/dashboard') {
            return in_array($currentPath, ['/dashboard', '/guru/dashboard', '/tata-usaha/dashboard', '/siswa/dashboard', '/kamad/dashboard']);
        }

        // Parsing URL menu untuk mengekstrak query parameters jika ada
        $parsedMenuUrl = parse_url($url);
        $menuPath = $parsedMenuUrl['path'] ?? '';
        $menuQuery = [];
        if (isset($parsedMenuUrl['query'])) {
            parse_str($parsedMenuUrl['query'], $menuQuery);
        }

        // Jika menu memiliki filter program_id, cocokkan dengan program_id di request saat ini
        if (isset($menuQuery['program_id'])) {
            $reqProgramId = request()->getGet('program_id');
            
            $isPathMatch = false;
            if ($currentPath === $menuPath) {
                $isPathMatch = true;
            } elseif (str_starts_with($currentPath, '/guru/tahfidz') && str_starts_with($menuPath, '/guru/tahfidz')) {
                $isPathMatch = true;
            } elseif (str_starts_with($currentPath, '/siswa/tahfidz') && str_starts_with($menuPath, '/siswa/tahfidz')) {
                $isPathMatch = true;
            }

            if ($isPathMatch && $reqProgramId == $menuQuery['program_id']) {
                return true;
            }
            return false;
        }

        if ($checkType === 'prefix') {
            if ($url === '/student' && str_starts_with($currentPath, '/student/alumni')) {
                return false;
            }
            if ($url === '/manual-schedule/input' && (str_starts_with($currentPath, '/manual-schedule/input') || str_starts_with($currentPath, '/manual-schedule/edit'))) {
                return true;
            }
            if ($url === '/manual-schedule' && (str_starts_with($currentPath, '/manual-schedule/input') || str_starts_with($currentPath, '/manual-schedule/edit'))) {
                return false;
            }
            return str_starts_with($currentPath, $url);
        }

        if ($checkType === 'contains') {
            return str_contains($currentPath, $url) || str_contains(uri_string(), basename($url));
        }

        return $currentPath === $url;
    }
}

if (!function_exists('render_sidebar_menu')) {
    /**
     * Merender HTML menu sidebar secara dinamis.
     */
    function render_sidebar_menu($context) {
        $config = new \Config\Menus();
        $menuItems = $config->menuItems;

        // ── PROSES DINAMISASI MENU TAHFIDZ ──
        $processedMenuItems = [];
        foreach ($menuItems as $item) {
            // SISI GURU: Pecah menu Tahfidz per program yang diampu di bawah SATU menu collapsible induk
            if ($context['role'] === 'guru' && isset($item['collapse_id']) && $item['collapse_id'] === 'menuTahfidz') {
                $myPrograms = $context['my_tahfidz_programs'] ?? [];
                
                $newChildren = [];
                foreach ($myPrograms as $p) {
                    $typeName = match($p['type']) {
                        'pk' => 'Tahfidz PK',
                        'boarding' => 'Tahfidz Boarding',
                        default => 'Tahfidz KBM Pagi'
                    };
                    $newChildren[] = [
                        'title' => $typeName . ' - ' . ($p['name'] ?? ''),
                        'icon' => 'bi bi-book-half',
                        'url' => '/guru/tahfidz?program_id=' . $p['id'],
                        'roles' => ['guru'],
                    ];
                }

                // Jika guru tidak mengampu program tahfidz apapun, sembunyikan menu tahfidz ini
                if (empty($newChildren)) {
                    continue;
                }

                $item['children'] = $newChildren;
                $processedMenuItems[] = $item;
                continue;
            }

            // SISI SISWA: Tidak perlu manipulasi per-program di sini.
            // Menu Tahfidz Al-Qur'an statis di Menus.php sudah cukup.
            // Pemilihan program dilakukan via tab/selector di dalam halaman /siswa/tahfidz.

            $processedMenuItems[] = $item;
        }

        $html = '';

        foreach ($processedMenuItems as $item) {
            // Filter menu utama
            if (!check_menu_access($item, $context)) {
                continue;
            }

            // Jika item adalah Section
            if (isset($item['is_section']) && $item['is_section'] === true) {
                // Filter child yang bisa diakses
                $activeChildren = [];
                if (isset($item['children'])) {
                    foreach ($item['children'] as $child) {
                        if (check_menu_access($child, $context)) {
                            $activeChildren[] = $child;
                        }
                    }
                }

                // Jika section tidak memiliki anak yang aktif, sembunyikan section
                if (empty($activeChildren)) {
                    continue;
                }

                $isFlat = (isset($item['is_flat']) && $item['is_flat'] === true);
                if (in_array($context['role'], ['guru', 'tata_usaha']) && !(isset($item['force_collapse']) && $item['force_collapse'] === true)) {
                    $isFlat = true;
                }

                if ($isFlat) {
                    $html .= '<div class="sidebar-section">';
                    $html .= '    <span>' . esc($item['title']) . '</span>';
                    $html .= '</div>';

                    foreach ($activeChildren as $child) {
                        $activeClass = is_menu_active($child) ? 'active' : '';
                        $targetUrl = $child['url'];
                        if ($targetUrl === '/dashboard') {
                            $targetUrl = get_dashboard_url($context['role']);
                        }

                        $targetAttr = isset($child['target']) ? ' target="' . esc($child['target']) . '"' : '';
                        $html .= '<li class="sidebar-item ' . $activeClass . '">';
                        $html .= '    <a href="' . $targetUrl . '" class="sidebar-link"' . $targetAttr . '>';
                        $html .= '        <i class="' . esc($child['icon']) . '"></i>';
                        $html .= '        <span>' . esc($child['title']) . '</span>';
                        $html .= '    </a>';
                        $html .= '</li>';
                    }
                } else {
                    // Hitung apakah section ini harus diekspansi (jika ada anak yang aktif)
                    $isExpanded = false;
                    foreach ($activeChildren as $child) {
                        if (is_menu_active($child)) {
                            $isExpanded = true;
                            break;
                        }
                    }

                    $collapseClass = $isExpanded ? 'show' : '';
                    $ariaExpanded = $isExpanded ? 'true' : 'false';

                    $title = $item['title'];
                    if ($item['collapse_id'] === 'menuWalas' && isset($context['homeroom_classroom_name'])) {
                        $title = 'Wali Kelas (' . $context['homeroom_classroom_name'] . ')';
                    }

                    $html .= '<div class="sidebar-section">';
                    $html .= '    <a class="sidebar-collapse-toggle d-flex align-items-center justify-content-between text-decoration-none w-100"';
                    $html .= '       data-bs-toggle="collapse" href="#' . $item['collapse_id'] . '" role="button"';
                    $html .= '       aria-expanded="' . $ariaExpanded . '">';
                    $html .= '        <span>' . esc($title) . '</span>';
                    $html .= '        <i class="bi bi-chevron-down submenu-arrow"></i>';
                    $html .= '    </a>';
                    $html .= '</div>';
                    $html .= '<div class="collapse ' . $collapseClass . '" id="' . $item['collapse_id'] . '">';

                    foreach ($activeChildren as $child) {
                        $activeClass = is_menu_active($child) ? 'active' : '';
                        $targetUrl = $child['url'];
                        if ($targetUrl === '/dashboard') {
                            $targetUrl = get_dashboard_url($context['role']);
                        }

                        $targetAttr = isset($child['target']) ? ' target="' . esc($child['target']) . '"' : '';
                        $html .= '<li class="sidebar-item ' . $activeClass . '">';
                        $html .= '    <a href="' . $targetUrl . '" class="sidebar-link"' . $targetAttr . '>';
                        $html .= '        <i class="' . esc($child['icon']) . '"></i>';
                        $html .= '        <span>' . esc($child['title']) . '</span>';
                        $html .= '    </a>';
                        $html .= '</li>';
                    }

                    $html .= '</div>';
                }
            } else {
                // Item single di root sidebar menu (contoh: Dashboard)
                $activeClass = is_menu_active($item) ? 'active' : '';
                $targetUrl = $item['url'];
                if ($targetUrl === '/dashboard') {
                    $targetUrl = get_dashboard_url($context['role']);
                }

                $targetAttr = isset($item['target']) ? ' target="' . esc($item['target']) . '"' : '';
                $html .= '<li class="sidebar-item ' . $activeClass . '">';
                $html .= '    <a href="' . $targetUrl . '" class="sidebar-link"' . $targetAttr . '>';
                $html .= '        <i class="' . esc($item['icon']) . '"></i>';
                $html .= '        <span>' . esc($item['title']) . '</span>';
                $html .= '    </a>';
                $html .= '</li>';
            }
        }

        return $html;
    }
}
