<?php

declare(strict_types=1);

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

$afPublicBrand = trim((string) ($ui_title_system ?? 'Ave Fénix')) ?: 'Ave Fénix';
$afPublicLogo = trim((string) ($ui_logo_login_path ?? 'assets/img/logo.png'));
$afPublicSubtitle = trim((string) ($ui_public_header_subtitle ?? 'Consulta y entrega de códigos'));
$afPublicPage = basename((string) ($_SERVER['PHP_SELF'] ?? 'index.php'));
$afPublicOnLanding = $afPublicPage === 'index.php';
$afPublicOnConsulta = $afPublicPage === 'consulta.php';
$afPublicOnConsultaLogin = $afPublicPage === 'login_consulta.php';
$afAdminSession = !empty($_SESSION['admin']['rol']);
$afConsultaSession = is_array($_SESSION['consulta'] ?? null)
    && array_key_exists('uid', $_SESSION['consulta']);
$afConsultaType = trim((string) ($_SESSION['consulta']['tipo_acceso'] ?? ''));
$afConsultaRole = strtolower(trim((string) ($_SESSION['consulta']['rol'] ?? '')));
$afConsultaManualUrl = $afConsultaRole === 'revendedor' ? 'manual_revendedor.php' : 'manual_usuario.php';
$afConsultaUid = (int) ($_SESSION['consulta']['uid'] ?? 0);
$afConsultaName = trim((string) ($_SESSION['consulta']['nombre_usuario'] ?? ''));
$afConsultaCode = trim((string) ($_SESSION['consulta']['codigo_consulta'] ?? ''));
$afConsultaEmail = strtolower(trim((string) ($_SESSION['consulta']['correo_permitido'] ?? '')));
$afConsultaPlatformName = trim((string) ($_SESSION['consulta']['plataforma_nombre'] ?? ''));

if (
    $afConsultaSession
    && $afConsultaType === 'cuenta_unica'
    && $afConsultaPlatformName === ''
    && isset($pdo)
    && $pdo instanceof PDO
) {
    try {
        $afPlatformId = (int) ($_SESSION['consulta']['plataforma_permitida'] ?? 0);
        if ($afPlatformId > 0) {
            $afPlatformStmt = $pdo->prepare('SELECT nombre FROM plataformas WHERE id = ? LIMIT 1');
            $afPlatformStmt->execute([$afPlatformId]);
            $afConsultaPlatformName = trim((string) ($afPlatformStmt->fetchColumn() ?: ''));
            if ($afConsultaPlatformName !== '') {
                $_SESSION['consulta']['plataforma_nombre'] = $afConsultaPlatformName;
            }
        }
    } catch (Throwable $ignored) {
        $afConsultaPlatformName = '';
    }
}

$afSessionPrimary = '';
$afSessionSecondary = '';
$afSessionIcon = 'fa-user-shield';
if ($afConsultaSession) {
    if ($afConsultaType === 'cuenta_unica') {
        $afSessionPrimary = 'Invitado' . ($afConsultaPlatformName !== '' ? ' · ' . $afConsultaPlatformName : ' · Cuenta individual');
        $afSessionSecondary = $afConsultaEmail !== '' ? $afConsultaEmail : ($afConsultaCode !== '' ? 'ID: ' . $afConsultaCode : 'Acceso individual');
        $afSessionIcon = 'fa-envelope-open-text';
    } else {
        $afSessionPrimary = $afConsultaName !== '' ? $afConsultaName : 'Usuario autorizado';
        $afSessionSecondary = $afConsultaCode !== '' ? 'ID de consulta: ' . $afConsultaCode : ucfirst($afConsultaRole ?: 'Cliente');
        $afSessionIcon = $afConsultaRole === 'revendedor' ? 'fa-store' : 'fa-user-check';
    }
}
$afConsultaPanelUrl = '';
$afConsultaPanelLabel = 'Mi panel';
$afConsultaPanelIcon = 'fa-table-columns';
if ($afConsultaSession) {
    if ($afConsultaType === 'cliente' && $afConsultaUid > 0) {
        $afConsultaPanelUrl = 'dashboard_usuario.php';
    } elseif ($afConsultaType === 'cuenta_unica') {
        $allowedPlatform = (int) ($_SESSION['consulta']['plataforma_permitida'] ?? 0);
        $allowedEmail = filter_var((string) ($_SESSION['consulta']['correo_permitido'] ?? ''), FILTER_VALIDATE_EMAIL) ?: '';
        $afConsultaPanelLabel = 'Mi cuenta';
        $afConsultaPanelIcon = 'fa-envelope-open-text';
        $afConsultaPanelUrl = 'consulta.php';
        if ($allowedPlatform > 0 && $allowedEmail !== '') {
            $afConsultaPanelUrl .= '?' . http_build_query([
                'plataforma' => $allowedPlatform,
                'correo' => strtolower($allowedEmail),
                'continuar' => '1',
            ], '', '&', PHP_QUERY_RFC3986);
        }
    }
}
$afConsultaBackUrl = 'consulta.php';
if ($afPublicOnConsultaLogin && is_array($_SESSION['consulta_pendiente'] ?? null)) {
    $pending = $_SESSION['consulta_pendiente'];
    $pendingPlatform = (int) ($pending['plataforma'] ?? 0);
    $pendingEmail = filter_var((string) ($pending['correo'] ?? ''), FILTER_VALIDATE_EMAIL) ?: '';
    if ($pendingPlatform > 0 && $pendingEmail !== '') {
        $afConsultaBackUrl .= '?' . http_build_query([
            'plataforma' => $pendingPlatform,
            'correo' => strtolower($pendingEmail),
        ], '', '&', PHP_QUERY_RFC3986);
    }
}

$afPublicHeaderBg = (string) ($ui_color_public_header_hex ?? '#ffffff');
$afPublicHeaderText = (string) ($ui_color_public_header_text_hex ?? '#0f172a');
$afPublicButton = (string) ($ui_color_button_hex ?? $ui_color_primary_bg_hex ?? '#dc2626');
$afPublicButtonText = (string) ($ui_color_button_text_hex ?? '#ffffff');
$afPublicIcons = (string) ($ui_color_public_icons_hex ?? $afPublicButton);
$afConsultLabel = trim((string)($ui_footer_action_consult_label ?? 'Consultar')) ?: 'Consultar';
$afConsultIcon = preg_match('/^fa-[a-z0-9-]+$/', (string)($ui_footer_action_consult_icon ?? '')) ? (string)$ui_footer_action_consult_icon : 'fa-magnifying-glass';
$afRegisterLabel = trim((string)($ui_footer_action_register_label ?? 'Crear cuenta')) ?: 'Crear cuenta';
$afRegisterIcon = preg_match('/^fa-[a-z0-9-]+$/', (string)($ui_footer_action_register_icon ?? '')) ? (string)$ui_footer_action_register_icon : 'fa-user-plus';
$afLoginLabel = trim((string)($ui_footer_action_login_label ?? 'Ingresar')) ?: 'Ingresar';
$afLoginIcon = preg_match('/^fa-[a-z0-9-]+$/', (string)($ui_footer_action_login_icon ?? '')) ? (string)$ui_footer_action_login_icon : 'fa-right-to-bracket';
?>
<style>
:root{--public-red:<?= af_public_e($afPublicButton) ?>;--public-red-dark:<?= af_public_e($afPublicButton) ?>;--public-header-bg:<?= af_public_e($afPublicHeaderBg) ?>;--public-header-text:<?= af_public_e($afPublicHeaderText) ?>;--public-icon:<?= af_public_e($afPublicIcons) ?>;--public-button-text:<?= af_public_e($afPublicButtonText) ?>}
.public-topbar{background:var(--public-header-bg)!important}.public-brand,.public-main-nav a,.public-action-secondary{color:var(--public-header-text)!important}.public-brand-copy small{color:color-mix(in srgb,var(--public-header-text) 62%,transparent)!important}.public-main-nav a i,.public-action-secondary i,.public-action-soft i{color:var(--public-icon)!important}.public-action-primary{background:var(--public-red)!important;color:var(--public-button-text)!important}.public-action-primary i{color:var(--public-button-text)!important}.public-topbar-inner.is-form-page{grid-template-columns:minmax(210px,1fr) auto!important}.public-topbar-inner.is-form-page .public-topbar-actions{grid-column:2;display:flex;gap:8px;flex-wrap:nowrap;justify-content:flex-end;align-items:center}.public-home-action{min-width:172px}.public-query-login-action{min-width:150px}.public-account-action{min-width:132px}.public-manual-action{min-width:116px}.public-session-identity{min-width:170px;max-width:225px;height:42px;display:flex;align-items:center;gap:9px;padding:5px 10px;border:1px solid #dbe4ef;border-radius:12px;background:color-mix(in srgb,var(--public-header-bg) 92%,#f8fafc);color:var(--public-header-text);box-shadow:0 6px 18px rgba(15,23,42,.05)}.public-session-identity>i{width:30px;height:30px;display:grid;place-items:center;flex:0 0 30px;border-radius:9px;background:color-mix(in srgb,var(--public-red) 10%,#fff);color:var(--public-red)}.public-session-identity>span{display:block;min-width:0;line-height:1.08}.public-session-identity strong,.public-session-identity small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.public-session-identity strong{font-size:10px;font-weight:900}.public-session-identity small{margin-top:4px;color:color-mix(in srgb,var(--public-header-text) 58%,transparent);font-size:8px;font-weight:750}.public-session-identity.is-account{max-width:245px}
@media(max-width:1180px){.public-session-identity{min-width:132px;max-width:158px}.public-home-action{min-width:44px}.public-home-action span{display:none}}
@media(max-width:930px){.public-session-identity{min-width:44px;max-width:112px;padding:5px 7px}.public-session-identity small{display:none}.public-session-identity strong{max-width:65px}.public-manual-action,.public-account-action{min-width:42px}.public-manual-action span,.public-account-action span{display:none}}
@media(max-width:760px){.public-home-action,.public-query-login-action,.public-account-action,.public-manual-action{min-width:40px}.public-topbar-inner.is-form-page .public-topbar-actions{gap:5px}.public-topbar-inner.is-form-page .public-action span{display:none}.public-session-identity{min-width:38px;max-width:90px;height:40px}.public-session-identity>i{width:28px;height:28px;flex-basis:28px}.public-session-identity strong{max-width:42px;font-size:8px}}
</style>
<header class="public-topbar" data-public-header>
    <div class="public-topbar-inner <?= $afPublicOnLanding ? '' : 'is-form-page' ?>">
        <a class="public-brand" href="index.php" aria-label="Ir al inicio de <?= af_public_e($afPublicBrand) ?>">
            <span class="public-brand-logo">
                <?php if ($afPublicLogo !== ''): ?>
                    <img src="<?= af_public_e($afPublicLogo) ?>" alt="Logo <?= af_public_e($afPublicBrand) ?>" onerror="this.style.display='none';this.parentElement.classList.add('is-fallback')">
                <?php endif; ?>
                <i class="fas fa-tv" aria-hidden="true"></i>
            </span>
            <span class="public-brand-copy">
                <strong><?= af_public_e($afPublicBrand) ?></strong>
                <small><?= af_public_e($afPublicSubtitle) ?></small>
            </span>
        </a>

        <?php if ($afPublicOnLanding): ?>
            <nav class="public-main-nav" aria-label="Navegación pública">
                <a href="#solucion"><i class="fas fa-diagram-project"></i><span>Solución</span></a>
                <a href="#plataformas"><i class="fas fa-layer-group"></i><span>Plataformas</span></a>
                <a href="#planes"><i class="fas fa-gem"></i><span>Planes</span></a>
            </nav>
            <div class="public-topbar-actions">
                <a class="public-action public-action-secondary" href="consulta.php" title="Consultar códigos"><i class="fas <?= af_public_e($afConsultIcon) ?>"></i><span><?= af_public_e($afConsultLabel) ?></span></a>
                <?php if ($afAdminSession): ?>
                    <a class="public-action public-action-primary" href="admin/index.php" title="Abrir panel administrativo"><i class="fas fa-gauge-high"></i><span>Panel</span></a>
                <?php elseif ($afConsultaSession && $afConsultaPanelUrl !== ''): ?>
                    <span class="public-session-identity <?= $afConsultaType === 'cuenta_unica' ? 'is-account' : '' ?>" title="<?= af_public_e($afSessionPrimary . ($afSessionSecondary !== '' ? ' · ' . $afSessionSecondary : '')) ?>"><i class="fas <?= af_public_e($afSessionIcon) ?>"></i><span><strong><?= af_public_e($afSessionPrimary) ?></strong><?php if ($afSessionSecondary !== ''): ?><small><?= af_public_e($afSessionSecondary) ?></small><?php endif; ?></span></span>
                    <a class="public-action public-action-soft public-manual-action" href="<?= af_public_e($afConsultaManualUrl) ?>" title="Abrir manual de uso"><i class="fas fa-book-open"></i><span>Manual</span></a>
                    <a class="public-action public-action-primary public-account-action" href="<?= af_public_e($afConsultaPanelUrl) ?>" title="Abrir <?= af_public_e(strtolower($afConsultaPanelLabel)) ?>"><i class="fas <?= af_public_e($afConsultaPanelIcon) ?>"></i><span><?= af_public_e($afConsultaPanelLabel) ?></span></a>
                    <a class="public-action public-action-secondary" href="logout_consulta.php" title="Cerrar sesión de consulta"><i class="fas fa-arrow-right-from-bracket"></i><span>Salir</span></a>
                <?php else: ?>
                    <a class="public-action public-action-soft" href="registro.php" title="Crear una cuenta"><i class="fas <?= af_public_e($afRegisterIcon) ?>"></i><span><?= af_public_e($afRegisterLabel) ?></span></a>
                    <a class="public-action public-action-primary" href="login.php" title="Ingresar al panel"><i class="fas <?= af_public_e($afLoginIcon) ?>"></i><span><?= af_public_e($afLoginLabel) ?></span></a>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <div class="public-topbar-actions">
                <a class="public-action public-action-secondary public-home-action" href="index.php" title="Ir a la página principal"><i class="fas fa-house"></i><span>Ir a página principal</span></a>
                <?php if ($afConsultaSession && $afConsultaPanelUrl !== ''): ?>
                    <span class="public-session-identity <?= $afConsultaType === 'cuenta_unica' ? 'is-account' : '' ?>" title="<?= af_public_e($afSessionPrimary . ($afSessionSecondary !== '' ? ' · ' . $afSessionSecondary : '')) ?>"><i class="fas <?= af_public_e($afSessionIcon) ?>"></i><span><strong><?= af_public_e($afSessionPrimary) ?></strong><?php if ($afSessionSecondary !== ''): ?><small><?= af_public_e($afSessionSecondary) ?></small><?php endif; ?></span></span>
                    <a class="public-action public-action-soft public-manual-action" href="<?= af_public_e($afConsultaManualUrl) ?>" title="Abrir manual de uso"><i class="fas fa-book-open"></i><span>Manual</span></a>
                    <a class="public-action public-action-primary public-account-action" href="<?= af_public_e($afConsultaPanelUrl) ?>" title="Abrir <?= af_public_e(strtolower($afConsultaPanelLabel)) ?>"><i class="fas <?= af_public_e($afConsultaPanelIcon) ?>"></i><span><?= af_public_e($afConsultaPanelLabel) ?></span></a>
                    <a class="public-action public-action-secondary" href="logout_consulta.php" title="Cerrar sesión de consulta"><i class="fas fa-arrow-right-from-bracket"></i><span>Salir</span></a>
                <?php elseif ($afPublicOnConsulta): ?>
                    <a class="public-action public-action-primary public-query-login-action js-consulta-login-link" href="login_consulta.php" title="Ingresar con ID de consulta o de cuenta"><i class="fas fa-key"></i><span>Login Consulta</span></a>
                <?php elseif ($afPublicOnConsultaLogin): ?>
                    <a class="public-action public-action-primary public-query-login-action" href="<?= af_public_e($afConsultaBackUrl) ?>" title="Volver a la consulta pública"><i class="fas fa-arrow-left"></i><span>Volver a consulta</span></a>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
</header>
