<?php
if (!defined('BASE_URL')) {
    define('BASE_URL', '/rooms');
}

/*
 * Corrected sidebar.php
 * - Uses role_permissions via permission_check.php
 * - Fails closed when PDO is missing instead of showing everything
 * - Wraps all menu items in permission checks
 * - Hides an entire group when the user has no visible item in that group
 */

$permissionHelper = __DIR__ . '/permission_check.php';
if (file_exists($permissionHelper)) {
    require_once $permissionHelper;
}

if (!function_exists('ss_pdo')) {
    function ss_pdo(): ?PDO
    {
        if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
            return $GLOBALS['pdo'];
        }

        if (isset($GLOBALS['connect']) && $GLOBALS['connect'] instanceof PDO) {
            return $GLOBALS['connect'];
        }

        return null;
    }
}

if (!function_exists('ss_can')) {
    function ss_can(string $permissionKey, string $action = 'view'): bool
    {
        $permissionKey = strtolower(trim($permissionKey));
        $action = strtolower(trim($action ?: 'view'));

        if ($permissionKey === '') {
            return true;
        }

        $pdoConn = ss_pdo();

        /*
         * Important security behaviour:
         * If permissions cannot be checked, do NOT show the menu item.
         */
        if (!$pdoConn instanceof PDO) {
            return false;
        }

        if (function_exists('has_permission')) {
            return has_permission($pdoConn, $permissionKey, $action);
        }

        if (function_exists('can_view_menu') && $action === 'view') {
            return can_view_menu($pdoConn, $permissionKey);
        }

        return false;
    }
}

if (!function_exists('ss_e')) {
    function ss_e($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('sidebar_group_active')) {
    function sidebar_group_active(array $paths): bool
    {
        if (!function_exists('nav_active')) {
            return false;
        }
        return nav_active($paths) !== '';
    }
}

if (!function_exists('ss_visible_items')) {
    function ss_visible_items(array $items): array
    {
        $visible = [];

        foreach ($items as $item) {
            if (!empty($item['children']) && is_array($item['children'])) {
                $item['children'] = ss_visible_items($item['children']);
                if ($item['children']) {
                    $visible[] = $item;
                }
                continue;
            }

            $permission = $item['permission'] ?? '';
            $action = $item['action'] ?? 'view';

            if (ss_can($permission, $action)) {
                $visible[] = $item;
            }
        }

        return $visible;
    }
}

if (!function_exists('ss_render_nav_item')) {
    function ss_render_nav_item(array $item): void
    {
        if (!empty($item['children']) && is_array($item['children'])) {
            $children = ss_visible_items($item['children']);
            if (!$children) return;

            $activePaths = [];
            foreach ($children as $child) {
                foreach (($child['active'] ?? [$child['href'] ?? '']) as $path) {
                    if ($path !== '') $activePaths[] = $path;
                }
            }

            $isOpen = sidebar_group_active($activePaths) ? 'is-open' : '';
            $icon = $item['icon'] ?? 'bi-folder2-open';
            $label = $item['label'] ?? 'Menu';
            ?>
            <div class="sidebar-subgroup <?php echo ss_e($isOpen); ?>">
                <button type="button"
                        class="sidebar-subgroup-toggle"
                        data-subgroup-toggle
                        aria-expanded="<?php echo $isOpen !== '' ? 'true' : 'false'; ?>">
                    <span class="nav-icon"><i class="bi <?php echo ss_e($icon); ?>"></i></span>
                    <span class="nav-text"><?php echo ss_e($label); ?></span>
                    <i class="bi bi-chevron-right subgroup-chevron"></i>
                </button>
                <div class="sidebar-subgroup-body">
                    <?php foreach ($children as $child) { ss_render_nav_item($child); } ?>
                </div>
            </div>
            <?php
            return;
        }

        $paths = $item['active'] ?? [$item['href'] ?? ''];
        $active = function_exists('nav_active') ? nav_active($paths) : '';
        $href = BASE_URL . ($item['href'] ?? '#');
        $icon = $item['icon'] ?? 'bi-circle';
        $label = $item['label'] ?? '';
        $extraClass = $item['class'] ?? '';
        ?>
        <a class="nav-link <?php echo ss_e($extraClass); ?> <?php echo ss_e($active); ?>" href="<?php echo ss_e($href); ?>" title="<?php echo ss_e($label); ?>">
            <span class="nav-icon"><i class="bi <?php echo ss_e($icon); ?>"></i></span>
            <span class="nav-text"><?php echo ss_e($label); ?></span>
            <?php if (!empty($item['tag'])): ?>
                <span class="nav-tag"><?php echo ss_e($item['tag']); ?></span>
            <?php endif; ?>
            <?php if (!empty($item['badge_id'])): ?>
                <span class="badge bg-danger alerts-badge" id="<?php echo ss_e($item['badge_id']); ?>">0</span>
            <?php endif; ?>
        </a>
        <?php
    }
}

if (!function_exists('ss_render_group')) {
    function ss_render_group(string $title, array $items, array $activePaths): void
    {
        $items = ss_visible_items($items);
        if (!$items) {
            return;
        }
        $isOpen = sidebar_group_active($activePaths) ? 'is-open' : '';
        ?>
        <div class="sidebar-group <?php echo ss_e($isOpen); ?>">
            <button type="button" class="sidebar-group-toggle" data-group-toggle>
                <span class="sidebar-section-title"><?php echo ss_e($title); ?></span>
                <i class="bi bi-chevron-down group-chevron"></i>
            </button>
            <div class="sidebar-group-body">
                <nav class="sidebar-nav">
                    <?php foreach ($items as $item) { ss_render_nav_item($item); } ?>
                </nav>
            </div>
        </div>
        <?php
    }
}

$appLabel  = isset($appName) && trim((string)$appName) !== '' ? $appName : 'RoomZ';
$userLabel = isset($currentUserName) && trim((string)$currentUserName) !== '' ? $currentUserName : 'User';

$groups = [
    [
        'title' => 'Overview',
        'active' => ['/rooms/dashboard.php', '/dashboard.php', '/modules/reports/executive_dashboard.php'],
        'items' => [
            ['label' => 'Dashboard', 'icon' => 'bi-speedometer2', 'href' => '/modules/calendar/calendar.php', 'active' => ['modules/calendar/calendar.php', '/calendar.php.php'], 'permission' => 'dashboard'],
            ['label' => 'Executive Dashboard', 'icon' => 'bi-stars', 'href' => '/modules/reports/executive_dashboard.php', 'active' => ['/modules/reports/executive_dashboard.php'], 'permission' => 'executive_dashboard'],
        ],
    ],
    [
        'title' => 'FrontDesk & Control',
        'active' => ['/modules/payments/frontdesk_dashboard.php', '/modules/payments/arrivals_today.php', '/modules/payments/departures_today.php', '/modules/payments/room_rack.php', '/modules/payments/housekeeping_board.php'],
        'items' => [
            ['label' => 'Front Desk', 'icon' => 'bi-display', 'href' => '/modules/payments/frontdesk_dashboard.php', 'active' => ['/modules/payments/frontdesk_dashboard.php'], 'permission' => 'frontdesk_dashboard'],
            ['label' => 'Arrivals', 'icon' => 'bi-box-arrow-in-right', 'href' => '/modules/payments/arrivals_today.php', 'active' => ['/modules/payments/arrivals_today.php'], 'permission' => 'arrivals_today'],
            ['label' => 'Departures', 'icon' => 'bi-box-arrow-right', 'href' => '/modules/payments/departures_today.php', 'active' => ['/modules/payments/departures_today.php'], 'permission' => 'departures_today'],
            ['label' => 'Weekly Forecast', 'icon' => 'bi-grid-3x3-gap', 'href' => '/modules/payments/weekly_forecast_with_pdf_groups.php', 'active' => ['/modules/payments/weekly_forecast_with_pdf_groups.php'], 'permission' => 'room_rack'],
            ['label' => 'Room Rack', 'icon' => 'bi-grid-3x3-gap', 'href' => '/modules/payments/room_rack.php', 'active' => ['/modules/payments/room_rack.php'], 'permission' => 'room_rack'],
            ['label' => 'HouseKeeping', 'icon' => 'bi-brush', 'href' => '/modules/payments/housekeeping_board.php', 'active' => ['/modules/payments/housekeeping_board.php'], 'permission' => 'housekeeping_board'],
            ['label' => 'Night Audit', 'icon' => 'bi-moon-stars', 'href' => '/modules/payments/night_audit.php', 'active' => ['/modules/payments/night_audit.php'], 'permission' => 'night_audit'],
            ['label' => 'Occupancy Forecast', 'icon' => 'bi-calendar-range', 'href' => '/modules/payments/occupancy_forecast.php', 'active' => ['/modules/payments/occupancy_forecast.php'], 'permission' => 'occupancy_forecast'],
            ['label' => 'Shift Summary', 'icon' => 'bi-clipboard-data', 'href' => '/modules/frontoffice/shift_summary.php', 'active' => ['/modules/frontoffice/shift_summary.php'], 'permission' => 'front_office_shift_summary'],
        ],
    ],
    [
        'title' => 'Operations',
        'active' => ['/modules/reservations/', '/modules/quotations/', '/modules/calendar/availability_calendar.php', '/modules/calendar/availability_planner.php', '/modules/guests/', '/modules/services/'],
        'items' => [
            ['label' => 'Booking Control Centre', 'icon' => 'bi-broadcast-pin', 'href' => '/modules/reservations/booking_control_centre.php', 'active' => ['/modules/reservations/booking_control_centre.php'], 'permission' => 'reservations', 'class' => 'nav-link-command', 'tag' => 'HUB'],
            ['label' => 'Reservations', 'icon' => 'bi-journal-text', 'href' => '/modules/reservations/reservation_list.php', 'active' => ['/modules/reservations/reservation_list.php', '/modules/reservations/reservation_form.php'], 'permission' => 'reservations'],
            ['label' => 'Quotations', 'icon' => 'bi-file-earmark-text', 'href' => '/modules/quotations/quotation_list.php', 'active' => ['/modules/quotations/', '/modules/quotations/quotation_list.php', '/modules/quotations/quotation_form.php'], 'permission' => 'quotations'],
            ['label' => 'Availability Calendar', 'icon' => 'bi-calendar-week', 'href' => '/modules/calendar/availability_calendar.php', 'active' => ['/modules/calendar/availability_calendar.php'], 'permission' => 'availability_calendar'],
           /* ['label' => 'Rooming', 'icon' => 'bi-diagram-3', 'href' => '/modules/calendar/availability_planner.php', 'active' => ['/modules/calendar/availability_planner.php'], 'permission' => 'availability_planner'],
            ['label' => 'Guests', 'icon' => 'bi-person-lines-fill', 'href' => '/modules/guests/guests.php', 'active' => ['/modules/guests/'], 'permission' => 'guests'],*/
            
        ],
    ],
    [
        'title' => 'Stores / Inventory',
        'active' => ['/modules/inventory/'],
        'items' => [
            [
                'label' => 'Inventory Operations',
                'icon' => 'bi-boxes',
                'children' => [
                    ['label' => 'Inventory Dashboard', 'icon' => 'bi-speedometer2', 'href' => '/modules/inventory/inventory_dashboard.php', 'active' => ['/modules/inventory/inventory_dashboard.php'], 'permission' => 'inventory_dashboard'],
                    ['label' => 'Items', 'icon' => 'bi-box-seam', 'href' => '/modules/inventory/inventory_items.php', 'active' => ['/modules/inventory/inventory_items.php'], 'permission' => 'inventory_items'],
                    ['label' => 'Stores', 'icon' => 'bi-shop', 'href' => '/modules/inventory/store_locations.php', 'active' => ['/modules/inventory/store_locations.php'], 'permission' => 'store_locations'],
                    ['label' => 'Stock by Location', 'icon' => 'bi-grid-3x3-gap', 'href' => '/modules/inventory/stock_by_location.php', 'active' => ['/modules/inventory/stock_by_location.php'], 'permission' => 'purchase_orders'],
                    ['label' => 'Suppliers', 'icon' => 'bi-truck-front', 'href' => '/modules/inventory/suppliers.php', 'active' => ['/modules/inventory/suppliers.php'], 'permission' => 'suppliers'],
                    ['label' => 'Purchase Orders', 'icon' => 'bi-file-earmark-text', 'href' => '/modules/inventory/purchase_orders.php', 'active' => ['/modules/inventory/purchase_orders.php'], 'permission' => 'purchase_orders'],
                    ['label' => 'PO Approvals', 'icon' => 'bi-shield-check', 'href' => '/modules/inventory/purchase_order_approvals.php', 'active' => ['/modules/inventory/purchase_order_approvals.php'], 'permission' => 'purchase_order_approvals'],
                    ['label' => 'Internal Requisition', 'icon' => 'bi-arrow-left-right', 'href' => '/modules/inventory/internal_requisition.php', 'active' => ['/modules/inventory/internal_requisition.php'], 'permission' => 'internal_requisition'],
                    ['label' => 'GRN / Purchases', 'icon' => 'bi-truck', 'href' => '/modules/inventory/grn.php', 'active' => ['/modules/inventory/grn.php'], 'permission' => 'grn'],
                    ['label' => 'Supplier Returns', 'icon' => 'bi-arrow-return-left', 'href' => '/modules/inventory/goods_return_note.php', 'active' => ['/modules/inventory/goods_return_note.php'], 'permission' => 'grn'],
                    ['label' => 'Stock Movements', 'icon' => 'bi-arrow-left-right', 'href' => '/modules/inventory/stock_movements.php', 'active' => ['/modules/inventory/stock_movements.php'], 'permission' => 'stock_movements'],
                    ['label' => 'Stock Adjustments', 'icon' => 'bi-sliders', 'href' => '/modules/inventory/stock_adjustments.php', 'active' => ['/modules/inventory/stock_adjustments.php'], 'permission' => 'stock_adjustments'],
                    ['label' => 'Adjustment Approvals', 'icon' => 'bi-shield-check', 'href' => '/modules/inventory/stock_adjustment_approvals.php', 'active' => ['/modules/inventory/stock_adjustment_approvals.php'], 'permission' => 'stock_adjustment_approvals'],
                    ['label' => 'Opening Stock', 'icon' => 'bi-box-arrow-in-down', 'href' => '/modules/inventory/import_opening_stock.php', 'active' => ['/modules/inventory/import_opening_stock.php'], 'permission' => 'low_stock_report'],
                    ['label' => 'Stock Take', 'icon' => 'bi-clipboard-check', 'href' => '/modules/inventory/stock_take.php', 'active' => ['/modules/inventory/stock_take.php'], 'permission' => 'stock_take'],
                ],
            ],
            [
                'label' => 'Control & Reporting',
                'icon' => 'bi-graph-up-arrow',
                'children' => [
                    ['label' => 'Consignment Stock', 'icon' => 'bi-box2-heart', 'href' => '/modules/inventory/curio_consignment.php', 'active' => ['/modules/inventory/curio_consignment.php'], 'permission' => 'purchase_orders'],
                    ['label' => 'Consignment Intake', 'icon' => 'bi-box-arrow-in-down', 'href' => '/modules/inventory/curio_consignment_intake.php', 'active' => ['/modules/inventory/curio_consignment_intake.php'], 'permission' => 'purchase_orders'],
                    ['label' => 'Supplier Ledger', 'icon' => 'bi-journal-text', 'href' => '/modules/inventory/supplier_ledger.php', 'active' => ['/modules/inventory/supplier_ledger.php'], 'permission' => 'supplier_ledger'],
                    ['label' => 'Supplier Payments', 'icon' => 'bi-cash-coin', 'href' => '/modules/inventory/supplier_payments.php', 'active' => ['/modules/inventory/supplier_payments.php'], 'permission' => 'supplier_payments'],
                    ['label' => 'Stock Valuation', 'icon' => 'bi-bar-chart', 'href' => '/modules/inventory/stock_valuation_report.php', 'active' => ['/modules/inventory/stock_valuation_report.php'], 'permission' => 'stock_valuation_report'],
                    ['label' => 'Month-End Closing', 'icon' => 'bi-calendar-check', 'href' => '/modules/inventory/month_end_inventory_report.php', 'active' => ['/modules/inventory/month_end_inventory_report.php'], 'permission' => 'month_end_inventory'],
                    ['label' => 'Stock Audit Trail', 'icon' => 'bi-shield-check', 'href' => '/modules/inventory/stock_audit_trail_report.php', 'active' => ['/modules/inventory/stock_audit_trail_report.php'], 'permission' => 'audit_log'],
                    ['label' => 'Shrinkage Dashboard', 'icon' => 'bi-exclamation-triangle', 'href' => '/modules/inventory/inventory_shrinkage_dashboard.php', 'active' => ['/modules/inventory/inventory_shrinkage_dashboard.php'], 'permission' => 'reports'],
                    ['label' => 'Owner Profit', 'icon' => 'bi-gem', 'href' => '/modules/inventory/owner_profit_dashboard.php', 'active' => ['/modules/inventory/owner_profit_dashboard.php'], 'permission' => 'owner_profit_dashboard'],
                ],
            ],
        ],
    ],

/*    [
        'title' => 'POS',
        'active' => ['/modules/pos/', '/modules/inventory/pos_sales_report.php'],
        'items' => [
            ['label' => 'POS Terminal', 'icon' => 'bi-cash-register', 'href' => '/modules/pos/pos.php', 'active' => ['/modules/pos/pos.php'], 'permission' => 'pos'],
            ['label' => 'Printer Setup', 'icon' => 'bi-printer', 'href' => '/modules/pos/pos_printers.php', 'active' => ['/modules/pos/pos_printers.php'], 'permission' => 'pos_printers'],
            ['label' => 'POS Orders', 'icon' => 'bi-receipt', 'href' => '/modules/pos/pos_orders.php', 'active' => ['/modules/pos/pos_orders.php'], 'permission' => 'pos_orders'],
            ['label' => 'POS Shifts', 'icon' => 'bi-person-badge', 'href' => '/modules/pos/pos_shifts.php', 'active' => ['/modules/pos/pos_shifts.php'], 'permission' => 'pos_shifts'],
            ['label' => 'POS Approvals', 'icon' => 'bi-shield-check', 'href' => '/modules/pos/pos_approvals.php', 'active' => ['/modules/pos/pos_approvals.php'], 'permission' => 'pos_approvals'],
            ['label' => 'POS Sales Report', 'icon' => 'bi-receipt-cutoff', 'href' => '/modules/inventory/pos_sales_report.php', 'active' => ['/modules/inventory/pos_sales_report.php'], 'permission' => 'pos_sales_report'],
        ],
    ],

    [
        'title' => 'Front Office POS',
        'active' => ['/modules/frontoffice/'],
        'items' => [
            ['label' => 'Front Office POS', 'icon' => 'bi-bag-check', 'href' => '/modules/frontoffice/front_office_pos.php', 'active' => ['/modules/frontoffice/front_office_pos.php'], 'permission' => 'front_office_pos'],
            ['label' => 'Spa & Curio Sales', 'icon' => 'bi-shop-window', 'href' => '/modules/frontoffice/sales_list.php', 'active' => ['/modules/frontoffice/sales_list.php', '/modules/frontoffice/sale_view.php'], 'permission' => 'front_office_sales'],
            ['label' => 'Shift Summary', 'icon' => 'bi-clipboard-data', 'href' => '/modules/frontoffice/shift_summary.php', 'active' => ['/modules/frontoffice/shift_summary.php'], 'permission' => 'front_office_shift_summary'],
        ],
    ],
*/

    [
        'title' => 'Restaurant',
        'active' => ['/modules/restaurant/', '/modules/inventory/recipes.php', '/modules/inventory/recipe_import.php', '/modules/inventory/recipe_profit_report.php'],
        'items' => [
            [
                'label' => 'Restaurant Operations',
                'icon' => 'bi-cup-hot',
                'children' => [
                    ['label' => 'Restaurant Dashboard', 'icon' => 'bi-speedometer2', 'href' => '/modules/restaurant/dashboard.php', 'active' => ['/modules/restaurant/dashboard.php'], 'permission' => 'restaurant_dashboard'],
                    ['label' => 'Table Planner', 'icon' => 'bi-grid-3x3-gap', 'href' => '/modules/restaurant/planner.php', 'active' => ['/modules/restaurant/planner.php', '/modules/restaurant/restaurant_planner.php'], 'permission' => 'restaurant_planner'],
                    ['label' => 'Room Planner', 'icon' => 'bi-grid-3x3-gap', 'href' => '/modules/restaurant/planner_room.php', 'active' => ['/modules/restaurant/planner_room.php', '/modules/restaurant/restaurant_planner.php'], 'permission' => 'restaurant_planner'],
                    ['label' => 'Restaurant Splits', 'icon' => 'bi-scissors', 'href' => '/modules/restaurant/restaurant_split_reprint.php', 'active' => ['/modules/restaurant/restaurant_split_reprint.php'], 'permission' => 'restaurant_reservations'],
                    ['label' => 'Restaurant Orders', 'icon' => 'bi-receipt-cutoff', 'href' => '/modules/restaurant/orders.php', 'active' => ['/modules/restaurant/orders.php', '/modules/restaurant/order_view.php'], 'permission' => 'restaurant_orders'],
                    ['label' => 'Cashier / Close Tables', 'icon' => 'bi-cash-register', 'href' => '/modules/restaurant/cashier.php', 'active' => ['/modules/restaurant/cashier.php'], 'permission' => 'restaurant_cashier'],
                ],
            ],
            [
                'label' => 'Setup & Reporting',
                'icon' => 'bi-sliders',
                'children' => [
                    ['label' => 'Tables Setup', 'icon' => 'bi-layout-wtf', 'href' => '/modules/restaurant/restaurant_tables.php', 'active' => ['/modules/restaurant/restaurant_tables.php'], 'permission' => 'restaurant_tables'],
                    ['label' => 'Menu Setup', 'icon' => 'bi-card-list', 'href' => '/modules/restaurant/menu.php', 'active' => ['/modules/restaurant/menu.php', '/modules/restaurant/restaurant_menu.php', '/modules/restaurant/menu_categories.php', '/modules/restaurant/menu_modifiers.php'], 'permission' => 'restaurant_menu'],
                    ['label' => 'Recipes', 'icon' => 'bi-journal-bookmark', 'href' => '/modules/inventory/recipes.php', 'active' => ['/modules/inventory/recipes.php'], 'permission' => 'recipes'],
                    ['label' => 'Recipe Import', 'icon' => 'bi-file-earmark-spreadsheet', 'href' => '/modules/inventory/recipe_import.php', 'active' => ['/modules/inventory/recipe_import.php'], 'permission' => 'recipe_import'],
                    ['label' => 'Recipe Profit', 'icon' => 'bi-graph-up', 'href' => '/modules/inventory/recipe_profit_report.php', 'active' => ['/modules/inventory/recipe_profit_report.php'], 'permission' => 'recipe_profit_report'],
                    ['label' => 'Printer Queue', 'icon' => 'bi-printer', 'href' => '/modules/restaurant/printer_jobs.php', 'active' => ['/modules/restaurant/printer_jobs.php', '/modules/restaurant/restaurant_print_queue.php'], 'permission' => 'restaurant_printers'],
                    ['label' => 'Restaurant Reports', 'icon' => 'bi-bar-chart-line', 'href' => '/modules/restaurant/reports.php', 'active' => ['/modules/restaurant/reports.php'], 'permission' => 'restaurant_reports'],
                ],
            ],
        ],
    ],
    [
        'title' => 'Setups and Admin',
        'active' => ['/modules/agents/', '/modules/masters/properties.php', '/modules/masters/banks.php', '/modules/masters/consultants.php', '/modules/masters/roomtypes.php', '/modules/masters/rooms.php', '/modules/masters/rate_plans.php'],
        'items' => [
            ['label' => 'Properties', 'icon' => 'bi-buildings', 'href' => '/modules/masters/properties.php', 'active' => ['/modules/masters/properties.php'], 'permission' => 'properties'],
            ['label' => 'Bank Details', 'icon' => 'bi-bank', 'href' => '/modules/masters/banks.php', 'active' => ['/modules/masters/banks.php'], 'permission' => 'banks'],
            ['label' => 'POS Machines', 'icon' => 'bi-credit-card-2-front', 'href' => '/modules/masters/pos_machines.php', 'active' => ['/modules/masters/pos_machines.php'], 'permission' => 'pos_machines'],
            ['label' => 'Agents', 'icon' => 'bi-people', 'href' => '/modules/agents/agents.php', 'active' => ['/modules/agents/'], 'permission' => 'agents'],
            ['label' => 'Consultants', 'icon' => 'bi-person-badge', 'href' => '/modules/masters/consultants.php', 'active' => ['/modules/masters/consultants.php'], 'permission' => 'consultants'],
            ['label' => 'Room Types', 'icon' => 'bi-grid', 'href' => '/modules/masters/roomtypes.php', 'active' => ['/modules/masters/roomtypes.php'], 'permission' => 'roomtypes'],
            ['label' => 'Rooms', 'icon' => 'bi-door-open', 'href' => '/modules/masters/rooms.php', 'active' => ['/modules/masters/rooms.php'], 'permission' => 'rooms'],
            ['label' => 'Rates Contracts', 'icon' => 'bi-tags', 'href' => '/modules/masters/rate_contracts.php', 'active' => ['/modules/masters/rate_contracts.php'], 'permission' => 'rate_plans'],
            ['label' => 'Rates', 'icon' => 'bi-tags', 'href' => '/modules/masters/rate_plans.php', 'active' => ['/modules/masters/rate_plans.php'], 'permission' => 'rate_plans'],
            ['label' => 'Extra Services', 'icon' => 'bi-bag-plus', 'href' => '/modules/services/services.php', 'active' => ['/modules/services/'], 'permission' => 'services'],
        ],
    ],
    [
        'title' => 'Finance & Control',
        'active' => ['/modules/payments/', '/modules/reports/'],
        'items' => [
            ['label' => 'Currencies', 'icon' => 'bi-currency-exchange', 'href' => '/modules/payments/rate_monitoring_dashboard.php', 'active' => ['/modules/payments/rate_monitoring_dashboard.php'], 'permission' => 'exchange_rates'],
            ['label' => 'Audit Trail', 'icon' => 'bi-shield-check', 'href' => '/modules/payments/audit_log.php', 'active' => ['/modules/payments/audit_log.php'], 'permission' => 'audit_log'],
            ['label' => 'Payments & Fiscalization', 'icon' => 'bi-shield-check', 'href' => '/modules/payments/accounting.php', 'active' => ['/modules/payments/accounting.php'], 'permission' => 'audit_log'],           
            ['label' => 'Customer Statement', 'icon' => 'bi-shield-check', 'href' => '/modules/payments/agent_statement.php', 'active' => ['/modules/payments/agent_statement.php'], 'permission' => 'audit_log'],           
            ['label' => 'Restaurant Cashup', 'icon' => 'bi-shield-check', 'href' => '/modules/restaurant/restaurant_cashup.php', 'active' => ['/modules/restaurant/restaurant_cashup.php'], 'permission' => 'audit_log'],
            ['label' => 'Reception Cashup', 'icon' => 'bi-shield-check', 'href' => '/modules/restaurant/spa_curios_cashup.php', 'active' => ['/modules/restaurant/spa_curios_cashup.php'], 'permission' => 'audit_log'],            
            ['label' => 'Rate Revenue Forecast', 'icon' => 'bi-graph-up', 'href' => '/modules/payments/rate_revenue_forecast.php', 'active' => ['/modules/payments/rate_revenue_forecast.php'], 'permission' => 'rate_revenue_forecast'],
            ['label' => 'Management Dashboard', 'icon' => 'bi-pie-chart', 'href' => '/modules/payments/management_dashboard.php', 'active' => ['/modules/payments/management_dashboard.php'], 'permission' => 'management_dashboard'],
        ],
    ],
    [
        'title' => 'Reports',
        'active' => ['/modules/reports/'],
        'items' => [
            ['label' => 'Reports Dashboard', 'icon' => 'bi-grid-1x2', 'href' => '/modules/reports/index.php', 'active' => ['/modules/reports/index.php', '/modules/reports/reports_index.php'], 'permission' => 'reports'],
            ['label' => 'Executive Dashboard', 'icon' => 'bi-stars', 'href' => '/modules/reports/executive_dashboard.php', 'active' => ['/modules/reports/executive_dashboard.php'], 'permission' => 'executive_dashboard'],
            ['label' => 'Alerts', 'icon' => 'bi-shield-exclamation', 'href' => '/modules/reports/alerts.php', 'active' => ['/modules/reports/alerts.php'], 'permission' => 'alerts', 'class' => 'nav-link-alerts', 'badge_id' => 'alertsCount'],
            ['label' => 'Daily Manager', 'icon' => 'bi-moon-stars', 'href' => '/modules/reports/daily_manager_report.php', 'active' => ['/modules/reports/daily_manager_report.php'], 'permission' => 'daily_manager_report'],
            ['label' => 'Revenue Report', 'icon' => 'bi-graph-up-arrow', 'href' => '/modules/reports/revenue_report.php', 'active' => ['/modules/reports/revenue_report.php'], 'permission' => 'revenue_report'],
            ['label' => 'Fast Food Report', 'icon' => 'bi-graph-up-arrow', 'href' => '/modules/reports/fast_food_tax_schedule.php', 'active' => ['/modules/reports/fast_food_tax_schedule.php'], 'permission' => 'revenue_report'],
            ['label' => 'Payments Report', 'icon' => 'bi-cash-coin', 'href' => '/modules/reports/payments_report.php', 'active' => ['/modules/reports/payments_report.php'], 'permission' => 'payments_report'],
            ['label' => 'Outstanding', 'icon' => 'bi-wallet2', 'href' => '/modules/reports/outstanding_report.php', 'active' => ['/modules/reports/outstanding_report.php'], 'permission' => 'outstanding_report'],
            ['label' => 'Occupancy', 'icon' => 'bi-calendar3', 'href' => '/modules/reports/occupancy_report.php', 'active' => ['/modules/reports/occupancy_report.php'], 'permission' => 'occupancy_report'],
            ['label' => 'ADR / RevPAR', 'icon' => 'bi-speedometer2', 'href' => '/modules/reports/adr_revpar_report.php', 'active' => ['/modules/reports/adr_revpar_report.php'], 'permission' => 'adr_revpar_report'],
            ['label' => 'Agent Production', 'icon' => 'bi-person-badge', 'href' => '/modules/reports/agent_production_report.php', 'active' => ['/modules/reports/agent_production_report.php'], 'permission' => 'agent_production_report'],
            ['label' => 'Extras Report', 'icon' => 'bi-bag-plus', 'href' => '/modules/reports/extras_report.php', 'active' => ['/modules/reports/extras_report.php'], 'permission' => 'extras_report'],
        ],
    ],
    [
        'title' => 'Channel Manager',
        'active' => ['/modules/channel_manager/', '/rooms/modules/channel_manager/'],
        'items' => [
            ['label' => 'Channel Dashboard', 'icon' => 'bi-broadcast', 'href' => '/modules/channel_manager/channel_manager_dashboard.php', 'active' => ['/modules/channel_manager/channel_manager_dashboard.php', '/modules/channel_manager/'], 'permission' => 'channel_manager'],
            ['label' => 'Connections', 'icon' => 'bi-plug', 'href' => '/modules/channel_manager/channel_settings.php', 'active' => ['/modules/channel_manager/channel_settings.php'], 'permission' => 'channel_settings'],
            ['label' => 'Room / Rate Mapping', 'icon' => 'bi-diagram-3', 'href' => '/modules/channel_manager/channel_mapping.php', 'active' => ['/modules/channel_manager/channel_mapping.php'], 'permission' => 'channel_mapping'],
            ['label' => 'Push Availability', 'icon' => 'bi-calendar-check', 'href' => '/modules/channel_manager/channel_push_availability.php', 'active' => ['/modules/channel_manager/channel_push_availability.php'], 'permission' => 'channel_push_availability'],
            ['label' => 'Push Rates', 'icon' => 'bi-tags', 'href' => '/modules/channel_manager/channel_push_rates.php', 'active' => ['/modules/channel_manager/channel_push_rates.php'], 'permission' => 'channel_push_rates'],
            ['label' => 'Pull Bookings', 'icon' => 'bi-cloud-download', 'href' => '/modules/channel_manager/channel_pull_bookings.php', 'active' => ['/modules/channel_manager/channel_pull_bookings.php'], 'permission' => 'channel_pull_bookings'],
            ['label' => 'Sync Log', 'icon' => 'bi-clock-history', 'href' => '/modules/channel_manager/channel_sync_log.php', 'active' => ['/modules/channel_manager/channel_sync_log.php'], 'permission' => 'channel_sync_log'],
        ],
    ],
    [
        'title' => 'Reservation Setup',
        'active' => [
            '/modules/reservations/booking_sources.php',
            '/modules/reservations/booking_statuses.php',
            '/modules/reservations/payment_statuses.php',
            '/modules/reservations/payment_due_types.php',
            '/modules/reservations/booking_color_rules.php',
        ],
        'items' => [
            ['label' => 'Booking Sources', 'icon' => 'bi-bookmark-plus', 'href' => '/modules/reservations/booking_sources.php', 'active' => ['/modules/reservations/booking_sources.php'], 'permission' => 'booking_sources'],
            ['label' => 'Booking Statuses', 'icon' => 'bi-flag', 'href' => '/modules/reservations/booking_statuses.php', 'active' => ['/modules/reservations/booking_statuses.php'], 'permission' => 'booking_statuses'],
            ['label' => 'Payment Statuses', 'icon' => 'bi-credit-card', 'href' => '/modules/reservations/payment_statuses.php', 'active' => ['/modules/reservations/payment_statuses.php'], 'permission' => 'payment_statuses'],
            ['label' => 'Payment Due Types', 'icon' => 'bi-calendar2-check', 'href' => '/modules/reservations/payment_due_types.php', 'active' => ['/modules/reservations/payment_due_types.php'], 'permission' => 'payment_due_types'],
            ['label' => 'Booking Color Rules', 'icon' => 'bi-palette', 'href' => '/modules/reservations/booking_color_rules.php', 'active' => ['/modules/reservations/booking_color_rules.php'], 'permission' => 'booking_color_rules'],
        ],
    ],
    [
        'title' => 'Configuration',
        'active' => ['/modules/settings/', '/modules/settings/role_permissions.php'],
        'items' => [
            ['label' => 'Settings', 'icon' => 'bi-sliders', 'href' => '/modules/settings/lodge_settings.php', 'active' => ['/modules/settings/lodge_settings.php'], 'permission' => 'settings'],
            ['label' => 'Users', 'icon' => 'bi-people', 'href' => '/modules/settings/users.php', 'active' => ['/modules/settings/users.php'], 'permission' => 'users'],
            ['label' => 'Manager Pins', 'icon' => 'bi-key', 'href' => '/modules/settings/manager_pins.php', 'active' => ['/modules/settings/manager_pins.php'], 'permission' => 'manager_pins'],
            ['label' => 'Role Permissions', 'icon' => 'bi-shield-lock', 'href' => '/modules/settings/role_permissions.php', 'active' => ['/modules/settings/role_permissions.php'], 'permission' => 'role_permissions'],
        ],
    ],
];
?>

<aside class="sidebar enterprise-sidebar" id="enterpriseSidebar">
    <div class="sidebar-brand">
        <button id="sidebarToggle"
                type="button"
                class="sidebar-toggle-btn"
                title="Expand / collapse menu"
                aria-label="Expand / collapse menu">
            <i class="bi bi-list"></i>
        </button>
        <div class="brand-badge">
            <i class="bi bi-buildings"></i>
        </div>
        <div class="brand-copy">
            <div class="brand-name"><?php echo ss_e($appLabel); ?></div>
            <div class="brand-sub">Rooms • Front Office • Restaurant</div>
        </div>
    </div>

    <div class="sidebar-scroll">
        <?php foreach ($groups as $group): ?>
            <?php ss_render_group($group['title'], $group['items'], $group['active']); ?>
        <?php endforeach; ?>
    </div>


</aside>

<style>
.enterprise-sidebar{
    width: 290px;
    background: linear-gradient(180deg, #0f172a 0%, #111827 100%);
    color: #e5e7eb;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    border-right: 1px solid rgba(255,255,255,.06);
    box-shadow: 8px 0 30px rgba(2, 6, 23, .16);
}

.enterprise-sidebar .sidebar-brand{
    display: flex;
    align-items: center;
    gap: 14px;
    padding: 22px 20px 18px;
    border-bottom: 1px solid rgba(255,255,255,.06);
}

.enterprise-sidebar .brand-badge{
    width: 46px;
    height: 46px;
    border-radius: 14px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
    color: #fff;
    font-size: 20px;
    box-shadow: 0 10px 24px rgba(37, 99, 235, .28);
    flex: 0 0 auto;
}

.enterprise-sidebar .brand-copy{
    min-width: 0;
}

.enterprise-sidebar .brand-name{
    font-size: 1.05rem;
    font-weight: 800;
    color: #fff;
    line-height: 1.15;
}

.enterprise-sidebar .brand-sub{
    font-size: .78rem;
    color: rgba(255,255,255,.6);
    margin-top: 3px;
    letter-spacing: .02em;
}

.enterprise-sidebar .sidebar-scroll{
    flex: 1 1 auto;
    overflow-y: auto;
    padding: 16px 14px 20px;
}

.enterprise-sidebar .sidebar-group + .sidebar-group{
    margin-top: 12px;
}

.enterprise-sidebar .sidebar-group{
    border-radius: 16px;
    overflow: hidden;
}

.enterprise-sidebar .sidebar-group-toggle{
    width: 100%;
    border: 0;
    background: transparent;
    color: inherit;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 8px 8px;
    cursor: pointer;
}

.enterprise-sidebar .sidebar-section-title{
    font-size: .72rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .08em;
    color: rgba(255,255,255,.45);
    padding: 0 2px;
    margin: 0;
}

.enterprise-sidebar .group-chevron{
    color: rgba(255,255,255,.42);
    font-size: .8rem;
    transition: transform .2s ease;
}

.enterprise-sidebar .sidebar-group.is-open .group-chevron{
    transform: rotate(180deg);
}

.enterprise-sidebar .sidebar-group-body{
    max-height: 0;
    overflow: hidden;
    transition: max-height .25s ease;
}

.enterprise-sidebar .sidebar-group.is-open .sidebar-group-body{
    max-height: 1400px;
}

.enterprise-sidebar .sidebar-nav{
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.enterprise-sidebar .nav-link{
    position: relative;
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 11px 12px;
    border-radius: 14px;
    text-decoration: none;
    color: rgba(255,255,255,.82);
    transition: all .18s ease;
    font-weight: 600;
}

.enterprise-sidebar .nav-link:hover{
    background: rgba(255,255,255,.06);
    color: #fff;
    transform: translateX(2px);
}

.enterprise-sidebar .nav-link.active{
    background: linear-gradient(135deg, rgba(37,99,235,.24) 0%, rgba(59,130,246,.16) 100%);
    color: #fff;
    box-shadow: inset 0 0 0 1px rgba(96,165,250,.22);
}

.enterprise-sidebar .nav-link.active::before{
    content: '';
    position: absolute;
    left: -6px;
    top: 8px;
    bottom: 8px;
    width: 4px;
    border-radius: 999px;
    background: linear-gradient(180deg, #60a5fa 0%, #2563eb 100%);
}

.enterprise-sidebar .nav-icon{
    width: 34px;
    height: 34px;
    border-radius: 11px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: rgba(255,255,255,.06);
    color: #cbd5e1;
    font-size: 1rem;
    flex: 0 0 auto;
    transition: all .18s ease;
}

.enterprise-sidebar .nav-link:hover .nav-icon,
.enterprise-sidebar .nav-link.active .nav-icon{
    background: rgba(255,255,255,.12);
    color: #fff;
}

.enterprise-sidebar .nav-text{
    min-width: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.enterprise-sidebar .nav-link-alerts{
    justify-content: space-between;
}


/* Nested module submenus */
.enterprise-sidebar .sidebar-subgroup{
    margin:2px 0 5px;
    border-radius:13px;
    overflow:hidden;
    background:rgba(255,255,255,.018);
    border:1px solid rgba(255,255,255,.045);
}
.enterprise-sidebar .sidebar-subgroup-toggle{
    width:100%;
    border:0;
    background:transparent;
    color:rgba(255,255,255,.84);
    display:flex;
    align-items:center;
    gap:12px;
    padding:9px 10px;
    cursor:pointer;
    text-align:left;
    font-weight:750;
}
.enterprise-sidebar .sidebar-subgroup-toggle:hover{
    background:rgba(255,255,255,.055);
    color:#fff;
}
.enterprise-sidebar .sidebar-subgroup-toggle .nav-icon{
    width:31px;
    height:31px;
    border-radius:9px;
    font-size:.92rem;
}
.enterprise-sidebar .subgroup-chevron{
    margin-left:auto;
    color:rgba(255,255,255,.42);
    font-size:.72rem;
    transition:transform .2s ease;
}
.enterprise-sidebar .sidebar-subgroup.is-open .subgroup-chevron{
    transform:rotate(90deg);
}
.enterprise-sidebar .sidebar-subgroup-body{
    display:none;
    padding:2px 6px 7px 15px;
}
.enterprise-sidebar .sidebar-subgroup.is-open .sidebar-subgroup-body{
    display:flex;
    flex-direction:column;
    gap:4px;
}
.enterprise-sidebar .sidebar-subgroup-body .nav-link{
    min-height:39px;
    padding:7px 9px;
    border-radius:10px;
    font-size:.84rem;
}
.enterprise-sidebar .sidebar-subgroup-body .nav-icon{
    width:29px;
    height:29px;
    border-radius:9px;
    font-size:.84rem;
}
.enterprise-sidebar .sidebar-subgroup-body .nav-link.active::before{
    left:-10px;
    top:7px;
    bottom:7px;
    width:3px;
}
body.sidebar-collapsed .enterprise-sidebar .sidebar-subgroup{
    border:0;
    background:transparent;
    overflow:visible;
}
body.sidebar-collapsed .enterprise-sidebar .sidebar-subgroup-toggle{
    justify-content:center;
    padding:8px 0;
}
body.sidebar-collapsed .enterprise-sidebar .sidebar-subgroup-toggle .nav-text,
body.sidebar-collapsed .enterprise-sidebar .subgroup-chevron{
    display:none;
}
body.sidebar-collapsed .enterprise-sidebar .sidebar-subgroup-body{
    display:none!important;
}

/* =========================================================
   BOOKING CONTROL CENTRE — flagship "command" nav item.
   Deliberately louder than the rest of the menu: amber accent,
   gradient chip icon, glow, HUB tag and a soft pulse so it reads
   as the primary jump-off point for booking operations.
   ========================================================= */
.enterprise-sidebar .nav-link-command{
    background: linear-gradient(135deg, rgba(245,158,11,.16) 0%, rgba(251,191,36,.07) 100%);
    box-shadow: inset 0 0 0 1px rgba(251,191,36,.30);
    color: #fff;
    font-weight: 800;
    letter-spacing: .01em;
    margin-bottom: 8px;
}

.enterprise-sidebar .nav-link-command:hover{
    background: linear-gradient(135deg, rgba(245,158,11,.28) 0%, rgba(251,191,36,.14) 100%);
    box-shadow: inset 0 0 0 1px rgba(251,191,36,.55), 0 6px 18px rgba(245,158,11,.22);
    transform: translateX(3px);
}

.enterprise-sidebar .nav-link-command .nav-icon{
    background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%);
    color: #111827;
    box-shadow: 0 4px 12px rgba(245,158,11,.45);
    font-size: 1.08rem;
}

.enterprise-sidebar .nav-link-command:hover .nav-icon{
    background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
    color: #111827;
    transform: scale(1.06);
}

/* Active state: strong amber rail instead of the standard blue. */
.enterprise-sidebar .nav-link-command.active{
    background: linear-gradient(135deg, rgba(245,158,11,.34) 0%, rgba(251,191,36,.18) 100%);
    box-shadow: inset 0 0 0 1px rgba(251,191,36,.65), 0 6px 20px rgba(245,158,11,.25);
}

.enterprise-sidebar .nav-link-command.active::before{
    background: linear-gradient(180deg, #fbbf24 0%, #f59e0b 100%);
    width: 5px;
}

.enterprise-sidebar .nav-link-command.active .nav-icon{
    background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
    color: #111827;
}

/* HUB tag chip */
.enterprise-sidebar .nav-tag{
    margin-left: auto;
    font-size: .58rem;
    font-weight: 900;
    letter-spacing: .10em;
    padding: 3px 7px;
    border-radius: 999px;
    background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%);
    color: #111827;
    flex: 0 0 auto;
    box-shadow: 0 2px 6px rgba(245,158,11,.4);
}

/* Gentle attention pulse (respects reduced-motion). */
@keyframes bccPulse{
    0%,100%{ box-shadow: inset 0 0 0 1px rgba(251,191,36,.30); }
    50%    { box-shadow: inset 0 0 0 1px rgba(251,191,36,.62), 0 0 14px rgba(245,158,11,.28); }
}
.enterprise-sidebar .nav-link-command:not(.active){
    animation: bccPulse 3.2s ease-in-out infinite;
}
@media (prefers-reduced-motion: reduce){
    .enterprise-sidebar .nav-link-command:not(.active){ animation: none; }
}

/* Collapsed sidebar: keep the chip loud, hide the tag. */
body.sidebar-collapsed .enterprise-sidebar .nav-link-command{
    animation: none;
    background: transparent;
    box-shadow: none;
}
body.sidebar-collapsed .enterprise-sidebar .nav-tag{
    display: none;
}
body.sidebar-collapsed .enterprise-sidebar .nav-link-command .nav-icon{
    box-shadow: 0 0 0 2px rgba(251,191,36,.55), 0 4px 12px rgba(245,158,11,.45);
}

.enterprise-sidebar .nav-left{
    display: inline-flex;
    align-items: center;
    gap: 12px;
    min-width: 0;
}

.enterprise-sidebar .alerts-badge{
    min-width: 24px;
    height: 22px;
    border-radius: 999px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: .72rem;
    font-weight: 800;
    box-shadow: 0 0 0 1px rgba(255,255,255,.18);
}

.enterprise-sidebar .alerts-badge.is-hidden{
    display: none;
}

.enterprise-sidebar .sidebar-footer{
    padding: 14px;
    border-top: 1px solid rgba(255,255,255,.06);
}

.enterprise-sidebar .sidebar-footer-card{
    border-radius: 18px;
    padding: 14px;
    background: linear-gradient(135deg, rgba(37,99,235,.22) 0%, rgba(15,23,42,.44) 100%);
    border: 1px solid rgba(255,255,255,.08);
}

.enterprise-sidebar .footer-user-top{
    display: flex;
    align-items: center;
    gap: 12px;
}

.enterprise-sidebar .footer-user-avatar{
    width: 42px;
    height: 42px;
    border-radius: 14px;
    background: rgba(255,255,255,.12);
    display: inline-flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 1.2rem;
    flex: 0 0 auto;
}


/* =========================================
   ENTERPRISE LEFT COLLAPSE / WIDE SCREEN
========================================= */

.sidebar-toggle-btn{
    position:absolute;
    right:10px;
    top:10px;
    width:34px;
    height:34px;
    border:0;
    border-radius:10px;
    background:rgba(255,255,255,.09);
    color:#fff;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    cursor:pointer;
    z-index:5;
    transition:all .18s ease;
}

.sidebar-toggle-btn:hover{
    background:rgba(255,255,255,.16);
    transform:scale(1.04);
}

.enterprise-sidebar{
    position:relative;
    transition:width .25s ease, transform .25s ease;
}

body.sidebar-collapsed .enterprise-sidebar{
    width:72px !important;
    min-width:72px !important;
}

body.sidebar-collapsed .enterprise-sidebar .sidebar-brand{
    justify-content:center;
    padding:54px 10px 14px;
}

body.sidebar-collapsed .enterprise-sidebar .brand-copy,
body.sidebar-collapsed .enterprise-sidebar .sidebar-section-title,
body.sidebar-collapsed .enterprise-sidebar .nav-text,
body.sidebar-collapsed .enterprise-sidebar .nav-tag,
body.sidebar-collapsed .enterprise-sidebar .group-chevron,
body.sidebar-collapsed .enterprise-sidebar .alerts-badge{
    display:none !important;
}

body.sidebar-collapsed .enterprise-sidebar .sidebar-scroll{
    padding:12px 8px 20px;
    overflow-x:hidden;
}

body.sidebar-collapsed .enterprise-sidebar .sidebar-group{
    margin-top:8px;
}

body.sidebar-collapsed .enterprise-sidebar .sidebar-group-toggle{
    justify-content:center;
    padding:6px 0;
    min-height:4px;
}

body.sidebar-collapsed .enterprise-sidebar .sidebar-group-body{
    max-height:1400px !important;
    display:block !important;
}

body.sidebar-collapsed .enterprise-sidebar .sidebar-nav{
    gap:8px;
}

body.sidebar-collapsed .enterprise-sidebar .nav-link{
    justify-content:center;
    padding:10px 0;
    gap:0;
}

body.sidebar-collapsed .enterprise-sidebar .nav-link:hover{
    transform:none;
}

body.sidebar-collapsed .enterprise-sidebar .nav-link.active::before{
    left:-4px;
}

body.sidebar-collapsed .enterprise-sidebar .nav-icon{
    margin:0;
}

body.sidebar-collapsed .enterprise-sidebar .brand-badge{
    width:42px;
    height:42px;
}

/* Common content wrappers widen automatically when sidebar is collapsed.
   If your layout uses a different wrapper, add it here. */
.main-content,
.content-wrapper,
.page-content,
.app-content,
.dashboard-content,
main{
    transition:margin-left .25s ease, width .25s ease;
}

body.sidebar-collapsed .main-content,
body.sidebar-collapsed .content-wrapper,
body.sidebar-collapsed .page-content,
body.sidebar-collapsed .app-content,
body.sidebar-collapsed .dashboard-content{
    margin-left:72px !important;
}

body.sidebar-collapsed main{
    max-width:none;
}

/* Optional full hide mode. Add body.sidebar-hidden if you want it totally off-screen. */
body.sidebar-hidden .enterprise-sidebar{
    transform:translateX(-100%);
    width:0 !important;
    min-width:0 !important;
    overflow:hidden;
}

body.sidebar-hidden .main-content,
body.sidebar-hidden .content-wrapper,
body.sidebar-hidden .page-content,
body.sidebar-hidden .app-content,
body.sidebar-hidden .dashboard-content{
    margin-left:0 !important;
}

@media (max-width: 991.98px){
    .enterprise-sidebar{
        width: 100%;
        min-height: auto;
        border-right: 0;
        border-bottom: 1px solid rgba(255,255,255,.06);
    }

    .enterprise-sidebar .sidebar-scroll{
        max-height: 60vh;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var OPEN_GROUP_KEY = 'enterprise_sidebar_open_group';
    var COLLAPSE_KEY   = 'enterprise_sidebar_collapsed';

    var sidebar = document.getElementById('enterpriseSidebar');
    if (!sidebar) return;

    var groups  = sidebar.querySelectorAll('.sidebar-group');
    var toggles = sidebar.querySelectorAll('[data-group-toggle]');
    var toggleBtn = document.getElementById('sidebarToggle');

    function getGroupTitle(group) {
        var title = group ? group.querySelector('.sidebar-section-title') : null;
        return title ? title.textContent.trim() : '';
    }

    function closeAllGroups(exceptGroup) {
        groups.forEach(function (group) {
            if (exceptGroup && group === exceptGroup) return;
            group.classList.remove('is-open');
        });
    }

    function openGroup(group, remember) {
        if (!group) return;

        closeAllGroups(group);
        group.classList.add('is-open');

        if (remember !== false) {
            var title = getGroupTitle(group);
            if (title) localStorage.setItem(OPEN_GROUP_KEY, title);
        }
    }

    function closeGroup(group) {
        if (!group) return;

        group.classList.remove('is-open');

        var title = getGroupTitle(group);
        if (title && localStorage.getItem(OPEN_GROUP_KEY) === title) {
            localStorage.removeItem(OPEN_GROUP_KEY);
        }
    }

    function setCollapsed(collapsed, remember) {
        document.body.classList.toggle('sidebar-collapsed', collapsed);

        if (remember !== false) {
            localStorage.setItem(COLLAPSE_KEY, collapsed ? '1' : '0');
        }

        if (toggleBtn) {
            toggleBtn.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
            toggleBtn.title = collapsed ? 'Expand menu' : 'Collapse menu';

            var icon = toggleBtn.querySelector('i');
            if (icon) {
                icon.className = collapsed ? 'bi bi-layout-sidebar-inset' : 'bi bi-list';
            }
        }
    }

    /*
     * Collapsed by default.
     * - First visit: collapsed.
     * - User expands: saved as 0.
     * - User collapses: saved as 1.
     */
    setCollapsed(localStorage.getItem(COLLAPSE_KEY) !== '0', false);

    if (toggleBtn) {
        toggleBtn.addEventListener('click', function (event) {
            event.preventDefault();
            event.stopPropagation();

            setCollapsed(!document.body.classList.contains('sidebar-collapsed'), true);
        });
    }

    // Support any external header button too.
    document.querySelectorAll('[data-sidebar-toggle], .sidebar-toggle').forEach(function (btn) {
        if (btn.id === 'sidebarToggle') return;

        btn.addEventListener('click', function (event) {
            event.preventDefault();
            setCollapsed(!document.body.classList.contains('sidebar-collapsed'), true);
        });
    });

    // Enterprise accordion: only one group open at a time.
    toggles.forEach(function (toggle) {
        toggle.addEventListener('click', function () {
            var group = this.closest('.sidebar-group');
            if (!group) return;

            // If collapsed and user clicks section title area, expand first.
            if (document.body.classList.contains('sidebar-collapsed')) {
                setCollapsed(false, true);
            }

            if (group.classList.contains('is-open')) {
                closeGroup(group);
            } else {
                openGroup(group, true);
            }
        });
    });

    // Nested submenus inside modules such as Inventory.
    sidebar.querySelectorAll('[data-subgroup-toggle]').forEach(function (toggle) {
        toggle.addEventListener('click', function (event) {
            event.preventDefault();
            event.stopPropagation();

            var subgroup = this.closest('.sidebar-subgroup');
            if (!subgroup) return;

            if (document.body.classList.contains('sidebar-collapsed')) {
                setCollapsed(false, true);
            }

            var willOpen = !subgroup.classList.contains('is-open');
            var parentGroup = subgroup.closest('.sidebar-group');

            if (parentGroup) {
                parentGroup.querySelectorAll('.sidebar-subgroup.is-open').forEach(function (other) {
                    if (other !== subgroup) {
                        other.classList.remove('is-open');
                        var otherToggle = other.querySelector('[data-subgroup-toggle]');
                        if (otherToggle) otherToggle.setAttribute('aria-expanded', 'false');
                    }
                });
            }

            subgroup.classList.toggle('is-open', willOpen);
            this.setAttribute('aria-expanded', willOpen ? 'true' : 'false');
        });
    });

    // Open the group containing the active link.
    var activeLink = sidebar.querySelector('.nav-link.active');

    if (activeLink) {
        openGroup(activeLink.closest('.sidebar-group'), false);

        var activeSubgroup = activeLink.closest('.sidebar-subgroup');
        if (activeSubgroup) {
            activeSubgroup.classList.add('is-open');
            var activeSubToggle = activeSubgroup.querySelector('[data-subgroup-toggle]');
            if (activeSubToggle) activeSubToggle.setAttribute('aria-expanded', 'true');
        }
    } else {
        var savedTitle = localStorage.getItem(OPEN_GROUP_KEY);

        if (savedTitle) {
            groups.forEach(function (group) {
                if (getGroupTitle(group) === savedTitle) {
                    openGroup(group, false);
                }
            });
        }
    }

    // On mobile, close/hide the whole sidebar after navigation.
    sidebar.querySelectorAll('.nav-link').forEach(function (link) {
        link.addEventListener('click', function () {
            if (window.innerWidth < 992) {
                document.body.classList.remove('sidebar-open', 'sidebar-expanded', 'menu-open');

                sidebar.classList.remove('show', 'is-open', 'open', 'active');

                var overlay = document.querySelector('.sidebar-backdrop, .offcanvas-backdrop, .menu-backdrop');
                if (overlay && overlay.parentNode) {
                    overlay.parentNode.removeChild(overlay);
                }
            }
        });
    });

    function loadAlertsCount() {
        var badge = document.getElementById('alertsCount');
        if (!badge) return;

        fetch('<?php echo BASE_URL; ?>/modules/reports/alerts_count.php', {
            credentials: 'same-origin',
            cache: 'no-store'
        })
            .then(function (res) {
                return res.json();
            })
            .then(function (data) {
                if (!data || !data.ok) return;

                var total    = parseInt(data.total || 0, 10);
                var critical = parseInt(data.critical || 0, 10);
                var warning  = parseInt(data.warning || 0, 10);

                badge.textContent = total;

                badge.classList.remove(
                    'bg-danger',
                    'bg-warning',
                    'bg-success',
                    'bg-secondary',
                    'is-hidden'
                );

                if (total <= 0) {
                    badge.classList.add('bg-success');
                    badge.textContent = '0';
                } else if (critical > 0) {
                    badge.classList.add('bg-danger');
                } else if (warning > 0) {
                    badge.classList.add('bg-warning');
                } else {
                    badge.classList.add('bg-secondary');
                }
            })
            .catch(function () {
                var badge = document.getElementById('alertsCount');
                if (!badge) return;

                badge.classList.remove('bg-danger', 'bg-warning', 'bg-success');
                badge.classList.add('bg-secondary');
                badge.textContent = '!';
            });
    }

    loadAlertsCount();
    setInterval(loadAlertsCount, 30000);
});
</script>
