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

// --- INÍCIO DA CORREÇÃO DO MENU LATERAL ---
$isAdmin = (isset($_SESSION['nivel']) && strtolower($_SESSION['nivel']) === 'admin');
$usuarioLogado = $_SESSION['usuario'] ?? '';
$total_msg_nao_lidas = 0;
try {
    if (!empty($usuarioLogado) && isset($connUser)) {
        $stmtMsg = $connUser->prepare("SELECT COUNT(*) FROM chamados_suporte WHERE destinatario = ? AND lida = 'nao'");
        $stmtMsg->execute([$usuarioLogado]);
        $total_msg_nao_lidas = $stmtMsg->fetchColumn();
    }
} catch (Exception $e) { }
// --- FIM DA CORREÇÃO DO MENU LATERAL ---

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

// --- 1. BUSCA CONFIGURAÇÕES DO SITE (NOME E COR) ---
$nomePainel = "IPTV PANEL"; 
$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. PROCESSAR SALVAMENTO DAS CONFIGURAÇÕES ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $senha_srv = $_POST['senha_servidor'];
        $deskeys   = $_POST['deskeys'];
        $ip_srv    = $_POST['ip_servidor'];
        $bloqueio  = isset($_POST['bloqueio_ip']) ? 'sim' : 'nao';
        $chave_xml = $_POST['chave_xml'];
        
        $existe = $connGeral->query("SELECT id FROM configuracao WHERE id=1")->rowCount();
        
        if ($existe > 0) {
            $sql = "UPDATE configuracao SET senha_servidor=?, deskeys=?, ip_servidor=?, bloqueio_ip=?, chave_xml=? WHERE id=1";
            $connGeral->prepare($sql)->execute([$senha_srv, $deskeys, $ip_srv, $bloqueio, $chave_xml]);
        } else {
            $sql = "INSERT INTO configuracao (id, senha_servidor, deskeys, ip_servidor, bloqueio_ip, chave_xml) VALUES (1, ?, ?, ?, ?, ?)";
            $connGeral->prepare($sql)->execute([$senha_srv, $deskeys, $ip_srv, $bloqueio, $chave_xml]);
        }
        
        $msg = "Configurações salvas com sucesso!";
        $msg_tipo = "success";
    } catch (Exception $e) {
        $msg = "Erro ao salvar: " . $e->getMessage();
        $msg_tipo = "danger";
    }
}

// --- 3. BUSCAR DADOS ATUAIS ---
try {
    $config = $connGeral->query("SELECT * FROM configuracao WHERE id=1")->fetch(PDO::FETCH_ASSOC);
    if(!$config) {
        $config = ['senha_servidor'=>'', 'deskeys'=>'0102030405060708091011121314', 'ip_servidor'=>'', 'bloqueio_ip'=>'nao', 'chave_xml'=>md5(time())];
    }
} catch (Exception $e) { $config = []; }

// --- 4. GERAR LINKS AUTOMÁTICOS ---
$protocolo_web = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
$base_url = "$protocolo_web://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
$base_url = str_replace('/config_geral.php', '', $base_url); 

$link_xml = $base_url . "/xml.php?key=" . ($config['chave_xml'] ?? '');
$link_cron = "*/1 * * * * curl --request GET '" . $base_url . "/cron.php'";
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>


<?php include 'tema_global.php'; ?>




    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Configuração Geral | <?= 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: #151521; --bg-card: #1e1e2d; --text-color: #d0d2d6; --border-color: #2b2b40; }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; }
        
        /* Sidebar Profissional */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid #333; z-index: 1050; padding: 20px; overflow-y: auto; transition: 0.3s; }
        .nav-link { color: #a6a6b7; padding: 12px 15px; border-radius: 8px; display: flex; align-items: center; gap: 12px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }
        
        /* Main Content */
        .main-content { margin-left: 260px; transition: 0.3s; min-height: 100vh; }
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--primary) 100%); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; }

        /* Forms e Cards */
        .card-custom { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 12px; height: 100%; }
        .form-control { background: #151521 !important; border: 1px solid #444 !important; color: #fff !important; padding: 10px; }
        .form-control:focus { border-color: var(--primary) !important; box-shadow: 0 0 0 0.25rem rgba(115, 103, 240, 0.25); }
        .form-label { color: #ffffff; font-weight: 600; font-size: 0.9rem; margin-bottom: 8px; }
        .input-group-text { background: #3b3b55; border: 1px solid #444; color: #fff; cursor: pointer; }

        @media (max-width: 992px) {
            .sidebar { transform: translateX(-100%); }
            .sidebar.show { transform: translateX(0); }
            .main-content { margin-left: 0; }
            .mobile-toggle { display: block !important; }
        }
        .mobile-toggle { display: none; color: #fff; font-size: 1.5rem; background: none; border: none; margin-right: 15px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; }
        .overlay.show { display: block; }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>


<main class="main-content">
    <div class="top-header">
        <div class="d-flex align-items-center">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title">Configuração do Sistema</div>
        </div>
        <div class="header-icons">
            <a href="sair.php" class="btn btn-danger btn-sm rounded-pill px-3 shadow-sm"><i class="fas fa-power-off"></i></a>
        </div>
    </div>

    <div class="container-fluid p-3 p-md-4">
        
        <?php if($msg): ?>
            <div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show border-0 shadow-sm">
                <?= $msg ?>
                <button class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <form method="POST">
            <div class="row g-4">
                <div class="col-xl-6">
                    <div class="card card-custom p-4 shadow-lg">
                        <h5 class="text-primary mb-4 fw-bold"><i class="fas fa-server me-2"></i> Dados do Servidor CSP</h5>
                        
                        <div class="mb-3">
                            <label class="form-label">Senha do Servidor (CSP)</label>
                            <input type="text" name="senha_servidor" class="form-control" value="<?= htmlspecialchars($config['senha_servidor'] ?? '') ?>" placeholder="Ex: 2X9xNVfDHL...">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">DesKeys (Chave de Criptografia)</label>
                            <input type="text" name="deskeys" class="form-control" value="<?= htmlspecialchars($config['deskeys'] ?? '0102030405060708091011121314') ?>">
                            <small class="text-muted">Padrão: 0102030405060708091011121314</small>
                        </div>

                        <div class="mb-4">
                            <label class="form-label">IP / Host do Servidor</label>
                            <input type="text" name="ip_servidor" class="form-control" value="<?= htmlspecialchars($config['ip_servidor'] ?? '') ?>" placeholder="Ex: 192.168.1.1 ou dns.servidor.com">
                        </div>

                        <div class="p-3 bg-dark rounded border border-secondary">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="bloqueio_ip" id="blk" <?= ($config['bloqueio_ip']??'nao') == 'sim' ? 'checked' : '' ?>>
                                <label class="form-check-label text-white fw-bold" for="blk">Ativar Bloqueio de IP (IP Lock)</label>
                            </div>
                            <small class="text-white-50 mt-1 d-block">Impede conexões de IPs não autorizados no painel.</small>
                        </div>
                    </div>
                </div>

                <div class="col-xl-6">
                    <div class="card card-custom p-4 border-start border-3 border-info shadow-lg">
                        <h5 class="text-info mb-4 fw-bold"><i class="fas fa-link me-2"></i> Integração e Links</h5>

                        <div class="mb-4">
                            <label class="form-label">Chave de Segurança (XML Key)</label>
                            <div class="input-group">
                                <input type="text" name="chave_xml" id="xmlKey" class="form-control text-warning fw-bold" value="<?= htmlspecialchars($config['chave_xml'] ?? '') ?>">
                                <button type="button" class="btn btn-outline-info" onclick="gerarKey()"><i class="fas fa-sync"></i> Gerar</button>
                            </div>
                            <small class="text-white-50">Protege o acesso aos seus dados via XML.</small>
                        </div>

                        <div class="mb-4">
                            <label class="form-label fw-bold">Link XML (Para o CSP)</label>
                            <div class="input-group">
                                <input type="text" class="form-control bg-dark text-white-50 small" id="linkXml" value="<?= $link_xml ?>" readonly>
                                <span class="input-group-text" onclick="copiar('linkXml')"><i class="fas fa-copy"></i></span>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold">Crontab (Agendamento Automático)</label>
                            <div class="input-group">
                                <input type="text" class="form-control bg-dark text-white-50 small" id="cronCode" value="<?= $link_cron ?>" readonly>
                                <span class="input-group-text" onclick="copiar('cronCode')"><i class="fas fa-copy"></i></span>
                            </div>
                            <small class="text-white-50">Comando para rodar a cada 1 minuto no seu Linux.</small>
                        </div>
                    </div>
                </div>

                <div class="col-12 mt-2">
                    <button type="submit" class="btn btn-success btn-lg fw-bold w-100 py-3 shadow-lg border-0">
                        <i class="fas fa-save me-2"></i> ATUALIZAR CONFIGURAÇÕES GERAIS
                    </button>
                </div>
            </div>
        </form>
    </div>
    <?php include 'rodape.php'; ?>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu() { 
        document.getElementById('sidebar').classList.toggle('show'); 
        document.getElementById('overlay').classList.toggle('show'); 
    }
    
    function copiar(id) {
        var copyText = document.getElementById(id);
        copyText.select();
        copyText.setSelectionRange(0, 99999); 
        navigator.clipboard.writeText(copyText.value).then(() => { 
            alert("Link copiado para a área de transferência!"); 
        });
    }

    function gerarKey() {
        let result = '';
        const characters = '0123456789abcdef';
        for (let i = 0; i < 32; i++) {
            result += characters.charAt(Math.floor(Math.random() * characters.length));
        }
        document.getElementById('xmlKey').value = result;
    }
</script>
</body>
</html>