<?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");

// --- INÍCIO: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---
$nome_painel = 'TOP IPTV';
$logo_url = '';
$cor_primaria = '#007bff';

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;
        }
    }
} 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 = "";

// --- FUNÇÕES DE MENSAGENS PARA O REVENDEDOR ---
function gerarMensagemRevenda($username, $password) {
    $prot = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $link_painel = $prot . $_SERVER['HTTP_HOST'];
    $texto = "🚀 *DADOS DO REVENDEDOR*\n\n🔗 *Painel:* {$link_painel}\n👤 *Usuário:* {$username}\n🔑 *Senha:* {$password}";
    return ['msg' => $texto, 'url' => "https://wa.me/?text=".urlencode($texto)];
}

function gerarMensagemCredito($username, $qtd) {
    $texto = "✅ *CRÉDITOS ADICIONADOS*\n\nOlá *{$username}*, foram adicionados *{$qtd}* créditos na sua conta de Revenda!\n\nBoas vendas! 🚀";
    return ['msg' => $texto, 'url' => "https://wa.me/?text=".urlencode($texto)];
}

// --- 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'] ?? '';
    $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 = ? WHERE id = ?")->execute([$user, $pass, $email, $id_editar]);
            $mensagem = "<div class='alert success'>Revenda atualizada!</div>";
        }
    } else {
        $sql = "INSERT INTO reg_users (username, password, email, credits, member_group_id, owner_id, date_registered, status) VALUES (?, ?, ?, 0, 2, ?, ?, 1)";
        $res = $pdo->prepare($sql)->execute([$user, $pass, $email, $my_id, time()]);
        if($res) {
            $_SESSION['comprovante_revenda'] = gerarMensagemRevenda($user, $pass);
            header("Location: revendedores.php"); exit;
        }
    }
}

// --- ADICIONAR / REMOVER CRÉDITOS COM TRAVA DE SEGURANÇA ---
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 para a mensagem
            $stmtR = $pdo->prepare("SELECT username FROM reg_users WHERE id = ?");
            $stmtR->execute([$r_id]);
            $revName = $stmtR->fetchColumn();
            
            $_SESSION['comprovante_revenda'] = gerarMensagemCredito($revName, $qtd);
            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 ?"; $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: 800px; }
        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-right: 4px; 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 { 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="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>
            
            <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>

            <div class="menu-category">Integração</div>
            <a href="pagamentos.php" class="menu-item active"><i class="fas fa-dollar-sign"></i> Pagamento Automático</a>
            
            <a href="admin_planos.php" class="menu-item active"><i class="fas fa-tags"></i> Meus Planos de Venda</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>

            <?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>
                
                <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="dns_manager.php" class="menu-item active"><i class="fas fa-link"></i> Alterar DNS</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>

                <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>
            <?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>Usuário</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="6" 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>
                                    <strong><?php echo htmlspecialchars($r['username']); ?></strong><br>
                                    <span class="badge <?php echo $badge_class; ?>"><?php echo $badge_text; ?></span>
                                </td>
                                <td style="color:var(--text-muted);"><?php echo htmlspecialchars($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']); 
                                    ?>
                                    <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-user="<?php echo htmlspecialchars($r['username'], ENT_QUOTES); ?>"
                                        data-pass="<?php echo htmlspecialchars($r['password'], 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>
                                </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>
    </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>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>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">
            <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';
        }

        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_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_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';
            }
        }

        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>
