<!DOCTYPE html>
<html lang="en" data-theme="{{ Auth::check() ? Auth::user()->theme ?? 'light' : 'light' }}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>@yield('title', \App\Helpers\Settings::getSystemName() . ' - Point of Sale')</title>
    <link rel="icon" type="image/png" href="{{ asset('icon2.png') }}">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <style>
        html {
            overflow-x: hidden;
        }
        :root {
            --sidebar-width: 260px;
            --sidebar-hidden-width: 0px;
            --bg-color: #f8f9fa;
            --text-color: #212529;
            --text-muted: #6c757d;
            --card-bg: #ffffff;
            --border-color: #dee2e6;
        }
        
        [data-theme="dark"] {
            --bg-color: #1a1a1a;
            --text-color: #e0e0e0;
            --text-muted: #a0a0a0;
            --card-bg: #2d2d2d;
            --border-color: #404040;
        }
        
        [data-theme="light"] {
            --bg-color: #f8f9fa;
            --text-color: #212529;
            --text-muted: #6c757d;
            --card-bg: #ffffff;
            --border-color: #dee2e6;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: var(--bg-color);
            color: var(--text-color);
            overflow-x: hidden;
        }
        input::placeholder {
            color: var(--text-muted);
        }
        select.form-select, input.form-control {
            background-color: var(--bg-color);
            color: var(--text-color);
            border-color: var(--border-color);
        }
        [data-theme="dark"] .form-select, [data-theme="dark"] .form-control {
            background-color: var(--bg-color);
            color: var(--text-color);
            border-color: var(--border-color);
        }
        .sidebar {
            width: var(--sidebar-width);
            height: 100vh;
            position: fixed;
            left: 0;
            top: 0;
            background: #1a1a2e;
            color: white;
            padding-top: 20px;
            overflow-y: auto;
            transition: transform 0.3s ease;
            z-index: 1000;
            transform: translateX(-100%);
        }
        .sidebar.shown {
            transform: translateX(0);
        }
        .sidebar-toggle {
            position: fixed;
            top: 10px;
            left: 10px;
            background: #1a1a2e;
            border: none;
            color: white;
            width: 35px;
            height: 35px;
            border-radius: 5px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.3s, left 0.3s ease;
            z-index: 1002;
        }
        .sidebar-toggle:hover {
            background: #2d2d4a;
        }
        .sidebar-toggle.expanded {
            left: calc(var(--sidebar-width) + 10px);
        }
        
        .sidebar-toggle i {
            font-size: 1.2rem;
        }
        [data-theme="dark"] .sidebar {
            background: #0d0d0d;
        }
        [data-theme="dark"] .sidebar-toggle {
            background: #0d0d0d;
        }
        [data-theme="dark"] .sidebar-toggle:hover {
            background: #1a1a1a;
        }
        .sidebar a {
            color: rgba(255,255,255,0.8);
            text-decoration: none;
            padding: 12px 20px;
            display: block;
            border-left: 3px solid transparent;
            transition: all 0.3s;
        }
        .sidebar a:hover, .sidebar a.active {
            background: rgba(255,255,255,0.1);
            border-left-color: #0d6efd;
            color: white;
        }
        .sidebar .brand {
            font-size: 1.5rem;
            font-weight: bold;
            padding: 20px;
            text-align: center;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            margin-bottom: 20px;
        }
        .sidebar .section-label {
            background: rgba(255,255,255,0.25);
            color: #ffffff;
            font-weight: 700;
            letter-spacing: 0.5px;
        }
        .main-content {
            margin-left: 0;
            padding: 20px;
            min-height: 100vh;
            background-color: var(--bg-color);
            transition: padding-left 0.3s ease;
            padding-left: 55px;
        }
        .main-content.sidebar-open {
            padding-left: calc(var(--sidebar-width) + 20px);
        }
        .table {
            color: var(--text-color);
        }
        [data-theme="dark"] .table {
            --bs-table-bg: var(--card-bg);
            --bs-table-color: var(--text-color);
        }
        .card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            background-color: var(--card-bg);
            color: var(--text-color);
        }
        [data-theme="dark"] .card {
            box-shadow: 0 2px 10px rgba(0,0,0,0.3);
        }
        .stat-card {
            border-radius: 10px;
            padding: 20px;
            color: white;
        }
        .stat-card.blue { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        .stat-card.green { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); }
        .stat-card.orange { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
        .stat-card.purple { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
        .stat-card.red { background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%); }
        .table-responsive {
            overflow-x: auto;
        }
        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .page-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: #1a1a2e;
        }
        .alert {
            border-radius: 8px;
        }
        .pos-product-card {
            cursor: pointer;
            transition: transform 0.2s;
        }
        .pos-product-card:hover {
            transform: scale(1.02);
        }
        .pos-product-card.selected {
            border: 2px solid #0d6efd;
        }
        @media print {
            .no-print { display: none !important; }
            .sidebar { display: none; }
            .main-content { margin-left: 0; }
            body { background: white; }
            .card { box-shadow: none; }
        }
        @media (max-width: 767.98px) {
            .sidebar {
                width: 100%;
                height: auto;
                position: relative;
                padding-bottom: 10px;
            }
            .sidebar a {
                padding: 10px 15px;
                font-size: 0.9rem;
            }
            .sidebar .brand {
                padding: 15px;
                font-size: 1.2rem;
            }
            .main-content {
                margin-left: 0;
                padding: 15px;
            }
            .page-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            .table {
                font-size: 0.85rem;
            }
            .btn-sm {
                padding: 0.2rem 0.4rem;
                font-size: 0.75rem;
            }
        }
    </style>
    @yield('styles')
</head>
<body>
    @auth
    @php 
    $user = Auth::user();
    $canDashboard = $user->hasPermission('dashboard.view');
    $canPos = $user->hasPermission('pos.sales');
    $canOpeningBalance = $user->hasPermission('opening-balance.view');
    $canOrders = $user->hasPermission('orders.view');
    $canProducts = $user->hasPermission('products.view');
    $canCategories = $user->hasPermission('categories.view');
    $canUnitOfMeasures = $user->hasPermission('unit-of-measures.view');
    $canInventory = $user->hasPermission('inventory.view');
    $canCustomers = $user->hasPermission('customers.view');
    $canSuppliers = $user->hasPermission('suppliers.view');
    $canSuppliersFinance = $user->hasPermission('suppliers.finance');
    $canUsers = $user->hasPermission('users.manage');
    $canSalesReport = $user->hasPermission('reports.sales');
    $canProfitReport = $user->hasPermission('reports.profit');
    $canInventoryReport = $user->hasPermission('reports.inventory');
    $canSupplierPaymentsReport = $user->hasPermission('reports.supplier-payments');
    $canOpeningBalanceReport = $user->hasPermission('reports.opening-balance');
    $canStockMovementReport = $user->hasPermission('reports.stock-movement');
    $canCashierReport = $user->hasPermission('reports.cashier');
    $canCashierSalesReport = $user->hasPermission('reports.cashier-sales');
    $canDisposedReport = $user->hasPermission('reports.disposed');
    $canReconciliationReport = $user->hasPermission('reports.reconciliation');
    $canStockValueReport = $user->hasPermission('reports.stock-value');
    $canMpesaTransactionsReport = $user->hasPermission('reports.mpesa-transactions');
    $canExpenses = $user->hasPermission('expenses.view');
    $canExpiry = $user->hasPermission('expiry.manage');
    $canReconciliation = $user->hasPermission('products.reconciliation');
    $canCashflow = $user->hasPermission('expenses.cashflow');
    $canTax = $user->hasPermission('tax.view');
    $canTaxManage = $user->hasPermission('tax.manage');
    $canEtims = $user->hasPermission('tax.etims.view');
    $canMpesa = $user->hasPermission('mpesa.view');
    $canMpesaManage = $user->hasPermission('mpesa.manage');
    $canCredit = $user->hasPermission('credit.view');
    $canSmsSettings = $user->hasPermission('settings.sms');
    $canReceiptSettings = $user->hasPermission('settings.receipt');
    $canSystemSettings = $user->hasPermission('settings.system');
    $canMpesaAccess = $user->hasPermission('mpesa.access');
    $isSuperUser = $user->isSuperAdmin();
    @endphp
    <button class="sidebar-toggle" onclick="toggleSidebar()">
        <i class="bi bi-list"></i>
    </button>
    <div class="sidebar" id="sidebar">
        <div class="brand">
            <i class="bi bi-shop"></i> <span class="brand-text">{{ \App\Helpers\Settings::getSystemName() }}</span>
        </div>

        <div class="px-3 py-2" style="position: sticky; top: 0; background: #1a1a2e; z-index: 10; padding-bottom: 10px;">
            <input type="text" id="navSearch" class="form-control form-control-sm" placeholder="Search menu..." onkeyup="filterNav(this.value)">
        </div>

        <!-- Main -->
        <div class="text-muted small px-3 py-2 mt-3 section-label">Main</div>
        @if($canDashboard)
        <a href="{{ route('dashboard') }}" class="{{ request()->routeIs('dashboard') ? 'active' : '' }}">
            <i class="bi bi-speedometer2 me-2"></i> <span class="nav-text">Dashboard</span>
        </a>
        @endif
        @if($canPos)
        <a href="{{ route('pos.sales') }}" class="{{ request()->routeIs('pos.*') ? 'active' : '' }}">
            <i class="bi bi-cart-plus me-2"></i> <span class="nav-text">POS / Sales</span>
        </a>
        @endif
        @if($canOrders)
        <a href="{{ route('orders.index') }}" class="{{ request()->routeIs('orders.*') ? 'active' : '' }}">
            <i class="bi bi-receipt me-2"></i> <span class="nav-text">Orders</span>
        </a>
        @endif

        <!-- Finance -->
        @if($canOpeningBalance || $canExpenses || $canCashflow)
        <div class="text-muted small px-3 py-2 mt-3 section-label">Finance</div>
        @endif
        @if($canOpeningBalance)
        <a href="{{ route('opening-balance.report') }}" class="{{ request()->routeIs('opening-balance*') ? 'active' : '' }}">
            <i class="bi bi-cash-stack me-2"></i> <span class="nav-text">Opening Balance</span>
        </a>
        @endif
        @if($canExpenses)
        <a href="{{ route('expenses.index') }}" class="{{ request()->routeIs('expenses.index') || request()->routeIs('expenses.create') ? 'active' : '' }}">
            <i class="bi bi-wallet2 me-2"></i> <span class="nav-text">Expense Management</span>
        </a>
        @endif
        @if($canCashflow)
        <a href="{{ route('expenses.cashflow') }}" class="{{ request()->routeIs('expenses.cashflow') ? 'active' : '' }}">
            <i class="bi bi-graph-down me-2"></i> <span class="nav-text">Cash Flow</span>
        </a>
        @endif
        @if($canTax)
        <a href="{{ route('tax.index') }}" class="{{ request()->routeIs('tax.*') ? 'active' : '' }}">
            <i class="bi bi-percent me-2"></i> <span class="nav-text">Tax</span>
        </a>
        @endif
        @if($isSuperUser)
        <a href="{{ route('mpesa.index') }}" class="{{ request()->routeIs('mpesa.*') ? 'active' : '' }}">
            <i class="bi bi-phone me-2"></i> <span class="nav-text">M-Pesa</span>
        </a>
        @endif
        @if($canCredit)
        <a href="{{ route('credit.index') }}" class="{{ request()->routeIs('credit.*') ? 'active' : '' }}">
            <i class="bi bi-credit-card me-2"></i> <span class="nav-text">Credit</span>
        </a>
        @endif

        <!-- Products -->
        @if($canProducts || $canCategories || $canInventory)
        <div class="text-muted small px-3 py-2 mt-3 section-label">Products</div>
        @if($canProducts)
        <a href="{{ route('products.index') }}" class="{{ request()->routeIs('products.*') ? 'active' : '' }}">
            <i class="bi bi-box-seam me-2"></i> <span class="nav-text">Products</span>
        </a>
        @endif
        @if($canCategories)
        <a href="{{ route('categories.index') }}" class="{{ request()->routeIs('categories.*') ? 'active' : '' }}">
            <i class="bi bi-tags me-2"></i> <span class="nav-text">Categories</span>
        </a>
        @endif
        @if($canUnitOfMeasures)
        <a href="{{ route('unit-of-measures.index') }}" class="{{ request()->routeIs('unit-of-measures.*') ? 'active' : '' }}">
            <i class="bi bi-stack me-2"></i> <span class="nav-text">Unit of Measures</span>
        </a>
        @endif
        @if($canInventory)
        <a href="{{ route('inventory.index') }}" class="{{ request()->routeIs('inventory.index') ? 'active' : '' }}">
            <i class="bi bi-clipboard-data me-2"></i> <span class="nav-text">Inventory Log</span>
        </a>
        <a href="{{ route('inventory.stock-in') }}" class="{{ request()->routeIs('inventory.stock-in') ? 'active' : '' }}">
            <i class="bi bi-plus-circle me-2"></i> <span class="nav-text">Stock In</span>
        </a>
        <a href="{{ route('inventory.price-adjustment') }}" class="{{ request()->routeIs('inventory.price-adjustment') ? 'active' : '' }}">
            <i class="bi bi-currency-dollar me-2"></i> <span class="nav-text">Price Adjustment</span>
        </a>
        <a href="{{ route('inventory.product-price-history') }}" class="{{ request()->routeIs('inventory.product-price-history') ? 'active' : '' }}">
            <i class="bi bi-graph-up me-2"></i> <span class="nav-text">Price History</span>
        </a>
        @if($canExpiry)
        <a href="{{ route('expiry.index') }}" class="{{ request()->routeIs('expiry.*') ? 'active' : '' }}">
            <i class="bi bi-calendar-x me-2"></i> <span class="nav-text">Expiry Management</span>
        </a>
        @endif
        @if($canReconciliation)
        <a href="{{ route('reports.reconciliation') }}" class="{{ request()->routeIs('reports.reconciliation*') ? 'active' : '' }}">
            <i class="bi bi-arrow-repeat me-2"></i> <span class="nav-text">Reconciliation Report</span>
        </a>
        @endif
        @endif

        <!-- Reports -->
        @if($isSuperUser || $canSalesReport || $canProfitReport || $canInventoryReport || $canStockValueReport || $canSupplierPaymentsReport || $canOpeningBalanceReport || $canStockMovementReport || $canCashierReport || $canCashierSalesReport || $canDisposedReport || $canReconciliationReport || $canMpesaTransactionsReport)
        <div class="text-muted small px-3 py-2 mt-3 section-label">Reports</div>
        @if($isSuperUser)
        <a href="{{ route('reports.mpesa-transactions') }}" class="{{ request()->routeIs('reports.mpesa-transactions*') ? 'active' : '' }}">
            <i class="bi bi-currency-exchange me-2"></i> <span class="nav-text">M-Pesa Transactions</span>
        </a>
        @endif
        @if($canCashierSalesReport)
        <a href="{{ route('reports.cashier-sales') }}" class="{{ request()->routeIs('reports.cashier-sales*') ? 'active' : '' }}">
            <i class="bi bi-people-fill me-2"></i> <span class="nav-text">Cashier Sales</span>
        </a>
        @endif
        @if($canCashierReport)
        <a href="{{ route('reports.cashier') }}" class="{{ request()->routeIs('reports.cashier') && !request()->routeIs('reports.cashier-sales*') ? 'active' : '' }}">
            <i class="bi bi-person-badge me-2"></i> <span class="nav-text">Cashier Activity</span>
        </a>
        @endif
        @if($canSalesReport)
        <a href="{{ route('reports.sales') }}" class="{{ request()->routeIs('reports.sales*') ? 'active' : '' }}">
            <i class="bi bi-graph-up me-2"></i> <span class="nav-text">Sales Report</span>
        </a>
        @endif
        @if($canStockMovementReport)
        <a href="{{ route('reports.stock-movement') }}" class="{{ request()->routeIs('reports.stock-movement*') ? 'active' : '' }}">
            <i class="bi bi-arrow-left-right me-2"></i> <span class="nav-text">Stock Movement</span>
        </a>
        @endif
        @if($canProfitReport)
        <a href="{{ route('reports.profit') }}" class="{{ request()->routeIs('reports.profit*') ? 'active' : '' }}">
            <i class="bi bi-currency-dollar me-2"></i> <span class="nav-text">Profit Report</span>
        </a>
        @endif
        @if($canInventoryReport)
        <a href="{{ route('reports.inventory') }}" class="{{ request()->routeIs('reports.inventory*') ? 'active' : '' }}">
            <i class="bi bi-boxes me-2"></i> <span class="nav-text">Inventory Report</span>
        </a>
        @endif
        @if($canStockValueReport)
        <a href="{{ route('reports.stock-value') }}" class="{{ request()->routeIs('reports.stock-value*') ? 'active' : '' }}">
            <i class="bi bi-cash-stack me-2"></i> <span class="nav-text">Stock Value Report</span>
        </a>
        @endif
        @if($canSupplierPaymentsReport)
        <a href="{{ route('reports.supplier-payments') }}" class="{{ request()->routeIs('reports.supplier-payments*') ? 'active' : '' }}">
            <i class="bi bi-credit-card me-2"></i> <span class="nav-text">Supplier Payments</span>
        </a>
        @endif
        @if($canDisposedReport)
        <a href="{{ route('reports.disposed') }}" class="{{ request()->routeIs('reports.disposed*') ? 'active' : '' }}">
            <i class="bi bi-trash me-2"></i> <span class="nav-text">Disposed Products</span>
        </a>
        @endif
        @if($canReconciliationReport)
        <a href="{{ route('reports.reconciliation') }}" class="{{ request()->routeIs('reports.reconciliation*') ? 'active' : '' }}">
            <i class="bi bi-arrow-repeat me-2"></i> <span class="nav-text">Reconciliation Report</span>
        </a>
        @endif
        @endif

        <!-- Settings -->
        @if($canUsers || $isSuperUser)
        <div class="text-muted small px-3 py-2 mt-3 section-label">Settings</div>
        @if($canUsers)
        <a href="{{ route('users.index') }}" class="{{ request()->routeIs('users.*') ? 'active' : '' }}">
            <i class="bi bi-person-gear me-2"></i> <span class="nav-text">Users</span>
        </a>
        @endif
        @if($isSuperUser)
        <a href="{{ route('settings.sms') }}" class="{{ request()->routeIs('settings.sms') ? 'active' : '' }}">
            <i class="bi bi-chat-dots me-2"></i> <span class="nav-text">SMS</span>
        </a>
        @endif
        @if($isSuperUser)
        <a href="{{ route('settings.index') }}" class="{{ request()->routeIs('settings.index') ? 'active' : '' }}">
            <i class="bi bi-receipt me-2"></i> <span class="nav-text">Receipt & Reports</span>
        </a>
        @endif
        @if($isSuperUser)
        <a href="{{ route('settings.system') }}" class="{{ request()->routeIs('settings.system') ? 'active' : '' }}">
            <i class="bi bi-gear me-2"></i> <span class="nav-text">System Settings</span>
        </a>
        @endif
        <div class="px-3 py-2">
            <label class="form-label small text-muted">Theme</label>
            <select class="form-select form-select-sm" id="themeSelect">
                <option value="light" {{ (Auth::user()->theme ?? 'light') == 'light' ? 'selected' : '' }}>Light</option>
                <option value="dark" {{ (Auth::user()->theme ?? 'light') == 'dark' ? 'selected' : '' }}>Dark</option>
            </select>
        </div>
        @endif
        @endif

        <div class="mt-4 pt-3 border-top">
            <a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('clientTime').value = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString(); document.getElementById('logout-form').submit();">
                <i class="bi bi-box-arrow-left me-2"></i> <span class="nav-text">Logout</span>
            </a>
            <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                @csrf
                <input type="hidden" name="client_time" id="clientTime">
            </form>
        </div>
    </div>
    @endauth

    <div class="main-content">
        @if(session('success'))
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                {{ session('success') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        @endif

        @if(session('error'))
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                {{ session('error') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        @endif

        @yield('content')
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script>
        // Set initial theme
        const userTheme = '{{ Auth::check() ? (Auth::user()->theme ?? "light") : "light" }}';
        document.documentElement.setAttribute('data-theme', userTheme);
        
        // Set CSRF token for jQuery AJAX
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        // Theme switcher
        document.getElementById('themeSelect')?.addEventListener('change', function() {
            const theme = this.value;
            document.documentElement.setAttribute('data-theme', theme);
            
            // Save to server
            fetch('{{ route("settings.theme") }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify({ theme: theme })
            }).catch(() => {});
        });
        
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const mainContent = document.querySelector('.main-content');
            const toggleBtn = document.querySelector('.sidebar-toggle');
            
            sidebar.classList.toggle('shown');
            mainContent.classList.toggle('sidebar-open');
            toggleBtn.classList.toggle('expanded');
            
            if (sidebar.classList.contains('shown')) {
                localStorage.setItem('sidebar-shown', 'true');
            } else {
                localStorage.setItem('sidebar-shown', 'false');
            }
        }

        function filterNav(query) {
            query = query.toLowerCase();
            const links = document.querySelectorAll('#sidebar a');
            const sections = document.querySelectorAll('#sidebar .section-label');
            
            links.forEach(link => {
                const text = link.querySelector('.nav-text');
                if (text) {
                    const match = text.textContent.toLowerCase().includes(query);
                    link.style.display = match ? '' : 'none';
                }
            });
            
            sections.forEach(section => {
                let next = section.nextElementSibling;
                let hasVisible = false;
                while (next && !next.classList.contains('section-label')) {
                    if (next.tagName === 'A' && next.style.display !== 'none') {
                        hasVisible = true;
                        break;
                    }
                    next = next.nextElementSibling;
                }
                section.style.display = hasVisible || query === '' ? '' : 'none';
            });
        }
        
        // Check saved state on page load - default to hidden
        document.addEventListener('DOMContentLoaded', function() {
            if (localStorage.getItem('sidebar-shown') === 'true') {
                document.getElementById('sidebar').classList.add('shown');
                document.querySelector('.main-content').classList.add('sidebar-open');
                document.querySelector('.sidebar-toggle').classList.add('expanded');
            }

            // Inactivity auto-logout
            const inactivityTimeout = {{ \App\Helpers\Settings::get('inactivity_timeout', 300) }};
            if (inactivityTimeout > 0) {
                let inactivityTimer;
                
                function resetTimer() {
                    clearTimeout(inactivityTimer);
                    inactivityTimer = setTimeout(function() {
                        // Show countdown modal before logout
                        let countdown = 30;
                        const modal = document.createElement('div');
                        modal.className = 'modal fade show';
                        modal.style.display = 'block';
                        modal.style.backgroundColor = 'rgba(0,0,0,0.5)';
                        modal.innerHTML = `
                            <div class="modal-dialog modal-dialog-centered">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title">Session Expiring</h5>
                                    </div>
                                    <div class="modal-body text-center">
                                        <p>You will be logged out due to inactivity in <strong id="countdown">${countdown}</strong> seconds.</p>
                                        <p class="text-muted">Move your mouse or press any key to stay logged in.</p>
                                    </div>
                                </div>
                            </div>
                        `;
                        document.body.appendChild(modal);
                        
                        const countdownEl = document.getElementById('countdown');
                        const countdownTimer = setInterval(function() {
                            countdown--;
                            countdownEl.textContent = countdown;
                            if (countdown <= 0) {
                                clearInterval(countdownTimer);
                                const localDate = new Date();
                                const offset = localDate.getTimezoneOffset();
                                const clientTime = new Date(localDate.getTime() - offset * 60000).toISOString().slice(0, 19).replace('T', ' ');
                                fetch('{{ route("auto.logout") }}', {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ client_time: clientTime })
                        }).then(() => window.location.href = '/login');
                            }
                        }, 1000);
                        
                        // Reset on user activity
                        const resetLogout = function() {
                            clearInterval(countdownTimer);
                            clearTimeout(inactivityTimer);
                            modal.remove();
                            resetTimer();
                            document.removeEventListener('mousemove', resetLogout);
                            document.removeEventListener('keydown', resetLogout);
                            document.removeEventListener('click', resetLogout);
                            document.removeEventListener('scroll', resetLogout);
                        };
                        
                        document.addEventListener('mousemove', resetLogout);
                        document.addEventListener('keydown', resetLogout);
                        document.addEventListener('click', resetLogout);
                        document.addEventListener('scroll', resetLogout);
                    }, inactivityTimeout * 1000);
                }
                
                // Initial timer
                resetTimer();
                
                // Reset on user activity
                ['mousemove', 'keydown', 'click', 'scroll'].forEach(function(event) {
                    document.addEventListener(event, function() {
                        clearTimeout(inactivityTimer);
                        inactivityTimer = setTimeout(resetTimer, inactivityTimeout * 1000);
                    });
                });
            }
        });
    </script>
    @yield('scripts')
</body>
</html>