<?php
    use Illuminate\Support\Facades\Route;
    use Illuminate\Support\Str;

    $businessName = app(\App\Services\SettingService::class)->get('business.name', config('app.name', 'ISP Billing'));
    $businessLogoPath = app(\App\Services\SettingService::class)->get('business.logo');
    $businessLogo = $businessLogoPath ? asset('storage/'.$businessLogoPath) : asset('assets/images/bsd/logo.png');

    $resolveRoute = function (array $candidates) {
        foreach($candidates as $c){
            if(Route::has($c)) return $c;
        }
        return null;
    };
    $canSee = function (array $item) {
        $user = auth()->user();
        if (! $user) return false;

        $adminScopeAllowed = empty($item['admin_only']) || $user->hasAnyRole(['Super Admin', 'Admin']);
        $permissionAllowed = $user->hasRole('Super Admin') || empty($item['permission']) || $user->can($item['permission']);

        $pluginAllowed = empty($item['plugin']) || app(\App\Services\PluginManager::class)->isEnabled($item['plugin']);

        return $adminScopeAllowed && $permissionAllowed && $pluginAllowed;
    };
    $translateMenu = fn (string $title) => $title === 'AI Assistant' ? __('ai.title') : (trans()->has('ui.menu.'.$title) ? __('ui.menu.'.$title) : $title);
    $currentRouteName = Route::currentRouteName();
    $matchesRouteCandidates = function (array $candidates) use ($currentRouteName) {
        if (! $currentRouteName) {
            return false;
        }

        foreach ($candidates as $candidate) {
            if ($currentRouteName === $candidate || Str::is($candidate.'.*', $currentRouteName)) {
                return true;
            }
        }

        return false;
    };

    $menu = [
        ['title' => 'Dashboard', 'icon' => 'grid', 'plugin' => 'dashboard', 'permission' => 'dashboard.view', 'route_candidates' => ['admin.dashboard','dashboard']],
        ['title' => 'AI Assistant', 'icon' => 'cpu', 'plugin' => 'ai-assistant', 'admin_only' => true, 'route_candidates' => ['admin.ai-assistant.index']],
        ['title' => 'Customer Management', 'icon' => 'users', 'plugin' => 'customer-management', 'children' => [
            ['title' => 'Customer List', 'icon' => 'list', 'permission' => 'customer.view', 'route_candidates' => ['admin.customers.index']],
            ['title' => 'Add Customer', 'icon' => 'user-plus', 'permission' => 'customer.create', 'route_candidates' => ['admin.customers.create']],
            ['title' => 'Customer Packages', 'icon' => 'layers', 'permission' => 'package.view', 'route_candidates' => ['admin.packages.index']],
            ['title' => 'Customer Zones', 'icon' => 'map-pin', 'permission' => 'zone.view', 'route_candidates' => ['admin.zones.index']],
            ['title' => 'Deleted Customers', 'icon' => 'trash-2', 'permission' => 'customer.delete', 'route_candidates' => ['admin.customers.deleted']],
        ]],
        ['title' => 'Billing & Collection', 'icon' => 'credit-card', 'plugin' => 'billing-collection', 'children' => [
            ['title' => 'Bill Collection', 'icon' => 'dollar-sign', 'permission' => 'billing.view', 'route_candidates' => ['admin.billings.index']],
            ['title' => 'Bill Generate', 'icon' => 'file-plus', 'permission' => 'billing.generate', 'route_candidates' => ['admin.billings.generate']],
            ['title' => 'Paid Bills', 'icon' => 'check-circle', 'permission' => 'billing.view', 'route_candidates' => ['admin.billings.full_paid']],
            ['title' => 'Invoices', 'icon' => 'file-text', 'permission' => 'billing.view', 'route_candidates' => ['admin.invoices.index','admin.invoices']],
            ['title' => 'Payments', 'icon' => 'repeat', 'permission' => 'billing.update', 'route_candidates' => ['admin.payments.index','admin.payments']],
        ]],
        ['title' => 'Network Management', 'icon' => 'server', 'plugin' => 'network-management', 'children' => [
            ['title'=>'MikroTik List','icon'=>'server','permission'=>'mikrotik.view','route_candidates'=>['admin.mikrotiks.index','admin.mikrotik.index']],
            ['title' => 'OLT Management', 'icon' => 'git-branch', 'plugin' => 'olt-gateway', 'permission' => 'olt.view', 'route_candidates' => ['admin.olts.index']],
            ['title'=>'MikroTik Secret List','icon'=>'key','permission'=>'mikrotik_secret.view','route_candidates'=>['admin.mikrotik-secrets.index','admin.mikrotik.secrets.index']],
            ['title'=>'Disconnect By Due Customer','icon'=>'alert-circle','permission'=>'mikrotik.view','route_candidates'=>['admin.mikrotik.disconnect-due','admin.mikrotik.disconnect-by-due']],
            ['title'=>'MikroTik Online List','icon'=>'wifi','permission'=>'mikrotik.view','route_candidates'=>['admin.mikrotik.online']],
            ['title'=>'MikroTik PPPOE Offline List','icon'=>'slash','permission'=>'mikrotik.view','route_candidates'=>['admin.mikrotik.pppoe-offline']],
            ['title'=>'MikroTik Online Static List','icon'=>'hard-drive','permission'=>'mikrotik.view','route_candidates'=>['admin.mikrotik.online-static']],
            ['title'=>'PPPoE Software Unmatching','icon'=>'upload-cloud','permission'=>'mikrotik.view','route_candidates'=>['admin.mikrotik.pppoe-software-unmatching']],
            ['title'=>'PPPoE MikroTik Unmatching','icon'=>'download-cloud','permission'=>'mikrotik.view','route_candidates'=>['admin.mikrotik.pppoe-mikrotik-unmatching']],
            ['title'=>'MikroTik Static Unmatching List','icon'=>'link-2','permission'=>'mikrotik.view','route_candidates'=>['admin.mikrotik.static-unmatching']],
        ]],
        ['title' => 'Finance & Inventory', 'icon' => 'briefcase', 'plugin' => 'finance-reports', 'children' => [
            ['title' => 'Inventory Management', 'icon' => 'box', 'permission' => 'inventory.view', 'route_candidates' => ['admin.inventory.index']],
            ['title' => 'Account Statement', 'icon' => 'book-open', 'permission' => 'accounts.view', 'route_candidates' => ['admin.accounts.statement']],
        ]],
        ['title' => 'Reports', 'icon' => 'bar-chart-2', 'plugin' => 'finance-reports', 'children' => [
            ['title' => 'Business Reports', 'icon' => 'bar-chart', 'permission' => 'reports.view', 'route_candidates' => ['admin.reports.index']],
            ['title' => 'BTRC Report', 'icon' => 'clipboard', 'permission' => 'reports.view', 'route_candidates' => ['admin.reports.btrc']],
        ]],
        ['title' => 'User Management', 'icon' => 'user-check', 'plugin' => 'core-platform', 'children' => [
            ['title' => 'Resellers', 'icon' => 'briefcase', 'permission' => 'reseller.view', 'route_candidates' => ['admin.resellers.index']],
            ['title' => 'Staff & Operators', 'icon' => 'users', 'permission' => 'user.manage', 'route_candidates' => ['admin.staff.index']],
            ['title' => 'Roles & Permissions', 'icon' => 'shield', 'permission' => 'role.manage', 'route_candidates' => ['admin.roles.index']],
        ]],
        ['title' => 'Communication', 'icon' => 'message-circle', 'plugin' => 'communications', 'children' => [
            ['title' => 'Send SMS & History', 'icon' => 'send', 'permission' => 'sms.view', 'route_candidates' => ['admin.sms-messages.index','admin.sms.index']],
            ['title' => 'SMS Templates', 'icon' => 'file-text', 'permission' => 'sms.view', 'route_candidates' => ['admin.sms-templates.index']],
            ['title' => 'SMS Configuration', 'icon' => 'sliders', 'permission' => 'sms.view', 'route_candidates' => ['admin.sms-gateways.index']],
            ['title' => 'Email Management', 'icon' => 'mail', 'permission' => 'email.view', 'route_candidates' => ['admin.email-messages.index','admin.email-templates.index']],
        ]],
        ['title' => 'System Logs', 'icon' => 'activity', 'plugin' => 'core-platform', 'children' => [
            ['title' => 'Main Activity Logs', 'icon' => 'list', 'permission' => 'activity_log.view', 'route_candidates' => ['admin.activity-logs.index']],
            ['title' => 'MikroTik Automation Logs', 'icon' => 'clock', 'permission' => 'activity_log.view', 'route_candidates' => ['admin.activity-logs.automation']],
        ]],
        ['title' => 'CMS', 'icon' => 'layout', 'plugin' => 'cms-website', 'permission' => 'settings.manage', 'children' => [
            ['title' => 'Homepage', 'icon' => 'home', 'permission' => 'settings.manage', 'route_candidates' => ['admin.cms.homepage.index']],
        ]],
        ['title' => 'Plugin Manager', 'icon' => 'package', 'plugin' => 'core-platform', 'permission' => 'plugin.manage', 'admin_only' => true, 'route_candidates' => ['admin.plugins.index']],
        ['title' => 'Settings', 'icon' => 'settings', 'plugin' => 'core-platform', 'permission' => 'settings.manage', 'route_candidates' => ['admin.settings.index']],
    ];
?>

<style>
    /* Modern smooth sidebar styles */
    .sidebar-modern { width: 260px; min-width: 260px; background: linear-gradient(180deg,#ffffff 0%,#f8fafc 100%); border-right:1px solid #e9eef3; height:100vh; position:fixed; left:0; top:0; overflow:auto; transition: width .25s ease; z-index:1000; padding-bottom:60px; }
    .sidebar-modern.collapsed { width:72px; min-width:72px; }
    .sidebar-modern .brand { padding:18px; display:flex; align-items:center; gap:12px; }
    .sidebar-modern .brand img.logo-lg{ height:36px; }
    .sidebar-modern .user-box{ padding:12px 16px; border-top:1px solid #f1f5f9; border-bottom:1px solid #f1f5f9; }
    .sidebar-modern .nav { list-style:none; margin:0; padding:8px 0; }
    .sidebar-modern .nav .nav-item { margin:0; width: 100%; }
    .sidebar-modern .nav .nav-link { display:flex; align-items:center; gap:12px; padding:10px 16px; color:#374151; text-decoration:none; font-weight:500; border-radius:8px; margin:4px 8px; }
    .sidebar-modern .nav .nav-link .icon{ width:28px; height:28px; display:inline-flex; align-items:center; justify-content:center; background:#f1f5f9; border-radius:8px; }
    .sidebar-modern .nav .nav-link:hover{ background:#eef2ff; color:#1e3a8a; }
    .sidebar-modern .nav .nav-link.active{ background:linear-gradient(135deg,#635bff 0%,#4f46e5 100%); color:#fff; box-shadow:0 10px 24px rgba(79,70,229,.28); }
    .sidebar-modern .nav .nav-link.active .icon{ background:rgba(255,255,255,.16); color:#fff; }
    .sidebar-modern .nav .nav-link.active .label{ color:#fff; }
    .sidebar-modern .nav .nav-link.is-open{ background:linear-gradient(135deg,#eef2ff 0%,#e0e7ff 100%); color:#4338ca; box-shadow:inset 0 0 0 1px rgba(99,102,241,.12); }
    .sidebar-modern .nav .nav-link.is-open .icon{ background:rgba(99,102,241,.12); color:#4f46e5; }
    .sidebar-modern .nav .nav-link.is-open .label{ color:#4338ca; }
    .sidebar-modern .nav .sub-menu{ list-style:none; padding-left:12px; }
    .sidebar-modern .collapse-toggle{ margin-left:auto; }
    .sidebar-customer-search{position:relative;margin:2px 8px 10px;padding:0 8px}.sidebar-customer-search .search-control{position:relative}.sidebar-customer-search .search-icon{position:absolute;left:11px;top:50%;width:16px;height:16px;transform:translateY(-50%);color:#64748b;pointer-events:none}.sidebar-customer-search input{height:38px;padding-left:34px;padding-right:30px;border:1px solid #dbe4ee;border-radius:10px;background:#fff;font-size:.82rem}.sidebar-customer-search input:focus{border-color:#818cf8;box-shadow:0 0 0 3px rgba(99,102,241,.12)}.sidebar-search-spinner{position:absolute;right:10px;top:11px;width:15px;height:15px}.sidebar-search-results{position:absolute;z-index:1200;top:43px;left:8px;right:8px;max-height:310px;overflow:auto;border:1px solid #dbe4ee;border-radius:11px;background:#fff;box-shadow:0 14px 35px rgba(15,23,42,.16)}.sidebar-search-result{display:block;padding:10px 11px;color:#1e293b;text-decoration:none;border-bottom:1px solid #f1f5f9}.sidebar-search-result:last-child{border-bottom:0}.sidebar-search-result:hover,.sidebar-search-result:focus{background:#eef2ff;color:#1e3a8a}.sidebar-search-result strong,.sidebar-search-result small{display:block}.sidebar-search-result small{margin-top:2px;color:#64748b;font-size:.72rem}.sidebar-search-empty{padding:12px;color:#64748b;font-size:.8rem;text-align:center}.sidebar-modern.collapsed .sidebar-customer-search{display:none}
    .sidebar-toggle-btn{ position:fixed; left:270px; top:16px; z-index:1100; background:#fff; border:1px solid #e6eef9; width:40px; height:40px; display:flex; align-items:center; justify-content:center; border-radius:8px; cursor:pointer; }
    .sidebar-modern.collapsed + .sidebar-toggle-btn{ left:86px; }

    @media (max-width: 992px){
        .sidebar-modern{ transform:translateX(-100%); position:fixed; }
        .sidebar-modern.show{ transform:none; }
        .sidebar-toggle-btn{ left:16px; }
    }
</style>

<div class="sidebar-modern" id="sidebarModern">
    <div class="brand">
        <a href="<?php echo e(url('/')); ?>">
            <img src="<?php echo e($businessLogo); ?>" alt="<?php echo e($businessName); ?> logo" class="logo-lg">
        </a>
        <div class="d-flex flex-column">
            <span style="font-weight:700"><?php echo e($businessName); ?></span>
            <small class="text-muted">Admin Panel</small>
        </div>
    </div>


    <nav>
        <ul class="nav">
            <?php if(auth()->user()?->can('customer.view')): ?>
                <li class="sidebar-customer-search" id="sidebarCustomerSearch">
                    <div class="search-control">
                        <i data-feather="search" class="search-icon"></i>
                        <input type="search" id="sidebarCustomerSearchInput" class="form-control" placeholder="ID, phone or IP..." autocomplete="off" aria-label="Search customer" aria-expanded="false">
                        <span class="spinner-border spinner-border-sm text-primary sidebar-search-spinner d-none" id="sidebarSearchSpinner" role="status" aria-hidden="true"></span>
                    </div>
                    <div class="sidebar-search-results d-none" id="sidebarCustomerSearchResults" role="listbox"></div>
                </li>
            <?php endif; ?>
            <?php $__currentLoopData = $menu; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <?php $has = false; $url = null; ?>
                <?php if(isset($item['children'])): ?>
                    <?php if($canSee($item)): ?>
                        <?php $__currentLoopData = $item['children']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $child): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <?php if($canSee($child) && $resolveRoute($child['route_candidates'] ?? [])) { $has = true; break; } ?>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    <?php endif; ?>
                <?php else: ?>
                    <?php
                        if($canSee($item) && isset($item['route_candidates'])){
                            $r = $resolveRoute($item['route_candidates']);
                            if($r){ $has = true; $url = route($r); }
                        }
                        if(isset($item['action']) && $item['action']==='logout') $has=true;
                    ?>
                <?php endif; ?>

                <?php if(!$has): ?> <?php continue; ?> <?php endif; ?>

                <?php if(isset($item['children'])): ?>
                    <?php
                        $cid = 'sm-'.Str::slug($item['title']);
                        $hasActiveChild = false;
                    ?>
                    <?php $__currentLoopData = $item['children']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $child): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <?php
                            if (! $hasActiveChild && ! empty($child['route_candidates']) && $matchesRouteCandidates($child['route_candidates'])) {
                                $hasActiveChild = true;
                            }
                        ?>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    <li class="nav-item menu-tone-<?php echo e($loop->index % 6); ?>">
                        <a class="nav-link d-flex align-items-center <?php echo e($hasActiveChild ? 'is-open' : ''); ?>" data-bs-toggle="collapse" href="#<?php echo e($cid); ?>" role="button" aria-expanded="<?php echo e($hasActiveChild ? 'true' : 'false'); ?>" aria-controls="<?php echo e($cid); ?>">
                            <span class="icon"><i data-feather="<?php echo e($item['icon']); ?>"></i></span>
                            <span class="label"><?php echo e($translateMenu($item['title'])); ?></span>
                            <span class="collapse-toggle ms-auto"><i data-feather="chevron-down"></i></span>
                        </a>
                        <div class="collapse <?php echo e($hasActiveChild ? 'show' : ''); ?>" id="<?php echo e($cid); ?>">
                            <ul class="sub-menu">
                                <?php $__currentLoopData = $item['children']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $child): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <?php $r = $resolveRoute($child['route_candidates'] ?? []); ?>
                                    <?php if($canSee($child) && $r): ?>
                                        <li class="nav-item"><a href="<?php echo e(route($r)); ?>" class="nav-link child-link <?php echo e(! empty($child['route_candidates']) && $matchesRouteCandidates($child['route_candidates']) ? 'active' : ''); ?>"><span class="icon"><i data-feather="<?php echo e($child['icon'] ?? 'circle'); ?>"></i></span><span class="label"><?php echo e($translateMenu($child['title'])); ?></span></a></li>
                                    <?php endif; ?>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </ul>
                        </div>
                    </li>
                <?php else: ?>
                    <li class="nav-item menu-tone-<?php echo e($loop->index % 6); ?>">
                        <?php if(isset($item['action']) && $item['action']==='logout'): ?>
                            <a href="#" class="nav-link" onclick="event.preventDefault(); document.getElementById('logout-form-side').submit();">
                                <span class="icon"><i data-feather="<?php echo e($item['icon']); ?>"></i></span>
                                <span class="label"><?php echo e($translateMenu($item['title'])); ?></span>
                            </a>
                            <form id="logout-form-side" action="<?php echo e(route('logout')); ?>" method="POST" style="display:none;"><?php echo csrf_field(); ?></form>
                        <?php else: ?>
                            <a href="<?php echo e($url); ?>" class="nav-link <?php echo e(! empty($item['route_candidates']) && $matchesRouteCandidates($item['route_candidates']) ? 'active' : ''); ?>">
                                <span class="icon"><i data-feather="<?php echo e($item['icon']); ?>"></i></span>
                                <span class="label"><?php echo e($translateMenu($item['title'])); ?></span>
                            </a>
                        <?php endif; ?>
                    </li>
                <?php endif; ?>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </ul>
    </nav>
</div>

<button class="sidebar-toggle-btn" id="sidebarToggleBtn" title="Toggle sidebar"><i data-feather="menu"></i></button>

<script>
    (function(){
        var sidebar = document.getElementById('sidebarModern');
        var btn = document.getElementById('sidebarToggleBtn');
        btn && btn.addEventListener('click', function(e){
            if(window.innerWidth < 992){
                sidebar.classList.toggle('show');
            } else {
                sidebar.classList.toggle('collapsed');
                document.body.classList.toggle('sidebar-collapsed');
                localStorage.setItem('sidebarCollapsed', sidebar.classList.contains('collapsed'));
            }
            if(window.feather) window.feather.replace();
        });

        if(localStorage.getItem('sidebarCollapsed') === 'true' && window.innerWidth >= 992){
            sidebar.classList.add('collapsed');
            document.body.classList.add('sidebar-collapsed');
        }

        document.addEventListener('DOMContentLoaded', function(){
            if(window.feather) window.feather.replace();

            var input = document.getElementById('sidebarCustomerSearchInput');
            var results = document.getElementById('sidebarCustomerSearchResults');
            var spinner = document.getElementById('sidebarSearchSpinner');
            var timer = null;
            var controller = null;
            var searchUrl = <?php echo json_encode(route('admin.customers.quick-search'), 15, 512) ?>;

            function closeResults(){
                if(!results || !input) return;
                results.classList.add('d-none');
                input.setAttribute('aria-expanded', 'false');
            }

            if(input && results){
                input.addEventListener('input', function(){
                    clearTimeout(timer);
                    if(controller) controller.abort();
                    var query = input.value.trim();
                    if(query.length < 2){ closeResults(); return; }

                    timer = setTimeout(function(){
                        controller = new AbortController();
                        spinner.classList.remove('d-none');
                        fetch(searchUrl + '?q=' + encodeURIComponent(query), {
                            headers: {'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest'},
                            signal: controller.signal
                        }).then(function(response){
                            if(!response.ok) throw new Error('Search failed');
                            return response.json();
                        }).then(function(payload){
                            results.replaceChildren();
                            if(!payload.data.length){
                                var empty = document.createElement('div');
                                empty.className = 'sidebar-search-empty';
                                empty.textContent = 'No customer found';
                                results.appendChild(empty);
                            } else {
                                payload.data.forEach(function(customer){
                                    var link = document.createElement('a');
                                    link.className = 'sidebar-search-result';
                                    link.href = customer.ledger_url;
                                    var title = document.createElement('strong');
                                    title.textContent = (customer.code || ('#' + customer.id)) + ' · ' + customer.name;
                                    var meta = document.createElement('small');
                                    meta.textContent = [customer.phone, customer.ip].filter(Boolean).join(' · ');
                                    link.append(title, meta);
                                    results.appendChild(link);
                                });
                            }
                            results.classList.remove('d-none');
                            input.setAttribute('aria-expanded', 'true');
                        }).catch(function(error){
                            if(error.name !== 'AbortError') closeResults();
                        }).finally(function(){
                            spinner.classList.add('d-none');
                        });
                    }, 300);
                });

                document.addEventListener('click', function(event){
                    if(!document.getElementById('sidebarCustomerSearch')?.contains(event.target)) closeResults();
                });
                input.addEventListener('keydown', function(event){ if(event.key === 'Escape') closeResults(); });
            }
        });

        document.addEventListener('click', function(e){
            if(window.innerWidth < 992){
                if(!sidebar.contains(e.target) && !btn.contains(e.target)){
                    sidebar.classList.remove('show');
                }
            }
        });
    })();
</script>
<?php /**PATH D:\herd\billing\laravel-app\resources\views/layouts/sidebar.blade.php ENDPATH**/ ?>