<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>@yield('title', 'Admin Panel') - {{ config('app.name') }}</title>

    <!-- Admin Favicon -->
    <link rel="icon" type="image/png" href="{{ asset($siteSettings['admin_favicon'] ?? $siteSettings['site_favicon'] ?? 'images/favicon.ico') }}">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- Google Fonts -->
    <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=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">

    <!-- Temporary fix - removed problematic built assets -->
    <style>
        * { font-family: 'Poppins', sans-serif !important; }
        body { background-color: #f4f6f9 !important; }
    </style>

    <!-- Material Icons -->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!-- Material Icons fallback from CDN -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/material-design-icons/3.0.1/iconfont/material-icons.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet">

    <!-- DataTables CSS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/datatables.net-bs4@1.13.4/css/dataTables.bootstrap4.min.css"
          onerror="console.error('❌ DataTables CSS failed to load');"
          onload="console.log('✅ DataTables CSS loaded');">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/datatables.net-responsive-bs4@2.4.1/css/responsive.bootstrap4.min.css"
          onerror="console.error('❌ DataTables Responsive CSS failed to load');"
          onload="console.log('✅ DataTables Responsive CSS loaded');">

    <!-- DataTables CSS Fallback -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Check if DataTables CSS loaded by checking for specific styles
            setTimeout(function() {
                if (!document.querySelector('link[href*="dataTables"]')) {
                    console.log('🔄 Loading DataTables CSS fallback...');
                    const fallbackCSS = document.createElement('link');
                    fallbackCSS.rel = 'stylesheet';
                    fallbackCSS.href = 'https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap4.min.css';
                    document.head.appendChild(fallbackCSS);
                }
            }, 100);
        });
    </script>

    <!-- Admin Assets -->
    <link type="text/css" href="{{ asset('admin-assets/css/app.css') }}" rel="stylesheet">

    <!-- Admin Custom Styles -->
    <link type="text/css" href="{{ asset('admin-assets/css/admin-custom.css') }}" rel="stylesheet">

    <!-- Warehouse Components CSS -->
    <link type="text/css" href="{{ asset('admin-assets/css/warehouse-components.css') }}" rel="stylesheet">

    <!-- Custom Brand & Navbar Styles -->
    <style>
        /* Material Icons fix */
        .material-icons {
            font-family: 'Material Icons', 'Material Icons Fallback', sans-serif !important;
            font-weight: normal;
            font-style: normal;
            font-size: 24px;
            line-height: 1;
            letter-spacing: normal;
            text-transform: none;
            display: inline-block;
            white-space: nowrap;
            word-wrap: normal;
            direction: ltr;
            -webkit-font-feature-settings: 'liga';
            -webkit-font-smoothing: antialiased;
            text-rendering: optimizeLegibility;
            -moz-osx-font-smoothing: grayscale;
            font-feature-settings: 'liga';
        }

        /* Navbar fixes */
        .navbar {
            z-index: 1030;
        }

        .navbar-brand {
            font-size: 1.25rem;
        }

        .navbar-nav .dropdown-menu {
            min-width: 250px;
            border: none;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        }

        /* Fix dropdown positioning */
        .navbar-nav .nav-item.dropdown {
            position: relative;
        }

        .navbar-nav .dropdown-menu {
            position: absolute !important;
            top: 100% !important;
            right: 0 !important;
            left: auto !important;
            transform: translateY(5px) !important;
            display: none;
        }

        .navbar-nav .dropdown-menu.show {
            display: block !important;
            opacity: 1 !important;
            visibility: visible !important;
            transform: translateY(5px) !important;
            background-color: white !important;
            border: 1px solid rgba(0,0,0,0.15) !important;
            border-radius: 0.375rem !important;
            z-index: 9999 !important;
            min-width: 250px !important;
            max-width: 300px !important;
        }

        /* Ensure navbar container doesn't clip the dropdown */
        .navbar {
            overflow: visible !important;
        }

        .navbar .container-fluid {
            overflow: visible !important;
        }

        /* Force dropdown to be visible in all scenarios */
        #navbarDropdown + .dropdown-menu {
            z-index: 10000 !important;
            position: fixed !important;
            top: 70px !important;
            right: 15px !important;
            left: auto !important;
            margin-top: 0 !important;
            min-top: 60px !important;
        }

        /* Prevent any negative top positioning */
        #navbarDropdown + .dropdown-menu.show {
            top: 70px !important;
            min-height: auto !important;
            background-color: white !important;
            border: 1px solid #dee2e6 !important;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
            transform: none !important;
        }

        /* Ensure the dropdown is always visible when shown */
        .dropdown-menu.show {
            z-index: 99999 !important;
            opacity: 1 !important;
            pointer-events: auto !important;
            visibility: visible !important;
            isolation: isolate !important;
        }

        /* Create a new stacking context for the navbar dropdown */
        .navbar .nav-item.dropdown {
            position: relative;
            z-index: 100000 !important;
            isolation: isolate !important;
        }

        /* Create a completely new dropdown that bypasses all conflicts */
        #custom-profile-dropdown {
            position: fixed !important;
            top: 70px !important;
            right: 15px !important;
            width: 280px !important;
            background: white !important;
            border: 1px solid #dee2e6 !important;
            border-radius: 0.375rem !important;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
            z-index: 999999 !important;
            display: none !important;
            padding: 0 !important;
            margin: 0 !important;
        }

        #custom-profile-dropdown.show {
            display: block !important;
        }

        #custom-profile-dropdown .profile-info {
            padding: 1rem;
            border-bottom: 1px solid #dee2e6;
            background-color: #f8f9fa;
        }

        #custom-profile-dropdown .profile-links {
            padding: 0.5rem 0;
        }

        #custom-profile-dropdown .profile-links a,
        #custom-profile-dropdown .profile-links button {
            display: block;
            width: 100%;
            padding: 0.75rem 1rem;
            color: #333;
            text-decoration: none;
            border: none;
            background: none;
            text-align: left;
            font-size: 0.875rem;
        }

        #custom-profile-dropdown .profile-links a:hover,
        #custom-profile-dropdown .profile-links button:hover {
            background-color: #f8f9fa;
        }

        .dropdown-header {
            padding: 0.75rem 1rem;
            background-color: #f8f9fa;
        }

        .dropdown-item {
            padding: 0.5rem 1rem;
        }

        .dropdown-item:hover {
            background-color: #f8f9fa;
        }

        /* Responsive navbar brand */
        @media (max-width: 576px) {
            .navbar-brand-text {
                display: none !important;
            }
        }
        @media (max-width: 768px) {
            .navbar-brand-text {
                font-size: 16px !important;
            }
        }

        /* Universal Search Styles */
        .universal-search-container {
            position: relative;
            z-index: 1050;
        }

        .universal-search-container .input-group {
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
            border-radius: 6px;
            overflow: hidden;
            transition: box-shadow 0.2s ease;
            border: 1px solid #e0e0e0;
        }

        .universal-search-container .input-group:focus-within {
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
            border-color: #667eea;
        }

        .universal-search-container .form-control {
            border: none !important;
            font-size: 13px;
            height: 36px;
            padding-top: 0.375rem;
            padding-bottom: 0.375rem;
            background: transparent;
        }

        .universal-search-container .form-control:focus {
            border: none !important;
            box-shadow: none !important;
            outline: none;
        }

        .universal-search-container .input-group-text {
            border: none !important;
            background: transparent;
            height: 36px;
            padding: 0.375rem 0.75rem;
        }

        .universal-search-container .input-group-prepend,
        .universal-search-container .input-group-append {
            margin: 0;
        }

        .universal-search-results {
            position: absolute;
            top: calc(100% + 4px);
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
            max-height: 480px;
            overflow-y: auto;
            z-index: 9999;
            margin-top: 2px;
        }

        .search-result-item {
            display: flex;
            align-items: center;
            padding: 10px 14px;
            text-decoration: none;
            color: #333;
            border-bottom: 1px solid #f5f5f5;
            transition: all 0.15s ease;
        }

        .search-result-item:hover,
        .search-result-item.active {
            background-color: #f5f7ff;
            text-decoration: none;
            color: #333;
            border-left: 3px solid #667eea;
            padding-left: 11px;
        }

        .search-result-item:last-child {
            border-bottom: none;
        }

        .search-result-icon {
            width: 36px;
            height: 36px;
            border-radius: 6px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            flex-shrink: 0;
        }

        .search-result-icon i {
            color: white;
            font-size: 18px;
        }

        .search-result-content {
            flex: 1;
            min-width: 0;
        }

        .search-result-label {
            font-weight: 500;
            font-size: 13px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-bottom: 2px;
            line-height: 1.4;
        }

        .search-result-subtitle {
            font-size: 11px;
            color: #666;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1.3;
        }

        .search-result-type {
            font-size: 9px;
            text-transform: uppercase;
            font-weight: 600;
            letter-spacing: 0.3px;
            padding: 4px 8px;
            border-radius: 3px;
            margin-left: 10px;
            flex-shrink: 0;
        }

        .search-results-category {
            padding: 8px 14px;
            font-size: 10px;
            font-weight: 600;
            text-transform: uppercase;
            color: #999;
            background: #fafafa;
            letter-spacing: 0.5px;
            border-bottom: 1px solid #f0f0f0;
        }

        .search-results-category:first-child {
            border-top-left-radius: 6px;
            border-top-right-radius: 6px;
        }

        /* Keyboard navigation hint */
        .search-keyboard-hint {
            padding: 6px 14px;
            background: #fafafa;
            border-top: 1px solid #e8e8e8;
            font-size: 10px;
            color: #999;
            display: flex;
            justify-content: space-between;
            border-bottom-left-radius: 6px;
            border-bottom-right-radius: 6px;
        }

        .search-keyboard-hint span {
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .search-keyboard-hint kbd {
            background: #e5e5e5;
            padding: 2px 5px;
            border-radius: 2px;
            font-size: 9px;
            font-family: inherit;
            font-weight: 500;
            box-shadow: 0 1px 1px rgba(0,0,0,0.1);
        }

        @media (max-width: 992px) {
            .universal-search-container {
                max-width: 400px !important;
            }
        }

        @media (max-width: 768px) {
            .universal-search-container {
                max-width: 300px !important;
            }
        }
    </style>

    @stack('styles')
</head>

<body class="layout-default">
    <div class="preloader"></div>

    <!-- Header Layout -->
    <div class="mdk-header-layout js-mdk-header-layout">

        <!-- Header -->
        <div id="header" class="mdk-header js-mdk-header m-0" data-fixed>
            <div class="mdk-header__content">
                <div class="navbar navbar-expand-sm navbar-main navbar-light bg-light pr-0" id="navbar" data-primary>
                    <div class="container-fluid p-0">

                        <!-- Navbar toggler -->
                        <button class="navbar-toggler d-block d-lg-none" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                            <span class="navbar-toggler-icon"></span>
                        </button>

                        <!-- Navbar Brand -->
                        <a href="{{ route('admin.dashboard') }}" class="navbar-brand d-flex align-items-center">
                            <img src="{{ asset($siteSettings['site_logo'] ?? 'assets/images/admin-logo.svg') }}" alt="{{ $siteSettings['site_name'] ?? 'UFG' }} Logo" style="height: 52px;" class="navbar-brand-img mr-2">
                            <span class="navbar-brand-text font-weight-bold" style="font-size: 18px; color: #2c3e50;">{{ $siteSettings['site_name'] ?? 'KCG Inventory' }}</span>
                        </a>

                        <!-- Universal Search Box -->
                        <div class="universal-search-container d-none d-md-block mx-auto" style="position: relative; width: 100%; max-width: 600px;">
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text">
                                        <i class="material-icons" style="font-size: 18px; color: #666;">search</i>
                                    </span>
                                </div>
                                <input type="text"
                                       id="universalSearchInput"
                                       class="form-control"
                                       placeholder="Search pages, items, projects, suppliers..."
                                       autocomplete="off">
                                <div class="input-group-append">
                                    <span class="input-group-text" style="cursor: pointer;" id="clearSearchBtn">
                                        <i class="material-icons" style="font-size: 16px; color: #999; display: none;" id="clearSearchIcon">close</i>
                                    </span>
                                </div>
                            </div>
                            <!-- Search Results Dropdown -->
                            <div id="universalSearchResults" class="universal-search-results" style="display: none;">
                                <div class="search-results-loading" style="display: none;">
                                    <div class="text-center py-3">
                                        <div class="spinner-border spinner-border-sm text-primary" role="status">
                                            <span class="sr-only">Searching...</span>
                                        </div>
                                        <span class="ml-2 text-muted">Searching...</span>
                                    </div>
                                </div>
                                <div class="search-results-content"></div>
                                <div class="search-results-empty" style="display: none;">
                                    <div class="text-center py-3 text-muted">
                                        <i class="material-icons" style="font-size: 32px; opacity: 0.5;">search_off</i>
                                        <p class="mb-0 mt-2">No results found</p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Navbar Menu -->
                        <div class="collapse navbar-collapse" id="navbarNav">
                            <ul class="navbar-nav ml-auto">
                                <!-- Profile Dropdown -->
                                <li class="nav-item dropdown">
                                    @php
                                        $user = auth()->user();
                                        $userName = $user ? $user->name : 'KCG Administrator';
                                        $userEmail = $user ? $user->email : 'admin@kcg.com';
                                        $userRole = $user && $user->role ? $user->role->display_name : 'Administrator';
                                        $userInitial = strtoupper(substr($userName, 0, 1));
                                    @endphp

                                    <a class="nav-link dropdown-toggle d-flex align-items-center" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                        <div style="width: 32px; height: 32px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; margin-right: 8px;">
                                            {{ $userInitial }}
                                        </div>
                                        <div class="d-none d-sm-block text-left">
                                            <div style="font-size: 14px; font-weight: 500; color: #333;">{{ $userName }}</div>
                                            <div style="font-size: 12px; color: #666;">{{ $userRole }}</div>
                                        </div>
                                    </a>
                                    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
                                        <h6 class="dropdown-header">
                                            <div class="d-flex align-items-center">
                                                <div style="width: 40px; height: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; margin-right: 12px;">
                                                    {{ $userInitial }}
                                                </div>
                                                <div>
                                                    <div style="font-weight: 600;">{{ $userName }}</div>
                                                    <small class="text-muted">{{ $userEmail }}</small>
                                                </div>
                                            </div>
                                        </h6>
                                        <div class="dropdown-divider"></div>
                                        <a class="dropdown-item" href="{{ route('admin.profile') ?? '#' }}">
                                            <i class="material-icons mr-2" style="font-size: 18px;">person</i>
                                            Profile Settings
                                        </a>
                                        <a class="dropdown-item" href="#" onclick="alert('Help center coming soon!'); return false;">
                                            <i class="material-icons mr-2" style="font-size: 18px;">help</i>
                                            Help Center
                                        </a>
                                        <div class="dropdown-divider"></div>
                                        <form method="POST" action="{{ route('admin.logout') }}" class="m-0">
                                            @csrf
                                            <button type="submit" class="dropdown-item text-danger">
                                                <i class="material-icons mr-2" style="font-size: 18px;">logout</i>
                                                Sign Out
                                            </button>
                                        </form>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Header Layout Content -->
        <div class="mdk-header-layout__content">
            <div class="mdk-drawer-layout js-mdk-drawer-layout" data-push data-responsive-width="992px">
                <div class="mdk-drawer-layout__content page">

                    <!-- Page Heading -->
                    <div class="container-fluid page__heading-container">
                        <div class="page__heading">
                            <div class="mb-3">
                                <nav aria-label="breadcrumb">
                                    <ol class="breadcrumb mb-0">
                                        @yield('breadcrumb')
                                    </ol>
                                </nav>
                            </div>
                            @if(View::hasSection('page-title'))
                                @yield('page-title')
                            @else
                                <div class="d-flex justify-content-between align-items-center">
                                    @yield('page-actions')
                                </div>
                            @endif
                        </div>
                    </div>

                    <!-- Page Content -->
                    <div class="container-fluid page__container">
                        @if(session('success'))
                            <div class="alert alert-success alert-dismissible fade show" role="alert">
                                {{ session('success') }}
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                        @endif
                        
                        @if(session('error'))
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                {{ session('error') }}
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                        @endif
                        
                        @yield('content')
                    </div>

                    <!-- Footer Credits -->
                    <div class="footer-credits">
                        Design, Maintained & Owned by BILLING AND COST CONTROLL DEPARTMENT - KCG UAE &copy; {{ date('Y') }} | powered by Calper Global & Signtech | WMS
                    </div>

                </div>

                <!-- Sidebar -->
                <div class="mdk-drawer js-mdk-drawer" id="default-drawer" data-align="start">
                    <div class="mdk-drawer__content">
                        <div class="sidebar sidebar-light sidebar-left sidebar-p-t" data-perfect-scrollbar>
                            <div>
                                <div class="sidebar-heading">Menu</div>
                                
                                <ul class="sidebar-menu">
                                    <!-- Dashboard -->
                                    <li class="sidebar-menu-item {{ request()->is('admin/dashboard') ? 'active' : '' }}">
                                        <a class="sidebar-menu-button" href="{{ route('admin.dashboard') }}">
                                            <i class="sidebar-menu-icon sidebar-menu-icon--left material-icons">dashboard</i>
                                            <span class="sidebar-menu-text">Dashboard</span>
                                        </a>
                                    </li>

                                    <!-- Warehouse Section -->
                                    @can('warehouse.access')

                                    <!-- MASTERS Section -->
                                    <div class="sidebar-heading mt-2" style="margin-bottom: 8px;">
                                        <span style="background: #4CAF50; padding: 6px 12px; border-radius: 6px; font-size: 12px; font-weight: 600; color: white; letter-spacing: 0.5px; display: inline-block;">MASTERS</span>
                                    </div>

                                    <!-- Suppliers -->
                                    @can('warehouse.suppliers.view')
                                    <li class="sidebar-menu-item {{ request()->is('warehouse/suppliers*') ? 'active' : '' }}">
                                        <a class="sidebar-menu-button" href="{{ route('warehouse.suppliers.index') }}">
                                            <i class="sidebar-menu-icon sidebar-menu-icon--left material-icons">business</i>
                                            <span class="sidebar-menu-text">Suppliers</span>
                                        </a>
                                    </li>
                                    @endcan

                                    <!-- Projects -->
                                    @if(auth()->user()->can('warehouse.projects.view') || auth()->user()->can('warehouse.project-divisions.view'))
                                    <li class="sidebar-menu-item {{ request()->is('warehouse/projects*') || request()->is('warehouse/project-divisions*') ? 'active open' : '' }}">
                                        <a class="sidebar-menu-button" data-toggle="collapse" href="#projects_menu">
                                            <i class="sidebar-menu-icon sidebar-menu-icon--left material-icons">work</i>
                                            <span class="sidebar-menu-text">Projects</span>
                                            <i class="material-icons ml-auto sidebar-menu-toggle-icon">{{ request()->is('warehouse/projects*') || request()->is('warehouse/project-divisions*') ? 'keyboard_arrow_up' : 'keyboard_arrow_down' }}</i>
                                        </a>
                                        <ul class="sidebar-submenu collapse {{ request()->is('warehouse/projects*') || request()->is('warehouse/project-divisions*') ? 'show' : '' }}" id="projects_menu">
                                            @can('warehouse.projects.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/projects*') && !request()->is('warehouse/project-divisions*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.projects.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Projects</span>
                                                </a>
                                            </li>
                                            @endcan
                                            @can('warehouse.project-divisions.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/project-divisions*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.project-divisions.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Project Divisions</span>
                                                </a>
                                            </li>
                                            @endcan
                                        </ul>
                                    </li>
                                    @endif

                                    <!-- Items -->
                                    @if(auth()->user()->can('warehouse.items.view') || auth()->user()->can('warehouse.item-categories.view'))
                                    <li class="sidebar-menu-item {{ request()->is('warehouse/items*') || request()->is('warehouse/item-categories*') || request()->is('warehouse/item-types*') ? 'active open' : '' }}">
                                        <a class="sidebar-menu-button" data-toggle="collapse" href="#items_menu">
                                            <i class="sidebar-menu-icon sidebar-menu-icon--left material-icons">inventory_2</i>
                                            <span class="sidebar-menu-text">Items</span>
                                            <i class="material-icons ml-auto sidebar-menu-toggle-icon">{{ request()->is('warehouse/items*') || request()->is('warehouse/item-categories*') || request()->is('warehouse/item-types*') ? 'keyboard_arrow_up' : 'keyboard_arrow_down' }}</i>
                                        </a>
                                        <ul class="sidebar-submenu collapse {{ request()->is('warehouse/items*') || request()->is('warehouse/item-categories*') || request()->is('warehouse/item-types*') ? 'show' : '' }}" id="items_menu">
                                            @can('warehouse.item-categories.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/item-categories*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.item-categories.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Item Categories</span>
                                                </a>
                                            </li>
                                            @endcan
                                            @can('warehouse.items.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/item-types*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.item-types.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Item Types</span>
                                                </a>
                                            </li>
                                            @endcan
                                            @can('warehouse.items.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/items*') && !request()->is('warehouse/item-categories*') && !request()->is('warehouse/item-types*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.items.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Items</span>
                                                </a>
                                            </li>
                                            @endcan
                                        </ul>
                                    </li>
                                    @endif

                                    <!-- Fixed Asset Masters -->
                                    @can('warehouse.fixed-assets.view')
                                    <li class="sidebar-menu-item {{ request()->is('warehouse/fixed-assets/catalog*') || request()->is('warehouse/fixed-assets/categories*') ? 'active open' : '' }}">
                                        <a class="sidebar-menu-button" data-toggle="collapse" href="#asset_masters_menu">
                                            <i class="sidebar-menu-icon sidebar-menu-icon--left material-icons">precision_manufacturing</i>
                                            <span class="sidebar-menu-text">Asset</span>
                                            <i class="material-icons ml-auto sidebar-menu-toggle-icon">{{ request()->is('warehouse/fixed-assets/catalog*') || request()->is('warehouse/fixed-assets/categories*') ? 'keyboard_arrow_up' : 'keyboard_arrow_down' }}</i>
                                        </a>
                                        <ul class="sidebar-submenu collapse {{ request()->is('warehouse/fixed-assets/catalog*') || request()->is('warehouse/fixed-assets/categories*') ? 'show' : '' }}" id="asset_masters_menu">
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/fixed-assets/catalog*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.fixed-assets.catalog.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Asset List</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/fixed-assets/categories*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.fixed-assets.categories.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Asset Categories</span>
                                                </a>
                                            </li>
                                        </ul>
                                    </li>
                                    @endcan

                                    <!-- TRANSACTIONS Section -->
                                    <div class="sidebar-heading mt-3" style="margin-bottom: 8px;">
                                        <span style="background: #FF9800; padding: 6px 12px; border-radius: 6px; font-size: 12px; font-weight: 600; color: white; letter-spacing: 0.5px; display: inline-block;">TRANSACTIONS</span>
                                    </div>

                                    <!-- Material Request (Standalone) -->
                                    @can('warehouse.outgoing.create')
                                    <li class="sidebar-menu-item {{ request()->is('warehouse/inventory/material-requests*') ? 'active' : '' }}">
                                        <a class="sidebar-menu-button" href="{{ route('warehouse.inventory.material-requests') }}">
                                            <i class="sidebar-menu-icon sidebar-menu-icon--left material-icons">assignment</i>
                                            <span class="sidebar-menu-text">Material Request</span>
                                        </a>
                                    </li>
                                    @endcan

                                    @can('warehouse.fixed-asset-allocations.view')
                                    <li class="sidebar-menu-item {{ request()->is('warehouse/fixed-assets/allocations*') ? 'active' : '' }}">
                                        <a class="sidebar-menu-button" href="{{ route('warehouse.fixed-assets.allocations.index') }}">
                                            <i class="sidebar-menu-icon sidebar-menu-icon--left material-icons">assignment_turned_in</i>
                                            <span class="sidebar-menu-text">Asset Allocation</span>
                                        </a>
                                    </li>
                                    @endcan

                                    <!-- Enhanced Incoming Operations -->
                                    @if(auth()->user()->can('warehouse.incoming.view') || auth()->user()->can('warehouse.incoming.create') || auth()->user()->can('warehouse.incoming.edit'))
                                    <li class="sidebar-menu-item {{ request()->is('warehouse/incoming-operations*') || request()->is('warehouse/supplier-delivery*') || request()->is('warehouse/site-return*') || request()->is('warehouse/easy-in*') ? 'active open' : '' }}">
                                        <a class="sidebar-menu-button" data-toggle="collapse" href="#incoming_operations_menu">
                                            <i class="sidebar-menu-icon sidebar-menu-icon--left material-icons">input</i>
                                            <span class="sidebar-menu-text">Incoming Operations</span>
                                            <i class="material-icons ml-auto sidebar-menu-toggle-icon">{{ request()->is('warehouse/incoming-operations*') || request()->is('warehouse/supplier-delivery*') || request()->is('warehouse/site-return*') || request()->is('warehouse/easy-in*') ? 'keyboard_arrow_up' : 'keyboard_arrow_down' }}</i>
                                        </a>
                                        <ul class="sidebar-submenu collapse {{ request()->is('warehouse/incoming-operations*') || request()->is('warehouse/supplier-delivery*') || request()->is('warehouse/site-return*') || request()->is('warehouse/easy-in*') ? 'show' : '' }}" id="incoming_operations_menu">
                                            @can('warehouse.incoming.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/incoming-operations') && !request()->has('type') && !request()->has('operation_type') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.incoming-operations.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Dashboard</span>
                                                </a>
                                            </li>
                                            @endcan
                                            @can('warehouse.incoming.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/supplier-delivery*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.supplier-delivery.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Supplier Deliveries</span>
                                                </a>
                                            </li>
                                            @endcan
                                            @can('warehouse.incoming.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/site-return*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.site-return.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Site Returns</span>
                                                </a>
                                            </li>
                                            @endcan
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/easy-in*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.easy-in.index') }}">
                                                    <span class="sidebar-menu-text ml-3">⚡ Easy In</span>
                                                </a>
                                            </li>
                                        </ul>
                                    </li>
                                    @endif

                                    <!-- Outgoing Transactions -->
                                    @if(auth()->user()->can('warehouse.outgoing.view') || auth()->user()->can('warehouse.outgoing.create') || auth()->user()->can('warehouse.outgoing.edit'))
                                    <li class="sidebar-menu-item {{ request()->is('warehouse/outgoing*') || request()->is('warehouse/inventory/material-requests*') || request()->is('warehouse/inventory/material-issued*') || request()->is('warehouse/site-transfers*') || request()->is('warehouse/direct-deliveries*') || request()->is('warehouse/easy-out*') ? 'active open' : '' }}">
                                        <a class="sidebar-menu-button" data-toggle="collapse" href="#outgoing_transactions_menu">
                                            <i class="sidebar-menu-icon sidebar-menu-icon--left material-icons">output</i>
                                            <span class="sidebar-menu-text">Outgoing Transactions</span>
                                            <i class="material-icons ml-auto sidebar-menu-toggle-icon">{{ request()->is('warehouse/outgoing*') || request()->is('warehouse/inventory/material-requests*') || request()->is('warehouse/inventory/material-issued*') || request()->is('warehouse/site-transfers*') || request()->is('warehouse/direct-deliveries*') || request()->is('warehouse/easy-out*') ? 'keyboard_arrow_up' : 'keyboard_arrow_down' }}</i>
                                        </a>
                                        <ul class="sidebar-submenu collapse {{ request()->is('warehouse/outgoing*') || request()->is('warehouse/inventory/material-requests*') || request()->is('warehouse/inventory/material-issued*') || request()->is('warehouse/site-transfers*') || request()->is('warehouse/direct-deliveries*') || request()->is('warehouse/easy-out*') ? 'show' : '' }}" id="outgoing_transactions_menu">
                                            @can('warehouse.outgoing.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/outgoing') && !request()->is('warehouse/outgoing/*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.outgoing.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Dashboard</span>
                                                </a>
                                            </li>
                                            @endcan
                                            @can('warehouse.inventory.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/inventory/material-issued*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.inventory.material-issued') }}">
                                                    <span class="sidebar-menu-text ml-3">Material Issue</span>
                                                </a>
                                            </li>
                                            @endcan
                                            @can('warehouse.outgoing.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/site-transfers*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.site-transfers.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Material Site Transfer</span>
                                                </a>
                                            </li>
                                            @endcan
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/easy-out*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.easy-out.index') }}">
                                                    <span class="sidebar-menu-text ml-3">⚡ Easy Out</span>
                                                </a>
                                            </li>

                                        </ul>
                                    </li>
                                    @endif

                                    <!-- INVENTORY MANAGEMENT Section -->
                                    <div class="sidebar-heading mt-3" style="margin-bottom: 8px;">
                                        <span style="background: #2196F3; padding: 6px 12px; border-radius: 6px; font-size: 12px; font-weight: 600; color: white; letter-spacing: 0.5px; display: inline-block;">INVENTORY MANAGEMENT</span>
                                    </div>

                                    <!-- Inventory -->
                                    @if(auth()->user()->can('warehouse.inventory.view') || auth()->user()->can('warehouse.inventory.adjust') || auth()->user()->can('warehouse.inventory.transfer') || auth()->user()->can('warehouse.inventory.count') || auth()->user()->can('warehouse.indirect-consumption.view'))
                                    @php
                                        $isInventorySection = (request()->is('warehouse/inventory*') && !request()->is('warehouse/inventory/material-issued*') && !request()->is('warehouse/inventory/material-requests*')) || request()->is('warehouse/indirect-goods/consumption*');
                                    @endphp
                                    <li class="sidebar-menu-item {{ $isInventorySection ? 'active open' : '' }}">
                                        <a class="sidebar-menu-button" data-toggle="collapse" href="#inventory_menu">
                                            <i class="sidebar-menu-icon sidebar-menu-icon--left material-icons">inventory</i>
                                            <span class="sidebar-menu-text">Inventory</span>
                                            <i class="material-icons ml-auto sidebar-menu-toggle-icon">keyboard_arrow_down</i>
                                        </a>
                                        <ul class="sidebar-submenu collapse {{ $isInventorySection ? 'show' : '' }}" id="inventory_menu">
                                            @can('warehouse.inventory.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/inventory') && !request()->is('warehouse/inventory/*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.inventory.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Dashboard</span>
                                                </a>
                                            </li>
                                            @endcan
                                            @can('warehouse.inventory.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/inventory/low-stock*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.inventory.low-stock') }}">
                                                    <span class="sidebar-menu-text ml-3">Low Stock Alerts</span>
                                                </a>
                                            </li>
                                            @endcan
                                            @can('warehouse.inventory.adjust')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/inventory/adjustments*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.inventory.adjustments') }}">
                                                    <span class="sidebar-menu-text ml-3">Stock Adjustments</span>
                                                </a>
                                            </li>
                                            @endcan
                                            @can('warehouse.inventory.count')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/inventory/physical-count*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.inventory.physical-count') }}">
                                                    <span class="sidebar-menu-text ml-3">Cycle Counting</span>
                                                </a>
                                            </li>
                                            @endcan
                                            @can('warehouse.inventory.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/inventory/valuation*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.inventory.valuation') }}">
                                                    <span class="sidebar-menu-text ml-3">Inventory Valuation</span>
                                                </a>
                                            </li>
                                            @endcan
                                            @can('warehouse.inventory.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/inventory/aging-report*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.inventory.aging-report') }}">
                                                    <span class="sidebar-menu-text ml-3">Aging Report</span>
                                                </a>
                                            </li>
                                            @endcan
                                            @can('warehouse.inventory.adjust')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/inventory/condition-conversion*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.inventory.condition-conversion') }}">
                                                    <span class="sidebar-menu-text ml-3">FOC Conversion</span>
                                                </a>
                                            </li>
                                            @endcan
                                            @can('warehouse.indirect-consumption.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/indirect-goods/consumption*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.indirect-goods.consumption.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Indirect Consumption / Write-Off</span>
                                                </a>
                                            </li>
                                            @endcan
                                        </ul>
                                    </li>
                                    @endif

                                    <!-- Asset Inventory -->
                                    @if(auth()->user()->can('warehouse.fixed-asset-inventory.view') || auth()->user()->can('warehouse.fixed-asset-depreciation.view'))
                                    <li class="sidebar-menu-item {{ request()->is('warehouse/fixed-assets/inventory*') || request()->is('warehouse/fixed-assets/depreciation*') ? 'active open' : '' }}">
                                        <a class="sidebar-menu-button" data-toggle="collapse" href="#asset_inventory_menu">
                                            <i class="sidebar-menu-icon sidebar-menu-icon--left material-icons">fact_check</i>
                                            <span class="sidebar-menu-text">Asset Inventory</span>
                                            <i class="material-icons ml-auto sidebar-menu-toggle-icon">{{ request()->is('warehouse/fixed-assets/inventory*') || request()->is('warehouse/fixed-assets/depreciation*') ? 'keyboard_arrow_up' : 'keyboard_arrow_down' }}</i>
                                        </a>
                                        <ul class="sidebar-submenu collapse {{ request()->is('warehouse/fixed-assets/inventory*') || request()->is('warehouse/fixed-assets/depreciation*') ? 'show' : '' }}" id="asset_inventory_menu">
                                            @can('warehouse.fixed-asset-inventory.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/fixed-assets/inventory') && !request()->is('warehouse/fixed-assets/inventory/*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.fixed-assets.inventory.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Asset Inventory Dashboard</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/fixed-assets/inventory/all-assets*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.fixed-assets.inventory.all-assets') }}">
                                                    <span class="sidebar-menu-text ml-3">All Assets</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/fixed-assets/inventory/condition-report*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.fixed-assets.inventory.condition-report') }}">
                                                    <span class="sidebar-menu-text ml-3">Asset Condition Report</span>
                                                </a>
                                            </li>
                                            @endcan
                                            @can('warehouse.fixed-asset-depreciation.view')
                                            <li class="sidebar-menu-item {{ request()->is('warehouse/fixed-assets/depreciation*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.fixed-assets.depreciation.index') }}">
                                                    <span class="sidebar-menu-text ml-3">Asset Depreciation</span>
                                                </a>
                                            </li>
                                            @endcan
                                        </ul>
                                    </li>
                                    @endif

                                    <!-- Reports -->
                                    @can('warehouse.reports.view')
                                    <li class="sidebar-menu-item {{ request()->is('warehouse/reports*') ? 'active open' : '' }}">
                                        <a class="sidebar-menu-button" data-toggle="collapse" href="#reports_menu">
                                            <i class="sidebar-menu-icon sidebar-menu-icon--left material-icons">assessment</i>
                                            <span class="sidebar-menu-text">Reports</span>
                                            <i class="material-icons ml-auto sidebar-menu-toggle-icon">{{ request()->is('warehouse/reports*') ? 'keyboard_arrow_up' : 'keyboard_arrow_down' }}</i>
                                        </a>
                                        <ul class="sidebar-submenu collapse {{ request()->is('warehouse/reports*') ? 'show' : '' }}" id="reports_menu">
                                            <li class="sidebar-menu-item {{ request()->routeIs('warehouse.reports.inventory') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.reports.inventory') }}">
                                                    <span class="sidebar-menu-text ml-3">Inventory Report</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->routeIs('warehouse.reports.materials') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.reports.materials') }}">
                                                    <span class="sidebar-menu-text ml-3">Materials Report</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->routeIs('warehouse.reports.incoming') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.reports.incoming') }}">
                                                    <span class="sidebar-menu-text ml-3">Supplier Delivery Report</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->routeIs('warehouse.reports.division-deliveries') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.reports.division-deliveries') }}">
                                                    <span class="sidebar-menu-text ml-3">Division Deliveries Report</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->routeIs('warehouse.reports.returns') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.reports.returns') }}">
                                                    <span class="sidebar-menu-text ml-3">Site Return Report</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->routeIs('warehouse.reports.outgoing') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.reports.outgoing') }}">
                                                    <span class="sidebar-menu-text ml-3">Material Request Report</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->routeIs('warehouse.reports.transactions') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.reports.transactions') }}">
                                                    <span class="sidebar-menu-text ml-3">Material Issue Report</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->routeIs('warehouse.reports.stock-on-project*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.reports.stock-on-project') }}">
                                                    <span class="sidebar-menu-text ml-3">Stock on Project</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->routeIs('warehouse.reports.damaged-items') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('warehouse.reports.damaged-items') }}">
                                                    <span class="sidebar-menu-text ml-3">FOC Report</span>
                                                </a>
                                            </li>
                                        </ul>
                                    </li>
                                    @endcan



                                    <!-- SETTINGS Section -->
                                    <div class="sidebar-heading mt-3" style="margin-bottom: 8px;">
                                        <span style="background: #9C27B0; padding: 6px 12px; border-radius: 6px; font-size: 12px; font-weight: 600; color: white; letter-spacing: 0.5px; display: inline-block;">SETTINGS</span>
                                    </div>

                                    <!-- Warehouse Settings -->
                                    @can('warehouse.settings.view')
                                    <li class="sidebar-menu-item {{ request()->is('warehouse/settings*') ? 'active' : '' }}">
                                        <a class="sidebar-menu-button" href="{{ route('warehouse.settings.index') }}">
                                            <i class="sidebar-menu-icon sidebar-menu-icon--left material-icons">tune</i>
                                            <span class="sidebar-menu-text">Warehouse Settings</span>
                                        </a>
                                    </li>
                                    @endcan
                                    @endcan

                                    <!-- Careers Management Removed -->

                                    <!-- Media Management Removed -->

                                    <!-- Product Management Removed -->

                                    <!-- Reports Management Removed -->

                                    <!-- Pages Management Removed -->

                                    <!-- Site Settings -->
                                    @if(auth()->user()->hasPermission('view_settings') || auth()->user()->hasPermission('manage_settings'))
                                    <li class="sidebar-menu-item {{ request()->is('admin/site-settings*') ? 'active' : '' }}">
                                        <a class="sidebar-menu-button" href="{{ route('admin.site-settings.index') }}">
                                            <i class="sidebar-menu-icon sidebar-menu-icon--left material-icons">settings</i>
                                            <span class="sidebar-menu-text">Site Settings</span>
                                        </a>
                                    </li>
                                    @endif

                                    <!-- Investor Inquiries Removed -->

                                    <!-- Team Members Removed -->

                                    <!-- Contact Inquiries Removed -->

                                    <!-- User System -->
                                    @if(auth()->user()->hasPermission('view_users') || auth()->user()->hasPermission('manage_roles') || auth()->user()->hasPermission('manage_departments') || auth()->user()->hasPermission('view_activity_logs'))
                                    <li class="sidebar-menu-item {{ request()->is('admin/users*') || request()->is('admin/roles*') || request()->is('admin/permissions*') || request()->is('admin/departments*') || request()->is('admin/activity-logs*') ? 'active open' : '' }}">
                                        <a class="sidebar-menu-button" data-toggle="collapse" href="#user_system_menu">
                                            <i class="sidebar-menu-icon sidebar-menu-icon--left material-icons">admin_panel_settings</i>
                                            <span class="sidebar-menu-text">User System</span>
                                            <i class="material-icons ml-auto sidebar-menu-toggle-icon">{{ request()->is('admin/users*') || request()->is('admin/roles*') || request()->is('admin/permissions*') || request()->is('admin/departments*') || request()->is('admin/activity-logs*') ? 'keyboard_arrow_up' : 'keyboard_arrow_down' }}</i>
                                        </a>
                                        <ul class="sidebar-submenu collapse {{ request()->is('admin/users*') || request()->is('admin/roles*') || request()->is('admin/permissions*') || request()->is('admin/departments*') || request()->is('admin/activity-logs*') ? 'show' : '' }}" id="user_system_menu">

                                            @if(auth()->user()->hasPermission('view_users'))
                                            <!-- Users Management Section -->
                                            <li class="sidebar-menu-item">
                                                <a class="sidebar-menu-button disabled" style="padding-left: 1rem; margin-top: 0.5rem;">
                                                    <span class="sidebar-menu-text" style="font-size: 10px; font-weight: 700; letter-spacing: 0.5px; color: #b0b0b0; transform: scale(0.8); transform-origin: left center; display: inline-block;">USERS</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->is('admin/users') && !request()->has('action') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('admin.users') }}" style="padding-left: 2.5rem;">
                                                    <span class="sidebar-menu-text">All Users</span>
                                                </a>
                                            </li>
                                            @endif

                                            @if(auth()->user()->hasPermission('manage_roles'))
                                            <!-- Roles & Permissions Section -->
                                            <li class="sidebar-menu-item mt-2">
                                                <a class="sidebar-menu-button disabled" style="padding-left: 1rem; margin-top: 0.5rem;">
                                                    <span class="sidebar-menu-text" style="font-size: 10px; font-weight: 700; letter-spacing: 0.5px; color: #b0b0b0; transform: scale(0.8); transform-origin: left center; display: inline-block;">ROLES & PERMISSIONS</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->is('admin/roles') && !request()->is('admin/roles/create') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('admin.roles') }}" style="padding-left: 2.5rem;">
                                                    <span class="sidebar-menu-text">Manage Roles</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->is('admin/roles/create') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('admin.roles.create') }}" style="padding-left: 2.5rem;">
                                                    <span class="sidebar-menu-text">Create Role</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->is('admin/permissions') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('admin.permissions') }}" style="padding-left: 2.5rem;">
                                                    <span class="sidebar-menu-text">View Permissions</span>
                                                </a>
                                            </li>
                                            @endif

                                            @if(auth()->user()->hasPermission('manage_departments'))
                                            <!-- Departments Section -->
                                            <li class="sidebar-menu-item mt-2">
                                                <a class="sidebar-menu-button disabled" style="padding-left: 1rem; margin-top: 0.5rem;">
                                                    <span class="sidebar-menu-text" style="font-size: 10px; font-weight: 700; letter-spacing: 0.5px; color: #b0b0b0; transform: scale(0.8); transform-origin: left center; display: inline-block;">ORGANIZATION</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->is('admin/departments*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('admin.departments') }}" style="padding-left: 2.5rem;">
                                                    <span class="sidebar-menu-text">Departments</span>
                                                </a>
                                            </li>
                                            @endif

                                            @if(auth()->user()->hasPermission('view_activity_logs'))
                                            <!-- Activity Logs Section -->
                                            <li class="sidebar-menu-item mt-2">
                                                <a class="sidebar-menu-button disabled" style="padding-left: 1rem; margin-top: 0.5rem;">
                                                    <span class="sidebar-menu-text" style="font-size: 10px; font-weight: 700; letter-spacing: 0.5px; color: #b0b0b0; transform: scale(0.8); transform-origin: left center; display: inline-block;">ACTIVITY</span>
                                                </a>
                                            </li>
                                            <li class="sidebar-menu-item {{ request()->is('admin/activity-logs*') ? 'active' : '' }}">
                                                <a class="sidebar-menu-button" href="{{ route('admin.activity-logs') }}" style="padding-left: 2.5rem;">
                                                    <span class="sidebar-menu-text">Activity Logs</span>
                                                </a>
                                            </li>
                                            @endif
                                        </ul>
                                    </li>
                                    @endif
                                </ul>
                            </div>

                            <!-- FlowDash User Account Component -->
                            <div class="d-flex align-items-center sidebar-p-a border-bottom sidebar-account">
                                <a href="#" class="flex d-flex align-items-center text-underline-0 text-body">
                                    <span class="avatar avatar-sm mr-2">
                                        <span class="avatar-title rounded-circle" style="background-color: #038BB9; color: white;">
                                            {{ substr(auth()->user()->name ?? 'A', 0, 1) }}
                                        </span>
                                    </span>
                                    <span class="flex d-flex flex-column">
                                        <strong>{{ auth()->user()->name ?? 'AUFG Admin' }}</strong>
                                        <small class="text-muted text-uppercase">{{ auth()->user()->role->display_name ?? 'User' }}</small>
                                    </span>
                                </a>
                            </div>

                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>

    @yield('modals')
    @yield('floating-tracker')

    <!-- Page Loading Overlay -->
    <div class="page-loading-overlay" id="pageLoadingOverlay">
        <div class="loading-spinner"></div>
        <div class="loading-text">Loading...</div>
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- Bootstrap -->
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js"></script>

    <!-- DataTables JavaScript with Fallback Loading -->
    <script>
        window.dataTablesLoaded = 0;
        window.dataTablesRequired = 4;

        function loadDataTablesFallback() {
            console.log('🔄 Loading DataTables fallback from cdnjs...');

            const fallbackScripts = [
                'https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js',
                'https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/dataTables.bootstrap4.min.js'
            ];

            let loadedCount = 0;
            fallbackScripts.forEach(function(src, index) {
                const script = document.createElement('script');
                script.src = src;
                script.onload = function() {
                    loadedCount++;
                    console.log(`✅ Fallback script ${index + 1} loaded`);
                    if (loadedCount === fallbackScripts.length) {
                        console.log('📦 All fallback DataTables scripts loaded');
                        setTimeout(function() {
                            if (typeof $ !== 'undefined' && typeof $.fn.DataTable !== 'undefined') {
                                console.log('✅ Fallback DataTables is ready!');
                                window.dispatchEvent(new CustomEvent('dataTablesReady'));
                            }
                        }, 100);
                    }
                };
                script.onerror = function() {
                    console.error(`❌ Fallback script ${index + 1} failed to load`);
                };
                document.head.appendChild(script);
            });
        }

        function onDataTableScriptLoad() {
            window.dataTablesLoaded++;
            console.log(`✅ DataTables script loaded (${window.dataTablesLoaded}/${window.dataTablesRequired})`);

            if (window.dataTablesLoaded === window.dataTablesRequired) {
                console.log('📦 All primary DataTables scripts loaded');
                setTimeout(function() {
                    if (typeof $ !== 'undefined' && typeof $.fn.DataTable !== 'undefined') {
                        console.log('✅ Primary DataTables is ready!');
                        window.dispatchEvent(new CustomEvent('dataTablesReady'));
                    } else {
                        console.warn('⚠️ DataTables scripts loaded but not available, trying fallback...');
                        loadDataTablesFallback();
                    }
                }, 100);
            }
        }

        function onDataTableScriptError(scriptName) {
            console.error(`❌ ${scriptName} failed to load`);
            window.dataTablesRequired--;

            // If any script fails, try fallback after a short delay
            setTimeout(function() {
                if (window.dataTablesLoaded < 2) { // If we don't have basic functionality
                    loadDataTablesFallback();
                }
            }, 1000);
        }
    </script>

    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/datatables.net@1.13.4/js/jquery.dataTables.min.js"
            onerror="onDataTableScriptError('DataTables Core JS');"
            onload="onDataTableScriptLoad();"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/datatables.net-bs4@1.13.4/js/dataTables.bootstrap4.min.js"
            onerror="onDataTableScriptError('DataTables Bootstrap JS');"
            onload="onDataTableScriptLoad();"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/datatables.net-responsive@2.4.1/js/dataTables.responsive.min.js"
            onerror="onDataTableScriptError('DataTables Responsive JS');"
            onload="onDataTableScriptLoad();"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/datatables.net-responsive-bs4@2.4.1/js/responsive.bootstrap4.min.js"
            onerror="onDataTableScriptError('DataTables Responsive Bootstrap JS');"
            onload="onDataTableScriptLoad();"></script>

    <!-- PerfectScrollbar (load before app.js) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/perfect-scrollbar/1.5.5/css/perfect-scrollbar.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/perfect-scrollbar/1.5.5/perfect-scrollbar.min.js"></script>

    <!-- Admin Assets (only the ones that exist) -->
    <script src="{{ asset('admin-assets/vendor/dom-factory.js') }}"></script>
    <script src="{{ asset('admin-assets/vendor/material-design-kit.js') }}"></script>
    <script src="{{ asset('admin-assets/js/app.js') }}"></script>
    
    <!-- Admin Custom JavaScript -->
    <script src="{{ asset('admin-assets/js/admin-custom.js') }}"></script>

    @stack('scripts')

    <!-- DataTables Global Configuration -->
    <script>
        let dataTablesInitialized = false;

        function initializeDataTablesGlobally() {
            if (dataTablesInitialized) {
                console.log('⚠️ DataTables already initialized, skipping...');
                return;
            }

            if (typeof $ === 'undefined' || typeof $.fn.DataTable === 'undefined') {
                console.error('❌ Cannot initialize DataTables: library not available');
                return;
            }

            console.log('🔧 Initializing DataTables globally...');

            // Set DataTables default configuration
            $.extend(true, $.fn.dataTable.defaults, {
                responsive: true,
                pageLength: 25,
                lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                language: {
                    search: "Search:",
                    lengthMenu: "Show _MENU_ entries",
                    info: "Showing _START_ to _END_ of _TOTAL_ entries",
                    infoEmpty: "Showing 0 to 0 of 0 entries",
                    infoFiltered: "(filtered from _MAX_ total entries)",
                    paginate: {
                        first: "First",
                        last: "Last",
                        next: "Next",
                        previous: "Previous"
                    }
                },
                dom: "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
                     "<'row'<'col-sm-12'tr>>" +
                     "<'row'<'col-sm-5'i><'col-sm-7'p>>",
                order: []
            });

            console.log('✅ DataTables global configuration set');

            // Auto-initialize DataTables on tables with 'dataTable' class
            if ($('.dataTable').length > 0) {
                console.log('🔍 Found', $('.dataTable').length, 'tables to auto-initialize');
                $('.dataTable').DataTable();
                console.log('✅ DataTables auto-initialized successfully');
            }

            dataTablesInitialized = true;
        }

        // Listen for the custom dataTablesReady event
        window.addEventListener('dataTablesReady', function() {
            console.log('🎉 DataTables ready event received!');
            initializeDataTablesGlobally();
        });

        // Also try on document ready as fallback
        $(document).ready(function() {
            console.log('📄 Document ready, checking if DataTables is available...');

            // Wait a bit then check if DataTables is available
            setTimeout(function() {
                if (typeof $ !== 'undefined' && typeof $.fn.DataTable !== 'undefined' && !dataTablesInitialized) {
                    console.log('✅ DataTables found on document ready, initializing...');
                    initializeDataTablesGlobally();
                } else if (!dataTablesInitialized) {
                    console.log('⏳ DataTables not ready yet, waiting for dataTablesReady event...');
                }
            }, 500);
        });
    </script>

    <!-- Material Icons Debug Script -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Check if Material Icons font is loaded
            setTimeout(function() {
                var testIcon = document.createElement('i');
                testIcon.className = 'material-icons';
                testIcon.textContent = 'home';
                testIcon.style.position = 'absolute';
                testIcon.style.left = '-1000px';
                testIcon.style.fontSize = '24px';
                document.body.appendChild(testIcon);

                // Check if the icon rendered properly
                var computedStyle = window.getComputedStyle(testIcon);
                var fontFamily = computedStyle.getPropertyValue('font-family');

                if (!fontFamily.includes('Material Icons')) {
                    console.warn('Material Icons font not loaded properly. Font-family:', fontFamily);
                    // Add fallback class to body
                    document.body.classList.add('material-icons-fallback');
                } else {
                    console.log('Material Icons loaded successfully');
                }

                document.body.removeChild(testIcon);
            }, 2000);
        });
    </script>

    <!-- Material Icons Fallback CSS -->
    <style>
        /* Fallback for when Material Icons don't load */
        .material-icons-fallback .material-icons {
            font-family: Arial, sans-serif;
            font-size: 16px;
            font-weight: bold;
        }

        .material-icons-fallback .material-icons:before {
            content: "●";
            color: #666;
        }

        /* Footer Credits */
        .footer-credits {
            text-align: center;
            padding: 15px 20px;
            background: transparent;
            color: #666;
            font-size: 11px;
            letter-spacing: 0.3px;
            margin-top: 30px;
        }

        .footer-credits a {
            color: #555;
            text-decoration: none;
        }

        .footer-credits a:hover {
            text-decoration: underline;
        }
    </style>

    <!-- Universal Search JavaScript -->
    <script>
        $(document).ready(function() {
            const searchInput = $('#universalSearchInput');
            const searchResults = $('#universalSearchResults');
            const resultsContent = searchResults.find('.search-results-content');
            const resultsLoading = searchResults.find('.search-results-loading');
            const resultsEmpty = searchResults.find('.search-results-empty');
            const clearBtn = $('#clearSearchBtn');
            const clearIcon = $('#clearSearchIcon');

            let searchTimeout = null;
            let currentIndex = -1;
            let currentResults = [];

            // Type labels and colors
            const typeLabels = {
                'navigation': 'Page',
                'item': 'Item',
                'project': 'Project',
                'division': 'Division',
                'supplier': 'Supplier',
                'incoming': 'Incoming',
                'material_request': 'MR'
            };

            const typeColors = {
                'navigation': '#607D8B',
                'item': '#4CAF50',
                'project': '#2196F3',
                'division': '#9C27B0',
                'supplier': '#FF9800',
                'incoming': '#00BCD4',
                'material_request': '#E91E63'
            };

            // Search input handler with debounce
            searchInput.on('input', function() {
                const query = $(this).val().trim();

                // Show/hide clear button
                if (query.length > 0) {
                    clearIcon.show();
                } else {
                    clearIcon.hide();
                }

                // Clear previous timeout
                if (searchTimeout) {
                    clearTimeout(searchTimeout);
                }

                if (query.length < 2) {
                    hideResults();
                    return;
                }

                // Show loading
                showLoading();

                // Debounce search
                searchTimeout = setTimeout(function() {
                    performSearch(query);
                }, 300);
            });

            // Clear button handler
            clearBtn.on('click', function() {
                searchInput.val('').focus();
                clearIcon.hide();
                hideResults();
            });

            // Perform search
            function performSearch(query) {
                $.ajax({
                    url: '{{ route("warehouse.search") }}',
                    method: 'GET',
                    data: { q: query },
                    success: function(response) {
                        currentResults = response.results;
                        currentIndex = -1;

                        if (response.results.length === 0) {
                            showEmpty();
                        } else {
                            renderResults(response.results);
                        }
                    },
                    error: function() {
                        showEmpty();
                    }
                });
            }

            // Render results
            function renderResults(results) {
                let html = '';

                // Group results by type
                const grouped = {};
                results.forEach(function(result) {
                    if (!grouped[result.type]) {
                        grouped[result.type] = [];
                    }
                    grouped[result.type].push(result);
                });

                // Render each group
                let index = 0;
                for (const type in grouped) {
                    // Handle singular/plural category labels
                    let categoryLabel = typeLabels[type] || type;
                    if (type !== 'navigation') {
                        categoryLabel += 's'; // Pluralize for non-navigation types
                    }
                    html += `<div class="search-results-category">${categoryLabel}</div>`;

                    grouped[type].forEach(function(result) {
                        const bgColor = result.color || typeColors[result.type] || '#666';
                        const typeLabel = typeLabels[result.type] || result.type;
                        const typeBgColor = hexToRgba(bgColor, 0.1);

                        html += `
                            <a href="${result.url}" class="search-result-item" data-index="${index}">
                                <div class="search-result-icon" style="background: ${bgColor};">
                                    <i class="material-icons">${result.icon}</i>
                                </div>
                                <div class="search-result-content">
                                    <div class="search-result-label">${highlightMatch(result.label, searchInput.val())}</div>
                                    <div class="search-result-subtitle">${result.subtitle}</div>
                                </div>
                                <span class="search-result-type" style="background: ${typeBgColor}; color: ${bgColor};">${typeLabel}</span>
                            </a>
                        `;
                        index++;
                    });
                }

                // Add keyboard hint
                html += `
                    <div class="search-keyboard-hint">
                        <span><kbd>↑</kbd> <kbd>↓</kbd> Navigate</span>
                        <span><kbd>Enter</kbd> Select</span>
                        <span><kbd>Esc</kbd> Close</span>
                    </div>
                `;

                resultsContent.html(html);
                resultsLoading.hide();
                resultsEmpty.hide();
                resultsContent.show();
                searchResults.show();
            }

            // Highlight matching text
            function highlightMatch(text, query) {
                if (!query) return text;
                const regex = new RegExp('(' + escapeRegex(query) + ')', 'gi');
                return text.replace(regex, '<strong style="color: #667eea;">$1</strong>');
            }

            // Escape regex special characters
            function escapeRegex(string) {
                return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            }

            // Convert hex to rgba
            function hexToRgba(hex, alpha) {
                const r = parseInt(hex.slice(1, 3), 16);
                const g = parseInt(hex.slice(3, 5), 16);
                const b = parseInt(hex.slice(5, 7), 16);
                return `rgba(${r}, ${g}, ${b}, ${alpha})`;
            }

            // Show loading state
            function showLoading() {
                resultsContent.hide();
                resultsEmpty.hide();
                resultsLoading.show();
                searchResults.show();
            }

            // Show empty state
            function showEmpty() {
                resultsLoading.hide();
                resultsContent.hide();
                resultsEmpty.show();
                searchResults.show();
            }

            // Hide results
            function hideResults() {
                searchResults.hide();
                currentIndex = -1;
            }

            // Keyboard navigation
            searchInput.on('keydown', function(e) {
                const items = resultsContent.find('.search-result-item');

                if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    if (currentIndex < items.length - 1) {
                        currentIndex++;
                        updateActiveItem(items);
                    }
                } else if (e.key === 'ArrowUp') {
                    e.preventDefault();
                    if (currentIndex > 0) {
                        currentIndex--;
                        updateActiveItem(items);
                    }
                } else if (e.key === 'Enter') {
                    e.preventDefault();
                    if (currentIndex >= 0 && currentIndex < items.length) {
                        window.location.href = items.eq(currentIndex).attr('href');
                    }
                } else if (e.key === 'Escape') {
                    hideResults();
                    searchInput.blur();
                }
            });

            // Update active item highlight
            function updateActiveItem(items) {
                items.removeClass('active');
                if (currentIndex >= 0) {
                    const activeItem = items.eq(currentIndex);
                    activeItem.addClass('active');

                    // Scroll into view if needed
                    const container = searchResults[0];
                    const item = activeItem[0];
                    if (item) {
                        const containerTop = container.scrollTop;
                        const containerBottom = containerTop + container.clientHeight;
                        const itemTop = item.offsetTop;
                        const itemBottom = itemTop + item.clientHeight;

                        if (itemTop < containerTop) {
                            container.scrollTop = itemTop;
                        } else if (itemBottom > containerBottom) {
                            container.scrollTop = itemBottom - container.clientHeight;
                        }
                    }
                }
            }

            // Close results when clicking outside
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.universal-search-container').length) {
                    hideResults();
                }
            });

            // Show results when focusing on input (if there's content)
            searchInput.on('focus', function() {
                if ($(this).val().trim().length >= 2 && currentResults.length > 0) {
                    searchResults.show();
                }
            });

            // Keyboard shortcut to focus search (Ctrl/Cmd + K)
            $(document).on('keydown', function(e) {
                if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                    e.preventDefault();
                    searchInput.focus().select();
                }
            });

            console.log('🔍 Universal Search initialized');
        });
    </script>

    <!-- Basic initialization - main dropdown handling is in admin-custom.js -->
    <script>
        $(document).ready(function() {
            console.log('🔧 Layout: Basic dropdown setup initialized');

            // Create custom profile dropdown
            let customDropdown = null;

            $('#navbarDropdown').on('click', function(e) {
                e.preventDefault();

                // Remove existing dropdown if any
                if (customDropdown) {
                    customDropdown.remove();
                }

                // Get user data from existing dropdown
                const userName = '{{ $userName ?? "KCG Administrator" }}';
                const userEmail = '{{ $userEmail ?? "admin@kcg.com" }}';
                const userInitial = '{{ $userInitial ?? "K" }}';

                // Create custom dropdown HTML
                customDropdown = $(`
                    <div id="custom-profile-dropdown" class="show">
                        <div class="profile-info">
                            <div style="display: flex; align-items: center;">
                                <div style="width: 40px; height: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; margin-right: 12px;">
                                    ${userInitial}
                                </div>
                                <div>
                                    <div style="font-weight: 600; color: #333;">${userName}</div>
                                    <small style="color: #666;">${userEmail}</small>
                                </div>
                            </div>
                        </div>
                        <div class="profile-links">
                            <a href="{{ route('admin.profile') ?? '#' }}">
                                <i class="material-icons mr-2" style="font-size: 18px;">person</i>
                                Profile Settings
                            </a>
                            <a href="#" onclick="alert('Help center coming soon!'); return false;">
                                <i class="material-icons mr-2" style="font-size: 18px;">help</i>
                                Help Center
                            </a>
                            <hr style="margin: 0.5rem 0;">
                            <form method="POST" action="{{ route('admin.logout') }}" style="margin: 0;">
                                <input type="hidden" name="_token" value="{{ csrf_token() }}">
                                <button type="submit" style="color: #dc3545; width: 100%; text-align: left; border: none; background: none; padding: 0.75rem 1rem; font-size: 0.875rem;">
                                    <i class="material-icons mr-2" style="font-size: 18px;">logout</i>
                                    Sign Out
                                </button>
                            </form>
                        </div>
                    </div>
                `);

                // Append to body
                $('body').append(customDropdown);

                console.log('👤 Custom profile dropdown created and shown');
            });

            // Close dropdown when clicking outside
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.nav-item.dropdown, #custom-profile-dropdown').length) {
                    $('#custom-profile-dropdown').remove();
                    customDropdown = null;
                    console.log('👤 Custom profile dropdown closed');
                }
            });

            // Prevent Select2 from interfering with Bootstrap dropdowns
            $(document).on('select2:open', function(e) {
                $('.dropdown-menu').removeClass('show').hide();
                console.log('🔧 Closed dropdowns due to Select2 opening');
            });

            // Auto-scroll sidebar to active menu item on page load
            setTimeout(function() {
                // Find the active menu item
                const activeMenuItem = document.querySelector('.sidebar-menu-item.active');

                if (activeMenuItem) {
                    // Find the scrollable sidebar container
                    const sidebar = document.querySelector('[data-perfect-scrollbar]');

                    if (sidebar) {
                        // Calculate the position to scroll to (center the active item)
                        const itemOffsetTop = activeMenuItem.offsetTop;
                        const sidebarHeight = sidebar.clientHeight;
                        const itemHeight = activeMenuItem.offsetHeight;

                        // Calculate scroll position to center the item
                        let scrollTo = itemOffsetTop - (sidebarHeight / 2) + (itemHeight / 2);
                        scrollTo = Math.max(0, scrollTo); // Don't scroll to negative

                        // Animate the scroll
                        const startScroll = sidebar.scrollTop;
                        const distance = scrollTo - startScroll;
                        const duration = 400;
                        let startTime = null;

                        function animateScroll(currentTime) {
                            if (!startTime) startTime = currentTime;
                            const elapsed = currentTime - startTime;
                            const progress = Math.min(elapsed / duration, 1);

                            // Easing function (ease-out)
                            const easeOut = 1 - Math.pow(1 - progress, 3);

                            sidebar.scrollTop = startScroll + (distance * easeOut);

                            if (progress < 1) {
                                requestAnimationFrame(animateScroll);
                            } else {
                                console.log('📍 Scrolled sidebar to active menu item');
                            }
                        }

                        requestAnimationFrame(animateScroll);
                    }
                }
            }, 600); // Delay to ensure sidebar is fully initialized
        });
    </script>
</body>
</html>
