<?php
session_start();
date_default_timezone_set('America/Sao_Paulo');

require_once 'config.php'; 
$pdo = getConexaoAtiva();
$pdo_int = getConexaoInterna();
$pdo->exec("SET NAMES utf8mb4");
$pdo->exec("SET SESSION sql_mode = ''");

if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }
$user_id_logado = $_SESSION['user_id']; 
$nome_usuario = $_SESSION['username'] ?? 'Usuário'; 

$modo_ativo = 'interno';
try { $modo_ativo = $pdo_int->query("SELECT modo_ativo FROM configuracoes LIMIT 1")->fetchColumn() ?: 'interno'; } catch (Exception $e) {}

// Permite a alteração temporária do modo_ativo pela sessão, se enviado via POST (Para o "switch" dinâmico funcionar)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_change_mode'])) {
    $novo_modo = $_POST['novo_modo'] ?? 'interno';
    if (in_array($novo_modo, ['interno', 'externo', 'xui'])) {
        $_SESSION['modo_ativo_temp'] = $novo_modo;
        $modo_ativo = $novo_modo;
        // Retorno rápido pro AJAX sem carregar a página
        header('Content-Type: application/json');
        echo json_encode(['sucesso' => true, 'modo' => strtoupper($modo_ativo)]);
        exit;
    }
} elseif (isset($_SESSION['modo_ativo_temp'])) {
    $modo_ativo = $_SESSION['modo_ativo_temp'];
}

$tabela_clientes = ($modo_ativo === 'xui') ? '`lines`' : '`users`';
$col_whatsapp = ($modo_ativo === 'xui') ? 'phone' : 'whatsapp';
$col_nome = ($modo_ativo === 'xui') ? 'admin_notes' : 'nome_cliente';
$cond_p2p = ($modo_ativo === 'xui') ? "1=1" : "(u.is_p2p = 0 OR u.is_p2p IS NULL)";
$tabela_revendedores = ($modo_ativo === 'xui') ? '`users`' : '`reg_users`';

try {
    $stmtRole = $pdo->prepare("SELECT member_group_id, credits FROM $tabela_revendedores WHERE id = ?");
    $stmtRole->execute([$user_id_logado]);
    $userData = $stmtRole->fetch(PDO::FETCH_ASSOC);
    $role = ($userData && $userData['member_group_id'] == 1) ? 'admin' : 'reseller';
    $user_credits = $userData ? floatval($userData['credits']) : 0.0;
} catch (Exception $e) { $role = 'reseller'; $user_credits = 0.0; }

$nome_painel = 'TOP IPTV'; $logo_url = ''; $cor_primaria = '#007bff'; $tempo_teste = 4;
$permitir_teste_revenda = 1; // Padrão: Liberado
$wa_url = ''; $wa_key = ''; $wa_inst = ''; $wa_status = 0;

try {
    $config_painel = $pdo_int->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;
        $logo_url = $config_painel['logo_url'] ?? '';
        if (isset($config_painel['tempo_teste'])) { $tempo_teste = (int)$config_painel['tempo_teste']; }
        if (isset($config_painel['permitir_teste_revenda'])) { $permitir_teste_revenda = (int)$config_painel['permitir_teste_revenda']; }
    }
} catch (Exception $e) {}

try {
    $api_user = $pdo->prepare("SELECT wa_api_url, wa_api_key, wa_instancia, wa_status FROM $tabela_revendedores WHERE id = ?");
    $api_user->execute([$user_id_logado]);
    $dados_api = $api_user->fetch(PDO::FETCH_ASSOC);
    if ($dados_api) {
        $wa_url = $dados_api['wa_api_url'] ?? ''; $wa_key = $dados_api['wa_api_key'] ?? '';
        $wa_inst = $dados_api['wa_instancia'] ?? ''; $wa_status = (int)($dados_api['wa_status'] ?? 0);
    }
} catch (Exception $e) {}

try {
    if ($modo_ativo !== 'xui') {
        $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_nome = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'nome_cliente'"); if (!$check_nome->fetch()) { $pdo->exec("ALTER TABLE `users` ADD COLUMN `nome_cliente` 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"); }
        
        // CORREÇÕES XTREAM UI: Colunas do Restreamer e Controle de Acesso
        $check_res = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'is_restreamer'"); if (!$check_res->fetch()) { $pdo->exec("ALTER TABLE `users` ADD COLUMN `is_restreamer` TINYINT(1) DEFAULT 0"); }
        $check_ips = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'allowed_ips'"); if (!$check_ips->fetch()) { $pdo->exec("ALTER TABLE `users` ADD COLUMN `allowed_ips` TEXT DEFAULT '[]'"); }
        $check_uas = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'allowed_ua'"); if (!$check_uas->fetch()) { $pdo->exec("ALTER TABLE `users` ADD COLUMN `allowed_ua` TEXT DEFAULT '[]'"); }
        $check_force = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'force_server_id'"); if (!$check_force->fetch()) { $pdo->exec("ALTER TABLE `users` ADD COLUMN `force_server_id` INT(11) DEFAULT 0"); }

    } else {
        $check_trust = $pdo->query("SHOW COLUMNS FROM `lines` LIKE 'trust_used'"); if (!$check_trust->fetch()) { $pdo->exec("ALTER TABLE `lines` ADD COLUMN `trust_used` TINYINT(1) DEFAULT 0"); }
        $check_phone = $pdo->query("SHOW COLUMNS FROM `lines` LIKE 'phone'"); if (!$check_phone->fetch()) { $pdo->exec("ALTER TABLE `lines` ADD COLUMN `phone` VARCHAR(255) DEFAULT NULL"); }
        
        // CORREÇÕES XUI: Colunas do Restreamer e Controle de Acesso
        $check_res = $pdo->query("SHOW COLUMNS FROM `lines` LIKE 'is_restreamer'"); if (!$check_res->fetch()) { $pdo->exec("ALTER TABLE `lines` ADD COLUMN `is_restreamer` TINYINT(1) DEFAULT 0"); }
        $check_ips = $pdo->query("SHOW COLUMNS FROM `lines` LIKE 'allowed_ips'"); if (!$check_ips->fetch()) { $pdo->exec("ALTER TABLE `lines` ADD COLUMN `allowed_ips` TEXT DEFAULT '[]'"); }
        $check_uas = $pdo->query("SHOW COLUMNS FROM `lines` LIKE 'allowed_ua'"); if (!$check_uas->fetch()) { $pdo->exec("ALTER TABLE `lines` ADD COLUMN `allowed_ua` TEXT DEFAULT '[]'"); }
        $check_force = $pdo->query("SHOW COLUMNS FROM `lines` LIKE 'force_server_id'"); if (!$check_force->fetch()) { $pdo->exec("ALTER TABLE `lines` ADD COLUMN `force_server_id` INT(11) DEFAULT 0"); }
    }
    $pdo_int->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`) )");
    $check_wa = $pdo_int->query("SHOW COLUMNS FROM `painel_config` LIKE 'wa_api_url'");
    if (!$check_wa->fetch()) { $pdo_int->exec("ALTER TABLE `painel_config` ADD COLUMN `wa_api_url` VARCHAR(255) DEFAULT '', ADD COLUMN `wa_api_key` VARCHAR(255) DEFAULT '', ADD COLUMN `wa_instancia` VARCHAR(255) DEFAULT '', ADD COLUMN `wa_status` TINYINT(1) DEFAULT 0"); }
    
    // ==============================================================================
    // AUTO-CORREÇÃO: Adiciona a coluna de permissão de teste na configuração do painel
    // ==============================================================================
    $check_test_rev = $pdo_int->query("SHOW COLUMNS FROM `painel_config` LIKE 'permitir_teste_revenda'");
    if (!$check_test_rev->fetch()) { $pdo_int->exec("ALTER TABLE `painel_config` ADD COLUMN `permitir_teste_revenda` TINYINT(1) DEFAULT 1"); }
    
} catch (Exception $e) {}

// ====================================================================
// CAPTURA DO DNS DE STREAMING GLOBAL (PUXANDO DA ÁREA DE DNS / SERVIDORES)
// ====================================================================
$protocolo_painel = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$url_painel = $protocolo_painel . $_SERVER['HTTP_HOST'];
$url_streaming_global = $url_painel; // Fallback padrão

$tabela_servidores_dns = ($modo_ativo === 'xui') ? 'servers' : 'streaming_servers';
try {
    $stmtDnsArea = $pdo->query("SELECT domain_name, server_ip FROM $tabela_servidores_dns ORDER BY id ASC LIMIT 1");
    $dnsAreaInfo = $stmtDnsArea->fetch(PDO::FETCH_ASSOC);
    if ($dnsAreaInfo) {
        $dns_val_area = '';
        if (isset($dnsAreaInfo['domain_name']) && !empty(trim($dnsAreaInfo['domain_name']))) {
            $dns_val_area = trim($dnsAreaInfo['domain_name']);
        } elseif (isset($dnsAreaInfo['server_ip']) && !empty(trim($dnsAreaInfo['server_ip']))) {
            $dns_val_area = trim($dnsAreaInfo['server_ip']);
        }
        if (!empty($dns_val_area)) {
            if (strpos($dns_val_area, 'http') !== 0) { $dns_val_area = "http://" . $dns_val_area; }
            $url_streaming_global = rtrim($dns_val_area, '/');
        }
    }
} catch(Exception $e){}

$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, $url_painel, $url_streaming_global, $user_id_logado; 
    
    $validade = $e ? date('d/m/Y H:i', $e) : "{$tempo_teste} Horas";
    
    // Links geradores locais usam o DNS de streaming global
    $link_m3u = "{$url_streaming_global}/get.php?username={$u}&password={$p}&type=m3u_plus&output=mpegts";
    $link_hls = "{$url_streaming_global}/get.php?username={$u}&password={$p}&type=m3u_plus&output=hls";
    $m3u_completo = "{$url_streaming_global}/get.php?username={$u}&password={$p}&type=m3u_plus&output=ts";

    $link_ssiptv = "{$url_streaming_global}/ssiptv.php?username={$u}&password={$p}&ssiptv=1";
    $m3u_encurtado = "{$url_streaming_global}/m3u-ts/{$u}/{$p}"; 
    $m3u_hls_encurtado = "{$url_streaming_global}/m3u-m3u8/{$u}/{$p}"; 
    $ssiptv_encurtado = "{$url_streaming_global}/ss-ts/{$u}/{$p}"; 
    $roku_encurtado = "{$url_streaming_global}/roku/{$u}/{$p}";
    
    // GERAÇÃO DO LINK DE PAGAMENTO ÚNICO E CRIPTOGRAFADO (REVENDA + CLIENTE)
    $hash_dono = base64_encode("RS-".$user_id_logado);
    $hash_cliente = base64_encode("CL-".$u);
    $link_pagamento = "{$url_painel}/checkout.php?r={$hash_dono}&c={$hash_cliente}";
    
    $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, $url_streaming_global, $m3u_encurtado, $m3u_hls_encurtado, $ssiptv_encurtado, $roku_encurtado, $link_m3u, $link_hls, $m3u_completo],
        $raw_template
    );
    
    // Limpa assinaturas ou duplicadas antigas do fim do texto
    $msg = preg_replace('/ATT: TOP IPTV\s+💳 \*Link de Pagamento \/ Planos:\*\s+https?:\/\/[^\s]+/i', '', $msg);
    $msg = preg_replace('/💳 \*Link de Pagamento \/ Planos:\*\s+https?:\/\/[^\s]+/i', '', $msg);

    // Injeta de forma cirúrgica logo após a linha de conexões/telas
    $regex_alvo = '/(├●\s*\*conexões\s*:\*?\s*\d+)/i';
    if (preg_match($regex_alvo, $msg)) {
        $msg = preg_replace($regex_alvo, "$1\n├● 💳 *Pagar/Renovar*: " . $link_pagamento, $msg);
    } else {
        $msg = str_replace($validade, $validade . "\n├● 💳 *Pagar/Renovar*: " . $link_pagamento, $msg);
    }
    
    return ['msg' => $msg, 'url' => "https://api.whatsapp.com/send?phone=".preg_replace('/\D/','',(string)$z)."&text=".urlencode($msg)];
}

function enviarMsgZapInvisivel($numero, $mensagem) {
    global $wa_url, $wa_key, $wa_inst, $wa_status;
    if ($wa_status == 0 || empty($wa_url)) return false;
    $numero = preg_replace('/\D/', '', $numero);
    if(empty($numero)) return false;
    if (strlen($numero) == 10 || strlen($numero) == 11) { $numero = "55" . $numero; }
    $endpoint = rtrim($wa_url, '/');
    if(strpos($endpoint, '/message/sendText') === false) { $endpoint = $endpoint . "/message/sendText/" . $wa_inst; }
    $dados = [ "number" => $numero, "options" => [ "delay" => 1200, "presence" => "composing" ], "textMessage" => [ "text" => $mensagem ] ];
    $ch = curl_init($endpoint);
    curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($dados, JSON_UNESCAPED_UNICODE), CURLOPT_HTTPHEADER => [ "Content-Type: application/json; charset=utf-8", "apikey: ".$wa_key, "Authorization: Bearer ".$wa_key ], CURLOPT_TIMEOUT => 5, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false ]);
    $res = curl_exec($ch); curl_close($ch); return $res;
}

if (isset($_GET['clear_msg'])) { unset($_SESSION['comprovante_teste']); exit; }
$mensagem_aviso = "";

if (isset($_POST['action_config_test_time']) && $role === 'admin') {
    $novo_tempo = intval($_POST['tempo_teste_novo']); if ($novo_tempo < 1) $novo_tempo = 4;
    $permitir_revenda = isset($_POST['permitir_teste_revenda']) ? 1 : 0;
    
    $pdo_int->prepare("UPDATE painel_config SET tempo_teste = ?, permitir_teste_revenda = ?")->execute([$novo_tempo, $permitir_revenda]);
    $tempo_teste = $novo_tempo;
    $permitir_teste_revenda = $permitir_revenda;
    
    $mensagem_aviso = "<div class='alert success'>Configurações de teste atualizadas!</div>";
}

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 $tabela_clientes WHERE id IN ($id_list) $condicao_seguranca"); } 
        elseif ($type === 'block') { $pdo->exec("UPDATE $tabela_clientes 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 $tabela_clientes SET exp_date = ? WHERE id IN ($id_list) $condicao_seguranca")->execute([$new_exp]); }
    }
}

// MÁGICA: AÇÃO DE EDIÇÃO DE TESTE
if (isset($_POST['action_edit_test'])) {
    $id_edit = intval($_POST['edit_id']);
    $user_edit = $_POST['username'];
    $pass_edit = $_POST['password'];
    $zap_edit = $_POST['whatsapp'] ?? '';
    $nome_edit = $_POST['nome_cliente'] ?? '';
    $telas_edit = isset($_POST['max_connections']) ? intval($_POST['max_connections']) : 1;
    $bouquets_edit = isset($_POST['user_bouquets']) ? json_encode($_POST['user_bouquets']) : '[]';
    
    $condicao_edit = ($role !== 'admin') ? " AND member_id = " . intval($user_id_logado) : "";
    
    $stmtChk = $pdo->prepare("SELECT id FROM $tabela_clientes WHERE id = ?$condicao_edit");
    $stmtChk->execute([$id_edit]);
    if ($stmtChk->fetch()) {
        if ($role === 'admin') {
            $is_restreamer = isset($_POST['is_restreamer']) ? 1 : 0;
            $force_server_id = isset($_POST['force_server_id']) ? intval($_POST['force_server_id']) : 1;
            $ips_arr = !empty($_POST['allowed_ips']) ? array_filter(array_map('trim', explode(',', $_POST['allowed_ips']))) : [];
            $ua_arr = !empty($_POST['allowed_ua']) ? array_filter(array_map('trim', explode(',', $_POST['allowed_ua']))) : [];
            $ips_json = empty($ips_arr) ? '[]' : json_encode(array_values($ips_arr));
            $ua_json = empty($ua_arr) ? '[]' : json_encode(array_values($ua_arr));
            
            $sql = "UPDATE $tabela_clientes SET username=?, password=?, $col_whatsapp=?, $col_nome=?, max_connections=?, bouquet=?, is_restreamer=?, allowed_ips=?, allowed_ua=?, force_server_id=? WHERE id=?";
            $pdo->prepare($sql)->execute([$user_edit, $pass_edit, $zap_edit, $nome_edit, $telas_edit, $bouquets_edit, $is_restreamer, $ips_json, $ua_json, $force_server_id, $id_edit]);
        } else {
            $sql = "UPDATE $tabela_clientes SET username=?, password=?, $col_whatsapp=?, $col_nome=?, max_connections=?, bouquet=? WHERE id=?";
            $pdo->prepare($sql)->execute([$user_edit, $pass_edit, $zap_edit, $nome_edit, $telas_edit, $bouquets_edit, $id_edit]);
        }
        $mensagem_aviso = "<div class='alert success'>Teste updated com sucesso!</div>";
    } else {
        $mensagem_aviso = "<div class='alert danger'>Acesso negado para editar este teste.</div>";
    }
}

if (isset($_POST['action_test'])) {
    if ($role !== 'admin' && $permitir_teste_revenda == 0) {
        $mensagem_aviso = "<div class='alert danger'>A criação de testes por revendedores está desativada no momento.</div>";
    } elseif ($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'] ?? '';
        $nome_cliente = $_POST['nome_cliente'] ?? '';
        $exp  = time() + ($tempo_teste * 3600); 
        $created_at = time(); 
        
        if ($is_auto) {
            $bouquets_selecionados = '[]';
            try {
                $bq_completo_id = $pdo->query("SELECT id FROM bouquets WHERE bouquet_name LIKE '%completo%' ORDER BY id ASC LIMIT 1")->fetchColumn();
                if (!$bq_completo_id) {
                    $todos_bqs = $pdo->query("SELECT id FROM bouquets")->fetchAll(PDO::FETCH_COLUMN);
                    if ($todos_bqs) {
                        $bouquets_selecionados = json_encode($todos_bqs);
                    }
                } else {
                    $bouquets_selecionados = json_encode([$bq_completo_id]);
                }
            } catch (Exception $e) {}
        } else {
            $bouquets_selecionados = isset($_POST['user_bouquets']) ? json_encode($_POST['user_bouquets']) : '[]';
        }

        if ($role === 'admin') {
            $is_restreamer = isset($_POST['is_restreamer']) ? 1 : 0;
            $force_server_id = isset($_POST['force_server_id']) ? intval($_POST['force_server_id']) : 1;
            $ips_arr = !empty($_POST['allowed_ips']) ? array_filter(array_map('trim', explode(',', $_POST['allowed_ips']))) : [];
            $ua_arr = !empty($_POST['allowed_ua']) ? array_filter(array_map('trim', explode(',', $_POST['allowed_ua']))) : [];
            $ips_json = empty($ips_arr) ? '[]' : json_encode(array_values($ips_arr));
            $ua_json = empty($ua_arr) ? '[]' : json_encode(array_values($ua_arr));
        } else {
            $is_restreamer = 0; $force_server_id = 1; $ips_json = '[]'; $ua_json = '[]';
        }
        
        try {
            if ($modo_ativo === 'xui') {
                $sql = "INSERT INTO `lines` (username, password, phone, exp_date, enabled, admin_enabled, member_id, max_connections, created_at, admin_notes, bouquet, is_trial, is_restreamer, allowed_ips, allowed_ua, force_server_id) VALUES (?, ?, ?, ?, 1, 1, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?)";
                $res_insert = $pdo->prepare($sql)->execute([$user, $pass, $zap, $exp, $user_id_logado, $telas, $created_at, $nome_cliente, $bouquets_selecionados, $is_restreamer, $ips_json, $ua_json, $force_server_id]);
            } else {
                $sql = "INSERT INTO users (username, password, whatsapp, exp_date, enabled, admin_enabled, member_id, is_p2p, max_connections, created_at, nome_cliente, bouquet, is_restreamer, allowed_ips, allowed_ua, force_server_id) VALUES (?, ?, ?, ?, 1, 1, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?)";
                $res_insert = $pdo->prepare($sql)->execute([$user, $pass, $zap, $exp, $user_id_logado, $telas, $created_at, $nome_cliente, $bouquets_selecionados, $is_restreamer, $ips_json, $ua_json, $force_server_id]);
            }
            
            if($res_insert) {
                $msgInfo = gerarDadosAcessoCompleto($user, $pass, $zap, $exp, $telas);
                $_SESSION['comprovante_teste'] = $msgInfo;
                if (!empty($zap)) { if ($wa_status == 1) { enviarMsgZapInvisivel($zap, $msgInfo['msg']); } else { $_SESSION['auto_zap_url'] = $msgInfo['url']; } }
                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']);
    $stmtCh = $pdo->prepare("SELECT member_id, username, password, $col_whatsapp as whatsapp FROM $tabela_clientes 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;
        if ($role !== 'admin') {
            if ($user_credits < 1) { $pode_renovar = false; $mensagem_aviso = "<div class='alert danger'>Saldo insuficiente para renovar!</div>"; } 
            else { $pdo->prepare("UPDATE $tabela_revendedores SET credits = credits - 1 WHERE id = ?")->execute([$user_id_logado]); }
        }

        if ($pode_renovar) {
            $nova_exp = time() + (30 * 86400);
            if ($modo_ativo === 'xui') { $pdo->prepare("UPDATE `lines` SET exp_date = ?, is_trial = 0 WHERE id = ?")->execute([$nova_exp, $id_teste]); } 
            else { $pdo->prepare("UPDATE users SET exp_date = ? WHERE id = ?")->execute([$nova_exp, $id_teste]); }
            
            if ($role !== 'admin') {
                try {
                    $agora = date('Y-m-d H:i:s');
                    $pdo_int->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) {}
            }

            $u = $dados_teste['username']; $p = $dados_teste['password']; $z = $dados_teste['whatsapp']; $data_formatada = date('d/m/Y H:i', $nova_exp);
            $msg_renovacao = "✅ *Acesso Renovado com Sucesso!*\n\nSeu teste foi convertido para cliente oficial.\n\n👤 *Usuário:* {$u}\n🔑 *Senha:* {$p}\n🗓 *Nova Validade:* {$data_formatada}\n\nObrigado pela preferência!";
            
            if (!empty($z)) {
                $url_zap = "https://api.whatsapp.com/send?phone=".preg_replace('/\D/','',(string)$z)."&text=".urlencode($msg_renovacao);
                if ($wa_status == 1) { enviarMsgZapInvisivel($z, $msg_renovacao); } else { $_SESSION['auto_zap_url'] = $url_zap; }
            } else { $url_zap = "https://api.whatsapp.com/send?text=".urlencode($msg_renovacao); }
            $_SESSION['comprovante_teste'] = ['msg' => $msg_renovacao, 'url' => $url_zap];
            header("Location: testes.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 $tabela_clientes 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 $tabela_clientes SET enabled = IF(enabled=1, 0, 1) WHERE id = ? $condicao")->execute([$_GET['block']]); header("Location: testes.php"); exit; 
}

$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'] ?? '';

$where_clause = "WHERE $cond_p2p AND (u.exp_date - UNIX_TIMESTAMP()) < 172800"; 
$params = [];
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 OR u.$col_nome LIKE :search)"; $params[':search'] = "%$search%"; }

$stmt = $pdo->prepare("SELECT u.*, u.$col_whatsapp as whatsapp, u.$col_nome as nome_cliente FROM $tabela_clientes u " . $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 $tabela_clientes u " . $where_clause);
foreach ($params as $key => $val) { $stmtC->bindValue($key, $val); }
$stmtC->execute();
$total_registros = $stmtC->fetchColumn();
$total_paginas = ceil($total_registros / $limit);

$revendedores_map = [];
try {
    $revs = $pdo->query("SELECT id, username FROM $tabela_revendedores")->fetchAll(PDO::FETCH_ASSOC);
    foreach($revs as $r) { $revendedores_map[$r['id']] = $r['username']; }
} catch (Exception $e) {}

$bouquets_lista = $pdo->query("SELECT id, bouquet_name FROM bouquets ORDER BY bouquet_name ASC")->fetchAll(PDO::FETCH_ASSOC);
?>
<!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; flex-shrink: 0; }
        .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 { width: 100%; max-width: 180px; height: auto; max-height: 60px; object-fit: contain; display: block; margin: 0 auto; }
        .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.7); 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); }
        
        /* NOVO BADGE INTERATIVO DA TOPBAR */
        .mode-badge-interactive { 
            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); 
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        .mode-badge-interactive:hover { filter: brightness(1.2); background: rgba(40, 167, 69, 0.3); }

        .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; }
        
        /* BOTÃO DE MODO DE VISUALIZAÇÃO */
        .btn-toggle-view { background: #121519; color: white; border: 1px solid var(--border-color); padding: 10px 20px; border-radius: 5px; cursor: pointer; font-weight: bold; display: flex; align-items: center; justify-content: center; gap: 8px; transition: 0.2s; width: 100%;}
        .btn-toggle-view:hover { background: var(--accent); border-color: var(--accent); }
        .btn-toggle-view.active { background: var(--accent); border-color: var(--accent); }

        .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; text-decoration: none; transition: 0.2s; margin: 0; }
        .btn-action:hover { filter: brightness(1.2); }
        #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; transition: 0.2s; }
        .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; max-height: 80vh; overflow-y: auto; padding-bottom: 30px;}
        .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; }
        
        .bouquet-grid { max-height: 150px; overflow-y: auto; background: #121519; padding: 10px; border-radius: 5px; border: 1px solid var(--border-color); }
        .bouquet-item { display: flex; align-items: center; gap: 8px; font-size: 13px; margin-bottom: 5px; color: white;}

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

        /* ==================================================================== */
        /* ESTILOS PARA O MODO GRID (CARDS) */
        /* ==================================================================== */
        .grid-view-container {
            display: none; 
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }

        .client-card {
            background: var(--bg-card);
            border: 1px solid var(--border-color);
            border-radius: 10px;
            padding: 15px;
            display: flex;
            flex-direction: column;
            gap: 12px;
            position: relative;
        }

        .card-header-top {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
        }

        .card-user-info {
            display: flex;
            flex-direction: column;
        }

        .card-username {
            font-size: 16px;
            font-weight: bold;
            color: var(--accent);
            word-break: break-all;
        }

        .card-client-name {
            font-size: 12px;
            color: var(--text-muted);
            margin-top: 2px;
        }

        .card-status-badges {
            display: flex;
            gap: 5px;
            margin-top: 8px;
        }

        .card-status-badges .badge {
            font-size: 10px;
            padding: 4px 8px;
            border-radius: 4px;
            border: 1px solid transparent;
            background: transparent;
        }

        .card-status-badges .badge.ativo { color: var(--success); border-color: var(--success); }
        .card-status-badges .badge.vencido { color: var(--danger); border-color: var(--danger); }
        .card-status-badges .badge.bloqueado { color: #fff; background: #000; border-color: #000; }
        .card-status-badges .badge.iptv { color: #8b5cf6; border-color: #8b5cf6; }
        .card-status-badges .badge.teste { color: var(--warning); border-color: var(--warning); }

        .card-details-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            background: #121519;
            padding: 10px;
            border-radius: 8px;
            border: 1px solid var(--border-color);
        }

        .detail-item {
            display: flex;
            flex-direction: column;
        }

        .detail-label {
            font-size: 10px;
            color: var(--text-muted);
            text-transform: uppercase;
            font-weight: bold;
        }

        .detail-value {
            font-size: 12px;
            color: white;
            font-weight: bold;
        }

        .card-actions-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 8px;
            margin-top: auto;
        }

        .card-btn-action {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 5px;
            background: #1a1d24;
            border: 1px solid var(--border-color);
            color: var(--text-main);
            padding: 8px 5px;
            border-radius: 8px;
            cursor: pointer;
            transition: 0.2s;
            text-decoration: none;
            font-size: 10px;
        }

        .card-btn-action:hover {
            filter: brightness(1.2);
            color: white;
        }

        .card-btn-action i {
            font-size: 16px;
        }

        .cb-action-edit { color: var(--text-muted); }
        .cb-action-edit:hover { background: #34495e; border-color: #34495e; }
        
        .cb-action-playlist { color: var(--info); }
        .cb-action-playlist:hover { background: var(--info); border-color: var(--info); }
        
        .cb-action-renew { color: var(--success); }
        .cb-action-renew:hover { background: var(--success); border-color: var(--success); }
        
        .cb-action-url { color: #8b5cf6; }
        .cb-action-url:hover { background: #8b5cf6; border-color: #8b5cf6; }

        .checkbox-container {
            position: absolute;
            top: 15px;
            right: 15px;
        }

        /* UNIFICAÇÃO DA CAIXA DE COMPROVANTE (TELA CHEIA E CENTRALIZADO NO PC E CELULAR) */
        #modalView {
            align-items: center !important;
            justify-content: center !important;
        }
        
        #modalView .modal-content {
            width: 100% !important;
            height: 100% !important;
            max-width: 100% !important;
            max-height: 100vh !important;
            margin: 0 !important;
            border-radius: 0 !important;
            border: none !important;
            display: flex !important;
            flex-direction: column !important;
            box-sizing: border-box !important;
            padding: 30px 20px !important;
            background: rgba(18, 21, 25, 0.98) !important; 
            backdrop-filter: blur(10px);
            align-items: center;
            justify-content: center;
        }
        
        #modalView > div:first-of-type {
            max-width: 450px;
            text-align: center;
        }

        #modalView textarea {
            display: block !important;
            width: 100% !important;
            max-width: 450px;
            height: 60vh !important;
            background: #0f1114 !important;
            color: #fff !important;
            border: 1px solid var(--border-color) !important;
            border-radius: 8px !important;
            padding: 15px !important;
            box-sizing: border-box !important;
            font-family: monospace !important;
            font-size: 13px !important;
            resize: none !important;
            margin-top: 15px !important;
        }

        #modalView div:last-of-type {
            max-width: 450px;
        }

        @media (max-width: 768px) {
            .menu-toggle { display: block; margin-right: 15px; }
            .sidebar { position: fixed; left: -260px; height: 100%; box-shadow: 10px 0 20px rgba(0,0,0,0.5); }
            .sidebar.active { left: 0; }
            .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; }
            .filter-bar { flex-direction: column; align-items: stretch; }
            #bulkActionsBar { flex-direction: column; align-items: stretch; }
            .grid-view-container { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>

    <div class="sidebar-overlay" id="overlay" onclick="toggleMenu()"></div>
    
    <?php include 'sidebar.php'; ?>

    <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>
            <div class="topbar-right">
                <button type="button" class="mode-badge-interactive" onclick="mudarModoDash()">
                    <i class="fas fa-server"></i> <span id="label_modo_ativo"><?php echo strtoupper($modo_ativo); ?></span>
                </button>
            </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="width: 100%; margin-top: 5px; margin-bottom: 5px;">
                        <button type="button" id="btnToggleView" class="btn-toggle-view" onclick="toggleViewMode()">
                            <i class="fas fa-list"></i> Modo de Visualização
                        </button>
                    </div>

                    <div style="margin-left: auto; display:flex; gap:10px; flex-wrap:wrap; width: 100%; justify-content: flex-end;">
                        <?php if($role === 'admin'): ?>
                        <button type="button" class="btn-main" style="background:#f39c12;" onclick="openModal('modalConfigTestTime')"><i class="fas fa-cogs"></i> Configurações de Teste</button>
                        <?php endif; ?>
                        
                        <?php if($role === 'admin' || $permitir_teste_revenda == 1): ?>
                        <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>
                        <?php endif; ?>
                    </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" id="tableViewContainer">
                <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>Cliente</th>
                            <th>Usuário</th>
                            <th>Senha</th>
                            <th>WhatsApp</th>
                            <th>Criado por</th>
                            <th>Telas (Uso)</th>
                            <th>Vencimento</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($testes)): ?>
                            <tr><td colspan="9" 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');
                            
                            $active_cons = 0;
                            try {
                                $stmtAct = $pdo->prepare("SELECT COUNT(*) FROM user_activity_now WHERE user_id = ?");
                                $stmtAct->execute([$t['id']]);
                                $active_cons = $stmtAct->fetchColumn();
                            } catch (Exception $e) {}
                        ?>
                            <tr>
                                <td style="text-align: center;">
                                    <input type="checkbox" class="user-checkbox table-checkbox" value="<?php echo $t['id']; ?>" onchange="syncCheckboxes(this)" style="cursor:pointer; width:16px; height:16px; accent-color: var(--accent);">
                                </td>
                                <td>
                                    <?php if(!empty($t['nome_cliente'])): ?>
                                        <span style="font-size:14px; font-weight:bold; color:var(--text-main);"><i class="fas fa-user" style="color:var(--text-muted); margin-right:5px;"></i> <?php echo htmlspecialchars($t['nome_cliente']); ?></span>
                                    <?php else: ?>
                                        <span style="color:var(--text-muted); font-size:12px;">---</span>
                                    <?php endif; ?>
                                </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>
                                    <?php if(!empty($t['whatsapp'])): ?>
                                        <span style="font-size:13px; color:var(--text-main);"><i class="fab fa-whatsapp" style="color:#25d366; margin-right:5px;"></i> <?php echo htmlspecialchars($t['whatsapp']); ?></span>
                                    <?php else: ?>
                                        <span style="color:var(--text-muted); font-size:12px;">---</span>
                                    <?php endif; ?>
                                </td>
                                <td><span class="badge" style="background: rgba(0, 123, 255, 0.1); color: var(--accent);"><?php echo htmlspecialchars($revendedores_map[$t['member_id']] ?? 'Admin'); ?></span></td>
                                <td>
                                    <span class="badge" style="background: rgba(255,255,255,0.05); color: white; font-size: 11px; border: 1px solid var(--border-color); padding: 5px 8px; white-space: nowrap;">
                                        <i class="fas fa-plug" style="color: <?php echo $active_cons > 0 ? 'var(--success)' : 'var(--text-muted)'; ?>;"></i> <?php echo $active_cons; ?> / <?php echo $t['max_connections']; ?>
                                    </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']); ?>
                                    
                                    <div style="display: flex; gap: 8px; flex-wrap: nowrap; min-width: max-content;">
                                        <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>
                                        
                                        <button type="button" class="btn-action" style="background:#34495e;" title="Download Playlist" onclick="openM3uModal('<?php echo htmlspecialchars($t['username'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($t['password'], ENT_QUOTES); ?>')"><i class="fas fa-download"></i></button>

                                        <button type="button" class="btn-action" style="background:var(--accent);" title="Editar Teste" onclick='openEditTestModal(<?php echo json_encode([
                                            "id" => $t["id"],
                                            "nome" => $t["nome_cliente"] ?? "",
                                            "username" => $t["username"],
                                            "password" => $t["password"],
                                            "whatsapp" => $t["whatsapp"] ?? "",
                                            "telas" => $t["max_connections"],
                                            "bouquet" => $t["bouquet"] ?? "[]",
                                            "is_restreamer" => $t["is_restreamer"] ?? 0,
                                            "force_server_id" => $t["force_server_id"] ?? 0,
                                            "allowed_ips" => isset($t["allowed_ips"]) && $t["allowed_ips"] !== "[]" && $t["allowed_ips"] !== "null" ? implode(", ", json_decode($t["allowed_ips"], true) ?: []) : "",
                                            "allowed_ua" => isset($t["allowed_ua"]) && $t["allowed_ua"] !== "[]" && $t["allowed_ua"] !== "null" ? implode(", ", json_decode($t["allowed_ua"], true) ?: []) : ""
                                        ], JSON_HEX_APOS | JSON_HEX_QUOT); ?>)'><i class="fas fa-edit"></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. Ele receberá o aviso de renovação no WhatsApp.')"><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>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>

            <div class="grid-view-container" id="gridViewContainer">
                <?php if(empty($testes)): ?>
                    <div style="text-align:center; padding: 20px; width: 100%; color: var(--text-muted);">Nenhum teste encontrado.</div>
                <?php else: foreach ($testes as $t): 
                    $vencido = ($t['exp_date'] < time() && $t['exp_date'] != 0);
                    $badge_class = $t['enabled'] == 0 ? 'bloqueado' : ($vencido ? 'vencido' : 'ativo');
                    $badge_text = $t['enabled'] == 0 ? 'BLOQUEADO' : ($vencido ? 'VENCIDO' : 'ATIVO');
                    
                    $active_cons = 0;
                    try {
                        $stmtAct = $pdo->prepare("SELECT COUNT(*) FROM user_activity_now WHERE user_id = ?");
                        $stmtAct->execute([$t['id']]);
                        $active_cons = $stmtAct->fetchColumn();
                    } catch (Exception $e) {}
                    
                    $msgInfo = gerarDadosAcessoCompleto($t['username'], $t['password'], $t['whatsapp'], $t['exp_date'], $t['max_connections']);
                ?>
                <div class="client-card">
                    <div class="checkbox-container">
                        <input type="checkbox" class="user-checkbox grid-checkbox" value="<?php echo $t['id']; ?>" onchange="syncCheckboxes(this)" style="cursor:pointer; width:18px; height:18px; accent-color: var(--accent);">
                    </div>
                    
                    <div class="card-header-top">
                        <div class="card-user-info">
                            <span class="card-username"><?php echo htmlspecialchars($t['username']); ?></span>
                            <?php if(!empty($t['nome_cliente'])): ?>
                                <span class="card-client-name"><?php echo htmlspecialchars($t['nome_cliente']); ?></span>
                            <?php else: ?>
                                <span class="card-client-name" style="visibility:hidden;">-</span>
                            <?php endif; ?>
                            
                            <div class="card-status-badges">
                                <span class="badge <?php echo $badge_class; ?>"><?php echo $badge_text; ?></span>
                                <span class="badge iptv">IPTV</span>
                                <span class="badge teste">TESTE</span>
                            </div>
                        </div>
                    </div>

                    <div class="card-details-grid">
                        <div class="detail-item">
                            <span class="detail-label">Vencimento</span>
                            <span class="detail-value text-warning"><?php echo $t['exp_date'] ? date('d/m/Y, H:i', $t['exp_date']) : 'Ilimitado'; ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">Criado em</span>
                            <span class="detail-value"><?php echo $t['created_at'] ? date('d/m/Y, H:i:s', $t['created_at']) : '---'; ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">Dono</span>
                            <span class="detail-value text-muted" style="font-weight: normal;"><?php echo $role === 'admin' ? ($t['member_id'] == $user_id_logado ? 'Admin' : htmlspecialchars($revendedores_map[$t['member_id']] ?? 'Desconhecido')) : 'Você'; ?></span>
                        </div>
                        <div class="detail-item" style="grid-column: span 2; display: flex; flex-direction: row; justify-content: space-between; align-items: center; border-top: 1px solid rgba(255,255,255,0.05); padding-top: 5px; margin-top: 5px;">
                            <span class="detail-label" style="margin-bottom: 0;">Conexões: <?php echo $active_cons; ?> / <?php echo $t['max_connections']; ?></span>
                            <span style="color: <?php echo $active_cons > 0 ? 'var(--success)' : 'var(--text-muted)'; ?>; font-size: 14px;"><i class="fas fa-eye"></i></span>
                        </div>
                    </div>

                    <div class="card-actions-grid">
                        <button type="button" class="card-btn-action cb-action-edit" onclick='openEditTestModal(<?php echo json_encode([
                            "id" => $t["id"],
                            "nome" => $t["nome_cliente"] ?? "",
                            "username" => $t["username"],
                            "password" => $t["password"],
                            "whatsapp" => $t["whatsapp"] ?? "",
                            "telas" => $t["max_connections"],
                            "bouquet" => $t["bouquet"] ?? "[]",
                            "is_restreamer" => $t["is_restreamer"] ?? 0,
                            "force_server_id" => $t["force_server_id"] ?? 0,
                            "allowed_ips" => isset($t["allowed_ips"]) && $t["allowed_ips"] !== "[]" && $t["allowed_ips"] !== "null" ? implode(", ", json_decode($t["allowed_ips"], true) ?: []) : "",
                            "allowed_ua" => isset($t["allowed_ua"]) && $t["allowed_ua"] !== "[]" && $t["allowed_ua"] !== "null" ? implode(", ", json_decode($t["allowed_ua"], true) ?: []) : ""
                        ], JSON_HEX_APOS | JSON_HEX_QUOT); ?>)'>
                            <i class="fas fa-pen"></i><span>Editar</span>
                        </button>
                        
                        <button type="button" class="card-btn-action cb-action-playlist" onclick="openM3uModal('<?php echo htmlspecialchars($t['username'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($t['password'], ENT_QUOTES); ?>')">
                            <i class="fas fa-tv"></i><span>Playlist</span>
                        </button>
                        
                        <a href="?renew_test=<?php echo $t['id']; ?>" class="card-btn-action cb-action-renew" 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. Ele receberá o aviso de renovação no WhatsApp.')">
                            <i class="fas fa-calendar-alt"></i><span>Ativar</span>
                        </a>
                        
                        <button type="button" class="card-btn-action cb-action-url" 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-link"></i><span>Acesso</span>
                        </button>
                    </div>
                </div>
                <?php endforeach; endif; ?>
            </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="modalM3U" class="modal">
        <div class="modal-content">
            <h3 style="margin-top:0; color:white;"><i class="fas fa-list"></i> Download Playlist</h3>
            <p style="color:var(--text-muted); font-size:12px;">Selecione o formato para baixar a lista deste cliente.</p>
            <div class="form-group-modal">
                <select id="m3u_format" onchange="updateM3uLink()" style="background:#1e2227; font-weight:bold;">
                    <option value="m3u_plus_mpegts">m3u With Options - MPEGTS</option>
                    <option value="m3u_plus_hls">m3u With Options - HLS</option>
                    <option value="simple_mpegts">Simple List - MPEGTS</option>
                    <option value="simple_hls">Simple List - HLS</option>
                </select>
            </div>
            <div class="form-group-modal" style="display:flex; gap:5px;">
                <input type="text" id="m3u_link_input" readonly style="flex:1; background:#000;">
                <button type="button" class="btn-action" style="background:#f39c12; margin:0;" onclick="copyM3u()" title="Copiar"><i class="fas fa-copy"></i></button>
                <button type="button" class="btn-action" style="background:var(--info); margin:0;" onclick="downloadM3u()" title="Baixar"><i class="fas fa-download"></i></button>
            </div>
            <button type="button" onclick="closeAllModals()" style="width:100%; background:none; border:none; color:var(--text-muted); margin-top:10px; margin-bottom:20px; cursor:pointer;">Fechar</button>
        </div>
    </div>

    <div id="modalClient" class="modal">
        </div>

    <div id="modalEditTest" class="modal">
        <div class="modal-content"><h3 style="margin-top:0; color:white;"><i class="fas fa-edit"></i> Editar Teste</h3>
            <form method="POST">
                <input type="hidden" name="action_edit_test" value="1">
                <input type="hidden" name="edit_id" id="edit_id">
                
                <div class="form-group-modal"><label>Nome do Cliente (Opcional)</label><input type="text" name="nome_cliente" id="edit_nome_cliente" placeholder="Ex: João Silva"></div>
                <div class="form-group-modal"><label>Usuário</label><input type="text" name="username" id="edit_username" required></div>
                <div class="form-group-modal"><label>Senha</label><input type="text" name="password" id="edit_password" required></div>
                <div class="form-group-modal"><label>WhatsApp</label><input type="text" name="whatsapp" id="edit_whatsapp" placeholder="Ex: 5511999999999"></div>
                
                <?php if($role === 'admin'): ?>
                <div class="form-group-modal">
                    <label>Forced Connection (Servidor Principal)</label>
                    <select name="force_server_id" id="edit_force_server_id">
                        <option value="0">Desativado (Disabled)</option>
                        <option value="1">Servidor Principal (Main Server)</option>
                    </select>
                </div>

                <div class="form-group-modal" style="margin-top:15px; margin-bottom:15px;">
                    <label style="display:flex; align-items:center; gap:10px; color:var(--success); font-size:14px; cursor:pointer; font-weight:bold;">
                        <input type="checkbox" name="is_restreamer" id="edit_is_restreamer" value="1" style="width:20px; height:20px; margin:0; accent-color: var(--success);"> 
                        Ativar Restreamer (Permitir acesso total à lista M3U)
                    </label>
                </div>
                
                <div style="display: flex; gap: 10px;">
                    <div class="form-group-modal" style="flex: 1;">
                        <label>IPs Permitidos (Opcional, vírgula)</label>
                        <input type="text" name="allowed_ips" id="edit_allowed_ips" placeholder="Ex: 192.168.1.1">
                    </div>
                    
                    <div class="form-group-modal" style="flex: 1;">
                        <label>User-Agents (Opcional, vírgula)</label>
                        <input type="text" name="allowed_ua" id="edit_allowed_ua" placeholder="Ex: VLC, Kodi">
                    </div>
                </div>
                <?php endif; ?>

                <div class="form-group-modal"><label>Quantidade de Telas (Conexões)</label><input type="number" name="max_connections" id="edit_max_connections" min="1"></div>
                
                <div class="form-group-modal">
                    <label>Pacote(s) Liberado(s)</label>
                    <div class="bouquet-grid">
                        <?php foreach($bouquets_lista as $bq): ?>
                            <label class="bouquet-item">
                                <input type="checkbox" name="user_bouquets[]" value="<?php echo $bq['id']; ?>" class="bq-check edit-bq-check"> 
                                <?php echo htmlspecialchars($bq['bouquet_name']); ?>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <button type="submit" class="btn-save-modal">SALVAR ALTERAÇÕES</button>
                <button type="button" onclick="closeAllModals()" style="width:100%; background:none; border:none; color:var(--text-muted); margin-top:15px; margin-bottom:20px; cursor:pointer;">Cancelar</button>
            </form>
        </div>
    </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; margin-bottom:20px; 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>Nome do Cliente (Opcional)</label><input type="text" name="nome_cliente" placeholder="Ex: João Silva"></div>
                <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" placeholder="Ex: 5511999999999"></div>
                
                <?php if($role === 'admin'): ?>
                <div class="form-group-modal">
                    <label>Forced Connection (Servidor Principal)</label>
                    <select name="force_server_id">
                        <option value="0">Desativado (Disabled)</option>
                        <option value="1" selected>Servidor Principal (Main Server)</option>
                    </select>
                </div>

                <div class="form-group-modal" style="margin-top:15px; margin-bottom:15px;">
                    <label style="display:flex; align-items:center; gap:10px; color:var(--success); font-size:14px; cursor:pointer; font-weight:bold;">
                        <input type="checkbox" name="is_restreamer" value="1" style="width:20px; height:20px; margin:0; accent-color: var(--success);"> 
                        Ativar Restreamer (Permitir acesso total à lista M3U)
                    </label>
                </div>
                
                <div style="display: flex; gap: 10px;">
                    <div class="form-group-modal" style="flex: 1;">
                        <label>IPs Permitidos (Opcional, vírgula)</label>
                        <input type="text" name="allowed_ips" placeholder="Ex: 192.168.1.1">
                    </div>
                    
                    <div class="form-group-modal" style="flex: 1;">
                        <label>User-Agents (Opcional, vírgula)</label>
                        <input type="text" name="allowed_ua" placeholder="Ex: VLC, Kodi">
                    </div>
                </div>
                <?php endif; ?>

                <div class="form-group-modal"><label>Quantidade de Telas (Conexões)</label><input type="number" name="max_connections" value="1" min="1"></div>
                
                <div class="form-group-modal">
                    <label>Pacote(s) Liberado(s)</label>
                    <div class="bouquet-grid">
                        <?php foreach($bouquets_lista as $bq): ?>
                            <label class="bouquet-item">
                                <input type="checkbox" name="user_bouquets[]" value="<?php echo $bq['id']; ?>" class="bq-check"> 
                                <?php echo htmlspecialchars($bq['bouquet_name']); ?>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </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; margin-bottom:20px; cursor:pointer;">Cancelar</button>
            </form>
        </div>
    </div>

    <?php if ($role === 'admin'): ?>
    <div id="modalConfigTestTime" class="modal">
        <div class="modal-content">
            <h3 style="margin-top:0; color:white;"><i class="fas fa-cogs" style="color:#f39c12;"></i> Configurações de Teste</h3>
            <form method="POST">
                <input type="hidden" name="action_config_test_time" value="1">
                
                <div class="form-group-modal">
                    <label>Duração dos Testes (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>
                
                <div class="form-group-modal" style="margin-top:20px; margin-bottom:20px;">
                    <label style="display:flex; align-items:center; gap:10px; color:var(--text-main); font-size:14px; cursor:pointer;">
                        <input type="checkbox" name="permitir_teste_revenda" value="1" <?php echo $permitir_teste_revenda == 1 ? 'checked' : ''; ?> style="width:20px; height:20px; margin:0; accent-color: var(--success);"> 
                        Permitir que Revendedores criem testes
                    </label>
                    
                    <div style="background: rgba(23, 162, 184, 0.1); border-left: 3px solid #17a2b8; padding: 12px; margin-top: 12px; border-radius: 4px; color: var(--text-muted); font-size: 12px; line-height: 1.5;">
                        <strong style="color: #17a2b8;"><i class="fas fa-info-circle"></i> Controle de Segurança:</strong><br>
                        • <b>Marcado:</b> Revendedores podem gerar testes livremente.<br>
                        • <b>Desmarcado:</b> A função de gerar testes é ocultada e bloqueada para todos os revendedores da sua rede (excelente para evitar congestionamento em dias de jogos).
                    </div>
                </div>

                <button type="submit" class="btn-save-modal" style="background:#f39c12;">SALVAR CONFIGURAÇÕES</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>
    <?php endif; ?>

    <div id="modalView" class="modal">
        <div class="modal-content"><h3 style="margin-top:0; color:white;"><i class="fas fa-eye"></i> Dados do Acesso</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; margin-bottom:20px; cursor:pointer;">Fechar</button>
        </div>
    </div>

    <script>
        function mudarModoDash() {
            let modos = ['interno', 'externo', 'xui'];
            let atual = '<?php echo $modo_ativo; ?>';
            let index = modos.indexOf(atual);
            let novo = modos[(index + 1) % modos.length];

            const formData = new FormData();
            formData.append('action_change_mode', '1');
            formData.append('novo_modo', novo);

            fetch(window.location.href, { method: 'POST', body: formData })
            .then(res => res.json())
            .then(data => {
                if(data.sucesso) {
                    document.getElementById('label_modo_ativo').innerText = data.modo;
                    location.reload(); 
                }
            });
        }

        document.addEventListener('DOMContentLoaded', () => {
            let savedMode = localStorage.getItem('viewModeTestes') || 'table';
            setViewMode(savedMode);
        });

        function toggleViewMode() {
            let currentMode = localStorage.getItem('viewModeTestes') || 'table';
            let newMode = currentMode === 'table' ? 'grid' : 'table';
            setViewMode(newMode);
        }

        function setViewMode(mode) {
            const tableView = document.getElementById('tableViewContainer');
            const gridView = document.getElementById('gridViewContainer');
            const btnToggle = document.getElementById('btnToggleView');
            
            if (mode === 'grid') {
                tableView.style.display = 'none';
                gridView.style.display = 'grid';
                btnToggle.innerHTML = '<i class="fas fa-th-large"></i> Modo de Visualização';
                btnToggle.classList.add('active');
            } else {
                tableView.style.display = 'block';
                gridView.style.display = 'none';
                btnToggle.innerHTML = '<i class="fas fa-list"></i> Modo de Visualização';
                btnToggle.classList.remove('active');
            }
            
            localStorage.setItem('viewModeTestes', mode);
        }

        function syncCheckboxes(source) {
            let val = source.value;
            let checked = source.checked;
            let checkboxes = document.querySelectorAll('.user-checkbox[value="' + val + '"]');
            checkboxes.forEach(cb => { cb.checked = checked; });
            toggleBulkActions();
        }

        let currentM3uUser = '';
        let currentM3uPass = '';
        let baseUrlStreaming = '<?php echo $url_streaming_global; ?>';

        function openEditTestModal(data) {
            document.getElementById('edit_id').value = data.id;
            document.getElementById('edit_nome_cliente').value = data.nome || '';
            document.getElementById('edit_username').value = data.username || '';
            document.getElementById('edit_password').value = data.password || '';
            document.getElementById('edit_whatsapp').value = data.whatsapp || '';
            document.getElementById('edit_max_connections').value = data.telas || 1;
            
            <?php if($role === 'admin'): ?>
            document.getElementById('edit_force_server_id').value = data.force_server_id || 0;
            document.getElementById('edit_is_restreamer').checked = (data.is_restreamer == 1);
            document.getElementById('edit_allowed_ips').value = data.allowed_ips || '';
            document.getElementById('edit_allowed_ua').value = data.allowed_ua || '';
            <?php endif; ?>

            let bouquets = [];
            try {
                if (data.bouquet && data.bouquet !== 'null' && data.bouquet !== '') {
                    bouquets = JSON.parse(data.bouquet);
                    if (!Array.isArray(bouquets)) {
                        bouquets = [bouquets];
                    }
                }
            } catch(e) {}
            
            let checkboxes = document.querySelectorAll('.edit-bq-check');
            checkboxes.forEach(cb => {
                cb.checked = bouquets.includes(cb.value) || bouquets.includes(parseInt(cb.value));
            });

            openModal('modalEditTest');
        }

        function openConfigTestModal() {
            document.getElementById('modalConfigTestTime').style.display = 'flex';
        }

        function openM3uModal(user, pass) {
            currentM3uUser = user;
            currentM3uPass = pass;
            document.getElementById('m3u_format').value = 'm3u_plus_mpegts';
            updateM3uLink();
            openModal('modalM3U');
        }

        function updateM3uLink() {
            let format = document.getElementById('m3u_format').value;
            let link = '';
            if(format === 'm3u_plus_mpegts') {
                link = baseUrlStreaming + '/get.php?username=' + currentM3uUser + '&password=' + currentM3uPass + '&type=m3u_plus&output=mpegts';
            } else if(format === 'm3u_plus_hls') {
                link = baseUrlStreaming + '/get.php?username=' + currentM3uUser + '&password=' + currentM3uPass + '&type=m3u_plus&output=hls';
            } else if(format === 'simple_mpegts') {
                link = baseUrlStreaming + '/get.php?username=' + currentM3uUser + '&password=' + currentM3uPass + '&type=m3u&output=mpegts';
            } else if(format === 'simple_hls') {
                link = baseUrlStreaming + '/get.php?username=' + currentM3uUser + '&password=' + currentM3uPass + '&type=m3u&output=hls';
            }
            document.getElementById('m3u_link_input').value = link;
        }

        function downloadM3u() {
            let link = document.getElementById('m3u_link_input').value;
            window.open(link, '_blank');
        }

        function copyM3u() {
            let link = document.getElementById('m3u_link_input').value;
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(link).then(() => alert('Link da Playlist copiado!'));
            } else {
                let tempInput = document.createElement("input");
                tempInput.value = link;
                document.body.appendChild(tempInput);
                tempInput.select();
                document.execCommand("copy");
                document.body.removeChild(tempInput);
                alert('Link da Playlist copiado!');
            }
        }

        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 uniqueIds = new Set();
            checkboxes.forEach(cb => uniqueIds.add(cb.value));

            var bar = document.getElementById('bulkActionsBar'); 
            var countSpan = document.getElementById('selectedCount'); 
            if (uniqueIds.size > 0) { 
                countSpan.innerText = uniqueIds.size; 
                bar.style.display = 'flex'; 
            } else { 
                bar.style.display = 'none'; 
                var sa = document.getElementById('selectAll');
                if(sa) sa.checked = false; 
            } 
        }
        function getSelectedIds() { 
            var checkboxes = document.querySelectorAll('.user-checkbox:checked'); 
            var uniqueIds = new Set();
            checkboxes.forEach(cb => uniqueIds.add(cb.value));
            return Array.from(uniqueIds).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(); }
        
        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');
                    
                    <?php if(isset($_SESSION['auto_zap_url'])): ?>
                        window.location.href = '<?php echo $_SESSION['auto_zap_url']; ?>';
                        <?php unset($_SESSION['auto_zap_url']); ?>
                    <?php endif; ?>

                    var xhr = new XMLHttpRequest(); xhr.open('GET', '?clear_msg=1', true); xhr.send();
                } catch(e) {}
            };
        <?php endif; ?>
        
        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); 
            } catch(e) {} 
        }, 4000);
    </script>
</body>
</html>
