<?php
session_start();
// --- FORÇA O FUSO HORÁRIO DE BRASÍLIA ---
date_default_timezone_set('America/Sao_Paulo'); 
require_once 'conexao.php';

// --- 1. TRAVA DE SEGURANÇA TOTAL ---
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true) {
    header("Location: login.php"); exit;
}

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

if (!$isAdmin) {
    $stmtCheck = $connUser->prepare("SELECT bloqueado, data_premio FROM rev WHERE usuario = ? LIMIT 1");
    $stmtCheck->execute([$usuarioLogado]);
    $me = $stmtCheck->fetch(PDO::FETCH_ASSOC);

    if ($me) {
        $isBloq = ($me['bloqueado'] == 'sim');
        $isVenc = ((int)$me['data_premio'] > 0 && (int)$me['data_premio'] < time());
        if ($isBloq || $isVenc) {
            die("Acesso Negado: Bloqueado ou Vencido");
        }
    }
}

// --- 2. CONFIGURAÇÕES VISUAIS E DADOS DO CSP ---
$nomePainel = "IPTV PANEL"; $corPrimaria = "#7367f0"; 
$IP_CSP = ""; $PORTA_CSP = ""; $USUARIO_CSP = ""; $SENHA_CSP = "";

try {
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($conf) {
        if (!empty($conf['NomePainel'])) $nomePainel = $conf['NomePainel'];
        if (!empty($conf['TemaPainel'])) $corPrimaria = $conf['TemaPainel'];
    }
    
    $total_msg_nao_lidas = 0;
    try {
        $stmtMsg = $connUser->prepare("SELECT COUNT(*) FROM chamados_suporte WHERE destinatario = ? AND lida = 'nao'");
        $stmtMsg->execute([$usuarioLogado]);
        $total_msg_nao_lidas = $stmtMsg->fetchColumn();
    } catch (Exception $e) { }

    $dadosCSP = $connGeral->query("SELECT url, porta, usuario, senha FROM painel LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($dadosCSP) {
        $IP_CSP = trim($dadosCSP['url']);
        $PORTA_CSP = trim($dadosCSP['porta']);
        $USUARIO_CSP = trim($dadosCSP['usuario']);
        $SENHA_CSP = trim($dadosCSP['senha']);
    }
} catch (Exception $e) { }

// =========================================================================
// 3. PROCESSAR BOTÕES DE AÇÃO (DERRUBAR E BLOQUEAR USUÁRIO)
// O Bloqueio de IP agora usa o "Assistente Rápido" na interface
// =========================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao_monitor'])) {
    header('Content-Type: application/json');
    $acao = $_POST['acao_monitor'];
    $user_login = trim($_POST['user_login']);
    
    $pode_editar = false;
    if ($isAdmin) {
        $pode_editar = true;
    } else {
        $stCheck = $connUser->prepare("SELECT id FROM usuario WHERE usuario = ? AND CadUser = ? UNION SELECT id FROM teste WHERE usuario = ? AND CadUser = ? LIMIT 1");
        $stCheck->execute([$user_login, $usuarioLogado, $user_login, $usuarioLogado]);
        if ($stCheck->rowCount() > 0) $pode_editar = true;
    }

    if ($pode_editar) {
        if ($acao === 'derrubar' || $acao === 'bloquear') {
            if (!empty($IP_CSP) && !empty($PORTA_CSP)) {
                $auth = base64_encode("{$USUARIO_CSP}:{$SENHA_CSP}");
                $ch_kick = curl_init("http://{$IP_CSP}:{$PORTA_CSP}/xmlHandler?command=kick-user&name=" . urlencode($user_login));
                curl_setopt($ch_kick, CURLOPT_HTTPHEADER, ["Authorization: Basic $auth"]);
                curl_setopt($ch_kick, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch_kick, CURLOPT_TIMEOUT, 5);
                curl_exec($ch_kick);
                curl_close($ch_kick);
            }
        }

        if ($acao === 'bloquear') {
            if ($isAdmin) {
                $connUser->prepare("UPDATE usuario SET bloqueado='sim' WHERE usuario=?")->execute([$user_login]);
                $connUser->prepare("UPDATE teste SET bloqueado='sim' WHERE usuario=?")->execute([$user_login]);
            } else {
                $connUser->prepare("UPDATE usuario SET bloqueado='sim' WHERE usuario=? AND CadUser=?")->execute([$user_login, $usuarioLogado]);
                $connUser->prepare("UPDATE teste SET bloqueado='sim' WHERE usuario=? AND CadUser=?")->execute([$user_login, $usuarioLogado]);
            }
        }
        
        echo json_encode(['status' => 'sucesso']);
        exit;
    } else {
        echo json_encode(['status' => 'erro', 'msg' => 'Sem permissão para alterar este cliente.']);
        exit;
    }
}

// DICIONÁRIO INTERNO DE CANAIS
$dicionario_canais = [
    "1053" => "TELECINE PREMIUM", "41D"  => "TELECINE PREMIUM", "041D" => "TELECINE PREMIUM",
    "155" => "BBB", "83" => "GLOBALSAT+", "57" => "A&E", "7A" => "ANIMAL PLANET", "80" => "APARECIDA",
    "82" => "ARTE 1", "54" => "AXN", "140" => "BAND ALTERNATIVO", "8C" => "BAND NEWS", "2F" => "BAND SPORT",
    "1A4" => "BANDEIRANTES", "90" => "BIS", "60" => "BOOMERANG", "43" => "CANAL BRASIL", "62" => "CANAL RURAL",
    "193" => "CANCAO NOVA", "5F" => "CARTOON NETWORK", "95" => "PREMIERE 9", "39" => "CINEMAX", "70" => "CNNE",
    "8D" => "CNNI", "7E" => "CNT", "18B" => "PREMIERE COMBATE", "5C" => "COMEDY CENTRAL", "9F" => "CURTA!",
    "9A" => "DEUTSCHE WELLE", "78" => "DISCOVERY CHANNEL", "2B" => "DISCOVERY H&H", "64" => "DISCOVERY KIDS",
    "6E" => "DISCOVERY TURBO", "66" => "DISNEY", "65" => "DISNEY JUNIOR", "67" => "DISNEY XD", "36" => "E!",
    "1AD" => "EPTV CAMPINAS", "1A3" => "EPTV RIBEIRAO PRETO", "1AF" => "EPTV SAO CARLOS", "2D" => "ESPN",
    "2E" => "ESPN BRASIL", "89" => "I-SAT", "30" => "ESPN+", "37" => "FOX", "2C" => "FOX LIFE", "32" => "FOX SPORT",
    "22" => "FOX SPORTV2", "1A8" => "FUTURA", "34" => "FISH TV", "23" => "FOOD NETWORK", "53" => "FX", "35" => "GLITZ",
    "197" => "GLOBO BAHIA", "198" => "GLOBO MINAS", "199" => "GLOBO NORDESTE", "194" => "GLOBO RIO DE JANEIRO",
    "195" => "GLOBO SAO PAULO", "28" => "GLOBO NEWS", "5E" => "GLOOB", "29" => "GNT", "45" => "HBO", "48" => "HBO FAMILY",
    "46" => "HBO PLUS", "4B" => "HBO PLUS E", "4C" => "HBO SIGNATURE", "47" => "HBO2", "7B" => "ID INVESTIGACAO DISCOVERY",
    "86" => "IDEAL TV", "1AC" => "INTER TV CABUGI", "4D" => "MAX", "49" => "MAX UP", "4A" => "MAX PRIME", "4E" => "MAX PRIME E",
    "3C" => "MEGAPIX", "7F" => "RBI", "1D" => "MTV", "2A" => "MULTISHOW", "88" => "MUSIC BOX BRAZIL", "79" => "NATIONAL GEOGRAPHIC",
    "73" => "NAT GEO WILD", "1A9" => "NBR", "9C" => "NHK PREMIUM", "6A" => "NICK JR", "6B" => "NICKELODEON", "33" => "OFF",
    "76" => "PLAY TV", "B0" => "POLISHOP", "18F" => "PREMIERE 1", "BC" => "PREMIERE 2", "191" => "PREMIERE 3",
    "192" => "PREMIERE 4", "BB" => "PREMIERE 5", "BA" => "PREMIERE 6", "18A" => "PREMIERE 7", "18E" => "PREMIERE 8",
    "18D" => "PREMIERE CLUBES", "44" => "PRIME BOX BRASIL", "85" => "RAI", "1A0" => "RBS PORTO ALEGRE", "6F" => "RECORD NEWS",
    "81" => "REDE BRASIL", "84" => "REDE TV", "5A" => "REDE VIDA", "7D" => "RIT", "19E" => "RPC TV PARANAENCE", "87" => "RECORD TV",
    "1AA" => "SBT", "96" => "SIC", "56" => "SONY", "4F" => "LIFETIME", "3A" => "SPACE", "27" => "SPORTV", "26" => "SPORTV2",
    "152" => "SPORTV2 ALTERNATIVO", "24" => "SPORTV3", "153" => "SPORTV ALTERNATIVO", "51" => "STUDIO UNUVERSAL", "52" => "SYFY",
    "5B" => "TBS", "50" => "TCM", "3E" => "TELECINE ACTION", "41" => "TELECINE CULT", "19C" => "TELECINE FUN", "40" => "TELECINE PIPOCA",
    "3D" => "TELECINE PREMIUM", "3F" => "TELECINE TOUCH", "6D" => "TERRA VIVA", "12D" => "TESTE1", "322" => "TESTE2", "69" => "H2",
    "68" => "THE HISTORY CHANNEL", "7C" => "TRAVEL AND LIVING CHANNEL", "3B" => "TNT", "61" => "TOONCAST", "58" => "TRU TV",
    "1A1" => "TV AMAZONAS", "19A" => "TV ANHANGUERA GOIANIA", "A4" => "TV BRASIL", "19D" => "TV CENTRO AMERICA", "1A7" => "TV CULTURA",
    "A2" => "TV CAMARA", "C7" => "TV ESCOLA", "97" => "TV ESPANA", "1AE" => "GLOBO BRASILIA", "A0" => "TV JUSTICA", "19F" => "TV LIBERAL BELEM",
    "6C" => "TV RA TIM BUM", "A1" => "TV SENADO", "1A6" => "TV TEM BAURU", "1A5" => "TV TEM SOROCABA", "19B" => "TV TEM SAO JOSE DO RIO PARDO",
    "1A2" => "TV TRIBUNAS SANTOS", "1B0" => "TV VANGUARDA SAO JOSE", "196" => "TV VERDES MARES FORTALE", "98" => "TV5 MONDE", "12C" => "TV EXEC",
    "8F" => "UNIVERSAL CHANNEL", "31" => "PARAMOUNT", "25" => "VIVA", "55" => "WARNER CHANNEL", "5D" => "WHOOHOO", "42" => "BOA VONTADE",
    "59" => "DISCOVERY CIVILIZATION", "74" => "DISCOVERY SCIENCE", "92" => "EI MAXX", "93" => "FISH TV", "B8" => "NOVO TEMPO",
    "38" => "SHOPTIME", "8E" => "TNT SERIES", "91" => "VH1 MEGA HITS",
    "C0" => "PLAYBOY", "C1" => "SEXHOT", "9E" => "SEXTREME",
    "20A" => "BAND HD", "243" => "BAND NEWS HD", "223" => "BAND SPORTS HD", "28A" => "CANAL BRASIL HD", "266" => "CARTOON HD",
    "28F" => "CINEMAX HD", "2E4" => "PREMIERE COMBATE HD", "2A8" => "COMEDY CENTRAL HD", "253" => "DISCOVERY KIDS HD",
    "268" => "DISCOVERY THEATER HD", "262" => "DISCOVERY TURBO HD", "251" => "DISCOVERY WORLD HD", "217" => "DISCOVERY HOME & HEALTH HD",
    "1DF" => "EPTV HD CAMPINAS", "222" => "ESPN BRASIL HD", "221" => "ESPN HD", "224" => "ESPN+ HD", "216" => "FOOD NETWORK HD",
    "28B" => "FOX LIFE HD", "288" => "FOX PREMIUM 1 HD", "289" => "FOX PREMIUM 2 HD", "225" => "FOX SPORTS 2 HD", "27A" => "FX HD",
    "21C" => "GLOBO NEWS HD", "1CA" => "GLOBO MINHAS HD", "1C6" => "GLOBO RJ HD", "1C7" => "GLOBO SP HD", "1CB" => "GLOBO NORDESTE HD",
    "261" => "H2 HD", "2A3" => "HBO FAMILY HD", "22B" => "ID INVESTIGAÇÃO DISCOVERY HD", "281" => "LIFETIME HD", "2A6" => "MAX HD",
    "2A7" => "MAX PRIME HD", "230" => "MEGAPIX HD", "271" => "VH1 HD", "218" => "VIVA HD", "21F" => "UNIVERSAL CHANNEL HD",
    "1C8" => "TV TEM VERDES MARES HD", "1D8" => "TV TEM BAURU HD", "1D1" => "TV LIBERAL BELEN HD", "1C9" => "TV BAHIA HD",
    "1CC" => "TV ANHANGUERA GOIANIA HD", "283" => "TNT SERIES HD", "29A" => "TELECINE CULT HD", "219" => "SPORT TV 3 HD",
    "25B" => "NIKELODEON HD", "26D" => "MTV HD", "1E0" => "GLOBO BRASILIA HD", "240" => "EI MAXX HD", "237" => "EI MAXX II HD",
    "22A" => "E! HD", "246" => "ANIMAL PLANET HD", "214" => "GLOBALSAT HD", "249" => "AXN HD", "220" => "BIS HD",
    "25C" => "DISCOVERY CHANNEL HD", "258" => "DISCOVERY THEATER HD", "256" => "DISNEY HD", "22C" => "FOX HD", "226" => "FOX SPORT HD",
    "252" => "GLOOB HD", "21D" => "GNT HD", "23A" => "HBO HD", "23C" => "HBO2 HD", "23B" => "HBO PLUS HD", "241" => "HBO SIGNATURE HD",
    "23E" => "MAX HD", "21E" => "MULTISHOW HD", "267" => "NATIONAL GEO WILD HD", "25E" => "NATIONAL GEO HD", "227" => "OFF HD",
    "24B" => "SONY HD", "22F" => "SPACE HD", "21A" => "SPORTV2 HD", "21B" => "SPORTV HD", "27F" => "SPORTV ALTERNATIVO HD",
    "232" => "TELECINE ACTION HD", "234" => "TELECINE FUN HD", "235" => "TELECINE PIPOCA HD", "231" => "TELECINE PREMIUM HD",
    "233" => "TELECINE TOUCH HD", "260" => "THE HISTORY CHANNEL HD", "25F" => "TRAVEL AND LIVING CHANNEL HD", "22E" => "TNT HD",
    "228" => "VH1 HD", "24A" => "WARNER CHANNEL HD", "244" => "PARAMOUNT HD", "2D2" => "PREMIERE 2 HD", "2D3" => "PREMIERE 3 HD",
    "2D4" => "PREMIERE 4 HD", "2D5" => "PREMIERE 5 HD", "2D1" => "PREMIERE CLUBES HD", "1D2" => "RSB TV PORTO ALEGRE HD",
    "1D3" => "REDE AMAZONICA HD", "1D0" => "RPC TV PARANAENCE HD", "2E5" => "BBB HD"
];

$online_users = [];
$erro = "";

// --- 4. CONEXÃO DIRETA COM O CSP PARA LISTAR OS USUÁRIOS ONLINE ---
if (!empty($IP_CSP) && !empty($PORTA_CSP)) {
    $auth = base64_encode("{$USUARIO_CSP}:{$SENHA_CSP}");
    $headers = [
        "Authorization: Basic $auth", 
        "User-Agent: Mozilla/5.0",
        "Connection: close"
    ];

    $ch = curl_init("http://{$IP_CSP}:{$PORTA_CSP}/xmlHandler?command=proxy-users");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $xml_bruto = trim(curl_exec($ch));
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($code == 200 && !empty($xml_bruto)) {
        libxml_use_internal_errors(true);
        $xml = @simplexml_load_string($xml_bruto);
        
        if ($xml) {
            foreach ($xml->xpath('//user') as $u) {
                $login = (string)$u['name'];
                
                if (empty($login) || $login === '*' || in_array(strtolower($login), ['sandisk', 'admin', 'mapa', 'copo', 'kauã', 'kaua', 'capa'])) continue; 

                $sessoes = $u->xpath('.//session');
                if (empty($sessoes)) continue; 

                foreach ($sessoes as $f) {
                    $ip_cliente = (string)$f['host'] ?: (string)$f['ip'] ?: "---";
                    $canal_assistindo = "Navegando no Menu";
                    $service_name = "";
                    $service_id = "";
                    
                    // EXTRAÇÃO DE FLAGS
                    $flags_csp = (string)$f['flags'];
                    if (empty($flags_csp)) {
                        $flags_csp = (string)$u['flags'];
                    }

                    // OPERADORA
                    $profile_str = (string)$f['profile'];
                    $operadora_html = "<span class='text-white-50 small'>".htmlspecialchars($profile_str)."</span>";
                    
                    if (!empty($profile_str)) {
                        $prof_lower = strtolower($profile_str);
                        if (strpos($prof_lower, 'claro') !== false) {
                            $operadora_html = "<img src='img/claro.png' class='img-perfil' style='height: 20px; width: auto;' alt='Claro'>";
                        } elseif (strpos($prof_lower, 'net') !== false) {
                            $operadora_html = "<img src='img/net.png' class='img-perfil' style='height: 20px; width: auto;' alt='Net'>";
                        }
                    }

                    $srvs = $f->xpath('.//service');
                    if (!empty($srvs)) {
                        $service_name = (string)$srvs[0]['name'];
                        $service_id = (string)$srvs[0]['id'];
                    }

                    if (!empty($service_name) && strpos(strtolower($service_name), 'unknown') === false) {
                        $nome_limpo = preg_replace('/\[.*?\]\s*/', '', $service_name); 
                        $nome_limpo = preg_replace('/\|.*?\|\s*/', '', $nome_limpo);
                        $canal_assistindo = trim($nome_limpo);
                        if (empty($canal_assistindo)) $canal_assistindo = trim($service_name);
                    } else if (!empty($service_id) && $service_id !== '0000:0000' && $service_id !== '0') {
                        $sid_orig = strtoupper(str_replace('0X', '', $service_id));
                        $sid_clean = ltrim($sid_orig, '0') ?: '0';
                        $tentativas = [ $sid_orig, $sid_clean, str_pad($sid_clean, 4, '0', STR_PAD_LEFT) ];
                        if (ctype_digit($sid_clean)) {
                            $hex_val = strtoupper(dechex((int)$sid_clean));
                            $tentativas[] = $hex_val;
                            $tentativas[] = str_pad($hex_val, 4, '0', STR_PAD_LEFT);
                        }
                        if (ctype_xdigit($sid_clean)) {
                            $tentativas[] = (string)hexdec($sid_clean);
                        }
                        $achou = false;
                        foreach ($tentativas as $t) {
                            if (isset($dicionario_canais[$t])) {
                                $canal_assistindo = $dicionario_canais[$t];
                                $achou = true;
                                break;
                            }
                        }
                        if (!$achou) { $canal_assistindo = "Canal ID: " . $sid_orig; }
                    }

                    $segundos = 0;
                    $duration_str = (string)$f['duration'];
                    if (!empty($duration_str)) {
                        if (preg_match('/(?:(\d+)d\s*)?(?:(\d+)h\s*)?(?:(\d+)m\s*)?(?:(\d+)s)?/i', $duration_str, $t)) {
                            $dias = !empty($t[1]) ? (int)$t[1] : 0;
                            $horas = !empty($t[2]) ? (int)$t[2] : 0;
                            $minutos = !empty($t[3]) ? (int)$t[3] : 0;
                            $segs = !empty($t[4]) ? (int)$t[4] : 0;
                            $segundos = ($dias * 86400) + ($horas * 3600) + ($minutos * 60) + $segs;
                        }
                    }

                    if ($segundos < 0) $segundos = 0;

                    $h_fmt = floor($segundos / 3600);
                    $m_fmt = floor(($segundos % 3600) / 60);
                    $s_fmt = $segundos % 60;
                    $tempo_fmt = sprintf("%02d:%02d:%02d", $h_fmt, $m_fmt, $s_fmt);

                    $nome_real = $login; 
                    $dono_c = 'Admin';
                    try {
                        $st = $connUser->prepare("SELECT nome, CadUser FROM usuario WHERE usuario = ? UNION SELECT nome, CadUser FROM teste WHERE usuario = ? LIMIT 1");
                        $st->execute([$login, $login]);
                        if ($r = $st->fetch()) { 
                            $nome_real = $r['nome']; 
                            $dono_c = empty($r['CadUser']) ? 'Admin' : $r['CadUser']; 
                        }
                    } catch(Exception $e) {}

                    $userId = md5($login . $ip_cliente);

                    if ($isAdmin || $dono_c === $usuarioLogado) {
                        $online_users[] = [
                            'id' => $userId, 
                            'nome' => $nome_real, 
                            'login' => $login, 
                            'ip' => $ip_cliente, 
                            'operadora' => $operadora_html,
                            'canal' => $canal_assistindo, 
                            'tempo' => $tempo_fmt, 
                            'segundos' => $segundos,
                            'dono' => $dono_c,
                            'flags' => $flags_csp
                        ];
                    }
                }
            }
        }
    }
} else {
    $erro = "Os dados do Servidor CSP não estão configurados.";
}

// =========================================================================
// RESPOSTA AJAX INVISÍVEL
// =========================================================================
if (isset($_GET['ajax'])) {
    if (!empty($erro)) {
        echo '<tr><td colspan="8" class="text-center py-5 text-danger fw-bold"><i class="fas fa-exclamation-triangle"></i> ' . htmlspecialchars($erro) . '</td></tr>';
    } elseif (empty($online_users)) {
        echo '<tr><td colspan="8" class="text-center py-5 text-muted">Nenhum receptor ativo no momento.</td></tr>';
    } else {
        foreach($online_users as $u) {
            echo '<tr class="user-row" id="usr_'.htmlspecialchars($u['id']).'" data-login="'.htmlspecialchars($u['login']).'" data-flags="'.htmlspecialchars($u['flags']).'">
                <td class="nome-destaque"><span class="dot-online"></span>'.htmlspecialchars($u['nome']).'</td>
                <td class="text-info login-cel">'.htmlspecialchars($u['login']).'</td>
                <td class="ip-text">'.htmlspecialchars($u['ip']).'</td>
                <td class="text-center text-operadora">'.$u['operadora'].'</td>
                <td class="text-warning fw-bold text-canal"><i class="fas fa-tv me-1 small"></i> '.htmlspecialchars($u['canal']).'</td>
                <td class="text-center text-secondary fw-bold small dono-cel">'.htmlspecialchars($u['dono']).'</td>
                <td class="text-center text-success fw-bold tempo-online" data-segundos="'.$u['segundos'].'">'.$u['tempo'].'</td>
                <td class="text-center btns-acao">
                    <button class="btn btn-sm btn-outline-warning rounded-circle px-2 py-1 me-1" title="Derrubar Conexão (Desconectar)" onclick="derrubarUser(\''.htmlspecialchars($u['login']).'\')"><i class="fas fa-plug"></i></button>
                    <button class="btn btn-sm btn-outline-danger rounded-circle px-2 py-1" title="Bloquear Usuário (Cortar Acesso)" onclick="bloquearUser(\''.htmlspecialchars($u['login']).'\')"><i class="fas fa-lock"></i></button>
                </td>
            </tr>';
        }
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Monitor Online | <?= htmlspecialchars($nomePainel) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root { --primary: <?= $corPrimaria ?>; --bg-body: #151521; --bg-card: #1e1e2d; --text-color: #d0d2d6; --border-color: #2b2b40; }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; }
        
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid #333; z-index: 1050; padding: 20px; overflow-y: auto; transition: 0.3s; left: 0; }
        .nav-link { color: #a6a6b7; padding: 12px 15px; border-radius: 8px; display: flex; align-items: center; gap: 12px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s;}
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }
        
        .main-content { margin-left: 260px; transition: 0.3s; min-height: 100vh; }
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--primary) 100%); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); }
        
        .card-monitor { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 15px; overflow: hidden; }
        .table-online { width: 100%; white-space: nowrap; border-collapse: collapse; }
        .table-online td { padding: 12px; font-size: 0.85rem; border-bottom: 1px solid var(--border-color); vertical-align: middle; }
        
        .table-online th { 
            padding: 12px; 
            font-size: 0.75rem; 
            border-bottom: 1px solid var(--border-color); 
            vertical-align: middle;
            color: #adb5bd !important; 
            background: rgba(0,0,0,0.2);
            text-transform: uppercase;
            font-weight: bold;
            letter-spacing: 1px;
        }

        .ip-text { color: #ffffff !important; font-family: monospace; font-size: 0.9rem; font-weight: 500; }
        .nome-destaque { color: #ffffff; font-weight: 700; }
        .dot-online { width: 8px; height: 8px; background: #28c76f; border-radius: 50%; display: inline-block; margin-right: 8px; box-shadow: 0 0 5px #28c76f; }

        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; margin-right: 15px; cursor: pointer; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; }
        .overlay.show { display: block; }

        .search-container { position: relative; max-width: 300px; }
        .search-container input { background: #151521; border: 1px solid #333; color: white; border-radius: 20px; padding: 8px 15px 8px 40px; width: 100%; font-size: 0.85rem; }
        .search-container i { position: absolute; left: 15px; top: 11px; color: #7367f0; }
        .filter-select { background: #151521; border: 1px solid #333; color: white; border-radius: 10px; padding: 5px 10px; font-size: 0.85rem; outline: none; }
        .pagination-container { display: flex; justify-content: space-between; align-items: center; padding: 15px; background: rgba(0,0,0,0.1); }
        .page-btn { background: #151521; border: 1px solid #333; color: white; padding: 5px 15px; border-radius: 5px; cursor: pointer; transition: 0.2s; }
        .page-btn:disabled { opacity: 0.3; cursor: not-allowed; }
        .page-btn:hover:not(:disabled) { background: var(--primary); }
        
        .nav-tabs .nav-link { border: none; color: var(--text-color); background: rgba(0,0,0,0.1); margin-right: 5px; border-radius: 10px 10px 0 0; cursor: pointer; }
        .nav-tabs .nav-link.active { background: var(--bg-body); border-bottom: 2px solid var(--primary); color: #fff; }
        
        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); } 
            .sidebar.show { transform: translateX(0); } 
            .main-content { margin-left: 0; } 
            .mobile-toggle { display: block !important; } 
            .controls-wrapper { flex-direction: column; gap: 15px; }
        }
    </style>
</head>
<body>

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

<nav class="sidebar" id="sidebar">
    <div class="text-center mb-4"><h4 class="fw-bold text-white"><?= htmlspecialchars($nomePainel) ?></h4></div>
    <div class="nav flex-column">
        <a href="index.php" class="nav-link active"><i class="fas fa-home"></i> Dashboard</a>
        <?php if ($isAdmin): ?>
            <div class="nav-group-title">ADMINISTRATIVO</div>
            <!-- MENU COLAPSÁVEL DA CSP -->
            <a href="#submenuCsp" data-bs-toggle="collapse" class="nav-link d-flex justify-content-between align-items-center" aria-expanded="true">
                <span><i class="fas fa-server"></i> Gerenciar CSP</span>
                <i class="fas fa-chevron-down submenu-icon"></i>
            </a>
            <div class="collapse show" id="submenuCsp">
                <div class="ms-3 ps-2 border-start border-secondary">
                    <a href="gerenciar_dns.php" class="nav-link"><i class="fas fa-network-wired"></i> Servidores</a>
                    <a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Perfis</a>
                    <a href="gerenciar_linhas_csp.php" class="nav-link"><i class="fas fa-plug"></i> Linhas CSP</a>
                    <a href="gerenciar_usuarios_csp.php" class="nav-link"><i class="fas fa-users-cog"></i> Usuários CSP</a>
                    <a href="gerenciar_backups_csp.php" class="nav-link"><i class="fas fa-save"></i> Backups CSP</a>
                </div>
            </div>
            <!-- FIM DO MENU DA CSP -->
            <a href="gerenciar_admins.php" class="nav-link"><i class="fas fa-user-shield"></i> Admins</a>
            <a href="personalizar_painel.php" class="nav-link"><i class="fas fa-paint-brush"></i> Personalizar</a>
            <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Configurações</a>
            
            <div class="nav-group-title">SISTEMA SAAS</div>
            <a href="painel_mestre.php" class="nav-link"><i class="fas fa-crown"></i> Gerenciar Licenças</a>
            
            
            
            
            <div class="nav-group-title">ADMIN</div>
            <a href="gerenciar_ips.php" class="nav-link"><i class="fas fa-user-shield"></i> Firewall IPs</a>
            <a href="gerenciar_backups.php" class="nav-link"><i class="fas fa-database"></i> Backup</a>
            <a href="ferramentas_migracao.php" class="nav-link"><i class="fas fa-exchange-alt"></i> Exportar/Importar</a>
        <?php endif; ?>
        
        
        <div class="nav-group-title">Gestao de Clientes</div>
        <a href="clientes.php" class="nav-link"><i class="fas fa-users"></i> Clientes</a>
        <a href="testes.php" class="nav-link"><i class="fas fa-stopwatch"></i> Testes</a>
        <a href="monitor.php" class="nav-link"><i class="fas fa-bell"></i> Clientes Online</a>
        <div class="nav-group-title">Gestao de Revendedores</div>
        <a href="revendedores.php" class="nav-link"><i class="fas fa-store"></i> Revendedores</a>
        
        <div class="nav-group-title">ChatBot</div>
        <li style="list-style: none;">
            <a href="gerador_robo.php" class="nav-link" style="color: #a6a6b7; padding: 12px 15px; border-radius: 8px; display: flex; align-items: center; gap: 12px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s;">
                <i class="fa fa-robot"></i> <span>ChatBot</span>
            </a>
        </li>
        
        
        <div class="nav-group-title">Api WhatsApp</div>
        <li style="list-style: none;">
           <a href="automacao_whatsapp.php" class="nav-link"><i class="fab fa-whatsapp"></i> Automação Zap</a>
           <a href="config_whatsapp.php" class="nav-link"><i class="fas fa-cogs"></i> Config. API Zap</a> 
            
            
        
        <div class="nav-group-title">Ferramentas</div>
        
        <a href="meus_links.php" class="nav-link"><i class="fas fa-link"></i> Central Links</a>
        <a href="gerenciar_mascara.php" class="nav-link"><i class="fas fa-mask"></i> Máscaras URL</a>        
        <a href="config_mp_revenda.php" class="nav-link"><i class="fas fa-wallet"></i> Config. Pagamento</a>
        <a href="gerenciar_planos.php" class="nav-link"><i class="fas fa-tags"></i> Planos de Venda</a>
        <a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> SMTP Email</a>
        <a href="relatorio.php" class="nav-link"><i class="fas fa-file-invoice-dollar"></i> Relatório de Faturas</a>
        <a href="suporte.php" class="nav-link"><i class="fas fa-headset"></i> Suporte <?php if($total_msg_nao_lidas > 0): ?><span class="badge bg-danger ms-auto rounded-pill"><?= $total_msg_nao_lidas ?></span><?php endif; ?></a>
        <a href="enviar_circular.php" class="nav-link"><i class="fas fa-paper-plane"></i> Enviar Circular</a>
        
        <a href="sair.php" class="nav-link text-danger mt-4"><i class="fas fa-sign-out-alt"></i> Sair</a>
    </div>
</nav>

<main class="main-content">
    <div class="top-header">
        <div class="d-flex align-items-center">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title text-white fw-bold">MONITORAMENTO REALTIME</div>
        </div>
        <button onclick="location.reload()" class="btn btn-sm btn-outline-light rounded-pill"><i class="fas fa-sync"></i> Recarregar</button>
    </div>

    <div class="container-fluid p-4">
        <?php if($erro): ?>
            <div class="alert alert-danger border-0 shadow-sm fw-bold">
                <i class="fas fa-exclamation-triangle me-2"></i> <?= htmlspecialchars($erro) ?>
            </div>
        <?php endif; ?>

        <div class="card card-monitor p-0 shadow">
            
            <ul class="nav nav-tabs px-4 pt-3 border-bottom-0" id="monitorTabs">
                <li class="nav-item">
                    <button class="nav-link active fw-bold" id="geral-tab" data-bs-target="#tab-geral" type="button"><i class="fas fa-users"></i> Monitor Geral</button>
                </li>
                <?php if ($isAdmin): ?>
                <li class="nav-item">
                    <button class="nav-link fw-bold text-warning" id="reshare-tab" data-bs-target="#tab-reshare" type="button"><i class="fas fa-share-alt"></i> Controle de Reshare / Flags</button>
                </li>
                <?php endif; ?>
            </ul>

            <div class="d-flex flex-wrap justify-content-between align-items-center px-4 py-3 controls-wrapper border-top" style="border-color: var(--border-color) !important;">
                <div class="d-flex align-items-center gap-3">
                    <div class="search-container">
                        <i class="fas fa-search"></i>
                        <input type="text" id="inputBusca" placeholder="Pesquisar cliente ou login..." onkeyup="filtrarTabela()">
                    </div>
                    <select id="filtroQtd" class="filter-select" onchange="mudarLimite()">
                        <option value="10">10 por página</option>
                        <option value="20">20 por página</option>
                        <option value="50">50 por página</option>
                        <option value="100">100 por página</option>
                        <option value="250">250 por página</option>
                        <option value="500">500 por página</option>
                        <option value="1000">1000 por página</option>
                    </select>
                </div>
                <span class="badge bg-success px-3 py-2 rounded-pill" id="badge-online"><?= count($online_users) ?> Dispositivos</span>
            </div>

            <div class="tab-content">
                <div class="tab-pane show active" id="tab-geral">
                    <div class="table-responsive">
                        <table class="table-online">
                            <thead>
                                <tr>
                                    <th>NOME DO CLIENTE</th>
                                    <th>USUÁRIO</th>
                                    <th>IP</th>
                                    <th class="text-center">OPERADORA</th>
                                    <th>CANAL</th>
                                    <th class="text-center">REVENDEDOR</th>
                                    <th class="text-center">TEMPO</th>
                                    <th class="text-center">AÇÕES</th>
                                </tr>
                            </thead>
                            <tbody id="tabela-corpo">
                                <?php if(empty($online_users)): ?>
                                    <tr><td colspan="8" class="text-center py-5 text-white">Nenhum receptor ativo no momento.</td></tr>
                                <?php else: foreach($online_users as $u): ?>
                                    <tr class="user-row" id="usr_<?= htmlspecialchars($u['id']) ?>" data-login="<?= htmlspecialchars($u['login']) ?>" data-flags="<?= htmlspecialchars($u['flags']) ?>">
                                        <td class="nome-destaque"><span class="dot-online"></span><?= htmlspecialchars($u['nome']) ?></td>
                                        <td class="text-info login-cel"><?= htmlspecialchars($u['login']) ?></td>
                                        <td class="ip-text"><?= htmlspecialchars($u['ip']) ?></td>
                                        <td class="text-center text-operadora"><?= $u['operadora'] ?></td>
                                        <td class="text-warning fw-bold text-canal"><i class="fas fa-tv me-1 small"></i> <?= htmlspecialchars($u['canal']) ?></td>
                                        <td class="text-center text-secondary fw-bold small dono-cel"><?= htmlspecialchars($u['dono']) ?></td>
                                        <td class="text-center text-success fw-bold tempo-online" data-segundos="<?= $u['segundos'] ?>"><?= $u['tempo'] ?></td>
                                        <td class="text-center btns-acao">
                                            <button class="btn btn-sm btn-outline-warning rounded-circle px-2 py-1 me-1" title="Derrubar Conexão (Desconectar)" onclick="derrubarUser('<?= htmlspecialchars($u['login']) ?>')"><i class="fas fa-plug"></i></button>
                                            <button class="btn btn-sm btn-outline-danger rounded-circle px-2 py-1" title="Bloquear Usuário (Cortar Acesso)" onclick="bloquearUser('<?= htmlspecialchars($u['login']) ?>')"><i class="fas fa-lock"></i></button>
                                        </td>
                                    </tr>
                                <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <?php if ($isAdmin): ?>
                <div class="tab-pane" id="tab-reshare" style="display: none;">
                    <div class="table-responsive">
                        <table class="table-online">
                            <thead>
                                <tr>
                                    <th>USUÁRIO</th>
                                    <th>IP DE CONEXÃO</th>
                                    <th class="text-center">REVENDEDOR</th>
                                    <th class="text-center text-warning"><i class="fas fa-flag"></i> FLAGS CSP</th>
                                    <th class="text-center">STATUS (ALERTA)</th>
                                    <th class="text-center">TEMPO</th>
                                    <th class="text-center">AÇÕES</th>
                                </tr>
                            </thead>
                            <tbody id="tabela-reshare-corpo">
                                </tbody>
                        </table>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <div class="pagination-container">
                <div class="small text-white">Mostrando <span id="mostrando-count">0</span> de <span id="total-count">0</span> registros</div>
                <div class="d-flex gap-2">
                    <button class="page-btn" id="btnPrev" onclick="mudarPagina(-1)"><i class="fas fa-chevron-left"></i></button>
                    <button class="page-btn" id="btnNext" onclick="mudarPagina(1)"><i class="fas fa-chevron-right"></i></button>
                </div>
            </div>
        </div>
    </div>
</main>

<div class="modal fade" id="modalMaquina" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content" style="background-color: #1e1e2d; color: #d0d2d6; border: 1px solid #2b2b40;">
      <div class="modal-header border-bottom-0">
        <h5 class="modal-title text-white fw-bold"><i class="fas fa-desktop text-info me-2"></i> Detalhes da Máquina</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body p-4">
        <ul class="list-group list-group-flush shadow-sm" style="border-radius: 10px; overflow: hidden; border: 1px solid #333;">
            <li class="list-group-item d-flex justify-content-between align-items-center" style="background: rgba(0,0,0,0.3); color: white;">
                <strong><i class="fas fa-user-circle text-muted me-2"></i> Usuário Logado:</strong> 
                <span id="modLogin" class="text-info fw-bold"></span>
            </li>
            <li class="list-group-item d-flex justify-content-between align-items-center" style="background: rgba(0,0,0,0.3); color: white;">
                <strong><i class="fas fa-network-wired text-muted me-2"></i> IP da Máquina:</strong> 
                <span id="modIp" class="font-monospace text-warning fw-bold"></span>
            </li>
            <li class="list-group-item" style="background: rgba(0,0,0,0.3); color: white;">
                <strong><i class="fas fa-flag text-muted me-2"></i> Tradução das Flags:</strong><br>
                <div id="modFlags" class="mt-2"></div>
            </li>
        </ul>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="modalBloqueioManual" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content" style="background-color: #1e1e2d; color: #d0d2d6; border: 1px solid #2b2b40;">
      <div class="modal-header border-bottom-0">
        <h5 class="modal-title text-white fw-bold"><i class="fas fa-shield-alt text-danger me-2"></i> Assistente de Bloqueio Rápido</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body p-4">
        <p class="text-white-50 mb-4" style="font-size: 0.9rem;">
            A sua versão da CSP bloqueia edições por fora. Para sua segurança e agilidade, use este assistente:
        </p>
        
        <div class="mb-4">
            <label class="text-white fw-bold small">1. Copie a linha mágica abaixo:</label>
            <div class="d-flex mt-1">
                <div class="form-control bg-dark text-warning font-monospace border-secondary d-flex align-items-center" id="modBloqueioLinha" style="border-radius: 5px 0 0 5px; height: 45px; overflow-x: auto; white-space: nowrap;" readonly></div>
                <button class="btn btn-primary px-3" onclick="copiarTexto('modBloqueioLinha')" style="border-radius: 0 5px 5px 0; height: 45px;">
                    <i class="fas fa-copy"></i>
                </button>
            </div>
        </div>

        <div class="mt-4 d-flex flex-column gap-2">
            <label class="text-white fw-bold small">2. Cole na sua CSP e Salve:</label>
            <a href="http://<?= htmlspecialchars($IP_CSP) ?>:<?= htmlspecialchars($PORTA_CSP) ?>/" target="_blank" class="btn btn-danger py-3 fw-bold text-uppercase" style="letter-spacing: 1px;">
                <i class="fas fa-external-link-alt me-2"></i> Abrir CSP no Navegador
            </a>
            <small class="text-muted text-center mt-2">Dica: Cole a linha que você copiou logo abaixo de <b>&lt;ca-profiles&gt;</b> e clique em <b>Save changes</b>.</small>
        </div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    let paginaAtual = 1;
    let limiteExibicao = 10;
    let currentIPAction = "";
    
    // Checagem se o admin está logado para os scripts JS da segunda aba
    const isAdminUser = <?= $isAdmin ? 'true' : 'false' ?>;

    // LÓGICA DE ABAS VANILLA JS
    document.querySelectorAll('#monitorTabs .nav-link').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('#monitorTabs .nav-link').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            document.querySelectorAll('.tab-content .tab-pane').forEach(p => {
                p.classList.remove('show', 'active');
                p.style.display = 'none';
            });
            
            const targetId = this.getAttribute('data-bs-target');
            const targetPane = document.querySelector(targetId);
            if(targetPane) {
                targetPane.style.display = 'block';
                setTimeout(() => targetPane.classList.add('show', 'active'), 10);
            }
            
            aplicarLogicaTabela();
        });
    });

    function toggleMenu() { 
        document.getElementById('sidebar').classList.toggle('show'); 
        document.getElementById('overlay').classList.toggle('show'); 
    }

    function derrubarUser(login) {
        if (confirm("Deseja realmente DERRUBAR a conexão atual do usuário '" + login + "'?")) {
            enviarAcaoMonitor('derrubar', login);
        }
    }

    function bloquearUser(login) {
        if (confirm("Aviso: Esta ação irá BLOQUEAR PERMANENTEMENTE o usuário '" + login + "'. Confirmar?")) {
            enviarAcaoMonitor('bloquear', login);
        }
    }

    function enviarAcaoMonitor(acao, login) {
        const formData = new FormData();
        formData.append('acao_monitor', acao);
        formData.append('user_login', login);

        fetch('monitor.php', { method: 'POST', body: formData })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'sucesso') {
                atualizarTabelaGhost(); 
            } else {
                alert("Erro: " + data.msg);
            }
        })
        .catch(err => console.error("Falha ao comunicar com o servidor: ", err));
    }

    // --- ABRIR INFO DA MÁQUINA ---
    function abrirInfoMaquina(login, ip, flags) {
        document.getElementById('modLogin').innerText = login;
        document.getElementById('modIp').innerText = ip;
        
        let flagsHtml = '';
        let fUpper = flags.toUpperCase();
        if (fUpper.includes('Z')) flagsHtml += '<div class="badge bg-danger d-block mb-1 p-2"><i class="fas fa-exclamation-circle"></i> Z - Reshare ou Multi-Telas</div>';
        if (fUpper.includes('R')) flagsHtml += '<div class="badge bg-info text-dark d-block mb-1 p-2">R - Puxando Cache Remoto</div>';
        if (fUpper.includes('C') || fUpper.includes('I')) flagsHtml += '<div class="badge bg-success d-block mb-1 p-2">C/I - Usando Cache Local Normal</div>';
        if (fUpper.includes('F')) flagsHtml += '<div class="badge bg-primary d-block mb-1 p-2">F - Tráfego Normal p/ Servidor</div>';
        if (fUpper.includes('B')) flagsHtml += '<div class="badge bg-dark d-block p-2">B - Cliente Bloqueado na CSP</div>';
        if (flagsHtml === '') flagsHtml = `<div class="badge bg-secondary p-2">Código bruto: ${flags}</div>`;
        
        document.getElementById('modFlags').innerHTML = flagsHtml;
        
        let myModal = new bootstrap.Modal(document.getElementById('modalMaquina'));
        myModal.show();
    }

    // --- NOVA SOLUÇÃO: ASSISTENTE RÁPIDO DE BLOQUEIO ---
    function prepararBloqueioIp(ip) {
        // Prepara a linha mágica que você viu no seu print
        let linhaPronta = `<default-deny-list>${ip}</default-deny-list>`;
        document.getElementById('modBloqueioLinha').innerText = linhaPronta;
        
        // Abre o modal do assistente
        let myModal = new bootstrap.Modal(document.getElementById('modalBloqueioManual'));
        myModal.show();
    }

    function copiarTexto(idElemento) {
        let texto = document.getElementById(idElemento).innerText;
        
        // Sistema de cópia blindado compatível com PC e Celular
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(texto).then(() => {
                alert("IP copiado! Agora é só clicar no botão 'Abrir Painel da CSP', colar e salvar.");
            });
        } else {
            let textArea = document.createElement("textarea");
            textArea.value = texto;
            textArea.style.position = "fixed";
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            try {
                document.execCommand('copy');
                alert("Copiado com sucesso! Cole na CSP.");
            } catch (err) {
                alert("Infelizmente seu navegador não deixou copiar sozinho. Selecione a linha amarela e copie manualmente!");
            }
            document.body.removeChild(textArea);
        }
    }

    function filtrarTabela() {
        paginaAtual = 1; 
        aplicarLogicaTabela();
    }

    function mudarLimite() {
        limiteExibicao = parseInt(document.getElementById('filtroQtd').value);
        paginaAtual = 1;
        aplicarLogicaTabela();
    }

    function mudarPagina(dir) {
        paginaAtual += dir;
        aplicarLogicaTabela();
    }

    function aplicarLogicaTabela() {
        const busca = document.getElementById('inputBusca').value.toLowerCase();
        
        let seletorRows = '#tabela-corpo tr.user-row';
        if (isAdminUser) {
            const isReshareAtiva = document.getElementById('tab-reshare') && document.getElementById('tab-reshare').style.display !== 'none';
            seletorRows = isReshareAtiva ? '#tabela-reshare-corpo tr.user-row' : '#tabela-corpo tr.user-row';
        }
        
        const rows = Array.from(document.querySelectorAll(seletorRows));
        
        let rowsFiltradas = rows.filter(row => {
            const texto = row.innerText.toLowerCase();
            return texto.includes(busca);
        });

        const total = rowsFiltradas.length;
        const totalPaginas = Math.ceil(total / limiteExibicao);
        if (paginaAtual > totalPaginas) paginaAtual = totalPaginas || 1;
        if (paginaAtual < 1) paginaAtual = 1;

        const inicio = (paginaAtual - 1) * limiteExibicao;
        const fim = inicio + limiteExibicao;

        rows.forEach(r => r.style.display = 'none');
        rowsFiltradas.slice(inicio, fim).forEach(r => r.style.display = '');

        document.getElementById('btnPrev').disabled = paginaAtual === 1;
        document.getElementById('btnNext').disabled = paginaAtual >= totalPaginas;
        document.getElementById('mostrando-count').innerText = rowsFiltradas.slice(inicio, fim).length;
        document.getElementById('total-count').innerText = total;
    }

    setInterval(() => {
        document.querySelectorAll('.tempo-online').forEach(e => {
            let s = parseInt(e.getAttribute('data-segundos')) + 1;
            e.setAttribute('data-segundos', s);
            let h = Math.floor(s/3600).toString().padStart(2,'0');
            let m = Math.floor((s%3600)/60).toString().padStart(2,'0');
            let sec = (s%60).toString().padStart(2,'0');
            e.innerText = h + ':' + m + ':' + sec;
        });
    }, 1000);

    // FUNÇÃO DA TABELA RESHARE ATUALIZADA PARA O NOVO BOTÃO
    function sincronizarAbaReshare() {
        if (!isAdminUser) return; // Se não for admin, não executa o sync da aba que não existe
        
        const tbodyReshare = document.getElementById('tabela-reshare-corpo');
        if(!tbodyReshare) return;
        
        tbodyReshare.innerHTML = '';
        
        const rows = document.querySelectorAll('#tabela-corpo tr.user-row');
        
        let loginCount = {};
        rows.forEach(row => {
            let login = row.getAttribute('data-login');
            if(login) loginCount[login] = (loginCount[login] || 0) + 1;
        });

        rows.forEach(row => {
            let login = row.getAttribute('data-login');
            let flags = row.getAttribute('data-flags') || '-';
            let ip = row.querySelector('.ip-text') ? row.querySelector('.ip-text').innerText : '-';
            let tempoHtml = row.querySelector('.tempo-online') ? row.querySelector('.tempo-online').outerHTML : '';
            let dono = row.querySelector('.dono-cel') ? row.querySelector('.dono-cel').innerText : '-';
            
            let isMultiLogin = loginCount[login] > 1;
            let fUpper = flags.toUpperCase();
            
            let isReshare = fUpper.includes('Z'); 
            let isBloqueado = fUpper.includes('B'); 
            
            let tr = document.createElement('tr');
            tr.className = 'user-row';
            let statusBadge = '';
            
            let flagsHtml = '';
            if (fUpper.includes('Z')) flagsHtml += '<span class="badge bg-danger ms-1" title="Z = Múltiplos sintonizadores">Z</span>';
            if (fUpper.includes('R')) flagsHtml += '<span class="badge bg-info text-dark ms-1" title="R = Cache Remoto">R</span>';
            if (fUpper.includes('C') || fUpper.includes('I')) flagsHtml += '<span class="badge bg-success ms-1" title="C/I = Cache Local">C/I</span>';
            if (fUpper.includes('F')) flagsHtml += '<span class="badge bg-primary ms-1" title="F = Normal">F</span>';
            if (fUpper.includes('B')) flagsHtml += '<span class="badge bg-dark ms-1" title="B = Bloqueado">B</span>';
            
            if (flagsHtml === '') flagsHtml = `<span class="badge bg-secondary">${flags}</span>`;

            if (isReshare || isMultiLogin) {
                tr.style.backgroundColor = 'rgba(255, 193, 7, 0.05)';
                statusBadge = '<span class="badge bg-danger px-2 py-1"><i class="fas fa-exclamation-triangle"></i> Verificar Reshare</span>';
            } else if (isBloqueado) {
                tr.style.backgroundColor = 'rgba(220, 53, 69, 0.05)';
                statusBadge = '<span class="badge bg-dark px-2 py-1"><i class="fas fa-ban"></i> Limite Excedido (B)</span>';
            } else {
                statusBadge = '<span class="badge bg-success px-2 py-1"><i class="fas fa-check-circle"></i> Normal</span>';
            }

            let safeLogin = login.replace(/'/g, "\\'");
            let safeIp = ip.replace(/'/g, "\\'");
            let safeFlags = flags.replace(/'/g, "\\'");
            
            // Aqui mudamos o botão vermelho para abrir o Assistente de Bloqueio Rápido
            let acoesHtml = `
                <button class="btn btn-sm btn-outline-info rounded-circle px-2 py-1 me-1" title="Info Máquina" onclick="abrirInfoMaquina('${safeLogin}', '${safeIp}', '${safeFlags}')"><i class="fas fa-desktop"></i></button>
                <button class="btn btn-sm btn-outline-danger rounded-circle px-2 py-1" title="Assistente de Bloqueio Rápido" onclick="prepararBloqueioIp('${safeIp}')"><i class="fas fa-ban"></i></button>
            `;

            tr.innerHTML = `
                <td class="text-info fw-bold">${login}</td>
                <td class="ip-text">${ip}</td>
                <td class="text-center text-secondary fw-bold small">${dono}</td>
                <td class="text-center">${flagsHtml}</td>
                <td class="text-center">${statusBadge} ${isMultiLogin ? '<span class="badge bg-warning text-dark ms-1">Multi-IP ('+loginCount[login]+')</span>' : ''}</td>
                <td class="text-center">${tempoHtml}</td>
                <td class="text-center btns-acao">${acoesHtml}</td>
            `;
            tbodyReshare.appendChild(tr);
        });
        
        if(rows.length === 0) {
            tbodyReshare.innerHTML = '<tr><td colspan="7" class="text-center py-5 text-muted">Nenhum receptor ativo no momento.</td></tr>';
        }
    }

    function atualizarTabelaGhost() {
        fetch('monitor.php?ajax=1')
        .then(r => r.text())
        .then(html => {
            let tempBody = document.createElement('tbody');
            tempBody.innerHTML = html;
            let currentBody = document.getElementById('tabela-corpo');
            
            if (html.includes('Nenhum receptor ativo') || html.includes('fa-exclamation-triangle')) {
                currentBody.innerHTML = html;
                document.getElementById('badge-online').innerText = '0 Dispositivos';
                if(isAdminUser) sincronizarAbaReshare();
                return;
            }

            let idsQueVieramAgora = [];

            tempBody.querySelectorAll('tr.user-row').forEach(newRow => {
                let rowId = newRow.getAttribute('id');
                if (!rowId) return;
                idsQueVieramAgora.push(rowId);
                
                let oldRow = document.getElementById(rowId);
                if (oldRow) {
                    oldRow.setAttribute('data-flags', newRow.getAttribute('data-flags'));
                    
                    let novoCanal = newRow.querySelector('.text-canal').innerHTML;
                    if (oldRow.querySelector('.text-canal').innerHTML !== novoCanal) {
                        oldRow.querySelector('.text-canal').innerHTML = novoCanal;
                    }
                    
                    let novaOp = newRow.querySelector('.text-operadora').innerHTML;
                    if (oldRow.querySelector('.text-operadora').innerHTML !== novaOp) {
                        oldRow.querySelector('.text-operadora').innerHTML = novaOp;
                    }

                    let novoTempo = newRow.querySelector('.tempo-online').innerHTML;
                    let novosSeg = newRow.querySelector('.tempo-online').getAttribute('data-segundos');
                    oldRow.querySelector('.tempo-online').innerHTML = novoTempo;
                    oldRow.querySelector('.tempo-online').setAttribute('data-segundos', novosSeg);
                } else {
                    currentBody.appendChild(newRow);
                }
            });

            currentBody.querySelectorAll('tr.user-row').forEach(oldRow => {
                if (!idsQueVieramAgora.includes(oldRow.getAttribute('id'))) {
                    oldRow.remove();
                }
            });

            let count = currentBody.querySelectorAll('tr.user-row').length;
            document.getElementById('badge-online').innerText = count + ' Dispositivos';
            
            if(isAdminUser) sincronizarAbaReshare(); 
            aplicarLogicaTabela(); 
            
        }).catch(err => console.log('Erro de background ocultado'));
    }

    setInterval(atualizarTabelaGhost, 5000);

    window.onload = function() {
        if(isAdminUser) sincronizarAbaReshare();
        aplicarLogicaTabela();
    };
</script>
</body>
</html>
