<!doctype html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= e($title ?? config('app.name')) ?></title>
    <link rel="icon" type="image/png" href="<?= e(asset('img/veltrix-favicon.png')) ?>">
    <link rel="apple-touch-icon" href="<?= e(asset('img/veltrix-favicon.png')) ?>">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css" rel="stylesheet">
    <link rel="stylesheet" href="<?= e(asset('css/app.css')) ?>">
</head>
<body class="vx-body">
<?php
$user = auth_user();
$requestPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$basePath = parse_url((string) config('app.url', ''), PHP_URL_PATH) ?: '';
$basePath = rtrim($basePath, '/');
$cashPendingTransfers = pending_cash_transfers_count();
$cashPendingPollingUrl = has_permission('caja.ver') ? url('caja/traspasos/pending-count') : '';

if ($basePath !== '' && $basePath !== '/' && str_starts_with($requestPath, $basePath)) {
    $requestPath = substr($requestPath, strlen($basePath)) ?: '/';
}

$requestPath = '/' . ltrim($requestPath, '/');

$isSuperadmin = is_superadmin();
$superadminSections = [
    'resumen',
    'wompi',
    'correo',
    'whatsapp_meta',
    'whatsapp_meta_templates',
    'whatsapp_manychat',
    'notificaciones',
    'ai',
    'reporte_openia',
    'checkout',
    'cobranza',
    'planes',
    'empresas',
    'suscripciones',
    'sla',
    'soporte',
    'pagos',
];
$superadminSection = strtolower(trim((string) ($_GET['seccion'] ?? 'resumen')));
if (!in_array($superadminSection, $superadminSections, true)) {
    $superadminSection = 'resumen';
}
$showTopbarMetaTemplateLink = $isSuperadmin
    && str_starts_with($requestPath, '/superadmin')
    && $superadminSection === 'whatsapp_meta';

$errorFlash = trim((string) (flash('error') ?? ''));
$successFlash = trim((string) (flash('success') ?? ''));
$successAction = flash('success_action');
$successActionsRaw = flash('success_actions');
$posCambio = trim((string) (flash('pos_cambio') ?? ''));
$flashActions = [];

if ($successFlash !== '') {
    if (is_array($successAction)) {
        $label = trim((string) ($successAction['label'] ?? ''));
        $url = trim((string) ($successAction['url'] ?? ''));
        $target = trim((string) ($successAction['target'] ?? ''));
        if ($label !== '' && $url !== '') {
            $flashActions[] = [
                'label' => $label,
                'url' => $url,
                'target' => $target,
            ];
        }
    }

    $successActions = is_array($successActionsRaw) ? $successActionsRaw : [];
    foreach ($successActions as $action) {
        if (!is_array($action)) {
            continue;
        }
        $label = trim((string) ($action['label'] ?? ''));
        $url = trim((string) ($action['url'] ?? ''));
        $target = trim((string) ($action['target'] ?? ''));
        if ($label === '' || $url === '') {
            continue;
        }
        $flashActions[] = [
            'label' => $label,
            'url' => $url,
            'target' => $target,
        ];
    }
}

$flashPayload = [
    'error' => $errorFlash,
    'success' => $successFlash,
    'actions' => $flashActions,
    'pos_cambio' => $posCambio,
];
$topbarActions = is_array($topbar_actions ?? null) ? $topbar_actions : [];
$showCompanySwitcher = (bool) ($show_company_switcher ?? true);
$activeTenantId = (int) (tenant_id() ?? 0);
$stockNotifications = [];
$stockNotificationsCount = 0;
$stockNotificationsStockCount = 0;
$stockNotificationsTicketCount = 0;
$stockNotificationsPollingUrl = '';
$stockNotificationsInventoryUrl = has_permission('inventario.ver') ? url('inventario') : url('dashboard');
$stockNotificationsSupportUrl = url('soporte');
$stockNotificationsScope = $isSuperadmin ? 'superadmin' : 'tenant';
$notificationsMarkReadUrl = url('notificaciones/marcar-leidas');

if (!$isSuperadmin && $activeTenantId > 0) {
    $tenantNotificationsPayload = tenant_notifications_payload(10);
    $stockNotifications = is_array($tenantNotificationsPayload['items'] ?? null) ? $tenantNotificationsPayload['items'] : [];
    $stockNotificationsCount = (int) ($tenantNotificationsPayload['count'] ?? 0);
    $stockNotificationsStockCount = (int) ($tenantNotificationsPayload['count_stock'] ?? 0);
    $stockNotificationsTicketCount = (int) ($tenantNotificationsPayload['count_tickets'] ?? 0);
    $stockNotificationsPollingUrl = url('notificaciones/stock-minimo');
} elseif ($isSuperadmin) {
    $superadminNotificationsPayload = superadmin_support_notifications_payload(10);
    $stockNotifications = is_array($superadminNotificationsPayload['items'] ?? null) ? $superadminNotificationsPayload['items'] : [];
    $stockNotificationsCount = (int) ($superadminNotificationsPayload['count'] ?? 0);
    $stockNotificationsStockCount = (int) ($superadminNotificationsPayload['count_stock'] ?? 0);
    $stockNotificationsTicketCount = (int) ($superadminNotificationsPayload['count_tickets'] ?? 0);
    $stockNotificationsPollingUrl = url('superadmin/notificaciones/soporte');
    $stockNotificationsInventoryUrl = url('superadmin') . '?seccion=soporte';
    $stockNotificationsSupportUrl = url('superadmin') . '?seccion=soporte';
}

$notificationsPrimaryUrl = $isSuperadmin ? $stockNotificationsSupportUrl : $stockNotificationsInventoryUrl;
$notificationsPrimaryLabel = $isSuperadmin ? 'Ver soporte' : 'Revisar inventario';
$notificationsSecondaryUrl = $isSuperadmin ? '' : $stockNotificationsSupportUrl;
$notificationsSecondaryLabel = 'Ver tickets';

if ($isSuperadmin) {
    $navGroups = [
        [
            'title' => 'General',
            'icon' => 'bx bxs-home',
            'items' => [
                ['label' => 'Superadmin', 'href' => url('superadmin') . '?seccion=resumen', 'match' => '/superadmin', 'icon' => 'bx bxs-crown', 'section' => 'resumen'],
            ],
        ],
        [
            'title' => 'Comercial',
            'icon' => 'bx bxs-briefcase-alt-2',
            'items' => [
                ['label' => 'Planes', 'href' => url('superadmin') . '?seccion=planes', 'match' => '/superadmin', 'icon' => 'bx bxs-package', 'section' => 'planes', 'class' => 'vx-nav-sub'],
                ['label' => 'Empresas', 'href' => url('superadmin') . '?seccion=empresas', 'match' => '/superadmin', 'icon' => 'bx bxs-buildings', 'section' => 'empresas', 'class' => 'vx-nav-sub'],
                ['label' => 'Suscripciones', 'href' => url('superadmin') . '?seccion=suscripciones', 'match' => '/superadmin', 'icon' => 'bx bxs-time-five', 'section' => 'suscripciones', 'class' => 'vx-nav-sub'],
                ['label' => 'Pagos', 'href' => url('superadmin') . '?seccion=pagos', 'match' => '/superadmin', 'icon' => 'bx bxs-wallet', 'section' => 'pagos', 'class' => 'vx-nav-sub'],
                ['label' => 'Checkout fallidos', 'href' => url('superadmin') . '?seccion=checkout', 'match' => '/superadmin', 'icon' => 'bx bxs-receipt', 'section' => 'checkout', 'class' => 'vx-nav-sub'],
                ['label' => 'Cobranza', 'href' => url('superadmin') . '?seccion=cobranza', 'match' => '/superadmin', 'icon' => 'bx bxs-envelope', 'section' => 'cobranza', 'class' => 'vx-nav-sub'],
            ],
        ],
        [
            'title' => 'API e Integraciones',
            'icon' => 'bx bx-link-alt',
            'items' => [
                ['label' => 'Wompi', 'href' => url('superadmin') . '?seccion=wompi', 'match' => '/superadmin', 'icon' => 'bx bxs-credit-card', 'section' => 'wompi', 'class' => 'vx-nav-sub'],
                ['label' => 'Correo electrónico', 'href' => url('superadmin') . '?seccion=correo', 'match' => '/superadmin', 'icon' => 'bx bxs-envelope-open', 'section' => 'correo', 'class' => 'vx-nav-sub'],
                ['label' => 'WhatsApp Meta', 'href' => url('superadmin') . '?seccion=whatsapp_meta', 'match' => '/superadmin', 'icon' => 'bx bxl-whatsapp', 'section' => 'whatsapp_meta', 'class' => 'vx-nav-sub'],
                ['label' => 'Enlazar Meta', 'href' => url('superadmin') . '?seccion=whatsapp_meta_templates', 'match' => '/superadmin', 'icon' => 'bx bx-link-alt', 'section' => 'whatsapp_meta_templates', 'class' => 'vx-nav-sub'],
                ['label' => 'ManyChat', 'href' => url('superadmin') . '?seccion=whatsapp_manychat', 'match' => '/superadmin', 'icon' => 'bx bx-chat', 'section' => 'whatsapp_manychat', 'class' => 'vx-nav-sub'],
                ['label' => 'Notificaciones', 'href' => url('superadmin') . '?seccion=notificaciones', 'match' => '/superadmin', 'icon' => 'bx bxs-bell', 'section' => 'notificaciones', 'class' => 'vx-nav-sub'],
                ['label' => 'Agente IA', 'href' => url('superadmin') . '?seccion=ai', 'match' => '/superadmin', 'icon' => 'bx bx-bot', 'section' => 'ai', 'class' => 'vx-nav-sub'],
            ],
        ],
        [
            'title' => 'Reporte',
            'icon' => 'bx bxs-report',
            'items' => [
                ['label' => 'OpenIA', 'href' => url('superadmin') . '?seccion=reporte_openia', 'match' => '/superadmin', 'icon' => 'bx bx-line-chart', 'section' => 'reporte_openia', 'class' => 'vx-nav-sub'],
            ],
        ],
        [
            'title' => 'Soporte',
            'icon' => 'bx bx-support',
            'items' => [
                ['label' => 'SLA soporte', 'href' => url('superadmin') . '?seccion=sla', 'match' => '/superadmin', 'icon' => 'bx bxs-shield-alt-2', 'section' => 'sla', 'class' => 'vx-nav-sub'],
                ['label' => 'Tickets soporte', 'href' => url('superadmin') . '?seccion=soporte', 'match' => '/superadmin', 'icon' => 'bx bx-help-circle', 'section' => 'soporte', 'class' => 'vx-nav-sub'],
            ],
        ],
    ];
} else {
    $navGroups = [
        [
            'title' => 'Operacion',
            'icon' => 'bx bxs-grid-alt',
            'items' => [
                ['label' => 'Dashboard', 'href' => url('dashboard'), 'match' => '/dashboard', 'icon' => 'bx bxs-grid-alt'],
                ['label' => 'POS', 'href' => url('pos'), 'match' => '/pos', 'icon' => 'bx bxs-cart-add'],
                ['label' => 'Ventas', 'href' => url('ventas'), 'match' => '/ventas', 'icon' => 'bx bxs-receipt'],
                ['label' => 'Caja', 'href' => url('caja'), 'match' => '/caja', 'icon' => 'bx bxs-wallet'],
                ['label' => 'C. Cobrar', 'href' => url('cuentas-cobrar'), 'match' => '/cuentas-cobrar', 'icon' => 'bx bxs-credit-card'],
            ],
        ],
        [
            'title' => 'Inventario',
            'icon' => 'bx bxs-package',
            'items' => [
                ['label' => 'Inventario', 'href' => url('inventario'), 'match' => '/inventario', 'icon' => 'bx bxs-package'],
                ['label' => 'Productos', 'href' => url('productos'), 'match' => '/productos', 'icon' => 'bx bxs-box'],
                ['label' => 'Categorias', 'href' => url('categorias'), 'match' => '/categorias', 'icon' => 'bx bxs-category'],
                ['label' => 'Compras', 'href' => url('compras'), 'match' => '/compras', 'icon' => 'bx bxs-cart-download'],
                ['label' => 'Proveedores', 'href' => url('proveedores'), 'match' => '/proveedores', 'icon' => 'bx bxs-truck'],
            ],
        ],
        [
            'title' => 'Comercial',
            'icon' => 'bx bxs-briefcase-alt-2',
            'items' => [
                ['label' => 'Clientes', 'href' => url('clientes'), 'match' => '/clientes', 'icon' => 'bx bxs-user-detail'],
                ['label' => 'Reportes', 'href' => url('reportes'), 'match' => '/reportes', 'icon' => 'bx bxs-bar-chart-alt-2'],
                ['label' => 'Soporte', 'href' => url('soporte'), 'match' => '/soporte', 'icon' => 'bx bx-support'],
                ['label' => 'Ayuda IA', 'href' => url('ayuda-ia'), 'match' => '/ayuda-ia', 'icon' => 'bx bx-bot'],
            ],
        ],
        [
            'title' => 'Administracion',
            'icon' => 'bx bxs-cog',
            'items' => [
                ['label' => 'Sucursales', 'href' => url('sucursales'), 'match' => '/sucursales', 'icon' => 'bx bxs-store', 'visible' => has_permission('sucursales.ver')],
                ['label' => 'Usuarios', 'href' => url('usuarios'), 'match' => '/usuarios', 'icon' => 'bx bxs-group'],
                ['label' => 'Configuracion', 'href' => url('configuracion'), 'match' => '/configuracion', 'icon' => 'bx bxs-cog', 'visible' => has_permission('configuracion.ver')],
                ['label' => 'Integraciones', 'href' => url('integraciones'), 'match' => '/integraciones', 'icon' => 'bx bx-link-alt', 'visible' => has_permission('configuracion.ver')],
                ['label' => 'Empresa', 'href' => url('empresas/seleccionar'), 'match' => '/empresas', 'icon' => 'bx bxs-buildings'],
            ],
        ],
    ];
}

$preparedGroups = [];
foreach ($navGroups as $group) {
    $groupTitle = trim((string) ($group['title'] ?? ''));
    $groupIcon = trim((string) ($group['icon'] ?? 'bx bxs-layer'));
    $itemsPrepared = [];
    $groupHasActive = false;

    foreach ((array) ($group['items'] ?? []) as $item) {
        if (array_key_exists('visible', $item) && !$item['visible']) {
            continue;
        }

        if (array_key_exists('section', $item)) {
            $isSuperadminRoute = $requestPath === '/superadmin' || str_starts_with($requestPath, '/superadmin/');
            $active = $isSuperadminRoute && $superadminSection === (string) $item['section'];
        } else {
            $active = $requestPath === $item['match'] || str_starts_with($requestPath, $item['match'] . '/');
        }

        $item['_active'] = $active;
        if ($active) {
            $groupHasActive = true;
        }

        $itemsPrepared[] = $item;
    }

    if (empty($itemsPrepared)) {
        continue;
    }

    $preparedGroups[] = [
        'title' => $groupTitle,
        'icon' => $groupIcon,
        'items' => $itemsPrepared,
        'has_active' => $groupHasActive,
    ];
}

$defaultOpenGroupIndex = null;
foreach ($preparedGroups as $groupIndex => $group) {
    if ((bool) ($group['has_active'] ?? false)) {
        $defaultOpenGroupIndex = $groupIndex;
        break;
    }
}
if ($defaultOpenGroupIndex === null && !empty($preparedGroups)) {
    $defaultOpenGroupIndex = 0;
}

$mobileBottomNavEnabled = true;
$mobilePrimaryTabs = [];
$mobileSecondaryItems = [];
$mobilePrimaryMatches = [];
$mobilePrimarySections = [];
$mobileQuickActions = [];

if ($mobileBottomNavEnabled) {
    if ($isSuperadmin) {
        $mobilePrimaryTabs = [
            [
                'key' => 'resumen',
                'label' => 'Inicio',
                'icon' => 'bx bxs-home-alt-2',
                'href' => url('superadmin') . '?seccion=resumen',
                'match' => '/superadmin',
                'section' => 'resumen',
                'enabled' => true,
            ],
            [
                'key' => 'empresas',
                'label' => 'Empresas',
                'icon' => 'bx bxs-buildings',
                'href' => url('superadmin') . '?seccion=empresas',
                'match' => '/superadmin',
                'section' => 'empresas',
                'enabled' => true,
            ],
            [
                'key' => 'soporte',
                'label' => 'Soporte',
                'icon' => 'bx bx-support',
                'href' => url('superadmin') . '?seccion=soporte',
                'match' => '/superadmin',
                'section' => 'soporte',
                'enabled' => true,
            ],
        ];
    } else {
        $mobilePrimaryTabs = [
            [
                'key' => 'dashboard',
                'label' => 'Dashboard',
                'icon' => 'bx bxs-grid-alt',
                'href' => url('dashboard'),
                'match' => '/dashboard',
                'enabled' => has_permission('dashboard.ver'),
            ],
            [
                'key' => 'pos',
                'label' => 'POS',
                'icon' => 'bx bxs-cart-add',
                'href' => url('pos'),
                'match' => '/pos',
                'enabled' => has_permission('pos.vender'),
            ],
            [
                'key' => 'ventas',
                'label' => 'Ventas',
                'icon' => 'bx bxs-receipt',
                'href' => url('ventas'),
                'match' => '/ventas',
                'enabled' => has_permission('ventas.ver'),
            ],
        ];
    }

    foreach ($mobilePrimaryTabs as $mobilePrimaryTab) {
        $mobilePrimaryMatch = trim((string) ($mobilePrimaryTab['match'] ?? ''));
        if ($mobilePrimaryMatch !== '') {
            $mobilePrimaryMatches[] = $mobilePrimaryMatch;
        }
        $mobilePrimarySection = trim((string) ($mobilePrimaryTab['section'] ?? ''));
        if ($mobilePrimarySection !== '') {
            $mobilePrimarySections[] = $mobilePrimarySection;
        }
    }

    $mobileSecondaryKeyed = [];
    foreach ($preparedGroups as $group) {
        $groupTitle = trim((string) ($group['title'] ?? 'Módulo'));
        foreach ((array) ($group['items'] ?? []) as $item) {
            $match = trim((string) ($item['match'] ?? ''));
            $section = trim((string) ($item['section'] ?? ''));

            if ($section !== '' && in_array($section, $mobilePrimarySections, true)) {
                continue;
            }

            if ($section === '' && $match !== '' && in_array($match, $mobilePrimaryMatches, true)) {
                continue;
            }

            $href = trim((string) ($item['href'] ?? ''));
            if ($href === '') {
                continue;
            }

            $itemKey = strtolower($href);
            if (isset($mobileSecondaryKeyed[$itemKey])) {
                continue;
            }

            $mobileSecondaryKeyed[$itemKey] = [
                'label' => trim((string) ($item['label'] ?? 'Módulo')),
                'icon' => trim((string) ($item['icon'] ?? 'bx bx-grid-alt')),
                'href' => $href,
                'group' => $groupTitle,
                'section' => $section,
            ];
        }
    }
    $mobileSecondaryItems = array_values($mobileSecondaryKeyed);

    if ($stockNotificationsPollingUrl !== '') {
        $mobileQuickActions[] = [
            'label' => 'Notificaciones',
            'icon' => 'bx bxs-bell',
            'href' => $notificationsPrimaryUrl,
            'badge' => $stockNotificationsCount,
        ];
    }

    $mobileQuickActions[] = [
        'label' => 'Mi perfil',
        'icon' => 'bx bx-user-circle',
        'href' => url('perfil'),
        'badge' => 0,
    ];
}
?>
<div class="vx-shell">
    <aside class="vx-sidebar" id="vxSidebar">
        <div class="vx-brand">
            <span class="vx-brand-dot">
                <img src="<?= e(asset('img/veltrix-icon-white.png')) ?>" alt="Veltrix" class="vx-brand-icon">
            </span>
            <div>
                <strong>Veltrix POS</strong>
            </div>
            <button class="vx-sidebar-close d-lg-none" id="vxSidebarClose" type="button">
                <i class="bx bx-x"></i>
            </button>
        </div>

        <nav class="vx-nav">
            <?php foreach ($preparedGroups as $groupIndex => $group): ?>
                <?php
                $groupTitle = trim((string) ($group['title'] ?? ''));
                $groupIcon = trim((string) ($group['icon'] ?? 'bx bxs-layer'));
                $groupItems = (array) ($group['items'] ?? []);
                $isGroupOpen = (bool) ($group['has_active'] ?? false) || $groupIndex === $defaultOpenGroupIndex;
                $groupPanelId = 'vxNavGroupPanel' . (string) $groupIndex;
                ?>
                <div class="vx-nav-group" data-vx-nav-group>
                    <button
                        class="vx-nav-group-toggle <?= $isGroupOpen ? 'is-open' : '' ?>"
                        type="button"
                        data-vx-nav-toggle
                        aria-expanded="<?= $isGroupOpen ? 'true' : 'false' ?>"
                        aria-controls="<?= e($groupPanelId) ?>"
                    >
                        <i class="<?= e('vx-nav-group-icon ' . $groupIcon) ?>"></i>
                        <span class="vx-nav-group-title"><?= e($groupTitle) ?></span>
                        <i class="bx bx-chevron-down vx-nav-group-arrow"></i>
                    </button>
                    <div
                        id="<?= e($groupPanelId) ?>"
                        class="vx-nav-group-body <?= $isGroupOpen ? 'is-open' : '' ?>"
                        data-vx-nav-panel
                    >
                        <?php foreach ($groupItems as $item): ?>
                            <?php
                            $active = (bool) ($item['_active'] ?? false);
                            $linkClasses = trim('vx-nav-link ' . (string) ($item['class'] ?? '') . ' ' . ($active ? 'is-active' : ''));
                            ?>
                            <a
                                class="<?= e($linkClasses) ?>"
                                href="<?= e($item['href']) ?>"
                                title="<?= e($item['label']) ?>"
                                aria-label="<?= e($item['label']) ?>"
                            >
                                <i class="<?= e($item['icon']) ?>"></i>
                                <span class="vx-nav-label"><?= e($item['label']) ?></span>
                                <?php if (($item['match'] ?? '') === '/caja'): ?>
                                    <span
                                        id="vxCajaPendingBadge"
                                        class="vx-nav-badge <?= $cashPendingTransfers > 0 ? '' : 'd-none' ?>"
                                        data-pending-url="<?= e($cashPendingPollingUrl) ?>"
                                    >
                                        <?= e((string) $cashPendingTransfers) ?>
                                    </span>
                                <?php endif; ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </nav>

        <div class="vx-sidebar-user">
            <p class="mb-0">Sesion activa</p>
            <strong><?= e($user['nombre'] ?? 'Usuario') ?></strong>
            <small class="d-block text-uppercase mt-1"><?= e((string) ($user['role_name'] ?? 'Sin rol')) ?></small>
            <a class="vx-sidebar-profile-link" href="<?= e(url('perfil')) ?>">
                <i class="bx bx-user-circle"></i>Mi perfil
            </a>
        </div>
    </aside>

    <div class="vx-main">
        <header class="vx-topbar">
            <div class="d-flex align-items-center gap-2 vx-topbar-heading">
                <button class="vx-icon-btn" id="vxSidebarToggle" type="button" aria-label="Abrir menu">
                    <i class="bx bx-menu-alt-left"></i>
                </button>
                <div>
                    <h1 class="vx-page-title"><?= e($title ?? 'Dashboard') ?></h1>
                    <small class="vx-page-subtitle">Gestion operativa en tiempo real</small>
                </div>
            </div>

            <div class="d-flex align-items-center gap-2 vx-topbar-actions">
                <?php if ($showTopbarMetaTemplateLink): ?>
                    <a
                        class="btn btn-light btn-sm vx-topbar-action vx-meta-template-btn vx-mobile-hide-top"
                        href="<?= e(url('superadmin') . '?seccion=whatsapp_meta_templates') ?>"
                        aria-label="Enlazar plantillas Meta"
                        title="Enlazar plantillas Meta"
                    >
                        <i class="bx bx-link-alt"></i>
                        <span>Enlazar Meta</span>
                    </a>
                <?php endif; ?>
                <?php if ($stockNotificationsPollingUrl !== ''): ?>
                    <?php $notificationBadgeText = $stockNotificationsCount > 99 ? '99+' : (string) $stockNotificationsCount; ?>
                    <div class="dropdown vx-topbar-notifications vx-mobile-hide-top">
                        <button
                            class="btn btn-light btn-sm vx-topbar-action vx-notify-btn dropdown-toggle"
                            type="button"
                            id="vxNotificationToggle"
                            data-bs-toggle="dropdown"
                            data-notifications-url="<?= e($stockNotificationsPollingUrl) ?>"
                            data-inventory-url="<?= e($stockNotificationsInventoryUrl) ?>"
                            data-support-url="<?= e($stockNotificationsSupportUrl) ?>"
                            data-mark-read-url="<?= e($notificationsMarkReadUrl) ?>"
                            data-notification-scope="<?= e($stockNotificationsScope) ?>"
                            aria-expanded="false"
                            aria-label="Notificaciones"
                        >
                            <i class="bx bxs-bell"></i>
                            <span id="vxNotificationBadge" class="vx-notify-badge <?= $stockNotificationsCount > 0 ? '' : 'd-none' ?>">
                                <?= e($notificationBadgeText) ?>
                            </span>
                        </button>
                        <div class="dropdown-menu dropdown-menu-end shadow-sm vx-notify-menu" aria-labelledby="vxNotificationToggle">
                            <div class="vx-notify-menu-header">
                                <div class="vx-notify-menu-title">
                                    <strong>Notificaciones</strong>
                                    <small id="vxNotificationCountLabel"><?= e((string) $stockNotificationsCount) ?> notificación(es)</small>
                                </div>
                                <button
                                    type="button"
                                    id="vxNotificationMarkRead"
                                    class="btn btn-sm btn-outline-primary vx-notify-mark-read"
                                    <?= $stockNotificationsCount > 0 ? '' : 'disabled' ?>
                                >
                                    Marcar como leído
                                </button>
                            </div>
                            <ul class="vx-notify-list" id="vxNotificationList">
                                <?php if ($stockNotifications === []): ?>
                                    <li id="vxNotificationEmpty" class="vx-notify-empty">
                                        No hay notificaciones pendientes.
                                    </li>
                                <?php else: ?>
                                    <?php foreach ($stockNotifications as $notification): ?>
                                        <?php
                                        $itemType = strtolower(trim((string) ($notification['notification_type'] ?? 'stock')));
                                        $itemSeverity = strtolower(trim((string) ($notification['severity'] ?? 'warning'))) === 'critical'
                                            ? 'is-critical'
                                            : 'is-warning';
                                        $itemIcon = $itemSeverity === 'is-critical' ? 'bx bxs-error-circle' : 'bx bxs-bell-ring';
                                        if ($itemType === 'ticket') {
                                            $itemSeverity = 'is-ticket';
                                            $itemIcon = 'bx bxs-message-dots';
                                        }
                                        ?>
                                        <li class="vx-notify-item <?= e($itemSeverity) ?>">
                                            <span class="vx-notify-item-icon">
                                                <i class="<?= e($itemIcon) ?>"></i>
                                            </span>
                                            <div class="vx-notify-item-body">
                                                <strong><?= e((string) ($notification['title'] ?? 'Alerta de stock')) ?></strong>
                                                <small><?= e((string) ($notification['message'] ?? 'Stock mínimo alcanzado.')) ?></small>
                                            </div>
                                        </li>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </ul>
                            <div class="vx-notify-menu-footer">
                                <a href="<?= e($notificationsPrimaryUrl) ?>"><?= e($notificationsPrimaryLabel) ?></a>
                                <?php if ($notificationsSecondaryUrl !== ''): ?>
                                    <a href="<?= e($notificationsSecondaryUrl) ?>" class="ms-2"><?= e($notificationsSecondaryLabel) ?></a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
                <?php foreach ($topbarActions as $topbarAction): ?>
                    <?php
                    if (!is_array($topbarAction)) {
                        continue;
                    }
                    $actionType = strtolower(trim((string) ($topbarAction['type'] ?? 'link')));
                    $actionLabel = trim((string) ($topbarAction['label'] ?? ''));
                    $actionIcon = trim((string) ($topbarAction['icon'] ?? ''));
                    $actionClass = trim((string) ($topbarAction['class'] ?? 'btn btn-primary btn-sm vx-topbar-action'));
                    $actionTarget = trim((string) ($topbarAction['target'] ?? ''));
                    $actionHref = trim((string) ($topbarAction['href'] ?? ''));
                    ?>
                    <?php if ($actionType === 'dropdown'): ?>
                        <?php
                        $dropdownItems = is_array($topbarAction['items'] ?? null) ? $topbarAction['items'] : [];
                        if ($dropdownItems === []) {
                            continue;
                        }
                        ?>
                        <div class="dropdown vx-topbar-dropdown">
                            <button
                                class="<?= e($actionClass . ' dropdown-toggle') ?>"
                                type="button"
                                data-bs-toggle="dropdown"
                                aria-expanded="false"
                            >
                                <?php if ($actionIcon !== ''): ?>
                                    <i class="<?= e($actionIcon) ?> me-1"></i>
                                <?php endif; ?>
                                <?= e($actionLabel !== '' ? $actionLabel : 'Acciones') ?>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end shadow-sm">
                                <?php foreach ($dropdownItems as $dropdownItem): ?>
                                    <?php
                                    if (!is_array($dropdownItem)) {
                                        continue;
                                    }
                                    $itemLabel = trim((string) ($dropdownItem['label'] ?? ''));
                                    $itemHref = trim((string) ($dropdownItem['href'] ?? ''));
                                    $itemIcon = trim((string) ($dropdownItem['icon'] ?? ''));
                                    $itemTarget = trim((string) ($dropdownItem['target'] ?? ''));
                                    $itemModalTarget = trim((string) ($dropdownItem['target_modal'] ?? ''));
                                    $itemDisabled = (bool) ($dropdownItem['disabled'] ?? false);
                                    if ($itemLabel === '' || ($itemHref === '' && $itemModalTarget === '')) {
                                        continue;
                                    }
                                    ?>
                                    <li>
                                        <?php if ($itemModalTarget !== ''): ?>
                                            <button
                                                class="dropdown-item d-flex align-items-center gap-2"
                                                type="button"
                                                data-bs-toggle="modal"
                                                data-bs-target="<?= e($itemModalTarget) ?>"
                                                <?= $itemDisabled ? 'disabled' : '' ?>
                                            >
                                                <?php if ($itemIcon !== ''): ?>
                                                    <i class="<?= e($itemIcon) ?>"></i>
                                                <?php endif; ?>
                                                <span><?= e($itemLabel) ?></span>
                                            </button>
                                        <?php else: ?>
                                            <a
                                                class="dropdown-item d-flex align-items-center gap-2"
                                                href="<?= e($itemHref) ?>"
                                                <?= $itemTarget === '_blank' ? 'target="_blank" rel="noopener"' : '' ?>
                                            >
                                                <?php if ($itemIcon !== ''): ?>
                                                    <i class="<?= e($itemIcon) ?>"></i>
                                                <?php endif; ?>
                                                <span><?= e($itemLabel) ?></span>
                                            </a>
                                        <?php endif; ?>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php else: ?>
                        <?php if ($actionType === 'modal'): ?>
                            <?php
                            $modalTarget = trim((string) ($topbarAction['target_modal'] ?? ''));
                            $isDisabled = (bool) ($topbarAction['disabled'] ?? false);
                            ?>
                            <?php if ($modalTarget !== ''): ?>
                                <button
                                    class="<?= e($actionClass) ?>"
                                    type="button"
                                    data-bs-toggle="modal"
                                    data-bs-target="<?= e($modalTarget) ?>"
                                    <?= $isDisabled ? 'disabled' : '' ?>
                                >
                                    <?php if ($actionIcon !== ''): ?>
                                        <i class="<?= e($actionIcon) ?> me-1"></i>
                                    <?php endif; ?>
                                    <?= e($actionLabel !== '' ? $actionLabel : 'Acción') ?>
                                </button>
                            <?php endif; ?>
                        <?php elseif ($actionHref !== ''): ?>
                            <a
                                class="<?= e($actionClass) ?>"
                                href="<?= e($actionHref) ?>"
                                <?= $actionTarget === '_blank' ? 'target="_blank" rel="noopener"' : '' ?>
                            >
                                <?php if ($actionIcon !== ''): ?>
                                    <i class="<?= e($actionIcon) ?> me-1"></i>
                                <?php endif; ?>
                                <?= e($actionLabel !== '' ? $actionLabel : 'Acción') ?>
                            </a>
                        <?php endif; ?>
                    <?php endif; ?>
                <?php endforeach; ?>
                <?php
                $profileName = trim((string) ($user['nombre'] ?? 'Usuario'));
                $profileRole = trim((string) ($user['role_name'] ?? 'Cuenta'));
                $profileInitial = strtoupper((string) mb_substr($profileName !== '' ? $profileName : 'U', 0, 1));
                ?>
                <div class="dropdown vx-topbar-dropdown vx-profile-dropdown vx-mobile-hide-top">
                    <button
                        class="vx-profile-menu-btn dropdown-toggle"
                        type="button"
                        data-bs-toggle="dropdown"
                        aria-expanded="false"
                        aria-label="Menú de perfil"
                    >
                        <span class="vx-profile-avatar"><?= e($profileInitial) ?></span>
                        <span class="vx-profile-meta">
                            <strong><?= e($profileName !== '' ? $profileName : 'Usuario') ?></strong>
                            <small><?= e($profileRole !== '' ? $profileRole : 'Cuenta') ?></small>
                        </span>
                        <i class="bx bx-chevron-down vx-profile-chevron"></i>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end shadow-sm vx-profile-menu">
                        <li class="vx-profile-menu-header">
                            <div class="vx-profile-menu-title">
                                <strong><?= e($profileName !== '' ? $profileName : 'Usuario') ?></strong>
                                <small><?= e($profileRole !== '' ? $profileRole : 'Cuenta') ?></small>
                            </div>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center gap-2" href="<?= e(url('perfil')) ?>">
                                <i class="bx bx-user-circle"></i>
                                <span>Mi perfil</span>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <li>
                            <form action="<?= e(url('logout')) ?>" method="post" class="m-0">
                                <?= csrf_field() ?>
                                <button class="dropdown-item d-flex align-items-center gap-2 text-danger" type="submit">
                                    <i class="bx bx-log-out-circle"></i>
                                    <span>Cerrar sesión</span>
                                </button>
                            </form>
                        </li>
                    </ul>
                </div>
            </div>
        </header>

        <main class="vx-content">
            <?= $content ?? '' ?>
        </main>
    </div>
</div>

<?php if ($mobileBottomNavEnabled): ?>
    <?php
    $moreTabActive = false;
    foreach ($mobileSecondaryItems as $secondaryItem) {
        $secondarySection = trim((string) ($secondaryItem['section'] ?? ''));
        if ($isSuperadmin && $secondarySection !== '') {
            if (($requestPath === '/superadmin' || str_starts_with($requestPath, '/superadmin/')) && $superadminSection === $secondarySection) {
                $moreTabActive = true;
                break;
            }
            continue;
        }

        $secondaryHref = trim((string) ($secondaryItem['href'] ?? ''));
        if ($secondaryHref === '') {
            continue;
        }
        $secondaryPath = parse_url($secondaryHref, PHP_URL_PATH) ?: '';
        if ($basePath !== '' && $basePath !== '/' && str_starts_with($secondaryPath, $basePath)) {
            $secondaryPath = substr($secondaryPath, strlen($basePath)) ?: '/';
        }
        $secondaryPath = '/' . ltrim($secondaryPath, '/');
        if ($secondaryPath !== '' && str_starts_with($requestPath, $secondaryPath)) {
            $moreTabActive = true;
            break;
        }
    }
    $secondaryBadge = $stockNotificationsCount > 99 ? '99+' : (string) $stockNotificationsCount;
    ?>
    <nav class="vx-mobile-bubble-nav d-lg-none" aria-label="Navegación principal móvil">
        <?php foreach ($mobilePrimaryTabs as $tab): ?>
            <?php
            $tabMatch = (string) ($tab['match'] ?? '');
            $tabSection = trim((string) ($tab['section'] ?? ''));
            if ($isSuperadmin && $tabSection !== '') {
                $tabActive = ($requestPath === $tabMatch || str_starts_with($requestPath, $tabMatch . '/')) && $superadminSection === $tabSection;
            } else {
                $tabActive = $requestPath === $tabMatch || str_starts_with($requestPath, $tabMatch . '/');
            }
            $tabEnabled = (bool) ($tab['enabled'] ?? false);
            $tabClasses = 'vx-mobile-bubble-item';
            if ($tabActive) {
                $tabClasses .= ' is-active';
            }
            if (!$tabEnabled) {
                $tabClasses .= ' is-disabled';
            }
            ?>
            <a
                class="<?= e($tabClasses) ?>"
                href="<?= e($tabEnabled ? (string) ($tab['href'] ?? '#') : '#') ?>"
                <?= $tabEnabled ? '' : 'aria-disabled="true" tabindex="-1"' ?>
            >
                <i class="<?= e((string) ($tab['icon'] ?? 'bx bx-circle')) ?>"></i>
                <span><?= e((string) ($tab['label'] ?? 'Módulo')) ?></span>
            </a>
        <?php endforeach; ?>

        <button
            class="vx-mobile-bubble-item <?= $moreTabActive ? 'is-active' : '' ?>"
            type="button"
            id="vxMobileMoreToggle"
            aria-controls="vxMobileSheet"
            aria-expanded="false"
        >
            <i class="bx bx-grid-alt"></i>
            <span>Más</span>
            <?php if ($stockNotificationsCount > 0): ?>
                <small class="vx-mobile-bubble-badge"><?= e($secondaryBadge) ?></small>
            <?php endif; ?>
        </button>
    </nav>

    <div class="vx-mobile-sheet-backdrop d-lg-none" id="vxMobileSheetBackdrop"></div>
    <aside class="vx-mobile-sheet d-lg-none" id="vxMobileSheet" aria-hidden="true">
        <div class="vx-mobile-sheet-header">
            <div>
                <strong>Más opciones</strong>
                <small>Acciones y módulos</small>
            </div>
            <button type="button" class="vx-mobile-sheet-close" id="vxMobileSheetClose" aria-label="Cerrar menú">
                <i class="bx bx-x"></i>
            </button>
        </div>

        <?php if ($mobileQuickActions !== []): ?>
            <div class="vx-mobile-sheet-quick">
                <?php foreach ($mobileQuickActions as $quickAction): ?>
                    <?php
                    $quickBadge = (int) ($quickAction['badge'] ?? 0);
                    $quickBadgeText = $quickBadge > 99 ? '99+' : (string) $quickBadge;
                    ?>
                    <a class="vx-mobile-sheet-quick-link" href="<?= e((string) ($quickAction['href'] ?? '#')) ?>">
                        <i class="<?= e((string) ($quickAction['icon'] ?? 'bx bx-star')) ?>"></i>
                        <span><?= e((string) ($quickAction['label'] ?? 'Acción')) ?></span>
                        <?php if ($quickBadge > 0): ?>
                            <small><?= e($quickBadgeText) ?></small>
                        <?php endif; ?>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <div class="vx-mobile-sheet-grid">
            <?php foreach ($mobileSecondaryItems as $secondaryItem): ?>
                <a class="vx-mobile-sheet-item" href="<?= e((string) ($secondaryItem['href'] ?? '#')) ?>">
                    <i class="<?= e((string) ($secondaryItem['icon'] ?? 'bx bx-grid-alt')) ?>"></i>
                    <span><?= e((string) ($secondaryItem['label'] ?? 'Módulo')) ?></span>
                    <small><?= e((string) ($secondaryItem['group'] ?? 'General')) ?></small>
                </a>
            <?php endforeach; ?>
        </div>

        <div class="vx-mobile-sheet-footer">
            <form action="<?= e(url('logout')) ?>" method="post" class="m-0">
                <?= csrf_field() ?>
                <button class="vx-mobile-sheet-logout" type="submit">
                    <i class="bx bx-log-out-circle"></i>
                    <span>Cerrar sesión</span>
                </button>
            </form>
        </div>
    </aside>
<?php endif; ?>

<div class="vx-sidebar-backdrop" id="vxSidebarBackdrop"></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="<?= e(asset('js/app.js')) ?>"></script>
<script>
    window.__veltrixFlash = <?= json_encode($flashPayload, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE) ?>;
    window.__veltrixStockNotifications = <?= json_encode([
        'count' => $stockNotificationsCount,
        'count_stock' => $stockNotificationsStockCount,
        'count_tickets' => $stockNotificationsTicketCount,
        'items' => $stockNotifications,
        'inventory_url' => $stockNotificationsInventoryUrl,
        'support_url' => $stockNotificationsSupportUrl,
    ], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE) ?>;

    window.addEventListener('DOMContentLoaded', () => {
        const flash = window.__veltrixFlash || {};
        const hasSwal = typeof window.Swal !== 'undefined';
        if (!hasSwal) {
            return;
        }

        const escapeHtml = (value) => String(value ?? '').replace(/[&<>"']/g, (char) => {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                '\'': '&#39;',
            };
            return map[char] || char;
        });

        const buildFooter = (actions) => {
            if (!Array.isArray(actions) || actions.length === 0) {
                return '';
            }

            return actions.map((action) => {
                if (!action || typeof action !== 'object') {
                    return '';
                }
                const label = escapeHtml(action.label || '');
                const url = escapeHtml(action.url || '');
                if (label === '' || url === '') {
                    return '';
                }
                const target = String(action.target || '').trim() === '_blank' ? '_blank' : '';
                const targetAttr = target !== '' ? ' target="_blank" rel="noopener"' : '';
                return '<a class="btn btn-sm btn-outline-primary me-2 mb-1" href="' + url + '"' + targetAttr + '>' + label + '</a>';
            }).join('');
        };

        const queue = [];
        if (typeof flash.error === 'string' && flash.error.trim() !== '') {
            queue.push({
                icon: 'error',
                title: 'Error',
                text: flash.error,
                confirmButtonText: 'Entendido',
            });
        }

        if (typeof flash.success === 'string' && flash.success.trim() !== '') {
            const footer = buildFooter(flash.actions);
            const cambio = typeof flash.pos_cambio === 'string' ? flash.pos_cambio.trim() : '';

            let swalConfig;
            if (cambio !== '') {
                swalConfig = {
                    icon: 'success',
                    title: 'Listo',
                    html: '<p style="margin:0 0 20px; font-size:1rem; color:#555;">' + escapeHtml(flash.success) + '</p>'
                        + '<div style="background:#d1fae5;border:2px solid #10b981;border-radius:14px;padding:18px 24px;">'
                        + '<div style="font-size:0.78rem;font-weight:600;letter-spacing:0.06em;text-transform:uppercase;color:#059669;margin-bottom:6px;">💵 Cambio a devolver</div>'
                        + '<div style="font-size:2.6rem;font-weight:800;color:#065f46;line-height:1;">' + escapeHtml(cambio) + '</div>'
                        + '</div>',
                    confirmButtonText: 'Continuar',
                    footer: footer !== '' ? footer : undefined,
                };
            } else {
                swalConfig = {
                    icon: 'success',
                    title: 'Listo',
                    text: flash.success,
                    confirmButtonText: 'Continuar',
                    footer: footer !== '' ? footer : undefined,
                };
            }
            queue.push(swalConfig);
        }

        if (queue.length === 0) {
            return;
        }

        const runQueue = async () => {
            for (const config of queue) {
                await window.Swal.fire(config);
            }
        };

        runQueue();
    });
</script>
</body>
</html>
