<?php
require_once __DIR__ . "/auth.php";

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

$panelIdentityPath = dirname(__DIR__) . "/api/panel_identity.json";
$panelName = "THEFULL TV";

if (is_file($panelIdentityPath)) {
    $panelIdentityRaw = @file_get_contents($panelIdentityPath);
    $panelIdentity = json_decode((string)$panelIdentityRaw, true);
    if (is_array($panelIdentity) && isset($panelIdentity["name"])) {
        $candidateName = trim((string)$panelIdentity["name"]);
        if ($candidateName !== "") {
            $panelName = $candidateName;
        }
    }
}

$panelLogoFile = dirname(__DIR__) . "/api/img/logo.png";
$panelLogoVersion = is_file($panelLogoFile) ? (string)filemtime($panelLogoFile) : (string)time();
$panelLogoUrl = $BASE_URL . "/api/img/logo.png?v=" . $panelLogoVersion;
?>

<!doctype html>
<html lang="pt-BR" class="color-sidebar">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" href="<?= $BASE_URL ?>/assets/images/favicon-32x32.png" type="image/png" />
    <!-- Plugins -->
    <link href="<?= $BASE_URL ?>/assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
    <link href="<?= $BASE_URL ?>/assets/plugins/perfect-scrollbar/css/perfect-scrollbar.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" />
    <!-- Loader -->
    <link href="<?= $BASE_URL ?>/assets/css/pace.min.css" rel="stylesheet" />
    <script src="<?= $BASE_URL ?>/assets/js/pace.min.js"></script>
    <!-- Bootstrap -->
    <link href="<?= $BASE_URL ?>/assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="<?= $BASE_URL ?>/assets/css/bootstrap-extended.css" rel="stylesheet">
    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <!-- Estilos originais -->
    <link href="<?= $BASE_URL ?>/assets/css/geral.css" rel="stylesheet">
    <link href="<?= $BASE_URL ?>/assets/css/icons.css" rel="stylesheet">
    <link rel="stylesheet" href="<?= $BASE_URL ?>/assets/css/tema-escuro.css" />
    <link rel="stylesheet" href="<?= $BASE_URL ?>/assets/css/semi-dark.css" />
    <link rel="stylesheet" href="<?= $BASE_URL ?>/assets/css/cores-do-menu.css" />
    <link rel="stylesheet" href="<?= $BASE_URL ?>/assets/css/apps_styles.css">
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-default/default.css" />
    <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>
    <!-- Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>

    <title><?= htmlspecialchars($panelName, ENT_QUOTES, "UTF-8") ?></title>
    <meta content="<?= htmlspecialchars($panelLogoUrl, ENT_QUOTES, "UTF-8") ?>" property="og:image" />

    <style>
        /* =====================================================
           TEMA VERDE PROFISSIONAL — SIDEBAR
        ====================================================== */
        :root {
            --green-50:  #eafaf1;
            --green-100: #c3efda;
            --green-200: #86efac;
            --green-400: #22c55e;
            --green-500: #16a34a;
            --green-600: #15803d;
            --green-700: #166534;
            --green-800: #14532d;
            --green-900: #052e16;

            --sidebar-bg:      #0d1f17;
            --sidebar-surface: #122a1e;
            --sidebar-hover:   #1a3d2b;
            --sidebar-active:  #1e4d35;

            --text-primary:   #e6faf0;
            --text-secondary: #86efac;
            --text-muted:     #4ade80;

            --border-color: #1e3a2a;
            --accent:       #22c55e;

            --font: 'Inter', system-ui, sans-serif;
        }

        /* Reset e base */
        *, *::before, *::after { box-sizing: border-box; }

        body {
            font-family: var(--font) !important;
            background: #0b1a12 !important;
            color: var(--text-secondary);
        }

        /* ---- Sidebar wrapper ---- */
        .sidebar-wrapper {
            background: var(--sidebar-bg) !important;
            border-right: 1px solid var(--border-color) !important;
        }

        /* ---- Header do logo ---- */
        .sidebar-header {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 20px 18px 16px;
            border-bottom: 1px solid var(--border-color) !important;
            background: var(--sidebar-bg) !important;
        }
        .sidebar-header .logo-icon {
            width: 36px;
            height: 36px;
            border-radius: 10px;
            background: linear-gradient(135deg, var(--green-500), var(--green-700));
        }
        .sidebar-header .logo-text {
            font-size: 15px !important;
            font-weight: 600 !important;
            color: var(--text-primary) !important;
            letter-spacing: 0.3px;
        }
        .sidebar-header .toggle-icon i {
            color: var(--text-muted) !important;
            transition: color 0.2s;
        }
        .sidebar-header .toggle-icon:hover i {
            color: var(--accent) !important;
        }

        /* ---- Créditos ---- */
        #creditos-badge {
            margin: 12px 14px 0;
            padding: 8px 12px;
            background: var(--sidebar-surface);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 12px;
            color: var(--text-muted);
        }
        #creditos-badge span:last-child {
            font-weight: 600;
            color: var(--accent);
            font-size: 13px;
        }

        /* ---- MetisMenu / navegação ---- */
        .metismenu { padding: 8px 0 !important; }

        .menu-label {
            font-size: 10px !important;
            font-weight: 600 !important;
            color: var(--text-muted) !important;
            letter-spacing: 1px !important;
            text-transform: uppercase !important;
            padding: 14px 20px 5px !important;
        }

        /* Links de nível 1 */
        .metismenu > li > a {
            display: flex !important;
            align-items: center !important;
            gap: 10px !important;
            margin: 1px 10px !important;
            padding: 9px 10px !important;
            border-radius: 8px !important;
            color: var(--text-secondary) !important;
            transition: background 0.18s, color 0.18s !important;
            text-decoration: none !important;
            font-size: 13.5px !important;
        }
        .metismenu > li > a:hover {
            background: var(--sidebar-hover) !important;
            color: var(--text-primary) !important;
        }
        .metismenu > li.mm-active > a,
        .metismenu > li > a.active {
            background: var(--sidebar-active) !important;
            color: var(--accent) !important;
        }

        /* Ícones pai */
        .parent-icon i {
            font-size: 18px !important;
            color: var(--text-secondary) !important;
            transition: color 0.18s;
        }
        .metismenu > li > a:hover .parent-icon i,
        .metismenu > li.mm-active > a .parent-icon i {
            color: var(--accent) !important;
        }
        .parent-icon {
            width: 30px !important;
            height: 30px !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            background: var(--sidebar-surface) !important;
            border-radius: 7px !important;
            flex-shrink: 0;
        }
        .metismenu > li.mm-active > a .parent-icon,
        .metismenu > li > a:hover .parent-icon {
            background: rgba(34,197,94,.15) !important;
        }

        /* Texto do menu */
        .menu-title {
            color: inherit !important;
            font-size: 13.5px !important;
            font-weight: 400 !important;
        }

        /* Arrow */
        .metismenu .has-arrow::after {
            border-color: var(--text-muted) !important;
            right: 12px !important;
        }

        /* Submenu */
        .metismenu ul {
            background: transparent !important;
            padding-left: 44px !important;
        }
        .metismenu ul a {
            padding: 7px 10px !important;
            border-radius: 7px !important;
            color: var(--text-muted) !important;
            font-size: 12.5px !important;
            margin: 1px 10px 1px 0 !important;
            transition: background 0.15s, color 0.15s !important;
        }
        .metismenu ul a i {
            color: var(--green-600) !important;
            font-size: 14px !important;
        }
        .metismenu ul a:hover {
            background: var(--sidebar-hover) !important;
            color: var(--text-primary) !important;
        }

        /* ---- Item "Servidores" — destaque SÓ quando página ativa ---- */
        .nav-servidores > a {
            color: var(--text-secondary) !important;
        }
        .nav-servidores.mm-active > a {
            background: rgba(34,197,94,.12) !important;
            border: 1px solid rgba(34,197,94,.25) !important;
            color: var(--accent) !important;
        }
        .nav-servidores.mm-active > a .parent-icon {
            background: rgba(34,197,94,.18) !important;
        }
        .nav-servidores.mm-active > a .parent-icon i {
            color: var(--accent) !important;
        }

        /* ---- Divisor ---- */
        .sidebar-divider-green {
            height: 1px;
            background: var(--border-color);
            margin: 6px 14px;
        }

        /* ---- Header / Topbar ---- */
        header .topbar {
            background: #0d1f17 !important;
            border-bottom: 1px solid var(--border-color) !important;
            padding: 0 20px !important;
        }
        header .topbar .navbar {
            background: transparent !important;
        }
        .mobile-toggle-menu i {
            color: var(--text-secondary) !important;
            font-size: 22px;
        }

        /* Marquee */
        .marquee {
            overflow: hidden;
            flex: 1;
            margin: 0 20px;
        }
        .marquee-content span {
            display: inline-block;
            white-space: nowrap;
            animation: marquee-scroll 20s linear infinite;
            font-size: 12.5px;
            font-weight: 500;
            color: var(--text-muted) !important;
            letter-spacing: 0.5px;
        }
        @keyframes marquee-scroll {
            0%   { transform: translateX(100%); }
            100% { transform: translateX(-100%); }
        }

        /* Botões da topbar */
        .top-menu .nav-link {
            color: var(--text-secondary) !important;
        }
        .top-menu .nav-link:hover {
            color: var(--accent) !important;
        }

        /* ---- Page wrapper ---- */
        .page-wrapper {
            background: #0b1a12 !important;
        }
        .page-content {
            background: #0b1a12 !important;
        }

        /* ---- Scrollbar ---- */
        .sidebar-wrapper ::-webkit-scrollbar { width: 4px; }
        .sidebar-wrapper ::-webkit-scrollbar-track { background: var(--sidebar-bg); }
        .sidebar-wrapper ::-webkit-scrollbar-thumb { background: var(--green-700); border-radius: 4px; }

        /* ---- Desktop: sidebar recolhida (toggle) ---- */
        @media (min-width: 769px) {
            .wrapper.toggled .sidebar-wrapper {
                width: 70px !important;
            }
            .wrapper.toggled .sidebar-wrapper .logo-text,
            .wrapper.toggled .sidebar-wrapper .menu-title,
            .wrapper.toggled .sidebar-wrapper .menu-label,
            .wrapper.toggled .sidebar-wrapper #creditos-badge {
                display: none !important;
            }
            .wrapper.toggled .sidebar-wrapper .metismenu > li > a {
                justify-content: center !important;
                padding: 10px !important;
            }
            .wrapper.toggled .sidebar-wrapper .parent-icon {
                width: 34px !important;
                height: 34px !important;
            }
        }

        /* ---- Mobile: overlay ---- */
        @media (max-width: 768px) {
            header .topbar {
                position: fixed !important;
                top: 0; left: 0; right: 0;
                z-index: 1000;
                height: 56px !important;
                padding: 0 16px !important;
            }
            .mobile-toggle-menu {
                display: flex !important;
                align-items: center;
                cursor: pointer;
            }
            .mobile-toggle-menu i {
                font-size: 24px !important;
                color: var(--accent) !important;
            }
            .page-wrapper {
                margin-left: 0 !important;
                padding-top: 56px !important;
            }
            .sidebar-wrapper {
                position: fixed !important;
                top: 0; left: 0;
                height: 100vh !important;
                width: 280px !important;
                z-index: 1100 !important;
                transform: translateX(-100%) !important;
                transition: transform 0.28s cubic-bezier(.4,0,.2,1) !important;
                overflow-y: auto !important;
            }
            .wrapper.mobile-open .sidebar-wrapper {
                transform: translateX(0) !important;
                box-shadow: 4px 0 24px rgba(0,0,0,.6) !important;
            }
            .sidebar-overlay {
                display: none;
                position: fixed;
                inset: 0;
                background: rgba(0,0,0,.55);
                z-index: 1099;
            }
            .wrapper.mobile-open .sidebar-overlay {
                display: block;
            }
            .sidebar-header .toggle-icon {
                display: none !important;
            }
            .sidebar-close-btn {
                display: flex !important;
            }
        }

        @media (min-width: 769px) {
            .sidebar-overlay { display: none !important; }
            .sidebar-close-btn { display: none !important; }
        }

        .sidebar-close-btn {
            display: none;
            margin-left: auto;
            width: 32px; height: 32px;
            border: none;
            background: var(--sidebar-surface);
            border-radius: 8px;
            cursor: pointer;
            color: var(--text-muted);
            font-size: 20px;
            align-items: center;
            justify-content: center;
            transition: background .2s, color .2s;
        }
        .sidebar-close-btn:hover {
            background: #3f1010;
            color: #f87171;
        }
    </style>
</head>

<body>
    <div class="wrapper">

        <!-- Overlay mobile -->
        <div class="sidebar-overlay" id="sidebarOverlay"></div>

        <!-- ======== SIDEBAR ======== -->
        <div class="sidebar-wrapper" data-simplebar="true">
            <div class="sidebar-header">
                <div>
                    <img src="<?= htmlspecialchars($panelLogoUrl, ENT_QUOTES, "UTF-8") ?>" class="logo-icon" alt="logo">
                </div>
                <div>
                    <h4 class="logo-text"><?= htmlspecialchars($panelName, ENT_QUOTES, "UTF-8") ?></h4>
                </div>
                <div class="toggle-icon ms-auto"><i class='bx bx-menu'></i></div>
                <button class="sidebar-close-btn" id="sidebarCloseBtn" title="Fechar menu"><i class='bx bx-x'></i></button>
            </div>

            <?php if (!is_null($creditos)) : ?>
            <div id="creditos-badge">
                <span>Créditos</span>
                <span><?= $creditos ?></span>
            </div>
            <?php endif; ?>

            <ul class="metismenu" id="menu">

                <!-- PRINCIPAL -->
                <li class="menu-label">Principal</li>
                <li>
                    <a href="<?= $BASE_URL ?>/dashboard.php">
                        <div class="parent-icon"><i class='bx bxs-dashboard'></i></div>
                        <div class="menu-title">Início</div>
                    </a>
                </li>

                <!-- CLIENTES -->
                <li>
                    <a href="javascript:;" class="has-arrow">
                        <div class="parent-icon"><i class='bx bx-user-circle'></i></div>
                        <div class="menu-title">Clientes</div>
                    </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>
                        <?php if ($nivel_admin == 1) { ?>
                        <li><a href="<?= $BASE_URL ?>/onlines.php"><i class='bx bx-right-arrow-alt'></i> Onlines</a></li>
                        <?php } ?>
                    </ul>
                </li>

                <!-- SERVIDORES — ativo somente na página dns.php -->
                <?php
                $paginaAtual = basename($_SERVER['PHP_SELF']);
                $servidoresAtivo = ($paginaAtual === 'dns.php') ? 'nav-servidores mm-active' : 'nav-servidores';
                ?>
                <li class="<?= $servidoresAtivo ?>">
                    <a href="<?= $BASE_URL ?>/dns.php">
                        <div class="parent-icon"><i class='bx bx-server'></i></div>
                        <div class="menu-title">Servidores</div>
                    </a>
                </li>

                <?php if ($nivel_admin == 1) { ?>

                <!-- MENSAGEM GLOBAL -->
                <li>
                    <a href="<?= $BASE_URL ?>/mensagem_remota.php">
                        <div class="parent-icon"><i class='bx bx-message-rounded-dots'></i></div>
                        <div class="menu-title">Mensagem Global</div>
                    </a>
                </li>

                <!-- VENCIMENTOS -->
                <li>
                    <a href="<?= $BASE_URL ?>/vencimentos.php">
                        <div class="parent-icon"><i class='bx bx-calendar-exclamation'></i></div>
                        <div class="menu-title">Vencimentos</div>
                    </a>
                </li>

                <!-- APLICATIVO -->
                <li class="menu-label">Aplicativo</li>
                <li>
                    <a href="javascript:;" class="has-arrow">
                        <div class="parent-icon"><i class='bx bx-palette'></i></div>
                        <div class="menu-title">Ajustes</div>
                    </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 ?>/bloqueio.php"><i class='bx bx-right-arrow-alt'></i> Tela de Bloqueio</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 ?>/login_fundo.php"><i class='bx bx-right-arrow-alt'></i> Fundo do Login</a></li>
                    </ul>
                </li>

                <!-- CONFIGURAÇÕES -->
                <li class="menu-label">Configurações</li>
                <li>
                    <a href="javascript:;" class="has-arrow">
                        <div class="parent-icon"><i class='bx bx-cog'></i></div>
                        <div class="menu-title">Sistema</div>
                    </a>
                    <ul>
                        <li><a href="<?= $BASE_URL ?>/dns.php"><i class='bx bx-right-arrow-alt'></i> Trocar DNS</a></li>
                        <li><a href="<?= $BASE_URL ?>/teste.php"><i class='bx bx-right-arrow-alt'></i> Teste Auto</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 ?>/emuladores.php">
                        <div class="parent-icon"><i class='bx bx-joystick'></i></div>
                        <div class="menu-title">Emuladores</div>
                    </a>
                </li>

                <?php } ?>

                <!-- CONTA -->
                <li class="menu-label">Conta</li>
                <li>
                    <a href="<?= $BASE_URL ?>/usuario.php">
                        <div class="parent-icon"><i class='bx bx-user'></i></div>
                        <div class="menu-title">Perfil</div>
                    </a>
                </li>

                <?php if ($nivel_admin == 1) { ?>
                <li>
                    <a href="<?= $BASE_URL ?>/whatsapp_chatbot.php">
                        <div class="parent-icon"><i class='bxl-whatsapp bx'></i></div>
                        <div class="menu-title">Chatbot</div>
                    </a>
                </li>
                <?php } ?>

                <li>
                    <a href="<?= $BASE_URL ?>/sair.php">
                        <div class="parent-icon"><i class='bx bx-exit'></i></div>
                        <div class="menu-title">Sair</div>
                    </a>
                </li>

            </ul>
        </div>
        <!-- ======== FIM SIDEBAR ======== -->

        <!-- ======== HEADER / TOPBAR ======== -->
        <header>
            <div class="topbar d-flex align-items-center">
                <nav class="navbar navbar-expand">
                    <div class="mobile-toggle-menu"><i class='bx bx-menu'></i></div>

                    <div class="marquee">
                        <div class="marquee-content">
                            <span id="vencimento-text"></span>
                        </div>
                    </div>

                    <div class="top-menu ms-auto">
                        <ul class="navbar-nav align-items-center">
                            <li class="nav-item dropdown dropdown-large">
                                <a class="nav-link dropdown-toggle dropdown-toggle-nocaret" href="#"
                                   role="button" data-bs-toggle="dropdown" aria-expanded="false">
                                    <i class='bx bx-category'></i>
                                </a>
                                <div class="dropdown-menu dropdown-menu-end">
                                    <div class="row row-cols-3 g-3 p-3"></div>
                                </div>
                            </li>
                        </ul>
                    </div>
                </nav>
            </div>
        </header>
        <!-- ======== FIM HEADER ======== -->

        <!-- Scripts -->
        <script>
        document.addEventListener("DOMContentLoaded", function () {
            var vencimentoText = document.getElementById('vencimento-text');
            <?php
            $tipoUser    = (string)($_SESSION["tipo_user"] ?? "");
            $isAdminHeader = ($tipoUser === "admin" || $nivel_admin == 1);
            if ($isAdminHeader) {
                echo 'vencimentoText.innerHTML = "";';
            } else {
                if (!empty($vencimento)) {
                    $dataAtual     = new DateTime();
                    $dataVencimento = new DateTime($vencimento);
                    $diasRestantes  = (int)$dataAtual->diff($dataVencimento)->format('%r%a');
                    if ($diasRestantes <= 0) {
                        echo 'vencimentoText.innerHTML = "⚠ SEU PAINEL REVENDA ESTÁ VENCIDO!";';
                    } else {
                        echo 'vencimentoText.innerHTML = "PAINEL REVENDA VENCE EM ' . $diasRestantes . ' DIAS!";';
                    }
                } else {
                    echo 'vencimentoText.innerHTML = "Vencimento da revenda não definido.";';
                }
            }
            ?>
        });
        </script>

        <script>
        document.addEventListener("DOMContentLoaded", function () {
            const wrapper       = document.querySelector(".wrapper");
            const sidebarToggle = document.querySelector(".toggle-icon");
            const mobileToggle  = document.querySelector(".mobile-toggle-menu");
            const overlay       = document.getElementById("sidebarOverlay");
            const closeBtn      = document.getElementById("sidebarCloseBtn");

            function isMobile() { return window.innerWidth <= 768; }

            function openMobileSidebar() {
                if (!wrapper) return;
                wrapper.classList.add("mobile-open");
                document.body.style.overflow = "hidden";
            }
            function closeMobileSidebar() {
                if (!wrapper) return;
                wrapper.classList.remove("mobile-open");
                document.body.style.overflow = "";
            }
            function toggleDesktop() {
                if (!wrapper) return;
                wrapper.classList.toggle("toggled");
            }

            if (sidebarToggle) {
                sidebarToggle.addEventListener("click", function (e) {
                    e.preventDefault();
                    if (isMobile()) openMobileSidebar();
                    else toggleDesktop();
                });
            }
            if (mobileToggle) {
                mobileToggle.addEventListener("click", function (e) {
                    e.preventDefault();
                    if (isMobile()) openMobileSidebar();
                    else toggleDesktop();
                });
            }
            if (overlay)  overlay.addEventListener("click",  closeMobileSidebar);
            if (closeBtn) closeBtn.addEventListener("click", closeMobileSidebar);

            window.addEventListener("resize", function () {
                if (!isMobile()) closeMobileSidebar();
            });
        });
        </script>

        <script>
        $(document).ready(function () { $('#menu').metisMenu(); });
        </script>

        <!-- ======== CONTEÚDO DA PÁGINA ABAIXO ======== -->
        <div class="page-wrapper">
            <div class="page-content">
                <!-- Conteúdo da página aqui -->