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

// --- FORÇA O BANCO DE DADOS A ACEITAR EMOJIS (UTF8MB4) ---
try {
    $connUser->exec("SET NAMES utf8mb4");
    $connGeral->exec("SET NAMES utf8mb4");
} catch (Exception $e) {}

// --- 1. TRAVA DE SEGURANÇA TOTAL ---
if (!isset($_SESSION['logado'])) { 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) { }

$total_msg_nao_lidas = 0;
try {
    $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) { }

// --- ATUALIZAÇÃO DA TABELA PARA SEPARAR POR REVENDEDOR ---
try {
    $connGeral->exec("CREATE TABLE IF NOT EXISTS `config_api_whatsapp` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `usuario` varchar(50) DEFAULT NULL,
      `api_url` varchar(255) DEFAULT '',
      `api_key` varchar(255) DEFAULT '',
      `instancia` varchar(100) DEFAULT '',
      `msg_novo` text DEFAULT NULL,
      `msg_renovacao` text DEFAULT NULL,
      `msg_cobranca` text DEFAULT NULL,
      `msg_email_novo` text DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
    
    // Adiciona a coluna se a tabela for antiga
    $connGeral->exec("ALTER TABLE config_api_whatsapp ADD COLUMN IF NOT EXISTS usuario VARCHAR(50) DEFAULT NULL");
    $connGeral->exec("ALTER TABLE config_api_whatsapp ADD COLUMN IF NOT EXISTS msg_email_novo TEXT DEFAULT NULL");
} catch (Exception $e) { }

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao']) && $_POST['acao'] === 'salvar') {
    $url = trim($_POST['api_url']); $key = trim($_POST['api_key']); $inst = trim($_POST['instancia']);
    $msg_n = $_POST['msg_novo']; $msg_r = $_POST['msg_renovacao']; $msg_c = $_POST['msg_cobranca'];
    $msg_e = $_POST['msg_email_novo'];
    
    // Verifica se já tem configuração para este usuário
    $check = $connGeral->prepare("SELECT id FROM config_api_whatsapp WHERE usuario = ?");
    $check->execute([$usuarioLogado]);
    
    if ($check->rowCount() > 0) {
        $stmt = $connGeral->prepare("UPDATE config_api_whatsapp SET api_url = ?, api_key = ?, instancia = ?, msg_novo = ?, msg_renovacao = ?, msg_cobranca = ?, msg_email_novo = ? WHERE usuario = ?");
        $stmt->execute([$url, $key, $inst, $msg_n, $msg_r, $msg_c, $msg_e, $usuarioLogado]);
    } else {
        $stmt = $connGeral->prepare("INSERT INTO config_api_whatsapp (usuario, api_url, api_key, instancia, msg_novo, msg_renovacao, msg_cobranca, msg_email_novo) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$usuarioLogado, $url, $key, $inst, $msg_n, $msg_r, $msg_c, $msg_e]);
    }
    $msg = "Configurações salvas para a sua conta ($usuarioLogado)!"; $msg_tipo = "success";
}

// Puxa as configurações SOMENTE do usuário logado
$stmtConf = $connGeral->prepare("SELECT * FROM config_api_whatsapp WHERE usuario = ?");
$stmtConf->execute([$usuarioLogado]);
$config_wpp = $stmtConf->fetch(PDO::FETCH_ASSOC);
?>

<!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, maximum-scale=1.0, user-scalable=no">
    <title>Config. Mensagens | <?= 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; padding: 0; }
        .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); }
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; }
        .card-custom { background: var(--bg-card) !important; border: 1px solid var(--border-color); border-radius: 12px; overflow: hidden; margin-bottom: 20px; padding: 20px;}
        .form-control { background: #151521 !important; border: 1px solid #444 !important; color: #fff !important; }
        .form-control:focus { border-color: var(--primary); box-shadow: none; }
        
        @media (max-width: 992px) { .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; } .mobile-toggle { display: block !important; margin-right: 15px; } }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; }
        .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 w-100">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title"><i class="fas fa-cogs text-warning me-2"></i> Mensagens (<?= htmlspecialchars($usuarioLogado) ?>)</div>
        </div>
    </div>

    <div class="container-fluid p-3 p-md-4">
        <?php if(isset($msg) && $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">
            <input type="hidden" name="acao" value="salvar">
            
            <div class="row">
                <div class="col-md-4">
                    <div class="card card-custom shadow-lg">
                        <h5 class="text-info mb-3"><i class="fas fa-plug me-2"></i> Conexão API</h5>
                        <label class="small fw-bold text-white-50">URL DA API</label>
                        <input type="text" name="api_url" class="form-control mb-3" value="<?= htmlspecialchars($config_wpp['api_url'] ?? '') ?>" placeholder="http://api.seusite.com:8080" required>
                        <label class="small fw-bold text-white-50">API KEY (SENHA)</label>
                        <input type="text" name="api_key" class="form-control mb-3" value="<?= htmlspecialchars($config_wpp['api_key'] ?? '') ?>" required>
                        <label class="small fw-bold text-white-50">INSTÂNCIA</label>
                        <input type="text" name="instancia" class="form-control mb-4" value="<?= htmlspecialchars($config_wpp['instancia'] ?? '') ?>" placeholder="Ex: RevendaJoao" required>
                        <button type="submit" class="btn btn-primary w-100 fw-bold shadow-sm py-2">SALVAR TUDO</button>
                    </div>
                    
                    <div class="card card-custom border-info">
                        <h6 class="text-info fw-bold">Tags Disponíveis:</h6>
                        <p class="small text-white-50 mb-1">Use as palavras abaixo nos seus textos:</p>
                        <code class="d-block text-warning" style="background:#111; padding:10px; border-radius:5px;">{nome} <br>{usuario} <br>{senha} <br>{vencimento} <br>{link_cliente} <br>{dns} <br>{porta}</code>
                    </div>
                </div>

                <div class="col-md-8">
                    <div class="card card-custom shadow-lg">
                        <h5 class="text-success mb-4"><i class="fab fa-whatsapp me-2"></i> Modelos de Mensagens</h5>
                        
                        <div class="mb-4">
                            <label class="fw-bold text-white-50 small mb-1">1. BOAS-VINDAS (WHATSAPP)</label>
                            <textarea name="msg_novo" class="form-control text-success font-monospace" rows="5"><?= htmlspecialchars($config_wpp['msg_novo'] ?? "Olá *{nome}*, seu acesso foi criado!\n\n👤 User: {usuario}\n🔑 Senha: {senha}\n📅 Vence: {vencimento}\n\n🌐 DNS: {dns}\n🔌 Porta: {porta}") ?></textarea>
                        </div>

                        <div class="mb-4">
                            <label class="fw-bold text-white-50 small mb-1">2. RENOVAÇÃO (WHATSAPP)</label>
                            <textarea name="msg_renovacao" class="form-control text-success font-monospace" rows="4"><?= htmlspecialchars($config_wpp['msg_renovacao'] ?? "✅ Sucesso! *{nome}*, o seu plano foi renovado.\n\n👤 User: {usuario}\n📅 Novo Vencimento: {vencimento}") ?></textarea>
                        </div>

                        <div class="mb-4">
                            <label class="fw-bold text-white-50 small mb-1">3. COBRANÇA (WHATSAPP)</label>
                            <textarea name="msg_cobranca" class="form-control text-success font-monospace" rows="5"><?= htmlspecialchars($config_wpp['msg_cobranca'] ?? "⚠️ *Aviso de Vencimento*\n\nOlá *{nome}*, o seu plano está a expirar.\nRenove na sua área do cliente:\n🌐 Link: {link_cliente}\n\n👤 User: {usuario}\n🔑 Senha: {senha}") ?></textarea>
                        </div>

                        <div class="mb-3">
                            <label class="fw-bold text-white-50 small mb-1">4. MODELO DE E-MAIL (ENVIADO NO TESTE)</label>
                            <textarea name="msg_email_novo" class="form-control text-primary font-monospace" rows="6"><?= htmlspecialchars($config_wpp['msg_email_novo'] ?? "Olá {nome}, seu teste foi criado!\n\nDados:\nUsuário: {usuario}\nSenha: {senha}\n\nDNS: {dns}\nPorta: {porta}") ?></textarea>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </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'); } </script>
</body>
</html>
