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

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

// 1. PROCESSAR SALVAMENTO
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'];
        
        // Verifica se já existe registro (ID 1)
        $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";
    }
}

// 2. BUSCAR DADOS
try {
    $config = $connGeral->query("SELECT * FROM configuracao WHERE id=1")->fetch(PDO::FETCH_ASSOC);
    if(!$config) {
        // Valores padrão visuais se não tiver no banco
        $config = ['senha_servidor'=>'', 'deskeys'=>'0102030405060708091011121314', 'ip_servidor'=>'', 'bloqueio_ip'=>'nao', 'chave_xml'=>md5(time())];
    }
} catch (Exception $e) { $config = []; }

// 3. GERAR LINKS AUTOMÁTICOS
$protocolo = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
$base_url = "$protocolo://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
// Remove o nome do arquivo atual para pegar a pasta raiz do painel se necessário
$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>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Configuração Geral</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>
        body { background: #151521; color: #fff; font-family: 'Segoe UI', sans-serif; }
        .sidebar { width: 260px; height: 100vh; position: fixed; background: #1e1e2d; padding: 20px; border-right: 1px solid #333; z-index: 1000; }
        .main-content { margin-left: 260px; padding: 30px; }
        .card-custom { background: #1e1e2d; border: 1px solid rgba(255,255,255,0.05); border-radius: 12px; margin-bottom: 20px; }
        
        .form-control, .form-select { background: #2b2b40; border: 1px solid #444; color: #fff; }
        .form-control:focus { background: #32324a; border-color: #7367f0; color: #fff; }
        .form-label { color: #ccc; font-weight: 500; }
        
        .input-group-text { background: #3b3b55; border: 1px solid #444; color: #fff; cursor: pointer; }
        .text-info-light { color: #0dcaf0; }

        @media (max-width: 768px) { .sidebar{display:none;} .main-content{margin-left:0;} }
    </style>
</head>
<body>

<nav class="sidebar">
    <h4 class="mb-4 fw-bold text-white"><i class="fas fa-tv text-primary"></i> Painel</h4>
    <div class="nav flex-column gap-2">
        <a href="index.php" class="btn btn-dark text-start border-0 py-2"><i class="fas fa-home me-2"></i> Dashboard</a>
        <a href="config_geral.php" class="btn btn-primary text-start border-0 py-2"><i class="fas fa-cogs me-2"></i> Config. Geral</a>
    </div>
</nav>

<main class="main-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold">Configuração do Painel (Geral)</h3>
    </div>

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

    <form method="POST">
        <div class="row">
            <div class="col-md-6">
                <div class="card card-custom p-4">
                    <h5 class="text-primary mb-4"><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="<?= $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="<?= $config['deskeys'] ?? '0102030405060708091011121314' ?>">
                        <small class="text-muted">Padrão: 0102030405060708091011121314</small>
                    </div>

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

                    <div class="mb-3">
                        <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" for="blk">Ativar Bloqueio de IP (IP Lock)</label>
                        </div>
                        <small class="text-white-50">Se ativar, o sistema pode bloquear conexões de IPs desconhecidos.</small>
                    </div>
                </div>
            </div>

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

                    <div class="mb-3">
                        <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="<?= $config['chave_xml'] ?? '' ?>">
                            <button type="button" class="btn btn-outline-secondary" onclick="gerarKey()"><i class="fas fa-sync"></i> Gerar</button>
                        </div>
                        <small class="text-white-50">Esta chave protege o link XML abaixo.</small>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold text-white">Link XML (Para o CSP)</label>
                        <div class="input-group">
                            <input type="text" class="form-control bg-dark text-white-50" 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 text-white">Crontab (Comando Automático)</label>
                        <div class="input-group">
                            <input type="text" class="form-control bg-dark text-white-50" 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">Use este comando no seu servidor para automação.</small>
                    </div>

                </div>
                
                <div class="text-end">
                    <button type="submit" class="btn btn-success btn-lg fw-bold px-5"><i class="fas fa-save me-2"></i> Atualizar Configurações</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 copiar(id) {
        var copyText = document.getElementById(id);
        copyText.select();
        copyText.setSelectionRange(0, 99999); 
        navigator.clipboard.writeText(copyText.value).then(() => { alert("Copiado!"); });
    }

    function gerarKey() {
        // Gera uma string aleatória de 32 caracteres (MD5 style)
        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>
