<?php
// FORÇA O PHP E O NAVEGADOR A USAREM UTF-8
header('Content-Type: text/html; charset=utf-8');
session_start();
require_once 'config.php';

$pdo = getConexaoInterna(); 

// --- INÍCIO: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---
$nome_painel = 'TOP IPTV';
$logo_url = '';
$cor_primaria = '#007bff';

try {
    $tabela_existe = $pdo->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_p = $pdo->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($config_p) {
            $nome_painel = !empty($config_p['nome_painel']) ? $config_p['nome_painel'] : $nome_painel;
            $logo_url = !empty($config_p['logo_url']) ? $config_p['logo_url'] : $logo_url;
            $cor_primaria = !empty($config_p['cor_primaria']) ? $config_p['cor_primaria'] : $cor_primaria;
        }
    }
} catch (Exception $e) {}
// --- FIM: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---

if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    die("Acesso negado. Apenas administradores podem configurar o servidor.");
}

$nome_usuario = $_SESSION['username'] ?? 'Usuário';
$role = $_SESSION['user_role'] ?? 'admin';

// =========================================================================
// BANCO DE DADOS (AUTO-CRIAÇÃO DAS COLUNAS XUI ONE E XTREAM)
// =========================================================================
try {
    $sql_tabela = "CREATE TABLE IF NOT EXISTS configuracoes (
        id INT(11) AUTO_INCREMENT PRIMARY KEY,
        modo_ativo VARCHAR(20) NOT NULL DEFAULT 'interno',
        int_host VARCHAR(255) NULL DEFAULT 'localhost',
        int_name VARCHAR(255) NULL,
        int_user VARCHAR(255) NULL,
        int_pass VARCHAR(255) NULL,
        ext_host VARCHAR(255) NULL,
        ext_name VARCHAR(255) NULL,
        ext_user VARCHAR(255) NULL,
        ext_pass VARCHAR(255) NULL,
        xui_host VARCHAR(255) NULL,
        xui_name VARCHAR(255) NULL,
        xui_user VARCHAR(255) NULL,
        xui_pass VARCHAR(255) NULL
    )";
    $pdo->exec($sql_tabela);

    $colunas = $pdo->query("SHOW COLUMNS FROM configuracoes")->fetchAll(PDO::FETCH_COLUMN);
    
    // Verifica/Cria colunas do Interno
    if (!in_array('int_host', $colunas)) {
        $pdo->exec("ALTER TABLE configuracoes ADD COLUMN int_host VARCHAR(255) DEFAULT 'localhost' AFTER modo_ativo,
                    ADD COLUMN int_name VARCHAR(255) AFTER int_host,
                    ADD COLUMN int_user VARCHAR(255) AFTER int_name,
                    ADD COLUMN int_pass VARCHAR(255) AFTER int_user");
    }
    
    // Verifica/Cria colunas do XUI One
    if (!in_array('xui_host', $colunas)) {
        $pdo->exec("ALTER TABLE configuracoes 
                    ADD COLUMN xui_host VARCHAR(255) NULL AFTER ext_pass,
                    ADD COLUMN xui_name VARCHAR(255) NULL AFTER xui_host,
                    ADD COLUMN xui_user VARCHAR(255) NULL AFTER xui_name,
                    ADD COLUMN xui_pass VARCHAR(255) NULL AFTER xui_user");
    }

    if ($pdo->query("SELECT COUNT(*) FROM configuracoes")->fetchColumn() == 0) {
        $pdo->exec("INSERT INTO configuracoes (modo_ativo, int_host) VALUES ('interno', 'localhost')");
    }
} catch (PDOException $e) {
    die("Erro no banco: " . $e->getMessage());
}

$mensagem = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $modo = $_POST['modo_ativo'];
    $sql = "UPDATE configuracoes SET 
            modo_ativo = :modo, 
            int_host = :i_host, int_name = :i_name, int_user = :i_user, int_pass = :i_pass,
            ext_host = :e_host, ext_name = :e_name, ext_user = :e_user, ext_pass = :e_pass,
            xui_host = :x_host, xui_name = :x_name, xui_user = :x_user, xui_pass = :x_pass
            WHERE id = 1";
            
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':modo' => $modo, 
        ':i_host' => trim($_POST['int_host']), ':i_name' => trim($_POST['int_name']), ':i_user' => trim($_POST['int_user']), ':i_pass' => trim($_POST['int_pass']),
        ':e_host' => trim($_POST['ext_host']), ':e_name' => trim($_POST['ext_name']), ':e_user' => trim($_POST['ext_user']), ':e_pass' => trim($_POST['ext_pass']),
        ':x_host' => trim($_POST['xui_host'] ?? ''), ':x_name' => trim($_POST['xui_name'] ?? ''), ':x_user' => trim($_POST['xui_user'] ?? ''), ':x_pass' => trim($_POST['xui_pass'] ?? '')
    ]);
    $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Configurações salvas com sucesso!</div>";
}

$atual = $pdo->query("SELECT * FROM configuracoes LIMIT 1")->fetch(PDO::FETCH_ASSOC);

?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Configurações - <?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">
    <style>
        /* ==========================================================================
           CSS PREMIUM V8 - MENU FIXO + ROLAGEM INTERNA (Desktop e Mobile)
           ========================================================================== */
        
        a { text-decoration: none !important; }
        *, *::before, *::after { box-sizing: border-box; outline: none; }
        
        :root {
            --bg-dark: #0b0f14;
            --bg-card: #161b22;
            --text-main: #c9d1d9;
            --text-muted: #8b949e;
            --accent: <?php echo $cor_primaria; ?>;
            --border-color: rgba(255, 255, 255, 0.05);
            --success: #238636;
            --danger: #da3633;
            --warning: #d4a000;
        }

        html, body { 
            width: 100%; max-width: 100vw; overflow-x: hidden; 
            font-family: 'Inter', '-apple-system', 'Segoe UI', sans-serif; 
            background-color: var(--bg-dark); color: var(--text-main); 
            display: flex; height: 100dvh; margin: 0; padding: 0; 
        }

        /* =========================================================
           A MÁGICA DO MENU LATERAL (Aplicada para Desktop e Mobile)
           ========================================================= */
        nav#sidebar.sidebar, .sidebar {
            height: 100dvh !important;
            max-height: 100dvh !important;
            display: flex !important;
            flex-direction: column !important;
            overflow: hidden !important; /* A BARRA NUNCA ROLA INTEIRA */
        }
        
        #sidebar .sidebar-header, #sidebar .user-info {
            flex-shrink: 0 !important; /* TOPO FICA FIXO */
            z-index: 10 !important;
            background-color: var(--bg-sidebar) !important;
        }

        #sidebar .menu-list {
            flex: 1 1 auto !important; 
            overflow-y: auto !important; /* APENAS OS LINKS ROLAM NO MEIO */
            padding-bottom: 10px !important;
        }
        #sidebar .menu-list::-webkit-scrollbar { width: 4px; }
        #sidebar .menu-list::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 10px; }

        #sidebar .logout-btn {
            flex-shrink: 0 !important; /* BOTÃO DE SAIR FICA FIXO NO FUNDO */
            margin-top: auto !important;
            margin-bottom: 20px !important;
            background-color: var(--bg-sidebar) !important; 
            z-index: 10 !important;
        }
        /* ========================================================= */

        .main-content { 
            flex: 1; display: flex; flex-direction: column; overflow-y: auto; overflow-x: hidden; 
            width: 100%; position: relative; scroll-behavior: smooth; 
        }
        .main-content::-webkit-scrollbar { width: 6px; }
        .main-content::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 10px; }

        .rodape-container {
            position: relative !important; display: block !important; width: 100% !important; 
            margin-top: auto !important; padding-bottom: 20px !important; z-index: 5 !important;
        }
        .rodape-container *, .rodape-container div, .rodape-container footer {
            position: static !important; bottom: auto !important; left: auto !important; right: auto !important; transform: none !important;
        }

        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.75); z-index: 1000; cursor: pointer; transition: opacity 0.3s; }
        .sidebar-overlay.active { display: block; }

        .topbar { display: flex; justify-content: space-between; align-items: center; padding: 20px 30px; background-color: transparent; border-bottom: 1px solid var(--border-color); flex-shrink: 0; width: 100%; }
        .menu-toggle { display: none; background: none; border: none; color: var(--text-main); font-size: 22px; cursor: pointer; padding: 5px; transition: 0.3s; }
        .menu-toggle:hover { color: var(--accent); }
        .mode-badge { padding: 6px 14px; background: rgba(35, 134, 54, 0.1); color: var(--success); border-radius: 20px; font-size: 11px; font-weight: 700; border: 1px solid rgba(35, 134, 54, 0.2); letter-spacing: 0.5px; }

        .content-area { padding: 30px; flex: 1 0 auto; max-width: 1000px; width: 100%; margin: 0 auto; }
        
        .container-box { background: var(--bg-card); border-radius: 12px; border: 1px solid var(--border-color); padding: 30px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); }
        
        .container-box h2 { margin-top: 0; color: white; display: flex; align-items: center; gap: 10px; font-size: 18px; font-weight: 600; margin-bottom: 25px; border-bottom: 1px solid var(--border-color); padding-bottom: 15px; }
        
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 25px; font-weight: 600; font-size: 14px; display: flex; align-items: center; gap: 10px; border: none; }
        .alert.success { background: rgba(46, 160, 67, 0.15); color: #3fb950; border: 1px solid rgba(46, 160, 67, 0.3); }
        .alert.danger { background: rgba(248, 81, 73, 0.15); color: #ff7b72; border: 1px solid rgba(248, 81, 73, 0.3); }

        .form-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 8px; color: var(--text-muted); font-weight: 600; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; }
        
        input, select { 
            width: 100%; padding: 14px 15px; background: #0d1117; border: 1px solid var(--border-color); 
            color: white; border-radius: 8px; font-size: 14px; transition: 0.3s; font-family: inherit;
        }
        input:focus, select:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }
        
        select { cursor: pointer; appearance: none; background-image: url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%238b949e%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E"); background-repeat: no-repeat; background-position: right 15px top 50%; background-size: 12px auto; padding-right: 40px; }

        .config-section { padding: 25px; border-radius: 10px; margin-bottom: 25px; background: rgba(255,255,255,0.02); border: 1px solid var(--border-color); }
        .config-section h4 { margin-top: 0; display: flex; align-items: center; gap: 10px; font-size: 15px; font-weight: 600; margin-bottom: 20px; }
        
        .btn-salvar { background: var(--accent); color: white; padding: 16px; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; width: 100%; margin-top: 10px; transition: 0.2s; font-size: 14px; text-transform: uppercase; letter-spacing: 0.5px; display: flex; align-items: center; justify-content: center; gap: 8px;}
        .btn-salvar:hover { filter: brightness(1.1); transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0, 123, 255, 0.4); }

        .show-mobile { display: none !important; }
        
        @media (max-width: 768px) {
            .topbar { padding: 15px 20px; justify-content: flex-start;}
            .content-area { padding: 15px; }
            .container-box { padding: 20px; }
            .show-desktop { display: none !important; }
            .show-mobile { display: flex !important; }
            .menu-toggle { display: block; margin-right: 15px; flex-shrink: 0; }
        }

        body.light-mode {
            --bg-dark: #f6f8fa; --bg-card: #ffffff; --text-main: #1f2328; --text-muted: #656d76; --border-color: rgba(0,0,0,0.08);
        }
        body.light-mode .container-box, body.light-mode .config-section { background: #ffffff; box-shadow: 0 8px 24px rgba(0,0,0,0.05); }
        body.light-mode input, body.light-mode select { background: #f6f8fa; color: #1f2328; }
        body.light-mode h2, body.light-mode h4 { color: #1f2328 !important; }
    </style>
</head>
<body style="display:flex; flex-direction:row;">

    <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; gap:15px;">
                <button class="menu-toggle" id="btn-menu" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
                <h2 style="margin:0; font-size: 18px; color:white;"><i class="fas fa-cogs" style="color: var(--text-muted); margin-right: 8px;"></i> Configurações</h2>
            </div>
            <div class="topbar-right">
                <span class="mode-badge"><i class="fas fa-database"></i> MODO: <?php echo defined('MODO_SISTEMA') ? strtoupper(MODO_SISTEMA) : strtoupper($modo_ativo); ?></span>
            </div>
        </header>

        <div class="content-area">
            <div class="container-box">
                <h2><i class="fas fa-server" style="color: var(--accent);"></i> Servidor Database</h2>
                <?php echo $mensagem; ?>

                <form method="POST">
                    <div class="form-group" style="margin-bottom: 30px;">
                        <label>MODO DE OPERAÇÃO ATIVO</label>
                        <select name="modo_ativo" style="border-color: var(--accent); color: var(--accent); font-weight: 600;">
                            <option value="interno" <?php echo ($atual['modo_ativo'] == 'interno') ? 'selected' : ''; ?>>MODO INTERNO (Painel Local)</option>
                            <option value="externo" <?php echo ($atual['modo_ativo'] == 'externo') ? 'selected' : ''; ?>>MODO EXTERNO (Xtream UI)</option>
                            <option value="xui" <?php echo ($atual['modo_ativo'] == 'xui') ? 'selected' : ''; ?>>MODO XUI ONE</option>
                        </select>
                    </div>

                    <div class="config-section" style="border-left: 4px solid #6c757d;">
                        <h4 style="color: #c9d1d9;"><i class="fas fa-database" style="color: #8b949e;"></i> Banco INTERNO</h4>
                        <div class="form-group"><label>Host</label><input type="text" name="int_host" value="<?php echo htmlspecialchars($atual['int_host']); ?>"></div>
                        <div class="form-group"><label>Banco</label><input type="text" name="int_name" value="<?php echo htmlspecialchars($atual['int_name']); ?>"></div>
                        <div class="form-group"><label>Usuário</label><input type="text" name="int_user" value="<?php echo htmlspecialchars($atual['int_user']); ?>"></div>
                        <div class="form-group"><label>Senha</label><input type="password" name="int_pass" value="<?php echo htmlspecialchars($atual['int_pass']); ?>"></div>
                    </div>

                    <div class="config-section" style="border-left: 4px solid var(--accent);">
                        <h4 style="color: #c9d1d9;"><i class="fas fa-network-wired" style="color: var(--accent);"></i> Banco EXTERNO (Xtream UI)</h4>
                        <div class="form-group"><label>IP Servidor</label><input type="text" name="ext_host" value="<?php echo htmlspecialchars($atual['ext_host']); ?>"></div>
                        <div class="form-group"><label>Banco</label><input type="text" name="ext_name" value="<?php echo htmlspecialchars($atual['ext_name']); ?>"></div>
                        <div class="form-group"><label>Usuário</label><input type="text" name="ext_user" value="<?php echo htmlspecialchars($atual['ext_user']); ?>"></div>
                        <div class="form-group"><label>Senha</label><input type="password" name="ext_pass" value="<?php echo htmlspecialchars($atual['ext_pass']); ?>"></div>
                    </div>

                    <div class="config-section" style="border-left: 4px solid #8957e5;">
                        <h4 style="color: #c9d1d9;"><i class="fas fa-server" style="color: #8957e5;"></i> Banco EXTERNO (XUI One)</h4>
                        <div class="form-group"><label>IP Servidor</label><input type="text" name="xui_host" value="<?php echo htmlspecialchars($atual['xui_host'] ?? ''); ?>"></div>
                        <div class="form-group"><label>Banco</label><input type="text" name="xui_name" value="<?php echo htmlspecialchars($atual['xui_name'] ?? ''); ?>"></div>
                        <div class="form-group"><label>Usuário</label><input type="text" name="xui_user" value="<?php echo htmlspecialchars($atual['xui_user'] ?? ''); ?>"></div>
                        <div class="form-group"><label>Senha</label><input type="password" name="xui_pass" value="<?php echo htmlspecialchars($atual['xui_pass'] ?? ''); ?>"></div>
                    </div>

                    <button type="submit" class="btn-salvar"><i class="fas fa-save"></i> SALVAR CONFIGURAÇÕES</button>
                </form>
            </div>
        </div>

        <!-- RODAPÉ CORRIGIDO E LIVRE -->
        <div class="rodape-container">
            <?php include 'rodape.php'; ?>
        </div>

    </div>

    <script>
        // Funcionalidade do Overlay e do Menu Lateral
        function toggleMenu() { 
            const sidebar = document.getElementById('sidebar');
            const overlay = document.getElementById('overlay');
            if (sidebar) sidebar.classList.toggle('active'); 
            if (overlay) overlay.classList.toggle('active'); 
        }

        // Garante que os submenus fiquem recolhidos e só abram ao clique
        function toggleSubmenu(id) {
            const sub = document.getElementById(id);
            const arrow = document.getElementById('arrow-' + id);
            if (sub && sub.style.display === "block") { 
                sub.style.display = "none"; 
                if(arrow) arrow.classList.remove('rotate'); 
            } else if(sub) { 
                sub.style.display = "block"; 
                if(arrow) arrow.classList.add('rotate'); 
            }
        }

        // MÁGICA: Fecha todos os submenus automaticamente assim que a página carrega
        document.addEventListener("DOMContentLoaded", function() {
            var submenus = document.querySelectorAll('.submenu');
            submenus.forEach(function(sub) {
                sub.style.display = 'none'; // Força o fechamento
            });
            var arrows = document.querySelectorAll('.arrow-icon');
            arrows.forEach(function(arrow) {
                arrow.classList.remove('rotate'); // Força a setinha pra baixo
            });
        });
    </script>
    <script src="tema.js"></script>
</body>
</html>
