<?php
session_start();
require_once 'config.php'; 

$pdo = getConexaoAtiva(); // Banco Principal
$pdo_int = getConexaoInterna(); // Banco Local (Onde ficam as configurações)

$pdo->exec("SET NAMES utf8mb4");
$pdo_int->exec("SET NAMES utf8mb4");

// --- SEGURANÇA E PERSONALIZAÇÃO ---
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }

$role = $_SESSION['user_role'] ?? 'reseller'; 
$nome_usuario = $_SESSION['username'] ?? 'Usuário';
$user_id_logado = $_SESSION['user_id'];

// Só admin acessa esta página
if ($role !== 'admin') { header("Location: dashboard.php"); exit; }

// =========================================================================
// AUTO-CRIAÇÃO DA COLUNA NO BANCO INTERNO E AJUSTE DE ESTRUTURA
// =========================================================================
try {
    $pdo_int->exec("CREATE TABLE IF NOT EXISTS `custom_settings` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `name` varchar(255) NOT NULL,
        `value` text DEFAULT NULL,
        PRIMARY KEY (`id`),
        UNIQUE KEY `name` (`name`)
    )");
    
    // Garante que a linha do link_mode exista para o ssiptv ler
    $stmt_chk = $pdo_int->query("SELECT id FROM custom_settings WHERE name = 'link_mode'");
    if (!$stmt_chk->fetch()) {
        $pdo_int->exec("INSERT INTO custom_settings (name, value) VALUES ('link_mode', '0')");
    }
} catch (Exception $e) {}

$nome_painel = 'TOP IPTV';
$logo_url = '';
$cor_primaria = '#007bff';

try {
    $config_painel = $pdo_int->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($config_painel) {
        $nome_painel = !empty($config_painel['nome_painel']) ? $config_painel['nome_painel'] : $nome_painel;
        $logo_url = !empty($config_painel['logo_url']) ? $config_painel['logo_url'] : $logo_url;
        $cor_primaria = !empty($config_painel['cor_primaria']) ? $config_painel['cor_primaria'] : $cor_primaria;
    }
} catch (Exception $e) { }

// Busca os créditos no Banco Interno
$user_credits = $pdo_int->query("SELECT credits FROM reg_users WHERE id = " . intval($user_id_logado))->fetchColumn() ?: 0;

// --- AÇÃO DE SALVAR (NO BANCO INTERNO - TABELA CUSTOM_SETTINGS) ---
$mensagem = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_save_token'])) {
    $novo_status = isset($_POST['link_mode']) ? "1" : "0";
    
    $stmt = $pdo_int->prepare("UPDATE custom_settings SET value = ? WHERE name = 'link_mode'");
    if ($stmt->execute([$novo_status])) {
        $mensagem = "<script>Swal.fire({icon: 'success', title: 'Sucesso!', text: 'Configuração salva! Atualize a página do aplicativo para ver as mudanças.', background: '#272c33', color: '#fff'});</script>";
    }
}

// LÊ O STATUS ATUAL DIRETAMENTE DA TABELA CUSTOM_SETTINGS NO BANCO INTERNO
$conf = $pdo_int->query("SELECT value FROM custom_settings WHERE name = 'link_mode'")->fetchColumn();
$token_ativo = ($conf === "1");
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <link rel="stylesheet" href="tema.css">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Token XUI - <?php echo htmlspecialchars($nome_painel); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        :root { --bg-dark: #121519; --bg-sidebar: #1e2227; --bg-card: #272c33; --text-main: #d1d5da; --text-muted: #8a94a1; --accent: <?php echo $cor_primaria; ?>; --border-color: #3a4149; --success: #28a745; --danger: #dc3545; --warning: #f39c12; }
        
        * { box-sizing: border-box; }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: var(--bg-dark); color: var(--text-main); display: flex; height: 100vh; overflow: hidden; }
        
        /* SIDEBAR */
        .sidebar { width: 260px; background-color: var(--bg-sidebar); border-right: 1px solid var(--border-color); display: flex; flex-direction: column; transition: 0.3s; z-index: 1001; flex-shrink: 0; }
        .sidebar-header { padding: 25px 20px; text-align: center; border-bottom: 1px solid var(--border-color); color: white; }
        .sidebar-logo { max-width: 180px; max-height: 60px; object-fit: contain; }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(255, 255, 255, 0.05); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .user-info .credits-badge { display: block; margin-top: 10px; color: var(--success); font-weight: bold; font-size: 13px; }
        
        .menu-list { list-style: none; padding: 0; margin: 0; flex: 1; overflow-y: auto; }
        .menu-item { padding: 14px 25px; color: var(--text-main); text-decoration: none; display: flex; align-items: center; transition: 0.2s; font-size: 15px; border-left: 4px solid transparent; cursor: pointer; }
        .menu-item i:first-child { margin-right: 15px; width: 20px; text-align: center; font-size: 16px; color: var(--text-muted); }
        .menu-item:hover, .menu-item.active { background: #2c3138; color: white; border-left-color: var(--accent); }
        .menu-item.active i:first-child { color: var(--accent) !important; }
        
        .submenu { display: none; background: #121519; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 14px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 12px; }
        .rotate { transform: rotate(180deg); }
        .menu-category { padding: 20px 25px 8px; font-size: 11px; text-transform: uppercase; color: var(--text-muted); font-weight: bold; letter-spacing: 1px; }
        .logout-btn { padding: 15px; background-color: var(--danger); color: white; text-align: center; text-decoration: none; font-weight: bold; margin-top: auto; }
        
        /* CONTEÚDO */
        .main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; width: 100%; position: relative; }
        .topbar { display: flex; justify-content: space-between; align-items: center; padding: 15px 30px; background-color: var(--bg-sidebar); border-bottom: 1px solid var(--border-color); }
        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 22px; cursor: pointer; }

        .content-area { padding: 30px; flex: 1; width: 100%; }
        .system-container { background: var(--bg-card); border-radius: 12px; border: 1px solid var(--border-color); padding: 40px; width: 100%; }
        
        .card-header { text-align: center; margin-bottom: 30px; }
        .card-header i { font-size: 50px; color: var(--warning) !important; margin-bottom: 15px; }
        .card-header h2 { margin: 0; color: white; }

        .setting-box { background: rgba(0,0,0,0.2); border: 1px solid var(--border-color); border-radius: 12px; padding: 30px; display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; gap: 20px; }
        
        .switch { position: relative; display: inline-block; width: 60px; height: 34px; flex-shrink: 0; }
        .switch input { opacity: 0; width: 0; height: 0; }
        .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #3a4149; transition: .4s; border-radius: 34px; }
        .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; transition: .4s; border-radius: 50%; }
        input:checked + .slider { background-color: var(--success); }
        input:checked + .slider:before { transform: translateX(26px); }

        .btn-save { width: 100%; padding: 16px; background: var(--accent); border: none; color: white; border-radius: 8px; font-weight: bold; cursor: pointer; font-size: 16px; transition: 0.2s;}
        .btn-save:hover { filter: brightness(1.1); }
        .preview-box { margin-top: 30px; padding: 20px; background: #000; border-radius: 8px; border: 1px dashed var(--border-color); font-family: monospace; font-size: 13px; word-break: break-all; }

        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; }

        @media (max-width: 768px) {
            .menu-toggle { display: block; margin-right: 15px; }
            .sidebar { position: fixed; left: -260px; height: 100%; box-shadow: 10px 0 20px rgba(0,0,0,0.5); }
            .sidebar.active { left: 0; }
            .sidebar-overlay.active { display: block; }
            .content-area { padding: 15px; }
            .system-container { padding: 20px; }
            .topbar { padding: 15px 20px; justify-content: flex-start; }
            .setting-box { flex-direction: column; align-items: flex-start; }
        }
    </style>
</head>
<body>
    <div class="sidebar-overlay" id="overlay" onclick="toggleMenu()"></div>
    
    <?php include 'sidebar.php'; ?>

    <div class="main-content">
        <header class="topbar">
            <div style="display:flex; align-items:center;">
                <button class="menu-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
                <h2 style="margin:0; font-size: 18px; color:white;">Configuração de Token</h2>
            </div>
            <div class="topbar-right">
                <div style="background:rgba(40,167,69,0.15); color:var(--success); border:1px solid var(--success); padding:5px 15px; border-radius:20px; font-size:12px; font-weight:bold;">SÓ ADMIN</div>
            </div>
        </header>

        <div class="content-area">
            <?php echo $mensagem; ?>

            <div class="system-container">
                <div class="card-header">
                    <i class="fas fa-user-secret"></i>
                    <h2>Modo Oculto (Token Híbrido)</h2>
                    <p style="color:var(--text-muted); margin-top:10px;">Criptografe os dados da sua lista M3U para evitar roubos. Funciona em Xtream e XUI ONE.</p>
                </div>

                <form method="POST">
                    <div class="setting-box">
                        <div style="flex:1;">
                            <h4 style="margin:0; color:white;">Ativar Criptografia</h4>
                            <p style="margin:5px 0 0; font-size:13px; color:var(--text-muted);">Links camuflados com o prefixo <strong>"NBR_"</strong>.</p>
                        </div>
                        <label class="switch">
                            <input type="checkbox" name="link_mode" <?php echo $token_ativo ? 'checked' : ''; ?>>
                            <span class="slider"></span>
                        </label>
                    </div>

                    <button type="submit" name="action_save_token" class="btn-save">SALVAR CONFIGURAÇÃO</button>
                </form>

                <div class="preview-box">
                    <span style="color:var(--success)"># MODO ATIVADO - Links Blindados</span><br>
                    <span style="color:#0ea5e9">http://<?php echo $_SERVER['HTTP_HOST']; ?>/play/</span><span style="color:#facc15">NBR_amVhbntyczpM@/1234.m3u8</span>
                </div>
            </div>
        </div>

        <?php if(file_exists('rodape.php')) include 'rodape.php'; ?>
    </div>

    <script>
        function toggleMenu() {
            document.getElementById('sidebar').classList.toggle('active');
            document.getElementById('overlay').classList.toggle('active');
        }

        function toggleSubmenu(id) {
            const sub = document.getElementById(id);
            const arrow = document.getElementById('arrow-' + id);
            if (sub.style.display === "block") {
                sub.style.display = "none";
                if(arrow) arrow.classList.remove('rotate');
            } else {
                sub.style.display = "block";
                if(arrow) arrow.classList.add('rotate');
            }
        }
    </script>
    <script src="tema.js"></script>
</body>
</html>