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

// Limpa a sessão do comprovante APENAS quando o usuário clica no "X"
if (isset($_GET['clear_msg'])) {
    unset($_SESSION['comprovante']);
    exit;
}

$pdo = getConexaoAtiva();
$pdo_int = getConexaoInterna(); // Conexão separada garantida para saldos, logs e revendedores locais

// 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 "Usuário já existe" ao criar o cliente!
// ====================================================================
$pdo->exec("SET SESSION sql_mode = ''");

// Validação de sessão movida para cima para podermos buscar o perfil do usuário logado
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }
$my_id = $_SESSION['user_id'];
$nome_usuario = $_SESSION['username'] ?? 'Usuário';
$mensagem = "";

// ====================================================================
// INTELIGÊNCIA ARTIFICIAL: DETECTA SE É XUI ONE OU XTREAM UI
// ====================================================================
$modo_ativo = 'interno';
try {
    $modo_ativo = $pdo_int->query("SELECT modo_ativo FROM configuracoes LIMIT 1")->fetchColumn() ?: 'interno';
} catch (Exception $e) {}

$tabela_clientes = ($modo_ativo === 'xui') ? '`lines`' : '`users`';
$col_whatsapp = ($modo_ativo === 'xui') ? 'phone' : 'whatsapp';
$col_nome = ($modo_ativo === 'xui') ? 'admin_notes' : 'nome_cliente';

// FILTRO CIRÚRGICO: Oculta clientes P2P da área de IPTV usando a senha universal
$cond_p2p = "u.password != 'topiptv1724'";
$tabela_revendedores = ($modo_ativo === 'xui') ? '`users`' : '`reg_users`';

// ====================================================================
// TRAVA DE SEGURANÇA ABSOLUTA - CHECAGEM DE PERFIL E SALDO EM TEMPO REAL
// ====================================================================
try {
    $stmtRole = $pdo->prepare("SELECT member_group_id, credits FROM $tabela_revendedores WHERE id = ?");
    $stmtRole->execute([$my_id]);
    $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;
}

// --- INÍCIO: BUSCA DE PERSONALIZAÇÃO E API WHATSAPP MULTI-REVENDEDOR ---
$nome_painel = 'TOP IPTV'; $logo_url = ''; $cor_primaria = '#007bff';
$wa_url = ''; $wa_key = ''; $wa_inst = ''; $wa_status = 0;

// 1. Busca Configurações Visuais Globais (Cores/Logo)
try {
    $config_painel = $pdo_int->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($config_painel) {
        $nome_painel = $config_painel['nome_painel'] ?? $nome_painel;
        $logo_url = $config_painel['logo_url'] ?? $logo_url;
        $cor_primaria = $config_painel['cor_primaria'] ?? $cor_primaria;
        $confianca_status = $config_painel['confianca_status'] ?? 0;
        $confianca_tempo = $config_painel['confianca_tempo'] ?? 1;
    }
} catch (Exception $e) { $confianca_status = 0; $confianca_tempo = 1; }

// 2. Busca a API EXCLUSIVA do Revendedor (No banco correto)
try {
    $api_user = $pdo->prepare("SELECT wa_api_url, wa_api_key, wa_instancia, wa_status FROM $tabela_revendedores WHERE id = ?");
    $api_user->execute([$my_id]);
    $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) {}

// --- LÓGICA DE AUTO-CORREÇÃO AUTOMÁTICA ---
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"); }
        
        // CORREÇÃO: Colunas do Restreamer e Controle de Acesso (Xtream UI)
        $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ÇÃO: Colunas do Restreamer e Controle de Acesso (XUI ONE)
        $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,
        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");
    }
} catch (PDOException $e) {}

// ====================================================================
// CAPTURA DO DNS DE STREAMING GLOBAL (CORRIGIDO PARA IGNORAR O MODO)
// ====================================================================
$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; // Por padrão, usa o próprio painel

$dns_encontrado = false;

// 1. TENTA O LOAD BALANCER PRIMEIRO (INDEPENDENTE DO MODO)
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'] != '') ? ":" . $lbAtivo['porta'] : "";
        $dns_val = trim($lbAtivo['ip_servidor']) . $porta_lb;
        if (strpos($dns_val, 'http') !== 0) { $dns_val = "http://" . $dns_val; }
        $url_streaming_global = rtrim($dns_val, '/');
        $dns_encontrado = true;
    }
} catch(Exception $e){}

// 2. SE NÃO ACHOU LB, TENTA O SERVIDOR SECUNDÁRIO (Apenas se não for interno)
if (!$dns_encontrado && $modo_ativo !== 'interno') {
    try {
        $tabela_servidores = ($modo_ativo === 'xui') ? 'servers' : 'streaming_servers';
        $stmtDns = $pdo->query("SELECT * FROM $tabela_servidores ORDER BY id ASC LIMIT 1");
        $serverInfo = $stmtDns->fetch(PDO::FETCH_ASSOC);
        if ($serverInfo) {
            $dns_val = '';
            if (isset($serverInfo['domain_name']) && !empty(trim($serverInfo['domain_name']))) {
                $dns_val = trim($serverInfo['domain_name']);
            } elseif (isset($serverInfo['server_ip']) && !empty(trim($serverInfo['server_ip']))) {
                $dns_val = trim($serverInfo['server_ip']);
            }
            if (!empty($dns_val)) {
                if (strpos($dns_val, 'http') !== 0) { $dns_val = "http://" . $dns_val; }
                $url_streaming_global = rtrim($dns_val, '/');
            }
        }
    } 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 gerarMensagemAcesso($username, $password, $whatsapp, $exp_date, $telas = 1) {
    global $raw_template, $url_streaming_global; 
    
    $data_formatada = $exp_date ? date('d/m/Y', $exp_date) : 'Ilimitado';

    $link_m3u = "{$url_streaming_global}/get.php?username={$username}&password={$password}&type=m3u_plus&output=mpegts";
    $link_hls = "{$url_streaming_global}/get.php?username={$username}&password={$password}&type=m3u_plus&output=hls";
    $m3u_completo = "{$url_streaming_global}/get.php?username={$username}&password={$password}&type=m3u_plus&output=ts";

    $link_ssiptv = "{$url_streaming_global}/ssiptv.php?username={$username}&password={$password}&ssiptv=1";
    $m3u_encurtado = "{$url_streaming_global}/m3u-ts/{$username}/{$password}";
    $m3u_hls_encurtado = "{$url_streaming_global}/m3u-m3u8/{$username}/{$password}";
    $ssiptv_encurtado = "{$url_streaming_global}/ss-ts/{$username}/{$password}";
    $roku_encurtado = "{$url_streaming_global}/roku/{$username}/{$password}";

    $texto = str_replace(
        ['#username#', '#password#', '#exp_date#', '#telas#', '#url#', '#m3u_encurtado#', '#m3u_hls_encurtado#', '#ssiptv_encurtado#', '#roku_encurtado#', '#m3u_link#', '#m3u_link_hls#', '#m3u_completo#'],
        [$username, $password, $data_formatada, $telas, $url_streaming_global, $m3u_encurtado, $m3u_hls_encurtado, $ssiptv_encurtado, $roku_encurtado, $link_m3u, $link_hls, $m3u_completo],
        $raw_template
    );
    return ['msg' => $texto, 'url' => "https://api.whatsapp.com/send?phone=".preg_replace('/\D/', '', (string)$whatsapp)."&text=".urlencode($texto)];
}

function gerarMensagemRenovacao($username, $password, $whatsapp, $exp_date) {
    $data_formatada = $exp_date ? date('d/m/Y', $exp_date) : 'Ilimitado';
    $texto = "✅ *RENOVAÇÃO CONCLUÍDA*\n\nSeu acesso foi renovado com sucesso!\n\n👤 *Usuário:* {$username}\n🔑 *Senha:* {$password}\n📅 *Novo Vencimento:* {$data_formatada}\n\nObrigado pela preferência! 🚀";
    return ['msg' => $texto, 'url' => "https://api.whatsapp.com/send?phone=".preg_replace('/\D/', '', (string)$whatsapp)."&text=".urlencode($texto)];
}

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),
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/json", 
            "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($_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($my_id) : "";
        if ($type === 'delete') {
            $pdo->exec("DELETE FROM $tabela_clientes WHERE id IN ($id_list) $condicao_seguranca");
            $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Clientes excluídos em massa!</div>";
        } elseif ($type === 'block') {
            $pdo->exec("UPDATE $tabela_clientes SET enabled = IF(enabled=1, 0, 1) WHERE id IN ($id_list) $condicao_seguranca");
            $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Status dos clientes alterado!</div>";
        } 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]);
            $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Vencimento em massa aplicado!</div>";
        } elseif ($type === 'owner' && $role === 'admin') {
            $new_owner = intval($_POST['bulk_owner_id']);
            $pdo->prepare("UPDATE $tabela_clientes SET member_id = ? WHERE id IN ($id_list)")->execute([$new_owner]);
            $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Dono(s) alterado(s) com sucesso!</div>";
        }
    }
}

if (isset($_POST['action_config_trust']) && $role === 'admin') {
    $c_status = isset($_POST['confianca_status']) ? 1 : 0;
    $c_tempo = intval($_POST['confianca_tempo']);
    if ($c_tempo < 1) $c_tempo = 1;
    $pdo_int->prepare("UPDATE painel_config SET confianca_status = ?, confianca_tempo = ?")->execute([$c_status, $c_tempo]);
    $confianca_status = $c_status; $confianca_tempo = $c_tempo;
    $mensagem = "<div class='alert success'><i class='fas fa-check'></i> Sistema de confiança atualizado!</div>";
}

if (isset($_POST['action_save'])) {
    $user = $_POST['username'];
    $pass = $_POST['password'];
    $zap  = $_POST['whatsapp'] ?? '';
    $nome_cliente = $_POST['nome_cliente'] ?? '';
    $telas = isset($_POST['max_connections']) ? intval($_POST['max_connections']) : 1;
    $exp  = !empty($_POST['exp_date']) ? strtotime($_POST['exp_date']) : strtotime('+30 days');
    $id   = $_POST['user_id'] ?? null;
    $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 = '[]';
        if (!empty($id)) {
            try {
                $stmtEx = $pdo->prepare("SELECT is_restreamer, force_server_id, allowed_ips, allowed_ua FROM $tabela_clientes WHERE id = ?");
                $stmtEx->execute([$id]);
                if ($ex = $stmtEx->fetch(PDO::FETCH_ASSOC)) {
                    $is_restreamer = $ex['is_restreamer']; 
                    $force_server_id = $ex['force_server_id'];
                    $ips_json = $ex['allowed_ips']; 
                    $ua_json = $ex['allowed_ua'];
                }
            } catch(Exception $e){}
        }
    }

    try {
        if (!empty($id)) {
            if ($modo_ativo === 'xui') {
                $pdo->prepare("UPDATE `lines` SET username = ?, password = ?, phone = ?, exp_date = ?, bouquet = ?, max_connections = ?, admin_notes = ?, is_restreamer = ?, allowed_ips = ?, allowed_ua = ?, force_server_id = ? WHERE id = ?")->execute([$user, $pass, $zap, $exp, $bouquets_selecionados, $telas, $nome_cliente, $is_restreamer, $ips_json, $ua_json, $force_server_id, $id]);
            } else {
                $pdo->prepare("UPDATE users SET username = ?, password = ?, whatsapp = ?, exp_date = ?, bouquet = ?, max_connections = ?, nome_cliente = ?, is_restreamer = ?, allowed_ips = ?, allowed_ua = ?, force_server_id = ? WHERE id = ?")->execute([$user, $pass, $zap, $exp, $bouquets_selecionados, $telas, $nome_cliente, $is_restreamer, $ips_json, $ua_json, $force_server_id, $id]);
            }
            $mensagem = "<div class='alert success'>Dados atualizados com sucesso!</div>";
        } else {
            $pode_criar = true;
            
            if ($role !== 'admin') {
                $stmtCred = $pdo->prepare("SELECT credits FROM $tabela_revendedores WHERE id = ?");
                $stmtCred->execute([$my_id]);
                $revenda = $stmtCred->fetch();
                
                if (!$revenda || $revenda['credits'] < 1) {
                    $pode_criar = false;
                    $mensagem = "<div class='alert danger'><i class='fas fa-times-circle'></i> Saldo insuficiente! Você não possui créditos para criar um usuário.</div>";
                } else {
                    $pdo->prepare("UPDATE $tabela_revendedores SET credits = credits - 1 WHERE id = ?")->execute([$my_id]);
                    $user_credits -= 1; 
                }
            }

            if ($pode_criar) {
                $created_at = time();
                
                if ($modo_ativo === 'xui') {
                    $res = $pdo->prepare("INSERT INTO `lines` (username, password, bouquet, phone, exp_date, enabled, admin_enabled, member_id, max_connections, created_at, admin_notes, is_restreamer, allowed_ips, allowed_ua, force_server_id) VALUES (?, ?, ?, ?, ?, 1, 1, ?, ?, ?, ?, ?, ?, ?, ?)")->execute([$user, $pass, $bouquets_selecionados, $zap, $exp, $my_id, $telas, $created_at, $nome_cliente, $is_restreamer, $ips_json, $ua_json, $force_server_id]);
                } else {
                    $res = $pdo->prepare("INSERT INTO users (username, password, bouquet, whatsapp, exp_date, enabled, admin_enabled, member_id, is_p2p, trust_used, max_connections, created_at, nome_cliente, is_restreamer, allowed_ips, allowed_ua, force_server_id) VALUES (?, ?, ?, ?, ?, 1, 1, ?, 0, 0, ?, ?, ?, ?, ?, ?, ?)")->execute([$user, $pass, $bouquets_selecionados, $zap, $exp, $my_id, $telas, $created_at, $nome_cliente, $is_restreamer, $ips_json, $ua_json, $force_server_id]);
                }
                
                if($res) {
                    if ($role !== 'admin') {
                        $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 (?, ?, 'Criacao de Conta', 1, ?)")->execute([$my_id, $user, $agora]);
                    }
                    
                    $msgInfo = gerarMensagemAcesso($user, $pass, $zap, $exp, $telas);
                    $_SESSION['comprovante'] = $msgInfo;
                    
                    if (!empty($zap)) {
                        if ($wa_status == 1) {
                            enviarMsgZapInvisivel($zap, $msgInfo['msg']); 
                        } else {
                            $_SESSION['auto_zap_url'] = $msgInfo['url']; 
                        }
                    }
                    header("Location: clientes.php"); exit;
                }
            }
        }
    } catch (PDOException $e) { 
        $mensagem = "<div class='alert danger'><i class='fas fa-times-circle'></i> Erro ao salvar. Verifique se o usuário já existe.</div>"; 
    }
}

if (isset($_POST['action_renew'])) {
    $id_renovar = intval($_POST['renew_user_id']);
    $is_manual = (isset($_POST['renew_months']) && $_POST['renew_months'] === 'manual');
    $pode_renovar = true;

    if ($is_manual) {
        $nova_data = !empty($_POST['manual_exp_date']) ? strtotime($_POST['manual_exp_date']) : null;
        if ($nova_data) {
            if ($role !== 'admin') {
                $stmtCred = $pdo->prepare("SELECT credits FROM $tabela_revendedores WHERE id = ?"); $stmtCred->execute([$my_id]);
                $revenda = $stmtCred->fetch();
                if (!$revenda || $revenda['credits'] < 1) { 
                    $pode_renovar = false; $mensagem = "<div class='alert danger'><i class='fas fa-times-circle'></i> Saldo insuficiente!</div>"; 
                }
                else { 
                    $pdo->prepare("UPDATE $tabela_revendedores SET credits = credits - 1 WHERE id = ?")->execute([$my_id]); 
                    $user_credits -= 1;
                }
            }
            if ($pode_renovar) {
                $pdo->prepare("UPDATE $tabela_clientes SET exp_date = ?, enabled = 1, trust_used = 0 WHERE id = ?")->execute([$nova_data, $id_renovar]);
                
                if ($role !== 'admin') {
                    try {
                        $agora = date('Y-m-d H:i:s');
                        $stmtM = $pdo->prepare("SELECT username FROM $tabela_clientes WHERE id = ?"); $stmtM->execute([$id_renovar]); $uData = $stmtM->fetch();
                        $pdo_int->prepare("INSERT INTO logs_creditos (revendedor_id, cliente_user, acao, qtd_descontada, data_hora) VALUES (?, ?, 'Renovacao Manual', 1, ?)")->execute([$my_id, $uData['username'], $agora]);
                    } catch(Exception $e) {}
                }
                
                $stmtM2 = $pdo->prepare("SELECT *, $col_whatsapp as whatsapp FROM $tabela_clientes WHERE id = ?"); $stmtM2->execute([$id_renovar]); $uDataFull = $stmtM2->fetch();
                $msgInfo = gerarMensagemRenovacao($uDataFull['username'], $uDataFull['password'], $uDataFull['whatsapp'], $uDataFull['exp_date']);
                $_SESSION['comprovante'] = $msgInfo;
                
                if (!empty($uDataFull['whatsapp'])) {
                    if ($wa_status == 1) { enviarMsgZapInvisivel($uDataFull['whatsapp'], $msgInfo['msg']); } 
                    else { $_SESSION['auto_zap_url'] = $msgInfo['url']; }
                }
                header("Location: clientes.php"); exit;
            }
        }
    } else {
        $meses = intval($_POST['renew_months']);
        if ($meses < 1) $meses = 1;
        if ($role !== 'admin') {
            $stmtCred = $pdo->prepare("SELECT credits FROM $tabela_revendedores WHERE id = ?"); $stmtCred->execute([$my_id]);
            $revenda = $stmtCred->fetch();
            if (!$revenda || $revenda['credits'] < $meses) { 
                $pode_renovar = false; $mensagem = "<div class='alert danger'><i class='fas fa-times-circle'></i> Saldo insuficiente!</div>"; 
            }
            else { 
                $pdo->prepare("UPDATE $tabela_revendedores SET credits = credits - ? WHERE id = ?")->execute([$meses, $my_id]); 
                $user_credits -= $meses;
            }
        }
        if ($pode_renovar) {
            $segundos = $meses * 30 * 86400; 
            $pdo->prepare("UPDATE $tabela_clientes SET exp_date = IF(exp_date > UNIX_TIMESTAMP(), exp_date + ?, UNIX_TIMESTAMP() + ?), enabled = 1, trust_used = 0 WHERE id = ?")->execute([$segundos, $segundos, $id_renovar]);
            
            if ($role !== 'admin') {
                try {
                    $agora = date('Y-m-d H:i:s');
                    $txt_acao = 'Renovacao (' . $meses . ' Meses)';
                    $stmtM = $pdo->prepare("SELECT username FROM $tabela_clientes WHERE id = ?"); $stmtM->execute([$id_renovar]); $uData = $stmtM->fetch();
                    $pdo_int->prepare("INSERT INTO logs_creditos (revendedor_id, cliente_user, acao, qtd_descontada, data_hora) VALUES (?, ?, ?, ?, ?)")->execute([$my_id, $uData['username'], $txt_acao, $meses, $agora]);
                } catch(Exception $e) {}
            }
            
            $stmtM2 = $pdo->prepare("SELECT *, $col_whatsapp as whatsapp FROM $tabela_clientes WHERE id = ?"); $stmtM2->execute([$id_renovar]); $uDataFull = $stmtM2->fetch();
            $msgInfo = gerarMensagemRenovacao($uDataFull['username'], $uDataFull['password'], $uDataFull['whatsapp'], $uDataFull['exp_date']);
            $_SESSION['comprovante'] = $msgInfo;
            
            if (!empty($uDataFull['whatsapp'])) {
                if ($wa_status == 1) { enviarMsgZapInvisivel($uDataFull['whatsapp'], $msgInfo['msg']); } 
                else { $_SESSION['auto_zap_url'] = $msgInfo['url']; }
            }
            header("Location: clientes.php"); exit;
        }
    }
}

if (isset($_POST['action_trust_renew']) && $confianca_status == 1) {
    $id_trust = intval($_POST['trust_user_id']);
    $stmtCh = $pdo->prepare("SELECT member_id, trust_used FROM $tabela_clientes WHERE id = ?"); $stmtCh->execute([$id_trust]); $cli_trust = $stmtCh->fetch(PDO::FETCH_ASSOC);
    if ($cli_trust && ($role === 'admin' || $cli_trust['member_id'] == $my_id)) {
        if ($cli_trust['trust_used'] == 0) {
            $segundos_trust = $confianca_tempo * 86400; 
            $pdo->prepare("UPDATE $tabela_clientes SET exp_date = IF(exp_date > UNIX_TIMESTAMP(), exp_date + ?, UNIX_TIMESTAMP() + ?), enabled = 1, trust_used = 1 WHERE id = ?")->execute([$segundos_trust, $segundos_trust, $id_trust]);
            $mensagem = "<div class='alert success'>Renovação de confiança aplicada!</div>";
        } else { $mensagem = "<div class='alert danger'><i class='fas fa-times-circle'></i> Este cliente já utilizou a renovação de confiança!</div>"; }
    }
}

if (isset($_GET['block'])) { $pdo->prepare("UPDATE $tabela_clientes SET enabled = IF(enabled=1, 0, 1) WHERE id = ?")->execute([$_GET['block']]); header("Location: clientes.php"); exit; }
if (isset($_GET['delete'])) { $pdo->prepare("DELETE FROM $tabela_clientes WHERE id = ?")->execute([$_GET['delete']]); header("Location: clientes.php"); exit; }

$search   = $_GET['search'] ?? '';
$status   = $_GET['status'] ?? 'ativos'; 
$reseller = $_GET['reseller'] ?? 'todos';
$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;

$where_clause = "WHERE $cond_p2p AND (u.exp_date IS NULL OR u.created_at IS NULL OR (u.exp_date - u.created_at) > 172800)";
$params = [];

if ($role !== 'admin') { $where_clause .= " AND u.member_id = :my_id"; $params[':my_id'] = $my_id; }
elseif ($reseller !== 'todos') { $where_clause .= " AND u.member_id = :reseller_id"; $params[':reseller_id'] = $reseller; }

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

if ($status === 'ativos') { $where_clause .= " AND u.enabled = 1 AND (u.exp_date > UNIX_TIMESTAMP() OR u.exp_date IS NULL)"; }
elseif ($status === 'vencidos') { $where_clause .= " AND u.enabled = 1 AND u.exp_date < UNIX_TIMESTAMP()"; }
elseif ($status === 'bloqueados') { $where_clause .= " AND u.enabled = 0"; }

$stmt_count = $pdo->prepare("SELECT COUNT(u.id) FROM $tabela_clientes u " . $where_clause);
foreach ($params as $key => $val) { $stmt_count->bindValue($key, $val); }
$stmt_count->execute();
$total_registros = $stmt_count->fetchColumn();
$total_paginas = ceil($total_registros / $limit);

$query = "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";
$stmt = $pdo->prepare($query);
foreach ($params as $key => $val) { $stmt->bindValue($key, $val); }
$stmt->execute();
$usuarios = $stmt->fetchAll(PDO::FETCH_ASSOC);

$revendedores_map = [];
if ($role === 'admin') { 
    $revendedores = $pdo->query("SELECT id, username FROM $tabela_revendedores WHERE member_group_id != 1 ORDER BY username ASC")->fetchAll(PDO::FETCH_ASSOC); 
    foreach($revendedores as $r) { $revendedores_map[$r['id']] = $r['username']; }
}

$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>
    
    <link rel="stylesheet" href="tema.css">
    
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clientes - <?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: #6c757d; --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 { max-width: 180px; max-height: 55px; 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(255, 255, 255, 0.05); 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-category { padding: 20px 20px 8px; font-size: 11px; text-transform: uppercase; color: var(--text-muted); font-weight: bold; letter-spacing: 1px; }
        .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); }
        .submenu { display: none; background: #16191d; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 14px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 12px; }
        .rotate { transform: rotate(180deg); }
        .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); }
        .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; text-decoration: none; font-size: 13px; display: inline-flex; align-items: center; gap: 5px; transition: 0.2s;}
        .btn-main:hover { filter: brightness(1.1); }

        /* 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-track { background: rgba(0,0,0,0.2); border-radius: 10px; }
        .card-table::-webkit-scrollbar-thumb { background: var(--accent); border-radius: 10px; }
        
        table { width: 100%; border-collapse: collapse; min-width: 900px; }
        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; margin: 0; transition: 0.2s;}
        .btn-action:hover { filter: brightness(1.2); }
        .btn-action:disabled { cursor: not-allowed; opacity: 0.5; filter: grayscale(100%); }
        
        /* CAIXA DE COMPROVANTE ATUALIZADA */
        .comprovante-box { background: rgba(40, 167, 69, 0.15); border: 1px solid #2ecc71; padding: 15px; border-radius: 10px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; position: relative; flex-wrap: wrap; gap: 10px; }
        .btn-zap { background: #25d366; color: white; padding: 10px 20px; border-radius: 5px; text-decoration: none; font-weight: bold; font-size: 14px; flex: 1; text-align: center; border:none; cursor:pointer;}
        .btn-zap:hover { filter: brightness(1.1); }
        .btn-copiar-msg { background: #3a4149; color: white; padding: 10px 20px; border-radius: 5px; border: none; font-weight: bold; font-size: 14px; cursor: pointer; transition: 0.2s; flex: 1; text-align: center; }
        .btn-copiar-msg:hover { background: var(--accent); }

        /* AÇÕES EM MASSA (NO TOPO) */
        #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; transition: 0.2s; }
        .btn-bulk:hover { filter: brightness(1.2); }

        /* PAGINAÇÃO */
        .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:hover, .page-link.active { background: var(--accent); border-color: var(--accent); }
        .page-dots { color: var(--text-muted); padding: 6px 5px; }
        
        /* MODALS */
        .modal { display: none; position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); overflow-y: auto; align-items: center; justify-content: center; }
        .modal-content { background: var(--bg-card); width: 90%; max-width: 450px; margin: 5% auto; 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; transition: 0.2s;}
        .btn-month { background: #1e2227; color: white; border: 1px solid var(--border-color); padding: 8px 12px; border-radius: 5px; cursor: pointer; transition: 0.2s; font-size: 13px; font-weight: bold; text-align: center;}
        .btn-month:hover { background: var(--accent); border-color: var(--accent); }
        .btn-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; }

        .input-group-gen { display: flex; width: 100%; }
        .input-group-gen input { border-radius: 5px 0 0 5px; flex: 1; }
        .input-group-gen button { background: var(--border-color); border: none; color: var(--text-main); padding: 0 15px; border-radius: 0 5px 5px 0; cursor: pointer; transition: 0.2s; }
        .input-group-gen button:hover { background: var(--accent); color: white; }
        
        .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; transition: 0.2s; }
        .btn-bulk:hover { filter: brightness(1.2); }
  
        /* ==================================================================== */
        /* FORÇA A COR AZUL NO ADMINISTRADOR E VERDE NO SALDO */
        /* ==================================================================== */
        .user-info > div:nth-child(2), .user-info .badge { background: rgba(0, 123, 255, 0.2) !important; color: var(--accent) !important; padding: 4px 10px !important; border-radius: 4px !important; font-size: 11px !important; text-transform: uppercase !important; font-weight: bold !important; margin-top: 5px !important; margin-bottom: 5px !important; display: inline-block !important; }
        .user-info > div:nth-child(3), .user-info .credits-badge, .user-info i.fa-coins { color: var(--success) !important; font-weight: bold !important; font-size: 13px !important; display: inline-block !important; }
        .user-info > div:nth-child(3) { margin-top: 8px !important; display: block !important; }

        /* ==================================================================== */
        /* FORÇA OS ÍCONES DA SIDEBAR A FICAREM AZUIS */
        /* ==================================================================== */
        .sidebar i, .sidebar span[class*="icon"], .sidebar .fas, .sidebar .fab { color: var(--accent) !important; }
        .menu-item i:first-child { margin-right: 12px; width: 20px; text-align: center; color: var(--accent) !important; }
        .menu-item:hover, .menu-item.active { background-color: #2c3138 !important; color: white !important; border-left-color: var(--accent) !important; }
        .sidebar .active, .sidebar .menu-item.active, .sidebar li.active > a { border-left-color: var(--accent) !important; color: white !important; background: #24282d !important; }
        .sidebar a:hover, .sidebar .menu-item:hover { border-left-color: var(--accent) !important; color: white !important; background: #2c3138 !important; }

        /* ==================================================================== */
        /* ESTILOS PARA O MODO GRID (CARDS) */
        /* ==================================================================== */
        .grid-view-container {
            display: none; /* Escondido por padrão */
            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.oficial { color: #facc15; border-color: #facc15; }

        .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; }
        
        .cb-action-sync { color: var(--success); }
        .cb-action-sync:hover { background: var(--success); border-color: var(--success); }
        
        .cb-action-migrate { color: #facc15; }
        .cb-action-migrate:hover { background: #facc15; border-color: #facc15; color: black; }
        
        .cb-action-active { color: #8b5cf6; }
        .cb-action-active:hover { background: #8b5cf6; border-color: #8b5cf6; }

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

        @media (max-width: 768px) { 
            .sidebar { position: fixed; left: -260px; height: 100%; box-shadow: 10px 0 20px rgba(0,0,0,0.5); } 
            .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; } 
            .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;">Clientes IPTV</h2>
            </div>
            <div class="topbar-right"><span class="mode-badge"><i class="fas fa-database"></i> <?php echo defined('MODO_SISTEMA') ? strtoupper(MODO_SISTEMA) : strtoupper($modo_ativo); ?></span></div>
        </header>

        <div class="content-area">
            <?php 
            $comp_display = 'none'; $comp_msg = ''; $comp_url = '#';
            if(isset($_SESSION['comprovante'])) {
                $comp_display = 'flex';
                $comp_msg = htmlspecialchars($_SESSION['comprovante']['msg'], ENT_QUOTES, 'UTF-8');
                $comp_url = htmlspecialchars($_SESSION['comprovante']['url'], ENT_QUOTES, 'UTF-8');
            }
            ?>
            <div class='comprovante-box' id='comprovanteBox' style='display: <?php echo $comp_display; ?>;'>
                <button onclick='fecharComprovante()' style='position:absolute; top:8px; right:10px; background:none; border:none; color:white; cursor:pointer; font-size:18px;'><i class='fas fa-times'></i></button>
                <div style='width: 100%;'><strong style='color: white;'>Dados do Cliente</strong><br><span style='color: #d1d5da; font-size:13px;'>Copie ou envie o acesso.</span></div>
                <textarea id='textoComprovante' style='display:none;'><?php echo $comp_msg; ?></textarea>
                <div style='display:flex; gap:10px; margin-top: 10px; width: 100%; flex-wrap: wrap;'>
                    <button type='button' class='btn-copiar-msg' onclick='copiarMensagemAcesso()'><i class='fas fa-copy'></i> Copiar Mensagem</button>
                    <a href='<?php echo $comp_url; ?>' id='btnZapLink' target='_blank' class='btn-zap'><i class='fab fa-whatsapp'></i> Enviar WhatsApp</a>
                </div>
            </div>
            
            <?php echo $mensagem; ?>

            <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); ?>" placeholder="Ex: joao123" onkeyup="autoSubmitSearch()"></div>
                    <div class="filter-group">
                        <label>Status</label>
                        <select name="status" onchange="this.form.submit()">
                            <option value="todos" <?php echo $status=='todos'?'selected':'';?>>Todos</option>
                            <option value="ativos" <?php echo $status=='ativos'?'selected':'';?>>Ativos</option>
                            <option value="vencidos" <?php echo $status=='vencidos'?'selected':'';?>>Vencidos</option>
                            <option value="bloqueados" <?php echo $status=='bloqueados'?'selected':'';?>>Bloqueados</option>
                        </select>
                    </div>
                    <div class="filter-group"><label>Exibir</label><select name="limit" onchange="this.form.submit()"><?php foreach([10, 20, 50, 100, 250, 500, 1000, 2000, 3000] as $l): ?><option value="<?php echo $l; ?>" <?php echo $limit == $l ? 'selected' : ''; ?>><?php echo $l; ?></option><?php endforeach; ?></select></div>
                    <?php if($role === 'admin'): ?><div class="filter-group"><label>Revendedor</label><select name="reseller" onchange="this.form.submit()"><option value="todos">Todos</option><option value="<?php echo $my_id; ?>" <?php echo $reseller==$my_id?'selected':'';?>>Meus Clientes</option><?php foreach($revendedores as $rev): ?><option value="<?php echo $rev['id']; ?>" <?php echo $reseller==$rev['id']?'selected':'';?>><?php echo htmlspecialchars($rev['username']); ?></option><?php endforeach; ?></select></div><?php endif; ?>
                    
                    <div style="margin-left: auto; display:flex; gap:10px; flex-wrap:wrap; width: 100%; justify-content: flex-end; margin-top: 10px;">
                        <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="display:flex; gap:10px; flex-wrap:wrap; width: 100%; justify-content: flex-end; margin-top: 10px;">
                        <?php if($role === 'admin'): ?><button type="button" class="btn-filter" style="background:#f39c12;" onclick="openModal('modalConfigTrust'); return false;"><i class="fas fa-handshake"></i> Sistema de Confiança</button><?php endif; ?>
                        <button type="button" class="btn-filter" style="background:var(--success);" onclick="openAddModal(); return false;"><i class="fas fa-user-plus"></i> Novo Cliente</button>
                    </div>
                </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>
                    <?php if($role === 'admin'): ?>
                    <button type="button" onclick="openModal('modalBulkOwner')" class="btn-bulk" style="background:#8b5cf6;"><i class="fas fa-user-tie"></i> Mudar Dono</button>
                    <?php endif; ?>
                    <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>
                            <?php if($role === 'admin') echo "<th>Dono</th>"; ?>
                            <th>Telas (Uso)</th>
                            <th>Vencimento</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($usuarios)): ?><tr><td colspan="9" style="text-align:center;">Nenhum cliente encontrado.</td></tr>
                        <?php else: foreach ($usuarios as $u): 
                            $vencido = ($u['exp_date'] < time() && $u['exp_date'] != 0);
                            $badge_class = $u['enabled'] == 0 ? 'bg-danger' : ($vencido ? 'bg-danger' : 'bg-success');
                            $badge_text = $u['enabled'] == 0 ? 'BLOQUEADO' : ($vencido ? 'VENCIDO' : 'ATIVO');
                            
                            $ips_decoded = json_decode($u['allowed_ips'] ?? '[]', true);
                            $ips_str = is_array($ips_decoded) ? implode(', ', $ips_decoded) : '';
                            $uas_decoded = json_decode($u['allowed_ua'] ?? '[]', true);
                            $uas_str = is_array($uas_decoded) ? implode(', ', $uas_decoded) : '';

                            // Busca Conexões Ativas no Servidor Original
                            $active_cons = 0;
                            try {
                                $stmtAct = $pdo->prepare("SELECT COUNT(*) FROM user_activity_now WHERE user_id = ?");
                                $stmtAct->execute([$u['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 $u['id']; ?>" onchange="syncCheckboxes(this)" style="cursor:pointer; width:16px; height:16px; accent-color: var(--accent);"></td>
                                <td>
                                    <?php if(!empty($u['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($u['nome_cliente']); ?></span>
                                    <?php else: ?>
                                        <span style="color:var(--text-muted); font-size:12px;">---</span>
                                    <?php endif; ?>
                                </td>
                                <td><strong><?php echo htmlspecialchars($u['username']); ?></strong><br><span class="badge <?php echo $badge_class; ?>"><?php echo $badge_text; ?></span></td>
                                <td style="color:var(--text-muted);"><?php echo htmlspecialchars($u['password']); ?></td>
                                <td><?php if(!empty($u['whatsapp'])): ?><a href="https://wa.me/<?php echo preg_replace('/\D/', '', $u['whatsapp']); ?>" target="_blank" style="color:#25d366; text-decoration:none;"><i class="fab fa-whatsapp"></i> <?php echo htmlspecialchars($u['whatsapp']); ?></a><?php else: echo "<span style='color:var(--text-muted);'>---</span>"; endif; ?></td>
                                <?php if($role === 'admin'): ?><td style="color:var(--text-muted); font-size:12px;"><?php echo $u['member_id'] == $my_id ? 'Admin' : htmlspecialchars($revendedores_map[$u['member_id']] ?? 'Desconhecido'); ?></td><?php endif; ?>
                                <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 $u['max_connections']; ?>
                                    </span>
                                </td>
                                <td><?php echo $u['exp_date'] ? date('d/m/Y H:i', $u['exp_date']) : 'Ilimitado'; ?></td>
                                <td>
                                    <?php $msgInfo = gerarMensagemAcesso($u['username'], $u['password'], $u['whatsapp'], $u['exp_date'], $u['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($u['username'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($u['password'], ENT_QUOTES); ?>')"><i class="fas fa-download"></i></button>

                                        <button type="button" class="btn-action" style="background:var(--accent);" data-id="<?php echo $u['id']; ?>" data-nome="<?php echo htmlspecialchars($u['nome_cliente'] ?? '', ENT_QUOTES); ?>" data-user="<?php echo htmlspecialchars($u['username'], ENT_QUOTES); ?>" data-pass="<?php echo htmlspecialchars($u['password'], ENT_QUOTES); ?>" data-zap="<?php echo htmlspecialchars($u['whatsapp'], ENT_QUOTES); ?>" data-telas="<?php echo $u['max_connections']; ?>" data-exp="<?php echo $u['exp_date'] ? date('Y-m-d\TH:i', $u['exp_date']) : ''; ?>" data-bq='<?php echo htmlspecialchars($u['bouquet'] ?? '[]', ENT_QUOTES); ?>' data-restreamer="<?php echo $u['is_restreamer'] ?? 0; ?>" data-ips="<?php echo htmlspecialchars($ips_str, ENT_QUOTES); ?>" data-uas="<?php echo htmlspecialchars($uas_str, ENT_QUOTES); ?>" data-forceserver="<?php echo $u['force_server_id'] ?? 0; ?>" onclick="openEditModal(this)"><i class="fas fa-edit"></i></button>
                                        
                                        <button type="button" class="btn-action" style="background:#8b5cf6;" title="Sincronizar" onclick="sincronizarCliente(<?php echo $u['id']; ?>)"><i class="fas fa-broom"></i></button>
                                        
                                        <button type="button" class="btn-action" style="background:var(--success);" onclick="openRenewModal('<?php echo $u['id']; ?>')"><i class="fas fa-sync-alt"></i></button>
                                        
                                        <?php if($confianca_status == 1 && ($u['trust_used'] ?? 0) == 0): ?>
                                        <button type="button" class="btn-action" style="background:#f39c12;" title="Renovação de Confiança (Dias Extras)" onclick="trustRenew('<?php echo $u['id']; ?>')"><i class="fas fa-handshake"></i></button>
                                        <?php endif; ?>
                                        
                                        <a href="?block=<?php echo $u['id']; ?>" class="btn-action" style="background:var(--warning);"><i class="fas <?php echo $u['enabled'] ? 'fa-ban' : 'fa-unlock'; ?>"></i></a>
                                        
                                        <a href="?delete=<?php echo $u['id']; ?>" class="btn-action" style="background:var(--danger);" onclick="return confirm('Excluir definitivamente?')"><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($usuarios)): ?>
                    <div style="text-align:center; padding: 20px; width: 100%; color: var(--text-muted);">Nenhum cliente encontrado.</div>
                <?php else: foreach ($usuarios as $u): 
                    $vencido = ($u['exp_date'] < time() && $u['exp_date'] != 0);
                    $badge_class = $u['enabled'] == 0 ? 'bloqueado' : ($vencido ? 'vencido' : 'ativo');
                    $badge_text = $u['enabled'] == 0 ? 'BLOQUEADO' : ($vencido ? 'VENCIDO' : 'ATIVO');
                    
                    $ips_decoded = json_decode($u['allowed_ips'] ?? '[]', true);
                    $ips_str = is_array($ips_decoded) ? implode(', ', $ips_decoded) : '';
                    $uas_decoded = json_decode($u['allowed_ua'] ?? '[]', true);
                    $uas_str = is_array($uas_decoded) ? implode(', ', $uas_decoded) : '';

                    $active_cons = 0;
                    try {
                        $stmtAct = $pdo->prepare("SELECT COUNT(*) FROM user_activity_now WHERE user_id = ?");
                        $stmtAct->execute([$u['id']]);
                        $active_cons = $stmtAct->fetchColumn();
                    } catch (Exception $e) {}
                    
                    $msgInfo = gerarMensagemAcesso($u['username'], $u['password'], $u['whatsapp'], $u['exp_date'], $u['max_connections']);
                ?>
                <div class="client-card">
                    <div class="checkbox-container">
                        <input type="checkbox" class="user-checkbox grid-checkbox" value="<?php echo $u['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($u['username']); ?></span>
                            <?php if(!empty($u['nome_cliente'])): ?>
                                <span class="card-client-name"><?php echo htmlspecialchars($u['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 oficial">OFICIAL</span>
                            </div>
                        </div>
                    </div>

                    <div class="card-details-grid">
                        <div class="detail-item">
                            <span class="detail-label">Vencimento</span>
                            <span class="detail-value"><?php echo $u['exp_date'] ? date('d/m/Y, H:i:s', $u['exp_date']) : 'Ilimitado'; ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">Criado em</span>
                            <span class="detail-value"><?php echo $u['created_at'] ? date('d/m/Y, H:i:s', $u['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' ? ($u['member_id'] == $my_id ? 'Admin' : htmlspecialchars($revendedores_map[$u['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 $u['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" data-id="<?php echo $u['id']; ?>" data-nome="<?php echo htmlspecialchars($u['nome_cliente'] ?? '', ENT_QUOTES); ?>" data-user="<?php echo htmlspecialchars($u['username'], ENT_QUOTES); ?>" data-pass="<?php echo htmlspecialchars($u['password'], ENT_QUOTES); ?>" data-zap="<?php echo htmlspecialchars($u['whatsapp'], ENT_QUOTES); ?>" data-telas="<?php echo $u['max_connections']; ?>" data-exp="<?php echo $u['exp_date'] ? date('Y-m-d\TH:i', $u['exp_date']) : ''; ?>" data-bq='<?php echo htmlspecialchars($u['bouquet'] ?? '[]', ENT_QUOTES); ?>' data-restreamer="<?php echo $u['is_restreamer'] ?? 0; ?>" data-ips="<?php echo htmlspecialchars($ips_str, ENT_QUOTES); ?>" data-uas="<?php echo htmlspecialchars($uas_str, ENT_QUOTES); ?>" data-forceserver="<?php echo $u['force_server_id'] ?? 0; ?>" onclick="openEditModal(this)">
                            <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($u['username'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($u['password'], ENT_QUOTES); ?>')">
                            <i class="fas fa-tv"></i><span>Playlist</span>
                        </button>
                        
                        <button type="button" class="card-btn-action cb-action-renew" onclick="openRenewModal('<?php echo $u['id']; ?>')">
                            <i class="fas fa-calendar-alt"></i><span>Renovar</span>
                        </button>
                        
                        <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>
                        
                        <button type="button" class="card-btn-action cb-action-sync" onclick="sincronizarCliente(<?php echo $u['id']; ?>)">
                            <i class="fas fa-sync-alt"></i><span>Sync</span>
                        </button>
                        
                        <a href="?block=<?php echo $u['id']; ?>" class="card-btn-action cb-action-migrate">
                            <i class="fas <?php echo $u['enabled'] ? 'fa-ban' : 'fa-unlock'; ?>"></i><span><?php echo $u['enabled'] ? 'Bloquear' : 'Desbloq.'; ?></span>
                        </a>
                        
                        <a href="?delete=<?php echo $u['id']; ?>" class="card-btn-action" style="color: var(--danger);" onclick="return confirm('Excluir definitivamente?')">
                            <i class="fas fa-trash"></i><span>Excluir</span>
                        </a>
                        
                        <?php if($confianca_status == 1 && ($u['trust_used'] ?? 0) == 0): ?>
                        <button type="button" class="card-btn-action" style="color: #f39c12;" onclick="trustRenew('<?php echo $u['id']; ?>')">
                            <i class="fas fa-handshake"></i><span>Confiança</span>
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; endif; ?>
            </div>

            <?php if ($total_paginas > 1): ?>
            <div class="pagination" style="margin-top: 20px; align-items: center; gap: 15px; justify-content: center;">
                <span style="color: var(--text-muted); font-size: 13px;">Página <?php echo $page; ?> de <?php echo $total_paginas; ?></span>
                <div>
                    <?php if ($page > 1): ?>
                        <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" class="page-link">&laquo; Anterior</a>
                    <?php endif; ?>
                    <?php if ($page < $total_paginas): ?>
                        <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" class="page-link">Próxima &raquo;</a>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
            
            <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"><input type="hidden" name="bulk_owner_id" id="bulkOwnerId"></form>
            
            <form id="trustRenewForm" method="POST" style="display:none;">
                <input type="hidden" name="action_trust_renew" value="1">
                <input type="hidden" name="trust_user_id" id="trustUserId">
            </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; cursor:pointer;">Fechar</button>
        </div>
    </div>

    <div id="modalClient" class="modal">
        <div class="modal-content">
            <h3 id="modalTitle" style="margin-top:0; color:white;"><i class="fas fa-user-plus"></i> Novo Cliente</h3>
            <form method="POST">
                <input type="hidden" name="action_save" value="1"><input type="hidden" name="user_id" id="u_id">
                
                <div class="form-group-modal">
                    <label>Nome do Cliente (Opcional)</label>
                    <input type="text" name="nome_cliente" id="u_nome" placeholder="Ex: João Silva">
                </div>

                <div class="form-group-modal">
                    <label>Usuário</label>
                    <div class="input-group-gen">
                        <input type="text" name="username" id="u_user" required>
                        <button type="button" onclick="gerarAleatorio('u_user')" title="Gerar Usuário Aleatório"><i class="fas fa-dice"></i></button>
                    </div>
                </div>
                
                <div class="form-group-modal">
                    <label>Senha</label>
                    <div class="input-group-gen">
                        <input type="text" name="password" id="u_pass" required>
                        <button type="button" onclick="gerarAleatorio('u_pass')" title="Gerar Senha Aleatória"><i class="fas fa-dice"></i></button>
                    </div>
                </div>
                
                <div class="form-group-modal"><label>WhatsApp (Opcional)</label><input type="text" name="whatsapp" id="u_zap" 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="u_force_server">
                        <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" id="u_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="u_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="u_uas" 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="u_telas" value="1" min="1"></div>
                <div class="form-group-modal"><label>Data de Vencimento</label><input type="datetime-local" name="exp_date" id="u_exp"></div>
                
                <div class="form-group-modal"><label>Pacote(s) Liberado(s)</label><div class="btn-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">SALVAR CLIENTE</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="modalRenew" class="modal">
        <div class="modal-content" style="text-align:center;"><h3 style="margin-top:0; color:white;"><i class="fas fa-sync-alt" style="color:var(--success);"></i> Renovar Conta</h3>
            <form method="POST"><input type="hidden" name="action_renew" value="1"><input type="hidden" name="renew_user_id" id="r_id"><div style="display:flex; justify-content:center; gap:10px; margin-bottom:20px; flex-wrap:wrap;"><?php foreach([1,2,3,6,12] as $m): ?><label style="cursor:pointer;"><input type="radio" name="renew_months" value="<?php echo $m; ?>" style="display:none;" onchange="updateRenewBtn(this, '<?php echo $m; ?>')"><div class="btn-month"><?php echo $m < 12 ? "$m Mês" : "1 Ano"; ?></div></label><?php endforeach; ?><label style="cursor:pointer;"><input type="radio" name="renew_months" value="manual" style="display:none;" onchange="updateRenewBtn(this, 'manual')"><div class="btn-month">Manual</div></label></div><div id="manualDateDiv" style="display:none; text-align:left;"><label style="font-size:12px; color:var(--text-muted); font-weight:bold;">Data Exata:</label><input type="datetime-local" name="manual_exp_date" style="width:100%; padding:10px; background:#121519; border:1px solid var(--border-color); color:white; border-radius:5px;"></div><button type="submit" id="btn-submit-renew" class="btn-save-modal" style="background:var(--success); margin-top:15px;" disabled>Selecione um prazo</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="modalBulkExp" class="modal">
        <div class="modal-content">
            <h3 style="margin-top:0; color:white;"><i class="fas fa-calendar-alt" style="color:var(--info);"></i> Alterar Vencimento (Massa)</h3>
            <p style="color:var(--text-muted); font-size:13px;">Defina uma nova data de vencimento para todos os clientes selecionados.</p>
            <div class="form-group-modal">
                <label>Nova Data de Vencimento</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 EM TODOS</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>

    <?php if($role === 'admin'): ?>
    <div id="modalBulkOwner" class="modal">
        <div class="modal-content">
            <h3 style="margin-top:0; color:white;"><i class="fas fa-user-tie" style="color:#8b5cf6;"></i> Alterar Dono (Revendedor)</h3>
            <p style="color:var(--text-muted); font-size:13px;">Transfira os clientes selecionados para outro revendedor ou para você.</p>
            <div class="form-group-modal">
                <label>Novo Dono</label>
                <select id="bulk_new_owner" required>
                    <option value="<?php echo $my_id; ?>">Mim (Administrador)</option>
                    <?php foreach($revendedores as $rev): ?>
                        <option value="<?php echo $rev['id']; ?>"><?php echo htmlspecialchars($rev['username']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="button" onclick="submitBulk('owner')" class="btn-save-modal" style="background:#8b5cf6;">TRANSFERIR CLIENTES</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>
    <?php endif; ?>

    <div id="modalConfigTrust" class="modal">
        <div class="modal-content">
            <h3 style="margin-top:0; color:white;"><i class="fas fa-handshake" style="color:#f39c12;"></i> Configurar Confiança</h3>
            <p style="color:var(--text-muted); font-size:13px;">Permita que você e seus revendedores liberem dias de cortesia para clientes em atraso.</p>
            <form method="POST">
                <input type="hidden" name="action_config_trust" value="1">
                <div class="form-group-modal" style="margin-top: 20px;">
                    <label style="display:flex; align-items:center; gap:10px; color:white; font-size:14px; cursor:pointer;">
                        <input type="checkbox" name="confianca_status" value="1" <?php echo $confianca_status == 1 ? 'checked' : ''; ?> style="width:20px; height:20px; margin:0;"> 
                        Ativar Renovação de Confiança
                    </label>
                </div>
                <div class="form-group-modal">
                    <label>Tempo liberado (em Dias)</label>
                    <input type="number" name="confianca_tempo" value="<?php echo htmlspecialchars($confianca_tempo); ?>" min="1" required>
                </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>

    <script>
        // SCRIPT MODO DE VISUALIZAÇÃO
        document.addEventListener('DOMContentLoaded', () => {
            let savedMode = localStorage.getItem('viewMode') || 'table';
            setViewMode(savedMode);
        });

        function toggleViewMode() {
            let currentMode = localStorage.getItem('viewMode') || '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('viewMode', 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();
        }

        // LOGICA DE PLAYLIST M3U
        let currentM3uUser = '';
        let currentM3uPass = '';
        
        // MÁGICA: O MODAL USA SEMPRE A URL DO PAINEL PARA DOWNLOAD
        let baseUrlStreaming = '<?php echo $url_painel; ?>';

        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 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() { 
            // Pega apenas checkboxes ativos (para evitar contar duplicado se estiver nos dois modos)
            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?')) return; 
            if (type === 'exp') { 
                var novaData = document.getElementById('bulk_new_exp').value; 
                if (!novaData) { alert('Informe a data!'); return; } 
                document.getElementById('bulkExpDate').value = novaData; 
            } 
            if (type === 'owner') { 
                var novoDono = document.getElementById('bulk_new_owner').value; 
                if (!novoDono) { alert('Selecione um dono!'); return; } 
                document.getElementById('bulkOwnerId').value = novoDono; 
            } 
            document.getElementById('bulkType').value = type; 
            document.getElementById('bulkIds').value = ids; 
            document.getElementById('bulkForm').submit(); 
        }

        function showReceipt(btn) { document.getElementById('textoComprovante').value = btn.getAttribute('data-texto'); document.getElementById('btnZapLink').href = btn.getAttribute('data-zapurl'); document.getElementById('comprovanteBox').style.display = 'flex'; window.scrollTo({ top: 0, behavior: 'smooth' }); }
        function copiarMensagemAcesso() { var texto = document.getElementById('textoComprovante').value; if (navigator.clipboard && window.isSecureContext) { navigator.clipboard.writeText(texto).then(function() { fecharComprovante(); }); } else { var textArea = document.createElement("textarea"); textArea.value = texto; document.body.appendChild(textArea); textArea.select(); try { document.execCommand('copy'); fecharComprovante(); } catch (err) {} document.body.removeChild(textArea); } }
        function fecharComprovante() { document.getElementById('comprovanteBox').style.display = 'none'; var xhr = new XMLHttpRequest(); xhr.open('GET', '?clear_msg=1', true); xhr.send(); }
        
        function openModal(id) { document.getElementById(id).style.display = 'flex'; }
        function closeAllModals() { var modals = document.querySelectorAll('.modal'); for(var i=0; i<modals.length; i++) { modals[i].style.display = 'none'; } }
        
        function gerarAleatorio(inputID) {
            const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
            let result = '';
            for (let i = 0; i < 6; i++) {
                result += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            document.getElementById(inputID).value = result;
        }
        
        function openAddModal() { 
            document.getElementById('u_id').value = ''; 
            document.getElementById('u_nome').value = ''; 
            document.getElementById('u_user').value = ''; 
            document.getElementById('u_pass').value = ''; 
            document.getElementById('u_zap').value = ''; 
            
            if(document.getElementById('u_force_server')) document.getElementById('u_force_server').value = '1';
            if(document.getElementById('u_restreamer')) document.getElementById('u_restreamer').checked = false;
            if(document.getElementById('u_ips')) document.getElementById('u_ips').value = '';
            if(document.getElementById('u_uas')) document.getElementById('u_uas').value = '';
            
            document.getElementById('u_telas').value = '1'; 
            document.getElementById('u_exp').value = '<?php echo date("Y-m-d\TH:i", strtotime("+30 days")); ?>'; 
            
            var chks = document.querySelectorAll('.bq-check'); 
            for(var i=0; i<chks.length; i++) { chks[i].checked = false; }
            
            openModal('modalClient'); 
        }
        
        function openEditModal(btn) { 
            document.getElementById('u_id').value = btn.getAttribute('data-id'); 
            document.getElementById('u_nome').value = btn.getAttribute('data-nome'); 
            document.getElementById('u_user').value = btn.getAttribute('data-user'); 
            document.getElementById('u_pass').value = btn.getAttribute('data-pass'); 
            document.getElementById('u_zap').value = btn.getAttribute('data-zap'); 
            
            if(document.getElementById('u_force_server')) document.getElementById('u_force_server').value = btn.getAttribute('data-forceserver') || '0';
            if(document.getElementById('u_restreamer')) document.getElementById('u_restreamer').checked = (btn.getAttribute('data-restreamer') == '1');
            if(document.getElementById('u_ips')) document.getElementById('u_ips').value = btn.getAttribute('data-ips');
            if(document.getElementById('u_uas')) document.getElementById('u_uas').value = btn.getAttribute('data-uas');
            
            document.getElementById('u_telas').value = btn.getAttribute('data-telas'); 
            document.getElementById('u_exp').value = btn.getAttribute('data-exp'); 
            var bqs = btn.getAttribute('data-bq'); 
            var chks = document.querySelectorAll('.bq-check'); for(var i=0; i<chks.length; i++) { chks[i].checked = (bqs && bqs.indexOf('"' + chks[i].value + '"') !== -1); }
            openModal('modalClient'); 
        }
        
        function openRenewModal(id) { 
            document.getElementById('r_id').value = id; 
            document.getElementById('btn-submit-renew').disabled = true; 
            document.getElementById('manualDateDiv').style.display = 'none';
            var btns = document.querySelectorAll('.btn-month'); for(var i=0; i<btns.length; i++) { btns[i].style.background = '#1e2227'; }
            openModal('modalRenew'); 
        }

        function updateRenewBtn(radioElem, meses) { 
            var btns = document.querySelectorAll('.btn-month'); for(var i=0; i<btns.length; i++) { btns[i].style.background='#1e2227'; } 
            radioElem.nextElementSibling.style.background='var(--accent)'; 
            document.getElementById('btn-submit-renew').disabled = false;
            document.getElementById('manualDateDiv').style.display = (meses === 'manual') ? 'block' : 'none';
        }

        function sincronizarCliente(idCliente) {
            if(confirm("Tem certeza que deseja sincronizar este cliente?\n\nIsso vai limpar conexões travadas e resetar o IP/MAC do aparelho dele.")) {
                fetch('ajax_sincronizar.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'id_cliente=' + idCliente
                })
                .then(response => response.json())
                .then(data => {
                    if(data.sucesso) {
                        alert("✅ " + data.msg);
                    } else {
                        alert("❌ Erro: " + data.erro);
                    }
                })
                .catch(error => {
                    alert("❌ Erro de comunicacao.");
                });
            }
        }
        
        function trustRenew(id) {
            if(confirm("Deseja aplicar a renovação de confiança (dias de cortesia) para este cliente?")) {
                document.getElementById('trustUserId').value = id;
                document.getElementById('trustRenewForm').submit();
            }
        }
       
        // --- SCRIPT EXCLUSIVO: GATILHO DE WHATSAPP AUTOMÁTICO NA TELA ---
        <?php if(isset($_SESSION['auto_zap_url'])): ?>
            window.onload = function() {
                window.location.href = '<?php echo $_SESSION['auto_zap_url']; ?>';
                <?php unset($_SESSION['auto_zap_url']); ?>
            }
        <?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>
    <script src="tema.js"></script>
</body>
</html>