<?php
session_start();

// Trava o relógio do sistema para o horário oficial do Brasil
date_default_timezone_set('America/Sao_Paulo');

require_once 'config.php'; 
$pdo = getConexaoAtiva();

// FORÇA O BANCO A FALAR EM UTF8 PARA ACABAR COM CARACTERES ESTRANHOS
$pdo->exec("SET NAMES utf8mb4");

// ====================================================================
// MÁGICA PARA VPS NOVA: DESLIGA O MODO ESTRITO DO MYSQL
// Isso impede o falso erro de Erro 500 / "Usuário já existe"
// ====================================================================
$pdo->exec("SET SESSION sql_mode = ''");

// ====================================================================
// --- LÓGICA DE AUTO-CORREÇÃO DO BANCO (MUITO IMPORTANTE PARA BANCO NOVO) ---
// ====================================================================
try {
    $check = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'whatsapp'");
    if (!$check->fetch()) { $pdo->exec("ALTER TABLE `users` ADD COLUMN `whatsapp` VARCHAR(255) DEFAULT NULL"); }
    
    $check_bq = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'bouquet'");
    if (!$check_bq->fetch()) { $pdo->exec("ALTER TABLE `users` ADD COLUMN `bouquet` TEXT DEFAULT NULL"); }

    $check_trust = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'trust_used'");
    if (!$check_trust->fetch()) { $pdo->exec("ALTER TABLE `users` ADD COLUMN `trust_used` TINYINT(1) DEFAULT 0"); }
    
    $check_p2p = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'is_p2p'");
    if (!$check_p2p->fetch()) { $pdo->exec("ALTER TABLE `users` ADD COLUMN `is_p2p` INT(11) DEFAULT 0"); }

    $pdo->exec("CREATE TABLE IF NOT EXISTS `painel_config` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `nome_painel` varchar(255) DEFAULT 'TOP IPTV',
        `logo_url` varchar(255) DEFAULT '',
        `cor_primaria` varchar(50) DEFAULT '#007bff',
        `confianca_status` tinyint(1) DEFAULT 0,
        `confianca_tempo` int(11) DEFAULT 1,
        `tempo_teste` int(11) DEFAULT 4,
        PRIMARY KEY (`id`)
    )");
} catch (Exception $e) {}

// --- INÍCIO: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---
$nome_painel = 'TOP IPTV'; $logo_url = ''; $cor_primaria = '#007bff'; $tempo_teste = 4;
try {
    $tabela_existe = $pdo->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_painel = $pdo->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($config_painel) {
            $nome_painel = !empty($config_painel['nome_painel']) ? $config_painel['nome_painel'] : $nome_painel;
            $cor_primaria = !empty($config_painel['cor_primaria']) ? $config_painel['cor_primaria'] : $cor_primaria;
            if (isset($config_painel['tempo_teste'])) { $tempo_teste = (int)$config_painel['tempo_teste']; }
        }
    }
} catch (Exception $e) {}

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

$user_id_logado = $_SESSION['user_id']; 
$role = $_SESSION['user_role'] ?? 'reseller';
$nome_usuario = $_SESSION['username'] ?? 'Usuário'; // <-- VARIÁVEL ADICIONADA AQUI PARA CORRIGIR O ERRO

// Busca saldo atual do usuário logado
try {
    $user_credits = $pdo->query("SELECT credits FROM reg_users WHERE id = " . intval($user_id_logado))->fetchColumn() ?: 0;
} catch (Exception $e) { $user_credits = 0; }

// --- FUNÇÃO ACESSO TESTE (COM TELAS E TEMPLATE C/ LINK LOAD BALANCER) ---
$template_file = __DIR__ . '/template_mensagem.txt';
$padrao_template = "Seu Acesso foi criado com sucesso!\n\n✅ *Usuário:* #username#\n✅ *Senha:* #password#\n🗓 *Valido até:* #exp_date#\n📺 *Telas:* #telas#\n\n--------------------------------------\n\n🟢 *Link M3U:* #m3u_encurtado#\n🟣 *Link HLS:* #m3u_hls_encurtado#\n📺 *Link SSIPTV:* #ssiptv_encurtado#\n🟣 *Link ROKU:* #roku_encurtado#";
$raw_template = file_exists($template_file) ? file_get_contents($template_file) : $padrao_template;

function gerarDadosAcessoCompleto($u, $p, $z, $e, $telas = 1) {
    global $raw_template, $tempo_teste, $pdo;
    
    // --- BUSCA DO LOAD BALANCER NA HORA DE GERAR O LINK ---
    $prot = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $dns = $prot . $_SERVER['HTTP_HOST']; // DNS PADRÃO COMO BACKUP

    try {
        $stmtLb = $pdo->query("SELECT ip_servidor, porta FROM servidores_lb WHERE status = 1 ORDER BY id DESC LIMIT 1");
        $lbAtivo = $stmtLb->fetch(PDO::FETCH_ASSOC);
        if ($lbAtivo && !empty($lbAtivo['ip_servidor'])) {
            $porta_lb = (isset($lbAtivo['porta']) && $lbAtivo['porta'] != 80) ? ":" . $lbAtivo['porta'] : "";
            $dns = "http://" . trim($lbAtivo['ip_servidor']) . $porta_lb;
        }
    } catch(Exception $ex){}
    // -----------------------------------------------------

    $validade = $e ? date('d/m/Y H:i', $e) : "{$tempo_teste} Horas";
    
    $link_m3u = "{$dns}/get.php?username={$u}&password={$p}&type=m3u_plus&output=mpegts";
    $link_hls = "{$dns}/get.php?username={$u}&password={$p}&type=m3u_plus&output=hls";
    $m3u_enc = "{$dns}/m3u-ts/{$u}/{$p}"; 
    $hls_enc = "{$dns}/m3u-m3u8/{$u}/{$p}"; 
    $ss_enc = "{$dns}/ss-ts/{$u}/{$p}"; 
    $roku_enc = "{$dns}/roku/{$u}/{$p}";
    $m3u_completo = "{$dns}/get.php?username={$u}&password={$p}&type=m3u_plus&output=ts";
    
    $msg = str_replace(
        ['#username#', '#password#', '#exp_date#', '#telas#', '#url#', '#m3u_encurtado#', '#m3u_hls_encurtado#', '#ssiptv_encurtado#', '#roku_encurtado#', '#m3u_link#', '#m3u_link_hls#', '#m3u_completo#'],
        [$u, $p, $validade, $telas, $dns, $m3u_enc, $hls_enc, $ss_enc, $roku_enc, $link_m3u, $link_hls, $m3u_completo],
        $raw_template
    );
    return ['msg' => $msg, 'url' => "https://wa.me/".preg_replace('/\D/','',(string)$z)."?text=".urlencode($msg)];
}

// Limpa sessão do comprovante de teste pelo X
if (isset($_GET['clear_msg'])) { unset($_SESSION['comprovante_teste']); exit; }

$mensagem_aviso = "";

// --- AÇÕES ---
if (isset($_POST['action_config_test_time']) && $role === 'admin') {
    $novo_tempo = intval($_POST['tempo_teste_novo']); if ($novo_tempo < 1) $novo_tempo = 4;
    $pdo->prepare("UPDATE painel_config SET tempo_teste = ?")->execute([$novo_tempo]);
    $tempo_teste = $novo_tempo;
}

if (isset($_POST['action_bulk'])) {
    $type = $_POST['bulk_type']; $ids_raw = isset($_POST['bulk_ids']) ? explode(',', trim($_POST['bulk_ids'])) : [];
    $clean_ids = []; foreach($ids_raw as $i) { if(intval($i) > 0) $clean_ids[] = intval($i); }
    if (!empty($clean_ids)) {
        $id_list = implode(',', $clean_ids); $condicao_seguranca = ($role !== 'admin') ? " AND member_id = " . intval($user_id_logado) : "";
        if ($type === 'delete') { $pdo->exec("DELETE FROM users WHERE id IN ($id_list) $condicao_seguranca"); } 
        elseif ($type === 'block') { $pdo->exec("UPDATE users SET enabled = IF(enabled=1, 0, 1) WHERE id IN ($id_list) $condicao_seguranca"); } 
        elseif ($type === 'exp') { $new_exp = !empty($_POST['bulk_exp_date']) ? strtotime($_POST['bulk_exp_date']) : null; $pdo->prepare("UPDATE users SET exp_date = ? WHERE id IN ($id_list) $condicao_seguranca")->execute([$new_exp]); }
    }
}

if (isset($_POST['action_test'])) {
    // VALIDAÇÃO DE SALDO MINIMO PARA REVENDEDOR
    if ($role !== 'admin' && $user_credits < 1) {
        $mensagem_aviso = "<div class='alert danger'>Saldo insuficiente! Você precisa de pelo menos 1 crédito para criar um Teste.</div>";
    } else {
        $is_auto = isset($_POST['is_auto']);
        $user = $is_auto ? "test".substr(md5(time()),0,5) : $_POST['username'];
        $pass = $is_auto ? substr(md5(time()."2"),0,6) : $_POST['password'];
        $telas = isset($_POST['max_connections']) ? intval($_POST['max_connections']) : 1;
        $zap  = $_POST['whatsapp'] ?? '';
        $exp  = time() + ($tempo_teste * 3600); 
        $created_at = time(); // <- O banco novo exige essa data de criação
        
        try {
            $sql = "INSERT INTO users (username, password, whatsapp, exp_date, enabled, admin_enabled, member_id, is_p2p, max_connections, created_at) VALUES (?, ?, ?, ?, 1, 0, ?, 0, ?, ?)";
            if($pdo->prepare($sql)->execute([$user, $pass, $zap, $exp, $user_id_logado, $telas, $created_at])) {
                $_SESSION['comprovante_teste'] = gerarDadosAcessoCompleto($user, $pass, $zap, $exp, $telas);
                header("Location: testes.php"); exit;
            }
        } catch(PDOException $e) {
            $mensagem_aviso = "<div class='alert danger'><i class='fas fa-exclamation-triangle'></i> Erro no Banco de Dados: " . htmlspecialchars($e->getMessage()) . "</div>";
        }
    }
}

if (isset($_GET['renew_test'])) {
    $id_teste = intval($_GET['renew_test']);
    
    // TRAVA DE SEGURANÇA: Só o dono do teste (ou admin) pode renovar
    $stmtCh = $pdo->prepare("SELECT member_id, username FROM users WHERE id = ?"); $stmtCh->execute([$id_teste]); $dados_teste = $stmtCh->fetch(PDO::FETCH_ASSOC);
    
    if ($dados_teste && ($role === 'admin' || $dados_teste['member_id'] == $user_id_logado)) {
        $pode_renovar = true;

        // VALIDAÇÃO DE SALDO (DESCONTA 1 CRÉDITO)
        if ($role !== 'admin') {
            if ($user_credits < 1) {
                $pode_renovar = false;
                $mensagem_aviso = "<div class='alert danger'>Saldo insuficiente para renovar este Teste para Cliente Oficial!</div>";
            } else {
                $pdo->prepare("UPDATE reg_users SET credits = credits - 1 WHERE id = ?")->execute([$user_id_logado]);
            }
        }

        if ($pode_renovar) {
            $pdo->prepare("UPDATE users SET exp_date = ? WHERE id = ?")->execute([(time() + (30 * 86400)), $id_teste]);
            
            // LOG DE CRÉDITO
            if ($role !== 'admin') {
                try {
                    $agora = date('Y-m-d H:i:s');
                    $pdo->prepare("INSERT INTO logs_creditos (revendedor_id, cliente_user, acao, qtd_descontada, data_hora) VALUES (?, ?, 'Ativacao de Teste', 1, ?)")->execute([$user_id_logado, $dados_teste['username'], $agora]);
                } catch(Exception $e) {}
            }
            header("Location: clientes.php"); exit;
        }
    } else {
        $mensagem_aviso = "<div class='alert danger'>Acesso negado a este teste.</div>";
    }
}

if (isset($_GET['delete'])) { 
    $condicao = ($role !== 'admin') ? " AND member_id = " . intval($user_id_logado) : "";
    $pdo->prepare("DELETE FROM users WHERE id = ? $condicao")->execute([$_GET['delete']]); 
    header("Location: testes.php"); exit; 
}
if (isset($_GET['block'])) { 
    $condicao = ($role !== 'admin') ? " AND member_id = " . intval($user_id_logado) : "";
    $pdo->prepare("UPDATE users SET enabled = IF(enabled=1, 0, 1) WHERE id = ? $condicao")->execute([$_GET['block']]); 
    header("Location: testes.php"); exit; 
}

// --- QUERY DE LISTAGEM ISOLADA ---
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50; $page = isset($_GET['page']) ? (int)$_GET['page'] : 1; if ($page < 1) $page = 1; $offset = ($page - 1) * $limit;
$search = $_GET['search'] ?? '';

// Filtro: P2P e Data Expiração Curta
$where_clause = "WHERE (u.is_p2p = 0 OR u.is_p2p IS NULL) AND (u.exp_date - UNIX_TIMESTAMP()) < 172800"; 
$params = [];

// ISOLAMENTO DE VISÃO: Revendedor só vê os dele
if ($role !== 'admin') {
    $where_clause .= " AND u.member_id = :my_id";
    $params[':my_id'] = $user_id_logado;
}

if (!empty($search)) { 
    $where_clause .= " AND u.username LIKE :search"; 
    $params[':search'] = "%$search%"; 
}

$stmt = $pdo->prepare("SELECT u.*, r.username AS criador FROM users u LEFT JOIN reg_users r ON u.member_id = r.id " . $where_clause . " ORDER BY u.id DESC LIMIT $limit OFFSET $offset");
foreach ($params as $key => $val) { $stmt->bindValue($key, $val); }
$stmt->execute();
$testes = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmtC = $pdo->prepare("SELECT COUNT(u.id) FROM users u " . $where_clause);
foreach ($params as $key => $val) { $stmtC->bindValue($key, $val); }
$stmtC->execute();
$total_registros = $stmtC->fetchColumn();
$total_paginas = ceil($total_registros / $limit);
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Gerenciar Testes - <?php echo htmlspecialchars($nome_painel); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --bg-dark: #121519; --bg-sidebar: #1e2227; --bg-card: #272c33; --text-main: #d1d5da; --text-muted: #8a94a1; --accent: <?php echo $cor_primaria; ?>; --border-color: #3a4149; --success: #28a745; --danger: #dc3545; --warning: #f39c12; --info: #17a2b8; }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: var(--bg-dark); color: var(--text-main); display: flex; height: 100vh; overflow: hidden; }
        .sidebar { width: 260px; background-color: var(--bg-sidebar); border-right: 1px solid var(--border-color); display: flex; flex-direction: column; z-index: 1001; transition: 0.3s; }
        .sidebar-header { padding: 25px 20px; text-align: center; font-size: 22px; font-weight: bold; color: white; border-bottom: 1px solid var(--border-color); }
        .sidebar-logo { max-width: 180px; max-height: 55px; object-fit: contain; }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(0, 123, 255, 0.2); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .credits-badge { display: block; margin-top: 10px; color: var(--success); font-weight: bold; font-size: 13px; }
        .menu-list { list-style: none; padding: 0; margin: 0; overflow-y: auto; flex: 1; }
        .menu-item { padding: 14px 20px; color: var(--text-main); text-decoration: none; display: flex; align-items: center; transition: 0.2s; border-left: 3px solid transparent; font-size: 15px; cursor: pointer; }
        .menu-item i:first-child { margin-right: 12px; width: 20px; text-align: center; color: var(--text-muted); }
        .menu-item:hover, .menu-item.active { background-color: #2c3138; color: white; border-left-color: var(--accent); }
        .menu-item.active i:first-child { color: var(--accent); }
        .submenu { display: none; background: #16191d; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 13px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 11px; }
        .rotate { transform: rotate(180deg); }
        .menu-category { padding: 20px 20px 8px; font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: bold; letter-spacing: 1px; }
        .logout-btn { padding: 15px; background-color: #dc3545; color: white; text-align: center; text-decoration: none; font-weight: bold; }
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; }
        .main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; overflow-x: hidden; transition: 0.3s; position: relative; width: 100vw; max-width: 100%; }
        .topbar { display: flex; justify-content: space-between; align-items: center; padding: 15px 30px; background-color: var(--bg-sidebar); border-bottom: 1px solid var(--border-color); }
        .mode-badge { padding: 6px 15px; background: rgba(40, 167, 69, 0.15); color: var(--success); border-radius: 20px; font-size: 12px; font-weight: bold; border: 1px solid var(--success); }
        .content-area { padding: 30px; flex: 1; overflow-y: auto; overflow-x: hidden; padding-bottom: 100px; box-sizing: border-box; width: 100%; }
        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 24px; cursor: pointer; }
        .filter-bar { background: var(--bg-card); padding: 15px; border-radius: 10px; border: 1px solid var(--border-color); margin-bottom: 20px; display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-end; }
        .filter-group { display: flex; flex-direction: column; gap: 5px; flex: 1; min-width: 120px; }
        .filter-group label { font-size: 11px; color: var(--text-muted); text-transform: uppercase; font-weight: bold; }
        .filter-bar input, .filter-bar select { background: #121519; border: 1px solid var(--border-color); color: white; padding: 10px; border-radius: 5px; font-size: 13px; }
        .btn-filter { background: var(--accent); color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; font-weight: bold; display: flex; align-items: center; justify-content: center; gap: 5px; }
        .btn-main { background: var(--accent); color: white; border: none; padding: 10px 18px; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 13px; display: inline-flex; align-items: center; gap: 5px; }
        .card-table { background: var(--bg-card); border-radius: 10px; border: 1px solid var(--border-color); overflow-x: auto; width: 100%; display: block; -webkit-overflow-scrolling: touch; }
        .card-table::-webkit-scrollbar { height: 8px; }
        .card-table::-webkit-scrollbar-thumb { background: var(--accent); border-radius: 10px; }
        table { width: 100%; border-collapse: collapse; min-width: 800px; }
        th { background: #16191d; padding: 15px; text-align: left; color: var(--text-muted); font-size: 11px; text-transform: uppercase; }
        td { padding: 15px; border-bottom: 1px solid var(--border-color); font-size: 14px; }
        .badge { padding: 4px 8px; border-radius: 4px; font-size: 10px; font-weight: bold; text-transform: uppercase; }
        .bg-success { background: rgba(46, 204, 113, 0.2); color: #2ecc71; }
        .bg-danger { background: rgba(231, 76, 60, 0.2); color: #e74c3c; }
        .btn-action { width: 32px; height: 32px; border-radius: 4px; border: none; cursor: pointer; color: white; display: inline-flex; align-items: center; justify-content: center; margin-right: 4px; }
        #bulkActionsBar { display:none; background: rgba(30, 34, 39, 0.95); padding: 15px 20px; border-radius: 10px; border: 1px dashed var(--accent); margin-bottom: 20px; align-items: center; gap: 15px; flex-wrap: wrap; justify-content: space-between; }
        .btn-bulk { background: var(--text-muted); color: white; border: none; padding: 8px 15px; border-radius: 6px; cursor: pointer; font-weight: bold; font-size: 13px; display: inline-flex; align-items: center; gap: 5px; }
        .pagination { display: flex; justify-content: center; gap: 5px; margin-top: 0; flex-wrap: wrap; }
        .page-link { background: var(--bg-card); color: white; border: 1px solid var(--border-color); padding: 6px 12px; border-radius: 5px; text-decoration: none; font-size: 13px; font-weight: bold; }
        .page-link.active { background: var(--accent); border-color: var(--accent); }
        .modal { display: none; position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); align-items: center; justify-content: center; }
        .modal-content { background: var(--bg-card); width: 90%; max-width: 450px; padding: 25px; border-radius: 12px; border: 1px solid var(--border-color); position: relative; }
        .form-group-modal { margin-bottom: 15px; }
        .form-group-modal label { display: block; margin-bottom: 5px; font-size: 12px; color: var(--text-muted); font-weight: bold;}
        .form-group-modal input, .form-group-modal select { width: 100%; padding: 10px; background: #121519; border: 1px solid var(--border-color); color: white; border-radius: 5px; box-sizing: border-box; }
        .btn-save-modal { width: 100%; padding: 12px; background: var(--accent); border: none; color: white; border-radius: 5px; font-weight: bold; cursor: pointer; }
        
        /* ALERTAS */
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: bold; font-size: 14px; transition: opacity 0.5s ease; }
        .alert.success { background: rgba(40, 167, 69, 0.1); color: var(--success); border: 1px solid var(--success); }
        .alert.danger { background: rgba(220, 53, 69, 0.15); color: #e74c3c; border: 1px solid #e74c3c; }

        @media (max-width: 768px) { .sidebar { position: fixed; left: -260px; height: 100%; } .sidebar.active { left: 0; } .menu-toggle { display: block; margin-right: 15px; } .sidebar-overlay.active { display: block; } .topbar { padding: 15px 20px; justify-content: flex-start; } .topbar-right { margin-left: auto; } .content-area { padding: 15px; padding-bottom: 120px; } .modal-content { width: 90%; margin: auto; } .filter-bar { flex-direction: column; align-items: stretch; } #bulkActionsBar { flex-direction: column; align-items: stretch; } }
    </style>
</head>
<body>

    <div class="sidebar-overlay" id="overlay" onclick="toggleMenu()"></div>
    <nav class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <?php if(!empty($logo_url) && file_exists($logo_url)): ?><img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" class="sidebar-logo"><?php else: ?><?php echo htmlspecialchars($nome_painel); ?><?php endif; ?>
        </div>
        <div class="user-info">
            <div style="color:white; font-size: 14px;">Olá, <strong><?php echo htmlspecialchars($nome_usuario); ?></strong></div>
            <span class="badge"><?php echo $role === 'admin' ? 'Administrador' : 'Revendedor'; ?></span>
            <div class="credits-badge"><i class="fas fa-coins"></i> Saldo: <?php echo number_format($user_credits, 1); ?></div>
        </div>
        <div class="menu-list">
            <a href="dashboard.php" class="menu-item active"><i class="fas fa-chart-line"></i> Dashboard</a>
            <a href="perfil.php" class="menu-item active"><i class="fas fa-user-circle"></i> Meu Perfil</a>
            
            <a href="lancamentos.php" class="menu-item active"><i class="fas fa-fire"></i> Últimos Adicionados</a>
            
            <a href="ajuda.php" class="menu-item active"><i class="fas fa-question-circle"></i> Material de Ajuda</a>
            
            <div class="menu-category">Gestão</div>
            <a href="clientes.php" class="menu-item active"><i class="fas fa-users"></i> Clientes IPTV</a>
            <a href="testes.php" class="menu-item active"><i class="fas fa-vial"></i> Gerenciar Testes</a>
            <a href="online.php" class="menu-item active"><i class="fas fa-plug"></i> Clientes Online</a>
            <a href="revendedores.php" class="menu-item active"><i class="fas fa-user-tie"></i> Revendedores</a>
            <a href="migrar_clientes.php" class="menu-item active"><i class="fas fa-exchange-alt"></i> Migrar Clientes</a>
            <a href="logs_creditos.php" class="menu-item active"><i class="fas fa-list-alt"></i> Extrato de Créditos</a>
            
            <div class="menu-category">Clientes P2P</div>
            <a href="p2p_clientes.php" class="menu-item active"><i class="fas fa-tv"></i> Clientes P2P</a>
            
            <?php if (!empty($api_conf['api_binstream_url'])): ?>
                <a href="binstream_p2p.php" class="menu-item active"><i class="fas fa-tv"></i> Binstream P2P</a>
            <?php endif; ?>

            <div class="menu-category">Integração & Cobrança</div>
            <a href="pagamentos.php" class="menu-item active"><i class="fas fa-dollar-sign"></i> Pagamento Automático</a>
            <a href="cobranca.php" class="menu-item active"><i class="fas fa-comment-dollar"></i> Central de Cobrança</a>
            <a href="admin_planos.php" class="menu-item active"><i class="fas fa-tags"></i> Meus Planos de Venda</a>
            <a href="comprar_creditos.php" class="menu-item active"><i class="fas fa-shopping-cart"></i> Comprar Créditos</a>
            
            <div class="menu-item active" onclick="toggleSubmenu('appsSub')">
                <i class="fas fa-rocket"></i><span>Aplicações</span><i class="fas fa-chevron-down arrow-icon" id="arrow-appsSub"></i>
            </div>
            <div class="submenu" id="appsSub">
                <a href="loja_apps.php" class="menu-item active"><i class="fas fa-store"></i> Loja de Aplicativos</a>
                <?php if($role === 'admin'): ?>
                    <a href="admin_loja.php" class="menu-item active"><i class="fas fa-cogs"></i> Gerenciar Loja</a>
                <?php endif; ?>
                <a href="chatbot.php" class="menu-item active"><i class="fab fa-whatsapp"></i> Chatbot Automático</a>
            </div>
           <a href="admin_player_revenda.php" class="menu-item active"><i class="fas fa-play-circle"></i> WebPlayer</a>
            
   <div class="menu-category">Segurança</div>
            <a href="historico_logins.php" class="menu-item active"><i class="fas fa-shield-alt"></i> Sessões Ativas</a>

            <?php if($role === 'admin'): ?>
                <div class="menu-category">Administração</div>
                <a href="admin_monitor.php" class="menu-item active"><i class="fas fa-heartbeat"></i> Monitor do Servidor</a>
                <a href="admin_template.php" class="menu-item active"><i class="fas fa-edit"></i> Editor de Template</a>
                <a href="admin_lb.php" class="menu-item active"><i class="fas fa-server"></i> Load Balancers</a>
                <a href="guia_cloudflare.php" class="menu-item active"><i class="fas fa-cloud"></i> Guia Cloudflare</a>
                 <a href="admin_loja_creditos.php" class="menu-item active"><i class="fas fa-store"></i> Configurar Loja (PIX)</a>
                 <a href="integracoes_api.php" class="menu-item active"><i class="fas fa-plug"></i> Integrações API</a>
                 <a href="admin_robo.php" class="menu-item active"><i class="fas fa-robot"></i> Robô de Cobrança</a>
                 <a href="admin_anti_bloqueio.php" class="menu-item active"><i class="fas fa-bolt"></i> Botão de Pânico</a>
                 <a href="admin_anti_fraude.php" class="menu-item active"><i class="fas fa-user-secret"></i> Radar Anti-Fraude</a>  
                 <a href="admin_watchdog.php" class="menu-item active"><i class="fas fa-dog"></i> Watchdog LB</a>  
                 
                 <a href="admin_epg_sync.php" class="menu-item active">
        <i class="fas fa-clock"></i> Sincronizar EPG
    </a>
 <div class="menu-item active" onclick="toggleSubmenu('painelSub')">
                    <i class="fas fa-desktop"></i><span>Painel</span><i class="fas fa-chevron-down arrow-icon" id="arrow-painelSub"></i>
                </div>
                <div class="submenu" id="painelSub">
                    <a href="personalizacao.php" class="menu-item active"><i class="fas fa-paint-brush"></i> Personalização</a>
                </div>

                <div class="menu-item active" onclick="toggleSubmenu('adminSub')">
                    <i class="fas fa-toolbox"></i><span>Ferramentas</span><i class="fas fa-chevron-down arrow-icon" id="arrow-adminSub"></i>
                </div>
                <div class="submenu" id="adminSub">
                    <a href="importar.php" class="menu-item active"><i class="fas fa-file-import"></i> Importador</a>
                    <a href="dns_manager.php" class="menu-item active"><i class="fas fa-link"></i> Alterar DNS</a>
                    <a href="mover_conteudos.php" class="menu-item active"><i class="fas fa-exchange-alt"></i> Mover Conteúdos</a>
                    <a href="limpeza.php" class="menu-item active"><i class="fas fa-trash-alt"></i> Limpeza de Dados</a>
                    <a href="limpar_duplicados.php" class="menu-item active"><i class="fas fa-copy"></i> Limpeza de Duplicados</a>
                    <a href="backup.php" class="menu-item active"><i class="fas fa-database"></i> Backup do Sistema</a>
                    <a href="seguranca.php" class="menu-item active"><i class="fas fa-shield-alt"></i> Sistema de Segurança</a>
                    <a href="configuracoes.php" class="menu-item active"><i class="fas fa-tools"></i> Configurações</a>
                </div>

                <div class="menu-category">Conteúdos</div>
                <a href="categorias.php" class="menu-item active"><i class="fas fa-folder-open"></i><span>Categorias</span></a>
                <div class="menu-item active" onclick="toggleSubmenu('contentSub')">
                    <i class="fas fa-layer-group"></i><span>Mídias</span><i class="fas fa-chevron-down arrow-icon" id="arrow-contentSub"></i>
                </div>
                <div class="submenu" id="contentSub">
                    <a href="bouquets.php" class="menu-item active">Editar Bouquets</a>
                    <a href="canais.php" class="menu-item active">Canais Ao Vivo</a>
                    <a href="filmes.php" class="menu-item active">Filmes (VOD)</a>
                    <a href="series.php" class="menu-item active">Séries</a>
                </div>
                 <a href="admin_autofix_vod.php" class="menu-item active"><i class="fas fa-magic"></i> Auto-Fix TMDB</a>
            <?php endif; ?>
        </div>
        <a href="logout.php" class="logout-btn"><i class="fas fa-power-off"></i> Sair</a>
    </nav>

    <div class="main-content">
        <header class="topbar">
            <div style="display:flex; align-items:center;"><button class="menu-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button><h2 style="margin:0; font-size: 18px; color:white;">Gerenciar Testes IPTV</h2></div>
        </header>

        <div class="content-area">
            
            <?php echo $mensagem_aviso; ?>

            <div class="filter-bar">
                <form id="filterForm" method="GET" style="display: flex; flex-wrap: wrap; gap: 10px; width: 100%; align-items: flex-end;">
                    <div class="filter-group"><label>Buscar Usuário</label><input type="text" name="search" value="<?php echo htmlspecialchars($search ?? ''); ?>" onkeyup="autoSubmitSearch()"></div>
                    <div class="filter-group"><label>Exibir</label><select name="limit" onchange="this.form.submit()"><?php foreach([10, 50, 100] as $l): ?><option value="<?php echo $l; ?>" <?php echo $limit == $l ? 'selected' : ''; ?>><?php echo $l; ?></option><?php endforeach; ?></select></div>
                    <div style="margin-left: auto; display:flex; gap:10px; flex-wrap:wrap;">
                        <?php if($role === 'admin'): ?><button type="button" class="btn-main" style="background:#f39c12;" onclick="openModal('modalConfigTestTime')"><i class="fas fa-clock"></i> Tempo de Teste</button><?php endif; ?>
                        
                        <button type="button" class="btn-main" onclick="document.getElementById('formAutoTest').submit()" style="background:var(--success);"><i class="fas fa-bolt"></i> Teste Automático</button>
                        <button type="button" class="btn-main" style="background:var(--accent);" onclick="openModal('modalManual')"><i class="fas fa-keyboard"></i> Teste Manual</button>
                    </div>
                </form>
                <form id="formAutoTest" method="POST" style="display:none;"><input type="hidden" name="is_auto" value="1"><input type="hidden" name="action_test" value="1"></form>
            </div>

            <div id="bulkActionsBar">
                <div style="display:flex; align-items:center; gap:10px;"><span style="color: white; font-weight: bold; font-size:14px;"><span id="selectedCount" style="color:var(--accent);">0</span> Selecionados</span></div>
                <div style="display:flex; gap:10px; flex-wrap:wrap;"><button type="button" onclick="submitBulk('block')" class="btn-bulk" style="background:var(--warning);"><i class="fas fa-ban"></i> Status</button><button type="button" onclick="openModal('modalBulkExp')" class="btn-bulk" style="background:var(--info);"><i class="fas fa-calendar-alt"></i> Vencimento</button><button type="button" onclick="submitBulk('delete')" class="btn-bulk" style="background:var(--danger);"><i class="fas fa-trash"></i> Excluir</button></div>
            </div>

            <div class="card-table">
                <table>
                    <thead><tr><th style="width: 30px; text-align: center;"><input type="checkbox" id="selectAll" onclick="toggleSelectAll(this)" style="cursor:pointer; width:16px; height:16px; accent-color: var(--accent);"></th><th>Usuário</th><th>Senha</th><th>Criado por</th><th>Vencimento</th><th>Ações</th></tr></thead>
                    <tbody>
                        <?php if(empty($testes)): ?><tr><td colspan="6" style="text-align:center;">Nenhum teste encontrado.</td></tr>
                        <?php else: foreach ($testes as $t): 
                            $vencido = ($t['exp_date'] < time() && $t['exp_date'] != 0);
                            $badge_class = $t['enabled'] == 0 ? 'bg-danger' : ($vencido ? 'bg-danger' : 'bg-success');
                        ?>
                            <tr>
                                <td style="text-align: center;"><input type="checkbox" class="user-checkbox" value="<?php echo $t['id']; ?>" onchange="toggleBulkActions()" style="cursor:pointer; width:16px; height:16px; accent-color: var(--accent);"></td>
                                <td><strong><?php echo htmlspecialchars($t['username']); ?></strong><br><span class="badge <?php echo $badge_class; ?>">TESTE</span></td>
                                <td><code><?php echo htmlspecialchars($t['password']); ?></code></td>
                                <td><span class="badge" style="background: rgba(0, 123, 255, 0.1); color: var(--accent);"><?php echo htmlspecialchars($t['criador'] ?? 'Admin'); ?></span></td>
                                <td><?php echo $vencido ? "<span style='color:var(--danger)'>Vencido</span>" : "<span style='color:var(--warning)'>".date('H:i - d/m', $t['exp_date'])."</span>"; ?></td>
                                <td>
                                    <?php $msgInfo = gerarDadosAcessoCompleto($t['username'], $t['password'], $t['whatsapp'], $t['exp_date'], $t['max_connections']); ?>
                                    <button type="button" class="btn-action" style="background:var(--info);" data-texto="<?php echo htmlspecialchars($msgInfo['msg'], ENT_QUOTES, 'UTF-8'); ?>" data-zapurl="<?php echo htmlspecialchars($msgInfo['url'], ENT_QUOTES, 'UTF-8'); ?>" onclick="showReceipt(this)"><i class="fas fa-eye"></i></button>
                                    
                                    <a href="?renew_test=<?php echo $t['id']; ?>" class="btn-action" style="background:var(--success);" onclick="return confirm('ATENÇÃO: Deseja tornar este Teste um Cliente Oficial?\n\nSerá cobrado 1 CRÉDITO do seu saldo e o cliente ganhará +30 dias de acesso.')"><i class="fas fa-check"></i></a>
                                    
                                    <a href="?delete=<?php echo $t['id']; ?>" class="btn-action" style="background:var(--danger);" onclick="return confirm('Excluir?')"><i class="fas fa-trash"></i></a>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>

            <div style="display: flex; justify-content: center; align-items: center; gap: 15px; margin-top: 20px; margin-bottom: 10px; width: 100%;">
                <span style="color: var(--text-muted); font-size: 13px;">Página <?php echo $page; ?> de <?php echo max(1, $total_paginas); ?></span>
                <div style="display: flex; gap: 5px;">
                    <?php if ($page > 1): ?>
                        <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" onmouseover="this.style.background='var(--accent)'" onmouseout="this.style.background='var(--bg-card)'" style="background: var(--bg-card); color: white; border: 1px solid var(--border-color); padding: 8px 15px; border-radius: 5px; text-decoration: none; font-size: 13px; font-weight: bold; transition: 0.2s;">&laquo; Anterior</a>
                    <?php endif; ?>
                    <?php if ($page < $total_paginas): ?>
                        <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" onmouseover="this.style.background='var(--accent)'" onmouseout="this.style.background='var(--bg-card)'" style="background: var(--bg-card); color: white; border: 1px solid var(--border-color); padding: 8px 15px; border-radius: 5px; text-decoration: none; font-size: 13px; font-weight: bold; transition: 0.2s;">Próxima &raquo;</a>
                    <?php endif; ?>
                </div>
            </div>
            <form id="bulkForm" method="POST" style="display:none;"><input type="hidden" name="action_bulk" value="1"><input type="hidden" name="bulk_type" id="bulkType"><input type="hidden" name="bulk_ids" id="bulkIds"><input type="hidden" name="bulk_exp_date" id="bulkExpDate"></form>
        </div>
        <?php include 'rodape.php'; ?>
    </div>

    <div id="modalBulkExp" class="modal">
        <div class="modal-content"><h3 style="margin-top:0; color:white;"><i class="fas fa-clock" style="color:var(--info);"></i> Alterar Tempo</h3>
            <div class="form-group-modal"><label>Novo Horário</label><input type="datetime-local" id="bulk_new_exp" required></div>
            <button type="button" onclick="submitBulk('exp')" class="btn-save-modal" style="background:var(--info);">APLICAR</button>
            <button type="button" onclick="closeAllModals()" style="width:100%; background:none; border:none; color:var(--text-muted); margin-top:10px; cursor:pointer;">Cancelar</button>
        </div>
    </div>

    <div id="modalManual" class="modal">
        <div class="modal-content"><h3 style="margin-top:0; color:white;"><i class="fas fa-keyboard"></i> Teste Manual</h3>
            <form method="POST"><input type="hidden" name="action_test" value="1">
                <div class="form-group-modal"><label>Usuário</label><input type="text" name="username" required></div>
                <div class="form-group-modal"><label>Senha</label><input type="text" name="password" required></div>
                <div class="form-group-modal"><label>WhatsApp</label><input type="text" name="whatsapp"></div>
                <div class="form-group-modal"><label>Quantidade de Telas (Conexões)</label><input type="number" name="max_connections" value="1" min="1" max="5"></div>
                <button type="submit" class="btn-save-modal">CRIAR AGORA</button>
                <button type="button" onclick="closeAllModals()" style="width:100%; background:none; border:none; color:var(--text-muted); margin-top:15px; cursor:pointer;">Cancelar</button>
            </form>
        </div>
    </div>

    <div id="modalConfigTestTime" class="modal">
        <div class="modal-content"><h3 style="margin-top:0; color:white;"><i class="fas fa-clock" style="color:#f39c12;"></i> Tempo Padrão</h3>
            <form method="POST"><input type="hidden" name="action_config_test_time" value="1">
                <div class="form-group-modal"><label>Duração (Horas)</label><select name="tempo_teste_novo"><?php foreach([1, 2, 3, 4, 6, 12, 24, 48] as $h): ?><option value="<?php echo $h; ?>" <?php echo $tempo_teste == $h ? 'selected' : ''; ?>><?php echo $h; ?> Hora(s)</option><?php endforeach; ?></select></div>
                <button type="submit" class="btn-save-modal" style="background:#f39c12;">SALVAR TEMPO</button>
                <button type="button" onclick="closeAllModals()" style="width:100%; background:none; border:none; color:var(--text-muted); margin-top:10px; cursor:pointer;">Cancelar</button>
            </form>
        </div>
    </div>

    <div id="modalView" class="modal">
        <div class="modal-content"><h3 style="margin-top:0; color:white;"><i class="fas fa-eye"></i> Dados do Teste</h3>
            <textarea id="view_text" rows="12" readonly style="width:100%; padding:15px; background:#0f1114; border:1px solid var(--border-color); color:#fff; border-radius:8px; resize:none; font-family: monospace; font-size:12px; margin-bottom:15px; box-sizing:border-box;"></textarea>
            <div style="display:flex; gap:10px;"><button type="button" onclick="copyText()" class="btn-main" style="width:100%; background:var(--accent); text-align:center; justify-content:center;"><i class="fas fa-copy"></i> COPIAR</button><a id="btn_zap_view" href="#" target="_blank" class="btn-main" style="width:100%; background:#25d366; text-align:center; justify-content:center;"><i class="fab fa-whatsapp"></i> ENVIAR</a></div>
            <button type="button" onclick="closeAllModals()" style="width:100%; background:none; border:none; color:var(--text-muted); margin-top:15px; cursor:pointer;">Fechar</button>
        </div>
    </div>

    <script>
        function toggleMenu() { document.getElementById('sidebar').classList.toggle('active'); document.getElementById('overlay').classList.toggle('active'); }
        function toggleSubmenu(id) { var sub = document.getElementById(id); var arrow = document.getElementById('arrow-' + id); if (sub.style.display === "block") { sub.style.display = "none"; if(arrow) arrow.classList.remove('rotate'); } else { sub.style.display = "block"; if(arrow) arrow.classList.add('rotate'); } }
        var searchTimeout; function autoSubmitSearch() { clearTimeout(searchTimeout); searchTimeout = setTimeout(function() { document.getElementById('filterForm').submit(); }, 600); }
        function toggleSelectAll(source) { var checkboxes = document.querySelectorAll('.user-checkbox'); for (var i = 0; i < checkboxes.length; i++) { checkboxes[i].checked = source.checked; } toggleBulkActions(); }
        function toggleBulkActions() { var checkboxes = document.querySelectorAll('.user-checkbox:checked'); var bar = document.getElementById('bulkActionsBar'); var countSpan = document.getElementById('selectedCount'); if (checkboxes.length > 0) { countSpan.innerText = checkboxes.length; bar.style.display = 'flex'; } else { bar.style.display = 'none'; document.getElementById('selectAll').checked = false; } }
        function getSelectedIds() { var checkboxes = document.querySelectorAll('.user-checkbox:checked'); var ids = []; for (var i = 0; i < checkboxes.length; i++) { ids.push(checkboxes[i].value); } return ids.join(','); }
        function submitBulk(type) { var ids = getSelectedIds(); if (!ids) return; if (type === 'delete' && !confirm('EXCLUIR TODOS?')) return; if (type === 'exp') { var novaData = document.getElementById('bulk_new_exp').value; if (!novaData) { alert('Informe a data!'); return; } document.getElementById('bulkExpDate').value = novaData; } document.getElementById('bulkType').value = type; document.getElementById('bulkIds').value = ids; document.getElementById('bulkForm').submit(); }
        
        // Abertura Universal dos Modais usando FLEX para centralizar
        function openModal(id) { document.getElementById(id).style.display = 'flex'; }
        function closeAllModals() { document.querySelectorAll('.modal').forEach(function(m){m.style.display='none';}); }

        function showReceipt(btn) {
            document.getElementById('view_text').value = btn.getAttribute('data-texto');
            document.getElementById('btn_zap_view').href = btn.getAttribute('data-zapurl');
            openModal('modalView');
        }

        function copyText() {
            var texto = document.getElementById('view_text').value;
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(texto).then(function() { alert('Copiado!'); closeAllModals(); });
            } else {
                var textArea = document.createElement("textarea"); textArea.value = texto; document.body.appendChild(textArea); textArea.select();
                try { document.execCommand('copy'); alert('Copiado!'); closeAllModals(); } catch (err) {} document.body.removeChild(textArea);
            }
        }

        <?php if(isset($_SESSION['comprovante_teste'])): ?>
            window.onload = function() {
                var compMsg = <?php echo json_encode($_SESSION['comprovante_teste']['msg']); ?>;
                var compUrl = <?php echo json_encode($_SESSION['comprovante_teste']['url']); ?>;
                try {
                    document.getElementById('view_text').value = compMsg;
                    document.getElementById('btn_zap_view').href = compUrl;
                    openModal('modalView');
                    var xhr = new XMLHttpRequest(); xhr.open('GET', '?clear_msg=1', true); xhr.send();
                } catch(e) {}
            };
        <?php endif; ?>
        
        // --- SCRIPT PARA FAZER O ALERTA SUMIR SOZINHO SUAVEMENTE ---
        setTimeout(function() { 
            try { 
                var alerts = document.querySelectorAll('.alert'); 
                for(var i=0; i<alerts.length; i++) { 
                    alerts[i].style.opacity = '0'; 
                    alerts[i].style.transition = 'opacity 0.5s ease';
                } 
                setTimeout(function(){ 
                    for(var j=0; j<alerts.length; j++) { 
                        alerts[j].style.display = 'none'; 
                    } 
                }, 500); // Espera a animação de opacidade terminar
            } catch(e) {} 
        }, 4000); // Tempo na tela: 4 Segundos
    </script>
</body>
</html>