<?php
session_start();

// Trava o relógio do sistema para o horário oficial do Brasil
date_default_timezone_set('America/Sao_Paulo');

require_once 'config.php';

// Limpa a sessão do comprovante APENAS quando o usuário clica no "X"
if (isset($_GET['clear_msg'])) {
    unset($_SESSION['comprovante']);
    exit;
}

$pdo = getConexaoAtiva();
// FORÇA O BANCO A FALAR EM UTF8 PARA ACABAR COM CARACTERES ESTRANHOS
$pdo->exec("SET NAMES utf8mb4");

// ====================================================================
// MÁGICA PARA VPS NOVA: DESLIGA O MODO ESTRITO DO MYSQL
// Isso impede o falso erro de "Usuário já existe" ao criar o cliente!
// ====================================================================
$pdo->exec("SET SESSION sql_mode = ''");

// --- INÍCIO: BUSCA DE PERSONALIZAÇÃO DINÂMICA E API WHATSAPP ---
$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;
            
            $confianca_status = isset($config_painel['confianca_status']) ? $config_painel['confianca_status'] : 0;
            $confianca_tempo = isset($config_painel['confianca_tempo']) ? $config_painel['confianca_tempo'] : 1;
            
            $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) {
    $confianca_status = 0;
    $confianca_tempo = 1;
}

// --- LÓGICA DE AUTO-CORREÇÃO AUTOMÁTICA ---
try {
    $check = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'whatsapp'");
    if (!$check->fetch()) { $pdo->exec("ALTER TABLE `users` ADD COLUMN `whatsapp` VARCHAR(255) DEFAULT NULL AFTER `password` text"); }
    
    $check_nome = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'nome_cliente'");
    if (!$check_nome->fetch()) { $pdo->exec("ALTER TABLE `users` ADD COLUMN `nome_cliente` VARCHAR(255) DEFAULT NULL"); }
    
    $check_bq = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'bouquet'");
    if (!$check_bq->fetch()) { $pdo->exec("ALTER TABLE `users` ADD COLUMN `bouquet` TEXT DEFAULT NULL AFTER `password` text"); }

    $check_trust = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'trust_used'");
    if (!$check_trust->fetch()) { $pdo->exec("ALTER TABLE `users` ADD COLUMN `trust_used` TINYINT(1) DEFAULT 0 AFTER `enabled` int"); }

    $pdo->exec("CREATE TABLE IF NOT EXISTS `painel_config` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `nome_painel` varchar(255) DEFAULT 'TOP IPTV',
        `logo_url` varchar(255) DEFAULT '',
        `cor_primaria` varchar(50) DEFAULT '#007bff',
        `confianca_status` tinyint(1) DEFAULT 0,
        `confianca_tempo` int(11) DEFAULT 1,
        PRIMARY KEY (`id`)
    )");
    
    // Garente as colunas da API do Whatsapp
    $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");
    }

    $c_rows = $pdo->query("SELECT COUNT(*) FROM `painel_config`")->fetchColumn();
    if ($c_rows == 0) { $pdo->exec("INSERT INTO `painel_config` (`nome_painel`) VALUES ('TOP IPTV')"); }
} catch (PDOException $e) {}

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

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

try {
    $user_credits = $pdo->query("SELECT credits FROM reg_users WHERE id = " . intval($my_id))->fetchColumn() ?: 0;
} catch (Exception $e) { $user_credits = 0; }

$template_file = __DIR__ . '/template_mensagem.txt';
$padrao_template = "Seu Acesso foi criado com sucesso!\n\n✅ *Usuário:* #username#\n✅ *Senha:* #password#\n🗓 *Valido até:* #exp_date#\n📺 *Telas:* #telas#\n\n--------------------------------------\n\n🟢 *Link M3U:* #m3u_encurtado#\n🟣 *Link HLS:* #m3u_hls_encurtado#\n📺 *Link SSIPTV:* #ssiptv_encurtado#\n🟣 *Link ROKU:* #roku_encurtado#";
$raw_template = file_exists($template_file) ? file_get_contents($template_file) : $padrao_template;

function gerarMensagemAcesso($username, $password, $whatsapp, $exp_date, $telas = 1) {
    global $raw_template, $pdo;
    
    // --- BUSCA DO LOAD BALANCER NA HORA DE GERAR O LINK ---
    $protocolo = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $dns = $protocolo . $_SERVER['HTTP_HOST']; // DNS PADRÃO COMO BACKUP

    try {
        $stmtLb = $pdo->query("SELECT ip_servidor, porta FROM servidores_lb WHERE status = 1 ORDER BY id DESC LIMIT 1");
        $lbAtivo = $stmtLb->fetch(PDO::FETCH_ASSOC);
        if ($lbAtivo && !empty($lbAtivo['ip_servidor'])) {
            $porta_lb = (isset($lbAtivo['porta']) && $lbAtivo['porta'] != 80) ? ":" . $lbAtivo['porta'] : "";
            $dns = "http://" . trim($lbAtivo['ip_servidor']) . $porta_lb;
        }
    } catch(Exception $e){}
    // -----------------------------------------------------

    $data_formatada = $exp_date ? date('d/m/Y', $exp_date) : 'Ilimitado';

    $link_m3u = "{$dns}/get.php?username={$username}&password={$password}&type=m3u_plus&output=mpegts";
    $link_hls = "{$dns}/get.php?username={$username}&password={$password}&type=m3u_plus&output=hls";
    $link_ssiptv = "{$dns}/ssiptv.php?username={$username}&password={$password}&ssiptv=1";
    $m3u_encurtado = "{$dns}/m3u-ts/{$username}/{$password}";
    $m3u_hls_encurtado = "{$dns}/m3u-m3u8/{$username}/{$password}";
    $ssiptv_encurtado = "{$dns}/ss-ts/{$username}/{$password}";
    $roku_encurtado = "{$dns}/roku/{$username}/{$password}";
    
    $m3u_completo = "{$dns}/get.php?username={$username}&password={$password}&type=m3u_plus&output=ts";

    $texto = str_replace(
        ['#username#', '#password#', '#exp_date#', '#telas#', '#url#', '#m3u_encurtado#', '#m3u_hls_encurtado#', '#ssiptv_encurtado#', '#roku_encurtado#', '#m3u_link#', '#m3u_link_hls#', '#m3u_completo#'],
        [$username, $password, $data_formatada, $telas, $dns, $m3u_encurtado, $m3u_hls_encurtado, $ssiptv_encurtado, $roku_encurtado, $link_m3u, $link_hls, $m3u_completo],
        $raw_template
    );
    return ['msg' => $texto, 'url' => "https://api.whatsapp.com/send?phone=".preg_replace('/\D/', '', (string)$whatsapp)."&text=".urlencode($texto)];
}

function gerarMensagemRenovacao($username, $password, $whatsapp, $exp_date) {
    $data_formatada = $exp_date ? date('d/m/Y', $exp_date) : 'Ilimitado';
    $texto = "✅ *RENOVAÇÃO CONCLUÍDA*\n\nSeu acesso foi renovado com sucesso!\n\n👤 *Usuário:* {$username}\n🔑 *Senha:* {$password}\n📅 *Novo Vencimento:* {$data_formatada}\n\nObrigado pela preferência! 🚀";
    return ['msg' => $texto, 'url' => "https://api.whatsapp.com/send?phone=".preg_replace('/\D/', '', (string)$whatsapp)."&text=".urlencode($texto)];
}

// =========================================================================
// O DISPARADOR INVISÍVEL (PUXANDO DADOS DO BANCO DE FORMA AUTOMÁTICA)
// =========================================================================
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;
}
// =========================================================================

// --- PROCESSAMENTO DE AÇÕES ---

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 member_id = " . intval($my_id) : "";
        if ($type === 'delete') {
            $pdo->exec("DELETE FROM users WHERE id IN ($id_list) $condicao_seguranca");
            $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Clientes excluídos em massa!</div>";
        } elseif ($type === 'block') {
            $pdo->exec("UPDATE users SET enabled = IF(enabled=1, 0, 1) WHERE id IN ($id_list) $condicao_seguranca");
            $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Status dos clientes alterado!</div>";
        } elseif ($type === 'exp') {
            $new_exp = !empty($_POST['bulk_exp_date']) ? strtotime($_POST['bulk_exp_date']) : null;
            $pdo->prepare("UPDATE users SET exp_date = ? WHERE id IN ($id_list) $condicao_seguranca")->execute([$new_exp]);
            $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Vencimento em massa aplicado!</div>";
        } elseif ($type === 'owner' && $role === 'admin') {
            $new_owner = intval($_POST['bulk_owner_id']);
            $pdo->prepare("UPDATE users SET member_id = ? WHERE id IN ($id_list)")->execute([$new_owner]);
            $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Dono(s) alterado(s) com sucesso!</div>";
        }
    }
}

if (isset($_POST['action_config_trust']) && $role === 'admin') {
    $c_status = isset($_POST['confianca_status']) ? 1 : 0;
    $c_tempo = intval($_POST['confianca_tempo']);
    if ($c_tempo < 1) $c_tempo = 1;
    $pdo->prepare("UPDATE painel_config SET confianca_status = ?, confianca_tempo = ?")->execute([$c_status, $c_tempo]);
    $confianca_status = $c_status; $confianca_tempo = $c_tempo;
    $mensagem = "<div class='alert success'><i class='fas fa-check'></i> Sistema de confiança atualizado!</div>";
}

if (isset($_POST['action_save'])) {
    $user = $_POST['username'];
    $pass = $_POST['password'];
    $zap  = $_POST['whatsapp'] ?? '';
    $nome_cliente = $_POST['nome_cliente'] ?? '';
    $telas = isset($_POST['max_connections']) ? intval($_POST['max_connections']) : 1;
    // Se a data de expiração não for enviada, garante 30 dias automaticamente
    $exp  = !empty($_POST['exp_date']) ? strtotime($_POST['exp_date']) : strtotime('+30 days');
    $id   = $_POST['user_id'] ?? null;
    $bouquets_selecionados = isset($_POST['user_bouquets']) ? json_encode($_POST['user_bouquets']) : '[]';

    try {
        if (!empty($id)) {
            // ATUALIZAÇÃO
            $pdo->prepare("UPDATE users SET username = ?, password = ?, whatsapp = ?, exp_date = ?, bouquet = ?, max_connections = ?, nome_cliente = ? WHERE id = ?")->execute([$user, $pass, $zap, $exp, $bouquets_selecionados, $telas, $nome_cliente, $id]);
            $mensagem = "<div class='alert success'>Dados atualizados com sucesso!</div>";
        } else {
            // CRIAÇÃO NOVA - VERIFICAÇÃO DE CRÉDITOS E DESCONTO
            $pode_criar = true;
            
            if ($role !== 'admin') {
                $stmtCred = $pdo->prepare("SELECT credits FROM reg_users WHERE id = ?");
                $stmtCred->execute([$my_id]);
                $revenda = $stmtCred->fetch();
                
                if (!$revenda || $revenda['credits'] < 1) {
                    $pode_criar = false;
                    $mensagem = "<div class='alert danger'><i class='fas fa-times-circle'></i> Saldo insuficiente! Você não possui créditos para criar um usuário.</div>";
                } else {
                    // DESCONTA 1 CRÉDITO DO SALDO ANTES DE SALVAR (CORREÇÃO DE BRECHA)
                    $pdo->prepare("UPDATE reg_users SET credits = credits - 1 WHERE id = ?")->execute([$my_id]);
                }
            }

            if ($pode_criar) {
                $created_at = time();
                $res = $pdo->prepare("INSERT INTO users (username, password, bouquet, whatsapp, exp_date, enabled, admin_enabled, member_id, is_p2p, trust_used, max_connections, created_at, nome_cliente) VALUES (?, ?, ?, ?, ?, 1, 0, ?, 0, 0, ?, ?, ?)")->execute([$user, $pass, $bouquets_selecionados, $zap, $exp, $my_id, $telas, $created_at, $nome_cliente]);
                
                if($res) {
                    // LOG DE CRIAÇÃO
                    if ($role !== 'admin') {
                        $agora = date('Y-m-d H:i:s');
                        $pdo->prepare("INSERT INTO logs_creditos (revendedor_id, cliente_user, acao, qtd_descontada, data_hora) VALUES (?, ?, 'Criacao de Conta', 1, ?)")->execute([$my_id, $user, $agora]);
                    }
                    
                    $msgInfo = gerarMensagemAcesso($user, $pass, $zap, $exp, $telas);
                    $_SESSION['comprovante'] = $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: clientes.php"); exit;
                }
            }
        }
    } catch (PDOException $e) { 
        $mensagem = "<div class='alert danger'><i class='fas fa-times-circle'></i> Erro ao salvar. Verifique se o usuário já existe.</div>"; 
    }
}

if (isset($_POST['action_renew'])) {
    $id_renovar = intval($_POST['renew_user_id']);
    $is_manual = (isset($_POST['renew_months']) && $_POST['renew_months'] === 'manual');
    $pode_renovar = true;

    if ($is_manual) {
        $nova_data = !empty($_POST['manual_exp_date']) ? strtotime($_POST['manual_exp_date']) : null;
        if ($nova_data) {
            if ($role !== 'admin') {
                $stmtCred = $pdo->prepare("SELECT credits FROM reg_users WHERE id = ?"); $stmtCred->execute([$my_id]);
                $revenda = $stmtCred->fetch();
                if (!$revenda || $revenda['credits'] < 1) { $pode_renovar = false; $mensagem = "<div class='alert danger'><i class='fas fa-times-circle'></i> Saldo insuficiente!</div>"; }
                else { $pdo->prepare("UPDATE reg_users SET credits = credits - 1 WHERE id = ?")->execute([$my_id]); }
            }
            if ($pode_renovar) {
                $pdo->prepare("UPDATE users SET exp_date = ?, enabled = 1, trust_used = 0 WHERE id = ?")->execute([$nova_data, $id_renovar]);
                $stmtM = $pdo->prepare("SELECT username FROM users WHERE id = ?"); $stmtM->execute([$id_renovar]); $uData = $stmtM->fetch();
                
                // --- REGISTRO DE LOG SEM ACENTOS ---
                if ($role !== 'admin') {
                    try {
                        $agora = date('Y-m-d H:i:s');
                        $pdo->prepare("INSERT INTO logs_creditos (revendedor_id, cliente_user, acao, qtd_descontada, data_hora) VALUES (?, ?, 'Renovacao Manual', 1, ?)")->execute([$my_id, $uData['username'], $agora]);
                    } catch(Exception $e) {}
                }
                
                $stmtM2 = $pdo->prepare("SELECT * FROM users WHERE id = ?"); $stmtM2->execute([$id_renovar]); $uDataFull = $stmtM2->fetch();
                $msgInfo = gerarMensagemRenovacao($uDataFull['username'], $uDataFull['password'], $uDataFull['whatsapp'], $uDataFull['exp_date']);
                $_SESSION['comprovante'] = $msgInfo;
                
                if (!empty($uDataFull['whatsapp'])) {
                    if ($wa_status == 1) {
                        enviarMsgZapInvisivel($uDataFull['whatsapp'], $msgInfo['msg']);
                    } else {
                        $_SESSION['auto_zap_url'] = $msgInfo['url'];
                    }
                }
                header("Location: clientes.php"); exit;
            }
        }
    } else {
        $meses = intval($_POST['renew_months']);
        if ($meses < 1) $meses = 1;
        if ($role !== 'admin') {
            $stmtCred = $pdo->prepare("SELECT credits FROM reg_users WHERE id = ?"); $stmtCred->execute([$my_id]);
            $revenda = $stmtCred->fetch();
            if (!$revenda || $revenda['credits'] < $meses) { $pode_renovar = false; $mensagem = "<div class='alert danger'><i class='fas fa-times-circle'></i> Saldo insuficiente!</div>"; }
            else { $pdo->prepare("UPDATE reg_users SET credits = credits - ? WHERE id = ?")->execute([$meses, $my_id]); }
        }
        if ($pode_renovar) {
            $segundos = $meses * 30 * 86400; 
            $pdo->prepare("UPDATE users SET exp_date = IF(exp_date > UNIX_TIMESTAMP(), exp_date + ?, UNIX_TIMESTAMP() + ?), enabled = 1, trust_used = 0 WHERE id = ?")->execute([$segundos, $segundos, $id_renovar]);
            $stmtM = $pdo->prepare("SELECT username FROM users WHERE id = ?"); $stmtM->execute([$id_renovar]); $uData = $stmtM->fetch();
            
            // --- REGISTRO DE LOG SEM ACENTOS ---
            if ($role !== 'admin') {
                try {
                    $agora = date('Y-m-d H:i:s');
                    $txt_acao = 'Renovacao (' . $meses . ' Meses)';
                    $pdo->prepare("INSERT INTO logs_creditos (revendedor_id, cliente_user, acao, qtd_descontada, data_hora) VALUES (?, ?, ?, ?, ?)")->execute([$my_id, $uData['username'], $txt_acao, $meses, $agora]);
                } catch(Exception $e) {}
            }
            
            $stmtM2 = $pdo->prepare("SELECT * FROM users WHERE id = ?"); $stmtM2->execute([$id_renovar]); $uDataFull = $stmtM2->fetch();
            $msgInfo = gerarMensagemRenovacao($uDataFull['username'], $uDataFull['password'], $uDataFull['whatsapp'], $uDataFull['exp_date']);
            $_SESSION['comprovante'] = $msgInfo;
            
            if (!empty($uDataFull['whatsapp'])) {
                if ($wa_status == 1) {
                    enviarMsgZapInvisivel($uDataFull['whatsapp'], $msgInfo['msg']);
                } else {
                    $_SESSION['auto_zap_url'] = $msgInfo['url'];
                }
            }
            header("Location: clientes.php"); exit;
        }
    }
}

if (isset($_POST['action_trust_renew']) && $confianca_status == 1) {
    $id_trust = intval($_POST['trust_user_id']);
    $stmtCh = $pdo->prepare("SELECT member_id, trust_used FROM users WHERE id = ?"); $stmtCh->execute([$id_trust]); $cli_trust = $stmtCh->fetch(PDO::FETCH_ASSOC);
    if ($cli_trust && ($role === 'admin' || $cli_trust['member_id'] == $my_id)) {
        if ($cli_trust['trust_used'] == 0) {
            $segundos_trust = $confianca_tempo * 86400; 
            $pdo->prepare("UPDATE users SET exp_date = IF(exp_date > UNIX_TIMESTAMP(), exp_date + ?, UNIX_TIMESTAMP() + ?), enabled = 1, trust_used = 1 WHERE id = ?")->execute([$segundos_trust, $segundos_trust, $id_trust]);
            $mensagem = "<div class='alert success'>Renovação de confiança aplicada!</div>";
        } else { $mensagem = "<div class='alert danger'><i class='fas fa-times-circle'></i> Este cliente já utilizou a renovação de confiança!</div>"; }
    }
}

if (isset($_GET['block'])) { $pdo->prepare("UPDATE users SET enabled = IF(enabled=1, 0, 1) WHERE id = ?")->execute([$_GET['block']]); header("Location: clientes.php"); exit; }
if (isset($_GET['delete'])) { $pdo->prepare("DELETE FROM users WHERE id = ?")->execute([$_GET['delete']]); header("Location: clientes.php"); exit; }

$search   = $_GET['search'] ?? '';
$status   = $_GET['status'] ?? 'ativos'; // PADRÃO AGORA É ATIVOS
$reseller = $_GET['reseller'] ?? 'todos';
$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_clause = "WHERE (u.is_p2p = 0 OR u.is_p2p IS NULL) AND (u.exp_date IS NULL OR (u.exp_date - UNIX_TIMESTAMP()) > 172800 OR u.exp_date < UNIX_TIMESTAMP())";
$params = [];

if ($role !== 'admin') { $where_clause .= " AND u.member_id = :my_id"; $params[':my_id'] = $my_id; }
elseif ($reseller !== 'todos') { $where_clause .= " AND u.member_id = :reseller_id"; $params[':reseller_id'] = $reseller; }

if (!empty($search)) { $where_clause .= " AND u.username LIKE :search"; $params[':search'] = "%$search%"; }

if ($status === 'ativos') { $where_clause .= " AND u.enabled = 1 AND (u.exp_date > UNIX_TIMESTAMP() OR u.exp_date IS NULL)"; }
elseif ($status === 'vencidos') { $where_clause .= " AND u.enabled = 1 AND u.exp_date < UNIX_TIMESTAMP()"; }
elseif ($status === 'bloqueados') { $where_clause .= " AND u.enabled = 0"; }

$stmt_count = $pdo->prepare("SELECT COUNT(u.id) FROM users u LEFT JOIN reg_users r ON u.member_id = r.id " . $where_clause);
foreach ($params as $key => $val) { $stmt_count->bindValue($key, $val); }
$stmt_count->execute();
$total_registros = $stmt_count->fetchColumn();
$total_paginas = ceil($total_registros / $limit);

$query = "SELECT u.*, r.username AS reseller_name FROM users u LEFT JOIN reg_users r ON u.member_id = r.id " . $where_clause . " ORDER BY u.id DESC LIMIT $limit OFFSET $offset";
$stmt = $pdo->prepare($query);
foreach ($params as $key => $val) { $stmt->bindValue($key, $val); }
$stmt->execute();
$usuarios = $stmt->fetchAll(PDO::FETCH_ASSOC);

$revendedores = [];
if ($role === 'admin') { $revendedores = $pdo->query("SELECT id, username FROM reg_users WHERE member_group_id != 1 ORDER BY username ASC")->fetchAll(PDO::FETCH_ASSOC); }
$bouquets_lista = $pdo->query("SELECT id, bouquet_name FROM bouquets ORDER BY bouquet_name ASC")->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">
    <title>Clientes - <?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); }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(255, 255, 255, 0.05); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .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: #dc3545; color: white; text-align: center; text-decoration: none; font-weight: bold; margin-top: auto; }
        .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; }
        .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; }
        .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; }
        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; }
        .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); }
        .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-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; }
        #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; }
        .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); }
        .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; align-items: center; justify-content: center; }
        .modal-content { background: var(--bg-card); width: 90%; max-width: 450px; 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;}
        .btn-month { background: #1e2227; color: white; border: 1px solid var(--border-color); padding: 8px 12px; border-radius: 5px; cursor: pointer; transition: 0.2s; font-size: 13px; font-weight: bold; text-align: center;}
        .btn-month:hover { background: var(--accent); border-color: var(--accent); }
        .bouquet-grid { max-height: 150px; overflow-y: auto; background: #121519; padding: 10px; border-radius: 5px; border: 1px solid var(--border-color); }
        .bouquet-item { display: flex; align-items: center; gap: 8px; font-size: 13px; margin-bottom: 5px; color: white;}
        
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: bold; font-size: 14px; transition: opacity 0.5s ease;}
        .alert.success { background: rgba(40, 167, 69, 0.1); color: var(--success); border: 1px solid var(--success); }
        .alert.danger { background: rgba(220, 53, 69, 0.15); color: #e74c3c; border: 1px solid #e74c3c; }

        .input-group-gen { display: flex; width: 100%; }
        .input-group-gen input { border-radius: 5px 0 0 5px; flex: 1; }
        .input-group-gen button { background: var(--border-color); border: none; color: var(--text-main); padding: 0 15px; border-radius: 0 5px 5px 0; cursor: pointer; transition: 0.2s; }
        .input-group-gen button:hover { background: var(--accent); color: white; }
        
        .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); }

        @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%; margin: auto; } .filter-bar { flex-direction: column; align-items: stretch; } #bulkActionsBar { flex-direction: column; align-items: stretch; } }
    </style>
</head>
<body>

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

    <nav class="sidebar" id="sidebar">
        <div class="sidebar-header" style="overflow: hidden; display: flex; align-items: center; justify-content: center; min-height: 80px; padding: 10px;">
            <?php if(!empty($logo_url)): ?>
                <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" style="width: 100%; max-width: 180px; height: auto; max-height: 60px; object-fit: contain; display: block; margin: 0 auto;">
            <?php else: ?>
                <span style="color: var(--accent);"><?php echo htmlspecialchars($nome_painel); ?></span>
            <?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>
            
            <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_whatsapp.php" class="menu-item active"><i class="fas fa-plug"></i> Integrações API</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="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>
                 <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">
            <button class="menu-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <h2 style="margin:0; font-size: 18px; color:white;">Clientes IPTV</h2>
            <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'])) {
                $comp_display = 'flex';
                $comp_msg = htmlspecialchars($_SESSION['comprovante']['msg'], ENT_QUOTES, 'UTF-8');
                $comp_url = htmlspecialchars($_SESSION['comprovante']['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;'>Dados do Cliente</strong><br><span style='color: #d1d5da; font-size:13px;'>Copie ou envie o acesso.</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 Usuário</label><input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Ex: joao123" onkeyup="autoSubmitSearch()"></div>
                    <div class="filter-group">
                        <label>Status</label>
                        <select name="status" onchange="this.form.submit()">
                            <option value="todos" <?php echo $status=='todos'?'selected':'';?>>Todos</option>
                            <option value="ativos" <?php echo $status=='ativos'?'selected':'';?>>Ativos</option>
                            <option value="vencidos" <?php echo $status=='vencidos'?'selected':'';?>>Vencidos</option>
                            <option value="bloqueados" <?php echo $status=='bloqueados'?'selected':'';?>>Bloqueados</option>
                        </select>
                    </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>
                    <?php if($role === 'admin'): ?><div class="filter-group"><label>Revendedor</label><select name="reseller" onchange="this.form.submit()"><option value="todos">Todos</option><option value="<?php echo $my_id; ?>" <?php echo $reseller==$my_id?'selected':'';?>>Meus Clientes</option><?php foreach($revendedores as $rev): ?><option value="<?php echo $rev['id']; ?>" <?php echo $reseller==$rev['id']?'selected':'';?>><?php echo htmlspecialchars($rev['username']); ?></option><?php endforeach; ?></select></div><?php endif; ?>
                    <div style="margin-left: auto; display:flex; gap:10px; flex-wrap:wrap;">
                        <?php if($role === 'admin'): ?><button type="button" class="btn-filter" style="background:#f39c12;" onclick="openModal('modalConfigTrust'); return false;"><i class="fas fa-handshake"></i> Sistema de Confiança</button><?php endif; ?>
                        <button type="button" class="btn-filter" style="background:var(--success);" onclick="openAddModal(); return false;"><i class="fas fa-user-plus"></i> Novo Cliente</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</button>
                    <button type="button" onclick="openModal('modalBulkExp')" class="btn-bulk" style="background:var(--info);"><i class="fas fa-calendar-alt"></i> Vencimento</button>
                    <?php if($role === 'admin'): ?>
                    <button type="button" onclick="openModal('modalBulkOwner')" class="btn-bulk" style="background:#8b5cf6;"><i class="fas fa-user-tie"></i> Mudar Dono</button>
                    <?php endif; ?>
                    <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>Cliente</th>
                            <th>Usuário</th>
                            <th>Senha</th>
                            <th>WhatsApp</th>
                            <?php if($role === 'admin') echo "<th>Dono</th>"; ?>
                            <th>Vencimento</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($usuarios)): ?><tr><td colspan="8" style="text-align:center;">Nenhum cliente encontrado.</td></tr>
                        <?php else: foreach ($usuarios as $u): 
                            $vencido = ($u['exp_date'] < time() && $u['exp_date'] != 0);
                            $badge_class = $u['enabled'] == 0 ? 'bg-danger' : ($vencido ? 'bg-danger' : 'bg-success');
                            $badge_text = $u['enabled'] == 0 ? 'BLOQUEADO' : ($vencido ? 'VENCIDO' : 'ATIVO');
                        ?>
                            <tr>
                                <td style="text-align: center;"><input type="checkbox" class="user-checkbox" value="<?php echo $u['id']; ?>" onchange="toggleBulkActions()" style="cursor:pointer; width:16px; height:16px; accent-color: var(--accent);"></td>
                                <td>
                                    <?php if(!empty($u['nome_cliente'])): ?>
                                        <span style="font-size:14px; font-weight:bold; color:var(--text-main);"><i class="fas fa-user" style="color:var(--text-muted); margin-right:5px;"></i> <?php echo htmlspecialchars($u['nome_cliente']); ?></span>
                                    <?php else: ?>
                                        <span style="color:var(--text-muted); font-size:12px;">---</span>
                                    <?php endif; ?>
                                </td>
                                <td><strong><?php echo htmlspecialchars($u['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($u['password']); ?></td>
                                <td><?php if(!empty($u['whatsapp'])): ?><a href="https://wa.me/<?php echo preg_replace('/\D/', '', $u['whatsapp']); ?>" target="_blank" style="color:#25d366; text-decoration:none;"><i class="fab fa-whatsapp"></i> <?php echo htmlspecialchars($u['whatsapp']); ?></a><?php else: echo "<span style='color:var(--text-muted);'>---</span>"; endif; ?></td>
                                <?php if($role === 'admin'): ?><td style="color:var(--text-muted); font-size:12px;"><?php echo $u['member_id'] == $my_id ? 'Admin' : htmlspecialchars($u['reseller_name']); ?></td><?php endif; ?>
                                <td><?php echo $u['exp_date'] ? date('d/m/Y H:i', $u['exp_date']) : 'Ilimitado'; ?></td>
                                <td>
                                    <?php $msgInfo = gerarMensagemAcesso($u['username'], $u['password'], $u['whatsapp'], $u['exp_date'], $u['max_connections']); ?>
                                    
                                    <!-- AQUI ESTÁ O FLEXBOX QUE MANTÉM OS BOTÕES LADO A LADO SEM EMPURRAR PARA BAIXO NO CELULAR -->
                                    <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)"><i class="fas fa-eye"></i></button>
                                        
                                        <button type="button" class="btn-action" style="background:var(--accent);" data-id="<?php echo $u['id']; ?>" data-nome="<?php echo htmlspecialchars($u['nome_cliente'] ?? '', ENT_QUOTES); ?>" data-user="<?php echo htmlspecialchars($u['username'], ENT_QUOTES); ?>" data-pass="<?php echo htmlspecialchars($u['password'], ENT_QUOTES); ?>" data-zap="<?php echo htmlspecialchars($u['whatsapp'], ENT_QUOTES); ?>" data-telas="<?php echo $u['max_connections']; ?>" data-exp="<?php echo $u['exp_date'] ? date('Y-m-d\TH:i', $u['exp_date']) : ''; ?>" data-bq='<?php echo htmlspecialchars($u['bouquet'] ?? '[]', ENT_QUOTES); ?>' onclick="openEditModal(this)"><i class="fas fa-edit"></i></button>
                                        
                                        <button type="button" class="btn-action" style="background:#8b5cf6;" title="Sincronizar" onclick="sincronizarCliente(<?php echo $u['id']; ?>)"><i class="fas fa-broom"></i></button>
                                        
                                        <button type="button" class="btn-action" style="background:var(--success);" onclick="openRenewModal('<?php echo $u['id']; ?>')"><i class="fas fa-sync-alt"></i></button>
                                        
                                        <?php if($confianca_status == 1 && $u['trust_used'] == 0): ?>
                                        <button type="button" class="btn-action" style="background:#f39c12;" title="Renovação de Confiança (Dias Extras)" onclick="trustRenew('<?php echo $u['id']; ?>')"><i class="fas fa-handshake"></i></button>
                                        <?php endif; ?>
                                        
                                        <a href="?block=<?php echo $u['id']; ?>" class="btn-action" style="background:var(--warning);"><i class="fas <?php echo $u['enabled'] ? 'fa-ban' : 'fa-unlock'; ?>"></i></a>
                                        
                                        <a href="?delete=<?php echo $u['id']; ?>" class="btn-action" style="background:var(--danger);" onclick="return confirm('Excluir definitivamente?')"><i class="fas fa-trash"></i></a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($total_paginas > 1): ?>
            <div class="pagination" style="margin-top: 20px; align-items: center; gap: 15px; justify-content: center;">
                <span style="color: var(--text-muted); font-size: 13px;">Página <?php echo $page; ?> de <?php echo $total_paginas; ?></span>
                <div>
                    <?php if ($page > 1): ?>
                        <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" class="page-link">&laquo; Anterior</a>
                    <?php endif; ?>
                    <?php if ($page < $total_paginas): ?>
                        <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" class="page-link">Próxima &raquo;</a>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
            
            <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"><input type="hidden" name="bulk_exp_date" id="bulkExpDate"><input type="hidden" name="bulk_owner_id" id="bulkOwnerId"></form>
            
            <form id="trustRenewForm" method="POST" style="display:none;">
                <input type="hidden" name="action_trust_renew" value="1">
                <input type="hidden" name="trust_user_id" id="trustUserId">
            </form>
        </div>
        <?php include 'rodape.php'; ?>
    </div>

    <div id="modalClient" class="modal">
        <div class="modal-content">
            <h3 id="modalTitle" style="margin-top:0; color:white;"><i class="fas fa-user-plus"></i> Novo Cliente</h3>
            <form method="POST">
                <input type="hidden" name="action_save" value="1"><input type="hidden" name="user_id" id="u_id">
                
                <div class="form-group-modal">
                    <label>Nome do Cliente (Opcional)</label>
                    <input type="text" name="nome_cliente" id="u_nome" placeholder="Ex: João Silva">
                </div>

                <div class="form-group-modal">
                    <label>Usuário</label>
                    <div class="input-group-gen">
                        <input type="text" name="username" id="u_user" required>
                        <button type="button" onclick="gerarAleatorio('u_user')" title="Gerar Usuário Aleatório"><i class="fas fa-dice"></i></button>
                    </div>
                </div>
                
                <div class="form-group-modal">
                    <label>Senha</label>
                    <div class="input-group-gen">
                        <input type="text" name="password" id="u_pass" required>
                        <button type="button" onclick="gerarAleatorio('u_pass')" title="Gerar Senha Aleatória"><i class="fas fa-dice"></i></button>
                    </div>
                </div>
                
                <div class="form-group-modal"><label>WhatsApp (Opcional)</label><input type="text" name="whatsapp" id="u_zap" placeholder="Ex: 5511999999999"></div>
                <div class="form-group-modal"><label>Quantidade de Telas (Conexões)</label><input type="number" name="max_connections" id="u_telas" value="1" min="1" max="10"></div>
                <div class="form-group-modal"><label>Data de Vencimento</label><input type="datetime-local" name="exp_date" id="u_exp"></div>
                
                <div class="form-group-modal"><label>Pacote(s) Liberado(s)</label><div class="bouquet-grid"><?php foreach($bouquets_lista as $bq): ?><label class="bouquet-item"><input type="checkbox" name="user_bouquets[]" value="<?php echo $bq['id']; ?>" class="bq-check"> <?php echo htmlspecialchars($bq['bouquet_name']); ?></label><?php endforeach; ?></div></div>
                
                <button type="submit" class="btn-save-modal">SALVAR CLIENTE</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="modalRenew" class="modal">
        <div class="modal-content" style="text-align:center;"><h3 style="margin-top:0; color:white;"><i class="fas fa-sync-alt" style="color:var(--success);"></i> Renovar Conta</h3>
            <form method="POST"><input type="hidden" name="action_renew" value="1"><input type="hidden" name="renew_user_id" id="r_id"><div style="display:flex; justify-content:center; gap:10px; margin-bottom:20px; flex-wrap:wrap;"><?php foreach([1,2,3,6,12] as $m): ?><label style="cursor:pointer;"><input type="radio" name="renew_months" value="<?php echo $m; ?>" style="display:none;" onchange="updateRenewBtn(this, '<?php echo $m; ?>')"><div class="btn-month"><?php echo $m < 12 ? "$m Mês" : "1 Ano"; ?></div></label><?php endforeach; ?><label style="cursor:pointer;"><input type="radio" name="renew_months" value="manual" style="display:none;" onchange="updateRenewBtn(this, 'manual')"><div class="btn-month">Manual</div></label></div><div id="manualDateDiv" style="display:none; text-align:left;"><label style="font-size:12px; color:var(--text-muted); font-weight:bold;">Data Exata:</label><input type="datetime-local" name="manual_exp_date" style="width:100%; padding:10px; background:#121519; border:1px solid var(--border-color); color:white; border-radius:5px;"></div><button type="submit" id="btn-submit-renew" class="btn-save-modal" style="background:var(--success); margin-top:15px;" disabled>Selecione um prazo</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="modalBulkExp" class="modal">
        <div class="modal-content">
            <h3 style="margin-top:0; color:white;"><i class="fas fa-calendar-alt" style="color:var(--info);"></i> Alterar Vencimento (Massa)</h3>
            <p style="color:var(--text-muted); font-size:13px;">Defina uma nova data de vencimento para todos os clientes selecionados.</p>
            <div class="form-group-modal">
                <label>Nova Data de Vencimento</label>
                <input type="datetime-local" id="bulk_new_exp" required>
            </div>
            <button type="button" onclick="submitBulk('exp')" class="btn-save-modal" style="background:var(--info);">APLICAR EM TODOS</button>
            <button type="button" onclick="closeAllModals()" style="width:100%; background:none; border:none; color:var(--text-muted); margin-top:10px; cursor:pointer;">Cancelar</button>
        </div>
    </div>

    <?php if($role === 'admin'): ?>
    <div id="modalBulkOwner" class="modal">
        <div class="modal-content">
            <h3 style="margin-top:0; color:white;"><i class="fas fa-user-tie" style="color:#8b5cf6;"></i> Alterar Dono (Revendedor)</h3>
            <p style="color:var(--text-muted); font-size:13px;">Transfira os clientes selecionados para outro revendedor ou para você.</p>
            <div class="form-group-modal">
                <label>Novo Dono</label>
                <select id="bulk_new_owner" required>
                    <option value="<?php echo $my_id; ?>">Mim (Administrador)</option>
                    <?php foreach($revendedores as $rev): ?>
                        <option value="<?php echo $rev['id']; ?>"><?php echo htmlspecialchars($rev['username']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="button" onclick="submitBulk('owner')" class="btn-save-modal" style="background:#8b5cf6;">TRANSFERIR CLIENTES</button>
            <button type="button" onclick="closeAllModals()" style="width:100%; background:none; border:none; color:var(--text-muted); margin-top:10px; cursor:pointer;">Cancelar</button>
        </div>
    </div>
    <?php endif; ?>

    <div id="modalConfigTrust" class="modal">
        <div class="modal-content">
            <h3 style="margin-top:0; color:white;"><i class="fas fa-handshake" style="color:#f39c12;"></i> Configurar Confiança</h3>
            <p style="color:var(--text-muted); font-size:13px;">Permita que você e seus revendedores liberem dias de cortesia para clientes em atraso.</p>
            <form method="POST">
                <input type="hidden" name="action_config_trust" value="1">
                <div class="form-group-modal" style="margin-top: 20px;">
                    <label style="display:flex; align-items:center; gap:10px; color:white; font-size:14px; cursor:pointer;">
                        <input type="checkbox" name="confianca_status" value="1" <?php echo $confianca_status == 1 ? 'checked' : ''; ?> style="width:20px; height:20px; margin:0;"> 
                        Ativar Renovação de Confiança
                    </label>
                </div>
                <div class="form-group-modal">
                    <label>Tempo liberado (em Dias)</label>
                    <input type="number" name="confianca_tempo" value="<?php echo htmlspecialchars($confianca_tempo); ?>" min="1" required>
                </div>
                <button type="submit" class="btn-save-modal" style="background:#f39c12;">SALVAR CONFIGURAÇÕES</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>

    <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('EXCLUIR?')) return; 
            if (type === 'exp') { 
                var novaData = document.getElementById('bulk_new_exp').value; 
                if (!novaData) { alert('Informe a data!'); return; } 
                document.getElementById('bulkExpDate').value = novaData; 
            } 
            if (type === 'owner') { 
                var novoDono = document.getElementById('bulk_new_owner').value; 
                if (!novoDono) { alert('Selecione um dono!'); return; } 
                document.getElementById('bulkOwnerId').value = novoDono; 
            } 
            document.getElementById('bulkType').value = type; 
            document.getElementById('bulkIds').value = ids; 
            document.getElementById('bulkForm').submit(); 
        }

        function showReceipt(btn) { document.getElementById('textoComprovante').value = btn.getAttribute('data-texto'); document.getElementById('btnZapLink').href = btn.getAttribute('data-zapurl'); document.getElementById('comprovanteBox').style.display = 'flex'; window.scrollTo({ top: 0, behavior: 'smooth' }); }
        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() { document.getElementById('comprovanteBox').style.display = 'none'; var xhr = new XMLHttpRequest(); xhr.open('GET', '?clear_msg=1', true); xhr.send(); }
        
        function openModal(id) { document.getElementById(id).style.display = 'flex'; }
        function closeAllModals() { var modals = document.querySelectorAll('.modal'); for(var i=0; i<modals.length; i++) { modals[i].style.display = 'none'; } }
        
        function gerarAleatorio(inputID) {
            const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
            let result = '';
            for (let i = 0; i < 6; i++) {
                result += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            document.getElementById(inputID).value = result;
        }
        
        function openAddModal() { 
            document.getElementById('u_id').value = ''; 
            document.getElementById('u_nome').value = ''; 
            document.getElementById('u_user').value = ''; 
            document.getElementById('u_pass').value = ''; 
            document.getElementById('u_zap').value = ''; 
            document.getElementById('u_telas').value = '1'; 
            document.getElementById('u_exp').value = '<?php echo date("Y-m-d\TH:i", strtotime("+30 days")); ?>'; 
            
            var chks = document.querySelectorAll('.bq-check'); 
            for(var i=0; i<chks.length; i++) { chks[i].checked = false; }
            
            openModal('modalClient'); 
        }
        
        function openEditModal(btn) { 
            document.getElementById('u_id').value = btn.getAttribute('data-id'); 
            document.getElementById('u_nome').value = btn.getAttribute('data-nome'); 
            document.getElementById('u_user').value = btn.getAttribute('data-user'); 
            document.getElementById('u_pass').value = btn.getAttribute('data-pass'); 
            document.getElementById('u_zap').value = btn.getAttribute('data-zap'); 
            document.getElementById('u_telas').value = btn.getAttribute('data-telas'); 
            document.getElementById('u_exp').value = btn.getAttribute('data-exp'); 
            var bqs = btn.getAttribute('data-bq'); 
            var chks = document.querySelectorAll('.bq-check'); for(var i=0; i<chks.length; i++) { chks[i].checked = (bqs && bqs.indexOf('"' + chks[i].value + '"') !== -1); }
            openModal('modalClient'); 
        }
        
        function openRenewModal(id) { 
            document.getElementById('r_id').value = id; 
            document.getElementById('btn-submit-renew').disabled = true; 
            document.getElementById('manualDateDiv').style.display = 'none';
            var btns = document.querySelectorAll('.btn-month'); for(var i=0; i<btns.length; i++) { btns[i].style.background = '#1e2227'; }
            openModal('modalRenew'); 
        }

        function updateRenewBtn(radioElem, meses) { 
            var btns = document.querySelectorAll('.btn-month'); for(var i=0; i<btns.length; i++) { btns[i].style.background='#1e2227'; } 
            radioElem.nextElementSibling.style.background='var(--accent)'; 
            document.getElementById('btn-submit-renew').disabled = false;
            document.getElementById('manualDateDiv').style.display = (meses === 'manual') ? 'block' : 'none';
        }

        function sincronizarCliente(idCliente) {
            if(confirm("Tem certeza que deseja sincronizar este cliente?\n\nIsso vai limpar conexões travadas e resetar o IP/MAC do aparelho dele.")) {
                fetch('ajax_sincronizar.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'id_cliente=' + idCliente
                })
                .then(response => response.json())
                .then(data => {
                    if(data.sucesso) {
                        alert("✅ " + data.msg);
                    } else {
                        alert("❌ Erro: " + data.erro);
                    }
                })
                .catch(error => {
                    alert("❌ Erro de comunicacao.");
                });
            }
        }
        
        function trustRenew(id) {
            if(confirm("Deseja aplicar a renovação de confiança (dias de cortesia) para este cliente?")) {
                document.getElementById('trustUserId').value = id;
                document.getElementById('trustRenewForm').submit();
            }
        }
      
        // --- 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.opacity = '0'; 
                    alerts[i].style.transition = 'opacity 0.5s ease';
                } 
                setTimeout(function(){ 
                    for(var j=0; j<alerts.length; j++) { 
                        alerts[j].style.display = 'none'; 
                    } 
                }, 500); 
            } catch(e) {} 
        }, 4000);
    </script>
    
</body>
</html>