<?php
session_start();

// --- TRAVA DO COMPROVANTE: Só apaga a memória se receber o comando silencioso do JS ---
if (isset($_GET['clear_msg'])) {
    unset($_SESSION['comprovante_revenda']);
    exit;
}

require_once 'config.php';

$pdo = getConexaoAtiva();
$pdo->exec("SET NAMES utf8mb4");

// ====================================================================
// MÁGICA PARA VPS NOVA: DESLIGA O MODO ESTRITO DO MYSQL
// Isso impede o falso Erro 500 ao criar um revendedor!
// ====================================================================
$pdo->exec("SET SESSION sql_mode = ''");

// --- LÓGICA DE AUTO-CORREÇÃO DO BANCO PARA REVENDEDORES E API ---
try {
    $check_zap = $pdo->query("SHOW COLUMNS FROM `reg_users` LIKE 'whatsapp'");
    if (!$check_zap->fetch()) { $pdo->exec("ALTER TABLE `reg_users` ADD COLUMN `whatsapp` VARCHAR(255) DEFAULT NULL"); }
    
    $check_nome = $pdo->query("SHOW COLUMNS FROM `reg_users` LIKE 'nome_revendedor'");
    if (!$check_nome->fetch()) { $pdo->exec("ALTER TABLE `reg_users` ADD COLUMN `nome_revendedor` VARCHAR(255) DEFAULT NULL"); }

    $check_wa = $pdo->query("SHOW COLUMNS FROM `painel_config` LIKE 'wa_api_url'");
    if (!$check_wa->fetch()) {
        $pdo->exec("ALTER TABLE `painel_config` ADD COLUMN `wa_api_url` VARCHAR(255) DEFAULT '', ADD COLUMN `wa_api_key` VARCHAR(255) DEFAULT '', ADD COLUMN `wa_instancia` VARCHAR(255) DEFAULT '', ADD COLUMN `wa_status` TINYINT(1) DEFAULT 0");
    }
} catch (Exception $e) {}

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

try {
    $tabela_existe = $pdo->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_painel = $pdo->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($config_painel) {
            $nome_painel = !empty($config_painel['nome_painel']) ? $config_painel['nome_painel'] : $nome_painel;
            $logo_url = !empty($config_painel['logo_url']) ? $config_painel['logo_url'] : $logo_url;
            $cor_primaria = !empty($config_painel['cor_primaria']) ? $config_painel['cor_primaria'] : $cor_primaria;
            
            $wa_url = $config_painel['wa_api_url'] ?? '';
            $wa_key = $config_painel['wa_api_key'] ?? '';
            $wa_inst = $config_painel['wa_instancia'] ?? '';
            $wa_status = (int)($config_painel['wa_status'] ?? 0);
        }
    }
} catch (Exception $e) {}
// --- FIM: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---

if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }

$role = $_SESSION['user_role'] ?? 'reseller';
$nome_usuario = $_SESSION['username'] ?? 'Usuário';
$my_id = $_SESSION['user_id'];

// Busca o saldo atualizado
$user_credits = $pdo->query("SELECT credits FROM reg_users WHERE id = $my_id")->fetchColumn() ?: 0.0;

$mensagem = "";

// --- CARREGAR TEMPLATES DO REVENDEDOR ---
$template_revenda_file = __DIR__ . '/template_revenda.txt';
$padrao_revenda = "🚀 *DADOS DO REVENDEDOR*\n\n🔗 *Painel:* #link_painel#\n👤 *Usuário:* #username#\n🔑 *Senha:* #password#";
$raw_template_revenda = file_exists($template_revenda_file) ? file_get_contents($template_revenda_file) : $padrao_revenda;

$template_creditos_file = __DIR__ . '/template_creditos.txt';
$padrao_creditos = "✅ *CRÉDITOS ADICIONADOS*\n\nOlá *#username#*, foram adicionados *#qtd#* créditos na sua conta de Revenda!\n\nBoas vendas! 🚀";
$raw_template_creditos = file_exists($template_creditos_file) ? file_get_contents($template_creditos_file) : $padrao_creditos;

// --- FUNÇÕES DE MENSAGENS PARA O REVENDEDOR ---
function gerarMensagemRevenda($username, $password, $whatsapp) {
    global $raw_template_revenda;
    $prot = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $link_painel = $prot . $_SERVER['HTTP_HOST'];
    
    $texto = str_replace(
        ['#username#', '#password#', '#link_painel#'],
        [$username, $password, $link_painel],
        $raw_template_revenda
    );
    return ['msg' => $texto, 'url' => "https://api.whatsapp.com/send?phone=".preg_replace('/\D/', '', (string)$whatsapp)."&text=".urlencode($texto)];
}

function gerarMensagemCredito($username, $qtd, $whatsapp) {
    global $raw_template_creditos;
    $texto = str_replace(
        ['#username#', '#qtd#'],
        [$username, $qtd],
        $raw_template_creditos
    );
    return ['msg' => $texto, 'url' => "https://api.whatsapp.com/send?phone=".preg_replace('/\D/', '', (string)$whatsapp)."&text=".urlencode($texto)];
}

// =========================================================================
// O DISPARADOR INVISÍVEL VIA API (Igual ao da tela de clientes)
// =========================================================================
function enviarMsgZapInvisivel($numero, $mensagem) {
    global $wa_url, $wa_key, $wa_inst, $wa_status;
    if ($wa_status == 0 || empty($wa_url)) return false;
    $numero = preg_replace('/\D/', '', $numero);
    if(empty($numero)) return false;
    $endpoint = rtrim($wa_url, '/');
    if(strpos($endpoint, '/message/sendText') === false) { $endpoint = $endpoint . "/message/sendText/" . $wa_inst; }
    $dados = [ "number" => "55" . $numero, "text" => $mensagem ];
    $ch = curl_init($endpoint);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($dados),
        CURLOPT_HTTPHEADER => ["Content-Type: application/json", "apikey: ".$wa_key], CURLOPT_TIMEOUT => 3
    ]);
    $res = curl_exec($ch); curl_close($ch); return $res;
}
// =========================================================================

// --- LÓGICA DE AÇÕES EM MASSA (BULK) ---
if (isset($_POST['action_bulk'])) {
    $type = $_POST['bulk_type'];
    $ids_raw = isset($_POST['bulk_ids']) ? explode(',', trim($_POST['bulk_ids'])) : [];
    
    $clean_ids = [];
    foreach($ids_raw as $i) { 
        if(intval($i) > 0) $clean_ids[] = intval($i); 
    }
    
    if (!empty($clean_ids)) {
        $id_list = implode(',', $clean_ids);
        $condicao_seguranca = ($role !== 'admin') ? " AND owner_id = " . intval($my_id) : "";
        
        if ($type === 'delete') {
            $pdo->exec("DELETE FROM reg_users WHERE id IN ($id_list) $condicao_seguranca");
            $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Revendedores selecionados foram excluídos com sucesso!</div>";
        } elseif ($type === 'block') {
            $pdo->exec("UPDATE reg_users SET status = IF(status=1, 0, 1) WHERE id IN ($id_list) $condicao_seguranca");
            $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Status dos revendedores selecionados foi alterado!</div>";
        }
    }
}

// --- PROCESSAMENTO DE AÇÕES INDIVIDUAIS ---
if (isset($_POST['action_save'])) {
    $user = $_POST['username'];
    $pass = $_POST['password'];
    $email = $_POST['email'] ?? '';
    $zap = $_POST['whatsapp'] ?? '';
    $nome_rev = $_POST['nome_revendedor'] ?? '';
    $id_editar = $_POST['reseller_id'] ?? null;

    if (!empty($id_editar)) {
        $check = $pdo->prepare("SELECT id FROM reg_users WHERE id = ? AND (owner_id = ? OR 'admin' = ?)");
        $check->execute([$id_editar, $my_id, $role]);
        if($check->fetch()) {
            $pdo->prepare("UPDATE reg_users SET username = ?, password = ?, email = ?, whatsapp = ?, nome_revendedor = ? WHERE id = ?")->execute([$user, $pass, $email, $zap, $nome_rev, $id_editar]);
            $mensagem = "<div class='alert success'>Revenda atualizada!</div>";
        }
    } else {
        $sql = "INSERT INTO reg_users (username, password, email, whatsapp, nome_revendedor, credits, member_group_id, owner_id, date_registered, status) VALUES (?, ?, ?, ?, ?, 0, 2, ?, ?, 1)";
        $res = $pdo->prepare($sql)->execute([$user, $pass, $email, $zap, $nome_rev, $my_id, time()]);
        if($res) {
            $msgInfo = gerarMensagemRevenda($user, $pass, $zap);
            $_SESSION['comprovante_revenda'] = $msgInfo;
            
            if (!empty($zap)) {
                if ($wa_status == 1) {
                    enviarMsgZapInvisivel($zap, $msgInfo['msg']); // Disparo invisível via API
                } else {
                    $_SESSION['auto_zap_url'] = $msgInfo['url']; // Prepara o redirecionamento Whatsapp
                }
            }
            
            header("Location: revendedores.php"); exit;
        }
    }
}

// --- ADICIONAR / REMOVER CRÉDITOS COM TRAVA DE SEGURANÇA E WHATSAPP AUTOMÁTICO ---
if (isset($_POST['action_credits'])) {
    $r_id = intval($_POST['credits_reseller_id']);
    $qtd = floatval($_POST['credits_amount']);
    $tipo = $_POST['credits_type']; 
    
    if ($tipo === 'add') {
        $pode_add = true;
        
        // Se NÃO for admin, checa se tem saldo suficiente antes de transferir
        if ($role !== 'admin') {
            $check_saldo = $pdo->prepare("SELECT credits FROM reg_users WHERE id = ?");
            $check_saldo->execute([$my_id]);
            $meu_saldo = floatval($check_saldo->fetchColumn());
            
            if ($meu_saldo < $qtd) {
                $pode_add = false;
                $mensagem = "<div class='alert danger'><i class='fas fa-exclamation-triangle'></i> Saldo insuficiente! Você não possui {$qtd} créditos para enviar.</div>";
            }
        }
        
        if ($pode_add) {
            $pdo->prepare("UPDATE reg_users SET credits = credits + ? WHERE id = ?")->execute([$qtd, $r_id]);
            if ($role !== 'admin') {
                $pdo->prepare("UPDATE reg_users SET credits = credits - ? WHERE id = ?")->execute([$qtd, $my_id]);
            }
            
            // Busca o nome do revendedor e WhatsApp para a mensagem
            $stmtR = $pdo->prepare("SELECT username, whatsapp FROM reg_users WHERE id = ?");
            $stmtR->execute([$r_id]);
            $revData = $stmtR->fetch(PDO::FETCH_ASSOC);
            
            $msgInfo = gerarMensagemCredito($revData['username'], $qtd, $revData['whatsapp']);
            $_SESSION['comprovante_revenda'] = $msgInfo;
            
            if (!empty($revData['whatsapp'])) {
                if ($wa_status == 1) {
                    enviarMsgZapInvisivel($revData['whatsapp'], $msgInfo['msg']);
                } else {
                    $_SESSION['auto_zap_url'] = $msgInfo['url'];
                }
            }
            
            header("Location: revendedores.php"); exit;
        }
        
    } else { // REMOVER CRÉDITOS
        
        // Trava para não remover mais créditos do que o sub-revendedor possui (não deixar ele negativo)
        $check_saldo_alvo = $pdo->prepare("SELECT credits FROM reg_users WHERE id = ?");
        $check_saldo_alvo->execute([$r_id]);
        $saldo_alvo = floatval($check_saldo_alvo->fetchColumn());
        
        if ($saldo_alvo < $qtd) {
            $mensagem = "<div class='alert danger'><i class='fas fa-exclamation-triangle'></i> O revendedor possui apenas {$saldo_alvo} créditos. Não é possível remover {$qtd}.</div>";
        } else {
            $pdo->prepare("UPDATE reg_users SET credits = credits - ? WHERE id = ?")->execute([$qtd, $r_id]);
            if ($role !== 'admin') {
                $pdo->prepare("UPDATE reg_users SET credits = credits + ? WHERE id = ?")->execute([$qtd, $my_id]);
                $user_credits += $qtd; // Atualiza a variável devolvendo saldo pra tela
            }
            $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Créditos removidos e devolvidos ao seu saldo!</div>";
        }
    }
}

// --- BLOQUEAR / EXCLUIR ---
if (isset($_GET['block'])) {
    $condicao_seguranca = ($role !== 'admin') ? " AND owner_id = " . intval($my_id) : "";
    $pdo->prepare("UPDATE reg_users SET status = IF(status=1, 0, 1) WHERE id = ? $condicao_seguranca")->execute([$_GET['block']]);
    header("Location: revendedores.php"); exit;
}

if (isset($_GET['delete'])) {
    $condicao_seguranca = ($role !== 'admin') ? " AND owner_id = " . intval($my_id) : "";
    $pdo->prepare("DELETE FROM reg_users WHERE id = ? $condicao_seguranca")->execute([$_GET['delete']]);
    header("Location: revendedores.php"); exit;
}

// --- QUERIES (Filtros e Paginação) ---
$search   = $_GET['search'] ?? '';
$limit    = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
$page     = isset($_GET['page']) ? (int)$_GET['page'] : 1;

if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

$where = " WHERE r.member_group_id != 1"; 
$params = [];
if ($role !== 'admin') { $where .= " AND r.owner_id = ?"; $params[] = $my_id; } 
if (!empty($search)) { $where .= " AND (r.username LIKE ? OR r.nome_revendedor LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%";}

// Conta o total de registros para a paginação
$stmt_count = $pdo->prepare("SELECT COUNT(r.id) FROM reg_users r " . $where);
$stmt_count->execute($params);
$total_registros = $stmt_count->fetchColumn();
$total_paginas = ceil($total_registros / $limit);

// Busca os registros COM O NOME DO DONO (JOIN)
$sql = "SELECT r.*, d.username as dono_nome FROM reg_users r LEFT JOIN reg_users d ON r.owner_id = d.id $where ORDER BY r.id DESC LIMIT $limit OFFSET $offset";
$stmtList = $pdo->prepare($sql);
$stmtList->execute($params);
$revendedores = $stmtList->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Revendedores - <?php echo htmlspecialchars($nome_painel); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { 
            --bg-dark: #121519; 
            --bg-sidebar: #1e2227; 
            --bg-card: #272c33; 
            --text-main: #d1d5da; 
            --text-muted: #8a94a1; 
            --accent: <?php echo $cor_primaria; ?>; 
            --border-color: #3a4149; 
            --success: #28a745; 
            --danger: #dc3545; 
            --warning: #6c757d; 
            --info: #17a2b8;
        }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: var(--bg-dark); color: var(--text-main); display: flex; height: 100vh; overflow: hidden; }
        
        .sidebar { width: 260px; background-color: var(--bg-sidebar); border-right: 1px solid var(--border-color); display: flex; flex-direction: column; z-index: 1001; transition: 0.3s; }
        .sidebar-header { padding: 25px 20px; text-align: center; font-size: 22px; font-weight: bold; color: white; border-bottom: 1px solid var(--border-color); }
        .sidebar-header span { color: var(--accent); }
        .sidebar-logo { max-width: 180px; max-height: 55px; object-fit: contain; }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(0, 123, 255, 0.2); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .user-info .credits-badge { display: block; margin-top: 10px; color: var(--success); font-weight: bold; font-size: 13px; }
        .menu-list { list-style: none; padding: 0; margin: 0; overflow-y: auto; flex: 1; }
        .menu-item { padding: 14px 20px; color: var(--text-main); text-decoration: none; display: flex; align-items: center; transition: 0.2s; border-left: 3px solid transparent; font-size: 15px; cursor: pointer; }
        .menu-item i:first-child { margin-right: 12px; width: 20px; text-align: center; color: var(--text-muted); }
        .menu-item:hover, .menu-item.active { background-color: #2c3138; color: white; border-left-color: var(--accent); }
        .menu-item.active i:first-child { color: var(--accent); }
        .submenu { display: none; background: #16191d; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 14px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 12px; }
        .rotate { transform: rotate(180deg); }
        .menu-category { padding: 20px 20px 8px; font-size: 11px; text-transform: uppercase; color: var(--text-muted); font-weight: bold; letter-spacing: 1px; }
        .logout-btn { padding: 15px; background-color: var(--danger); color: white; text-align: center; text-decoration: none; font-weight: bold; }
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; }
        
        .main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; overflow-x: hidden; transition: 0.3s; position: relative; width: 100vw; max-width: 100%; }
        .topbar { display: flex; justify-content: space-between; align-items: center; padding: 15px 30px; background-color: var(--bg-sidebar); border-bottom: 1px solid var(--border-color); }
        .mode-badge { padding: 6px 15px; background: rgba(40, 167, 69, 0.15); color: var(--success); border-radius: 20px; font-size: 12px; font-weight: bold; border: 1px solid var(--success); }
        .content-area { padding: 30px; flex: 1; overflow-y: auto; overflow-x: hidden; padding-bottom: 100px; box-sizing: border-box; width: 100%; }
        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 24px; cursor: pointer; }
        
        /* FILTROS E BUSCA */
        .filter-bar { background: var(--bg-card); padding: 15px; border-radius: 10px; border: 1px solid var(--border-color); margin-bottom: 20px; display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-end; }
        .filter-group { display: flex; flex-direction: column; gap: 5px; flex: 1; min-width: 120px; }
        .filter-group label { font-size: 11px; color: var(--text-muted); text-transform: uppercase; font-weight: bold; }
        .filter-bar input, .filter-bar select { background: #121519; border: 1px solid var(--border-color); color: white; padding: 10px; border-radius: 5px; font-size: 13px; }
        .btn-filter { background: var(--accent); color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; font-weight: bold; display: flex; align-items: center; justify-content: center; gap: 5px; }
        
        .btn-main { background: var(--accent); color: white; border: none; padding: 10px 18px; border-radius: 6px; cursor: pointer; font-weight: 600; text-decoration: none; font-size: 13px; display: inline-flex; align-items: center; gap: 5px; transition: 0.2s;}
        .btn-main:hover { filter: brightness(1.1); }

        /* TABELA COM SCROLL LATERAL MÓVEL */
        .card-table { background: var(--bg-card); border-radius: 10px; border: 1px solid var(--border-color); overflow-x: auto; width: 100%; display: block; -webkit-overflow-scrolling: touch; }
        .card-table::-webkit-scrollbar { height: 8px; }
        .card-table::-webkit-scrollbar-track { background: rgba(0,0,0,0.2); border-radius: 10px; }
        .card-table::-webkit-scrollbar-thumb { background: var(--accent); border-radius: 10px; }
        
        table { width: 100%; border-collapse: collapse; min-width: 900px; }
        th { background: #16191d; padding: 15px; text-align: left; color: var(--text-muted); font-size: 11px; text-transform: uppercase; }
        td { padding: 15px; border-bottom: 1px solid var(--border-color); font-size: 14px; }
        .badge { padding: 4px 8px; border-radius: 4px; font-size: 10px; font-weight: bold; text-transform: uppercase; }
        .bg-success { background: rgba(46, 204, 113, 0.2); color: #2ecc71; }
        .bg-danger { background: rgba(231, 76, 60, 0.2); color: #e74c3c; }
        
        .alert { padding: 15px; border-radius: 5px; margin-bottom: 15px; font-weight: bold; }
        .alert.success { background: rgba(46, 204, 113, 0.2); color: #2ecc71; border: 1px solid #2ecc71; }
        .alert.danger { background: rgba(231, 76, 60, 0.2); color: #e74c3c; border: 1px solid #e74c3c; }
        
        .btn-action { width: 32px; height: 32px; border-radius: 4px; border: none; cursor: pointer; color: white; display: inline-flex; align-items: center; justify-content: center; text-decoration: none; margin: 0; transition: 0.2s;}
        .btn-action:hover { filter: brightness(1.2); }
        .btn-action:disabled { cursor: not-allowed; opacity: 0.5; filter: grayscale(100%); }
        
        /* CAIXA DE COMPROVANTE ATUALIZADA */
        .comprovante-box { background: rgba(40, 167, 69, 0.15); border: 1px solid #2ecc71; padding: 15px; border-radius: 10px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; position: relative; flex-wrap: wrap; gap: 10px; }
        .btn-zap { background: #25d366; color: white; padding: 10px 20px; border-radius: 5px; text-decoration: none; font-weight: bold; font-size: 14px; flex: 1; text-align: center; border:none; cursor:pointer;}
        .btn-zap:hover { filter: brightness(1.1); }
        .btn-copiar-msg { background: #3a4149; color: white; padding: 10px 20px; border-radius: 5px; border: none; font-weight: bold; font-size: 14px; cursor: pointer; transition: 0.2s; flex: 1; text-align: center; }
        .btn-copiar-msg:hover { background: var(--accent); }

        /* AÇÕES EM MASSA (NO TOPO) */
        #bulkActionsBar { display:none; background: rgba(30, 34, 39, 0.95); padding: 15px 20px; border-radius: 10px; border: 1px dashed var(--accent); margin-bottom: 20px; align-items: center; gap: 15px; flex-wrap: wrap; justify-content: space-between; }
        .btn-bulk { background: var(--text-muted); color: white; border: none; padding: 8px 15px; border-radius: 6px; cursor: pointer; font-weight: bold; font-size: 13px; display: inline-flex; align-items: center; gap: 5px; transition: 0.2s; }
        .btn-bulk:hover { filter: brightness(1.2); }

        /* PAGINAÇÃO */
        .pagination { display: flex; justify-content: center; gap: 5px; margin-top: 0; flex-wrap: wrap; }
        .page-link { background: var(--bg-card); color: white; border: 1px solid var(--border-color); padding: 6px 12px; border-radius: 5px; text-decoration: none; font-size: 13px; font-weight: bold; transition: 0.2s; }
        .page-link:hover, .page-link.active { background: var(--accent); border-color: var(--accent); }
        .page-dots { color: var(--text-muted); padding: 6px 5px; }
        
        /* MODALS */
        .modal { display: none; position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); overflow-y: auto; }
        .modal-content { background: var(--bg-card); width: 90%; max-width: 450px; margin: 5% auto; padding: 25px; border-radius: 12px; border: 1px solid var(--border-color); position: relative; }
        .form-group-modal { margin-bottom: 15px; }
        .form-group-modal label { display: block; margin-bottom: 5px; font-size: 12px; color: var(--text-muted); font-weight: bold;}
        .form-group-modal input, .form-group-modal select { width: 100%; padding: 10px; background: #121519; border: 1px solid var(--border-color); color: white; border-radius: 5px; box-sizing: border-box; }
        .btn-save-modal { width: 100%; padding: 12px; background: var(--accent); border: none; color: white; border-radius: 5px; font-weight: bold; cursor: pointer; transition: 0.2s;}

        @media (max-width: 768px) {
            .sidebar { position: fixed; left: -260px; height: 100%; }
            .sidebar.active { left: 0; }
            .menu-toggle { display: block; margin-right: 15px; }
            .sidebar-overlay.active { display: block; }
            .topbar { padding: 15px 20px; justify-content: flex-start; }
            .topbar-right { margin-left: auto; }
            .content-area { padding: 15px; padding-bottom: 120px; }
            .modal-content { width: 90%; }
            .filter-bar { flex-direction: column; align-items: stretch; }
            .btn-filter { width: 100%; justify-content: center; }
            #bulkActionsBar { flex-direction: column; align-items: stretch; }
            .btn-bulk { justify-content: center; }
            .btn-main { width: 100%; justify-content: center; }
        }
    </style>
</head>
<body>

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

    <nav class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <?php if(!empty($logo_url) && file_exists($logo_url)): ?>
                <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" class="sidebar-logo">
            <?php else: ?>
                <?php echo htmlspecialchars($nome_painel); ?>
            <?php endif; ?>
        </div>
        <div class="user-info">
            <div style="color:white; font-size: 14px;">Olá, <strong><?php echo htmlspecialchars($nome_usuario); ?></strong></div>
            <span class="badge"><?php echo $role === 'admin' ? 'Administrador' : 'Revendedor'; ?></span>
            <div class="credits-badge"><i class="fas fa-coins"></i> Saldo: <?php echo number_format($user_credits, 1); ?></div>
        </div>
        <div class="menu-list">
            <a href="dashboard.php" class="menu-item active"><i class="fas fa-chart-line"></i> Dashboard</a>
            <a href="perfil.php" class="menu-item active"><i class="fas fa-user-circle"></i> Meu Perfil</a>
            
            <a href="lancamentos.php" class="menu-item active"><i class="fas fa-fire"></i> Últimos Adicionados</a>
            
            <a href="ajuda.php" class="menu-item active"><i class="fas fa-question-circle"></i> Material de Ajuda</a>
            
            <div class="menu-category">Gestão</div>
            <a href="clientes.php" class="menu-item active"><i class="fas fa-users"></i> Clientes IPTV</a>
            <a href="testes.php" class="menu-item active"><i class="fas fa-vial"></i> Gerenciar Testes</a>
            <a href="online.php" class="menu-item active"><i class="fas fa-plug"></i> Clientes Online</a>
            <a href="revendedores.php" class="menu-item active"><i class="fas fa-user-tie"></i> Revendedores</a>
            <a href="migrar_clientes.php" class="menu-item active"><i class="fas fa-exchange-alt"></i> Migrar Clientes</a>
            <a href="logs_creditos.php" class="menu-item active"><i class="fas fa-list-alt"></i> Extrato de Créditos</a>
            <a href="marketing.php" class="menu-item active"><i class="fas fa-bullhorn"></i> Central de Marketing</a>
            
            
            <div class="menu-category">Clientes P2P</div>
            <a href="p2p_clientes.php" class="menu-item active"><i class="fas fa-tv"></i> Clientes P2P</a>
            
            <?php if (!empty($api_conf['api_binstream_url'])): ?>
                <a href="binstream_p2p.php" class="menu-item active"><i class="fas fa-tv"></i> Binstream P2P</a>
            <?php endif; ?>

            <div class="menu-category">Integração & Cobrança</div>
            <a href="pagamentos.php" class="menu-item active"><i class="fas fa-dollar-sign"></i> Pagamento Automático</a>
            <a href="cobranca.php" class="menu-item active"><i class="fas fa-comment-dollar"></i> Central de Cobrança</a>
            <a href="admin_planos.php" class="menu-item active"><i class="fas fa-tags"></i> Meus Planos de Venda</a>
            <a href="comprar_creditos.php" class="menu-item active"><i class="fas fa-shopping-cart"></i> Comprar Créditos</a>
            
            <div class="menu-item active" onclick="toggleSubmenu('appsSub')">
                <i class="fas fa-rocket"></i><span>Aplicações</span><i class="fas fa-chevron-down arrow-icon" id="arrow-appsSub"></i>
            </div>
            <div class="submenu" id="appsSub">
                <a href="loja_apps.php" class="menu-item active"><i class="fas fa-store"></i> Loja de Aplicativos</a>
                <?php if($role === 'admin'): ?>
                    <a href="admin_loja.php" class="menu-item active"><i class="fas fa-cogs"></i> Gerenciar Loja</a>
                <?php endif; ?>
                <a href="chatbot.php" class="menu-item active"><i class="fab fa-whatsapp"></i> Chatbot Automático</a>
            </div>
           <a href="admin_player_revenda.php" class="menu-item active"><i class="fas fa-play-circle"></i> WebPlayer</a>
            
   <div class="menu-category">Segurança</div>
            <a href="historico_logins.php" class="menu-item active"><i class="fas fa-shield-alt"></i> Sessões Ativas</a>

            <?php if($role === 'admin'): ?>
                <div class="menu-category">Administração</div>
                <a href="admin_monitor.php" class="menu-item active"><i class="fas fa-heartbeat"></i> Monitor do Servidor</a>
                <a href="admin_template.php" class="menu-item active"><i class="fas fa-edit"></i> Editor de Template</a>
                <a href="admin_lb.php" class="menu-item active"><i class="fas fa-server"></i> Load Balancers</a>
                <a href="guia_cloudflare.php" class="menu-item active"><i class="fas fa-cloud"></i> Guia Cloudflare</a>
                 <a href="admin_loja_creditos.php" class="menu-item active"><i class="fas fa-store"></i> Configurar Loja (PIX)</a>
                 <a href="integracoes_api.php" class="menu-item active"><i class="fas fa-plug"></i> Integrações API</a>
                 <a href="integracoes_api_whatsapp.php" class="menu-item active"><i class="fas fa-plug"></i> Integrações API WhatsApp</a>
                 <a href="admin_robo.php" class="menu-item active"><i class="fas fa-robot"></i> Robô de Cobrança</a>
                 <a href="admin_anti_bloqueio.php" class="menu-item active"><i class="fas fa-bolt"></i> Botão de Pânico</a>
                 <a href="admin_anti_fraude.php" class="menu-item active"><i class="fas fa-user-secret"></i> Radar Anti-Fraude</a>  
                 <a href="admin_watchdog.php" class="menu-item active"><i class="fas fa-dog"></i> Watchdog LB</a>  
                 
                 <a href="admin_epg_sync.php" class="menu-item active">
        <i class="fas fa-clock"></i> Sincronizar EPG
    </a>

 <div class="menu-item active" onclick="toggleSubmenu('painelSub')">
                    <i class="fas fa-desktop"></i><span>Painel</span><i class="fas fa-chevron-down arrow-icon" id="arrow-painelSub"></i>
                </div>
                <div class="submenu" id="painelSub">
                    <a href="personalizacao.php" class="menu-item active"><i class="fas fa-paint-brush"></i> Personalização</a>
                </div>
             
                <div class="menu-item active" onclick="toggleSubmenu('adminSub')">
                    <i class="fas fa-toolbox"></i><span>Ferramentas</span><i class="fas fa-chevron-down arrow-icon" id="arrow-adminSub"></i>
                </div>
                <div class="submenu" id="adminSub">
                    <a href="importar.php" class="menu-item active"><i class="fas fa-file-import"></i> Importador</a>
                    <a href="importar3.php" class="menu-item active"><i class="fas fa-file-import"></i> Importador Turbo</a>
                    <a href="dns_manager.php" class="menu-item active"><i class="fas fa-link"></i> Alterar DNS</a>
                    <a href="admin_logos.php" class="menu-item active"><i class="fas fa-image"></i> Alterar Logos</a>
                    <a href="mover_conteudos.php" class="menu-item active"><i class="fas fa-exchange-alt"></i> Mover Conteúdos</a>
                    <a href="limpeza.php" class="menu-item active"><i class="fas fa-trash-alt"></i> Limpeza de Dados</a>
                    <a href="limpar_duplicados.php" class="menu-item active"><i class="fas fa-copy"></i> Limpeza de Duplicados</a>
                    <a href="backup.php" class="menu-item active"><i class="fas fa-database"></i> Backup do Sistema</a>
                    <a href="seguranca.php" class="menu-item active"><i class="fas fa-shield-alt"></i> Sistema de Segurança</a>
                    <a href="configuracoes.php" class="menu-item active"><i class="fas fa-tools"></i> Configurações</a>
                </div>

                 <?php if($role === 'admin'): ?>
    <div class="menu-category">Financeiro</div>
     <!-- NOVO MENU FINANCEIRO COM SUBMENU -->
            <div class="menu-item active" onclick="toggleSubmenu('finSub')">
                <i class="fas fa-hand-holding-usd"></i><span>Financeiro</span><i class="fas fa-chevron-down arrow-icon rotate" id="arrow-finSub"></i>
            </div>
            <div class="submenu" id="finSub" style="display: block;">
                <a href="financeiro.php" class="menu-item active">Faturamento</a>
            </div>
    
    <?php endif; ?>

                <div class="menu-category">Conteúdos</div>
                <a href="categorias.php" class="menu-item active"><i class="fas fa-folder-open"></i><span>Categorias</span></a>
                <div class="menu-item active" onclick="toggleSubmenu('contentSub')">
                    <i class="fas fa-layer-group"></i><span>Mídias</span><i class="fas fa-chevron-down arrow-icon" id="arrow-contentSub"></i>
                </div>
                <div class="submenu" id="contentSub">
                    <a href="bouquets.php" class="menu-item active">Editar Bouquets</a>
                    <a href="canais.php" class="menu-item active">Canais Ao Vivo</a>
                    <a href="filmes.php" class="menu-item active">Filmes (VOD)</a>
                    <a href="series.php" class="menu-item active">Séries</a>
                </div>
                 <a href="admin_autofix_vod.php" class="menu-item active"><i class="fas fa-magic"></i> Auto-Fix TMDB</a>
            <?php endif; ?>
        </div>
        <a href="logout.php" class="logout-btn"><i class="fas fa-power-off"></i> Sair</a>
    </nav>

    <div class="main-content">
        <header class="topbar">
            <div style="display:flex; align-items:center;">
                <button class="menu-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
                <h2 style="margin:0; font-size: 18px; color:white;">Gestão de Revendedores</h2>
            </div>
            <div class="topbar-right">
                <span class="mode-badge"><i class="fas fa-database"></i> <?php echo defined('MODO_SISTEMA') ? strtoupper(MODO_SISTEMA) : 'INTERNO'; ?></span>
            </div>
        </header>

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

            <div class="filter-bar">
                <form id="filterForm" method="GET" style="display: flex; flex-wrap: wrap; gap: 10px; width: 100%; align-items: flex-end;">
                    <div class="filter-group">
                        <label>Buscar Revendedor</label>
                        <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Ex: joao_rev" onkeyup="autoSubmitSearch()">
                    </div>
                    
                    <div class="filter-group">
                        <label>Exibir</label>
                        <select name="limit" onchange="this.form.submit()">
                            <?php foreach([10, 20, 50, 100, 250, 500, 1000, 2000, 3000] as $l): ?>
                                <option value="<?php echo $l; ?>" <?php echo $limit == $l ? 'selected' : ''; ?>><?php echo $l; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="filter-group" style="flex: none; display:none;">
                        <button type="submit" class="btn-filter"><i class="fas fa-search"></i> Filtrar</button>
                    </div>
                    
                    <div style="margin-left: auto; display:flex; gap:10px; flex-wrap:wrap;">
                        <button type="button" class="btn-main" style="background:var(--success);" onclick="openAddModal()"><i class="fas fa-user-tie"></i> Novo Revendedor</button>
                    </div>
                </form>
            </div>

            <div id="bulkActionsBar">
                <div style="display:flex; align-items:center; gap:10px;">
                    <span style="color: white; font-weight: bold; font-size:14px;"><span id="selectedCount" style="color:var(--accent);">0</span> Selecionados</span>
                </div>
                <div style="display:flex; gap:10px; flex-wrap:wrap;">
                    <button type="button" onclick="submitBulk('block')" class="btn-bulk" style="background:var(--warning);"><i class="fas fa-ban"></i> Status (Bloq/Desbloq)</button>
                    <button type="button" onclick="submitBulk('delete')" class="btn-bulk" style="background:var(--danger);"><i class="fas fa-trash"></i> Excluir</button>
                </div>
            </div>

            <div class="card-table">
                <table>
                    <thead>
                        <tr>
                            <th style="width: 30px; text-align: center;">
                                <input type="checkbox" id="selectAll" onclick="toggleSelectAll(this)" style="cursor:pointer; width:16px; height:16px; accent-color: var(--accent);">
                            </th>
                            <th>Revendedor</th>
                            <th>Usuário</th>
                            <th>WhatsApp</th>
                            <th>Email</th>
                            <th>Créditos</th>
                            <th>Dono</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($revendedores)): ?>
                            <tr><td colspan="8" style="text-align:center;">Nenhum revendedor encontrado.</td></tr>
                        <?php else: foreach ($revendedores as $r): 
                            $status_rev = isset($r['status']) ? $r['status'] : 1;
                            $badge_class = $status_rev == 1 ? 'bg-success' : 'bg-danger';
                            $badge_text = $status_rev == 1 ? 'ATIVO' : 'BLOQUEADO';
                        ?>
                            <tr>
                                <td style="text-align: center;">
                                    <input type="checkbox" class="user-checkbox" value="<?php echo $r['id']; ?>" onchange="toggleBulkActions()" style="cursor:pointer; width:16px; height:16px; accent-color: var(--accent);">
                                </td>
                                <td>
                                    <?php if(!empty($r['nome_revendedor'])): ?>
                                        <span style="font-size:14px; font-weight:bold; color:var(--text-main);"><i class="fas fa-user-tie" style="color:var(--text-muted); margin-right:5px;"></i> <?php echo htmlspecialchars($r['nome_revendedor']); ?></span>
                                    <?php else: ?>
                                        <span style="color:var(--text-muted); font-size:12px;">---</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($r['username']); ?></strong><br>
                                    <span class="badge <?php echo $badge_class; ?>"><?php echo $badge_text; ?></span>
                                </td>
                                <td>
                                    <?php if(!empty($r['whatsapp'])): ?>
                                        <a href="https://wa.me/<?php echo preg_replace('/\D/', '', $r['whatsapp']); ?>" target="_blank" style="color:#25d366; text-decoration:none;"><i class="fab fa-whatsapp"></i> <?php echo htmlspecialchars($r['whatsapp']); ?></a>
                                    <?php else: ?>
                                        <span style="color:var(--text-muted); font-size:12px;">---</span>
                                    <?php endif; ?>
                                </td>
                                <td style="color:var(--text-muted);"><?php echo htmlspecialchars($r['email'] ?: 'Não informado'); ?></td>
                                <td><span style="color:var(--success); font-weight:bold; font-size:16px;"><i class="fas fa-coins"></i> <?php echo number_format($r['credits'], 1); ?></span></td>
                                
                                <td style="color:var(--text-muted); font-size:12px;">
                                    <?php echo ($r['owner_id'] == $my_id) ? 'Você' : htmlspecialchars($r['dono_nome'] ?? 'Admin'); ?>
                                </td>

                                <td>
                                    <?php 
                                    $msgInfo = gerarMensagemRevenda($r['username'], $r['password'], $r['whatsapp']); 
                                    ?>
                                    
                                    <!-- FLEXBOX PARA MANTER OS BOTÕES LADO A LADO -->
                                    <div style="display: flex; gap: 8px; flex-wrap: nowrap; min-width: max-content;">
                                        <button type="button" class="btn-action" style="background:var(--info);" 
                                            data-texto="<?php echo htmlspecialchars($msgInfo['msg'], ENT_QUOTES, 'UTF-8'); ?>"
                                            data-zapurl="<?php echo htmlspecialchars($msgInfo['url'], ENT_QUOTES, 'UTF-8'); ?>"
                                            onclick="showReceipt(this)" title="Ver Informações do Revendedor"><i class="fas fa-eye"></i></button>

                                        <button type="button" class="btn-action" style="background:var(--accent);" 
                                            data-id="<?php echo $r['id']; ?>"
                                            data-nome="<?php echo htmlspecialchars($r['nome_revendedor'] ?? '', ENT_QUOTES); ?>"
                                            data-user="<?php echo htmlspecialchars($r['username'], ENT_QUOTES); ?>"
                                            data-pass="<?php echo htmlspecialchars($r['password'], ENT_QUOTES); ?>"
                                            data-zap="<?php echo htmlspecialchars($r['whatsapp'] ?? '', ENT_QUOTES); ?>"
                                            data-email="<?php echo htmlspecialchars($r['email'] ?? '', ENT_QUOTES); ?>"
                                            onclick="openEditModal(this)" title="Editar Cadastro"><i class="fas fa-edit"></i></button>
                                        
                                        <button type="button" class="btn-action" style="background:var(--success);" onclick="openCreditsModal('<?php echo $r['id']; ?>', '<?php echo htmlspecialchars($r['username'], ENT_QUOTES); ?>')" title="Gerenciar Créditos"><i class="fas fa-coins"></i></button>
                                        
                                        <a href="?block=<?php echo $r['id']; ?>" class="btn-action" style="background:var(--warning);" title="<?php echo $status_rev == 1 ? 'Bloquear' : 'Desbloquear'; ?>"><i class="fas <?php echo $status_rev == 1 ? 'fa-ban' : 'fa-unlock'; ?>"></i></a>
                                        
                                        <a href="?delete=<?php echo $r['id']; ?>" class="btn-action" style="background:var(--danger);" onclick="return confirm('Excluir este revendedor definitivamente?')" title="Excluir"><i class="fas fa-trash"></i></a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>

            <div style="display:flex; justify-content: space-between; align-items: center; margin-top: 15px; flex-wrap: wrap; gap:10px;">
                <div style="color: var(--text-muted); font-size: 13px;">
                    Exibindo <?php echo ($total_registros > 0) ? $offset + 1 : 0; ?> até <?php echo min($offset + $limit, $total_registros); ?> de <strong><?php echo $total_registros; ?></strong> registros
                </div>
                
                <?php if($total_paginas > 1): ?>
                <div class="pagination">
                    <?php
                    $qs = $_GET;
                    unset($qs['page']); 
                    $base_url = '?' . http_build_query($qs) . '&page=';
                    
                    if($page > 1) echo "<a href='".$base_url.($page-1)."' class='page-link'><i class='fas fa-chevron-left'></i></a>";
                    
                    $start = max(1, $page - 2);
                    $end = min($total_paginas, $page + 2);
                    
                    if($start > 1) { 
                        echo "<a href='".$base_url."1' class='page-link'>1</a>"; 
                        if($start > 2) echo "<span class='page-dots'>...</span>"; 
                    }
                    
                    for($i = $start; $i <= $end; $i++) {
                        $active = ($i == $page) ? 'active' : '';
                        echo "<a href='".$base_url.$i."' class='page-link $active'>$i</a>";
                    }
                    
                    if($end < $total_paginas) { 
                        if($end < $total_paginas - 1) echo "<span class='page-dots'>...</span>"; 
                        echo "<a href='".$base_url.$total_paginas."' class='page-link'>$total_paginas</a>"; 
                    }
                    
                    if($page < $total_paginas) echo "<a href='".$base_url.($page+1)."' class='page-link'><i class='fas fa-chevron-right'></i></a>";
                    ?>
                </div>
                <?php endif; ?>
            </div>
            
            <form id="bulkForm" method="POST" style="display:none;">
                <input type="hidden" name="action_bulk" value="1">
                <input type="hidden" name="bulk_type" id="bulkType">
                <input type="hidden" name="bulk_ids" id="bulkIds">
            </form>
            
        </div>
        <?php include 'rodape.php'; ?>
    </div>

    <div id="modalReseller" class="modal">
        <div class="modal-content">
            <h3 id="modalTitle" style="margin-top:0; color:white;"><i class="fas fa-user-tie"></i> Novo Revendedor</h3>
            <form method="POST">
                <input type="hidden" name="action_save" value="1">
                <input type="hidden" name="reseller_id" id="r_id">
                
                <div class="form-group-modal">
                    <label>Nome do Revendedor (Opcional)</label>
                    <input type="text" name="nome_revendedor" id="r_nome" placeholder="Ex: João da Silva">
                </div>

                <div class="form-group-modal">
                    <label>Usuário do Revendedor</label>
                    <input type="text" name="username" id="r_user" required>
                </div>
                <div class="form-group-modal">
                    <label>Senha</label>
                    <input type="text" name="password" id="r_pass" required>
                </div>
                <div class="form-group-modal">
                    <label>WhatsApp (Opcional)</label>
                    <input type="text" name="whatsapp" id="r_zap" placeholder="Ex: 5511999999999">
                </div>
                <div class="form-group-modal">
                    <label>E-mail (Opcional)</label>
                    <input type="email" name="email" id="r_email" placeholder="revendedor@email.com">
                </div>

                <button type="submit" class="btn-save-modal">SALVAR REVENDEDOR</button>
                <button type="button" onclick="closeAllModals()" style="width:100%; background:none; border:none; color:var(--text-muted); margin-top:10px; cursor:pointer;">Cancelar</button>
            </form>
        </div>
    </div>

    <div id="modalCredits" class="modal">
        <div class="modal-content">
            <h3 style="margin-top:0; color:white;"><i class="fas fa-coins" style="color:var(--success);"></i> Gerenciar Créditos</h3>
            <p style="color:var(--text-muted); font-size:13px;">Revendedor: <strong id="cr_name" style="color:white;"></strong></p>
            
            <form method="POST">
                <input type="hidden" name="action_credits" value="1">
                <input type="hidden" name="credits_reseller_id" id="cr_id">
                
                <div style="display:flex; justify-content:center; gap:10px; margin-bottom: 20px; margin-top: 15px;">
                    <label style="cursor:pointer; flex:1;">
                        <input type="radio" name="credits_type" value="add" required style="display:none;" onchange="updateCreditsBtn(this, 'add')" checked>
                        <div class="btn-month" style="background:var(--success); border-color:var(--success); text-align:center;"><i class="fas fa-plus"></i> Adicionar</div>
                    </label>
                    <label style="cursor:pointer; flex:1;">
                        <input type="radio" name="credits_type" value="remove" style="display:none;" onchange="updateCreditsBtn(this, 'remove')">
                        <div class="btn-month" style="text-align:center;"><i class="fas fa-minus"></i> Remover</div>
                    </label>
                </div>

                <div class="form-group-modal">
                    <label>Quantidade de Créditos</label>
                    <input type="number" name="credits_amount" min="1" step="0.1" required placeholder="Ex: 10">
                </div>

                <button type="submit" id="btn-submit-credits" class="btn-save-modal" style="background:var(--success);">CONFIRMAR TRANSFERÊNCIA</button>
                <button type="button" onclick="closeAllModals()" style="width:100%; background:none; border:none; color:var(--text-muted); margin-top:10px; cursor:pointer;">Cancelar</button>
            </form>
        </div>
    </div>

    <div id="modalView" class="modal">
        <div class="modal-content" style="display:flex; flex-direction:column;">
            <h3 style="margin-top:0; color:white;"><i class="fas fa-eye"></i> Dados do Revendedor</h3>
            
            <textarea id="view_text" rows="8" readonly style="width:100%; padding:15px; background:#0f1114; border:1px solid var(--border-color); color:#fff; border-radius:8px; resize:none; font-family: monospace; font-size:13px; margin-bottom:15px; box-sizing:border-box;"></textarea>
            
            <div style="display:flex; gap:10px;">
                <button type="button" onclick="copyText()" class="btn-main" style="width:100%; background:var(--accent); text-align:center; justify-content:center;"><i class="fas fa-copy"></i> COPIAR</button>
                <a id="btn_zap_view" href="#" target="_blank" class="btn-main" style="width:100%; background:#25d366; text-align:center; justify-content:center;"><i class="fab fa-whatsapp"></i> ENVIAR</a>
            </div>
            
            <button type="button" onclick="closeAllModals()" style="width:100%; background:none; border:none; color:var(--text-muted); margin-top:15px; cursor:pointer;">Fechar</button>
        </div>
    </div>

    <script>
        function toggleMenu() { 
            document.getElementById('sidebar').classList.toggle('active'); 
            document.getElementById('overlay').classList.toggle('active'); 
        }

        function toggleSubmenu(id) {
            var sub = document.getElementById(id);
            var arrow = document.getElementById('arrow-' + id);
            if (sub.style.display === "block") { 
                sub.style.display = "none"; 
                if(arrow) arrow.classList.remove('rotate'); 
            } else { 
                sub.style.display = "block"; 
                if(arrow) arrow.classList.add('rotate'); 
            }
        }

        var searchTimeout;
        function autoSubmitSearch() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(function() {
                document.getElementById('filterForm').submit();
            }, 600);
        }

        function toggleSelectAll(source) {
            var checkboxes = document.querySelectorAll('.user-checkbox');
            for (var i = 0; i < checkboxes.length; i++) {
                checkboxes[i].checked = source.checked;
            }
            toggleBulkActions();
        }

        function toggleBulkActions() {
            var checkboxes = document.querySelectorAll('.user-checkbox:checked');
            var bar = document.getElementById('bulkActionsBar');
            var countSpan = document.getElementById('selectedCount');
            
            if (checkboxes.length > 0) {
                countSpan.innerText = checkboxes.length;
                bar.style.display = 'flex';
            } else {
                bar.style.display = 'none';
                document.getElementById('selectAll').checked = false;
            }
        }

        function getSelectedIds() {
            var checkboxes = document.querySelectorAll('.user-checkbox:checked');
            var ids = [];
            for (var i = 0; i < checkboxes.length; i++) {
                ids.push(checkboxes[i].value);
            }
            return ids.join(',');
        }

        function submitBulk(type) {
            var ids = getSelectedIds();
            if (!ids) return;

            if (type === 'delete' && !confirm('Tem certeza que deseja EXCLUIR todos os revendedores selecionados? Essa ação não tem volta!')) return;
            if (type === 'block' && !confirm('Tem certeza que deseja alterar o status (Bloquear/Desbloquear) de todos os revendedores selecionados?')) return;

            document.getElementById('bulkType').value = type;
            document.getElementById('bulkIds').value = ids;
            document.getElementById('bulkForm').submit();
        }

        // ==========================================
        // BOTÃO DO OLHO E COMPROVANTE (ATUALIZADO)
        // ==========================================
        function showReceipt(btn) {
            var texto = btn.getAttribute('data-texto');
            var url = btn.getAttribute('data-zapurl');
            
            document.getElementById('view_text').value = texto;
            document.getElementById('btn_zap_view').href = url;
            document.getElementById('modalView').style.display = 'flex';
            
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }

        function copyText() {
            var texto = document.getElementById('view_text').value;
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(texto).then(function() {
                    alert('Copiado com sucesso!');
                    closeAllModals();
                });
            } else {
                var textArea = document.createElement("textarea");
                textArea.value = texto;
                document.body.appendChild(textArea);
                textArea.select();
                try {
                    document.execCommand('copy');
                    alert('Copiado com sucesso!');
                    closeAllModals();
                } catch (err) {}
                document.body.removeChild(textArea);
            }
        }

        function copiarMensagemAcesso() {
            var texto = document.getElementById('textoComprovante').value;
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(texto).then(function() {
                    fecharComprovante();
                });
            } else {
                var textArea = document.createElement("textarea");
                textArea.value = texto;
                document.body.appendChild(textArea);
                textArea.select();
                try {
                    document.execCommand('copy');
                    fecharComprovante();
                } catch (err) {}
                document.body.removeChild(textArea);
            }
        }

        function fecharComprovante() {
            var box = document.getElementById('comprovanteBox');
            if(box) box.style.display = 'none';
            var xhr = new XMLHttpRequest();
            xhr.open('GET', '?clear_msg=1', true);
            xhr.send();
        }

        function openAddModal() {
            document.getElementById('modalReseller').style.display = 'block';
            document.getElementById('modalTitle').innerHTML = '<i class="fas fa-user-tie"></i> Novo Revendedor';
            document.getElementById('r_id').value = '';
            document.getElementById('r_nome').value = '';
            document.getElementById('r_zap').value = '';
            document.getElementById('r_user').value = 'revenda' + Math.floor(Math.random() * 1000);
            document.getElementById('r_pass').value = Math.random().toString(36).slice(-6);
            document.getElementById('r_email').value = '';
        }

        function openEditModal(btn) {
            document.getElementById('modalReseller').style.display = 'block';
            document.getElementById('modalTitle').innerHTML = '<i class="fas fa-edit"></i> Editar Revendedor';
            
            document.getElementById('r_id').value = btn.getAttribute('data-id');
            document.getElementById('r_nome').value = btn.getAttribute('data-nome');
            document.getElementById('r_zap').value = btn.getAttribute('data-zap');
            document.getElementById('r_user').value = btn.getAttribute('data-user');
            document.getElementById('r_pass').value = btn.getAttribute('data-pass');
            document.getElementById('r_email').value = btn.getAttribute('data-email');
        }

        function openCreditsModal(id, nome) {
            document.getElementById('modalCredits').style.display = 'block';
            document.getElementById('cr_id').value = id;
            document.getElementById('cr_name').innerText = nome;
            
            var btns = document.querySelectorAll('#modalCredits .btn-month');
            btns[0].style.background = 'var(--success)';
            btns[0].style.borderColor = 'var(--success)';
            btns[1].style.background = '#1e2227';
            btns[1].style.borderColor = 'var(--border-color)';
            
            var radios = document.getElementsByName('credits_type');
            radios[0].checked = true;
            
            var btnSubmit = document.getElementById('btn-submit-credits');
            btnSubmit.style.background = 'var(--success)';
            btnSubmit.innerHTML = "CONFIRMAR TRANSFERÊNCIA";
        }

        function updateCreditsBtn(radioElem, type) {
            var btns = document.querySelectorAll('#modalCredits .btn-month');
            for(var i=0; i<btns.length; i++) {
                btns[i].style.background = '#1e2227';
                btns[i].style.borderColor = 'var(--border-color)';
            }
            
            var color = (type === 'add') ? 'var(--success)' : 'var(--danger)';
            
            radioElem.nextElementSibling.style.background = color;
            radioElem.nextElementSibling.style.borderColor = color;
            
            var btnSubmit = document.getElementById('btn-submit-credits');
            btnSubmit.style.background = color;
        }

        function closeAllModals() {
            var modals = document.querySelectorAll('.modal');
            for(var i=0; i<modals.length; i++) {
                modals[i].style.display = 'none';
            }
        }

        // --- SCRIPT EXCLUSIVO: GATILHO DE WHATSAPP AUTOMÁTICO NA TELA ---
        <?php if(isset($_SESSION['auto_zap_url'])): ?>
            window.onload = function() {
                window.location.href = '<?php echo $_SESSION['auto_zap_url']; ?>';
                <?php unset($_SESSION['auto_zap_url']); ?>
            }
        <?php endif; ?>

        setTimeout(function() {
            try {
                var alerts = document.querySelectorAll('.alert');
                for(var i=0; i<alerts.length; i++) {
                    alerts[i].style.transition = 'opacity 0.5s ease';
                    alerts[i].style.opacity = '0';
                }
                setTimeout(function() {
                    for(var j=0; j<alerts.length; j++) {
                        alerts[j].style.display = 'none';
                    }
                }, 500);
            } catch(e) {}
        }, 4000);
    </script>
</body>
</html>