<?php
declare(strict_types=1);

if (!headers_sent()) {
    header('X-Content-Type-Options: nosniff');
    header('X-Frame-Options: SAMEORIGIN');
    header('Referrer-Policy: strict-origin-when-cross-origin');
    header('Permissions-Policy: geolocation=(), microphone=(), camera=()');
}

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/page_assets.php';

$scriptName = str_replace('\\', '/', (string)($_SERVER['SCRIPT_NAME'] ?? ''));
$basePath = preg_replace('#/controllers/[^/]+\.php$#', '', $scriptName);
$basePath = preg_replace('#/[^/]+\.php$#', '', (string)$basePath);
$basePath = rtrim((string)$basePath, '/');
$BASE_URL = $basePath === '' ? '' : $basePath;

$panelIdentityPath = dirname(__DIR__) . '/api/panel_identity.json';
$panelName = 'THEFULL TV';
if (is_file($panelIdentityPath)) {
    $panelIdentity = json_decode((string)@file_get_contents($panelIdentityPath), true);
    if (is_array($panelIdentity)) {
        $candidateName = trim((string)($panelIdentity['name'] ?? ''));
        if ($candidateName !== '') {
            $panelName = $candidateName;
        }
    }
}

require_once __DIR__ . '/branding.php';
$headerOwnerType = $isRev ? 'revendedor' : 'admin';
$headerOwnerId = $isRev ? (int)($_SESSION['revendedor_id'] ?? 0) : 0;
$brandingDb = (isset($db) && $db instanceof PDO)
    ? $db
    : ((isset($pdo) && $pdo instanceof PDO) ? $pdo : ($db ?? null));
$panelLogoUrl = branding_logo_url($brandingDb, $headerOwnerType, $headerOwnerId);
if ($panelLogoUrl === '') {
    $panelLogoUrl = $BASE_URL . '/assets/images/profile-placeholder.svg';
}

$requestPath = (string)(parse_url((string)($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH) ?? '');
$currentPage = strtolower((string)pathinfo(basename($requestPath), PATHINFO_FILENAME));
if ($currentPage === '' || $currentPage === 'controllers') {
    $currentPage = strtolower((string)pathinfo(basename($scriptName), PATHINFO_FILENAME));
}
if ($currentPage === '') {
    $currentPage = 'dashboard';
}

$pageMetaMap = [
    'dashboard' => ['Visão geral', 'Acompanhe clientes, acessos e atividades do painel.', 'bx-grid-alt'],
    'users' => ['Clientes', 'Gerencie acessos, dispositivos e assinaturas.', 'bx-user-circle'],
    'users_create' => ['Novo cliente', 'Cadastre um novo acesso de forma rápida.', 'bx-user-plus'],
    'onlines' => ['Usuários online', 'Veja quem está conectado e o conteúdo em reprodução.', 'bx-broadcast'],
    'revendas' => ['Revendas', 'Controle contas, limites e clientes das revendas.', 'bx-store-alt'],
    'revendas_criar' => ['Nova revenda', 'Crie e configure uma nova conta de revenda.', 'bx-store'],
    'revendas_clientes' => ['Clientes da revenda', 'Visualize os clientes vinculados à revenda.', 'bx-group'],
    'dns' => ['Servidores DNS', 'Cadastre e organize os servidores disponíveis.', 'bx-globe'],
    'migrar_dns' => ['Migrar DNS', 'Troque o servidor dos clientes selecionados.', 'bx-transfer-alt'],
    'teste' => ['Teste automático', 'Configure a geração de testes para novos clientes.', 'bx-bolt-circle'],
    'qrcode' => ['QR Code', 'Atualize o QR Code exibido nos aplicativos.', 'bx-qr'],
    'logo' => ['Identidade visual', 'Atualize a marca exibida no painel e nos aplicativos.', 'bx-image-alt'],
    'mensagem_remota' => ['Mensagem global', 'Envie avisos e mensagens para os dispositivos.', 'bx-message-square-detail'],
    'vencimentos' => ['Vencimentos', 'Configure regras e avisos de vencimento.', 'bx-calendar-exclamation'],
    'atualizacao' => ['Atualizações', 'Gerencie versões e arquivos de atualização dos aplicativos.', 'bx-cloud-upload'],
    'config' => ['Login do aplicativo', 'Defina o modo de autenticação usado pelos aplicativos.', 'bx-log-in-circle'],
    'configuracoes_gerais' => ['Configurações', 'Gerencie idioma, TMDB e a API da aba Esportes.', 'bx-slider-alt'],
    'app_' => ['Integração da API', 'Consulte as configurações seguras de integração.', 'bx-code-curly'],
    'emuladores' => ['Emuladores e ROMs', 'Gerencie jogos retrô e arquivos disponíveis.', 'bx-joystick'],
    'p2p' => ['Configuração P2P', 'Escolha o motor e configure as credenciais P2P.', 'bx-network-chart'],
    'usuario' => ['Meu perfil', 'Atualize os dados da sua conta e sua senha.', 'bx-user'],
    'whatsapp_chatbot' => ['WhatsApp e chatbot', 'Configure automações, conexão e mensagens.', 'bxl-whatsapp'],
    'tema' => ['Tema do aplicativo', 'Consulte a configuração visual ativa.', 'bx-paint'],
];
$pageMeta = $pageMetaMap[$currentPage] ?? ['Painel administrativo', 'Gerencie as configurações do sistema.', 'bx-layer'];
$pageTitle = (string)$pageMeta[0];
$pageSubtitle = (string)$pageMeta[1];
$pageIcon = (string)$pageMeta[2];

$userDisplayName = trim((string)($name_header ?? $username ?? 'Usuário'));
if ($userDisplayName === '') {
    $userDisplayName = $isRev ? 'Revendedor' : 'Administrador';
}
$userInitial = mb_strtoupper(mb_substr($userDisplayName, 0, 1, 'UTF-8'), 'UTF-8');
$userRoleLabel = $isRev ? 'Revendedor' : 'Administrador';
$assetVersion = static function (string $relativePath): int {
    $fullPath = dirname(__DIR__) . '/' . ltrim($relativePath, '/');
    return is_file($fullPath) ? (int)@filemtime($fullPath) : time();
};
?>
<!doctype html>
<html lang="pt-BR" class="panel-html color-sidebar">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
    <meta name="theme-color" content="#070b12">
    <meta name="color-scheme" content="dark">
    <title><?= htmlspecialchars($pageTitle . ' • ' . $panelName, ENT_QUOTES, 'UTF-8') ?></title>
    <meta property="og:image" content="<?= htmlspecialchars($panelLogoUrl, ENT_QUOTES, 'UTF-8') ?>">

    <link rel="icon" href="<?= htmlspecialchars($panelLogoUrl, ENT_QUOTES, 'UTF-8') ?>" type="image/png">
    <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://unpkg.com/boxicons@2.1.4/css/boxicons.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <link href="<?= $BASE_URL ?>/assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="<?= $BASE_URL ?>/assets/css/bootstrap-extended.css" rel="stylesheet">
    <link href="<?= $BASE_URL ?>/assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="<?= $BASE_URL ?>/assets/css/geral.css?v=<?= $assetVersion('assets/css/geral.css') ?>" rel="stylesheet">
    <link href="<?= $BASE_URL ?>/assets/css/icons.css?v=<?= $assetVersion('assets/css/icons.css') ?>" rel="stylesheet">
    <link href="<?= $BASE_URL ?>/assets/css/apps_styles.css?v=<?= $assetVersion('assets/css/apps_styles.css') ?>" rel="stylesheet">
    <link href="<?= $BASE_URL ?>/assets/css/panel-modern.css?v=<?= $assetVersion('assets/css/panel-modern.css') ?>" rel="stylesheet">
    <link href="<?= $BASE_URL ?>/assets/css/panel-sidebar-legacy.css?v=<?= $assetVersion('assets/css/panel-sidebar-legacy.css') ?>" rel="stylesheet">
    <?php $pageCssAsset = panel_page_asset('css', $currentPage, $BASE_URL); ?>
    <?php if ($pageCssAsset !== null): ?>
        <link href="<?= htmlspecialchars($pageCssAsset['url'], ENT_QUOTES, 'UTF-8') ?>?v=<?= (int)$pageCssAsset['version'] ?>" rel="stylesheet">
    <?php endif; ?>
    <link href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-default/default.css" rel="stylesheet">
    <link href="<?= $BASE_URL ?>/assets/css/panel-modern-overrides.css?v=<?= $assetVersion('assets/css/panel-modern-overrides.css') ?>" rel="stylesheet">

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
</head>
<body class="panel-modern" data-page="<?= htmlspecialchars($currentPage, ENT_QUOTES, 'UTF-8') ?>">
<div class="wrapper">
    <aside class="sidebar-wrapper" aria-label="Menu principal">
        <div class="sidebar-header">
            <div class="legacy-logo-wrap">
                <img src="<?= htmlspecialchars($panelLogoUrl, ENT_QUOTES, 'UTF-8') ?>" class="logo-icon" alt="Logo <?= htmlspecialchars($panelName, ENT_QUOTES, 'UTF-8') ?>" data-fallback-src="<?= htmlspecialchars($BASE_URL . '/assets/images/profile-placeholder.svg', ENT_QUOTES, 'UTF-8') ?>">
            </div>
            <div class="legacy-logo-copy">
                <h4 class="logo-text"><?= htmlspecialchars($panelName, ENT_QUOTES, 'UTF-8') ?></h4>
            </div>
            <button type="button" class="toggle-icon ms-auto" aria-label="Abrir ou recolher menu"><i class="bx bx-menu"></i></button>
        </div>

        <nav class="sidebar-nav">
            <ul class="metismenu" id="menu">
                <?php if ($creditos !== null): ?>
                    <li class="legacy-credit-row"><small>CRÉDITOS: (<?= (int)$creditos ?>)</small></li>
                <?php endif; ?>
                <li class="menu-label">Principal</li>
                <li><a href="<?= $BASE_URL ?>/dashboard.php"><span class="parent-icon"><i class="bx bxs-dashboard"></i></span><span class="menu-title">Início</span></a></li>

                <li>
                    <a href="javascript:;" class="has-arrow"><span class="parent-icon"><i class="bx bx-user-circle"></i></span><span class="menu-title">Clientes</span></a>
                    <ul>
                        <li><a href="<?= $BASE_URL ?>/users.php"><i class="bx bx-right-arrow-alt"></i>Todos clientes</a></li>
                        <li><a href="<?= $BASE_URL ?>/users_create.php"><i class="bx bx-right-arrow-alt"></i>Criar cliente</a></li>
                        <li><a href="<?= $BASE_URL ?>/onlines.php"><i class="bx bx-right-arrow-alt"></i>Onlines</a></li>
                    </ul>
                </li>

                <?php if ($nivel_admin === 1): ?>
                    <li class="menu-label">Revendas</li>
                    <li>
                        <a href="javascript:;" class="has-arrow"><span class="parent-icon"><i class="bx bx-store-alt"></i></span><span class="menu-title">Revendas</span></a>
                        <ul>
                            <li><a href="<?= $BASE_URL ?>/revendas.php"><i class="bx bx-right-arrow-alt"></i>Todas as revendas</a></li>
                            <li><a href="<?= $BASE_URL ?>/revendas_criar.php"><i class="bx bx-right-arrow-alt"></i>Criar revenda</a></li>
                        </ul>
                    </li>
                <?php endif; ?>

                <?php if ($isRev): ?>
                    <li class="menu-label">Minha revenda</li>
                    <li><a href="<?= $BASE_URL ?>/logo.php"><span class="parent-icon"><i class="bx bx-image-alt"></i></span><span class="menu-title">Minha logo</span></a></li>
                    <li><a href="<?= $BASE_URL ?>/dns.php"><span class="parent-icon"><i class="bx bx-globe"></i></span><span class="menu-title">Meus DNS</span></a></li>
                <?php endif; ?>

                <?php if ($nivel_admin === 1): ?>
                    <li class="menu-label">Aplicativo</li>
                    <li>
                        <a href="javascript:;" class="has-arrow"><span class="parent-icon"><i class="bx bx-palette"></i></span><span class="menu-title">Ajustes</span></a>
                        <ul>
                           
                            <li><a href="<?= $BASE_URL ?>/qrcode.php"><i class="bx bx-right-arrow-alt"></i>QR Code</a></li>
                            
                            <li><a href="<?= $BASE_URL ?>/logo.php"><i class="bx bx-right-arrow-alt"></i>Logotipo</a></li>
                        
                            <li><a href="<?= $BASE_URL ?>/mensagem_remota.php"><i class="bx bx-right-arrow-alt"></i>Mensagem global</a></li>
                            <li><a href="<?= $BASE_URL ?>/vencimentos.php"><i class="bx bx-right-arrow-alt"></i>Vencimentos</a></li>
                            <li><a href="<?= $BASE_URL ?>/atualizacao.php"><i class="bx bx-right-arrow-alt"></i>Atualização</a></li>
                        </ul>
                    </li>

                    <li class="menu-label">Sistema</li>
                    <li>
                        <a href="javascript:;" class="has-arrow"><span class="parent-icon"><i class="bx bx-cog"></i></span><span class="menu-title">Configurações</span></a>
                        <ul>
                            <li><a href="<?= $BASE_URL ?>/configuracoes_gerais.php"><i class="bx bx-right-arrow-alt"></i>Configurações</a></li>
                            <li><a href="<?= $BASE_URL ?>/dns.php"><i class="bx bx-right-arrow-alt"></i>Servidores DNS</a></li>
                            <li><a href="<?= $BASE_URL ?>/teste.php"><i class="bx bx-right-arrow-alt"></i>Teste automático</a></li>
                         
                            <li><a href="<?= $BASE_URL ?>/emuladores.php"><i class="bx bx-right-arrow-alt"></i>Emuladores</a></li>
                               <li><a href="<?= $BASE_URL ?>/p2p.php"><i class="bx bx-right-arrow-alt"></i>P2P</a></li>
                            <li><a href="<?= $BASE_URL ?>/app_.php"><i class="bx bx-right-arrow-alt"></i>API</a></li>
                          
                        </ul>
                    </li>
                
                    <li><a href="<?= $BASE_URL ?>/whatsapp_chatbot.php"><span class="parent-icon"><i class="bx bxl-whatsapp"></i></span><span class="menu-title">Chatbot</span></a></li>
                <?php endif; ?>

                <li class="menu-label">Conta</li>
                <li><a href="<?= $BASE_URL ?>/usuario.php"><span class="parent-icon"><i class="bx bx-user"></i></span><span class="menu-title">Meu perfil</span></a></li>
                <li><a href="<?= $BASE_URL ?>/sair.php" class="logout-link"><span class="parent-icon"><i class="bx bx-log-out"></i></span><span class="menu-title">Sair</span></a></li>
            </ul>
        </nav>
    </aside>

    <header class="topbar">
        <nav class="navbar navbar-expand">
            <button type="button" class="mobile-toggle-menu" aria-label="Abrir menu"><i class="bx bx-menu"></i></button>
            <div class="topbar-page-context">
                <span class="topbar-page-icon"><i class="bx <?= htmlspecialchars($pageIcon, ENT_QUOTES, 'UTF-8') ?>"></i></span>
                <span class="topbar-page-copy">
                    <strong><?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?></strong>
                    <small><?= htmlspecialchars($pageSubtitle, ENT_QUOTES, 'UTF-8') ?></small>
                </span>
            </div>
            <div class="topbar-actions ms-auto">
                <?php if ($isRev && !empty($vencimento)): ?>
                    <span class="topbar-status d-none d-xl-inline-flex"><i class="bx bx-calendar-check"></i>Vence em <?= htmlspecialchars(date('d/m/Y', strtotime((string)$vencimento)), ENT_QUOTES, 'UTF-8') ?></span>
                <?php else: ?>
                 
                <?php endif; ?>
                
                <a class="topbar-profile" href="<?= $BASE_URL ?>/usuario.php" title="Abrir meu perfil">
                    <span class="topbar-avatar"><?= htmlspecialchars($userInitial, ENT_QUOTES, 'UTF-8') ?></span>
                    <span class="topbar-profile-copy d-none d-sm-flex"><strong><?= htmlspecialchars($userDisplayName, ENT_QUOTES, 'UTF-8') ?></strong><small><?= htmlspecialchars($userRoleLabel, ENT_QUOTES, 'UTF-8') ?></small></span>
                </a>
            </div>
        </nav>
    </header>

    <div class="page-wrapper">
        <main class="page-content" id="mainContent">
            <div class="mobile-page-heading d-lg-none">
                <span class="mobile-page-icon"><i class="bx <?= htmlspecialchars($pageIcon, ENT_QUOTES, 'UTF-8') ?>"></i></span>
                <span><strong><?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?></strong><small><?= htmlspecialchars($pageSubtitle, ENT_QUOTES, 'UTF-8') ?></small></span>
            </div>
