<?php
session_start();
require_once 'conexao.php';

// --- FORÇAR UTF-8 PARA SALVAR EMOJIS CORRETAMENTE ---
try { 
    $connGeral->exec("SET NAMES utf8mb4"); 
    $connUser->exec("SET NAMES utf8mb4"); 
} catch (Exception $e) { }

// --- CRIAR COLUNAS CASO NÃO EXISTAM (SISTEMA DE SEGURANÇA SILENCIOSO) ---
try { $connUser->exec("ALTER TABLE rev ADD COLUMN valor_claro DECIMAL(10,2) DEFAULT 0"); } catch (Exception $e) { }
try { $connUser->exec("ALTER TABLE rev ADD COLUMN valor_net DECIMAL(10,2) DEFAULT 0"); } catch (Exception $e) { }
try { $connUser->exec("ALTER TABLE rev ADD COLUMN nome VARCHAR(255) DEFAULT ''"); } catch (Exception $e) { }
try { $connUser->exec("ALTER TABLE rev ADD COLUMN whatsapp VARCHAR(20) DEFAULT NULL"); } catch (Exception $e) { }

// --- CRIAR TABELA DE MENSAGENS EXCLUSIVA PARA O ADMIN (SILENCIOSO) ---
try {
    $connGeral->exec("CREATE TABLE IF NOT EXISTS config_msg_rev (
        id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
        msg_novo TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
        msg_cobranca TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
        cron_hora VARCHAR(5) DEFAULT '10:00',
        cron_status VARCHAR(10) DEFAULT 'ativo',
        ultima_execucao DATE DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");
    
    $connGeral->exec("ALTER TABLE config_msg_rev CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    
    try { $connGeral->exec("ALTER TABLE config_msg_rev ADD COLUMN cron_hora VARCHAR(5) DEFAULT '10:00'"); } catch (Exception $e) {}
    try { $connGeral->exec("ALTER TABLE config_msg_rev ADD COLUMN cron_status VARCHAR(10) DEFAULT 'ativo'"); } catch (Exception $e) {}
    try { $connGeral->exec("ALTER TABLE config_msg_rev ADD COLUMN ultima_execucao DATE DEFAULT NULL"); } catch (Exception $e) {}
    try { $connGeral->exec("ALTER TABLE config_msg_rev ADD COLUMN cpf_admin VARCHAR(20) DEFAULT ''"); } catch (Exception $e) {} // CPF MESTRE

    $connGeral->exec("INSERT IGNORE INTO config_msg_rev (id, msg_novo, msg_cobranca, cron_hora, cron_status) VALUES (1, '*🎉 BOAS VINDAS AO NOSSO SERVIDOR! 🎉*\\n\\n*🚀 ACESSO REVENDA*\\n\\n👤 *User:* {usuario}\\n🔑 *Senha:* {senha}\\n🔗 *Painel:* {link_painel}\\n📅 *Venc:* {vencimento}\\n\\n_Guarde esses dados com segurança!_', '🚨 *Aviso de Vencimento!* 🚨\\n\\nOlá {nome}, o seu painel de revenda vence em *{dias} dias*!\\n\\nVocê tem {qtd_ativos} clientes e a sua fatura gerada é de *{total_pagar}*\\n\\nPague sua fatura clicando no link abaixo:\\n{link_painel}/servidor/fatura.php?u={usuario}\\n\\nRenove com antecedência para evitar bloqueios.', '10:00', 'ativo')");
} catch (Exception $e) { }
// ----------------------------------------------------------------------

// --- 1. TRAVA DE SEGURANÇA TOTAL (KILL SWITCH) ---
if (!isset($_SESSION['logado'])) { 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 && ($me['bloqueado'] == 'sim' || ((int)$me['data_premio'] > 0 && strtotime(date('Y-m-d 23:59:59', (int)$me['data_premio'])) < time()))) {
        die("<!DOCTYPE html><html lang='pt-br'><head><meta charset='UTF-8'><title>Acesso Negado</title><link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'><style>body{background:#151521;color:#fff;display:flex;align-items:center;justify-content:center;height:100vh;text-align:center;}</style></head><body><div><h1 class='text-danger fw-bold' style='font-size: 4rem;'>🚫</h1><h2 class='fw-bold text-uppercase'>ACESSO SUSPENSO</h2><a href='sair.php' class='btn btn-outline-light mt-4 px-5'>Sair</a></div></body></html>");
    }
}

// --- 2. CONFIGURAÇÕES VISUAIS ---
$nomePainel = "IPTV PANEL"; $corPrimaria = "#7367f0"; 
try {
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($conf) {
        $nomePainel = $conf['NomePainel'] ?? $nomePainel;
        $corPrimaria = $conf['TemaPainel'] ?? $corPrimaria;
    }
} catch (Exception $e) { }

$total_msg_nao_lidas = 0;
$confMsgRev = [];
try {
    $stmtMsg = $connUser->prepare("SELECT COUNT(*) FROM chamados_suporte WHERE destinatario = ? AND lida = 'nao'");
    $stmtMsg->execute([$usuarioLogado]);
    $total_msg_nao_lidas = $stmtMsg->fetchColumn();
    
    if ($isAdmin) {
        $confMsgRev = $connGeral->query("SELECT * FROM config_msg_rev WHERE id=1")->fetch(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) { }

$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
$urlPainel = $protocol . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);

try {
    $perfis_sistema = $connGeral->query("SELECT id, nome FROM perfil WHERE (bloqueado IS NULL OR bloqueado != 'sim') ORDER BY nome ASC")->fetchAll(PDO::FETCH_ASSOC);
    $mapa_perfis = [];
    foreach($perfis_sistema as $ps) { $mapa_perfis[$ps['id']] = $ps; }
} catch (Exception $e) { $perfis_sistema = []; $mapa_perfis = []; }

function enviarZapPainel($numero, $mensagem, $connGeral, $origem_acao, $confAPI) {
    try {
        if(!$confAPI || empty($confAPI['api_url']) || empty($numero) || empty($confAPI['instancia'])) return false;
        $numero_limpo = preg_replace("/[^0-9]/", "", $numero);
        if (strlen($numero_limpo) == 10 || strlen($numero_limpo) == 11) { $numero_limpo = "55" . $numero_limpo; }
        if (strlen($numero_limpo) < 12) return false;
        
        $url = rtrim($confAPI['api_url'], '/') . "/message/sendText/" . trim($confAPI['instancia']);
        
        $curl = curl_init();
        curl_setopt_array($curl, array(
          CURLOPT_URL => $url,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 10, 
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS => json_encode(["number" => $numero_limpo, "options" => ["delay" => 0, "presence" => "composing", "linkPreview" => false], "textMessage" => ["text" => $mensagem]]),
          CURLOPT_SSL_VERIFYHOST => 0,
          CURLOPT_SSL_VERIFYPEER => 0,
          CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'apikey: ' . trim($confAPI['api_key'])],
        ));
        
        $resposta = curl_exec($curl); 
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $erro_curl = curl_error($curl);
        curl_close($curl);
        
        $status_log = ($httpcode >= 200 && $httpcode < 300) ? 'sucesso' : 'falha';
        $resumo_log = "Nº: $numero_limpo | HTTP: $httpcode";
        if($erro_curl) $resumo_log .= " | CurlErro: $erro_curl";
        
        $origem_completa = "Painel (" . $confAPI['usuario'] . " - " . $origem_acao . ")";
        $stmtLog = $connGeral->prepare("INSERT INTO log_disparos (origem, resumo, status) VALUES (?, ?, ?)");
        $stmtLog->execute([$origem_completa, $resumo_log, $status_log]);
        return ($status_log === 'sucesso');
    } catch (Exception $e) { return false; }
}

$msg = ""; $msg_tipo = ""; $texto_zap = ""; $redirecionar_limpo = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $acao = $_POST['acao'] ?? '';
        $id_rev = (int)($_POST['id_rev'] ?? 0);
        $ids_massa = $_POST['ids_massa'] ?? []; 
        $filtroSeguranca = $isAdmin ? "" : " AND CadUser = '$usuarioLogado'";

        $stmtConfPost = $connGeral->prepare("SELECT * FROM config_api_whatsapp WHERE usuario = ? LIMIT 1");
        $stmtConfPost->execute([$usuarioLogado]);
        $confZap = $stmtConfPost->fetch(PDO::FETCH_ASSOC);

        // SALVA AS MSGS E O CPF MESTRE
        if ($acao === 'salvar_msg_rev' && $isAdmin) {
            $m_novo = $_POST['msg_novo'];
            $m_cob = $_POST['msg_cobranca'];
            $c_hora = $_POST['cron_hora'];
            $c_status = $_POST['cron_status'];
            $cpf_admin = preg_replace('/[^0-9]/', '', $_POST['cpf_admin'] ?? '');
            
            $connGeral->prepare("UPDATE config_msg_rev SET msg_novo=?, msg_cobranca=?, cron_hora=?, cron_status=?, cpf_admin=?, ultima_execucao=NULL WHERE id=1")->execute([$m_novo, $m_cob, $c_hora, $c_status, $cpf_admin]);
            $msg = "Configurações e CPF salvos com sucesso!"; $msg_tipo = "success"; $redirecionar_limpo = true;
        }

        if (!empty($ids_massa)) {
            $lista_ids = implode(',', array_map('intval', $ids_massa));
            if ($acao === 'vencimento_massa') {
                $nova_data = strtotime($_POST['data_massa']);
                if($nova_data > 0) {
                    $connUser->query("UPDATE rev SET data_premio = '$nova_data' WHERE id IN ($lista_ids) $filtroSeguranca");
                    $msg = "Vencimento de " . count($ids_massa) . " revendedores alterado!"; $msg_tipo = "success"; $redirecionar_limpo = true;
                }
            } elseif ($acao === 'perfil_massa') {
                $novo_perfil = $_POST['perfil_massa'];
                $connUser->query("UPDATE rev SET perfil = '$novo_perfil' WHERE id IN ($lista_ids) $filtroSeguranca");
                $msg = "Perfil de " . count($ids_massa) . " revendedores alterado!"; $msg_tipo = "success"; $redirecionar_limpo = true;
            } elseif ($acao === 'bloquear_massa') {
                $connUser->query("UPDATE rev SET bloqueado = 'sim' WHERE id IN ($lista_ids) $filtroSeguranca");
                $msg = count($ids_massa) . " revendedores bloqueados!"; $msg_tipo = "warning"; $redirecionar_limpo = true;
            } elseif ($acao === 'desbloquear_massa') {
                $connUser->query("UPDATE rev SET bloqueado = 'nao' WHERE id IN ($lista_ids) $filtroSeguranca");
                $msg = count($ids_massa) . " revendedores desbloqueados!"; $msg_tipo = "success"; $redirecionar_limpo = true;
            } elseif ($acao === 'excluir_massa') {
                $connUser->query("DELETE FROM rev WHERE id IN ($lista_ids) $filtroSeguranca");
                $msg = count($ids_massa) . " revendedores removidos!"; $msg_tipo = "danger"; $redirecionar_limpo = true;
            }
        }

        if ($acao === 'criar' || $acao === 'editar') {
            $nome_rev = trim($_POST['nome'] ?? '');
            $user = trim($_POST['usuario']); $pass = trim($_POST['senha']); $limite = (int)$_POST['limite'];
            $venc_ts = (!empty($_POST['data_premio'])) ? strtotime($_POST['data_premio']) : 0;
            $perfis_salvar = !empty($_POST['perfis']) ? implode(',', $_POST['perfis']) : '';
            $whatsapp = trim($_POST['whatsapp'] ?? '');
            
            $valor_claro = !empty($_POST['valor_claro']) ? str_replace(',', '.', $_POST['valor_claro']) : 0;
            $valor_net = !empty($_POST['valor_net']) ? str_replace(',', '.', $_POST['valor_net']) : 0;

            if ($acao === 'criar') {
                $check = $connUser->prepare("SELECT id FROM rev WHERE usuario = ? UNION SELECT id FROM usuario WHERE usuario = ?");
                $check->execute([$user, $user]);
                if($check->rowCount() > 0){
                    $msg = "O usuário '$user' já existe!"; $msg_tipo = "warning";
                } else {
                    $sql = "INSERT INTO rev (nome, usuario, senha, LimiteUser, data_premio, data_cadastro, CadUser, perfil, bloqueado, inativo, valor_claro, valor_net, whatsapp) VALUES (?, ?, ?, ?, ?, NOW(), ?, ?, 'nao', 'nao', ?, ?, ?)";
                    $connUser->prepare($sql)->execute([$nome_rev, $user, $pass, $limite, $venc_ts, $usuarioLogado, $perfis_salvar, $valor_claro, $valor_net, $whatsapp]);
                    
                    $venc_str = ($venc_ts > 0) ? date('d/m/Y', $venc_ts) : 'Ilimitado';
                    if ($isAdmin && !empty($confMsgRev['msg_novo'])) {
                        $texto_zap = str_replace(['{nome}', '{usuario}', '{senha}', '{vencimento}', '{limite}', '{link_painel}', '{qtd_ativos}', '{total_pagar}'], [$nome_rev, $user, $pass, $venc_str, $limite, $urlPainel, '0', 'R$ 0,00'], $confMsgRev['msg_novo']);
                    } else {
                        $texto_zap = "*🎉 BOAS VINDAS AO NOSSO SERVIDOR! 🎉*\n\n*🚀 ACESSO REVENDA CRIADO COM SUCESSO*\n\n👤 *User:* $user\n🔑 *Senha:* $pass\n🔗 *Painel:* $urlPainel\n📅 *Vencimento:* $venc_str\n\n_Guarde esses dados com segurança!_";
                    }
                    
                    if(!empty($whatsapp) && $confZap) { enviarZapPainel($whatsapp, $texto_zap, $connGeral, "Nova Revenda", $confZap); }
                    $msg = "Revendedor criado!"; $msg_tipo = "success"; $redirecionar_limpo = true;
                }
            } else {
                $sql = "UPDATE rev SET nome=?, usuario=?, senha=?, LimiteUser=?, data_premio=?, perfil=?, valor_claro=?, valor_net=?, whatsapp=? WHERE id=? $filtroSeguranca";
                $connUser->prepare($sql)->execute([$nome_rev, $user, $pass, $limite, $venc_ts, $perfis_salvar, $valor_claro, $valor_net, $whatsapp, $id_rev]);
                $msg = "Dados atualizados!"; $msg_tipo = "primary"; $redirecionar_limpo = true;
            }
        }

        if ($acao === 'alternar_bloqueio') {
            $status_atual = $_POST['status_atual'];
            $novo_status = ($status_atual == 'sim') ? 'nao' : 'sim';
            $st = $connUser->prepare("SELECT usuario FROM rev WHERE id=? LIMIT 1");
            $st->execute([$id_rev]);
            $targetUser = $st->fetchColumn();

            if ($targetUser) {
                $targetUser = trim($targetUser);
                $connUser->prepare("UPDATE rev SET bloqueado=? WHERE id=?")->execute([$novo_status, $id_rev]);
                $connUser->prepare("UPDATE usuario SET bloqueado=? WHERE CadUser = ?")->execute([$novo_status, $targetUser]);
                $connUser->prepare("UPDATE teste SET bloqueado=? WHERE CadUser = ?")->execute([$novo_status, $targetUser]);
                $connUser->prepare("UPDATE rev SET bloqueado=? WHERE CadUser = ?")->execute([$novo_status, $targetUser]);
                $connUser->prepare("UPDATE usuario SET bloqueado=? WHERE CadUser IN (SELECT usuario FROM rev WHERE CadUser = ?)")->execute([$novo_status, $targetUser]);
                $connUser->prepare("UPDATE teste SET bloqueado=? WHERE CadUser IN (SELECT usuario FROM rev WHERE CadUser = ?)")->execute([$novo_status, $targetUser]);
                
                $msg = ($novo_status == 'sim') ? "TODA A REDE SUSPENSA!" : "REDE LIBERADA!";
                $msg_tipo = ($novo_status == 'sim') ? "danger" : "success";
                $redirecionar_limpo = true;
            }
        }
        if ($acao === 'excluir') {
            $connUser->prepare("DELETE FROM rev WHERE id=? $filtroSeguranca")->execute([$id_rev]);
            $msg = "Removido!"; $msg_tipo = "danger"; $redirecionar_limpo = true;
        }
        
        if ($redirecionar_limpo && empty($texto_zap)) {
            $_SESSION['temp_msg'] = $msg;
            $_SESSION['temp_msg_tipo'] = $msg_tipo;
            header("Location: revendedores.php"); exit;
        }
    } catch (Exception $e) { $msg = "Erro: " . $e->getMessage(); $msg_tipo = "danger"; }
}

if (isset($_SESSION['temp_msg'])) {
    $msg = $_SESSION['temp_msg']; $msg_tipo = $_SESSION['temp_msg_tipo'];
    unset($_SESSION['temp_msg']); unset($_SESSION['temp_msg_tipo']);
}

$limit_pg = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$pg = isset($_GET['pagina']) ? (int)$_GET['pagina'] : 1;
$offset = ($pg - 1) * $limit_pg;
$busca = trim($_GET['busca'] ?? '');
$where = " WHERE 1=1";
if (!$isAdmin) $where .= " AND CadUser = '$usuarioLogado'";
if ($busca) $where .= " AND (usuario LIKE '%$busca%' OR nome LIKE '%$busca%')";
$revendas = $connUser->query("SELECT * FROM rev $where ORDER BY id DESC LIMIT $limit_pg OFFSET $offset")->fetchAll();

if (isset($_GET['ajax']) && $_GET['ajax'] == 'true') {
    if (count($revendas) == 0) {
        echo "<tr><td colspan='11' class='text-center py-4 text-white-50'>Nenhum revendedor encontrado.</td></tr>";
        exit;
    }
    foreach ($revendas as $r) {
        $venc_ts = (int)$r['data_premio'];
        $isBloq = ($r['bloqueado'] == 'sim');
        $isVenc = ($venc_ts > 0 && strtotime(date('Y-m-d 23:59:59', $venc_ts)) < time());
        $venc_fmt_input = ($venc_ts > 0) ? date('Y-m-d', $venc_ts) : '';
        $venc_fmt_list = ($venc_ts > 0) ? date('d/m/Y', $venc_ts) : '---';
        $data_venc_br = ($venc_ts > 0) ? date('d/m/Y', $venc_ts) : 'Ilimitado';
        $status_text = $isBloq ? 'BLOQUEADO' : ($isVenc ? 'VENCIDO' : 'ATIVO');
        
        $nomeRev = trim($r['usuario']);
        $agora = time();
        $sql_conta_cli = "SELECT perfil FROM usuario WHERE CadUser = ? AND bloqueado != 'sim' AND IF(data_premio REGEXP '^[0-9]+$', CAST(data_premio AS UNSIGNED), UNIX_TIMESTAMP(STR_TO_DATE(data_premio, '%Y-%m-%d'))) > ?";
        $stmt_conta = $connUser->prepare($sql_conta_cli);
        $stmt_conta->execute([$nomeRev, $agora]);
        $clientes_ativos = $stmt_conta->fetchAll(PDO::FETCH_ASSOC);
        
        $qtd_ativos = count($clientes_ativos);
        $total_fatura = 0;
        foreach($clientes_ativos as $cli) {
            $p_info = $mapa_perfis[$cli['perfil']] ?? ['nome' => ''];
            $p_nome = mb_strtolower($p_info['nome']);
            if (strpos($p_nome, 'net') !== false) {
                $total_fatura += (float)$r['valor_net'];
            } else {
                $total_fatura += (float)$r['valor_claro'];
            }
        }
        $total_pagar_fmt = number_format($total_fatura, 2, ',', '.');

        $badge_venc = "<span class='badge ".($isVenc ? 'bg-danger' : 'bg-success')." p-2'>{$venc_fmt_list}</span>";
        if($isVenc) $badge_venc .= "<br><small class='text-danger fw-bold'>VENCIDO</small>";

        // --- SISTEMA DE PERFIS (Correção de Visualização) ---
        $perfis_array = [];
        if(!empty($r['perfil'])){
            $tags = explode(',', $r['perfil']);
            foreach($tags as $t) if(trim($t) != "") $perfis_array[] = trim($t);
        }
        
        if(count($perfis_array) > 0) {
            $perfis_html = "";
            foreach($perfis_array as $t) {
                $perfis_html .= "<span class='badge-perfil'>".htmlspecialchars($t)."</span>";
            }
            // Formato com traços ex: Claro HD - Net Brasilia - Net Rio
            $perfis_card_text = htmlspecialchars(implode(' - ', $perfis_array));
        } else {
            $perfis_html = "<small class='text-muted'>Nenhum</small>";
            $perfis_card_text = "Nenhum";
        }
        // ---------------------------------------------------

        $icon_bloq = $isBloq ? 'fa-lock-open' : 'fa-lock';
        
        // Passar os dados para o JS usando data attributes para não bugar aspas duplas
        $json_r = htmlspecialchars(json_encode($r), ENT_QUOTES, 'UTF-8');
        
        echo "
        <tr>
            <td class='text-center td-checkbox'><input type='checkbox' name='ids_massa[]' value='{$r['id']}' class='form-check-input check-item' style='cursor:pointer;'></td>
            <td class='text-white fw-bold traditional-content'>".(!empty($r['nome']) ? htmlspecialchars($r['nome']) : "<span class='text-muted small'>---</span>")."</td>
            <td class='ps-3 traditional-content'><div class='d-flex align-items-center'><span class='status-dot ".($isBloq || $isVenc ? 'offline' : 'online')."'></span><div class='nome-destaque ".($isBloq || $isVenc ? 'text-danger' : '')."'>".htmlspecialchars($r['usuario'])."</div></div></td>
            <td class='text-center text-white-50 small traditional-content'>".htmlspecialchars($r['senha'])."</td>
            <td class='text-center text-white-50 small traditional-content'>".htmlspecialchars($r['whatsapp'] ?? '')."</td>
            <td class='text-center traditional-content'><span class='badge bg-primary px-3'>{$r['LimiteUser']}</span></td>
            <td class='text-center traditional-content'><span class='badge bg-success px-3 py-1' style='font-size: 0.85rem;'><i class='fas fa-users me-1'></i> {$qtd_ativos}</span></td>
            <td class='text-center traditional-content'>{$badge_venc}</td>
            <td class='traditional-content'>{$perfis_html}</td>
            <td class='text-center small text-info fw-bold traditional-content'><i class='fas fa-user-tie me-1 text-white-50'></i>".htmlspecialchars($r['CadUser'])."</td>
            <td class='pe-3 traditional-content'>
                <div class='d-flex gap-1 justify-content-end'>
                    <button type='button' class='btn-sq bg-sq-purple btn-ver-dados' title='Ver Dados' data-r='{$json_r}' data-venc='{$venc_fmt_list}' data-total='{$total_pagar_fmt}' data-ativos='{$qtd_ativos}'><i class='fas fa-eye'></i></button>
                    <button type='button' class='btn-sq bg-sq-blue btn-editar' title='Editar' data-r='{$json_r}' data-venc='{$venc_fmt_input}'><i class='fas fa-pen'></i></button>
                    <button type='button' class='btn-sq bg-sq-orange' title='Bloquear Rede' onclick='acaoRapidaAlternar({$r['id']}, \"{$r['bloqueado']}\")'><i class='fas {$icon_bloq}'></i></button>
                    <button type='button' class='btn-sq bg-sq-red' title='Excluir' onclick='acaoRapidaExcluir({$r['id']})'><i class='fas fa-trash'></i></button>
                </div>
            </td>

            <td class='card-content' colspan='10'>
                <div class='card-sigma'>
                    <div class='cs-id'>".htmlspecialchars($r['usuario'])."</div>
                    <div class='cs-nome'>".(!empty($r['nome']) ? htmlspecialchars($r['nome']) : '---')."</div>
                    
                    <div class='cs-perfil text-info' style='font-size: 0.75rem; margin-bottom: 8px;'><span class='text-white-50 fw-bold'>Perfis Liberados:</span><br>{$perfis_card_text}</div>
                    
                    <div class='cs-user'>Créditos: {$r['LimiteUser']}</div>

                    <div class='cs-info-box'>
                        <div class='cs-info-col'>
                            <span class='cs-info-label'>Vencimento</span>
                            <span class='cs-info-val fw-bold'>{$data_venc_br}</span>
                        </div>
                        <div class='cs-info-col text-end'>
                            <span class='cs-info-label'>Ativos / Fatura</span>
                            <span class='cs-info-val'>{$qtd_ativos} cli | R$ {$total_pagar_fmt}</span>
                        </div>
                    </div>

                    <div class='cs-badges'>
                        <div class='cs-badge ".($isBloq || $isVenc ? 'vencido' : 'ativo')."'>{$status_text}</div>
                        <div class='cs-badge dono'>Dono: ".htmlspecialchars($r['CadUser'])."</div>
                    </div>

                    <button type='button' class='cs-btn-zap btn-zap-direto' data-nome='".htmlspecialchars($r['nome'] ?? '', ENT_QUOTES)."' data-usuario='".htmlspecialchars($r['usuario'], ENT_QUOTES)."' data-senha='".htmlspecialchars($r['senha'], ENT_QUOTES)."' data-venc='{$venc_fmt_list}' data-limite='{$r['LimiteUser']}' data-total='{$total_pagar_fmt}' data-ativos='{$qtd_ativos}' data-whatsapp='".htmlspecialchars($r['whatsapp'] ?? '', ENT_QUOTES)."' data-url='{$urlPainel}'>
                        <i class='fab fa-whatsapp me-2'></i> WhatsApp
                    </button>

                    <div class='cs-actions-grid'>
                        <div class='cs-action-item btn-editar' data-r='{$json_r}' data-venc='{$venc_fmt_input}'>
                            <div class='cs-icon bg-sq-blue'><i class='fas fa-pen'></i></div>
                            <span class='cs-action-text'>Editar</span>
                        </div>
                        <div class='cs-action-item btn-ver-dados' data-r='{$json_r}' data-venc='{$venc_fmt_list}' data-total='{$total_pagar_fmt}' data-ativos='{$qtd_ativos}'>
                            <div class='cs-icon bg-sq-purple'><i class='fas fa-eye'></i></div>
                            <span class='cs-action-text'>Dados</span>
                        </div>
                        <div class='cs-action-item' onclick='acaoRapidaAlternar({$r['id']}, \"{$r['bloqueado']}\")'>
                            <div class='cs-icon bg-sq-orange'><i class='fas {$icon_bloq}'></i></div>
                            <span class='cs-action-text'>Status</span>
                        </div>
                        <div class='cs-action-item' onclick='acaoRapidaExcluir({$r['id']})'>
                            <div class='cs-icon bg-sq-red'><i class='fas fa-trash'></i></div>
                            <span class='cs-action-text'>Excluir</span>
                        </div>
                    </div>
                </div>
            </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, maximum-scale=1.0, user-scalable=no">
    <title>Revendedores | <?= 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; padding: 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; }
        .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; }
        .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 20px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

        .card-custom { background: var(--bg-card) !important; border: 1px solid var(--border-color); border-radius: 12px; }
        .form-control, .form-select { background: #151521 !important; border: 1px solid #444 !important; color: #fff !important; }
        .table-responsive { background: var(--bg-card) !important; -webkit-overflow-scrolling: touch; }
        .table-video { width: 100%; border-collapse: collapse; white-space: nowrap; }
        .table-video thead th { background: rgba(0,0,0,0.2) !important; color: #ffffff; text-transform: uppercase; font-weight: 700; font-size: 0.75rem; padding: 15px 12px; border-bottom: 1px solid var(--border-color); }
        
        .table-video th, .table-video td { width: 1% !important; white-space: nowrap !important; padding: 12px !important; border-bottom: 1px solid var(--border-color) !important; background: var(--bg-card) !important; color: #fff !important; vertical-align: middle !important; }
        
        .label-visivel { color: #ffffff !important; font-weight: 700; text-transform: uppercase; font-size: 0.75rem; }
        .nome-destaque { color: #ffffff !important; font-weight: 700; }
        .badge-perfil { font-size: 0.7rem; padding: 4px 8px; border-radius: 4px; background: rgba(115, 103, 240, 0.2); color: #7367f0; border: 1px solid rgba(115, 103, 240, 0.3); font-weight: 700; margin-right: 4px; display: inline-block; margin-bottom: 2px;}
        
        .btn-sq { width: 32px; height: 32px; border-radius: 6px; border: none; color: #fff !important; display: inline-flex; align-items: center; justify-content: center; transition: 0.2s; box-shadow: 0 2px 4px rgba(0,0,0,0.3); }
        .btn-sq i { color: #fff !important; font-size: 0.85rem; }
        .bg-sq-blue { background-color: #00cfe8 !important; } .bg-sq-purple { background-color: #7367f0 !important; } .bg-sq-orange { background-color: #ff9f43 !important; } .bg-sq-red { background-color: #ea5455 !important; }
        
        .status-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; margin-right: 6px; }
        .online { background-color: #28c76f; box-shadow: 0 0 8px #28c76f; }
        .offline { background-color: #ea5455; box-shadow: 0 0 8px #ea5455; }
        
        @media (max-width: 992px) { .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; } .mobile-toggle { display: block !important; margin-right: 15px; } }
        @media (max-width: 576px) { .header-title { font-size: 1rem !important; } }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; }
        .overlay.show { display: block; }

        /* ======== SISTEMA DE VISUALIZAÇÃO DUPLA (TABELA vs CARDS) ======== */
        .modo-table .card-content { display: none !important; }
        .modo-table .traditional-content { display: table-cell; }
        .modo-table .td-checkbox { display: table-cell; }

        .modo-cards .table-video, .modo-cards .table-video tbody { 
            display: block; width: 100%; border: none; background: transparent !important;
        }
        .modo-cards .table-video thead { display: none; }
        .modo-cards .table-video tbody { 
            display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 15px; padding: 10px 0;
        }
        .modo-cards .table-video tr { 
            display: flex; flex-direction: column; width: 100%; height: 100%;
            background: transparent !important; border: none !important; padding: 0 !important; margin: 0 !important;
        }
        .modo-cards .table-video td { display: none !important; }
        .modo-cards .table-video td.td-checkbox { 
            display: block !important; position: absolute; top: 15px; right: 15px; padding: 0 !important; border: none !important; z-index: 10; background: transparent !important; width: auto !important;
        }
        .modo-cards .table-video td.card-content { 
            display: block !important; width: 100% !important; max-width: 100% !important; padding: 0 !important; border: none !important; white-space: normal !important; background: transparent !important; 
        }

        /* ESTILIZAÇÃO DO CARD SIGMA */
        .card-sigma {
            background: #1e1e2d; border: 1px solid #2b2b40; border-radius: 12px; padding: 18px; text-align: left; position: relative; box-shadow: 0 4px 10px rgba(0,0,0,0.15); transition: transform 0.2s; height: 100%; display: flex; flex-direction: column;
        }
        .card-sigma:hover { transform: translateY(-3px); }
        .cs-id { color: #00cfe8; font-size: 0.9rem; font-weight: bold; margin-bottom: 2px; }
        .cs-nome { color: #ffffff; font-size: 1.1rem; font-weight: bold; margin-bottom: 2px; padding-right: 25px; }
        .cs-perfil { color: #a6a6b7; font-size: 0.85rem; margin-bottom: 2px; }
        .cs-user { color: #a6a6b7; font-size: 0.85rem; margin-bottom: 15px; }
        
        .cs-info-box { background: #151521; border: 1px solid #2b2b40; border-radius: 8px; padding: 12px; display: flex; justify-content: space-between; margin-bottom: 12px; }
        .cs-info-col { display: flex; flex-direction: column; }
        .cs-info-label { font-size: 0.65rem; color: #a6a6b7; text-transform: uppercase; font-weight: bold; margin-bottom: 4px; }
        .cs-info-val { font-size: 0.8rem; color: #d0d2d6; }
        
        .cs-badges { display: flex; gap: 8px; margin-bottom: 12px; flex-wrap: wrap; }
        .cs-badge { padding: 4px 10px; border-radius: 6px; font-size: 0.7rem; font-weight: 700; background: transparent; text-transform: uppercase; }
        .cs-badge.ativo { border: 1px solid #28c76f; color: #28c76f; }
        .cs-badge.vencido { border: 1px solid #ea5455; color: #ea5455; }
        .cs-badge.bloqueado { border: 1px solid #ff9f43; color: #ff9f43; }
        .cs-badge.dono { border: 1px solid #6c757d; color: #6c757d; text-transform: none; }
        
        .cs-btn-zap { display: block; width: 100%; background: #28c76f; color: #fff; text-align: center; padding: 10px; border-radius: 8px; font-weight: bold; margin-bottom: 15px; text-decoration: none; border: none; transition: 0.2s; cursor: pointer; }
        .cs-btn-zap:hover { background: #24b263; color: #fff; }
        
        .cs-actions-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(65px, 1fr)); gap: 12px; margin-top: auto; }
        .cs-action-item { display: flex; flex-direction: column; align-items: center; justify-content: flex-start; cursor: pointer; text-align: center; gap: 6px; }
        .cs-icon { width: 42px; height: 42px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 1.1rem; color: #fff; box-shadow: 0 4px 8px rgba(0,0,0,0.15); transition: transform 0.2s; }
        .cs-action-item:hover .cs-icon { transform: scale(1.05); }
        .cs-action-text { font-size: 0.7rem; color: #a6a6b7; font-weight: 500; }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>


<main class="main-content">
    <div class="top-header">
        <div class="d-flex align-items-center overflow-hidden">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title">REVENDEDORES</div>
        </div>
        <div class="d-flex gap-1 gap-md-2 ms-2">
            <?php if($isAdmin): ?>
            <button onclick="new bootstrap.Modal(document.getElementById('modalMsgRev')).show()" class="btn btn-primary btn-sm fw-bold px-2 px-md-3 rounded-pill shadow-sm text-nowrap"><i class="fas fa-envelope"></i> <span class="d-none d-sm-inline ms-1">MSG. REVENDA</span><span class="d-inline d-sm-none ms-1">MSG.</span></button>
            <?php endif; ?>
            <button onclick="new bootstrap.Modal(document.getElementById('modalCriar')).show()" class="btn btn-light btn-sm fw-bold px-2 px-md-3 rounded-pill shadow-sm text-nowrap"><i class="fas fa-plus"></i> <span class="d-none d-sm-inline ms-1">NOVO</span></button>
        </div>
    </div>

    <div class="container-fluid p-2 p-md-4">
        <?php if($msg): ?><div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show border-0 shadow-sm mb-4 mx-2"><?= $msg ?><button class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="card card-custom mb-4 p-3 shadow-lg">
            <form method="GET" id="formFiltro" class="row g-2 align-items-end">
                <div class="col-md-7">
                    <label class="label-visivel mb-1">PESQUISAR (Ao Vivo)</label>
                    <input type="text" name="busca" id="inputPesquisaLive" class="form-control" placeholder="Usuário..." value="<?= htmlspecialchars($busca) ?>">
                </div>
                <div class="col-md-2">
                    <label class="label-visivel mb-1">EXIBIR</label>
                    <select name="limit" id="filtroLimit" class="form-select">
                        <?php foreach([10,20,50,100] as $l): ?><option value="<?= $l ?>" <?= $limit_pg == $l ? 'selected' : '' ?>><?= $l ?> linhas</option><?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3" id="divOpcoesMassa" style="display: none;">
                    <label class="label-visivel mb-1 text-warning">AÇÕES EM MASSA</label>
                    <div class="dropdown">
                        <button class="btn btn-warning w-100 fw-bold dropdown-toggle py-2 shadow text-dark" type="button" data-bs-toggle="dropdown">OPÇÕES (<span id="countMassa">0</span>)</button>
                        <ul class="dropdown-menu dropdown-menu-dark w-100 shadow-lg">
                            <li><a class="dropdown-item" href="javascript:void(0)" onclick="abrirVencMassa()"><i class="fas fa-calendar-alt me-2 text-info"></i> Alterar Vencimento</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="javascript:void(0)" onclick="confirmarMassa('bloquear_massa')"><i class="fas fa-lock me-2 text-danger"></i> Bloquear Todos</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0)" onclick="confirmarMassa('desbloquear_massa')"><i class="fas fa-lock-open me-2 text-success"></i> Desbloquear Todos</a></li>
                            <li><a class="dropdown-item text-danger" href="javascript:void(0)" onclick="confirmarMassa('excluir_massa')"><i class="fas fa-trash me-2"></i> Excluir Todos</a></li>
                        </ul>
                    </div>
                </div>
                <div class="col-md-3" id="btnFiltrarNormal">
                    <label class="label-visivel mb-1 text-transparent d-none d-md-block" style="color:transparent;">.</label>
                    <div class="d-flex flex-column gap-2">
                        <button type="submit" class="btn btn-primary w-100 fw-bold py-2 shadow"><i class="fas fa-filter me-1"></i> FILTRAR</button>
                        <button type="button" class="btn btn-info w-100 fw-bold py-2 shadow text-white" onclick="toggleViewMode()"><i class="fas fa-th-large me-1"></i> VISUALIZAÇÃO</button>
                    </div>
                </div>
            </form>
        </div>

        <form id="formMassa" method="POST">
            <input type="hidden" name="acao" id="acaoMassaInput">
            <input type="hidden" name="data_massa" id="dataMassaInput">

            <div class="card card-custom shadow-lg overflow-hidden">
                <div class="table-responsive modo-table" id="tableViewContainer">
                    <table class="table table-video">
                        <thead>
                            <tr>
                                <th class="text-center" style="width: 1%;"><input type="checkbox" id="checkAll" class="form-check-input" style="cursor:pointer;"></th>
                                <th>Nome</th>
                                <th>Usuário</th>
                                <th class="text-center">Senha</th>
                                <th class="text-center">WhatsApp</th>
                                <th class="text-center">Créditos</th>
                                <th class="text-center">Clientes Ativos</th>
                                <th class="text-center">Vencimento</th>
                                <th>Perfis Liberados</th>
                                <th class="text-center">Criado Por</th>
                                <th class="text-end pe-3">Opções</th>
                            </tr>
                        </thead>
                        <tbody id="corpoTabelaRev">
                            <?php foreach($revendas as $r): 
                                $venc_ts = (int)$r['data_premio'];
                                $isBloq = ($r['bloqueado'] == 'sim');
                                $isVenc = ($venc_ts > 0 && strtotime(date('Y-m-d 23:59:59', $venc_ts)) < time());
                                $venc_fmt_input = ($venc_ts > 0) ? date('Y-m-d', $venc_ts) : '';
                                $venc_fmt_list = ($venc_ts > 0) ? date('d/m/Y', $venc_ts) : '---';
                                $data_venc_br = ($venc_ts > 0) ? date('d/m/Y', $venc_ts) : 'Ilimitado';
                                $status_text = $isBloq ? 'BLOQUEADO' : ($isVenc ? 'VENCIDO' : 'ATIVO');
                                
                                $nomeRev = trim($r['usuario']);
                                $agora = time();
                                $sql_conta_cli = "SELECT perfil FROM usuario WHERE CadUser = ? AND bloqueado != 'sim' AND IF(data_premio REGEXP '^[0-9]+$', CAST(data_premio AS UNSIGNED), UNIX_TIMESTAMP(STR_TO_DATE(data_premio, '%Y-%m-%d'))) > ?";
                                $stmt_conta = $connUser->prepare($sql_conta_cli);
                                $stmt_conta->execute([$nomeRev, $agora]);
                                $clientes_ativos = $stmt_conta->fetchAll(PDO::FETCH_ASSOC);
                                
                                $qtd_ativos = count($clientes_ativos);
                                $total_fatura = 0;
                                foreach($clientes_ativos as $cli) {
                                    $p_info = $mapa_perfis[$cli['perfil']] ?? ['nome' => ''];
                                    $p_nome = mb_strtolower($p_info['nome']);
                                    if (strpos($p_nome, 'net') !== false) {
                                        $total_fatura += (float)$r['valor_net'];
                                    } else {
                                        $total_fatura += (float)$r['valor_claro'];
                                    }
                                }
                                $total_pagar_fmt = number_format($total_fatura, 2, ',', '.');

                                $badge_venc = "<span class='badge ".($isVenc ? 'bg-danger' : 'bg-success')." p-2'>{$venc_fmt_list}</span>";
                                if($isVenc) $badge_venc .= "<br><small class='text-danger fw-bold'>VENCIDO</small>";

                                // --- SISTEMA DE PERFIS (Correção de Visualização) ---
                                $perfis_array = [];
                                if(!empty($r['perfil'])){
                                    $tags = explode(',', $r['perfil']);
                                    foreach($tags as $t) if(trim($t) != "") $perfis_array[] = trim($t);
                                }
                                
                                if(count($perfis_array) > 0) {
                                    $perfis_html = "";
                                    foreach($perfis_array as $t) {
                                        $perfis_html .= "<span class='badge-perfil'>".htmlspecialchars($t)."</span>";
                                    }
                                    // Formato com traços ex: Claro HD - Net Brasilia - Net Rio
                                    $perfis_card_text = htmlspecialchars(implode(' - ', $perfis_array));
                                } else {
                                    $perfis_html = "<small class='text-muted'>Nenhum</small>";
                                    $perfis_card_text = "Nenhum";
                                }
                                // ---------------------------------------------------

                                $icon_bloq = $isBloq ? 'fa-lock-open' : 'fa-lock';
                                
                                // Passar os dados para o JS usando data attributes para evitar erro de aspas do PHP
                                $json_r = htmlspecialchars(json_encode($r), ENT_QUOTES, 'UTF-8');
                            ?>
                            <tr>
                                <td class="text-center td-checkbox"><input type="checkbox" name="ids_massa[]" value="<?= $r['id'] ?>" class="form-check-input check-item" style="cursor:pointer;"></td>
                                
                                <td class="text-white fw-bold traditional-content"><?= !empty($r['nome']) ? htmlspecialchars($r['nome']) : '<span class="text-muted small">---</span>' ?></td>
                                <td class="ps-3 traditional-content"><div class="d-flex align-items-center"><span class="status-dot <?= ($isBloq || $isVenc) ? 'offline' : 'online' ?>"></span><div class="nome-destaque <?= ($isBloq || $isVenc) ? 'text-danger' : '' ?>"><?= htmlspecialchars($r['usuario']) ?></div></div></td>
                                <td class="text-center text-white-50 small traditional-content"><?= htmlspecialchars($r['senha']) ?></td>
                                <td class="text-center text-white-50 small traditional-content"><?= htmlspecialchars($r['whatsapp'] ?? '') ?></td>
                                <td class="text-center traditional-content"><span class="badge bg-primary px-3"><?= $r['LimiteUser'] ?></span></td>
                                <td class="text-center traditional-content"><span class="badge bg-success px-3 py-1" style="font-size: 0.85rem;"><i class="fas fa-users me-1"></i> <?= $qtd_ativos ?></span></td>
                                <td class="text-center traditional-content"><?= $badge_venc ?></td>
                                <td class="traditional-content"><?= $perfis_html ?></td>
                                <td class="text-center small text-info fw-bold traditional-content"><i class="fas fa-user-tie me-1 text-white-50"></i><?= htmlspecialchars($r['CadUser']) ?></td>
                                <td class="pe-3 traditional-content">
                                    <div class="d-flex gap-1 justify-content-end">
                                        <button type="button" class="btn-sq bg-sq-purple btn-ver-dados" title="Ver Dados" data-r="<?= $json_r ?>" data-venc="<?= $venc_fmt_list ?>" data-total="<?= $total_pagar_fmt ?>" data-ativos="<?= $qtd_ativos ?>"><i class="fas fa-eye"></i></button>
                                        <button type="button" class="btn-sq bg-sq-blue btn-editar" title="Editar" data-r="<?= $json_r ?>" data-venc="<?= $venc_fmt_input ?>"><i class="fas fa-pen"></i></button>
                                        <button type="button" class="btn-sq bg-sq-orange" title="Bloquear Rede" onclick="acaoRapidaAlternar(<?= $r['id'] ?>, '<?= $r['bloqueado'] ?>')"><i class="fas <?= $icon_bloq ?>"></i></button>
                                        <button type="button" class="btn-sq bg-sq-red" title="Excluir" onclick="acaoRapidaExcluir(<?= $r['id'] ?>)"><i class="fas fa-trash"></i></button>
                                    </div>
                                </td>

                                <td class="card-content" colspan="10">
                                    <div class="card-sigma">
                                        <div class="cs-id"><?= htmlspecialchars($r['usuario']) ?></div>
                                        <div class="cs-nome"><?= !empty($r['nome']) ? htmlspecialchars($r['nome']) : '---' ?></div>
                                        
                                        <div class="cs-perfil text-info" style="font-size: 0.75rem; margin-bottom: 8px;"><span class="text-white-50 fw-bold">Perfis Liberados:</span><br><?= $perfis_card_text ?></div>
                                        
                                        <div class="cs-user">Créditos: <?= $r['LimiteUser'] ?></div>

                                        <div class="cs-info-box">
                                            <div class="cs-info-col">
                                                <span class="cs-info-label">Vencimento</span>
                                                <span class="cs-info-val fw-bold"><?= $data_venc_br ?></span>
                                            </div>
                                            <div class="cs-info-col text-end">
                                                <span class="cs-info-label">Ativos / Fatura</span>
                                                <span class="cs-info-val"><?= $qtd_ativos ?> cli | R$ <?= $total_pagar_fmt ?></span>
                                            </div>
                                        </div>

                                        <div class="cs-badges">
                                            <div class="cs-badge <?= ($isBloq || $isVenc) ? 'vencido' : 'ativo' ?>"><?= $status_text ?></div>
                                            <div class="cs-badge dono">Dono: <?= htmlspecialchars($r['CadUser']) ?></div>
                                        </div>

                                        <button type="button" class="cs-btn-zap btn-zap-direto" data-nome="<?= htmlspecialchars($r['nome'] ?? '', ENT_QUOTES) ?>" data-usuario="<?= htmlspecialchars($r['usuario'], ENT_QUOTES) ?>" data-senha="<?= htmlspecialchars($r['senha'], ENT_QUOTES) ?>" data-venc="<?= $venc_fmt_list ?>" data-limite="<?= $r['LimiteUser'] ?>" data-total="<?= $total_pagar_fmt ?>" data-ativos="<?= $qtd_ativos ?>" data-whatsapp="<?= htmlspecialchars($r['whatsapp'] ?? '', ENT_QUOTES) ?>" data-url="<?= $urlPainel ?>">
                                            <i class="fab fa-whatsapp me-2"></i> WhatsApp
                                        </button>

                                        <div class="cs-actions-grid">
                                            <div class="cs-action-item btn-editar" data-r="<?= $json_r ?>" data-venc="<?= $venc_fmt_input ?>">
                                                <div class="cs-icon bg-sq-blue"><i class="fas fa-pen"></i></div>
                                                <span class="cs-action-text">Editar</span>
                                            </div>
                                            <div class="cs-action-item btn-ver-dados" data-r="<?= $json_r ?>" data-venc="<?= $venc_fmt_list ?>" data-total="<?= $total_pagar_fmt ?>" data-ativos="<?= $qtd_ativos ?>">
                                                <div class="cs-icon bg-sq-purple"><i class="fas fa-eye"></i></div>
                                                <span class="cs-action-text">Dados</span>
                                            </div>
                                            <div class="cs-action-item" onclick="acaoRapidaAlternar(<?= $r['id'] ?>, '<?= $r['bloqueado'] ?>')">
                                                <div class="cs-icon bg-sq-orange"><i class="fas <?= $icon_bloq ?>"></i></div>
                                                <span class="cs-action-text">Status</span>
                                            </div>
                                            <div class="cs-action-item" onclick="acaoRapidaExcluir(<?= $r['id'] ?>)">
                                                <div class="cs-icon bg-sq-red"><i class="fas fa-trash"></i></div>
                                                <span class="cs-action-text">Excluir</span>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </form>
    </div>
</main>

<form id="formAcaoIndividual" method="POST" style="display:none;"><input type="hidden" name="acao" id="acaoIndividual"><input type="hidden" name="id_rev" id="idIndividual"><input type="hidden" name="status_atual" id="statusIndividual"></form>

<?php if($isAdmin): ?>
<div class="modal fade" id="modalMsgRev" tabindex="-1"><div class="modal-dialog modal-dialog-centered modal-lg"><div class="modal-content bg-dark border-primary text-white"><form method="POST"><input type="hidden" name="acao" value="salvar_msg_rev"><div class="modal-header border-primary"><h5><i class="fas fa-envelope me-2 text-primary"></i>Configurar Mensagens & Cron</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body p-4"><div class="alert alert-info border-0" style="background: rgba(0, 207, 232, 0.1);"><h6 class="text-info fw-bold"><i class="fas fa-code me-2"></i>Tags Disponíveis:</h6><code class="text-white">{nome}</code>, <code class="text-white">{usuario}</code>, <code class="text-white">{senha}</code>, <code class="text-white">{vencimento}</code>, <code class="text-white">{limite}</code>, <code class="text-white">{link_painel}</code><br><code class="text-warning">{qtd_ativos}</code> (Total clientes), <code class="text-warning">{total_pagar}</code> (Soma fatura)</div>
                    
                    <div class="mb-4">
                        <label class="small fw-bold text-white-50 mb-1">SEU CPF (Padrão para API Asaas)</label>
                        <input type="text" name="cpf_admin" class="form-control border-primary" value="<?= htmlspecialchars($confMsgRev['cpf_admin'] ?? '') ?>" placeholder="Apenas números">
                        <small class="text-info mt-1 d-block" style="font-size: 0.70rem;"><i class="fas fa-info-circle me-1"></i> Será usado invisivelmente para gerar os PIX do Asaas sem pedir ao cliente.</small>
                    </div>

                    <div class="mb-4"><label class="small fw-bold text-primary mb-1">MENSAGEM DE CRIAÇÃO</label><textarea name="msg_novo" class="form-control text-success font-monospace" rows="6"><?= htmlspecialchars($confMsgRev['msg_novo'] ?? '') ?></textarea></div><div class="mb-4"><label class="small fw-bold text-warning mb-1">MENSAGEM DE COBRANÇA</label><textarea name="msg_cobranca" class="form-control text-warning font-monospace" rows="6"><?= htmlspecialchars($confMsgRev['msg_cobranca'] ?? '') ?></textarea></div><hr class="border-primary opacity-25"><h6 class="text-primary fw-bold mb-3"><i class="fas fa-robot me-2"></i>Automação de Cobrança</h6><div class="row"><div class="col-md-6 mb-3"><label class="small fw-bold text-white-50 mb-1">STATUS DA COBRANÇA</label><select name="cron_status" class="form-select border-primary"><option value="ativo" <?= ($confMsgRev['cron_status'] ?? 'ativo') == 'ativo' ? 'selected' : '' ?>>🟢 Ativado</option><option value="inativo" <?= ($confMsgRev['cron_status'] ?? '') == 'inativo' ? 'selected' : '' ?>>🔴 Desativado</option></select></div><div class="col-md-6 mb-3"><label class="small fw-bold text-white-50 mb-1">HORÁRIO DO DISPARO</label><input type="time" name="cron_hora" class="form-control border-primary" value="<?= htmlspecialchars($confMsgRev['cron_hora'] ?? '10:00') ?>"></div></div></div><div class="modal-footer border-primary"><button type="submit" class="btn btn-primary w-100 fw-bold shadow">SALVAR E LIBERAR TESTE</button></div></form></div></div></div>
<?php endif; ?>

<div class="modal fade" id="modalVencMassa" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content bg-dark border-secondary text-white"><div class="modal-header border-secondary"><h5>Alterar Vencimento em Massa</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body p-4"><div class="mb-3"><label class="small fw-bold">NOVA DATA</label><input type="date" id="inputVencMassa" class="form-control"></div></div><div class="modal-footer"><button type="button" class="btn btn-primary w-100 fw-bold" onclick="submitVencMassa()">APLICAR ALTERAÇÃO</button></div></div></div></div>

<div class="modal fade" id="modalCriar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary text-white">
            <form method="POST">
                <input type="hidden" name="acao" value="criar">
                <div class="modal-header"><h5>Nova Revenda</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
                <div class="modal-body p-4">
                    <div class="mb-3"><label class="small fw-bold">NOME</label><input type="text" name="nome" class="form-control"></div>
                    <div class="row">
                        <div class="col-6 mb-3"><label class="small fw-bold">USUÁRIO</label><input type="text" name="usuario" class="form-control" required></div>
                        <div class="col-6 mb-3"><label class="small fw-bold">SENHA</label><input type="text" name="senha" class="form-control" required></div>
                    </div>
                    <div class="mb-3"><label class="small fw-bold">WHATSAPP</label><input type="text" name="whatsapp" class="form-control" placeholder="DDI+DDD+Número"></div>
                    <div class="row">
                        <div class="col-6 mb-3"><label class="small fw-bold">LIMITE</label><input type="number" name="limite" class="form-control" value="10"></div>
                        <div class="col-6 mb-3"><label class="small fw-bold">VENCIMENTO</label><input type="date" name="data_premio" class="form-control"></div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3"><label class="small fw-bold text-info">VALOR CLARO (R$)</label><input type="text" name="valor_claro" class="form-control" placeholder="Ex: 10.00"></div>
                        <div class="col-6 mb-3"><label class="small fw-bold text-danger">VALOR NET (R$)</label><input type="text" name="valor_net" class="form-control" placeholder="Ex: 10.00"></div>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2"><label class="text-primary fw-bold small mb-0">PERFIS LIBERADOS:</label><div class="form-check mb-0"><input class="form-check-input" type="checkbox" id="selectAllCriar" onclick="toggleAllCriar(this)"><label class="form-check-label small text-white-50" style="cursor:pointer;" for="selectAllCriar">Selecionar Todos</label></div></div>
                    <div style="max-height: 120px; overflow-y: auto;" class="p-2 border border-secondary rounded">
                        <?php foreach($perfis_sistema as $p): ?>
                            <div class="form-check"><input class="form-check-input chk-criar" type="checkbox" name="perfis[]" value="<?= $p['nome'] ?>" id="c_<?= $p['id'] ?>"><label class="form-check-label" for="c_<?= $p['id'] ?>"><?= $p['nome'] ?></label></div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="modal-footer"><button type="submit" class="btn btn-primary w-100 fw-bold shadow">CADASTRAR</button></div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalEditar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary text-white">
            <form method="POST">
                <input type="hidden" name="acao" value="editar"><input type="hidden" name="id_rev" id="edit_id">
                <div class="modal-header border-secondary"><h5>Editar Revenda</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
                <div class="modal-body p-4">
                    <div class="mb-3"><label class="small fw-bold">NOME</label><input type="text" name="nome" id="edit_nome" class="form-control"></div>
                    <div class="row">
                        <div class="col-6 mb-3"><label class="small fw-bold">USUÁRIO</label><input type="text" name="usuario" id="edit_user" class="form-control"></div>
                        <div class="col-6 mb-3"><label class="small fw-bold">SENHA</label><input type="text" name="senha" id="edit_pass" class="form-control"></div>
                    </div>
                    <div class="mb-3"><label class="small fw-bold">WHATSAPP</label><input type="text" name="whatsapp" id="edit_whatsapp" class="form-control"></div>
                    <div class="row">
                        <div class="col-6 mb-3"><label class="small fw-bold">LIMITE</label><input type="number" name="limite" id="edit_limite" class="form-control"></div>
                        <div class="col-6 mb-3"><label class="small fw-bold">VENCIMENTO</label><input type="date" name="data_premio" id="edit_venc" class="form-control"></div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3"><label class="small fw-bold text-info">VALOR CLARO (R$)</label><input type="text" name="valor_claro" id="edit_valor_claro" class="form-control"></div>
                        <div class="col-6 mb-3"><label class="small fw-bold text-danger">VALOR NET (R$)</label><input type="text" name="valor_net" id="edit_valor_net" class="form-control"></div>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2"><label class="text-primary fw-bold small mb-0">PERFIS LIBERADOS:</label><div class="form-check mb-0"><input class="form-check-input" type="checkbox" id="selectAllEditar" onclick="toggleAllEditar(this)"><label class="form-check-label small text-white-50" style="cursor:pointer;" for="selectAllEditar">Selecionar Todos</label></div></div>
                    <div style="max-height: 120px; overflow-y: auto;" class="p-2 border border-secondary rounded">
                        <?php foreach($perfis_sistema as $p): ?>
                            <div class="form-check"><input class="form-check-input chk-edit" type="checkbox" name="perfis[]" value="<?= $p['nome'] ?>" id="e_<?= $p['id'] ?>"><label class="form-check-label" for="e_<?= $p['id'] ?>"><?= $p['nome'] ?></label></div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="modal-footer"><button type="submit" class="btn btn-primary w-100 fw-bold shadow">SALVAR ALTERAÇÕES</button></div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalVerDados" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content bg-dark border-info text-white"><div class="modal-header border-secondary"><h5>Dados da Revenda</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body p-4"><input type="hidden" id="view_nome_rev"><input type="hidden" id="view_limite_rev"><input type="hidden" id="view_qtd_ativos"><input type="hidden" id="view_total_pagar"><div class="mb-2"><label class="small text-white-50">Usuário:</label><input type="text" readonly class="form-control" id="view_user"></div><div class="mb-2"><label class="small text-white-50">Senha:</label><input type="text" readonly class="form-control" id="view_pass"></div><div class="mb-2"><label class="small text-white-50">WhatsApp:</label><input type="text" readonly class="form-control" id="view_whatsapp"></div><div class="mb-2"><label class="small text-white-50">Vencimento:</label><input type="text" readonly class="form-control text-warning fw-bold" id="view_venc"></div><div class="d-flex gap-2 mt-4"><button onclick="copiarVisualizar()" class="btn btn-outline-light w-50 fw-bold">COPIAR</button><button onclick="zapVisualizar()" class="btn btn-success w-50 fw-bold">WHATSAPP</button></div><input type="hidden" id="view_link" value="<?= $urlPainel ?>"></div></div></div></div>

<div class="modal fade" id="modalZap" tabindex="-1"><div class="modal-dialog modal-dialog-centered text-center"><div class="modal-content bg-dark border-success text-white"><div class="modal-header border-0 pb-0"><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" id="btnCloseZap"></button></div><div class="modal-body p-4 pt-0"><h5 class="text-success mb-3">Concluído!</h5><textarea id="textoZapArea" class="form-control mb-3" rows="8" style="background:#111; color:#0f0; border:none; font-family:monospace;"><?= $texto_zap ?></textarea><div class="d-flex gap-2"><button onclick="copiarTexto()" class="btn btn-outline-light w-50 fw-bold">COPIAR</button><button onclick="enviarZap()" class="btn btn-success w-50 fw-bold">WHATSAPP</button></div></div></div></div></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu() { document.getElementById('sidebar').classList.toggle('show'); document.getElementById('overlay').classList.toggle('show'); }

    // ======== SISTEMA DE TROCA DE VISUALIZAÇÃO ========
    function toggleViewMode() {
        const wrapper = document.getElementById('tableViewContainer');
        if (wrapper.classList.contains('modo-table')) {
            wrapper.classList.remove('modo-table');
            wrapper.classList.add('modo-cards');
            localStorage.setItem('revendedoresViewMode', 'cards');
        } else {
            wrapper.classList.remove('modo-cards');
            wrapper.classList.add('modo-table');
            localStorage.setItem('revendedoresViewMode', 'table');
        }
    }

    document.addEventListener('DOMContentLoaded', () => {
        const savedMode = localStorage.getItem('revendedoresViewMode');
        const wrapper = document.getElementById('tableViewContainer');
        if (savedMode === 'cards') {
            wrapper.classList.remove('modo-table');
            wrapper.classList.add('modo-cards');
        }
    });
    // ==================================================

    // Ligar eventos dinâmicos usando delegação para não quebrar no AJAX
    document.addEventListener('click', function(e) {
        if (e.target.closest('.btn-ver-dados')) {
            const btn = e.target.closest('.btn-ver-dados');
            const r = JSON.parse(btn.getAttribute('data-r'));
            abrirVisualizar(r, btn.getAttribute('data-venc'), btn.getAttribute('data-total'), btn.getAttribute('data-ativos'));
        }
        if (e.target.closest('.btn-editar')) {
            const btn = e.target.closest('.btn-editar');
            const r = JSON.parse(btn.getAttribute('data-r'));
            abrirEditar(r, btn.getAttribute('data-venc'));
        }
        if (e.target.closest('.btn-zap-direto')) {
            const btn = e.target.closest('.btn-zap-direto');
            enviarZapDiretoRev(
                btn.getAttribute('data-nome'), 
                btn.getAttribute('data-usuario'), 
                btn.getAttribute('data-senha'), 
                btn.getAttribute('data-venc'), 
                btn.getAttribute('data-limite'), 
                btn.getAttribute('data-total'), 
                btn.getAttribute('data-ativos'), 
                btn.getAttribute('data-whatsapp'), 
                btn.getAttribute('data-url')
            );
        }
    });
    
    function abrirVisualizar(r, venc, total_pagar, qtd_ativos) { 
        document.getElementById('view_nome_rev').value = r.nome || ''; 
        document.getElementById('view_limite_rev').value = r.LimiteUser || ''; 
        document.getElementById('view_user').value = r.usuario; 
        document.getElementById('view_pass').value = r.senha; 
        document.getElementById('view_whatsapp').value = r.whatsapp || ''; 
        document.getElementById('view_venc').value = venc; 
        document.getElementById('view_total_pagar').value = total_pagar || '0,00'; 
        document.getElementById('view_qtd_ativos').value = qtd_ativos || '0'; 
        new bootstrap.Modal(document.getElementById('modalVerDados')).show(); 
    }
    
    function gerarMensagem() { 
        let template = <?= ($isAdmin && !empty($confMsgRev['msg_novo'])) ? json_encode($confMsgRev['msg_novo']) : json_encode("*🎉 BOAS VINDAS AO NOSSO SERVIDOR! 🎉*\n\n*🚀 ACESSO REVENDA*\n\n👤 *User:* {usuario}\n🔑 *Senha:* {senha}\n🔗 *Painel:* {link_painel}\n📅 *Venc:* {vencimento}\n\n_Guarde esses dados com segurança!_") ?>;
        template = template.replace(/{nome}/g, document.getElementById('view_nome_rev').value);
        template = template.replace(/{usuario}/g, document.getElementById('view_user').value);
        template = template.replace(/{senha}/g, document.getElementById('view_pass').value);
        template = template.replace(/{vencimento}/g, document.getElementById('view_venc').value);
        template = template.replace(/{link_painel}/g, document.getElementById('view_link').value);
        template = template.replace(/{limite}/g, document.getElementById('view_limite_rev').value);
        template = template.replace(/{total_pagar}/g, "R$ " + document.getElementById('view_total_pagar').value);
        template = template.replace(/{qtd_ativos}/g, document.getElementById('view_qtd_ativos').value);
        return template; 
    }

    // Funcionalidade de enviar Zap diretamente do card
    function enviarZapDiretoRev(r_nome, r_usuario, r_senha, venc, limite, total_pagar, qtd_ativos, whatsapp, link_painel) {
        let template = <?= ($isAdmin && !empty($confMsgRev['msg_novo'])) ? json_encode($confMsgRev['msg_novo']) : json_encode("*🎉 BOAS VINDAS AO NOSSO SERVIDOR! 🎉*\n\n*🚀 ACESSO REVENDA*\n\n👤 *User:* {usuario}\n🔑 *Senha:* {senha}\n🔗 *Painel:* {link_painel}\n📅 *Venc:* {vencimento}\n\n_Guarde esses dados com segurança!_") ?>;
        template = template.replace(/{nome}/g, r_nome || '');
        template = template.replace(/{usuario}/g, r_usuario || '');
        template = template.replace(/{senha}/g, r_senha || '');
        template = template.replace(/{vencimento}/g, venc || '');
        template = template.replace(/{link_painel}/g, link_painel || '');
        template = template.replace(/{limite}/g, limite || '');
        template = template.replace(/{total_pagar}/g, "R$ " + (total_pagar || '0,00'));
        template = template.replace(/{qtd_ativos}/g, qtd_ativos || '0');
        
        const num = whatsapp ? whatsapp.replace(/\D/g, '') : '';
        const urlFinal = num ? "https://api.whatsapp.com/send?phone=" + num + "&text=" : "https://api.whatsapp.com/send?text=";
        window.open(urlFinal + encodeURIComponent(template), '_blank');
    }
    
    function copiarVisualizar() { navigator.clipboard.writeText(gerarMensagem()).then(() => alert("Copiado!")); }
    function zapVisualizar() { 
        const m = gerarMensagem();
        const zapVal = document.getElementById('view_whatsapp').value; 
        const num = zapVal.replace(/\D/g, ''); 
        const urlFinal = num ? "https://api.whatsapp.com/send?phone=" + num + "&text=" : "https://api.whatsapp.com/send?text=";
        window.open(urlFinal + encodeURIComponent(m), '_blank'); 
    }
    
    function copiarTexto() { document.getElementById("textoZapArea").select(); document.execCommand("copy"); alert("Copiado!"); }
    function enviarZap() { window.open("https://api.whatsapp.com/send?text=" + encodeURIComponent(document.getElementById("textoZapArea").value), '_blank'); }

    function toggleAllCriar(source) { document.querySelectorAll('.chk-criar').forEach(cb => cb.checked = source.checked); }
    function toggleAllEditar(source) { document.querySelectorAll('.chk-edit').forEach(cb => cb.checked = source.checked); }

    function abrirEditar(r, venc_iso) { 
        document.getElementById('edit_id').value = r.id; 
        document.getElementById('edit_nome').value = r.nome || '';
        document.getElementById('edit_user').value = r.usuario; 
        document.getElementById('edit_pass').value = r.senha; 
        document.getElementById('edit_whatsapp').value = r.whatsapp || ''; 
        document.getElementById('edit_limite').value = r.LimiteUser; 
        document.getElementById('edit_venc').value = venc_iso; 
        document.getElementById('edit_valor_claro').value = r.valor_claro && parseFloat(r.valor_claro) > 0 ? parseFloat(r.valor_claro).toFixed(2) : ''; 
        document.getElementById('edit_valor_net').value = r.valor_net && parseFloat(r.valor_net) > 0 ? parseFloat(r.valor_net).toFixed(2) : ''; 
        document.querySelectorAll('.chk-edit').forEach(el => el.checked = false); 
        if(document.getElementById('selectAllEditar')) document.getElementById('selectAllEditar').checked = false;
        if(r.perfil) { 
            r.perfil.split(',').forEach(p_nome => { 
                document.querySelectorAll('.chk-edit').forEach(c => { if(c.value.trim() === p_nome.trim()) c.checked = true; }); 
            }); 
        } 
        new bootstrap.Modal(document.getElementById('modalEditar')).show(); 
    }

    const checkAll = document.getElementById('checkAll');
    function refazerCheckboxes() {
        const checkItems = document.querySelectorAll('.check-item');
        if(checkAll) { checkAll.onclick = function() { checkItems.forEach(item => item.checked = checkAll.checked); atualizarLayoutMassa(); }; }
        checkItems.forEach(item => { item.onchange = atualizarLayoutMassa; });
        function atualizarLayoutMassa() {
            const selecionados = document.querySelectorAll('.check-item:checked').length;
            if (selecionados > 0) { document.getElementById('divOpcoesMassa').style.display = 'block'; document.getElementById('btnFiltrarNormal').style.display = 'none'; document.getElementById('countMassa').innerText = selecionados; } else { document.getElementById('divOpcoesMassa').style.display = 'none'; document.getElementById('btnFiltrarNormal').style.display = 'block'; }
        }
    }
    refazerCheckboxes();

    let timeoutPesquisa;
    const inputsFiltro = ['inputPesquisaLive', 'filtroLimit'];
    inputsFiltro.forEach(id => { const el = document.getElementById(id); if(el) { el.addEventListener('input', function() { clearTimeout(timeoutPesquisa); timeoutPesquisa = setTimeout(fazerPesquisaAjax, 400); }); } });

    function fazerPesquisaAjax() {
        const busca = document.getElementById('inputPesquisaLive').value;
        const limit = document.getElementById('filtroLimit').value;
        const url = `revendedores.php?ajax=true&busca=${encodeURIComponent(busca)}&limit=${limit}`;
        document.getElementById('corpoTabelaRev').style.opacity = '0.5';
        fetch(url).then(response => response.text()).then(html => { 
            document.getElementById('corpoTabelaRev').innerHTML = html; 
            document.getElementById('corpoTabelaRev').style.opacity = '1'; 
            if(checkAll) checkAll.checked = false; 
            document.getElementById('divOpcoesMassa').style.display = 'none'; 
            document.getElementById('btnFiltrarNormal').style.display = 'block'; 
            refazerCheckboxes(); 
        }).catch(err => console.error(err));
    }

    function abrirVencMassa() { new bootstrap.Modal(document.getElementById('modalVencMassa')).show(); }
    function submitVencMassa() { const data = document.getElementById('inputVencMassa').value; if(!data) return alert("Selecione uma data!"); document.getElementById('acaoMassaInput').value = 'vencimento_massa'; document.getElementById('dataMassaInput').value = data; document.getElementById('formMassa').submit(); }
    function confirmarMassa(tipo) { if(confirm("Deseja aplicar esta ação em todos os revendedores selecionados?")) { document.getElementById('acaoMassaInput').value = tipo; document.getElementById('formMassa').submit(); } }
    function acaoRapidaAlternar(id, statusAtual) { if(!confirm('Atenção: ' + (statusAtual === 'sim' ? 'Desbloquear' : 'Bloquear') + ' este revendedor também afetará todos os clientes dele. Continuar?')) return; document.getElementById('acaoIndividual').value = 'alternar_bloqueio'; document.getElementById('idIndividual').value = id; document.getElementById('statusIndividual').value = statusAtual; document.getElementById('formAcaoIndividual').submit(); }
    function acaoRapidaExcluir(id) { if(confirm('Excluir esta revenda? (Isso NÃO apaga os clientes dele, eles ficarão órfãos)')) { document.getElementById('acaoIndividual').value = 'excluir'; document.getElementById('idIndividual').value = id; document.getElementById('formAcaoIndividual').submit(); } }

    window.onload = function() { 
        if(`<?= trim($texto_zap) ?>` !== "") { 
            new bootstrap.Modal(document.getElementById('modalZap')).show(); 
            <?php if($redirecionar_limpo): ?> const redir = () => { window.location.href = 'revendedores.php'; }; document.getElementById('modalZap').addEventListener('hidden.bs.modal', redir); document.getElementById('btnCloseZap').onclick = redir; <?php endif; ?> 
        } 
    }
</script>
</body>
</html>
