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

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

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

$msg = ""; $msg_tipo = ""; $texto_zap = "";
$redirecionar = false;

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

// --- 2. 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']);
            $venc = date('Y-m-d H:i:s', strtotime("+".(int)$_POST['tempo']." hours"));
            $sql = "INSERT INTO teste (CadUser, usuario, senha, data_premio, perfil, bloqueado, data_cadastro) VALUES (?,?,?,?,?,'nao',NOW())";
            $connUser->prepare($sql)->execute([$usuarioLogado, $user, $_POST['senha'], $venc, $_POST['perfil_id']]);
            
            $p = $mapa_perfis[$_POST['perfil_id']];
            $texto_zap = "*✅ Teste Gerado!*\n\n👤 *User:* $user\n🔑 *Senha:* {$_POST['senha']}\n⏳ *Expira:* ".date('d/m H:i', strtotime($venc));
            $msg = "Teste criado!"; $msg_tipo = "success";
        }

        // EDITAR TESTE (NOVA OPÇÃO)
        if ($acao === 'editar') {
            $sql = "UPDATE teste SET usuario=?, senha=?, perfil=? WHERE id=? $filtroSeguranca";
            $connUser->prepare($sql)->execute([$_POST['usuario'], $_POST['senha'], $_POST['perfil_id'], $id_teste]);
            $msg = "Informações atualizadas!"; $msg_tipo = "primary";
        }

        // RENOVAR (CONVERTER EM CLIENTE 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'));
                
                // Insere na tabela de clientes (usuario)
                $sql_ins = "INSERT INTO usuario (CadUser, nome, usuario, senha, conexao, data_premio, id_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']]);
                
                // Remove dos testes
                $connUser->prepare("DELETE FROM teste WHERE id = ?")->execute([$id_teste]);

                // Mensagem de Renovação Personalizada
                $texto_zap = "*Plano renovado com sucesso!*\n\n👤 Usuario: {$t['usuario']}\n🔑 Senha: {$t['senha']}\n📆 Vencimento: ".date('d/m/Y', strtotime($venc_cliente));
                $redirecionar = true; // Ativa redirecionamento via JS
            }
        }

        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"; }
}

// --- 3. LISTAGEM COM PAGINAÇÃO (10 em 10) ---
$busca = $_GET['busca'] ?? '';
$status = $_GET['status'] ?? 'todos';
$rev_f = $_GET['revendedor'] ?? '';
$pagina = isset($_GET['pagina']) ? (int)$_GET['pagina'] : 1;
$offset = ($pagina - 1) * 10;

$where = " WHERE 1=1";
$params = [];
if (!$isAdmin) { $where .= " AND CadUser = :dono"; $params[':dono'] = $usuarioLogado; }
elseif ($rev_f) { $where .= " AND CadUser = :rev"; $params[':rev'] = $rev_f; }
if ($busca) { $where .= " AND usuario LIKE :b"; $params[':b'] = "%$busca%"; }

$total = $connUser->prepare("SELECT COUNT(*) FROM teste $where");
$total->execute($params);
$total_paginas = ceil($total->fetchColumn() / 10);

$stmt = $connUser->prepare("SELECT * FROM teste $where ORDER BY id DESC LIMIT 10 OFFSET $offset");
$stmt->execute($params);
$testes = $stmt->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</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: #151521; color: #fff; font-family: 'Segoe UI', sans-serif; }
        .sidebar { width: 260px; height: 100vh; position: fixed; background: #1e1e2d; padding: 20px; border-right: 1px solid #333; }
        .main-content { margin-left: 260px; padding: 25px; }
        .card-custom { background: #1e1e2d; border: 1px solid #333; border-radius: 12px; }
        .form-control, .form-select { background: #2b2b40; border: 1px solid #444; color: #fff; }
        .table-dark { background: #1e1e2d; --bs-table-bg: #1e1e2d; }
        .pagination .page-link { background: #2b2b40; border-color: #444; color: #fff; }
        @media (max-width: 768px) { .sidebar { display: none; } .main-content { margin-left: 0; } }
    </style>
</head>
<body>

<nav class="sidebar">
    <h4 class="mb-5 fw-bold text-primary">IPTV PANEL</h4>
    <div class="nav flex-column gap-2">
        <a href="clientes.php" class="btn btn-dark text-start border-0 py-2"><i class="fas fa-users me-2"></i> Clientes</a>
        <a href="testes.php" class="btn btn-primary text-start border-0 py-2"><i class="fas fa-stopwatch me-2"></i> Testes</a>
    </div>
</nav>

<main class="main-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <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"><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-3">
            <div class="col-md-5"><input type="text" name="busca" class="form-control" placeholder="Buscar usuário..." value="<?= htmlspecialchars($busca) ?>"></div>
            <?php if($isAdmin): ?>
            <div class="col-md-4">
                <select name="revendedor" class="form-select" onchange="this.form.submit()">
                    <option value="">Todos os Revendedores</option>
                    <?php foreach($lista_rev as $rv): ?><option value="<?= $rv['usuario'] ?>" <?= $rev_f == $rv['usuario'] ? 'selected' : '' ?>><?= $rv['usuario'] ?></option><?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>
            <div class="col-md-3"><button class="btn btn-primary w-100">Filtrar</button></div>
        </form>
    </div>

    <?php if($msg): ?><div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show"><?= $msg ?><button class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

    <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">
                        <th class="ps-3">USUÁRIO</th>
                        <th>EXPIRA EM</th>
                        <th>DONO</th>
                        <th class="text-end pe-3">AÇÕES</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($testes as $t): 
                        $restante = strtotime($t['data_premio']) - time();
                    ?>
                    <tr>
                        <td class="ps-3">
                            <div class="fw-bold text-white"><?= htmlspecialchars($t['usuario']) ?></div>
                            <div class="text-white-50 small">Senha: <?= $t['senha'] ?></div>
                        </td>
                        <td class="<?= $restante < 0 ? 'text-danger' : 'text-success fw-bold' ?>">
                            <?= $restante < 0 ? 'Expirado' : gmdate("H:i:s", $restante) ?>
                        </td>
                        <td><span class="badge bg-secondary"><?= $t['CadUser'] ?></span></td>
                        <td class="text-end pe-3">
                            <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="Renovar e 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" title="Editar"><i class="fas fa-pen text-white"></i></button>
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="acao" value="excluir"><input type="hidden" name="id_teste" value="<?= $t['id'] ?>">
                                <button type="submit" class="btn btn-sm btn-danger rounded-circle" onclick="return confirm('Excluir?')"><i class="fas fa-trash"></i></button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($total_paginas > 1): ?>
        <nav class="p-3"><ul class="pagination justify-content-center mb-0">
            <?php for($i=1; $i<=$total_paginas; $i++): ?>
                <li class="page-item <?= $i == $pagina ? 'active' : '' ?>"><a class="page-link" href="?pagina=<?= $i ?>&busca=<?= $busca ?>&revendedor=<?= $rev_f ?>"><?= $i ?></a></li>
            <?php endfor; ?>
        </ul></nav>
        <?php endif; ?>
    </div>
</main>

<div class="modal fade" id="modalZap" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-success text-white text-center">
            <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>

<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 border-secondary"><h5 class="modal-title">Editar Teste</h5><button type="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" required></div>
                    <div class="mb-3"><label>Senha</label><input type="text" name="senha" id="edit_pass" class="form-control" required></div>
                    <div class="mb-3"><label>Perfil</label><select name="perfil_id" id="edit_perfil" class="form-select">
                        <?php foreach($lista_perfis as $p): ?><option value="<?= $p['id'] ?>"><?= $p['nome'] ?></option><?php endforeach; ?>
                    </select></div>
                </div>
                <div class="modal-footer border-secondary"><button type="submit" class="btn btn-primary w-100 fw-bold">SALVAR ALTERAÇÕES</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 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 || 0;
        new bootstrap.Modal(document.getElementById('modalEditar')).show();
    }

    window.onload = function() {
        if(`<?= trim($texto_zap) ?>` !== "") {
            let myModal = new bootstrap.Modal(document.getElementById('modalZap'));
            myModal.show();
            
            <?php if($redirecionar): ?>
            document.getElementById('btnFecharZap').onclick = function() { window.location.href = 'clientes.php'; };
            document.getElementById('modalZap').addEventListener('hidden.bs.modal', function () { window.location.href = 'clientes.php'; });
            <?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>
