<?php
$current_url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// Ensure Auth User is available
if (!isset($authUser)) {
 $authUser = \App\Core\Auth::user();
}

$menuGroups = [
 [
 'id' => 'main',
 'title' => 'Dashboard',
 'icon' => 'fa-gauge-high',
 'url' => '/dashboard',
 'items' => []
 ],
 [
 'id' => 'crm',
 'title' => 'Admissions & CRM',
 'icon' => 'fa-users-viewfinder',
 'items' => [
 ['label' => 'Lead Management', 'icon' => 'fa-users-viewfinder', 'url' => '/admin/leads', 'permission' => 'leads'],
 ['label' => 'Our Students', 'icon' => 'fa-user-graduate', 'url' => '/admin/students', 'permission' => 'students'],
 ['label' => 'Admission', 'icon' => 'fa-graduation-cap', 'url' => '/admin/admissions', 'permission' => 'admissions'],
 ]
 ],
 [
 'id' => 'academic',
 'title' => 'Academic Setup',
 'icon' => 'fa-book-open',
 'items' => [
 ['label' => 'Our Courses', 'icon' => 'fa-book-open', 'url' => '/admin/courses', 'permission' => 'courses'],
 ['label' => 'Batch Management', 'icon' => 'fa-users-rectangle', 'url' => '/admin/batches', 'permission' => 'batches'],
 ['label' => 'Study Materials', 'icon' => 'fa-folder-open', 'url' => '/admin/study-materials', 'permission' => 'materials'],
 ['label' => 'Certificates', 'icon' => 'fa-certificate', 'url' => '/admin/certificates', 'permission' => 'certificates'],
 ['label' => 'Course Categories', 'icon' => 'fa-layer-group', 'url' => '/admin/categories', 'permission' => 'categories'],
 ]
 ],
 [
 'id' => 'faculty',
 'title' => 'Staff & HR',
 'icon' => 'fa-user-tie',
 'items' => [
 ['label' => 'Our Teachers', 'icon' => 'fa-chalkboard-user', 'url' => '/admin/teachers', 'permission' => 'teachers'],
 ['label' => 'Attendance', 'icon' => 'fa-clipboard-user', 'url' => '/admin/attendance', 'permission' => 'attendance'],
 ]
 ],
 [
 'id' => 'financial',
 'title' => 'Accounts & Fees',
 'icon' => 'fa-hand-holding-dollar',
 'items' => [
 ['label' => 'Fees Head', 'icon' => 'fa-tags', 'url' => '/admin/fee-heads', 'permission' => 'fees_head'],
 ['label' => 'Fees Management', 'icon' => 'fa-hand-holding-dollar', 'url' => '/admin/fees', 'permission' => 'fees_management'],
 ['label' => 'Expenses', 'icon' => 'fa-receipt', 'url' => '/admin/expenses', 'permission' => 'expenses'],
 ]
 ],
 [
 'id' => 'system',
 'title' => 'System Control',
 'icon' => 'fa-user-gear',
 'items' => [
 ['label' => 'User Management', 'icon' => 'fa-user-gear', 'url' => '/admin/users', 'permission' => 'users'],
 ['label' => 'Institute Settings', 'icon' => 'fa-gear', 'url' => '/admin/settings', 'permission' => 'settings'],
 ['label' => 'My Profile', 'icon' => 'fa-id-badge', 'url' => '/admin/profile', 'permission' => 'dashboard'],
 ]
 ],
];

// Determine which groups should be open based on current URL
$openGroups = [];
foreach ($menuGroups as $group) {
 if (!empty($group['items'])) {
 foreach ($group['items'] as $item) {
 $processedUrl = url($item['url']);
 if (parse_url($processedUrl, PHP_URL_PATH) === parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)) {
 $openGroups[] = $group['id'];
 break;
 }
 }
 }
}
$openGroupsJson = json_encode($openGroups);
?>

<div class="flex flex-col h-full bg-white" x-data="{ openGroups: <?php echo htmlspecialchars($openGroupsJson); ?> }">
 <!-- Fixed Logo Section -->
 <div class="flex items-center justify-between h-16 flex-none px-4 <?php echo $theme['bg'] ?? 'bg-blue-600'; ?> border-b border-white/10">
 <div class="flex items-center gap-3 overflow-hidden">
 <div class="flex-none bg-white p-1.5 rounded-xl overflow-hidden h-11 w-11 flex items-center justify-center transform hover:rotate-3 transition-transform duration-300">
 <?php if(!empty($siteSettings['institute_logo'])): ?>
 <img src="<?php echo url($siteSettings['institute_logo']); ?>" class="h-full w-full object-contain">
 <?php else: ?>
 <i class="fa-solid fa-graduation-cap <?php echo $theme['text'] ?? 'text-blue-600'; ?> text-xl"></i>
 <?php endif; ?>
 </div>
 <div x-show="sidebarOpen || mobileSidebar" x-transition:enter="transition-opacity duration-300" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100" class="flex flex-col leading-none">
 <span class="text-white font-black text-lg tracking-tight whitespace-nowrap">
 <?php echo $siteSettings['institute_name'] ?? 'Smart Tuitions'; ?>
 </span>
 <span class="text-[9px] font-bold text-white/60 uppercase tracking-widest mt-1"><?php echo ucfirst($authUser['role'] ?? 'Portal'); ?> Portal</span>
 </div>
 </div>
 <button @click="mobileSidebar = false" class="lg:hidden flex items-center justify-center h-9 w-9 rounded-xl bg-white/20 text-white hover:bg-white/30 transition-all active:scale-95">
 <i class="fa-solid fa-xmark text-lg"></i>
 </button>
 </div>

 <!-- Navigation with Custom Scrollbar -->
 <nav class="flex-1 px-3 py-6 space-y-2 overflow-y-auto custom-scrollbar">
 <?php foreach($menuGroups as $group): ?>
 <?php 
 $userPerms = json_decode($authUser['permissions'] ?? '[]', true);
 
 // If group has a direct URL (like Dashboard)
 if (isset($group['url']) && empty($group['items'])) {
 $processedUrl = url($group['url']);
 $isActive = (parse_url($processedUrl, PHP_URL_PATH) === parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
 ?>
 <a href="<?php echo $processedUrl; ?>"
 class="group flex items-center px-3 py-2.5 text-sm font-bold rounded-xl transition-all duration-200 <?php echo $isActive ? ($theme['bg-light'] ?? 'bg-blue-50') . ' ' . ($theme['text'] ?? 'text-blue-600') : 'text-gray-700 hover:bg-gray-50'; ?>">
 <div class="flex-none w-8 text-center">
 <i class="fa-solid <?php echo $group['icon']; ?> <?php echo $isActive ? ($theme['text'] ?? 'text-blue-600') : 'text-gray-400 group-hover:' . ($theme['text'] ?? 'text-blue-600'); ?> text-base"></i>
 </div>
 <span x-show="sidebarOpen || mobileSidebar" class="ml-2"><?php echo $group['title']; ?></span>
 </a>
 <?php
 continue;
 }

 // Filter sub-items based on permissions
 $filteredItems = array_filter($group['items'], function($item) use ($authUser, $userPerms) {
 if (!$authUser) return false;
 if ($authUser['role'] === 'admin') return true;
 return in_array($item['permission'], $userPerms);
 });

 if (empty($filteredItems)) continue;
 
 $isGroupActive = in_array($group['id'], $openGroups);
 ?>
 
 <div class="space-y-1" x-data="{ isOpen: openGroups.includes('<?php echo $group['id']; ?>') }">
 <button @click="isOpen = !isOpen"
 class="w-full group flex items-center justify-between px-3 py-2.5 text-sm font-bold rounded-xl transition-all duration-200 text-gray-700 hover:bg-gray-50">
 <div class="flex items-center">
 <div class="flex-none w-8 text-center">
 <i class="fa-solid <?php echo $group['icon']; ?> text-gray-400 group-hover:<?php echo $theme['text'] ?? 'text-blue-600'; ?> text-base"></i>
 </div>
 <span x-show="sidebarOpen || mobileSidebar" class="ml-2"><?php echo $group['title']; ?></span>
 </div>
 <i x-show="sidebarOpen || mobileSidebar" class="fa-solid fa-chevron-right text-[10px] transition-transform duration-200" :class="isOpen ? 'rotate-90' : ''"></i>
 </button>

 <div x-show="isOpen"
 x-transition:enter="transition ease-out duration-100"
 x-transition:enter-start="transform opacity-0 scale-95"
 x-transition:enter-end="transform opacity-100 scale-100"
 class="mt-1 ml-4 space-y-1 border-l-2 border-gray-50 pl-2">
 <?php foreach($filteredItems as $item): ?>
 <?php 
 $processedUrl = url($item['url']);
 $isActive = (parse_url($processedUrl, PHP_URL_PATH) === parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
 ?>
 <a href="<?php echo $processedUrl; ?>"
 class="flex items-center px-3 py-2 text-xs font-bold rounded-lg transition-all duration-200 <?php echo $isActive ? ($theme['bg-light'] ?? 'bg-blue-50') . ' ' . ($theme['text'] ?? 'text-blue-600') : 'text-gray-500 hover:text-gray-900 hover:bg-gray-50'; ?>">
 <i class="fa-solid <?php echo $item['icon']; ?> w-5 text-center mr-2 <?php echo $isActive ? ($theme['text'] ?? 'text-blue-600') : 'text-gray-300'; ?>"></i>
 <span x-show="sidebarOpen || mobileSidebar"><?php echo $item['label']; ?></span>
 </a>
 <?php endforeach; ?>
 </div>
 </div>
 <?php endforeach; ?>
 </nav>

 <!-- Fixed Bottom Logout Section -->
 <div class="p-3 border-t border-gray-100 flex-none bg-gray-50/50">
 <a href="<?php echo url('/logout'); ?>" class="w-full group flex items-center px-3 py-2.5 text-sm font-medium rounded-xl transition-all duration-200 text-red-600 hover:bg-red-50" title="Logout">
 <div class="flex-none w-8 text-center">
 <i class="fa-solid fa-power-off text-base text-red-600"></i>
 </div>
 <span x-show="sidebarOpen || mobileSidebar" class="ml-2 whitespace-nowrap font-bold">Logout</span>
 </a>
 </div>
</div>
