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

// Verifica Login
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true) {
    header("Location: login.php"); exit;
}

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

// --- BUSCAR DADOS DO USUÁRIO ATUAL ---
$meuDono = 'Administrador';
try {
    $stmtMe = $connUser->prepare("SELECT CadUser FROM usuario WHERE usuario = ?");
    $stmtMe->execute([$usuarioLogado]);
    $resMe = $stmtMe->fetch(PDO::FETCH_ASSOC);
    if($resMe && !empty($resMe['CadUser'])) { $meuDono = $resMe['CadUser']; }
} catch (Exception $e) {}

// --- 1. PROCESSAR ENVIO DE MENSAGEM (SUPORTE) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao_suporte']) && $_POST['acao_suporte'] === 'enviar_msg') {
    $assunto = trim($_POST['assunto']);
    $mensagem = trim($_POST['mensagem']);
    $destinatario = ($isAdmin && !empty($_POST['destinatario'])) ? trim($_POST['destinatario']) : $meuDono;
    $data_envio = date('d/m/Y H:i'); 

    if(!empty($assunto) && !empty($mensagem)) {
        $sql = "INSERT INTO suporte (UserEmissor, UserReceptor, Assunto, Mensagem, data, LidaReceptor) VALUES (?, ?, ?, ?, ?, 'nao')";
        try {
            $connUser->prepare($sql)->execute([$usuarioLogado, $destinatario, $assunto, $mensagem, $data_envio]);
            echo "<script>alert('✅ Mensagem enviada com sucesso!'); location.href='dashboard.php';</script>";
        } catch (Exception $e) { }
    }
}

// --- 2. SALVAR PREFERÊNCIAS DO LINK DE TESTE ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao_pref']) && $_POST['acao_pref'] === 'salvar_config_teste') {
    $email = $_POST['email_copia'];
    $ativo = isset($_POST['receber_copia']) ? 'sim' : 'nao';
    // Garante tabela
    $connUser->exec("CREATE TABLE IF NOT EXISTS usuario_pref (id INT AUTO_INCREMENT PRIMARY KEY, usuario VARCHAR(50) UNIQUE, email_copia VARCHAR(100), receber_copia ENUM('sim','nao'))");
    
    $sql = "INSERT INTO usuario_pref (usuario, email_copia, receber_copia) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE email_copia = VALUES(email_copia), receber_copia = VALUES(receber_copia)";
    try {
        $connUser->prepare($sql)->execute([$usuarioLogado, $email, $ativo]);
        echo "<script>alert('Configurações salvas!'); location.href='dashboard.php';</script>";
    } catch (Exception $e) { }
}

// --- 3. CONFIGURAÇÕES VISUAIS E DADOS ---
$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) { }

// Estatísticas
$ativos = 0; $esgotados = 0; $bloqueados = 0; $testes_ativos = 0;
try {
    $sql = $isAdmin ? "SELECT * FROM usuario" : "SELECT * FROM usuario WHERE CadUser = '$usuarioLogado'";
    $usuarios = $connUser->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    foreach ($usuarios as $u) {
        $venc = is_numeric($u['data_premio']) ? $u['data_premio'] : strtotime($u['data_premio']);
        if ($u['bloqueado'] == 'sim') { $bloqueados++; } elseif ($venc < time()) { $esgotados++; } else { $ativos++; }
    }
    $sql_t = $isAdmin ? "SELECT COUNT(*) FROM teste" : "SELECT COUNT(*) FROM teste WHERE CadUser = '$usuarioLogado'";
    $testes_ativos = $connUser->query($sql_t)->fetchColumn();
} catch (Exception $e) { }

// Servidores
$lista_servidores = [];
try {
    if ($isAdmin) {
        $lista_servidores = $connGeral->query("SELECT nome, url, porta FROM perfil WHERE bloqueado IS NULL OR bloqueado != 'sim'")->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $st_rev = $connUser->prepare("SELECT perfil FROM rev WHERE usuario = ?");
        $st_rev->execute([$usuarioLogado]);
        $perfis_liberados = $st_rev->fetchColumn();
        if (!empty($perfis_liberados)) {
            $nomes_perfis = explode(',', $perfis_liberados);
            $in_query = str_repeat('?,', count($nomes_perfis) - 1) . '?';
            $st_p = $connGeral->prepare("SELECT nome, url, porta FROM perfil WHERE nome IN ($in_query) AND (bloqueado IS NULL OR bloqueado != 'sim')");
            $st_p->execute($nomes_perfis);
            $lista_servidores = $st_p->fetchAll(PDO::FETCH_ASSOC);
        }
    }
} catch (Exception $e) { }

// Link de Teste e Prefs
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
$urlTeste = $protocol . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/cadtest.php?r=" . base64_encode($usuarioLogado);
$pref_email = ""; $pref_ativo = "nao";
try {
    $stmtPref = $connUser->prepare("SELECT email_copia, receber_copia FROM usuario_pref WHERE usuario = ?");
    $stmtPref->execute([$usuarioLogado]);
    $resPref = $stmtPref->fetch(PDO::FETCH_ASSOC);
    if($resPref) { $pref_email = $resPref['email_copia']; $pref_ativo = $resPref['receber_copia']; }
} catch (Exception $e) { }

// --- 4. LISTAR MENSAGENS (CAIXA DE ENTRADA) ---
$mensagens = [];
$total_msg_nao_lidas = 0;
try {
    $stmtMsg = $connUser->prepare("SELECT * FROM suporte WHERE UserReceptor = ? ORDER BY id DESC LIMIT 20");
    $stmtMsg->execute([$usuarioLogado]);
    $mensagens = $stmtMsg->fetchAll(PDO::FETCH_ASSOC);
    foreach($mensagens as $m) { if(isset($m['LidaReceptor']) && $m['LidaReceptor'] == 'nao') $total_msg_nao_lidas++; }
} catch (Exception $e) { } 

// Check Status Real
function checkStatusReal($url, $porta) {
    $host = preg_replace('#^https?://#', '', $url); $host = rtrim($host, '/'); 
    $connection = @fsockopen($host, $porta, $errno, $errstr, 1); 
    if ($connection) { fclose($connection); return true; } return false;
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard | <?= 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; }
        
        .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; padding: 0; transition: 0.3s; }
        
        .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; box-shadow: 0 2px 10px rgba(0,0,0,0.3); margin-bottom: 30px; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .header-title { font-size: 1.5rem; font-weight: 800; color: #fff; letter-spacing: 1px; text-transform: uppercase; }
        
        .header-icons { display: flex; align-items: center; gap: 10px; }
        .btn-icon { color: #fff; background: rgba(255,255,255,0.15); border: none; width: 42px; height: 42px; border-radius: 50%; display: flex; align-items: center; justify-content: center; transition: 0.2s; position: relative; cursor: pointer; text-decoration: none; }
        .btn-icon:hover { background: rgba(255,255,255,0.3); transform: translateY(-2px); color: #fff; }
        .badge-notif { position: absolute; top: 0; right: 0; width: 12px; height: 12px; background: #ea5455; border-radius: 50%; border: 2px solid var(--bg-card); }

        .content-wrapper { padding: 0 30px 30px 30px; }
        .stat-card-row { background: var(--bg-card); border-radius: 12px; padding: 20px; display: flex; align-items: center; gap: 20px; border: 1px solid var(--border-color); margin-bottom: 15px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .stat-icon-box { width: 60px; height: 60px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.8rem; color: #fff; flex-shrink: 0; }
        .stat-info h2 { margin: 0; font-weight: 700; font-size: 2rem; color: #fff; line-height: 1; }
        .bg-icon-purple { background: linear-gradient(135deg, #7367f0 0%, #ce9ffc 100%); }
        
        .section-card { background: var(--bg-card); border-radius: 12px; border: 1px solid var(--border-color); margin-bottom: 25px; overflow: hidden; }
        .section-header { padding: 15px 20px; border-bottom: 1px solid var(--border-color); font-weight: 600; font-size: 1.1rem; color: #fff; }
        .section-body { padding: 20px; }
        .url-box { background: #2b2b40; border: 1px solid #444; color: #a6a6b7; padding: 12px; border-radius: 6px; font-family: monospace; font-size: 0.9rem; word-break: break-all; margin-bottom: 15px; }
        
        .btn-custom-light { background: #fff; color: #5e5873; border: 1px solid #d8d6de; font-weight: 600; padding: 8px 16px; border-radius: 6px; transition: 0.2s; }
        .btn-custom-info { background: #00cfe8; color: #fff; border: none; font-weight: 600; padding: 8px 16px; border-radius: 6px; float: right; cursor: pointer; text-decoration: none; }
        .btn-custom-purple { background: #7367f0; color: #fff; border: none; font-weight: 600; padding: 10px 20px; border-radius: 6px; width: 100%; margin-top: 10px; }
        
        .table-custom { width: 100%; border-collapse: collapse; }
        .table-custom th { text-align: left; padding: 12px 15px; color: #b9b9c3; font-size: 0.8rem; text-transform: uppercase; font-weight: 600; border-bottom: 1px solid var(--border-color); background: #252535; }
        .table-custom td { padding: 12px 15px; border-bottom: 1px solid var(--border-color); font-size: 0.9rem; color: #fff; vertical-align: middle; }
        .status-badge { padding: 4px 10px; border-radius: 4px; font-size: 0.75rem; font-weight: 700; text-transform: uppercase; }
        .status-online { background: rgba(40, 199, 111, 0.2); color: #28c76f; border: 1px solid rgba(40, 199, 111, 0.2); }
        .status-offline { background: rgba(234, 84, 85, 0.2); color: #ea5455; border: 1px solid rgba(234, 84, 85, 0.2); }
        
        .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; }
        
        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; }
            .mobile-toggle { display: block; } .header-title { font-size: 1.2rem; } .content-wrapper { padding: 0 15px 30px 15px; }
        }
    </style>
</head>
<body>

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

<nav class="sidebar" id="sidebar">
    <div class="nav flex-column mt-4">
        <a href="dashboard.php" class="nav-link active"><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="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> SMTP Email</a>
            <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Configurações</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-bell"></i> Monitor</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"><?= htmlspecialchars($nomePainel) ?></div>
        </div>
        <div class="header-icons">
            <a href="https://api.whatsapp.com/send?phone=SEUNUMERO" target="_blank" class="btn-icon" title="Suporte via WhatsApp"><i class="fab fa-whatsapp"></i></a>
            <button class="btn-icon" data-bs-toggle="modal" data-bs-target="#modalPerfil" title="Meu Perfil"><i class="fas fa-user"></i></button>
            <button class="btn-icon" data-bs-toggle="modal" data-bs-target="#modalMensagens" title="Suporte / Mensagens">
                <i class="fas fa-envelope"></i>
                <?php if($total_msg_nao_lidas > 0): ?><span class="badge-notif"></span><?php endif; ?>
            </button>
            <a href="sair.php" class="btn-icon" style="background: rgba(234,84,85,0.2); color: #ea5455;" title="Sair"><i class="fas fa-power-off"></i></a>
        </div>
    </div>

    <div class="content-wrapper">
        <div class="row">
            <div class="col-12 col-md-6 col-xl-3"><div class="stat-card-row"><div class="stat-icon-box bg-icon-purple"><i class="fas fa-user"></i></div><div class="stat-info"><h2><?= $ativos ?></h2><p style="color: #a6a6b7;">ATIVOS</p></div></div></div>
            <div class="col-12 col-md-6 col-xl-3"><div class="stat-card-row"><div class="stat-icon-box bg-icon-purple"><i class="fas fa-user-slash"></i></div><div class="stat-info"><h2><?= $esgotados ?></h2><p style="color: #a6a6b7;">ESGOTADOS</p></div></div></div>
            <div class="col-12 col-md-6 col-xl-3"><div class="stat-card-row"><div class="stat-icon-box bg-icon-purple"><i class="fas fa-user-lock"></i></div><div class="stat-info"><h2><?= $bloqueados ?></h2><p style="color: #a6a6b7;">BLOQUEADOS</p></div></div></div>
            <div class="col-12 col-md-6 col-xl-3"><div class="stat-card-row"><div class="stat-icon-box bg-icon-purple"><i class="fas fa-user-clock"></i></div><div class="stat-info"><h2><?= $testes_ativos ?></h2><p style="color: #a6a6b7;">TESTES ATIVOS</p></div></div></div>
        </div>

        <div class="section-card">
            <div class="section-header">Url de Teste</div>
            <div class="section-body">
                <div class="url-box" id="urlTesteTexto"><?= $urlTeste ?></div>
                <div class="d-flex justify-content-between align-items-center">
                    <button class="btn-custom-light" onclick="copiarUrl()"><i class="fas fa-link me-2"></i>Copiar Link</button>
                    <button class="btn-custom-info" data-bs-toggle="modal" data-bs-target="#modalConfigTeste">Configurações</button>
                </div>
            </div>
        </div>

        <div class="section-card">
            <div class="section-header">Status do Cliente</div>
            <div class="section-body">
                <p class="text-white-50 mb-3 small">Clique em <strong class="text-white">Verificar Status</strong> para verificar o estado atual da sua conexão.</p>
                <div class="text-end"><button class="btn-custom-purple" onclick="location.reload()">Verificar Status</button></div>
            </div>
        </div>

        <div class="section-card">
            <div class="section-header">Informações da Operadora</div>
            <div class="p-0">
                <div class="table-responsive">
                    <table class="table-custom">
                        <thead><tr><th>OPERADORA</th><th>URL</th><th>PORTA</th></tr></thead>
                        <tbody>
                            <?php if(count($lista_servidores) > 0): ?>
                                <?php foreach($lista_servidores as $s): ?>
                                    <tr>
                                        <td style="color: #a6a6b7;"><?= htmlspecialchars($s['nome']) ?></td>
                                        <td style="color: #a6a6b7;"><?= htmlspecialchars($s['url']) ?></td>
                                        <td style="color: #a6a6b7;"><?= htmlspecialchars($s['porta']) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="3" class="text-center text-muted py-3">Nenhuma operadora disponível</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="section-card">
            <div class="section-header">Status do Servidor (Tempo Real)</div>
            <div class="p-0">
                <div class="table-responsive">
                    <table class="table-custom">
                        <thead><tr><th>SERVIDOR</th><th>OPERADORA</th><th class="text-center">STATUS</th></tr></thead>
                        <tbody>
                            <?php if(count($lista_servidores) > 0): ?>
                                <?php foreach($lista_servidores as $s): 
                                    $isOnline = checkStatusReal($s['url'], $s['porta']);
                                ?>
                                <tr>
                                    <td style="color: #a6a6b7;">CSP</td>
                                    <td style="color: #a6a6b7;"><?= htmlspecialchars($s['nome']) ?></td>
                                    <td class="text-center">
                                        <?php if($isOnline): ?>
                                            <span class="status-badge status-online">Online</span>
                                        <?php else: ?>
                                            <span class="status-badge status-offline">Offline</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="3" class="text-center text-muted py-3">Nenhum servidor monitorado</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</main>

<div class="modal fade" id="modalPerfil" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary text-white">
            <div class="modal-header border-secondary">
                <h5 class="modal-title">Perfil do Usuário</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center p-4">
                <div style="width: 80px; height: 80px; background: var(--primary); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto; font-size: 2rem;"><i class="fas fa-user"></i></div>
                <h4 class="mt-3"><?= htmlspecialchars($usuarioLogado) ?></h4>
                <span class="badge bg-secondary"><?= $isAdmin ? 'Administrador' : 'Revendedor' ?></span>
                <hr class="border-secondary">
                <p class="text-white-50">Status: <strong class="text-success">Ativa</strong> | Criado por: <strong class="text-info"><?= $meuDono ?></strong></p>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalMensagens" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content bg-dark border-secondary text-white">
            <div class="modal-header border-secondary">
                <h5 class="modal-title"><i class="fas fa-headset me-2"></i>Suporte / Mensagens</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-3">
                <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
                    <li class="nav-item"><button class="nav-link active" id="tab-inbox" data-bs-toggle="pill" data-bs-target="#content-inbox" type="button">Caixa de Entrada</button></li>
                    <li class="nav-item"><button class="nav-link" id="tab-write" data-bs-toggle="pill" data-bs-target="#content-write" type="button"><i class="fas fa-pen me-2"></i>Nova Mensagem</button></li>
                </ul>
                <div class="tab-content">
                    <div class="tab-pane fade show active" id="content-inbox">
                        <div class="list-group list-group-flush bg-dark rounded border border-secondary" style="max-height: 400px; overflow-y: auto;">
                            <?php if(count($mensagens) > 0): foreach($mensagens as $m): ?>
                                <div class="list-group-item bg-dark text-white border-secondary p-3">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h6 class="mb-1 text-primary fw-bold"><?= htmlspecialchars($m['Assunto']) ?></h6>
                                        <small class="text-muted"><?= htmlspecialchars($m['data']) ?></small>
                                    </div>
                                    <p class="mb-1 text-light mt-2"><?= nl2br(htmlspecialchars($m['Mensagem'])) ?></p>
                                    <small class="text-muted"><i class="fas fa-user me-1"></i> De: <?= htmlspecialchars($m['UserEmissor']) ?></small>
                                </div>
                            <?php endforeach; else: ?>
                                <div class="p-5 text-center text-white-50"><i class="fas fa-inbox fa-3x mb-3"></i><br>Nenhuma mensagem recebida.</div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="content-write">
                        <form method="POST">
                            <input type="hidden" name="acao_suporte" value="enviar_msg">
                            <?php if($isAdmin): ?>
                            <div class="mb-3"><label class="form-label">Destinatário (Usuário)</label><input type="text" name="destinatario" class="form-control bg-dark text-white border-secondary" placeholder="Digite o usuário do revendedor" required></div>
                            <?php else: ?>
                                <div class="alert alert-info py-2 small"><i class="fas fa-info-circle me-1"></i> Sua mensagem será enviada para: <strong><?= $meuDono ?></strong></div>
                            <?php endif; ?>
                            <div class="mb-3"><label class="form-label">Assunto</label><input type="text" name="assunto" class="form-control bg-dark text-white border-secondary" required></div>
                            <div class="mb-3"><label class="form-label">Mensagem</label><textarea name="mensagem" class="form-control bg-dark text-white border-secondary" rows="5" required></textarea></div>
                            <button type="submit" class="btn btn-success w-100 fw-bold"><i class="fas fa-paper-plane me-2"></i>ENVIAR MENSAGEM</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalConfigTeste" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary text-white">
            <form method="POST">
                <input type="hidden" name="acao_pref" value="salvar_config_teste">
                <div class="modal-header border-secondary"><h5 class="modal-title">Configurar Cópia de Teste</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
                <div class="modal-body p-4">
                    <p class="text-white-50 small mb-3">Receba uma cópia no seu e-mail sempre que um teste automático for criado.</p>
                    <div class="mb-3"><label class="form-label fw-bold">E-mail para Cópia</label><input type="email" name="email_copia" class="form-control bg-dark text-white border-secondary" placeholder="seu@email.com" value="<?= htmlspecialchars($pref_email) ?>"></div>
                    <div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="receber_copia" id="switchReceber" <?= $pref_ativo == 'sim' ? 'checked' : '' ?>><label class="form-check-label" for="switchReceber">Ativar envio de cópia</label></div>
                </div>
                <div class="modal-footer border-secondary"><button type="submit" class="btn btn-primary w-100">Salvar Preferências</button></div>
            </form>
        </div>
    </div>
</div>

<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'); }
    function copiarUrl() { navigator.clipboard.writeText(document.getElementById('urlTesteTexto').innerText).then(() => alert("URL copiada!")); }
</script>
</body>
</html>
