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

// 1. Verifica login
if (!isset($_SESSION['usuario']) || empty($_SESSION['usuario'])) { header("Location: index.php"); exit; }
$login_atual = $_SESSION['usuario'];
$usuarioLogado = $_SESSION['usuario']; // CORREÇÃO AQUI: Declarada a variável para o menu lateral ler
$isAdmin = (strtolower($_SESSION['nivel'] ?? '') === 'admin');

// --- 2. BUSCA CONFIGURAÇÕES DO SITE (NOME E COR) ---
$nomePainel = "IPTV PANEL"; 
$corPrimaria = "#7367f0"; 
try {
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config WHERE id=1 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) { }


// --- 3. CORREÇÃO DO MENU LATERAL (MENSAGENS NÃO LIDAS) ---
$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) { }

// --- 3.1 CRIA TABELA DE WHATSAPP SE NÃO EXISTIR ---
try {
    $connGeral->exec("CREATE TABLE IF NOT EXISTS whatsapp_config (
        id INT AUTO_INCREMENT PRIMARY KEY,
        CadUser VARCHAR(50) NOT NULL,
        whatsapp VARCHAR(50)
    )");
} catch (Exception $e) { }

// --- 3.2 CRIA MODELOS SE NÃO EXISTIREM ---
$check = $connGeral->prepare("SELECT count(*) FROM email_modelo WHERE CadUser = ?");
$check->execute([$login_atual]);
if ($check->fetchColumn() == 0) {
    // Blindagem inicial em Base64
    $textoTeste = '[B64]' . base64_encode("Olá {nome}, seu teste foi liberado com sucesso! 🚀\n\nSeus dados de acesso:\nUsuário: {login}\nSenha: {senha}\nVencimento: {vencimento}\n\nConfiguração no App:\nURL/DNS: {url}\nPorta: {porta}\n\nAproveite! 📺");
    $textoVenc  = '[B64]' . base64_encode("Olá {nome}, sua assinatura vence em breve no dia {vencimento}. ⚠️\n\nNão deixe de renovar seu usuário: {login}.");
    
    $padroes = [
        ['teste', 'Seu Teste Solicitado - {nome}', $textoTeste, 'nao'],
        ['vencimento', 'Aviso de Vencimento', $textoVenc, 'nao']
    ];
    $ins = $connGeral->prepare("INSERT INTO email_modelo (tipo, assunto, mensagem, CadUser, bloqueado) VALUES (?, ?, ?, ?, ?)");
    foreach ($padroes as $p) { $ins->execute([$p[0], $p[1], $p[2], $login_atual, $p[3]]); }
}

$msg = "";

// --- 4. SALVAR MODELO (COM BLINDAGEM BASE64) ---
if (isset($_POST['salvar_modelo'])) {
    $ativo = isset($_POST['ativo']) ? 'nao' : 'sim'; 
    $assunto_seguro = $_POST['assunto'];
    
    // O SEGREDO ESTÁ AQUI: Criptografa o texto pra não bugar no banco de dados latin1
    $mensagem_segura = '[B64]' . base64_encode($_POST['mensagem']);
    
    $upd = $connGeral->prepare("UPDATE email_modelo SET assunto=?, mensagem=?, bloqueado=? WHERE id=? AND CadUser=?");
    if ($upd->execute([$assunto_seguro, $mensagem_segura, $ativo, $_POST['id_modelo'], $login_atual])) {
        $msg = "<div class='alert alert-success fw-bold border-0 shadow-sm'>Modelo de e-mail salvo com sucesso! Emojis protegidos. 🚀</div>";
    }
}

// --- 5. SALVAR SMTP ---
if (isset($_POST['salvar_smtp'])) {
    $email = $_POST['email']; $senha = $_POST['senha']; $porta = $_POST['porta'];
    $existe = $connGeral->prepare("SELECT id FROM email_adicionar WHERE CadUser=?");
    $existe->execute([$login_atual]);
    
    if ($existe->rowCount() > 0) {
        $sql = "UPDATE email_adicionar SET email=?, senha=?, Port=?, Host='smtp.gmail.com' WHERE CadUser=?";
        $connGeral->prepare($sql)->execute([$email, $senha, $porta, $login_atual]);
    } else {
        $sql = "INSERT INTO email_adicionar (email, senha, Port, Host, CadUser, bloqueado) VALUES (?, ?, ?, 'smtp.gmail.com', ?, 'nao')";
        $connGeral->prepare($sql)->execute([$email, $senha, $porta, $login_atual]);
    }
    $msg = "<div class='alert alert-success fw-bold border-0 shadow-sm'>Configuração SMTP salva!</div>";
}

// --- 5.1 SALVAR WHATSAPP ---
if (isset($_POST['salvar_whatsapp'])) {
    $wpp = strip_tags($_POST['whatsapp']);
    $checkWpp = $connGeral->prepare("SELECT id FROM whatsapp_config WHERE CadUser = ?");
    $checkWpp->execute([$login_atual]);
    
    if ($checkWpp->rowCount() > 0) {
        $connGeral->prepare("UPDATE whatsapp_config SET whatsapp = ? WHERE CadUser = ?")->execute([$wpp, $login_atual]);
    } else {
        $connGeral->prepare("INSERT INTO whatsapp_config (CadUser, whatsapp) VALUES (?, ?)")->execute([$login_atual, $wpp]);
    }
    $msg = "<div class='alert alert-success fw-bold border-0 shadow-sm'>WhatsApp salvo com sucesso!</div>";
}

// --- 6. BUSCA DADOS ---
$modelos = $connGeral->prepare("SELECT * FROM email_modelo WHERE CadUser = ?");
$modelos->execute([$login_atual]);
$lista_modelos = $modelos->fetchAll(PDO::FETCH_ASSOC);

$smtp = $connGeral->prepare("SELECT * FROM email_adicionar WHERE CadUser = ?");
$smtp->execute([$login_atual]);
$config_smtp = $smtp->fetch(PDO::FETCH_ASSOC);

$stmtWpp = $connGeral->prepare("SELECT whatsapp FROM whatsapp_config WHERE CadUser = ? LIMIT 1");
$stmtWpp->execute([$login_atual]);
$meu_whatsapp = $stmtWpp->fetchColumn() ?: "";
?>

<!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>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: #151521; 
            --bg-card: #1e1e2d; 
            --text-color: #d0d2d6; 
            --border-color: #2b2b40;
            --overlay-desk: rgba(0, 0, 0, 0.65); 
            --overlay-mob: rgba(0, 0, 0, 0.85); 
        }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; padding: 0; }
        
        /* SCROLLBAR */
        ::-webkit-scrollbar { width: 8px; height: 8px; }
        ::-webkit-scrollbar-track { background: var(--bg-body); }
        ::-webkit-scrollbar-thumb { background: #444; border-radius: 4px; }
        ::-webkit-scrollbar-thumb:hover { background: var(--primary); }

        /* MENU LATERAL */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid var(--border-color); z-index: 1050; padding: 20px; overflow-y: auto; transition: transform 0.3s ease, box-shadow 0.3s ease; }
        .sidebar .nav-link { white-space: nowrap !important; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; color: #a6a6b7; padding: 12px 15px; border-radius: 8px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .sidebar .nav-link:hover, .sidebar .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .sidebar .nav-link i.fa-fw { margin-right: 8px; text-align: center; }
        .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; padding-bottom: 30px;}
        
        /* HEADER */
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--overlay-desk) 100%), var(--primary); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 30px;}
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; margin: 0; }

        /* CARDS E ELEMENTOS PREMIUM */
        .card-custom { background: var(--bg-card) !important; border: 1px solid var(--border-color); border-radius: 12px; }
        
        .form-control { background: #111 !important; border: 1px solid var(--border-color) !important; color: #fff !important; border-radius: 8px; padding: 12px 15px; transition: 0.2s; font-weight: normal; }
        .form-control:focus { border-color: var(--primary) !important; box-shadow: 0 0 0 0.25rem rgba(115, 103, 240, 0.25) !important; }
        .form-control:read-only { background: #1a1a24 !important; color: #a6a6b7 !important; }

        .label-visivel { color: #ffffff !important; font-weight: 700 !important; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.5px; display: block; margin-bottom: 8px; }
        
        /* MENU ABAS (TABS) PREMIUM */
        .nav-pills-custom { background: rgba(0,0,0,0.2); padding: 8px; border-radius: 12px; gap: 8px; display: flex; flex-wrap: wrap; }
        .nav-pills-custom .nav-link { color: #a6a6b7; border-radius: 8px; font-weight: 600; padding: 12px 20px; transition: 0.3s; flex: 1; text-align: center; border: none; background: transparent;}
        .nav-pills-custom .nav-link:hover { color: #fff; background: rgba(255,255,255,0.05); }
        .nav-pills-custom .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 10px rgba(0,0,0,0.3); }
        
        /* TAGS */
        .tag-legend { background: rgba(0, 207, 232, 0.05); border: 1px dashed rgba(0, 207, 232, 0.3); border-radius: 12px; padding: 20px; color: #fff; }
        .tag-badge { background: rgba(0, 207, 232, 0.15); color: #00cfe8; font-weight: 700; margin-right: 8px; margin-bottom: 8px; display: inline-block; padding: 6px 14px; border-radius: 6px; font-size: 0.8rem; border: 1px solid rgba(0, 207, 232, 0.3); letter-spacing: 0.5px;}

        @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; } 
            .top-header { flex-direction: row; padding: 15px 20px; background: linear-gradient(var(--overlay-mob), var(--overlay-mob)), var(--primary); }
            .nav-pills-custom { flex-direction: column; }
            .nav-pills-custom .nav-link { width: 100%; text-align: left; }
        }
        .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.7); z-index: 1040; backdrop-filter: blur(3px); }
        .overlay.show { display: block; }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>
<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<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">Configurações Pessoais</div>
        </div>
        <div class="d-none d-lg-block ms-4 text-white-50 small text-nowrap">
            Configurações de SMTP, Mensagens e WhatsApp
        </div>
    </div>

    <div class="container-fluid px-3 px-md-4">
        
        <?= $msg ?>

        <!-- ABAS PREMIUM -->
        <ul class="nav nav-pills-custom mb-4 shadow-sm" id="emailTabs">
            <li class="nav-item">
                <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#smtp"><i class="fas fa-envelope me-2"></i> SERVIDOR (GMAIL)</button>
            </li>
            <li class="nav-item">
                <button class="nav-link" data-bs-toggle="tab" data-bs-target="#modelos"><i class="fas fa-comment-alt me-2"></i> MENSAGENS</button>
            </li>
            <li class="nav-item">
                <button class="nav-link text-success" data-bs-toggle="tab" data-bs-target="#whatsappTab"><i class="fab fa-whatsapp me-2"></i> WHATSAPP</button>
            </li>
        </ul>

        <div class="tab-content card card-custom shadow-sm border-0 p-2 p-md-4">
            
            <!-- ABA SMTP -->
            <div class="tab-pane fade show active" id="smtp">
                <h5 class="fw-bold mb-4" style="color: var(--text-color);"><i class="fas fa-server text-primary me-2"></i> Configuração de E-mail (SMTP)</h5>
                <form method="POST">
                    <div class="row g-4">
                        <div class="col-md-8">
                            <label class="label-visivel text-info">SERVIDOR (GMAIL)</label>
                            <input type="text" class="form-control" value="smtp.gmail.com" readonly>
                        </div>
                        <div class="col-md-4">
                            <label class="label-visivel text-warning">PORTA</label>
                            <input type="number" name="porta" class="form-control fw-bold" value="<?= htmlspecialchars($config_smtp['Port'] ?? '465') ?>">
                        </div>
                        <div class="col-md-12">
                            <label class="label-visivel">SEU E-MAIL (Onde será enviado)</label>
                            <input type="email" name="email" class="form-control" placeholder="exemplo@gmail.com" value="<?= htmlspecialchars($config_smtp['email'] ?? '') ?>" required>
                        </div>
                        <div class="col-md-12">
                            <label class="label-visivel">SENHA DE APLICATIVO DO GMAIL</label>
                            <input type="text" name="senha" class="form-control" placeholder="Cole a senha gerada pelo Google" value="<?= htmlspecialchars($config_smtp['senha'] ?? '') ?>" required>
                        </div>
                        <div class="col-12 mt-4 text-end">
                            <button type="submit" name="salvar_smtp" class="btn btn-primary fw-bold px-5 py-2 shadow-sm rounded-pill"><i class="fas fa-save me-2"></i> SALVAR CONFIGURAÇÃO SMTP</button>
                        </div>
                    </div>
                </form>
            </div>

            <!-- ABA MODELOS DE EMAIL -->
            <div class="tab-pane fade" id="modelos">
                <div class="tag-legend mb-4 shadow-sm">
                    <p class="mb-2 fw-bold text-info fs-5"><i class="fas fa-code me-2"></i> Variáveis Automáticas</p>
                    <p class="small mb-3 text-white-50">Copie as tags abaixo e cole na sua mensagem. O sistema vai trocar automaticamente pelos dados reais do cliente na hora do envio.</p>
                    <div class="d-flex flex-wrap">
                        <span class="tag-badge">{nome}</span>
                        <span class="tag-badge">{login}</span>
                        <span class="tag-badge">{senha}</span>
                        <span class="tag-badge">{vencimento}</span>
                        <span class="tag-badge">{url}</span>
                        <span class="tag-badge">{porta}</span>
                    </div>
                </div>

                <div class="row g-4">
                <?php foreach($lista_modelos as $m): 
                    // DESCRIPTOGRAFA O TEXTO PARA EXIBIR NA TELA PERFEITAMENTE
                    $msg_db = $m['mensagem'];
                    if (strpos($msg_db, '[B64]') === 0) {
                        $mensagem_exibir = htmlspecialchars(base64_decode(substr($msg_db, 5)));
                    } else {
                        // Caso seja um modelo antigo
                        $decoded = @json_decode($msg_db, true);
                        $mensagem_exibir = htmlspecialchars($decoded !== null ? $decoded : $msg_db);
                    }
                ?>
                    <div class="col-12">
                        <div class="p-4 border-0 rounded-4 shadow-sm bg-dark" style="border: 1px solid var(--border-color) !important;">
                            <form method="POST">
                                <input type="hidden" name="id_modelo" value="<?= $m['id'] ?>">
                                <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
                                    <span class="badge bg-primary fs-6 px-4 py-2 shadow-sm rounded-pill"><i class="fas fa-paper-plane me-2"></i> <?= strtoupper($m['tipo']) ?></span>
                                    <div class="form-check form-switch d-flex align-items-center gap-2 m-0 p-0">
                                        <label class="small fw-bold text-white mb-0">ATIVAR ENVIO AUTOMÁTICO</label>
                                        <input class="form-check-input m-0" type="checkbox" style="width: 40px; height: 20px; cursor:pointer;" name="ativo" <?= ($m['bloqueado'] == 'nao') ? 'checked' : '' ?>>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label class="label-visivel">ASSUNTO DO E-MAIL</label>
                                    <input type="text" name="assunto" class="form-control" value="<?= htmlspecialchars($m['assunto']) ?>">
                                </div>
                                <div class="mb-4">
                                    <label class="label-visivel">MENSAGEM DO CORPO</label>
                                    <textarea name="mensagem" class="form-control" rows="6"><?= $mensagem_exibir ?></textarea>
                                </div>
                                <div class="text-end">
                                    <button type="submit" name="salvar_modelo" class="btn btn-primary fw-bold px-4 py-2 shadow-sm rounded-pill"><i class="fas fa-save me-1"></i> SALVAR MODELO <?= strtoupper($m['tipo']) ?></button>
                                </div>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
                </div>
            </div>
            
            <!-- ABA WHATSAPP -->
            <div class="tab-pane fade" id="whatsappTab">
                <h5 class="fw-bold mb-4" style="color: var(--text-color);"><i class="fab fa-whatsapp text-success me-2"></i> Configuração do WhatsApp</h5>
                <form method="POST">
                    <div class="row g-4">
                        <div class="col-md-12">
                            <label class="label-visivel text-success">SEU NÚMERO DE WHATSAPP (Apenas números, com DDD)</label>
                            <input type="text" name="whatsapp" class="form-control form-control-lg fw-bold" placeholder="Ex: 5547988870797" value="<?= htmlspecialchars($meu_whatsapp) ?>" required>
                            <small class="text-white-50 mt-2 d-block"><i class="fas fa-info-circle text-info me-1"></i> Este número será utilizado na tela final do Teste Automático, para que o cliente saiba qual é o seu contato de suporte.</small>
                        </div>
                        <div class="col-12 mt-4 text-end">
                            <button type="submit" name="salvar_whatsapp" class="btn btn-success fw-bold px-5 py-2 shadow-sm rounded-pill"><i class="fas fa-save me-2"></i> SALVAR NÚMERO WHATSAPP</button>
                        </div>
                    </div>
                </form>
            </div>

        </div>
    </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'); 
    }
</script>
</body>
</html>