<?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'; 

$pdo = getConexaoAtiva(); // Banco Principal (Xtream ou XUI)
$pdo_int = getConexaoInterna(); // Banco Local (Garante configs e saldos)

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

// ====================================================================
// INTELIGÊNCIA ARTIFICIAL: DETECTA SE É XUI ONE OU XTREAM UI
// ====================================================================
$modo_ativo = 'interno';
try {
    $modo_ativo = $pdo_int->query("SELECT modo_ativo FROM configuracoes LIMIT 1")->fetchColumn() ?: 'interno';
} catch (Exception $e) {}

$tabela_clientes = ($modo_ativo === 'xui') ? '`lines`' : '`users`';
$col_whatsapp = ($modo_ativo === 'xui') ? 'phone' : 'whatsapp';

// FILTRO CIRÚRGICO: Separa IPTV de P2P usando a senha universal
$cond_p2p = "password != 'topiptv1724'"; 

if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }
$role = $_SESSION['user_role'] ?? 'reseller'; 
$nome_usuario = $_SESSION['username'] ?? 'Usuário';
$user_id_logado = $_SESSION['user_id'];

// ==============================================================================
// --- LÓGICA DE AUTO-CORREÇÃO AUTOMÁTICA DO BANCO (INCLUI PERMISSÃO DE TESTE) ---
// ==============================================================================
try {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    if ($modo_ativo !== 'xui') {
        $check_p2p = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'is_p2p'");
        if (!$check_p2p->fetch()) {
            $pdo->exec("ALTER TABLE `users` ADD COLUMN `is_p2p` INT DEFAULT 0 AFTER `enabled`");
        }
        
        $check_last = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'last_activity'");
        if (!$check_last->fetch()) {
            $pdo->exec("ALTER TABLE `users` ADD COLUMN `last_activity` INT(11) DEFAULT 0");
        }
        
        $check_channel = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'current_channel'");
        if (!$check_channel->fetch()) {
            $pdo->exec("ALTER TABLE `users` ADD COLUMN `current_channel` INT(11) DEFAULT NULL");
        }
    }
    
    // Adiciona a coluna permitir_teste_revenda se não existir no banco interno
    $check_perm_teste = $pdo_int->query("SHOW COLUMNS FROM `painel_config` LIKE 'permitir_teste_revenda'");
    if (!$check_perm_teste->fetch()) {
        $pdo_int->exec("ALTER TABLE `painel_config` ADD COLUMN `permitir_teste_revenda` TINYINT(1) DEFAULT 1");
    }
} catch (PDOException $e) {}

// ==============================================================================
// --- MINI API PARA GERAR TESTE VIA AJAX DIRETO NO DASHBOARD (COM TEMPLATES E TRAVA DE SALDO) ---
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_gerar_teste'])) {
    header('Content-Type: application/json');
    $tipo_teste = $_POST['tipo']; // 'iptv' ou 'p2p'
    $tempo_horas = 4; // Padrão
    $permitir_teste_revenda = 1;
    
    // Busca configurações do banco
    $senha_p2p = '123456';
    $api_p2p_url = '';
    $api_p2p_key = '';
    try {
        $conf = $pdo_int->query("SELECT tempo_teste, senha_p2p, api_p2p_url, api_p2p_key, permitir_teste_revenda FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($conf) {
            if ((int)$conf['tempo_teste'] > 0) $tempo_horas = (int)$conf['tempo_teste'];
            if (isset($conf['permitir_teste_revenda'])) $permitir_teste_revenda = (int)$conf['permitir_teste_revenda'];
            if (!empty($conf['senha_p2p'])) $senha_p2p = $conf['senha_p2p'];
            $api_p2p_url = $conf['api_p2p_url'] ?? '';
            $api_p2p_key = $conf['api_p2p_key'] ?? '';
        }
    } catch(Exception $e){}
    
    // ==============================================================================
    // TRAVA BLINDADA DE CRÉDITO E PERMISSÃO PARA REVENDEDORES
    // ==============================================================================
    if ($role !== 'admin') {
        if ($permitir_teste_revenda == 0) {
            echo json_encode(['erro' => true, 'msg' => 'A criação de testes por revendedores está desativada no momento.']);
            exit;
        }

        $user_credits = 0;
        try {
            $tabela_rev = ($modo_ativo === 'xui') ? '`users`' : '`reg_users`';
            $stmtCred = $pdo->prepare("SELECT credits FROM $tabela_rev WHERE id = ?");
            $stmtCred->execute([$user_id_logado]);
            $user_credits = floatval($stmtCred->fetchColumn());
        } catch (Exception $e) {}

        if ($user_credits < 1) { 
            echo json_encode(['erro' => true, 'msg' => 'Saldo insuficiente! Você não possui créditos para gerar testes.']);
            exit;
        }
    }
    // ==============================================================================
    
    $exp_date = time() + ($tempo_horas * 3600);
    $data_formatada = date('d/m/Y H:i', $exp_date);
    
    // Configurações Globais de URL para os Templates
    $protocolo_painel = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $url_painel = $protocolo_painel . $_SERVER['HTTP_HOST'];
    $link_loja_p2p = $url_painel . "/loja";
    
    if ($tipo_teste === 'p2p') {
        $username = mt_rand(10000000, 99999999);
        try {
            $pdo->prepare("INSERT INTO $tabela_clientes (username, password, exp_date, enabled, member_id, is_p2p) VALUES (?, ?, ?, 1, ?, 1)")->execute([$username, $senha_p2p, $exp_date, $user_id_logado]);
            
            // Envia pra API remota se existir
            if (!empty($api_p2p_url)) {
                $dados_sync = ['acao' => 'salvar', 'nome' => $username, 'senha' => $senha_p2p, 'tipo_conta' => 'teste', 'bouquet_id' => 1, 'token' => $api_p2p_key];
                $ch = curl_init($api_p2p_url);
                curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_POST=>true, CURLOPT_POSTFIELDS=>http_build_query($dados_sync), CURLOPT_TIMEOUT=>5, CURLOPT_SSL_VERIFYPEER=>false]);
                curl_exec($ch); curl_close($ch);
            }
            
            // PUXANDO DO TEMPLATE P2P
            $template_p2p_file = __DIR__ . '/template_p2p.txt';
            $padrao_p2p = "🚀 *TESTE P2P ($tempo_horas HORAS)*\n\n🔑 *Código:* #username#\n📅 *Vencimento:* #exp_date#\n\n📥 *BAIXE O APLICATIVO AQUI:*\n#link_loja#";
            $raw_p2p = file_exists($template_p2p_file) ? file_get_contents($template_p2p_file) : $padrao_p2p;
            
            $msg_zap = str_replace(
                ['#username#', '#password#', '#exp_date#', '#link_loja#', 'DADOS DE ACESSO P2P', 'DADOS DE ACESSO'],
                [$username, $senha_p2p, $data_formatada, $link_loja_p2p, "TESTE P2P ($tempo_horas HORAS)", "TESTE P2P ($tempo_horas HORAS)"],
                $raw_p2p
            );
            
            echo json_encode(['erro' => false, 'msg_zap' => $msg_zap]); exit;
        } catch(Exception $e) { echo json_encode(['erro' => true, 'msg' => 'Erro ao salvar P2P no banco.']); exit; }
    } else {
        $username = "test" . substr(md5(time().mt_rand()), 0, 5);
        $password = substr(md5(time().mt_rand()), 0, 6);
        try {
            if ($modo_ativo === 'xui') {
                $pdo->prepare("INSERT INTO `lines` (username, password, exp_date, enabled, admin_enabled, member_id, max_connections, created_at, is_trial) VALUES (?, ?, ?, 1, 1, ?, 1, ?, 1)")->execute([$username, $password, $exp_date, $user_id_logado, time()]);
            } else {
                $pdo->prepare("INSERT INTO users (username, password, exp_date, enabled, admin_enabled, member_id, is_p2p, max_connections, created_at) VALUES (?, ?, ?, 1, 0, ?, 0, 1, ?)")->execute([$username, $password, $exp_date, $user_id_logado, time()]);
            }
            
            // LÓGICA DE DNS (LOAD BALANCER OU XTREAM/XUI) PARA O TEMPLATE
            $url_streaming = $url_painel;
            $dns_encontrado = false;
            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'] != '') ? ":" . $lbAtivo['porta'] : "";
                    $dns_val = trim($lbAtivo['ip_servidor']) . $porta_lb;
                    if (strpos($dns_val, 'http') !== 0) { $dns_val = "http://" . $dns_val; }
                    $url_streaming = rtrim($dns_val, '/');
                    $dns_encontrado = true;
                }
            } catch(Exception $ex){}
            
            if (!$dns_encontrado) {
                try {
                    $tabela_servidores = ($modo_ativo === 'xui') ? 'servers' : 'streaming_servers';
                    $stmtDns = $pdo->query("SELECT * FROM $tabela_servidores ORDER BY id ASC LIMIT 1");
                    $serverInfo = $stmtDns->fetch(PDO::FETCH_ASSOC);
                    if ($serverInfo) {
                        $dns_val = !empty(trim($serverInfo['domain_name'] ?? '')) ? trim($serverInfo['domain_name']) : trim($serverInfo['server_ip'] ?? '');
                        if (!empty($dns_val)) {
                            if (strpos($dns_val, 'http') !== 0) { $dns_val = "http://" . $dns_val; }
                            $url_streaming = rtrim($dns_val, '/');
                        }
                    }
                } catch(Exception $ex){}
            }

            // GERAÇÃO CRIPTOGRAFADA DO LINK DE PAGAMENTO EXCLUSIVO DA REVENDA
            $hash_dono = base64_encode("RS-".$user_id_logado);
            $hash_cliente = base64_encode("CL-".$username);
            $link_pagamento = "{$url_painel}/checkout.php?r={$hash_dono}&c={$hash_cliente}";

            // MÁGICA DE VOLTA À ORIGEM: Os links que chamam os arquivos de geração (get.php, ssiptv.php) 
            // PRECISAM ser do $url_painel para não dar erro "Usuário inválido". O LB fica no #url#
            $link_m3u = "{$url_painel}/get.php?username={$username}&password={$password}&type=m3u_plus&output=mpegts";
            $link_hls = "{$url_painel}/get.php?username={$username}&password={$password}&type=m3u_plus&output=hls";
            $m3u_completo = "{$url_painel}/get.php?username={$username}&password={$password}&type=m3u_plus&output=ts";
            $m3u_enc = "{$url_painel}/m3u-ts/{$username}/{$password}"; 
            $hls_enc = "{$url_painel}/m3u-m3u8/{$username}/{$password}"; 
            $ss_enc = "{$url_painel}/ss-ts/{$username}/{$password}"; 
            $roku_enc = "{$url_painel}/roku/{$username}/{$password}";
            
            // PUXANDO DO TEMPLATE IPTV
            $template_file = __DIR__ . '/template_mensagem.txt';
            $padrao_template = "✅ *TESTE IPTV ($tempo_horas HORAS)*\n\n👤 *Usuário:* #username#\n🔑 *Senha:* #password#\n📆 *Vencimento:* #exp_date#\n\n🌐 *Aplicativos:* {$link_loja_p2p}";
            $raw_template = file_exists($template_file) ? file_get_contents($template_file) : $padrao_template;

            $msg_zap = str_replace(
                ['#username#', '#password#', '#exp_date#', '#telas#', '#url#', '#m3u_encurtado#', '#m3u_hls_encurtado#', '#ssiptv_encurtado#', '#roku_encurtado#', '#m3u_link#', '#m3u_link_hls#', '#m3u_completo#', 'DADOS DE ACESSO'],
                [$username, $password, $data_formatada, 1, $url_streaming, $m3u_enc, $hls_enc, $ss_enc, $roku_enc, $link_m3u, $link_hls, $m3u_completo, "TESTE IPTV ($tempo_horas HORAS)"],
                $raw_template
            );
            
            // Limpa assinaturas antigas ou duplicadas para o formato limpo
            $msg_zap = preg_replace('/ATT: TOP IPTV\s+💳 \*Link de Pagamento \/ Planos:\*\s+https?:\/\/[^\s]+/i', '', $msg_zap);
            $msg_zap = preg_replace('/💳 \*Link de Pagamento \/ Planos:\*\s+https?:\/\/[^\s]+/i', '', $msg_zap);

            // Injeta cirurgicamente após as conexões (telas) no dashboard também
            $regex_alvo = '/(├●\s*\*conexões\s*:\*?\s*\d+)/i';
            if (preg_match($regex_alvo, $msg_zap)) {
                $msg_zap = preg_replace($regex_alvo, "$1\n├● 💳 *Pagar/Renovar*: " . $link_pagamento, $msg_zap);
            } else {
                $msg_zap = str_replace($data_formatada, $data_formatada . "\n├● 💳 *Pagar/Renovar*: " . $link_pagamento, $msg_zap);
            }
            
            echo json_encode(['erro' => false, 'msg_zap' => $msg_zap]); exit;
        } catch(Exception $e) { echo json_encode(['erro' => true, 'msg' => 'Erro ao salvar IPTV no banco.']); exit; }
    }
}

// --- INÍCIO: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---
$nome_painel = 'TOP IPTV';
$logo_url = '';
$cor_primaria = '#007bff';
$permitir_teste_revenda = 1; // Variável para controlar a view

try {
    $tabela_existe = $pdo_int->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_painel = $pdo_int->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;
            if (isset($config_painel['permitir_teste_revenda'])) { $permitir_teste_revenda = (int)$config_painel['permitir_teste_revenda']; }
            if (isset($config_painel['tempo_teste'])) { $tempo_teste = (int)$config_painel['tempo_teste']; }
        }
    }
} catch (Exception $e) { }

// --- LÓGICA DE VERIFICAÇÃO DA API BINSTREAM ---
$api_conf = ['api_binstream_url' => ''];
try {
    $api_conf = $pdo_int->query("SELECT api_binstream_url FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC) ?: ['api_binstream_url' => ''];
} catch (Exception $e) {}
// --- FIM: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---

// ==============================================================================
// --- MINI API DE RENOVAÇÃO RÁPIDA (COM POPUP NOVO) ---
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao_renovar']) && $_POST['acao_renovar'] === 'true') {
    header('Content-Type: application/json');
    $id_cliente = (int)$_POST['id_cliente'];
    
    try {
        $check_owner = ($role === 'admin') ? "" : " AND member_id = $user_id_logado";
        $stmtC = $pdo->query("SELECT * FROM $tabela_clientes WHERE id = $id_cliente $check_owner");
        $uData = $stmtC->fetch(PDO::FETCH_ASSOC);

        if (!$uData) { echo json_encode(['erro' => true, 'msg' => 'Cliente não encontrado ou sem permissão']); exit; }

        if ($role !== 'admin') {
            $creditos = 0;
            try {
                $tabela_rev = ($modo_ativo === 'xui') ? '`users`' : '`reg_users`';
                $stmtCred = $pdo->prepare("SELECT credits FROM $tabela_rev WHERE id = ?");
                $stmtCred->execute([$user_id_logado]);
                $creditos = floatval($stmtCred->fetchColumn());
            } catch(Exception $ex) {}
            
            if ($creditos < 1) { echo json_encode(['erro' => true, 'msg' => 'Sem saldo de créditos']); exit; }
            $pdo->prepare("UPDATE $tabela_rev SET credits = credits - 1 WHERE id = ?")->execute([$user_id_logado]);
        }

        $nova_data = ($uData['exp_date'] > time()) ? $uData['exp_date'] + (30 * 86400) : time() + (30 * 86400);
        $pdo->prepare("UPDATE $tabela_clientes SET exp_date = ?, enabled = 1 WHERE id = ?")->execute([$nova_data, $id_cliente]);

        echo json_encode(['erro' => false, 'nova_data' => date('d/m/Y', $nova_data)]);
    } catch (Exception $e) {
        echo json_encode(['erro' => true, 'msg' => 'Erro interno']);
    }
    exit;
}
// ==============================================================================

try {
    $tabela_rev = ($modo_ativo === 'xui') ? '`users`' : '`reg_users`';
    $user_credits = $pdo->query("SELECT credits FROM $tabela_rev WHERE id = " . intval($user_id_logado))->fetchColumn() ?: 0;
    
    // Filtro para queries
    $filtro_and = ($role === 'admin') ? "" : "AND member_id = $user_id_logado";

    // --- CONTADORES IPTV ---
    $total_clientes = $pdo->query("SELECT COUNT(id) FROM $tabela_clientes WHERE $cond_p2p $filtro_and")->fetchColumn();
    $clientesAtivos = $pdo->query("SELECT COUNT(id) FROM $tabela_clientes WHERE enabled = 1 AND (exp_date IS NULL OR (exp_date - UNIX_TIMESTAMP()) >= 172800) AND $cond_p2p $filtro_and")->fetchColumn();
    $testesTotal    = $pdo->query("SELECT COUNT(id) FROM $tabela_clientes WHERE (exp_date - UNIX_TIMESTAMP()) < 172800 AND exp_date > UNIX_TIMESTAMP() AND $cond_p2p $filtro_and")->fetchColumn();
    
    // --- CONTADORES P2P ---
    $p2p_total  = $pdo->query("SELECT COUNT(id) FROM $tabela_clientes WHERE password = 'topiptv1724' $filtro_and")->fetchColumn();
    $p2p_ativos = $pdo->query("SELECT COUNT(id) FROM $tabela_clientes WHERE enabled = 1 AND (exp_date IS NULL OR (exp_date - UNIX_TIMESTAMP()) >= 172800) AND password = 'topiptv1724' $filtro_and")->fetchColumn();
    $p2p_testes = $pdo->query("SELECT COUNT(id) FROM $tabela_clientes WHERE (exp_date - UNIX_TIMESTAMP()) < 172800 AND exp_date > UNIX_TIMESTAMP() AND password = 'topiptv1724' $filtro_and")->fetchColumn();

    // --- CLIENTES ONLINE ---
    $time_limit = time() - 35; // 35 segundos atrás
    $clientes_online = $pdo->query("SELECT COUNT(id) FROM $tabela_clientes WHERE last_activity >= $time_limit AND $cond_p2p $filtro_and")->fetchColumn();

    $totalRevendas = 0;
    $liveStreams = 0;

    if ($role === 'admin') {
        $totalRevendas = $pdo->query("SELECT COUNT(id) FROM $tabela_rev WHERE member_group_id != 1")->fetchColumn();
        if ($modo_ativo === 'xui') {
            try { $liveStreams = $pdo->query("SELECT COUNT(id) FROM streams WHERE type = 1 AND (direct_source = 0 OR direct_source IS NULL)")->fetchColumn(); } catch(Exception $e) { $liveStreams = 0; }
        } else {
            $liveStreams = $pdo->query("SELECT COUNT(id) FROM streams WHERE type = 1 AND (direct_source = 0 OR direct_source IS NULL)")->fetchColumn();
        }
    }
    
    // --- DADOS DINÂMICOS BINSTREAM ---
    $bin_ativos = 0; 
    $bin_testes = 0; 
    $bin_vencidos = 0;
    if (!empty($api_conf['api_binstream_url'])) {
        try {
            $bin_ativos = $pdo_int->query("SELECT COUNT(id) FROM binstream_clientes WHERE status = 'ativo' AND vencimento > NOW()")->fetchColumn();
            $bin_testes = $pdo_int->query("SELECT COUNT(id) FROM binstream_clientes WHERE status = 'ativo' AND vencimento > NOW() AND vencimento < DATE_ADD(NOW(), INTERVAL 24 HOUR)")->fetchColumn();
            $bin_vencidos = $pdo_int->query("SELECT COUNT(id) FROM binstream_clientes WHERE vencimento < NOW()")->fetchColumn();
        } catch (Exception $e) {}
    }

    // --- VENCIMENTOS PRÓXIMOS 7 DIAS ---
    $sql_venc = "SELECT id, username, password, exp_date, $col_whatsapp as whatsapp FROM $tabela_clientes WHERE exp_date >= (UNIX_TIMESTAMP() + 172800) AND exp_date <= (UNIX_TIMESTAMP() + (7 * 86400)) AND enabled = 1 AND $cond_p2p $filtro_and ORDER BY exp_date ASC LIMIT 50";
    $lista_vencendo_bd = $pdo->query($sql_venc)->fetchAll(PDO::FETCH_ASSOC);
    
    $lista_vencimentos_formatada = [];
    foreach($lista_vencendo_bd as $r) {
        $lista_vencimentos_formatada[] = [
            'id'    => $r['id'],
            'user'  => $r['username'],
            'pass'  => $r['password'],
            'nome'  => $r['username'],
            'phone' => preg_replace('/[^0-9]/', '', (string)$r['whatsapp']),
            'data'  => date('d/m/Y H:i', $r['exp_date'])
        ];
    }

} catch (Exception $e) { 
    $total_clientes = $totalRevendas = $user_credits = $liveStreams = $testesTotal = $clientesAtivos = $p2p_total = $p2p_ativos = $p2p_testes = $clientes_online = 0; 
    $lista_vencimentos_formatada = []; 
}
?>
<!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>Dashboard - <?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">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
    <style>
        /* ==========================================================================
           CSS PREMIUM V8 - DASHBOARD SIGMA (MÁGICA DO MENU NO MOBILE RESOLVIDA)
           ========================================================================== */
        
        /* REMOVE OS SUBLINHADOS HORRÍVEIS DOS LINKS EM TODA A PÁGINA */
        a { text-decoration: none !important; }

        /* RESET PROTEGIDO */
        *, *::before, *::after { box-sizing: border-box; outline: none; }
        
        :root {
            --bg-dark: #0b0f14;
            --bg-card: #161b22;
            --text-main: #c9d1d9;
            --text-muted: #8b949e;
            --accent: <?php echo $cor_primaria; ?>;
            --border-color: rgba(255, 255, 255, 0.05);
            --success: #238636;
            --danger: #da3633;
            --warning: #d4a000;
        }

        /* ESTRUTURA BASE DA PÁGINA */
        html, body { 
            width: 100%; 
            max-width: 100vw; 
            overflow: hidden; 
            background-color: var(--bg-dark); 
            color: var(--text-main); 
            display: flex; 
            height: 100dvh; 
            margin: 0; 
            padding: 0; 
            font-family: 'Inter', '-apple-system', 'Segoe UI', sans-serif;
        }

        /* =========================================================
           A MÁGICA DO MENU LATERAL (DESKTOP E MOBILE)
           ========================================================= */
        nav#sidebar.sidebar, .sidebar {
            height: 100dvh !important;
            max-height: 100dvh !important;
            display: flex !important;
            flex-direction: column !important;
            overflow: hidden !important; /* Impede a barra inteira de rolar */
        }

        #sidebar .sidebar-header, #sidebar .user-info {
            flex-shrink: 0 !important; /* TOPO FICA FIXO */
            z-index: 10 !important;
            background-color: var(--bg-sidebar) !important;
        }

        #sidebar .menu-list {
            flex: 1 1 auto !important;
            overflow-y: auto !important; /* APENAS OS LINKS ROLAM NO MEIO */
            padding-bottom: 20px !important;
        }
        #sidebar .menu-list::-webkit-scrollbar { width: 4px; }
        #sidebar .menu-list::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 10px; }

        #sidebar .logout-btn {
            flex-shrink: 0 !important; /* BOTÃO DE SAIR FICA FIXO NO FUNDO */
            margin-top: auto !important;
            margin-bottom: 20px !important;
            background-color: var(--bg-sidebar) !important;
            z-index: 10 !important;
        }

        .show-mobile { display: none !important; }

        /* MAIN CONTENT - CONTAINER QUE VAI ROLAR POR DENTRO */
        .main-content { 
            flex: 1; 
            display: flex; 
            flex-direction: column; 
            overflow-y: auto; 
            overflow-x: hidden; 
            width: 100%; 
            position: relative; 
            scroll-behavior: smooth; 
        }
        .main-content::-webkit-scrollbar { width: 6px; }
        .main-content::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 10px; }

        /* A SOLUÇÃO DO RODAPÉ FICA AQUI */
        .rodape-container {
            position: relative !important;
            display: block !important;
            width: 100% !important;
            margin-top: auto !important; 
            padding-bottom: 20px !important;
            z-index: 5 !important;
        }
        .rodape-container *, .rodape-container div, .rodape-container footer {
            position: static !important;
            bottom: auto !important;
            left: auto !important;
            right: auto !important;
            transform: none !important;
        }

        /* OVERLAY DO MENU MOBILE */
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.75); z-index: 1000; cursor: pointer; transition: opacity 0.3s; }
        .sidebar-overlay.active { display: block; }

        .topbar { display: flex; justify-content: space-between; align-items: center; padding: 20px 30px; background-color: transparent; border-bottom: 1px solid var(--border-color); flex-shrink: 0; width: 100%; box-sizing: border-box;}
        .menu-toggle { display: none; background: none; border: none; color: var(--text-main); font-size: 22px; cursor: pointer; padding: 5px; transition: 0.3s; }
        .menu-toggle:hover { color: var(--accent); }
        .mode-badge { padding: 6px 14px; background: rgba(35, 134, 54, 0.1); color: var(--success); border-radius: 20px; font-size: 11px; font-weight: 700; border: 1px solid rgba(35, 134, 54, 0.2); letter-spacing: 0.5px; }

        .content-area { padding: 25px; flex: 1 0 auto; max-width: 1400px; width: 100%; margin: 0 auto; overflow-x: hidden; box-sizing: border-box;}

        /* HEADERS */
        .section-header { 
            display: flex; 
            align-items: center; 
            justify-content: space-between; 
            margin: 0 0 20px 0; 
            font-size: 15px; 
            font-weight: 600; 
            color: var(--text-strong, #fff); 
            text-transform: uppercase; 
            letter-spacing: 1px; 
        }
        .section-header i { margin-right: 10px; font-size: 16px; }

        /* BOTÃO DE TESTE DESKTOP */
        .btn-teste-header { 
            background: linear-gradient(135deg, #1877f2, #0056b3); 
            border: none; 
            color: white; 
            height: 36px; 
            padding: 0 20px; 
            border-radius: 8px; 
            display: inline-flex; 
            align-items: center; 
            justify-content: center; 
            cursor: pointer; 
            transition: 0.3s; 
            font-size: 12px; 
            font-weight: 700; 
            text-transform: uppercase; 
            letter-spacing: 0.5px; 
            box-shadow: 0 4px 15px rgba(24, 119, 242, 0.3); 
        }
        .btn-teste-header i { margin-right: 6px; font-size: 14px; }
        .btn-teste-header:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(24, 119, 242, 0.5); }

        /* CARDS */
        .grid-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; margin-bottom: 35px; width: 100%; box-sizing: border-box;}
        
        .app-card { 
            position: relative; 
            background-color: var(--bg-card); 
            border-radius: 12px; 
            padding: 25px 20px; 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            border: 1px solid var(--border-color); 
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); 
            width: 100%; 
            box-sizing: border-box;
        }
        .app-card:hover { transform: translateY(-4px); box-shadow: 0 12px 24px rgba(0,0,0,0.15); border-color: rgba(255,255,255,0.1); }
        
        .card-icon { font-size: 26px; width: 55px; height: 55px; display: flex; justify-content: center; align-items: center; border-radius: 12px; background: rgba(255,255,255,0.02); transition: 0.3s; flex-shrink: 0; }
        .app-card:hover .card-icon { transform: scale(1.1); }
        
        .card-data { display: flex; flex-direction: column; align-items: flex-end; overflow: hidden;}
        .card-number { font-size: 28px; font-weight: 800; color: var(--text-strong, #fff); line-height: 1.2; display: block; margin-bottom: 4px; text-align: right; }
        .card-label { font-size: 11px; text-transform: uppercase; color: var(--text-muted); font-weight: 600; text-align: right; display: block; letter-spacing: 0.5px; }

        /* BOTÃO DE TESTE MOBILE (ESTILO FOTO - TOPO DO CARTÃO) */
        .btn-card-middle { 
            position: absolute; 
            top: -14px; 
            left: 50%; 
            transform: translateX(-50%); 
            background: #1c2128; 
            border: 1px solid rgba(255,255,255,0.05); 
            color: #8b949e; 
            height: 28px; 
            padding: 0 14px; 
            border-radius: 20px; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            cursor: pointer; 
            transition: 0.3s; 
            font-size: 10px; 
            font-weight: 700; 
            text-transform: uppercase; 
            letter-spacing: 0.5px; 
            box-shadow: 0 4px 10px rgba(0,0,0,0.3); 
            z-index: 10; 
        }
        .btn-card-middle i { margin-right: 6px; font-size: 12px; color: #388bfd; }
        .btn-card-middle:hover { background: #1877f2; color: white; border-color: #1877f2; }
        .btn-card-middle:hover i { color: white; }

        /* CHARTS & TABLES */
        .chart-card, .table-card { background-color: var(--bg-card); border: 1px solid var(--border-color); border-radius: 12px; padding: 20px; margin-bottom: 30px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); width: 100%; box-sizing: border-box; overflow: hidden; }
        .table-header-custom { display: flex; justify-content: space-between; align-items: center; padding: 0 0 15px 0; border-bottom: 1px solid var(--border-color); color: var(--text-muted); font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: 1px; }
        .table-row-custom { display: flex; justify-content: space-between; align-items: center; padding: 15px 0; border-bottom: 1px solid rgba(255,255,255,0.02); transition: 0.2s; }
        .table-row-custom:hover { background: rgba(255,255,255,0.02); padding-left: 5px; border-radius: 4px; }
        .table-row-custom:last-child { border-bottom: none; padding-bottom: 0; }

        .btn-action { border: none; width: 38px; height: 38px; border-radius: 8px; cursor: pointer; color: white; margin-left: 8px; font-size: 15px; display: inline-flex; align-items: center; justify-content: center; transition: 0.2s; flex-shrink: 0; }
        .btn-wpp { background: linear-gradient(135deg, #238636, #2ea043); box-shadow: 0 4px 10px rgba(35, 134, 54, 0.2); }
        .btn-ren { background: linear-gradient(135deg, #1877f2, #0056b3); box-shadow: 0 4px 10px rgba(24, 119, 242, 0.2); }
        .btn-action:hover { transform: translateY(-2px); filter: brightness(1.1); }

        .paginacao-controles { display: flex; justify-content: center; align-items: center; gap: 20px; margin-top: 25px; }
        .btn-pag { background: transparent; border: 1px solid var(--border-color); color: var(--text-main); padding: 8px 16px; border-radius: 8px; cursor: pointer; transition: 0.3s; font-size: 14px;}
        .btn-pag:hover:not(:disabled) { background: var(--accent); border-color: var(--accent); color: white; }
        .btn-pag:disabled { opacity: 0.3; cursor: not-allowed; }

        /* THEME TOGGLE */
        .btn-theme-toggle { background: rgba(255,255,255,0.05); border: 1px solid var(--border-color); color: var(--text-main); font-size: 16px; width: 36px; height: 36px; border-radius: 50%; cursor: pointer; margin-right: 15px; transition: 0.3s; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
        .btn-theme-toggle:hover { background: var(--accent); color: white; border-color: var(--accent); transform: rotate(15deg); }

        @media (max-width: 768px) {
            .topbar { padding: 15px 20px; justify-content: flex-start;}
            .topbar-right { margin-left: auto; display: flex; }
            .content-area { padding: 15px; padding-bottom: 20px !important; width: 100%; overflow-x: hidden; }
            
            .grid-cards { grid-template-columns: 1fr; gap: 20px; margin-bottom: 25px; width: 100%; display: flex; flex-direction: column; }
            .app-card { width: 100%; }
            .app-card.has-top-btn { margin-top: 15px; }

            .show-desktop { display: none !important; }
            .show-mobile { display: flex !important; }
            
            .menu-toggle { display: block; margin-right: 15px; flex-shrink: 0; }
        }

        /* LIGHT MODE ADAPTATION */
        body.light-mode {
            --bg-dark: #f6f8fa;
            --bg-card: #ffffff;
            --text-main: #1f2328;
            --text-muted: #656d76;
            --border-color: rgba(0,0,0,0.08);
            --text-strong: #1f2328;
        }
        body.light-mode .topbar h2, body.light-mode .section-header, body.light-mode .card-number { color: var(--text-strong); }
        body.light-mode .btn-theme-toggle { background: rgba(0,0,0,0.04); }
        body.light-mode .card-icon { background: rgba(0,0,0,0.03); }
        body.light-mode .app-card:hover { box-shadow: 0 12px 24px rgba(0,0,0,0.08); border-color: var(--border-color); }
        body.light-mode .btn-card-middle { background: #f6f8fa; border-color: #d0d7de; color: #656d76; }
        
        .text-iptv { color: #1877f2 !important; }
        .text-p2p { color: #238636 !important; }
        .text-yellow { color: #d4a000 !important; }
        
        .icon-cyan { color: #1877f2; }
        .icon-green { color: #238636; }
        .icon-yellow { color: #d4a000; }
        .icon-red { color: #da3633; }
        .icon-orange { color: #f59e0b; }
        .icon-purple { color: #8957e5; }

        .table-row-custom span[style*="color: white;"] { color: var(--text-strong) !important; }
    </style>
</head>
<body style="display:flex; flex-direction:row;">
    <div class="sidebar-overlay" id="overlay" onclick="toggleMenu()"></div>
    
    <?php include 'sidebar.php'; ?>

    <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; display:flex; align-items:center; white-space: nowrap;">
                    <i class="fas fa-gauge-high" style="color: var(--text-muted); margin-right: 8px; font-size: 20px;"></i> Dashboard
                </h2>
            </div>
            <div class="topbar-right" style="display: flex; align-items: center;">
                <button class="btn-theme-toggle" onclick="toggleTheme()" title="Alternar Tema Claro/Escuro">
                    <i class="fas fa-sun" id="theme-icon"></i>
                </button>
                <span class="mode-badge"><i class="fas fa-database"></i> <?php echo defined('MODO_SISTEMA') ? strtoupper(MODO_SISTEMA) : strtoupper($modo_ativo); ?></span>
            </div>
        </header>

        <div class="content-area">

            <!-- BLOCO CLIENTES IPTV -->
            <div class="section-header">
                <div><i class="fas fa-desktop text-iptv"></i> <span>Clientes IPTV</span></div>
                
                <?php if ($role === 'admin' || $permitir_teste_revenda == 1): ?>
                <div class="show-desktop">
                    <button type="button" onclick="gerarTesteRapido('iptv')" class="btn-teste-header" title="Criar Teste IPTV Rapidamente">
                        <i class="fas fa-bolt"></i> TESTE RAPIDO IPTV
                    </button>
                </div>
                <?php endif; ?>
            </div>

            <div class="grid-cards">
                <div class="app-card has-top-btn" style="border-left: 4px solid #1877f2;">
                    <!-- BOTÃO MOBILE ESTILO FOTO (FLUTUANTE NO TOPO DO CARTÃO) -->
                    <?php if ($role === 'admin' || $permitir_teste_revenda == 1): ?>
                    <button type="button" onclick="gerarTesteRapido('iptv')" class="btn-card-middle show-mobile" title="Criar Teste IPTV">
                        <i class="fas fa-clock"></i> TESTE IPTV
                    </button>
                    <?php endif; ?>
                    
                    <div class="card-icon icon-cyan"><i class="fas fa-users"></i></div>
                    <div class="card-data"><span class="card-number"><?php echo $total_clientes; ?></span><span class="card-label">Total Clientes</span></div>
                </div>
                
                <div class="app-card" style="border-left: 4px solid #238636;">
                    <div class="card-icon icon-green"><i class="far fa-check-circle"></i></div>
                    <div class="card-data"><span class="card-number"><?php echo $clientesAtivos; ?></span><span class="card-label">Ativos (Pagantes)</span></div>
                </div>
                
                <div class="app-card" style="border-left: 4px solid #d4a000;">
                    <div class="card-icon icon-yellow"><i class="fas fa-clock"></i></div>
                    <div class="card-data"><span class="card-number"><?php echo $testesTotal; ?></span><span class="card-label">Total de Testes</span></div>
                </div>
                
                <div class="app-card" style="border-left: 4px solid #388bfd;">
                    <div class="card-icon" style="color: #388bfd;"><i class="fas fa-plug"></i></div>
                    <div class="card-data"><span class="card-number"><?php echo $clientes_online; ?></span><span class="card-label">Clientes Online</span></div>
                </div>
            </div>

            <!-- BLOCO CLIENTES P2P -->
            <div class="section-header">
                <div><i class="fas fa-share-alt text-p2p"></i> <span>Clientes P2P</span></div>
                
                <?php if ($role === 'admin' || $permitir_teste_revenda == 1): ?>
                <div class="show-desktop">
                    <button type="button" onclick="gerarTesteRapido('p2p')" class="btn-teste-header" style="background: linear-gradient(135deg, #238636, #2ea043); box-shadow: 0 4px 15px rgba(35, 134, 54, 0.3);" title="Criar Teste P2P Rapidamente">
                        <i class="fas fa-bolt"></i> TESTE RAPIDO P2P
                    </button>
                </div>
                <?php endif; ?>
            </div>

            <div class="grid-cards">
                <div class="app-card has-top-btn" style="border-left: 4px solid #238636;">
                    <!-- BOTÃO MOBILE ESTILO FOTO (FLUTUANTE NO TOPO DO CARTÃO) -->
                    <?php if ($role === 'admin' || $permitir_teste_revenda == 1): ?>
                    <button type="button" onclick="gerarTesteRapido('p2p')" class="btn-card-middle show-mobile" title="Criar Teste P2P">
                        <i class="fas fa-clock"></i> TESTE P2P
                    </button>
                    <?php endif; ?>
                    
                    <div class="card-icon icon-green"><i class="fas fa-users"></i></div>
                    <div class="card-data"><span class="card-number"><?php echo $p2p_total; ?></span><span class="card-label">Total P2P</span></div>
                </div>

                <div class="app-card" style="border-left: 4px solid #238636;">
                    <div class="card-icon icon-green"><i class="fas fa-check-circle"></i></div>
                    <div class="card-data"><span class="card-number"><?php echo $p2p_ativos; ?></span><span class="card-label">P2P Ativos</span></div>
                </div>

                <div class="app-card" style="border-left: 4px solid #8957e5;">
                    <div class="card-icon icon-purple"><i class="fas fa-clock"></i></div>
                    <div class="card-data"><span class="card-number"><?php echo $p2p_testes; ?></span><span class="card-label">Testes P2P</span></div>
                </div>
            </div>

            <?php if (!empty($api_conf['api_binstream_url'])): ?>
            <div class="section-header"><div><i class="fas fa-satellite-dish" style="color: #8957e5;"></i> <span>Clientes Binstream</span></div></div>
            <div class="grid-cards">
                <div class="app-card" style="border-left: 4px solid #8957e5;">
                    <div class="card-icon icon-purple"><i class="fas fa-check-circle"></i></div>
                    <div class="card-data"><span class="card-number"><?php echo $bin_ativos; ?></span><span class="card-label">Ativos Binstream</span></div>
                </div>
                <div class="app-card" style="border-left: 4px solid #f59e0b;">
                    <div class="card-icon icon-orange"><i class="fas fa-clock"></i></div>
                    <div class="card-data"><span class="card-number"><?php echo $bin_testes; ?></span><span class="card-label">Testes Binstream</span></div>
                </div>
                <div class="app-card" style="border-left: 4px solid #da3633;">
                    <div class="card-icon icon-red"><i class="fas fa-times-circle"></i></div>
                    <div class="card-data"><span class="card-number"><?php echo $bin_vencidos; ?></span><span class="card-label">Vencidos Binstream</span></div>
                </div>
            </div>
            <?php endif; ?>

            <?php if ($role === 'admin'): ?>
            <div class="section-header"><div><i class="fas fa-cogs text-yellow"></i> <span>Sistema</span></div></div>
            <div class="grid-cards">
                <div class="app-card" style="border-left: 4px solid #d4a000;">
                    <div class="card-icon icon-yellow"><i class="fas fa-user-tie"></i></div>
                    <div class="card-data"><span class="card-number"><?php echo $totalRevendas; ?></span><span class="card-label">Revendas</span></div>
                </div>
                <div class="app-card" style="border-left: 4px solid #da3633;">
                    <div class="card-icon icon-red"><i class="fas fa-signal"></i></div>
                    <div class="card-data"><span class="card-number"><?php echo $liveStreams; ?></span><span class="card-label">Canais Live</span></div>
                </div>
            </div>
            <?php endif; ?>

            <div class="section-header"><div><i class="fas fa-chart-line text-iptv"></i> <span>Crescimento</span></div></div>
            <div class="chart-card"><div id="growthChart"></div></div>

            <div class="section-header"><div><i class="fas fa-hourglass-half text-p2p"></i> <span>Expiram em 7 dias (IPTV)</span></div></div>
            <div class="table-card">
                <div class="table-header-custom"><span>Login / Vencimento</span><span>Ações</span></div>
                
                <div id="lista-expirando-container">
                    <div class="table-row-custom" style="justify-content:center; color: var(--text-muted);">Carregando...</div>
                </div>

                <div class="paginacao-controles" id="paginacao-box" style="display:none;">
                    <button class="btn-pag" id="btn-ant" onclick="mudarPagina(-1)"><i class="fas fa-chevron-left"></i></button>
                    <span style="font-size:12px; font-weight:bold; color:var(--text-muted);" id="pag-info">1 / 1</span>
                    <button class="btn-pag" id="btn-prox" onclick="mudarPagina(1)"><i class="fas fa-chevron-right"></i></button>
                </div>
            </div>

        </div>

        <!-- RODAPÉ -->
        <div class="rodape-container">
            <?php include 'rodape.php'; ?>
        </div>
        
    </div>

    <script>
        function toggleTheme() {
            const body = document.body;
            const icon = document.getElementById('theme-icon');
            body.classList.toggle('light-mode');
            
            if (body.classList.contains('light-mode')) {
                icon.classList.remove('fa-sun');
                icon.classList.add('fa-moon');
                localStorage.setItem('temaPainel', 'light');
            } else {
                icon.classList.remove('fa-moon');
                icon.classList.add('fa-sun');
                localStorage.setItem('temaPainel', 'dark');
            }
        }

        document.addEventListener('DOMContentLoaded', () => {
            if (localStorage.getItem('temaPainel') === 'light') {
                document.body.classList.add('light-mode');
                document.getElementById('theme-icon').classList.replace('fa-sun', 'fa-moon');
            }
        });

        // FUNCIONALIDADE DO MENU MOBILE COM OVERLAY
        function toggleMenu() { 
            const sidebar = document.getElementById('sidebar');
            const overlay = document.getElementById('overlay');
            if (sidebar) sidebar.classList.toggle('active'); 
            if (overlay) overlay.classList.toggle('active'); 
        }

        function gerarTesteRapido(tipo) {
            Swal.fire({
                title: 'Gerando Teste...',
                text: 'Aguarde um momento.',
                allowOutsideClick: false,
                background: '#161b22',
                color: '#fff',
                didOpen: () => { Swal.showLoading(); }
            });

            const formData = new FormData();
            formData.append('ajax_gerar_teste', 'true');
            formData.append('tipo', tipo);

            fetch(window.location.href, { method: 'POST', body: formData })
            .then(res => res.json())
            .then(data => {
                if(data.erro) {
                    Swal.fire({icon: 'error', title: 'Erro!', text: data.msg, background: '#161b22', color: '#fff'});
                } else {
                    Swal.fire({
                        title: '✅ Teste Gerado!',
                        html: `<textarea id="msgCopyAjax" style="width:100%; height:150px; background:#0b0f14; border:1px solid rgba(255,255,255,0.1); color:white; border-radius:5px; padding:10px; resize:none;">${data.msg_zap}</textarea>`,
                        icon: 'success',
                        showCancelButton: true, showDenyButton: true,
                        confirmButtonText: '<i class="fab fa-whatsapp"></i> WhatsApp',
                        confirmButtonColor: '#238636',
                        denyButtonText: '<i class="fas fa-copy"></i> Copiar',
                        denyButtonColor: '#1877f2',
                        cancelButtonText: 'Fechar',
                        cancelButtonColor: '#656d76',
                        background: '#161b22', color: '#c9d1d9'
                    }).then((res) => {
                        if(res.isConfirmed) {
                            window.open(`https://wa.me/?text=${encodeURIComponent(data.msg_zap)}`, '_blank');
                            setTimeout(() => { location.reload(); }, 500); 
                        } else if (res.isDenied) {
                            const copyText = document.getElementById("msgCopyAjax");
                            copyText.select(); document.execCommand("copy");
                            Swal.fire({icon: 'success', title: 'Copiado!', background: '#161b22', color: '#c9d1d9', timer:1500, showConfirmButton:false}).then(() => { location.reload(); });
                        } else {
                            location.reload();
                        }
                    });
                }
            })
            .catch(err => {
                Swal.fire({icon: 'error', title: 'Erro!', text: 'Falha na comunicação.', background: '#161b22', color: '#c9d1d9'});
            });
        }

        const clientesVencendo = <?php echo json_encode($lista_vencimentos_formatada); ?>;
        let paginaAtual = 1;
        const itensPorPagina = 5;

        document.addEventListener("DOMContentLoaded", function() {
            var options = {
                series: [{ name: 'Vendas', data: [10, 15, 8, 20, 15, 25, 30] }],
                chart: { height: 250, type: 'area', toolbar: { show: false }, background: 'transparent' },
                dataLabels: { enabled: false }, stroke: { curve: 'smooth', width: 2 },
                xaxis: { categories: ["Seg", "Ter", "Qua", "Qui", "Sex", "Sab", "Dom"], labels: { style: { colors: '#8b949e' } } },
                yaxis: { labels: { style: { colors: '#8b949e' } } },
                fill: { type: 'gradient', gradient: { shadeIntensity: 1, opacityFrom: 0.6, opacityTo: 0.1 } }, 
                colors: ['#1877f2']
            };
            var chart = new ApexCharts(document.querySelector("#growthChart"), options); 
            chart.render();

            renderizarTabela();
        });

        function cobrarWpp(nome, data, phone) {
            const msg = `Olá *${nome}*! 👋\n\nPassando para lembrar que seu plano IPTV vence dia *${data}*.\nEvite o bloqueio e renove agora mesmo! 😉\n\nQualquer dúvida estou à disposição.`;
            const url = phone ? `https://wa.me/${phone}?text=${encodeURIComponent(msg)}` : `https://wa.me/?text=${encodeURIComponent(msg)}`;
            window.open(url, '_blank');
        }

        function renovarCliente(id, user, pass) {
            Swal.fire({
                title: 'Renovar 30 Dias?',
                text: `Deseja renovar o usuário ${user} por mais 1 mês? (Custa 1 crédito)`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#1877f2',
                cancelButtonColor: '#da3633',
                confirmButtonText: 'Sim, Renovar!',
                background: '#161b22',
                color: '#c9d1d9'
            }).then((result) => {
                if (result.isConfirmed) {
                    const formData = new FormData();
                    formData.append('acao_renovar', 'true');
                    formData.append('id_cliente', id);

                    fetch(window.location.href, { method: 'POST', body: formData })
                    .then(response => response.json())
                    .then(data => {
                        if(data.erro) {
                            Swal.fire({icon: 'error', title: 'Erro!', text: data.msg, background: '#161b22', color: '#c9d1d9'});
                        } else {
                            const msgSucesso = `✅ *RENOVAÇÃO CONCLUÍDA*\n\n👤 Usuário: ${user}\n🔑 Senha: ${pass}\n📆 Vencimento: ${data.nova_data}`;

                            Swal.fire({
                                title: 'Renovado!',
                                html: `<textarea id="msgCopy" style="width:100%; height:100px; background:#0b0f14; border:1px solid rgba(255,255,255,0.1); color:white; border-radius:5px; padding:10px;">${msgSucesso}</textarea>`,
                                icon: 'success',
                                showCancelButton: true, showDenyButton: true,
                                confirmButtonText: '<i class="fab fa-whatsapp"></i> Enviar WhatsApp',
                                confirmButtonColor: '#238636',
                                denyButtonText: '<i class="fas fa-copy"></i> Copiar',
                                denyButtonColor: '#1877f2',
                                cancelButtonText: 'Fechar',
                                cancelButtonColor: '#656d76',
                                background: '#161b22', color: '#c9d1d9'
                            }).then((res) => {
                                if(res.isConfirmed) {
                                    window.open(`https://wa.me/?text=${encodeURIComponent(msgSucesso)}`, '_blank');
                                    setTimeout(() => { location.reload(); }, 1000);
                                } else if (res.isDenied) {
                                    const copyText = document.getElementById("msgCopy");
                                    copyText.select(); document.execCommand("copy");
                                    Swal.fire({icon: 'success', title: 'Copiado!', background: '#161b22', color: '#c9d1d9'}).then(() => { location.reload(); });
                                } else { location.reload(); }
                            });
                        }
                    })
                    .catch(err => Swal.fire({icon: 'error', title: 'Erro!', text: 'Falha na comunicação.', background: '#161b22', color: '#c9d1d9'}));
                }
            });
        }

        function renderizarTabela() {
            const container = document.getElementById('lista-expirando-container');
            const boxPag = document.getElementById('paginacao-box');
            const infoPag = document.getElementById('pag-info');
            const btnAnt = document.getElementById('btn-ant');
            const btnProx = document.getElementById('btn-prox');

            if (!clientesVencendo || clientesVencendo.length === 0) {
                container.innerHTML = '<div class="table-row-custom" style="justify-content:center; color: var(--text-muted);">Nenhum cliente IPTV expirando em 7 dias.</div>';
                boxPag.style.display = 'none';
                return;
            }

            const totalPaginas = Math.ceil(clientesVencendo.length / itensPorPagina);
            if (paginaAtual < 1) paginaAtual = 1;
            if (paginaAtual > totalPaginas) paginaAtual = totalPaginas;

            const inicio = (paginaAtual - 1) * itensPorPagina;
            const fim = inicio + itensPorPagina;
            const itensAtuais = clientesVencendo.slice(inicio, fim);

            let html = '';
            itensAtuais.forEach(cli => {
                html += `
                    <div class="table-row-custom">
                        <div style="display:flex; flex-direction:column;">
                            <span style="font-weight:bold; color: var(--text-strong);">${cli.nome}</span>
                            <span style="font-size:12px; color:var(--danger); font-weight:bold; margin-top: 3px;"><i class="far fa-clock"></i> Vence: ${cli.data}</span>
                        </div>
                        <div style="display:flex;">
                            <button class="btn-action btn-wpp" onclick="cobrarWpp('${cli.nome}', '${cli.data}', '${cli.phone}')" title="Cobrar Whatsapp"><i class="fab fa-whatsapp"></i></button>
                            <button class="btn-action btn-ren" onclick="renovarCliente(${cli.id}, '${cli.user}', '${cli.pass}')" title="Renovar +30 Dias"><i class="fas fa-sync-alt"></i></button>
                        </div>
                    </div>
                `;
            });
            container.innerHTML = html;

            if (totalPaginas > 1) {
                boxPag.style.display = 'flex';
                infoPag.innerText = `${paginaAtual} / ${totalPaginas}`;
                btnAnt.disabled = (paginaAtual === 1);
                btnProx.disabled = (paginaAtual === totalPaginas);
            } else {
                boxPag.style.display = 'none';
            }
        }

        function mudarPagina(direcao) {
            paginaAtual += direcao;
            renderizarTabela();
        }
    </script>
</body>
</html>