<?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)
// =========================================================================
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') && !empty($IP_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') {
            $connUser->prepare("UPDATE usuario SET bloqueado='sim' WHERE usuario=?")->execute([$user_login]);
            $connUser->prepare("UPDATE teste SET bloqueado='sim' WHERE usuario=?")->execute([$user_login]);
        }
        echo json_encode(['status' => 'sucesso']); exit;
    }
    echo json_encode(['status' => 'erro']); exit;
}

$online_users = [];
$revendedores_lista = [];

// --- 4. CONEXÃO CSP ---
if (!empty($IP_CSP) && !empty($PORTA_CSP)) {
    $auth = base64_encode("{$USUARIO_CSP}:{$SENHA_CSP}");
    $ch = curl_init("http://{$IP_CSP}:{$PORTA_CSP}/xmlHandler?command=proxy-users");
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Basic $auth", "Connection: close"]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $xml_bruto = trim(curl_exec($ch));
    curl_close($ch);

    if (!empty($xml_bruto)) {
        $xml = @simplexml_load_string($xml_bruto);
        if ($xml) {
            foreach ($xml->xpath('//user') as $u) {
                $login = (string)$u['name'];
                if (empty($login) || $login === '*') continue;
                $sessoes = $u->xpath('.//session');
                foreach ($sessoes as $f) {
                    $ip = (string)$f['host'] ?: (string)$f['ip'];
                    $canal = "Menu";
                    $srvs = $f->xpath('.//service');
                    if (!empty($srvs)) $canal = (string)$srvs[0]['name'];

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

                    if ($isAdmin || $dono_c === $usuarioLogado) {
                        if ($isAdmin && !in_array($dono_c, $revendedores_lista)) $revendedores_lista[] = $dono_c;
                        $online_users[] = [
                            'id' => md5($login . $ip), 'login' => $login, 'ip' => $ip, 
                            'canal' => $canal, 'dono' => $dono_c, 'flags' => (string)$f['flags'] ?: (string)$u['flags'],
                            'tempo' => (string)$f['duration']
                        ];
                    }
                }
            }
        }
    }
}
sort($revendedores_lista);

// AJAX GHOST REFRESH (Retorno em Modo Flexível Escuro/Claro)
if (isset($_GET['ajax'])) {
    foreach($online_users as $u) {
        echo '<tr class="user-row" id="usr_'.$u['id'].'" data-login="'.$u['login'].'" data-flags="'.$u['flags'].'">
            <td class="fw-bold" style="color: var(--text-color);"><span class="dot-online"></span>'.$u['login'].'</td>
            <td class="ip-text text-info fw-bold">'.$u['ip'].'</td>
            <td class="text-warning fw-bold">'.$u['canal'].'</td>
            <td class="text-center dono-cel" style="color: var(--text-color); opacity: 0.7;">'.$u['dono'].'</td>
            <td class="text-center text-success fw-bold">'.$u['tempo'].'</td>
            <td class="text-center">
                <button class="btn btn-sm btn-outline-warning shadow-sm rounded-3" title="Derrubar" onclick="derrubarUser(\''.$u['login'].'\')"><i class="fas fa-plug"></i></button>
                <button class="btn btn-sm btn-outline-danger shadow-sm rounded-3 ms-1" title="Bloquear" onclick="bloquearUser(\''.$u['login'].'\')"><i class="fas fa-lock"></i></button>
            </td>
        </tr>';
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>

<?php include 'tema_global.php'; ?>

    <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;
            --overlay-desk: rgba(0, 0, 0, 0.65); 
            --overlay-mob: rgba(0, 0, 0, 0.85); 
        }
        body.light-mode { 
            --bg-body: #f4f5f8; 
            --bg-card: #ffffff; 
            --text-color: #5e5873; 
            --border-color: #ebe9f1; 
            --overlay-desk: rgba(255, 255, 255, 0.1); 
            --overlay-mob: rgba(255, 255, 255, 0); 
        }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; margin: 0; overflow-x: hidden; }
        
        /* Sidebar Restourada Premium */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid var(--border-color); z-index: 1050; padding: 20px; overflow-y: auto; transition: transform 0.3s ease, box-shadow 0.3s ease; }
        .sidebar .nav-link { white-space: nowrap !important; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; color: #a6a6b7; padding: 12px 15px; border-radius: 8px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .sidebar .nav-link:hover, .sidebar .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .sidebar .nav-link i.fa-fw { margin-right: 8px; text-align: center; }
        .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 Flexbox (Para Rodapé Fixo) */
        .main-content { margin-left: 260px; transition: 0.3s; display: flex; flex-direction: column; min-height: 100vh; }
        
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--overlay-desk) 100%), var(--primary); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 30px; position: sticky; top:0; z-index: 1000; box-shadow: 0 2px 10px rgba(0,0,0,0.3);}
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; margin: 0; }
        
        /* Modificações Premium no Monitor */
        .card-monitor { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 12px; margin-bottom: 25px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); overflow: hidden; }
        
        /* Menu Abas (Tabs) Premium */
        .nav-pills-custom { background: rgba(0,0,0,0.05); padding: 8px; border-radius: 12px; gap: 8px; display: flex; flex-wrap: wrap; margin: 15px; border: 1px solid var(--border-color);}
        .nav-pills-custom .nav-link { color: var(--text-color); border-radius: 8px; font-weight: 600; padding: 12px 20px; transition: 0.3s; flex: 1; text-align: center; border: none; background: transparent; cursor: pointer;}
        .nav-pills-custom .nav-link:hover { background: rgba(115, 103, 240, 0.1); }
        .nav-pills-custom .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 10px rgba(0,0,0,0.3); }

        /* Tabela Dinâmica e Inteligente */
        .table-custom { width: 100%; margin-bottom: 0; border-collapse: separate; border-spacing: 0; background: transparent !important; }
        .table-custom th { background-color: rgba(0,0,0,0.02) !important; border-bottom: 1px solid var(--border-color) !important; color: #a6a6b7 !important; font-size: 0.8rem; text-transform: uppercase; font-weight: 700; padding: 15px; white-space: nowrap; }
        .table-custom td { background-color: var(--bg-card) !important; border-bottom: 1px solid var(--border-color) !important; color: var(--text-color) !important; vertical-align: middle; padding: 15px; font-size: 0.95rem; }
        .table-custom tbody tr:hover td { background-color: rgba(115, 103, 240, 0.05) !important; }

        .dot-online { width: 10px; height: 10px; background: #28c76f; border-radius: 50%; display: inline-block; margin-right: 8px; box-shadow: 0 0 8px #28c76f; animation: pulse 2s infinite; }
        @keyframes pulse { 0% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.2); opacity: 0.7; } 100% { transform: scale(1); opacity: 1; } }
        
        .controls-wrapper { padding: 15px; display: flex; flex-wrap: wrap; gap: 10px; border-bottom: 1px solid var(--border-color); background: rgba(0,0,0,0.02); }
        .search-container { position: relative; flex: 1; min-width: 200px; }
        .search-container input { background: rgba(0,0,0,0.1) !important; border: 1px solid var(--border-color) !important; color: var(--text-color) !important; border-radius: 8px; padding: 10px 15px 10px 40px; width: 100%; transition: 0.2s;}
        .search-container input:focus { border-color: var(--primary) !important; outline: none; }
        .search-container i { position: absolute; left: 15px; top: 14px; color: var(--primary); }
        .filter-select { background: rgba(0,0,0,0.1) !important; border: 1px solid var(--border-color) !important; color: var(--text-color) !important; border-radius: 8px; padding: 10px 15px; flex: 1; min-width: 150px; cursor: pointer; transition: 0.2s;}
        .filter-select:focus { border-color: var(--primary) !important; outline: none; }

        @media (max-width: 992px) {
            .sidebar { transform: translateX(-100%); box-shadow: none; z-index: 1050; } 
            .sidebar.show { transform: translateX(0); box-shadow: 5px 0 30px rgba(0,0,0,0.9); } 
            .main-content { margin-left: 0; width: 100%;}
            .mobile-toggle { display: block !important; margin-right: 15px; } 
            .top-header { flex-direction: row; padding: 15px 20px; background: linear-gradient(var(--overlay-mob), var(--overlay-mob)), var(--primary); border-bottom: none; }
            .overlay.show { display: block; }
            .controls-wrapper { flex-direction: column; }
            .nav-pills-custom { flex-direction: column; }
            .nav-pills-custom .nav-link { width: 100%; }
        }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; cursor: pointer; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7); z-index: 1040; backdrop-filter: blur(3px); }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>
<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<main class="main-content d-flex flex-column min-vh-100">
    <div class="top-header">
        <div class="d-flex align-items-center">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <h5 class="header-title m-0"><i class="fas fa-tv me-2 d-none d-md-inline-block"></i> MONITORAMENTO AO VIVO</h5>
        </div>
        <button onclick="location.reload()" class="btn btn-outline-light rounded-pill fw-bold shadow-sm px-4"><i class="fas fa-sync-alt me-1"></i> REFRESH</button>
    </div>

    <div class="container-fluid px-3 px-md-4 flex-grow-1">
        
        <div class="card-monitor shadow-sm">
            
            <ul class="nav nav-pills-custom" id="monitorTabs">
                <li class="nav-item"><button class="nav-link active" onclick="trocarAba('geral')"><i class="fas fa-globe me-2"></i> Monitor Geral</button></li>
                <?php if ($isAdmin): ?>
                    <li class="nav-item"><button class="nav-link text-warning" onclick="trocarAba('reshare')"><i class="fas fa-exclamation-triangle me-2"></i> Controle Reshare</button></li>
                <?php endif; ?>
            </ul>

            <div class="controls-wrapper">
                <div class="search-container"><i class="fas fa-search"></i><input type="text" id="inputBusca" placeholder="Pesquisar cliente ou revenda..." onkeyup="filtrarTabela()"></div>
                <?php if ($isAdmin): ?>
                    <select id="filtroRevenda" class="filter-select" onchange="filtrarTabela()">
                        <option value="todos">Todos os Revendedores</option>
                        <?php foreach($revendedores_lista as $rev): ?><option value="<?= $rev ?>"><?= $rev ?></option><?php endforeach; ?>
                    </select>
                <?php endif; ?>
                <select id="filtroQtd" class="filter-select" onchange="mudarLimite()">
                    <option value="10">Exibir 10 por pág.</option>
                    <option value="50">Exibir 50 por pág.</option>
                    <option value="100">Exibir 100 por pág.</option>
                    <option value="999">Exibir Tudo</option>
                </select>
                <div class="d-flex align-items-center justify-content-center bg-success bg-opacity-10 text-success border border-success rounded px-4 fw-bold shadow-sm" style="white-space: nowrap;">
                    <i class="fas fa-users me-2"></i> <span id="badge-count"><?= count($online_users) ?> Online</span>
                </div>
            </div>

            <div id="aba-geral">
                <div class="table-responsive">
                    <table class="table-custom w-100 align-middle">
                        <thead>
                            <tr>
                                <th class="ps-4">USUÁRIO</th>
                                <th>IP</th>
                                <th>CANAL</th>
                                <th class="text-center">REVENDA</th>
                                <th class="text-center">TEMPO</th>
                                <th class="text-center pe-4">AÇÕES</th>
                            </tr>
                        </thead>
                        <tbody id="tabela-corpo">
                            <?php if(empty($online_users)): ?>
                                <tr><td colspan="6" class="text-center text-muted py-5"><i class="fas fa-tv fs-2 mb-2 opacity-50"></i><br>Nenhum cliente online no momento.</td></tr>
                            <?php else: foreach($online_users as $u): ?>
                            <tr class="user-row" data-login="<?= htmlspecialchars($u['login']) ?>" data-flags="<?= htmlspecialchars($u['flags']) ?>">
                                <td class="ps-4 fw-bold" style="color: var(--text-color);"><span class="dot-online"></span><?= htmlspecialchars($u['login']) ?></td>
                                <td class="ip-text text-info fw-bold"><?= htmlspecialchars($u['ip']) ?></td>
                                <td class="text-warning fw-bold opacity-75"><?= htmlspecialchars($u['canal']) ?></td>
                                <td class="text-center dono-cel" style="color: var(--text-color); opacity: 0.7;"><?= htmlspecialchars($u['dono']) ?></td>
                                <td class="text-center text-success fw-bold"><?= htmlspecialchars($u['tempo']) ?></td>
                                <td class="text-center pe-4">
                                    <div class="d-flex gap-2 justify-content-center">
                                        <button class="btn btn-sm btn-outline-warning shadow-sm rounded-3" title="Derrubar Conexão" onclick="derrubarUser('<?= htmlspecialchars($u['login']) ?>')"><i class="fas fa-plug"></i></button>
                                        <button class="btn btn-sm btn-outline-danger shadow-sm rounded-3" title="Bloquear Cliente" onclick="bloquearUser('<?= htmlspecialchars($u['login']) ?>')"><i class="fas fa-lock"></i></button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div id="aba-reshare" style="display:none;">
                <div class="table-responsive">
                    <table class="table-custom w-100 align-middle">
                        <thead>
                            <tr>
                                <th class="ps-4">USUÁRIO</th>
                                <th>IP</th>
                                <th class="text-center">REVENDA</th>
                                <th class="text-center">FLAGS</th>
                                <th class="text-center">ALERTA</th>
                                <th class="text-center pe-4">AÇÕES</th>
                            </tr>
                        </thead>
                        <tbody id="tabela-reshare-corpo"></tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>
    
    <div class="mt-auto w-100">
        <?php include 'rodape.php'; ?>
    </div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    let abaAtual = 'geral';

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

    function trocarAba(aba) {
        abaAtual = aba;
        document.querySelectorAll('#monitorTabs .nav-link').forEach(b => b.classList.remove('active'));
        event.currentTarget.classList.add('active');

        if(aba === 'geral') {
            document.getElementById('aba-geral').style.display = 'block';
            document.getElementById('aba-reshare').style.display = 'none';
        } else {
            document.getElementById('aba-geral').style.display = 'none';
            document.getElementById('aba-reshare').style.display = 'block';
            sincronizarReshare();
        }
        filtrarTabela();
    }

    function sincronizarReshare() {
        const reshareBody = document.getElementById('tabela-reshare-corpo');
        reshareBody.innerHTML = '';
        const logins = {};
        const rows = document.querySelectorAll('#tabela-corpo tr.user-row');
        
        rows.forEach(r => {
            let log = r.getAttribute('data-login');
            logins[log] = (logins[log] || 0) + 1;
        });

        rows.forEach(r => {
            let log = r.getAttribute('data-login');
            let flags = r.getAttribute('data-flags').toUpperCase();
            if (logins[log] > 1 || flags.includes('Z')) {
                let clone = r.cloneNode(true);
                // Ajustar colunas para o layout de Reshare
                let tds = clone.querySelectorAll('td');
                let ip = tds[1].innerText;
                let revenda = tds[3].innerText;
                let acoes = tds[5].innerHTML;

                clone.innerHTML = `
                    <td class="ps-4 fw-bold text-info">${log}</td>
                    <td class="text-warning fw-bold">${ip}</td>
                    <td class="text-center" style="color: var(--text-color); opacity: 0.7;">${revenda}</td>
                    <td class="text-center"><span class="badge bg-secondary border border-secondary shadow-sm">${flags}</span></td>
                    <td class="text-center"><span class="badge bg-danger bg-opacity-10 text-danger border border-danger px-2 py-1">ALERTA RESHARE</span></td>
                    <td class="text-center pe-4">${acoes}</td>
                `;
                reshareBody.appendChild(clone);
            }
        });
        if(reshareBody.innerHTML === '') reshareBody.innerHTML = '<tr><td colspan="6" class="text-center p-5 text-muted"><i class="fas fa-shield-alt fs-2 mb-2 opacity-50"></i><br>Nenhum reshare detectado. Sistema Limpo!</td></tr>';
    }

    function filtrarTabela() {
        let busca = document.getElementById('inputBusca').value.toLowerCase();
        let rev = document.getElementById('filtroRevenda') ? document.getElementById('filtroRevenda').value : 'todos';
        let limite = parseInt(document.getElementById('filtroQtd').value);
        
        let seletor = abaAtual === 'geral' ? '#tabela-corpo tr.user-row' : '#tabela-reshare-corpo tr';
        let rows = Array.from(document.querySelectorAll(seletor));

        let filtradas = rows.filter(r => {
            let txt = r.innerText.toLowerCase();
            let donoTd = r.querySelector('.dono-cel');
            // No modo reshare a coluna dona é a 3 (index 2)
            let dono = donoTd ? donoTd.innerText.trim() : (r.querySelectorAll('td')[2] ? r.querySelectorAll('td')[2].innerText.trim() : 'Admin');
            return txt.includes(busca) && (rev === 'todos' || dono === rev);
        });

        rows.forEach(r => r.style.display = 'none');
        filtradas.slice(0, limite).forEach(r => r.style.display = '');
    }

    function mudarLimite() { filtrarTabela(); }
    
    function derrubarUser(l) { if(confirm("Deseja realmente derrubar o cliente "+l+"?")) acao('derrubar', l); }
    function bloquearUser(l) { if(confirm("Deseja bloquear permanentemente o cliente "+l+"?")) acao('bloquear', l); }
    
    function acao(t, l) {
        let f = new FormData(); f.append('acao_monitor', t); f.append('user_login', l);
        fetch('monitor.php', {method:'POST', body:f}).then(()=>location.reload());
    }

    // Refresh Ajax
    setInterval(() => {
        fetch('monitor.php?ajax=1').then(r => r.text()).then(html => {
            // Se a tela não retornar erro, insere os dados
            if (html.trim() !== "") {
                document.getElementById('tabela-corpo').innerHTML = html;
                if(abaAtual === 'reshare') sincronizarReshare();
                filtrarTabela();
            } else {
                document.getElementById('tabela-corpo').innerHTML = '<tr><td colspan="6" class="text-center text-muted py-5"><i class="fas fa-tv fs-2 mb-2 opacity-50"></i><br>Nenhum cliente online no momento.</td></tr>';
            }
        });
    }, 15000);

    window.onload = filtrarTabela;
</script>
</body>
</html>
