<?php
session_start();
if (!isset($_SESSION['logado']) || $_SESSION['nivel'] !== 'admin') { 
    header("Location: index.php"); exit; 
}
require_once 'conexao.php'; // Usa $connGeral (geanrober_painel_geral)

$msg = ""; $msg_tipo = "";

// --- 1. CONFIGURAÇÕES VISUAIS DO BANCO ---
$nomePainel = "TOP IPTV"; $corPrimaria = "#7367f0"; 
try {
    $conf_site = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($conf_site) {
        if (!empty($conf_site['NomePainel'])) $nomePainel = $conf_site['NomePainel'];
        if (!empty($conf_site['TemaPainel'])) $corPrimaria = $conf_site['TemaPainel'];
    }
} catch (Exception $e) { }

// --- 2. SALVAR CONFIGURAÇÕES (TABELA painel_config) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $senha_key = trim($_POST['senha_servidor']); 
        $deskeys   = trim($_POST['deskeys']);
        $ip_srv    = trim($_POST['ip_servidor']);
        $iplock    = isset($_POST['bloqueio_ip']) ? 'sim' : 'nao';
        
        // CORREÇÃO: Força a atualização ou inserção na tabela correta
        $check = $connGeral->query("SELECT id FROM painel_config WHERE id=1");
        if ($check->rowCount() > 0) {
            $sql = "UPDATE painel_config SET senha=?, deskeys=?, ip=?, iplock=? WHERE id=1";
            $connGeral->prepare($sql)->execute([$senha_key, $deskeys, $ip_srv, $iplock]);
        } else {
            $sql = "INSERT INTO painel_config (id, senha, deskeys, ip, iplock) VALUES (1, ?, ?, ?, ?)";
            $connGeral->prepare($sql)->execute([$senha_key, $deskeys, $ip_srv, $iplock]);
        }
        $msg = "Configurações salvas!"; $msg_tipo = "success";
    } catch (Exception $e) { $msg = "Erro: " . $e->getMessage(); $msg_tipo = "danger"; }
}

// --- 3. CARREGAR DADOS ATUAIS ---
try {
    $config = $connGeral->query("SELECT * FROM painel_config WHERE id=1")->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) { $config = false; }

if (!$config) {
    $config = ['senha' => '', 'deskeys' => '0102030405060708091011121314', 'ip' => '', 'iplock' => 'nao'];
}

// --- 4. LINKS DINÂMICOS (DOMÍNIO LOGADO + KEY) ---
$protocolo = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
$base_url  = $protocolo . "://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$link_xml  = $base_url . "/xml.php?key=" . $config['senha'];
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Configurações | <?= htmlspecialchars($nomePainel) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root { --primary: <?= $corPrimaria ?>; --bg-body: #161d31; --bg-card: #283046; }
        body { background: var(--bg-body); color: #ebebed; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; }
        
        /* SIDEBAR E CONTEÚDO RESPONSIVO */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); transition: 0.3s; z-index: 1050; border-right: 1px solid #3b4253; overflow-y: auto; }
        .main-content { margin-left: 260px; padding: 25px; transition: 0.3s; min-height: 100vh; }
        
        .nav-link { color: #d0d2d6; padding: 12px 15px; border-radius: 6px; margin: 2px 15px; display: flex; align-items: center; gap: 10px; text-decoration: none; font-size: 0.95rem; transition: 0.2s; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 0 10px rgba(115,103,240,0.3); }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #676d7d; font-weight: 700; margin: 20px 0 10px 25px; letter-spacing: 1px; }

        .card-custom { background: var(--bg-card); border: none; border-radius: 12px; margin-bottom: 20px; box-shadow: 0 4px 24px 0 rgba(0,0,0,0.24); }
        .form-control { background: #161d31 !important; border: 1px solid #404656 !important; color: #fff !important; height: 50px; font-weight: 600; }
        
        /* VISIBILIDADE LABELS */
        label { color: #ffffff !important; font-weight: 700; margin-bottom: 8px; font-size: 0.85rem; }

        /* MOBILE MENU */
        .overlay { display: none; position: fixed; width: 100vw; height: 100vh; background: rgba(0,0,0,0.5); z-index: 1040; }
        @media (max-width: 992px) {
            .sidebar { transform: translateX(-100%); }
            .sidebar.show { transform: translateX(0); }
            .main-content { margin-left: 0; padding: 15px; }
            .mobile-toggle { display: block !important; }
            .overlay.active { display: block; }
        }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.8rem; cursor: pointer; }
    </style>
</head>
<body>

<div class="overlay" id="overlay" onclick="toggleSidebar()"></div>

<nav class="sidebar" id="sidebar">
    <div class="p-4 text-center">
        <h4 class="fw-bold text-white mb-0"><i class="fas fa-tv text-primary me-2"></i><?= htmlspecialchars($nomePainel) ?></h4>
    </div>
    
    <div class="nav flex-column mt-2">
        <a href="index.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        
        <div class="nav-group-title">Operacional</div>
        <a href="clientes.php" class="nav-link"><i class="fas fa-users"></i> Clientes</a>
        <a href="testes.php" class="nav-link"><i class="fas fa-stopwatch"></i> Testes</a>
        <a href="revendedores.php" class="nav-link"><i class="fas fa-store"></i> Revendedores</a>
        
        <div class="nav-group-title">Administração</div>
        <a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Perfis e Canais</a>
        <a href="gerenciar_dns.php" class="nav-link"><i class="fas fa-network-wired"></i> Servidores DNS</a>
        <a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> Config. E-mail</a>
        <a href="config_geral.php" class="nav-link active"><i class="fas fa-cogs"></i> Configuração Geral</a>
        <a href="gerenciar_backups.php" class="nav-link"><i class="fas fa-database"></i> Backups</a>
        
        <hr class="border-secondary mx-3 mt-4">
        <a href="sair.php" class="nav-link text-danger"><i class="fas fa-power-off"></i> Sair do Painel</a>
    </div>
</nav>

<main class="main-content">
    <div class="d-flex align-items-center mb-4">
        <button class="mobile-toggle me-3" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
        <h3 class="fw-bold mb-0">Configuração Geral</h3>
    </div>

    <?php if($msg): ?><div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show"><?= $msg ?><button class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

    <form method="POST">
        <div class="row g-4">
            <div class="col-lg-6">
                <div class="card card-custom p-4 h-100">
                    <h5 class="text-primary mb-4 fw-bold"><i class="fas fa-server me-2"></i> Dados do CSP</h5>
                    
                    <div class="mb-3">
                        <label>XML KEY (CHAVE DE INTEGRAÇÃO)</label>
                        <div class="input-group">
                            <input type="text" name="senha_servidor" id="inputKey" class="form-control" value="<?= htmlspecialchars($config['senha']) ?>" placeholder="Clique no ícone para gerar..." required>
                            <button type="button" class="btn btn-outline-primary" onclick="gerarNovaChave()"><i class="fas fa-sync-alt"></i></button>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label>HOST / IP DO SERVIDOR</label>
                        <input type="text" name="ip_servidor" class="form-control" value="<?= htmlspecialchars($config['ip']) ?>" placeholder="Ex: 162.19.228.152">
                    </div>

                    <div class="mb-3">
                        <label>DESKEYS</label>
                        <input type="text" name="deskeys" class="form-control" value="<?= htmlspecialchars($config['deskeys']) ?>">
                    </div>

                    <div class="form-check form-switch mt-3">
                        <input class="form-check-input" type="checkbox" name="bloqueio_ip" id="blk" <?= ($config['iplock']??'nao') == 'sim' ? 'checked' : '' ?>>
                        <label class="form-check-label text-white fw-bold" for="blk">Ativar Bloqueio por IP</label>
                    </div>
                </div>
            </div>

            <div class="col-lg-6">
                <div class="card card-custom p-4 border-start border-4 border-info h-100">
                    <h5 class="text-info mb-4 fw-bold"><i class="fas fa-link me-2"></i> Integração Externa</h5>
                    
                    <div class="mb-4">
                        <label>LINK XML PARA O APARELHO</label>
                        <div class="p-3 bg-dark rounded border border-secondary text-break">
                            <code class="text-warning fw-bold" style="font-size: 0.9rem;"><?= $link_xml ?></code>
                        </div>
                        <div class="mt-2 small text-white-50"><i class="fas fa-info-circle me-1"></i> Este link usa o seu domínio atual e a chave salva acima.</div>
                    </div>

                    <button type="submit" class="btn btn-primary btn-lg fw-bold w-100 mt-auto py-3 shadow-lg"><i class="fas fa-save me-2"></i> SALVAR TUDO</button>
                </div>
            </div>
        </div>
    </form>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleSidebar() {
        document.getElementById('sidebar').classList.toggle('show');
        document.getElementById('overlay').classList.toggle('active');
    }
    function gerarNovaChave() {
        const chars = '0123456789abcdefghijklmnopqrstuvwxyz';
        let key = '';
        for (let i = 0; i < 20; i++) key += chars.charAt(Math.floor(Math.random() * chars.length));
        document.getElementById('inputKey').value = key;
    }
</script>
</body>
</html>
