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

// --- 1. TRAVA DE SEGURANÇA TOTAL (KILL SWITCH) ---
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true) {
    header("Location: login.php"); exit;
}

$isAdmin = (strtolower($_SESSION['nivel']) === 'admin');
$usuarioLogado = $_SESSION['usuario'];

if (!$isAdmin) {
    $stmtCheck = $connUser->prepare("SELECT bloqueado, data_premio FROM rev WHERE usuario = ? LIMIT 1");
    $stmtCheck->execute([$usuarioLogado]);
    $me = $stmtCheck->fetch(PDO::FETCH_ASSOC);

    if ($me) {
        $isBloq = ($me['bloqueado'] == 'sim');
        $isVenc = ((int)$me['data_premio'] > 0 && (int)$me['data_premio'] < time());
        if ($isBloq || $isVenc) {
            $motivo = $isBloq ? "BLOQUEADO PELO ADMINISTRADOR" : "PLANO VENCIDO";
            die("<!DOCTYPE html><html lang='pt-br'><head><meta charset='UTF-8'><title>Acesso Negado</title><link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'><style>body{background:#151521;color:#fff;display:flex;align-items:center;justify-content:center;height:100vh;text-align:center;}</style></head><body><div><h1 class='text-danger fw-bold' style='font-size: 4rem;'>??</h1><h2 class='fw-bold text-uppercase'>ACESSO SUSPENSO</h2><p class='lead text-muted'>$motivo</p><a href='sair.php' class='btn btn-outline-light mt-4 px-5'>Sair do Painel</a></div></body></html>");
        }
    }
}

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

<!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>Gerador de Robô | <?= 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 */
        .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 { 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); }
        
        /* Cartão do Gerador */
        .card-generator { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 15px; max-width: 600px; margin: 0 auto; box-shadow: 0 10px 30px rgba(0,0,0,0.3); }
        .input-dark { background-color: #151822 !important; border: 1px solid #3b4256 !important; color: #fff !important; padding: 12px !important; }
        .aviso-box { background-color: rgba(115, 103, 240, 0.1); border-left: 4px solid var(--primary); padding: 15px; border-radius: 6px; font-size: 0.9rem; color: #b4b7bd; margin-bottom: 20px; }
        
        @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>

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

<nav class="sidebar" id="sidebar">
    <div class="text-center mb-4"><h4 class="fw-bold text-white"><?= htmlspecialchars($nomePainel) ?></h4></div>
    <div class="nav flex-column">
        <a href="index.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        
        <?php if ($isAdmin): ?>
            <div class="nav-group-title">ADMINISTRATIVO</div>
            <a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Perfis</a>
            <a href="gerenciar_dns.php" class="nav-link"><i class="fas fa-network-wired"></i> Servidores</a>
            <a href="gerenciar_admins.php" class="nav-link"><i class="fas fa-user-shield"></i> Admins</a>
            <a href="personalizar_painel.php" class="nav-link"><i class="fas fa-paint-brush"></i> Personalizar</a>
            <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Configurações</a>
            <a href="gerenciar_ips.php" class="nav-link"><i class="fas fa-shield-halved"></i> Firewall IPs</a>
            <a href="gerenciar_backups.php" class="nav-link"><i class="fas fa-database"></i> Backup</a>
        <?php endif; ?>

        <div class="nav-group-title">MENU</div>
        <a href="revendedores.php" class="nav-link"><i class="fas fa-store"></i> Revendedores</a>
        <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="monitor.php" class="nav-link"><i class="fas fa-wifi"></i> Monitor</a>
        <a href="config_mp_revenda.php" class="nav-link"><i class="fas fa-wallet"></i> Pagamento</a>
        <a href="gerenciar_planos.php" class="nav-link"><i class="fas fa-tags"></i> Planos</a>
        <a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> SMTP Email</a>
        <a href="gerador_robo.php" class="nav-link active"><i class="fas fa-robot"></i> WhatsAuto</a>
        
        <a href="sair.php" class="nav-link text-danger mt-4"><i class="fas fa-sign-out-alt"></i> Sair</a>
    </div>
</nav>

<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">WhatsAuto Robot</div>
        </div>
        <div class="header-icons">
            <a href="sair.php" class="btn btn-danger btn-sm rounded-pill px-3"><i class="fas fa-power-off me-1"></i> Sair</a>
        </div>
    </div>

    <div class="container-fluid p-4">
        <div class="card-generator p-4 shadow-lg">
            <div class="text-center mb-4">
                <div class="display-4 text-primary mb-2"><i class="fas fa-robot"></i></div>
                <h3 class="fw-bold text-white">Robô Automático</h3>
                <p class="text-white">Gere seu link exclusivo para integrar ao app WhatsAuto.</p>
            </div>

            <div class="mb-4">
                <label class="form-label fw-bold text-white-50 small text-uppercase">1. Seu Usuário (Identificador)</label>
                <input type="text" class="form-control input-dark" id="revendedor" value="<?= htmlspecialchars($usuarioLogado) ?>" readonly style="opacity: 0.6; cursor: not-allowed;">
            </div>

            <div class="mb-4">
                <label class="form-label fw-bold text-white-50 small text-uppercase">2. Palavra-chave de Ativação</label>
                <div class="aviso-box">
                    <i class="fas fa-info-circle me-2 text-primary"></i> 
                    Esta é a frase que o cliente digita no WhatsApp para receber o teste. (Ex: <b>teste cs</b>)
                </div>
                <input type="text" id="palavra" class="form-control input-dark" placeholder="Ex: teste cs">
            </div>

            <button type="button" class="btn btn-success btn-lg w-100 fw-bold mb-5 shadow" id="btn_salvar" onclick="salvarPalavra()">
                <i class="fas fa-save me-2"></i> SALVAR E GERAR LINK
            </button>

            <div class="border-top border-secondary pt-4">
                <label class="form-label fw-bold text-info small text-uppercase">Link Exclusivo para Webhook</label>
                <div class="input-group">
                    <input type="text" id="link_gerado" class="form-control input-dark font-monospace" readonly placeholder="Gere o link acima primeiro...">
                    <button class="btn btn-primary px-4 fw-bold" type="button" id="btn_copiar" onclick="copiarLink()">COPIAR</button>
                </div>
                <small class="text-white mt-2 d-block text-center">Cole este link na configuração de "Server" do app WhatsAuto.</small>
            </div>
        </div>
    </div>
</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'); 
    }

    window.onload = function() {
        let rev = document.getElementById('revendedor').value.trim();
        let palavraSalva = localStorage.getItem('palavra_robo_' + rev);
        if (palavraSalva) {
            document.getElementById('palavra').value = palavraSalva;
            gerarLink();
        }
    };

    function salvarPalavra() {
        let rev = document.getElementById('revendedor').value.trim();
        let palavra = document.getElementById('palavra').value.trim().toLowerCase();
        if(!palavra) { alert("Por favor, digite uma palavra-chave primeiro!"); return; }
        
        localStorage.setItem('palavra_robo_' + rev, palavra);
        gerarLink();
        
        var btnSalvar = document.getElementById("btn_salvar");
        btnSalvar.innerHTML = "<i class='fas fa-check-circle me-2'></i> CONFIGURAÇÃO SALVA!";
        btnSalvar.classList.replace("btn-success", "btn-dark");
        setTimeout(() => {
            btnSalvar.innerHTML = "<i class='fas fa-save me-2'></i> SALVAR E GERAR LINK";
            btnSalvar.classList.replace("btn-dark", "btn-success");
        }, 2500);
    }

    function gerarLink() {
        const base_url = window.location.origin + window.location.pathname.replace(/[^/]*$/, '') + 'webhook_cs.php';
        let rev = document.getElementById('revendedor').value.trim();
        let palavra = document.getElementById('palavra').value.trim().toLowerCase();
        if(!palavra) { palavra = 'teste cs'; }
        const linkFinal = base_url + '?rev=' + encodeURIComponent(rev) + '&palavra=' + encodeURIComponent(palavra);
        document.getElementById('link_gerado').value = linkFinal;
    }

    function copiarLink() {
        var copyText = document.getElementById("link_gerado");
        if(!copyText.value) { alert("Gere o link antes de copiar!"); return; }
        var btn = document.getElementById("btn_copiar");
        copyText.select();
        copyText.setSelectionRange(0, 99999);
        document.execCommand("copy");
        
        var original = btn.innerHTML;
        btn.innerHTML = "OK!";
        btn.classList.replace("btn-primary", "btn-success");
        setTimeout(() => { 
            btn.innerHTML = original; 
            btn.classList.replace("btn-success", "btn-primary"); 
        }, 2000);
    }
</script>
</body>
</html>