<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Teste Automático</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: linear-gradient(135deg, #0f0c29, #302b63, #24243e); color: #fff; min-height: 100vh; display: flex; align-items: center; justify-content: center; font-family: 'Segoe UI', sans-serif; }
        .card-teste { background: rgba(25, 25, 35, 0.95); border: 1px solid rgba(255,255,255,0.1); border-radius: 15px; padding: 40px; width: 90%; max-width: 450px; box-shadow: 0 0 40px rgba(0,0,0,0.6); }
        .form-control, .form-select { background: #2b2b40 !important; border: 1px solid #444 !important; color: #fff !important; height: 50px; }
        .form-control:focus, .form-select:focus { border-color: #7367f0 !important; box-shadow: 0 0 10px rgba(115,103,240,0.3); }
        .btn-gradient { background: linear-gradient(45deg, #7367f0, #9e95f5); border: none; color: white; font-weight: bold; height: 50px; width: 100%; border-radius: 8px; transition: 0.3s; text-transform: uppercase; letter-spacing: 1px; }
        .btn-gradient:hover { transform: scale(1.02); box-shadow: 0 5px 15px rgba(115, 103, 240, 0.4); }
        .logo-area { text-align: center; margin-bottom: 30px; }
        .logo-area i { font-size: 3.5rem; color: #7367f0; text-shadow: 0 0 15px rgba(115,103,240,0.5); }
    </style>
</head>
<body>

<div class="card-teste">
    <?php
    ini_set('display_errors', 1); error_reporting(E_ALL);

    // Carrega PHPMailer se existir
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;
    
    if (file_exists('PHPMailer/src/Exception.php')) {
        require 'PHPMailer/src/Exception.php';
        require 'PHPMailer/src/PHPMailer.php';
        require 'PHPMailer/src/SMTP.php';
    }

    $conexao_ok = false;
    if (file_exists('conexao.php')) { include 'conexao.php'; if (isset($connUser) && isset($connGeral)) $conexao_ok = true; }

    if (!$conexao_ok): 
    ?>
        <div class="alert alert-danger text-center"><h4>Erro de Sistema</h4><p>Falha na conexão com o banco.</p></div>
    <?php else: 
        $link_user = 'admin'; $id_rev = 0; $perfis = []; $is_admin = false; $msg = ""; $msg_tipo = "";

        // Identifica revendedor
        if (isset($_GET['r'])) {
            $link_user = preg_replace('/[^a-zA-Z0-9_]/', '', base64_decode($_GET['r']));
            $admins = ['admin', 'jeanrs', 'Admin', 'Jeanrs']; 
            if (in_array($link_user, $admins)) $is_admin = true;
            else {
                $id_rev = $connUser->query("SELECT id FROM rev WHERE usuario = '$link_user'")->fetchColumn();
                if (!$id_rev) die("<div class='text-center text-white'>Link Inválido</div>");
            }
        } else $is_admin = true;

        // Busca perfis
        try {
            if ($is_admin) $perfis = $connGeral->query("SELECT id, nome FROM perfil WHERE bloqueado IS NULL OR bloqueado != 'sim'")->fetchAll(PDO::FETCH_ASSOC);
            elseif ($id_rev) {
                $ids = $connUser->query("SELECT id_perfil FROM rev_perfil WHERE id_rev = $id_rev")->fetchAll(PDO::FETCH_COLUMN);
                if (!empty($ids)) {
                    $ids_str = implode(',', $ids);
                    $perfis = $connGeral->query("SELECT id, nome FROM perfil WHERE id IN ($ids_str) AND (bloqueado IS NULL OR bloqueado != 'sim')")->fetchAll(PDO::FETCH_ASSOC);
                }
            }
        } catch (Exception $e) {}

        // --- PROCESSAMENTO (POST) ---
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $nome = strip_tags($_POST['nome']);
            $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
            $pid = (int)$_POST['perfil'];
            
            // ======================================================
            // NOVA TRAVA: VERIFICA SE O E-MAIL JÁ EXISTE NO TESTE
            // ======================================================
            try {
                $check = $connUser->prepare("SELECT id FROM teste WHERE email = ?");
                $check->execute([$email]);
                
                if ($check->rowCount() > 0) {
                    $msg = "<b>Atenção:</b> Este e-mail já possui um teste ativo ou pendente.<br>Por favor, use outro e-mail ou contate o suporte.";
                    $msg_tipo = "warning";
                } else {
                    // SE NÃO EXISTE, PROSSEGUE COM A CRIAÇÃO
                    
                    $user_teste = "t" . rand(1000, 9999) . date('s');
                    $pass_teste = rand(1000, 9999);
                    $venc = date('Y-m-d H:i:s', strtotime("+48 hours")); 
                    $venc_formatado = date('d/m/Y H:i', strtotime($venc));

                    $connUser->prepare("INSERT INTO teste (CadUser, usuario, senha, data_premio, id_perfil, email, bloqueado, data_cadastro) VALUES (?, ?, ?, ?, ?, ?, 'nao', NOW())")
                             ->execute([$link_user, $user_teste, $pass_teste, $venc, $pid, $email]);

                    // ENVIO DE E-MAIL
                    $dono = $link_user;
                    $smtp = $connGeral->prepare("SELECT * FROM email_adicionar WHERE dono = ?");
                    $smtp->execute([$dono]);
                    if($smtp->rowCount()==0) { 
                        $smtp = $connGeral->prepare("SELECT * FROM email_adicionar WHERE dono = 'admin' OR dono = 'jeanrs' LIMIT 1");
                        $smtp->execute();
                    }
                    $conf = $smtp->fetch(PDO::FETCH_ASSOC);
                    
                    $mod = $connGeral->prepare("SELECT * FROM email_modelo WHERE dono = ? AND tipo = 'teste_cs'");
                    $mod->execute([$dono]);
                    if($mod->rowCount()==0) {
                         $mod = $connGeral->prepare("SELECT * FROM email_modelo WHERE (dono = 'admin' OR dono = 'jeanrs') AND tipo = 'teste_cs' LIMIT 1");
                         $mod->execute();
                    }
                    $modelo = $mod->fetch(PDO::FETCH_ASSOC);
                    $p_dados = $connGeral->query("SELECT * FROM perfil WHERE id=$pid")->fetch(PDO::FETCH_ASSOC);

                    if($conf && $modelo && $p_dados) {
                        $corpo = str_replace(
                            ['{nome}','{usuario}','{senha}','{url}','{porta}','{tempo}','{vencimento}'], 
                            [$nome, $user_teste, $pass_teste, $p_dados['url'], $p_dados['porta'], '48', $venc_formatado], 
                            $modelo['mensagem']
                        );
                        
                        if (class_exists('PHPMailer\PHPMailer\PHPMailer')) {
                            $mail = new PHPMailer(true);
                            try {
                                $mail->isSMTP();
                                $mail->Host = $conf['Host'];
                                $mail->SMTPAuth = true;
                                $mail->Username = $conf['usuario'];
                                $mail->Password = $conf['senha'];
                                $mail->SMTPSecure = $conf['SMTPSecure']; 
                                $mail->Port = $conf['Port']; 

                                $mail->setFrom($conf['email'], $conf['servidor']);
                                $mail->addAddress($email, $nome);
                                $mail->isHTML(true);
                                $mail->Subject = $modelo['assunto'];
                                $mail->Body    = nl2br($corpo);
                                $mail->send();
                            } catch (Exception $e) {
                                $headers = "MIME-Version: 1.0\r\nContent-type:text/html;charset=UTF-8\r\nFrom: ".$conf['email'];
                                @mail($email, $modelo['assunto'], nl2br($corpo), $headers);
                            }
                        } else {
                            $headers = "MIME-Version: 1.0\r\nContent-type:text/html;charset=UTF-8\r\nFrom: ".$conf['email'];
                            @mail($email, $modelo['assunto'], nl2br($corpo), $headers);
                        }
                    }
                    $msg = "Teste Gerado com Sucesso!";
                    $msg_tipo = "success";
                } // Fim do Else (não existe email)

            } catch(Exception $e) { $msg = "Erro: ".$e->getMessage(); $msg_tipo = "danger"; }
        }
    ?>

    <div class="logo-area">
        <i class="fas fa-tv"></i>
        <h3 class="mt-3 fw-bold">Teste Automático</h3>
        <p class="text-white-50 small">Solicite seu acesso agora.</p>
    </div>

    <?php if($msg): ?>
        <div class="alert alert-<?= $msg_tipo ?> text-center border-0 shadow-sm">
            <?php if($msg_tipo == 'success'): ?>
                <i class="fas fa-check-circle fa-3x mb-3 d-block text-success"></i>
                <h4>Enviado!</h4><p>Verifique seu e-mail (e a caixa de SPAM).</p>
            <?php elseif($msg_tipo == 'warning'): ?>
                <i class="fas fa-exclamation-circle fa-3x mb-3 d-block text-warning"></i>
                <h4>Ops!</h4><p><?= $msg ?></p>
            <?php else: ?>
                <?= $msg ?>
            <?php endif; ?>
        </div>
        
        <?php if($msg_tipo == 'success'): ?>
            <div class="p-3 bg-dark rounded border border-secondary mb-3 mt-3">
                <p class="mb-2 text-white-50 small text-center">Seu acesso (anote agora):</p>
                <div class="input-group mb-2"><span class="input-group-text bg-black border-secondary text-secondary"><i class="fas fa-user"></i></span><input type="text" class="form-control text-center text-warning fw-bold bg-black" value="<?= $user_teste ?>" readonly></div>
                <div class="input-group"><span class="input-group-text bg-black border-secondary text-secondary"><i class="fas fa-key"></i></span><input type="text" class="form-control text-center text-warning fw-bold bg-black" value="<?= $pass_teste ?>" readonly></div>
            </div>
        <?php endif; ?>
        <div class="text-center mt-3"><a href="cadtest.php?r=<?= $_GET['r'] ?? '' ?>" class="btn btn-outline-light w-100">Voltar</a></div>
    <?php else: ?>
        <form method="POST">
            <div class="mb-3"><label class="form-label text-white-50">Seu Nome</label><div class="input-group"><span class="input-group-text bg-dark border-secondary text-white"><i class="fas fa-user"></i></span><input type="text" name="nome" class="form-control" placeholder="Digite seu nome" required></div></div>
            <div class="mb-3"><label class="form-label text-white-50">Seu E-mail</label><div class="input-group"><span class="input-group-text bg-dark border-secondary text-white"><i class="fas fa-envelope"></i></span><input type="email" name="email" class="form-control" placeholder="Para receber o login" required></div></div>
            <div class="mb-4"><label class="form-label text-white-50">Pacote</label><select name="perfil" class="form-select" required><?php if(empty($perfis)): ?><option value="">Indisponível</option><?php else: ?><option value="" selected disabled>Selecione...</option><?php foreach($perfis as $p): ?><option value="<?= $p['id'] ?>"><?= $p['nome'] ?></option><?php endforeach; ?><?php endif; ?></select></div>
            <button type="submit" class="btn btn-gradient" <?= empty($perfis) ? 'disabled' : '' ?>><i class="fas fa-rocket me-2"></i> GERAR TESTE</button>
        </form>
    <?php endif; ?>
    <?php endif; ?>
</div>
</body>
</html>
