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

if (!isset($_SESSION['logado'])) { header("Location: login.php"); exit; }

$isAdmin = (strtolower($_SESSION['nivel']) === 'admin');
$usuarioLogado = $_SESSION['usuario'];
$msg = ""; $msg_tipo = ""; $texto_zap = "";
$redirecionar = false;

// --- 1. CONFIGURAÇÃO DE FILTROS E PAGINAÇÃO ---
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$pagina = isset($_GET['pagina']) ? (int)$_GET['pagina'] : 1;
$offset = ($pagina - 1) * $limit;

$busca = trim($_GET['busca'] ?? '');
$status_f = $_GET['status'] ?? 'todos';
$rev_f = $_GET['revendedor'] ?? '';

// --- 2. BUSCAR PERFIS E REVENDEDORES ---
$mapa_perfis = [];
$lista_perfis_select = [];
$lista_rev = [];
try {
    $res_p = $connGeral->query("SELECT id, valorcsp, nome, url, porta FROM perfil WHERE (bloqueado IS NULL OR bloqueado != 'sim')")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($res_p as $p) { $mapa_perfis[$p['valorcsp']] = $p; $lista_perfis_select[] = $p; }
    
    if ($isAdmin) {
        $lista_rev = $connUser->query("SELECT usuario FROM rev ORDER BY usuario ASC")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) { }

// --- 3. PROCESSAMENTO DE AÇÕES (POST) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $acao = $_POST['acao'];
        $id_teste = (int)($_POST['id_teste'] ?? 0);
        $filtroSeguranca = $isAdmin ? "" : " AND CadUser = '$usuarioLogado'";

        // CRIAR TESTE
        if ($acao === 'criar') {
            $user = trim($_POST['usuario']);
            $pass = $_POST['senha'];
            $perfil_csp = $_POST['perfil_csp'];
            $horas = (int)$_POST['tempo'];
            $venc_time = strtotime("+$horas hours"); 

            $sql = "INSERT INTO teste (CadUser, usuario, senha, data_premio, perfil, bloqueado, data_cadastro) VALUES (?,?,?,?,?,'nao',NOW())";
            $connUser->prepare($sql)->execute([$usuarioLogado, $user, $pass, $venc_time, $perfil_csp]);
            
            $p_info = $mapa_perfis[$perfil_csp] ?? [];
            $texto_zap = "*✅ Teste IPTV Gerado!*\n\n👤 *User:* $user\n🔑 *Senha:* $pass\n⏳ *Expira:* ".date('d/m/Y H:i', $venc_time)."\n\n🌐 *URL:* ".($p_info['url']??'---')."\n🔌 *Porta:* ".($p_info['porta']??'---');
            $msg = "Teste criado!"; $msg_tipo = "success";
        }

        // EDITAR TESTE
        if ($acao === 'editar') {
            $sql = "UPDATE teste SET usuario=?, senha=?, perfil=? WHERE id=? $filtroSeguranca";
            $connUser->prepare($sql)->execute([$_POST['usuario'], $_POST['senha'], $_POST['perfil_csp'], $id_teste]);
            $msg = "Dados salvos!"; $msg_tipo = "primary";
        }

        // BLOQUEAR TESTE
        if ($acao === 'bloquear_toggle') {
            $novo = ($_POST['status_atual'] == 'sim') ? 'nao' : 'sim';
            $connUser->prepare("UPDATE teste SET bloqueado=? WHERE id=? $filtroSeguranca")->execute([$novo, $id_teste]);
            $msg = "Status atualizado!"; $msg_tipo = "info";
        }

        // RENOVAR (EFETIVAR E REDIRECIONAR)
        if ($acao === 'renovar') {
            $stmt = $connUser->prepare("SELECT * FROM teste WHERE id = ? $filtroSeguranca");
            $stmt->execute([$id_teste]);
            $t = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($t) {
                $venc_cliente = date('Y-m-d', strtotime('+30 days'));
                $sql_ins = "INSERT INTO usuario (CadUser, nome, usuario, senha, conexao, data_premio, perfil, bloqueado, data_cadastro) 
                            VALUES (?, ?, ?, ?, 1, ?, ?, 'nao', NOW())";
                $connUser->prepare($sql_ins)->execute([$t['CadUser'], $t['usuario'], $t['usuario'], $t['senha'], $venc_cliente, $t['perfil']]);
                
                $connUser->prepare("DELETE FROM teste WHERE id = ?")->execute([$id_teste]);

                $texto_zap = "*✅ Teste Convertido em Cliente!*\n\n👤 *User:* {$t['usuario']}\n🔑 *Senha:* {$t['senha']}\n📆 *Novo Vencimento:* ".date('d/m/Y', strtotime($venc_cliente));
                $redirecionar = true; 
                $msg = "Convertido com sucesso!"; $msg_tipo = "success";
            }
        }

        if ($acao === 'excluir') {
            $connUser->prepare("DELETE FROM teste WHERE id=? $filtroSeguranca")->execute([$id_teste]);
            $msg = "Removido!"; $msg_tipo = "danger";
        }
    } catch (Exception $e) { $msg = "Erro: ".$e->getMessage(); $msg_tipo = "danger"; }
}

// --- 4. LISTAGEM COM FILTROS ---
$where = " WHERE 1=1";
$params = [];
if (!$isAdmin) { $where .= " AND CadUser = :u"; $params[':u'] = $usuarioLogado; }
elseif ($rev_f !== '') { $where .= " AND CadUser = :rev"; $params[':rev'] = $rev_f; }
if ($busca) { $where .= " AND usuario LIKE :b"; $params[':b'] = "%$busca%"; }

$hoje_ts = time();
if ($status_f === 'ativos') { $where .= " AND data_premio > $hoje_ts AND bloqueado != 'sim'"; }
elseif ($status_f === 'vencidos') { $where .= " AND data_premio <= $hoje_ts"; }
elseif ($status_f === 'bloqueados') { $where .= " AND bloqueado = 'sim'"; }

$total_reg = $connUser->prepare("SELECT COUNT(*) FROM teste $where");
$total_reg->execute($params);
$total_pgs = ceil($total_reg->fetchColumn() / $limit);

$testes = $connUser->prepare("SELECT * FROM teste $where ORDER BY id DESC LIMIT $limit OFFSET $offset");
$testes->execute($params);
$lista_testes = $testes->fetchAll();
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Testes | IPTV Panel</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: #7367f0; --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); padding: 20px; border-right: 1px solid #333; transition: 0.3s; z-index: 1050; overflow-y: auto; }
        .main-content { margin-left: 260px; padding: 30px; transition: 0.3s; }
        .nav-link { color: #a6a6b7; padding: 10px 12px; border-radius: 8px; margin-bottom: 2px; display: flex; align-items: center; gap: 10px; transition: 0.2s; text-decoration: none; font-size: 0.9rem; }
        .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; }
        .card-custom { background: var(--bg-card); border: 1px solid #333; border-radius: 12px; }
        .form-control, .form-select { background: #2b2b40; border: 1px solid #444; color: #fff; }
        .table-dark { background: var(--bg-card); --bs-table-bg: var(--bg-card); }
        .status-expired { color: #ff4d4d !important; font-weight: bold; }
        .info-acesso { font-size: 0.75rem; color: #aaa; }
        .info-acesso b { color: #7367f0; }
        @media (max-width: 992px) { .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; padding: 15px; } .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; }
    </style>
</head>
<body>

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

<nav class="sidebar" id="sidebar">
    <h4 class="mb-4 fw-bold text-white text-center"><i class="fas fa-tv text-primary"></i> IPTV PANEL</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_email.php" class="nav-link"><i class="fas fa-envelope"></i> Config. E-mail</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 active"><i class="fas fa-stopwatch"></i> Testes</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>

    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
        <h3 class="fw-bold">Gestão de Testes</h3>
        <button onclick="new bootstrap.Modal(document.getElementById('modalCriar')).show()" class="btn btn-warning fw-bold px-4 text-dark"><i class="fas fa-plus me-2"></i>Novo Teste</button>
    </div>

    <div class="card card-custom p-3 mb-4">
        <form method="GET" class="row g-2">
            <div class="col-md-3"><input type="text" name="busca" class="form-control" placeholder="Usuário..." value="<?= $busca ?>"></div>
            <div class="col-6 col-md-2"><select name="status" class="form-select"><option value="todos" <?= $status_f=='todos'?'selected':'' ?>>Todos</option><option value="ativos" <?= $status_f=='ativos'?'selected':'' ?>>Ativos</option><option value="vencidos" <?= $status_f=='vencidos'?'selected':'' ?>>Vencidos</option><option value="bloqueados" <?= $status_f=='bloqueados'?'selected':'' ?>>Bloqueados</option></select></div>
            <?php if($isAdmin): ?>
            <div class="col-6 col-md-2"><select name="revendedor" class="form-select"><option value="">Revendedores</option><?php foreach($lista_rev as $r): ?><option value="<?= $r['usuario'] ?>" <?= $rev_f==$r['usuario']?'selected':'' ?>><?= $r['usuario'] ?></option><?php endforeach; ?></select></div>
            <?php endif; ?>
            <div class="col-6 col-md-2"><select name="limit" class="form-select"><?php foreach([10,20,50,100,250,500,1000,3000,30000] as $o): ?><option value="<?= $o ?>" <?= $limit==$o?'selected':'' ?>><?= $o ?> itens</option><?php endforeach; ?></select></div>
            <div class="col-6 col-md-1"><button class="btn btn-primary w-100"><i class="fas fa-filter"></i></button></div>
        </form>
    </div>

    <div class="card card-custom overflow-hidden">
        <div class="table-responsive">
            <table class="table table-dark table-hover mb-0 align-middle">
                <thead>
                    <tr class="text-secondary small text-uppercase">
                        <th class="ps-3">Usuário / Acesso</th>
                        <th>Expira em</th>
                        <th>Dono</th>
                        <th class="text-end pe-3">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($lista_testes as $t): 
                        $venc_ts = is_numeric($t['data_premio']) ? (int)$t['data_premio'] : strtotime($t['data_premio']);
                        $restante = $venc_ts - time();
                        $data_br = date('d/m/Y H:i', $venc_ts);
                        $isBlocked = ($t['bloqueado'] == 'sim');
                        $p_info = $mapa_perfis[$t['perfil']] ?? ['nome' => 'S/ Perfil', 'url' => '---', 'porta' => '---'];
                    ?>
                    <tr>
                        <td class="ps-3">
                            <div class="fw-bold text-white"><?= htmlspecialchars($t['usuario']) ?></div>
                            <div class="info-acesso"><b>User:</b> <?= $t['usuario'] ?> | <b>Senha:</b> <?= $t['senha'] ?></div>
                            <div class="text-info" style="font-size: 0.7rem;"><?= $p_info['nome'] ?></div>
                        </td>
                        <td class="<?= $restante < 0 ? 'status-expired fst-italic' : 'text-success fw-bold' ?>">
                            <?= $isBlocked ? '<span class="text-danger">BLOQUEADO</span>' : ($restante < 0 ? 'EXPIRADO' : $data_br) ?>
                        </td>
                        <td><span class="badge bg-secondary"><?= $t['CadUser'] ?></span></td>
                        <td class="text-end pe-3">
                            <button onclick='abrirVisualizar(<?= json_encode($t) ?>, <?= json_encode($p_info) ?>, "<?= $data_br ?>")' class="btn btn-sm btn-light rounded-circle me-1"><i class="fas fa-eye text-dark"></i></button>
                            
                            <form method="POST" class="d-inline"><input type="hidden" name="acao" value="renovar"><input type="hidden" name="id_teste" value="<?= $t['id'] ?>"><button type="submit" class="btn btn-sm btn-success rounded-circle me-1" title="Efetivar"><i class="fas fa-check"></i></button></form>
                            
                            <button onclick='abrirEditar(<?= json_encode($t) ?>)' class="btn btn-sm btn-info rounded-circle me-1"><i class="fas fa-pen text-white"></i></button>
                            
                            <form method="POST" class="d-inline"><input type="hidden" name="acao" value="bloquear_toggle"><input type="hidden" name="id_teste" value="<?= $t['id'] ?>"><input type="hidden" name="status_atual" value="<?= $t['bloqueado'] ?>"><button class="btn btn-sm <?= $isBlocked?'btn-danger':'btn-warning' ?> rounded-circle me-1"><i class="fas <?= $isBlocked?'fa-lock':'fa-lock-open' ?>"></i></button></form>
                            
                            <form method="POST" class="d-inline"><input type="hidden" name="acao" value="excluir"><input type="hidden" name="id_teste" value="<?= $t['id'] ?>"><button class="btn btn-sm btn-outline-danger rounded-circle" onclick="return confirm('Apagar?')"><i class="fas fa-trash"></i></button></form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<div class="modal fade" id="modalVerDados" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-info text-white">
            <div class="modal-header border-secondary"><h5><i class="fas fa-id-card me-2 text-info"></i>Dados do Teste</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <div class="modal-body p-4">
                <div class="mb-2"><label class="small text-white-50">Usuário:</label><input type="text" readonly class="form-control bg-dark border-secondary" id="view_user"></div>
                <div class="mb-2"><label class="small text-white-50">Senha:</label><input type="text" readonly class="form-control bg-dark border-secondary" id="view_pass"></div>
                <div class="mb-3"><label class="small text-white-50">Expira em:</label><input type="text" readonly class="form-control bg-dark border-secondary text-warning" id="view_venc"></div>
                <hr class="border-secondary">
                <div class="mb-2"><label class="small text-white-50">URL / DNS:</label><input type="text" readonly class="form-control bg-dark border-secondary text-info" id="view_url"></div>
                <div class="mb-3"><label class="small text-white-50">Porta:</label><input type="text" readonly class="form-control bg-dark border-secondary text-warning" id="view_porta"></div>
                <div class="d-flex gap-2"><button onclick="copiarVisualizar()" class="btn btn-outline-light w-50 fw-bold">COPIAR</button><button onclick="zapVisualizar()" class="btn btn-success w-50 fw-bold">WHATSAPP</button></div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalCriar" 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" value="criar">
            <div class="modal-header"><h5>Gerar Novo Teste</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <div class="modal-body p-4">
                <div class="mb-3"><label>Usuário</label><input type="text" name="usuario" class="form-control" required></div>
                <div class="mb-3"><label>Senha</label><input type="text" name="senha" class="form-control" value="<?= rand(1000,9999) ?>" required></div>
                <div class="row">
                    <div class="col-6 mb-3"><label>Duração</label><select name="tempo" class="form-select"><option value="3">3 Horas</option><option value="24">24 Horas</option><option value="48">48 Horas</option></select></div>
                    <div class="col-6 mb-3"><label>Perfil</label><select name="perfil_csp" class="form-select" required><?php foreach($lista_perfis_select as $ps): ?><option value="<?= $ps['valorcsp'] ?>"><?= $ps['nome'] ?></option><?php endforeach; ?></select></div>
                </div>
            </div>
            <div class="modal-footer"><button type="submit" class="btn btn-success w-100 fw-bold">GERAR TESTE</button></div>
        </form></div>
    </div>
</div>

<div class="modal fade" id="modalEditar" 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" value="editar"><input type="hidden" name="id_teste" id="edit_id">
            <div class="modal-header"><h5>Editar Teste</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <div class="modal-body p-4">
                <div class="mb-3"><label>Usuário</label><input type="text" name="usuario" id="edit_user" class="form-control"></div>
                <div class="mb-3"><label>Senha</label><input type="text" name="senha" id="edit_pass" class="form-control"></div>
                <div class="mb-3"><label>Perfil</label><select name="perfil_csp" id="edit_perfil" class="form-select"><?php foreach($lista_perfis_select as $ps): ?><option value="<?= $ps['valorcsp'] ?>"><?= $ps['nome'] ?></option><?php endforeach; ?></select></div>
            </div>
            <div class="modal-footer"><button type="submit" class="btn btn-primary w-100 fw-bold">SALVAR</button></div>
        </form></div>
    </div>
</div>

<div class="modal fade" id="modalZap" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered text-center"><div class="modal-content bg-dark border-success text-white">
        <div class="modal-header border-0 pb-0"><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" id="btnFecharZap"></button></div>
        <div class="modal-body p-4 pt-0">
            <h5 class="text-success mb-3">Concluído!</h5>
            <textarea id="textoZapArea" class="form-control mb-3" rows="6" style="background:#111; color:#0f0; border:none;"><?= $texto_zap ?></textarea>
            <button onclick="copiarTexto()" class="btn btn-outline-light me-2">Copiar</button>
            <button onclick="enviarZap()" class="btn btn-success">WhatsApp</button>
        </div>
    </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 abrirVisualizar(t, p, data_f) {
        document.getElementById('view_user').value = t.usuario; document.getElementById('view_pass').value = t.senha;
        document.getElementById('view_venc').value = data_f; document.getElementById('view_url').value = p.url;
        document.getElementById('view_porta').value = p.porta; new bootstrap.Modal(document.getElementById('modalVerDados')).show();
    }
    function abrirEditar(t) {
        document.getElementById('edit_id').value = t.id; document.getElementById('edit_user').value = t.usuario;
        document.getElementById('edit_pass').value = t.senha; document.getElementById('edit_perfil').value = t.perfil;
        new bootstrap.Modal(document.getElementById('modalEditar')).show();
    }
    function copiarVisualizar() { const m = `👤 User: ${document.getElementById('view_user').value}\n🔑 Senha: ${document.getElementById('view_pass').value}\n⏳ Expira: ${document.getElementById('view_venc').value}\n🌐 URL: ${document.getElementById('view_url').value}\n🔌 Porta: ${document.getElementById('view_porta').value}`; navigator.clipboard.writeText(m).then(() => alert("Copiado!")); }
    function zapVisualizar() { const m = `👤 *User:* ${document.getElementById('view_user').value}\n🔑 *Senha:* ${document.getElementById('view_pass').value}\n⏳ *Expira:* ${document.getElementById('view_venc').value}\n🌐 *URL:* ${document.getElementById('view_url').value}\n🔌 *Porta:* ${document.getElementById('view_porta').value}`; window.open("https://api.whatsapp.com/send?text=" + encodeURIComponent(m), '_blank'); }
    
    window.onload = function() {
        if(`<?= trim($texto_zap) ?>` !== "") {
            new bootstrap.Modal(document.getElementById('modalZap')).show();
            <?php if($redirecionar): ?>
            const red = () => { window.location.href = 'clientes.php'; };
            document.getElementById('modalZap').addEventListener('hidden.bs.modal', red);
            document.getElementById('btnFecharZap').onclick = red;
            <?php endif; ?>
        }
    }
    function copiarTexto() { document.getElementById("textoZapArea").select(); document.execCommand("copy"); alert("Copiado!"); }
    function enviarZap() { window.open("https://api.whatsapp.com/send?text=" + encodeURIComponent(document.getElementById("textoZapArea").value), '_blank'); }
</script>
</body>
</html>
