<?php
// Cabecera visual compartida del panel. Mantiene intactos permisos, rutas y lógica de cada módulo.
if (session_status() === PHP_SESSION_NONE) { session_start(); }

$current_page = basename($_SERVER['PHP_SELF']);
$titulo_pagina = $titulo_pagina ?? 'Panel';
$rol_actual = trim((string) ($_SESSION['admin']['rol'] ?? 'guest'));
$rol_normalizado = mb_strtolower($rol_actual, 'UTF-8');
$es_superadmin_actual = $rol_normalizado === 'superadmin';
$es_admin_actual = in_array($rol_normalizado, ['admin', 'ayudante de superadmin'], true);
$id_usuario_logueado = (int)($_SESSION['admin']['uid'] ?? 0);
$nombre_usuario_logueado = $_SESSION['admin']['nombre_usuario'] ?? '';
$ui_title_system = $ui_title_system ?? 'Panel Administrativo';
$ui_admin_header_subtitle = trim((string)($ui_admin_header_subtitle ?? 'Panel administrativo')) ?: 'Panel administrativo';
$ui_admin_quick_consult_title = trim((string)($ui_admin_quick_consult_title ?? 'Consultas')) ?: 'Consultas';
$ui_admin_quick_consult_subtitle = trim((string)($ui_admin_quick_consult_subtitle ?? 'Abrir códigos')) ?: 'Abrir códigos';
$ui_admin_quick_site_title = trim((string)($ui_admin_quick_site_title ?? 'Sitio web')) ?: 'Sitio web';
$ui_admin_quick_site_subtitle = trim((string)($ui_admin_quick_site_subtitle ?? 'Vista pública')) ?: 'Vista pública';

$brand_primary = $ui_color_primary_bg_hex ?? '#dc2626';
$brand_secondary = $ui_color_secondary_hex ?? '#111827';
$brand_accent = $ui_color_accent_hex ?? '#f59e0b';
$brand_sidebar = $ui_color_sidebar_hex ?? '#08111f';
$brand_admin_bg = $ui_color_admin_bg_hex ?? '#f4f7fb';
$brand_button = $ui_color_button_hex ?? $brand_primary;
$brand_button_text = $ui_color_button_text_hex ?? '#ffffff';
$brand_admin_header = $ui_color_admin_header_hex ?? '#ffffff';
$brand_admin_header_text = $ui_color_admin_header_text_hex ?? '#0f172a';
$brand_admin_icons = $ui_color_admin_icons_hex ?? $brand_primary;
$brand_footer = $ui_color_footer_hex ?? '#08111f';
$brand_footer_text = $ui_color_footer_text_hex ?? '#cbd5e1';
if (!preg_match('/^#[0-9a-fA-F]{6}$/', $brand_primary)) { $brand_primary = '#dc2626'; }
if (!preg_match('/^#[0-9a-fA-F]{6}$/', $brand_secondary)) { $brand_secondary = '#111827'; }
if (!preg_match('/^#[0-9a-fA-F]{6}$/', $brand_accent)) { $brand_accent = '#f59e0b'; }
if (!preg_match('/^#[0-9a-fA-F]{6}$/', $brand_sidebar)) { $brand_sidebar = '#08111f'; }
if (!preg_match('/^#[0-9a-fA-F]{6}$/', $brand_admin_bg)) { $brand_admin_bg = '#f4f7fb'; }
$brand_primary_rgb = implode(', ', [
    hexdec(substr($brand_primary, 1, 2)),
    hexdec(substr($brand_primary, 3, 2)),
    hexdec(substr($brand_primary, 5, 2)),
]);

$logo_configurado = trim((string)($ui_logo_login_path ?? 'assets/img/logo.png'));
if ($logo_configurado !== '' && !preg_match('#^(?:https?:|data:|/|\.\./)#i', $logo_configurado)) {
    $logo_configurado = '../' . ltrim($logo_configurado, './');
}

$favicon_configurado = trim((string)($ui_favicon_path ?? 'assets/img/logo.png'));
if ($favicon_configurado !== '' && !preg_match('#^(?:https?:|data:|/|\.\./)#i', $favicon_configurado)) {
    $favicon_configurado = '../' . ltrim($favicon_configurado, './');
}

// Resumen compacto del plan del Admin para mostrarlo en todas las páginas.
$topbar_plan = null;
if ($es_admin_actual && $id_usuario_logueado > 0 && isset($pdo) && $pdo instanceof PDO) {
    try {
        $topbarPlanStmt = $pdo->prepare(
            "SELECT p.nombre_plan, s.fecha_fin, s.estado
             FROM suscripciones s
             JOIN planes p ON p.id = s.id_plan
             WHERE s.id_admin = ?
             ORDER BY CASE WHEN s.estado IN ('activa','prueba') THEN 0 ELSE 1 END,
                      s.fecha_fin DESC, s.id DESC
             LIMIT 1"
        );
        $topbarPlanStmt->execute([$id_usuario_logueado]);
        if ($topbarPlanRow = $topbarPlanStmt->fetch(PDO::FETCH_ASSOC)) {
            $topbarPlanName = trim((string)($topbarPlanRow['nombre_plan'] ?? '')) ?: 'Sin plan';
            $topbarPlanEndRaw = trim((string)($topbarPlanRow['fecha_fin'] ?? ''));
            $topbarPlanState = trim((string)($topbarPlanRow['estado'] ?? 'sin_plan'));
            $topbarPlanDays = null;
            $topbarPlanEndLabel = 'Sin fecha';
            $topbarPlanTraffic = 'neutral';
            $topbarPlanCountdown = 'Sin vigencia definida';

            if ($topbarPlanEndRaw !== '' && strtotime($topbarPlanEndRaw) !== false) {
                $topbarPlanEnd = new DateTimeImmutable(date('Y-m-d', strtotime($topbarPlanEndRaw)));
                $topbarToday = new DateTimeImmutable('today');
                $topbarPlanDays = (int)$topbarToday->diff($topbarPlanEnd)->format('%r%a');
                $topbarPlanEndLabel = $topbarPlanEnd->format('d/m/Y');

                if ($topbarPlanDays < 0) {
                    $topbarPlanTraffic = 'danger';
                    $topbarPlanCountdown = 'Vencido hace ' . abs($topbarPlanDays) . ' día' . (abs($topbarPlanDays) === 1 ? '' : 's');
                } elseif ($topbarPlanDays === 0) {
                    $topbarPlanTraffic = 'danger';
                    $topbarPlanCountdown = 'Vence hoy';
                } elseif ($topbarPlanDays <= 7) {
                    $topbarPlanTraffic = 'danger';
                    $topbarPlanCountdown = $topbarPlanDays . ' día' . ($topbarPlanDays === 1 ? '' : 's') . ' restantes';
                } elseif ($topbarPlanDays <= 15) {
                    $topbarPlanTraffic = 'warning';
                    $topbarPlanCountdown = $topbarPlanDays . ' días restantes';
                } elseif ($topbarPlanDays <= 30) {
                    $topbarPlanTraffic = 'attention';
                    $topbarPlanCountdown = $topbarPlanDays . ' días restantes';
                } else {
                    $topbarPlanTraffic = 'success';
                    $topbarPlanCountdown = $topbarPlanDays . ' días restantes';
                }
            }

            $topbar_plan = [
                'name' => $topbarPlanName,
                'end' => $topbarPlanEndLabel,
                'state' => $topbarPlanState,
                'traffic' => $topbarPlanTraffic,
                'countdown' => $topbarPlanCountdown,
            ];
        }
    } catch (Throwable $topbarPlanError) {
        error_log('Topbar plan: ' . $topbarPlanError->getMessage());
    }
}


$subscription_status = (array) ($_SESSION['admin']['subscription_status'] ?? []);
$subscription_locked = $es_admin_actual && !(bool) ($subscription_status['operational'] ?? false);
$admin_can_operate = !$subscription_locked;
$topbar_wallet = null;
if ($es_admin_actual && $id_usuario_logueado > 0 && isset($pdo) && $pdo instanceof PDO) {
    try {
        require_once __DIR__ . '/../lib/WalletSubscriptionService.php';
        $walletHeaderService = new WalletSubscriptionService($pdo);
        $topbar_wallet = [
            'balance' => $walletHeaderService->getBalance($id_usuario_logueado),
            'currency' => $walletHeaderService->getCurrency(),
            'symbol' => $walletHeaderService->getCurrencySymbol(),
        ];
    } catch (Throwable $walletHeaderError) {
        error_log('Topbar wallet: ' . $walletHeaderError->getMessage());
    }
}

if (!function_exists('afenixx_nav_link')) {
    function afenixx_nav_link(string $href, string $icon, string $label, string $currentPage): void {
        $active = $currentPage === basename($href) ? ' active' : '';
        echo '<a href="' . htmlspecialchars($href, ENT_QUOTES, 'UTF-8') . '" class="sidebar-link' . $active . '">';
        echo '<i class="' . htmlspecialchars($icon, ENT_QUOTES, 'UTF-8') . ' fa-fw" aria-hidden="true"></i>';
        echo '<span class="nav-label">' . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . '</span></a>';
    }
}
?>
<!DOCTYPE html>
<html lang="<?= htmlspecialchars($ui_language ?? 'es') ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="theme-color" content="<?= htmlspecialchars($brand_primary) ?>">
    <meta name="description" content="<?= htmlspecialchars($ui_seo_description ?? 'Panel administrativo') ?>">
    <title><?= htmlspecialchars($titulo_pagina) ?> | <?= htmlspecialchars($ui_title_system) ?></title>
    <?php if ($favicon_configurado !== ''): ?><link rel="icon" href="<?= htmlspecialchars($favicon_configurado) ?>"><?php endif; ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    <link href="../assets/css/admin-premium.css?v=4.2.0" rel="stylesheet">
    <link href="../assets/css/admin-unified.css?v=9.0.0" rel="stylesheet">
    <link href="../assets/css/admin-forms.css?v=9.0.0" rel="stylesheet">
    <link href="../assets/css/superadmin-unified.css?v=4.2.0" rel="stylesheet">
    <link href="../assets/css/subscription-wallet.css?v=1.5.0" rel="stylesheet">
    <link href="../assets/css/admin-final-unified.css?v=2026.07.25-v16" rel="stylesheet">
    <style>
        :root {
            --brand-primary: <?= htmlspecialchars($brand_primary) ?>;
            --brand-secondary: <?= htmlspecialchars($brand_secondary) ?>;
            --brand-primary-rgb: <?= htmlspecialchars($brand_primary_rgb) ?>;
            --brand-accent: <?= htmlspecialchars($brand_accent) ?>;
            --admin-sidebar: <?= htmlspecialchars($brand_sidebar) ?>;
            --admin-bg: <?= htmlspecialchars($brand_admin_bg) ?>;
            --brand-button: <?= htmlspecialchars($brand_button) ?>;
            --brand-button-text: <?= htmlspecialchars($brand_button_text) ?>;
            --admin-header: <?= htmlspecialchars($brand_admin_header) ?>;
            --admin-header-text: <?= htmlspecialchars($brand_admin_header_text) ?>;
            --admin-icons: <?= htmlspecialchars($brand_admin_icons) ?>;
            --admin-footer: <?= htmlspecialchars($brand_footer) ?>;
            --admin-footer-text: <?= htmlspecialchars($brand_footer_text) ?>;
        }

        .premium-topbar{background:var(--admin-header)!important;color:var(--admin-header-text)!important}
        .premium-page-title,.premium-page-eyebrow,.topbar-quick-copy strong,.topbar-quick-copy small,.premium-user-name,.premium-user-role{color:var(--admin-header-text)!important}
        .topbar-quick-icon,.premium-avatar,.mobile-menu-toggle,.sidebar-toggle,.topbar-icon-btn,.premium-brand-mark i{color:var(--admin-icons)!important}
        .sa-btn--primary,.af-btn-primary,.sc-btn-primary,.auth-submit{background:var(--brand-button)!important;color:var(--brand-button-text)!important;border-color:var(--brand-button)!important}
        .premium-footer{background:var(--admin-footer)!important;color:var(--admin-footer-text)!important}
        .premium-footer a,.premium-footer-status{color:var(--admin-footer-text)!important}
        .premium-footer-status{display:inline!important;padding:0!important;border:0!important;border-radius:0!important;background:transparent!important;box-shadow:none!important;font-weight:600!important;line-height:inherit!important;cursor:default!important}
    </style>
    <script>
    // Captura Escape antes que los controladores particulares de cada módulo.
    // Escape cierra el modal activo sin ejecutar confirmaciones de cambios pendientes.
    (function () {
        'use strict';
        if (window.__afenixEscapeGuardInstalled) return;
        window.__afenixEscapeGuardInstalled = true;

        const visible = (element) => {
            if (!(element instanceof HTMLElement)) return false;
            const style = window.getComputedStyle(element);
            return style.display !== 'none'
                && style.visibility !== 'hidden'
                && !element.classList.contains('hidden')
                && element.getClientRects().length > 0;
        };

        window.addEventListener('keydown', function (event) {
            if (event.key !== 'Escape' && event.keyCode !== 27) return;

            // SweetAlert2 también es un modal. El guard global se ejecuta antes
            // que la librería, por eso debe cerrarlo explícitamente para no
            // bloquear Escape en vistas previas de WhatsApp y confirmaciones.
            const swalVisible = window.Swal
                && typeof window.Swal.isVisible === 'function'
                && window.Swal.isVisible();
            if (swalVisible) {
                event.preventDefault();
                event.stopPropagation();
                event.stopImmediatePropagation();
                window.Swal.close();
                return;
            }

            const selectors = [
                '.af-modal-backdrop.is-open',
                '.module-modal:not(.hidden)',
                '[role="dialog"].is-open',
                '[id$="Modal"].is-open',
                '[id$="modal"].is-open',
                'body[data-role="Superadmin"] [id$="Modal"]:not(.hidden)',
                'body[data-role="Superadmin"] [id$="modal"]:not(.hidden)'
            ].join(',');
            const modals = Array.from(document.querySelectorAll(selectors)).filter(visible);
            const modal = modals.length ? modals[modals.length - 1] : null;
            if (!modal) return;

            event.preventDefault();
            event.stopPropagation();
            event.stopImmediatePropagation();
            window.__afenixEscapeClosing = true;

            try {
                const controller = modal.__afModalController;
                if (controller && typeof controller.close === 'function') {
                    controller.close(true);
                } else {
                    modal.dispatchEvent(new CustomEvent('afenixx:escape-close', { bubbles: false }));
                    modal.classList.remove('is-open', 'open', 'show', 'active');
                    if (modal.classList.contains('module-modal') || document.body.dataset.role === 'Superadmin') modal.classList.add('hidden');
                    modal.setAttribute('aria-hidden', 'true');
                    document.body.classList.remove('af-modal-open', 'modal-open', 'overflow-hidden');
                    document.documentElement.classList.remove('overflow-hidden');
                }
            } finally {
                window.setTimeout(function () { window.__afenixEscapeClosing = false; }, 0);
            }
        }, true);
    })();
    </script>
    <!-- Dependencias compartidas del panel: se cargan una sola vez antes de los scripts de cada módulo. -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.full.min.js"></script>
</head>
<body class="admin-premium<?= $subscription_locked ? ' subscription-locked' : '' ?>" data-page="<?= htmlspecialchars($current_page) ?>" data-role="<?= htmlspecialchars($rol_actual) ?>">
<div class="admin-shell">
    <div id="sidebar-overlay" class="sidebar-overlay" aria-hidden="true"></div>

    <aside id="premium-sidebar" class="premium-sidebar" aria-label="Navegación principal">
        <div class="premium-brand">
            <?php if ($logo_configurado !== ''): ?>
                <span class="premium-brand-logo"><img src="<?= htmlspecialchars($logo_configurado) ?>" alt="Logo <?= htmlspecialchars($ui_title_system) ?>" onerror="this.closest('.premium-brand-logo').style.display='none';this.closest('.premium-brand').querySelector('.premium-brand-mark').style.display='grid';"></span>
                <span class="premium-brand-mark" style="display:none"><i class="fas fa-bolt" aria-hidden="true"></i></span>
            <?php else: ?>
                <span class="premium-brand-mark"><i class="fas fa-bolt" aria-hidden="true"></i></span>
            <?php endif; ?>
            <span class="brand-copy">
                <span class="brand-name"><?= htmlspecialchars($ui_title_system) ?></span>
                <span class="brand-role"><?= htmlspecialchars($rol_actual) ?></span>
            </span>
        </div>

        <nav class="premium-sidebar-nav">
            <p class="sidebar-section">Resumen</p>
            <?php if (tiene_permiso('ver_dashboard')) { afenixx_nav_link('index.php', 'fas fa-chart-pie', 'Panel Principal', $current_page); } ?>

            <p class="sidebar-section">Operación</p>
            <?php if (!$es_superadmin_actual && $admin_can_operate && tiene_permiso('gestionar_propios_buzones')) { afenixx_nav_link('gestionar_buzones.php', 'fas fa-inbox', 'Buzones', $current_page); } ?>
            <?php if (!$es_superadmin_actual && $admin_can_operate && tiene_permiso('gestionar_propios_dominios')) { afenixx_nav_link('gestionar_dominios.php', 'fas fa-at', 'Dominios', $current_page); } ?>
            <?php if (tiene_permiso('gestionar_plataformas')) { afenixx_nav_link('gestionar_plataformas.php', 'fas fa-tv', 'Plataformas', $current_page); } ?>
            <?php if (tiene_permiso('gestionar_asuntos')) { afenixx_nav_link('gestionar_asuntos.php', 'fas fa-tags', 'Asuntos', $current_page); } ?>
            <?php if (!$es_superadmin_actual && $admin_can_operate && tiene_permiso('gestionar_propios_clientes')) { afenixx_nav_link('gestionar_clientes.php', 'fas fa-users', 'Clientes', $current_page); } ?>
            <?php if (!$es_superadmin_actual && $admin_can_operate && tiene_permiso('gestionar_propias_cuentas')) { afenixx_nav_link('gestionar_cuentas.php', 'fas fa-envelope-open-text', 'Cuentas', $current_page); } ?>

            <p class="sidebar-section">Comercial</p>
            <?php if (tiene_permiso('ver_suscripciones')) { afenixx_nav_link('gestionar_suscripciones.php', 'fas fa-id-card', 'Suscriptores', $current_page); } ?>
            <?php if ($es_superadmin_actual) { afenixx_nav_link('gestionar_creditos.php', 'fas fa-wallet', 'Créditos', $current_page); } ?>
            <?php /* AFENIXX-ADMIN-PERMISSIONS-20260724 */ ?>
<?php if ($es_admin_actual && tiene_permiso('ver_mi_suscripcion_admin')) { afenixx_nav_link('mi_suscripcion.php', 'fas fa-credit-card', 'Mi suscripción', $current_page); } ?>
            <?php if ($rol_normalizado === 'admin' && (($ui_referrals_enabled ?? true) === true) && tiene_permiso('ver_referidos_propios_admin')) { afenixx_nav_link('mis_referidos.php', 'fas fa-user-group', 'Mis Referidos', $current_page); } ?>
            <?php if (tiene_permiso('ver_pagos')) { afenixx_nav_link('gestionar_pagos.php', 'fas fa-receipt', 'Pagos', $current_page); } ?>
            <?php if (tiene_permiso('gestionar_planes')) { afenixx_nav_link('gestionar_planes.php', 'fas fa-layer-group', 'Planes', $current_page); } ?>
            <?php if ($es_admin_actual): ?>
                <p class="sidebar-section">Administración</p>
            <?php else: ?>
                <p class="sidebar-section">Comunicación</p>
            <?php endif; ?>

            <?php if (tiene_permiso('gestionar_plantillas')) { afenixx_nav_link('gestionar_plantillas.php', 'fab fa-whatsapp', 'Plantillas', $current_page); } ?>
            <?php if (tiene_permiso('gestionar_mensajes')) { afenixx_nav_link('gestionar_mensajes.php', 'fas fa-bell', 'Mensajes', $current_page); } ?>

            <?php if (!$es_admin_actual): ?>
                <p class="sidebar-section">Administración</p>
            <?php endif; ?>

            <?php if ($es_superadmin_actual) { afenixx_nav_link('configurar_marca.php', 'fas fa-swatchbook', 'Marca Blanca', $current_page); } ?>
            <?php if (tiene_permiso('gestionar_roles')) { afenixx_nav_link('gestionar_roles.php', 'fas fa-user-shield', 'Roles y permisos', $current_page); } ?>
            <?php if (tiene_permiso('gestionar_pruebas')) { afenixx_nav_link('gestionar_pruebas.php', 'fas fa-flask-vial', 'Liberar Pruebas', $current_page); } ?>
            <?php if (tiene_permiso('gestionar_ayudantes')) { afenixx_nav_link('gestionar_ayudantes.php', 'fas fa-user-gear', 'Ayudantes', $current_page); } ?>
            <?php if ($es_superadmin_actual) { afenixx_nav_link('gestionar_reportes.php', 'fas fa-chart-column', 'Reportes', $current_page); } ?>
            <?php if ($es_admin_actual && $admin_can_operate && tiene_permiso('ver_reportes_propios_admin')) { afenixx_nav_link('mis_reportes.php', 'fas fa-chart-line', 'Mis Reportes', $current_page); } ?>


            <?php
            $mostrar_ayuda_admin = !$es_superadmin_actual
                && (tiene_permiso('ver_manual_admin') || tiene_permiso('ver_manual_gmail_admin'));
            $mostrar_ayuda_superadmin = tiene_permiso('ver_manual_superadmin');
            ?>
            <?php if ($mostrar_ayuda_admin || $mostrar_ayuda_superadmin): ?>
                <p class="sidebar-section">Ayuda</p>
                <?php if (!$es_superadmin_actual && tiene_permiso('ver_manual_admin')) { afenixx_nav_link('manual_de_uso.php', 'fas fa-book-open', 'Manual de Uso', $current_page); } ?>
                <?php if (!$es_superadmin_actual && tiene_permiso('ver_manual_gmail_admin')) { afenixx_nav_link('manual_gmail.php', 'fab fa-google', 'Manual Gmail', $current_page); } ?>
                <?php if (tiene_permiso('ver_manual_superadmin')) { afenixx_nav_link('manual_superadmin.php', 'fas fa-book', 'Manual Superadmin', $current_page); } ?>
            <?php endif; ?>
        </nav>

        <div class="sidebar-footer">
            <a href="../logout.php" class="sidebar-link">
                <i class="fas fa-arrow-right-from-bracket fa-fw" aria-hidden="true"></i>
                <span class="nav-label">Cerrar Sesión</span>
            </a>
        </div>
    </aside>

    <div class="premium-content">
        <header class="premium-topbar">
            <div class="topbar-left">
                <button id="mobile-menu-toggle" class="mobile-menu-toggle" type="button" aria-label="Abrir menú" aria-expanded="false"><i class="fas fa-bars"></i></button>
                <button id="sidebar-toggle" class="sidebar-toggle" type="button" aria-label="Contraer menú" aria-expanded="true"><i class="fas fa-bars-staggered"></i></button>
                <div class="premium-page-copy">
                    <h1 class="premium-page-title"><?= htmlspecialchars($titulo_pagina) ?></h1>
                    <span class="premium-page-eyebrow"><?= htmlspecialchars($ui_admin_header_subtitle) ?></span>
                </div>
            </div>

            <div class="topbar-right">
                <?php if ($topbar_plan !== null && tiene_permiso('ver_mi_suscripcion_admin')): ?>
                    <a href="mi_suscripcion.php" class="topbar-plan-chip is-<?= htmlspecialchars((string)$topbar_plan['traffic']) ?>" title="Plan <?= htmlspecialchars((string)$topbar_plan['name']) ?> · vence <?= htmlspecialchars((string)$topbar_plan['end']) ?>">
                        <span class="topbar-plan-light" aria-hidden="true"></span>
                        <span class="topbar-plan-icon"><i class="fas fa-gem"></i></span>
                        <span class="topbar-plan-copy">
                            <strong><?= htmlspecialchars((string)$topbar_plan['name']) ?></strong>
                            <span>Vence <?= htmlspecialchars((string)$topbar_plan['end']) ?></span>
                        </span>
                        <span class="topbar-plan-days"><?= htmlspecialchars((string)$topbar_plan['countdown']) ?></span>
                    </a>
                <?php endif; ?>
                <?php if ($topbar_wallet !== null && tiene_permiso('ver_mi_suscripcion_admin')): ?>
                    <a href="mi_suscripcion.php" class="topbar-wallet-chip" title="Saldo disponible para renovaciones">
                        <span class="topbar-wallet-icon"><i class="fas fa-wallet"></i></span>
                        <span><small>Mi saldo</small><strong><?= htmlspecialchars((string)$topbar_wallet['symbol']) ?> <?= number_format((float)$topbar_wallet['balance'], 2) ?></strong></span>
                    </a>
                <?php endif; ?>
                <a href="../consulta.php" target="_blank" rel="noopener" class="topbar-quick-link" title="Abrir consulta pública">
                    <span class="topbar-quick-icon"><i class="fas fa-magnifying-glass"></i></span>
                    <span class="topbar-quick-copy"><strong><?= htmlspecialchars($ui_admin_quick_consult_title) ?></strong><small><?= htmlspecialchars($ui_admin_quick_consult_subtitle) ?></small></span>
                </a>
                <a href="../index.php" target="_blank" rel="noopener" class="topbar-quick-link" title="Abrir sitio principal">
                    <span class="topbar-quick-icon"><i class="fas fa-globe"></i></span>
                    <span class="topbar-quick-copy"><strong><?= htmlspecialchars($ui_admin_quick_site_title) ?></strong><small><?= htmlspecialchars($ui_admin_quick_site_subtitle) ?></small></span>
                </a>

                <div class="premium-user-chip" title="<?= htmlspecialchars($nombre_usuario_logueado . ' · ' . $rol_actual) ?>">
                    <span class="premium-avatar"><i class="fas fa-user"></i></span>
                    <span class="premium-user-copy">
                        <span class="premium-user-name"><?= htmlspecialchars($nombre_usuario_logueado ?: 'Usuario') ?></span>
                        <span class="premium-user-role"><?= htmlspecialchars($rol_actual) ?></span>
                    </span>
                </div>

                <?php if ($current_page === 'index.php'): ?>
                    <div class="topbar-dropdown">
                        <button id="admin-menu-button" class="topbar-icon-btn" type="button" aria-label="Configuración de la cuenta" aria-haspopup="true" aria-expanded="false">
                            <i class="fas fa-gear"></i>
                        </button>
                        <div id="admin-config-dropdown-menu" class="topbar-dropdown-menu hidden">
                            <a href="#" id="configure-my-data-btn"><i class="fas fa-user-pen"></i>Mis Datos</a>
                            <?php if ($es_admin_actual && tiene_permiso('ver_mi_suscripcion_admin')): ?>
                                <a href="mi_suscripcion.php"><i class="fas fa-wallet"></i>Mi suscripción y saldo</a>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </header>

        <main class="admin-main">
            <?php if ($subscription_locked): ?>
                <div class="subscription-lock-banner" role="alert">
                    <span class="subscription-lock-icon"><i class="fas fa-lock"></i></span>
                    <div>
                        <strong>Suscripción vencida: administración bloqueada</strong>
                        <p><?= htmlspecialchars((string) ($subscription_status['message'] ?? 'Renueva tu plan para continuar.')) ?> Tus consultas pueden mostrar resultados, pero el contenido no se abrirá hasta renovar.</p>
                    </div>
                    <a href="mi_suscripcion.php"><i class="fas fa-wallet"></i> Renovar con saldo</a>
                </div>
            <?php endif; ?>
