<?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'];
$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. CRIA MODELOS SE NÃO EXISTIREM (COM AS NOVAS TAGS) ---
$check = $connGeral->prepare("SELECT count(*) FROM email_modelo WHERE CadUser = ?");
$check->execute([$login_atual]);
if ($check->fetchColumn() == 0) {
    $padroes = [
        ['teste', 'Seu Teste Solicitado - {nome}', "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!", 'nao'],
        ['vencimento', 'Aviso de Vencimento', "Olá {nome}, sua assinatura vence em breve no dia {vencimento}.\n\nNão deixe de renovar seu usuário: {login}.", '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 ---
if (isset($_POST['salvar_modelo'])) {
    $ativo = isset($_POST['ativo']) ? 'nao' : 'sim'; // 'nao' significa NÃO bloqueado (ativo)
    $upd = $connGeral->prepare("UPDATE email_modelo SET assunto=?, mensagem=?, bloqueado=? WHERE id=? AND CadUser=?");
    if ($upd->execute([$_POST['assunto'], $_POST['mensagem'], $ativo, $_POST['id_modelo'], $login_atual])) {
        $msg = "<div class='alert alert-success fw-bold'>Modelo de e-mail salvo com sucesso!</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'>Configuração SMTP salva!</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);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>E-mails | <?= 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; }
        body { background: var(--bg-body); color: #fff; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; }
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid #333; z-index: 1050; padding: 20px; transition: 0.3s; }
        .main-content { margin-left: 260px; padding: 30px; transition: 0.3s; }
        .nav-link { color: #a6a6b7; padding: 10px 12px; border-radius: 8px; display: flex; align-items: center; gap: 10px; text-decoration: none; margin-bottom: 2px; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 20px 0 10px 12px; }
        
        /* ALTA VISIBILIDADE */
        label { color: #ffffff !important; font-weight: 700 !important; margin-bottom: 8px; display: block; text-shadow: 1px 1px 2px #000; }
        .form-control { background: #ffffff !important; color: #000000 !important; font-weight: 600; }
        .card-custom { background: var(--bg-card); border: 1px solid #444; border-radius: 0 0 12px 12px; padding: 25px; }
        @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; background: none; border: none; color: #fff; font-size: 1.5rem; margin-bottom: 20px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; }
        .overlay.show { display: block; }
        
        .tag-legend { background: rgba(0, 207, 232, 0.1); border: 1px dashed #00cfe8; border-radius: 8px; padding: 15px; color: #fff; font-size: 0.9rem; }
        .tag-badge { background: #00cfe8; color: #000; font-weight: bold; margin-right: 5px; margin-bottom: 5px; display: inline-block; padding: 4px 8px; border-radius: 5px; }
    </style>
</head>
<body>

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

<nav class="sidebar" id="sidebar">
    <h4 class="mb-4 fw-bold text-center text-white"><i class="fas fa-tv text-primary"></i> <?= htmlspecialchars($nomePainel) ?></h4>
    <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">Administração</div>
            <a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Gerenciar Perfis</a>
            <a href="gerenciar_dns.php" class="nav-link"><i class="fas fa-network-wired"></i> Servidores DNS</a>
            <a href="gerenciar_admins.php" class="nav-link"><i class="fas fa-user-shield"></i> Gestão de Admins</a>
            <a href="gerenciar_email.php" class="nav-link active"><i class="fas fa-envelope"></i> Config. E-mail</a>
            <a href="personalizar_painel.php" class="nav-link"><i class="fas fa-paint-brush"></i> Personalizar</a>
            <a href="gerenciar_backups.php" class="nav-link"><i class="fas fa-database"></i> Backups</a>
            <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Config. Geral</a>
        <?php endif; ?>
        <div class="nav-group-title">Operacional</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="status_online.php" class="nav-link"><i class="fas fa-wifi"></i> Monitor Online</a>
        <hr class="border-secondary mt-4"><a href="sair.php" class="nav-link text-danger"><i class="fas fa-sign-out-alt"></i> Sair</a>
    </div>
</nav>

<main class="main-content">
    <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
    <h3 class="fw-bold mb-4">Gestão de E-mails</h3>

    <?= $msg ?>

    <ul class="nav nav-tabs border-0" id="emailTabs">
        <li class="nav-item flex-grow-1"><button class="nav-link active w-100 py-3 fw-bold" data-bs-toggle="tab" data-bs-target="#smtp">SERVIDOR (GMAIL)</button></li>
        <li class="nav-item flex-grow-1"><button class="nav-link w-100 py-3 fw-bold" data-bs-toggle="tab" data-bs-target="#modelos">MENSAGENS</button></li>
    </ul>

    <div class="tab-content card card-custom shadow-lg">
        <div class="tab-pane fade show active" id="smtp">
            <form method="POST">
                <div class="row g-3">
                    <div class="col-md-8"><label>SERVIDOR (GMAIL)</label><input type="text" class="form-control" value="smtp.gmail.com" readonly></div>
                    <div class="col-md-4"><label>PORTA</label><input type="number" name="porta" class="form-control" value="<?= $config_smtp['Port'] ?? '587' ?>"></div>
                    <div class="col-md-12"><label>SEU EMAIL (Onde será enviado)</label><input type="email" name="email" class="form-control" value="<?= $config_smtp['email'] ?? '' ?>" required></div>
                    <div class="col-md-12"><label>SENHA DE APLICATIVO DO GMAIL</label><input type="text" name="senha" class="form-control" value="<?= $config_smtp['senha'] ?? '' ?>" required></div>
                    <div class="col-12 mt-4"><button type="submit" name="salvar_smtp" class="btn btn-success w-100 fw-bold p-3">SALVAR CONFIGURAÇÃO</button></div>
                </div>
            </form>
        </div>

        <div class="tab-pane fade" id="modelos">
            <div class="tag-legend mb-4">
                <p class="mb-2 fw-bold"><i class="fas fa-info-circle me-1"></i> Variáveis Automáticas:</p>
                <p class="small mb-2 text-white-50">Copie as tags abaixo e cole na sua mensagem. O sistema vai trocar pelos dados do cliente na hora de enviar.</p>
                <div>
                    <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>

            <?php foreach($lista_modelos as $m): ?>
            <div class="mb-4 p-3 border rounded border-secondary" style="background: rgba(255,255,255,0.05);">
                <form method="POST">
                    <input type="hidden" name="id_modelo" value="<?= $m['id'] ?>">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <span class="badge bg-primary fs-6"><?= strtoupper($m['tipo']) ?></span>
                        <div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="ativo" <?= ($m['bloqueado'] == 'nao') ? 'checked' : '' ?>><label class="ms-1 small">Ativar Envio Automático</label></div>
                    </div>
                    <div class="mb-2"><label>Assunto do E-mail</label><input type="text" name="assunto" class="form-control" value="<?= htmlspecialchars($m['assunto']) ?>"></div>
                    <div class="mb-3"><label>Mensagem</label><textarea name="mensagem" class="form-control" rows="8"><?= htmlspecialchars($m['mensagem']) ?></textarea></div>
                    <button type="submit" name="salvar_modelo" class="btn btn-primary btn-sm px-4 fw-bold">SALVAR MODELO</button>
                </form>
            </div>
            <?php endforeach; ?>
        </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'); }
</script>
</body>
</html>
