<?php
session_start();
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'];

// ==============================================================================
// --- MINI API PARA GERAR TESTE VIA AJAX DIRETO NO DASHBOARD (COM TEMPLATES) ---
// ==============================================================================
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
    
    // 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 FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($conf) {
            if ((int)$conf['tempo_teste'] > 0) $tempo_horas = (int)$conf['tempo_teste'];
            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){}
    
    if ($role !== 'admin') {
        $user_credits = $pdo_int->query("SELECT credits FROM reg_users WHERE id = $user_id_logado")->fetchColumn() ?: 0;
        if ($user_credits < 1) { 
            echo json_encode(['erro' => true, 'msg' => 'Saldo insuficiente! Você precisa ter pelo menos 1 crédito.']);
            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 DOS LINKS PARA O TEMPLATE IPTV
            $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
            );
            
            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; }
    }
}
// ==============================================================================

// --- LÓGICA DE AUTO-CORREÇÃO AUTOMÁTICA DO BANCO ---
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");
        }
    }
} catch (PDOException $e) {}

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

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;
        }
    }
} 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 = $pdo_int->query("SELECT credits FROM reg_users WHERE id = $user_id_logado")->fetchColumn();
            if ($creditos < 1) { echo json_encode(['erro' => true, 'msg' => 'Sem saldo de créditos']); exit; }
            $pdo_int->prepare("UPDATE reg_users 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 {
    $user_credits = $pdo_int->query("SELECT credits FROM reg_users 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_int->query("SELECT COUNT(id) FROM reg_users 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>
        :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; }
        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; flex-shrink: 0; }
        .sidebar-header { padding: 25px 20px; text-align: center; font-size: 22px; font-weight: bold; color: white; border-bottom: 1px solid var(--border-color); }
        .sidebar-logo { width: 100%; max-width: 180px; height: auto; max-height: 60px; object-fit: contain; display: block; margin: 0 auto; }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(0, 123, 255, 0.2); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .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: 13px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 11px; }
        .rotate { transform: rotate(180deg); }
        .menu-category { padding: 20px 20px 8px; font-size: 10px; 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; }
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; }

        .main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; width: 100%; position: relative; }
        .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); }
        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 22px; cursor: pointer; padding: 5px; }
        .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: 20px; flex: 1; }
        .section-header { display: flex; align-items: center; justify-content: space-between; margin: 15px 0 15px 0; font-size: 16px; font-weight: 700; color: white; border-bottom: 1px solid var(--border-color); padding-bottom: 8px; }
        .section-header i { margin-right: 10px; font-size: 18px; }
        .text-iptv { color: #0ea5e9; } .text-p2p { color: #22c55e; } .text-yellow { color: #facc15; } 
        
        .grid-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 25px; }
        
        .app-card { position: relative; background-color: var(--bg-card); border-radius: 8px; padding: 20px; display: flex; justify-content: space-between; align-items: center; border: 1px solid var(--border-color); transition: 0.2s; }
        .app-card:hover { transform: translateY(-3px); box-shadow: 0 5px 15px rgba(0,0,0,0.3); }
        .card-icon { font-size: 35px; }
        .icon-cyan { color: #0ea5e9; } .icon-green { color: #22c55e; } .icon-yellow { color: #facc15; } .icon-red { color: #ef4444; } .icon-orange { color: #f59e0b; } .icon-purple { color: #8b5cf6; }
        .card-number { font-size: 28px; font-weight: 800; color: white; line-height: 1; display: block; margin-bottom: 4px; text-align: right; }
        .card-label { font-size: 11px; text-transform: uppercase; color: var(--text-muted); font-weight: 700; text-align: right; display: block; }
        
        .chart-card, .table-card { background-color: var(--bg-card); border: 1px solid var(--border-color); border-radius: 8px; padding: 20px; margin-bottom: 20px; }
        .table-header-custom, .table-row-custom { display: flex; justify-content: space-between; align-items: center; padding: 12px 0; border-bottom: 1px solid var(--border-color); color: var(--text-main); }
        .table-header-custom { font-weight: bold; color: var(--text-muted); font-size: 11px; text-transform: uppercase; border-bottom: 2px solid var(--border-color); }
        
        .paginacao-controles { display: flex; justify-content: center; align-items: center; gap: 15px; margin-top: 15px; }
        .btn-pag { background: var(--bg-sidebar); border: 1px solid var(--border-color); color: white; padding: 6px 14px; border-radius: 4px; cursor: pointer; transition: 0.2s; }
        .btn-pag:hover { background: var(--accent); border-color: var(--accent); }
        .btn-pag:disabled { opacity: 0.3; cursor: not-allowed; }
        
        .btn-action { border: none; width: 35px; height: 35px; border-radius: 5px; cursor: pointer; color: white; margin-left: 5px; font-size: 14px; display: inline-flex; align-items: center; justify-content: center; }
        .btn-wpp { background-color: #25D366; } .btn-wpp:hover { filter: brightness(1.1); }
        .btn-ren { background-color: #0ea5e9; } .btn-ren:hover { filter: brightness(1.1); }
        
        /* ========================================================= */
        /* BOTAO PENDURADO NO TOPO DO CARD PARA CELULAR */
        /* ========================================================= */
        .btn-card-middle { 
            position: absolute; 
            top: -15px; 
            left: 50%; 
            transform: translateX(-50%); 
            background-color: var(--bg-sidebar); 
            border: 1px solid var(--border-color); 
            color: var(--text-main); 
            height: 30px; 
            padding: 0 15px; 
            white-space: nowrap; 
            border-radius: 6px; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            cursor: pointer; 
            transition: 0.2s; 
            text-decoration: none; 
            font-size: 11px; 
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.4);
            z-index: 10;
        }
        .btn-card-middle i { margin-right: 6px; font-size: 13px; color: var(--accent); }
        .btn-card-middle:hover { background-color: var(--accent); color: white; border-color: var(--accent); }
        .btn-card-middle:hover i { color: white; }

        /* ========================================================= */
        /* BOTAO DE TESTE NO CABEÇALHO PARA PC (ALINHADO À DIREITA) */
        /* ========================================================= */
        .btn-teste-header {
            background-color: var(--accent); /* Cor de destaque */
            border: none;
            color: white;
            height: 32px;
            padding: 0 16px;
            border-radius: 6px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: 0.2s;
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.2);
        }
        .btn-teste-header i { margin-right: 6px; font-size: 14px; }
        .btn-teste-header:hover { filter: brightness(1.1); transform: translateY(-1px); }

        /* ========================================================= */
        /* MELHORIAS DE DESIGN E ANIMAÇÃO APENAS NO MODO PC */
        /* ========================================================= */
        @media (min-width: 769px) {
            .grid-cards {
                gap: 25px; /* Mais espaço (respiro) entre os cards */
            }
            .app-card {
                min-height: 80px; /* <--- Altura reduzida para ficar um pouco mais baixo */
                transition: all 0.3s ease;
            }
            .app-card:hover {
                transform: translateY(-6px);
                box-shadow: 0 10px 25px rgba(0,0,0,0.5); /* Sombra mais profunda e premium no hover */
            }
            .app-card .card-icon {
                transition: transform 0.3s ease;
            }
            .app-card:hover .card-icon {
                transform: scale(1.15) rotate(-5deg); /* Ícone cresce e inclina levemente no hover */
            }
        }

        /* Visibilidade para mostrar no lugar certo dependendo do dispositivo */
        .show-mobile { display: none !important; }

        @media (max-width: 768px) {
            .menu-toggle { display: block; margin-right: 15px; }
            .sidebar { position: fixed; left: -260px; height: 100%; box-shadow: 10px 0 20px rgba(0,0,0,0.5); }
            .sidebar.active { left: 0; }
            .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; }

            /* Oculta os botões da segunda coluna e mostra os da primeira coluna no mobile, sem perder a formatação */
            .show-desktop { display: none !important; }
            .show-mobile { display: flex !important; }
        }

        /* ========================================================= */
        /* INÍCIO DAS ADIÇÕES: TEMA CLARO */
        /* ========================================================= */
        body.light-mode { 
            --bg-dark: #f4f6f9; 
            --bg-sidebar: #ffffff; 
            --bg-card: #ffffff; 
            --text-main: #333333; 
            --text-muted: #6c757d; 
            --border-color: #dee2e6; 
        }
        body.light-mode .topbar h2,
        body.light-mode .section-header,
        body.light-mode .sidebar-header,
        body.light-mode .card-number,
        body.light-mode .menu-toggle,
        body.light-mode .table-row-custom span[style*="color: white;"] {
            color: var(--text-main) !important;
        }
        body.light-mode .app-card:hover { box-shadow: 0 10px 25px rgba(0,0,0,0.1); }
        body.light-mode .menu-item:hover, body.light-mode .menu-item.active { background-color: #f8f9fa; color: var(--accent); }
        
        .btn-theme-toggle {
            background: none; border: none; color: var(--text-main); font-size: 20px; cursor: pointer; margin-right: 15px; transition: 0.3s;
        }
        .btn-theme-toggle:hover { color: var(--accent); transform: scale(1.1); }
        /* ========================================================= */
        /* FIM DAS ADIÇÕES: TEMA CLARO */
        /* ========================================================= */
    </style>
</head>
<body>
    <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;">
                    <i class="fas fa-gauge-high" style="color: #8a94a1; 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">

            <div class="section-header">
                <div><i class="fas fa-desktop text-iptv"></i> <span>Clientes IPTV</span></div>
                
                <div class="show-desktop">
                    <button type="button" onclick="gerarTesteRapido('iptv')" class="btn-teste-header" title="Criar Teste IPTV Rapidamente">
                        <i class="fas fa-clock"></i> Teste Rapido IPTV
                    </button>
                </div>
            </div>

            <div class="grid-cards">
                <div class="app-card">
                    <button type="button" onclick="gerarTesteRapido('iptv')" class="btn-card-middle show-mobile" title="Criar Teste IPTV Rapidamente">
                        <i class="fas fa-clock"></i> Teste IPTV
                    </button>
                    
                    <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 #28a745;">
                    <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 #facc15;">
                    <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 #17a2b8;">
                    <div class="card-icon" style="color: #17a2b8;"><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>

            <div class="section-header">
                <div><i class="fas fa-share-alt text-p2p"></i> <span>Clientes P2P</span></div>
                
                <div class="show-desktop">
                    <button type="button" onclick="gerarTesteRapido('p2p')" class="btn-teste-header" title="Criar Teste P2P Rapidamente">
                        <i class="fas fa-clock"></i> Teste Rapido P2P
                    </button>
                </div>
            </div>

            <div class="grid-cards">
                <div class="app-card" style="border-left: 4px solid #22c55e;">
                    <button type="button" onclick="gerarTesteRapido('p2p')" class="btn-card-middle show-mobile" title="Criar Teste P2P Rapidamente">
                        <i class="fas fa-clock"></i> Teste P2P
                    </button>
                    
                    <div class="card-icon icon-cyan"><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 #22c55e;">
                    <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 #8b5cf6;">
                    <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: #8b5cf6;"></i> <span style="color:white;">Clientes Binstream</span></div></div>
            <div class="grid-cards">
                <div class="app-card" style="border-left: 4px solid #8b5cf6;">
                    <div class="card-icon" style="color: #8b5cf6;"><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 #dc3545;">
                    <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">
                    <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">
                    <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"></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"></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>
        <?php include 'rodape.php'; ?>
    </div>

    <script>
        // =========================================================================================
        // INÍCIO DAS ADIÇÕES: LÓGICA DO TEMA
        // =========================================================================================
        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');
            }
        }

        // Carrega o tema salvo ao abrir a página
        document.addEventListener('DOMContentLoaded', () => {
            if (localStorage.getItem('temaPainel') === 'light') {
                document.body.classList.add('light-mode');
                document.getElementById('theme-icon').classList.replace('fa-sun', 'fa-moon');
            }
        });
        // =========================================================================================
        // FIM DAS ADIÇÕES: LÓGICA DO TEMA
        // =========================================================================================

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

        // =========================================================================================
        // MÁGICA: CRIAÇÃO DO TESTE VIA AJAX DIRETO PELO DASHBOARD
        // =========================================================================================
        function gerarTesteRapido(tipo) {
            Swal.fire({
                title: 'Gerando Teste...',
                text: 'Aguarde um momento.',
                allowOutsideClick: false,
                background: '#272c33',
                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: '#272c33', color: '#fff'});
                } else {
                    Swal.fire({
                        title: '✅ Teste Gerado!',
                        html: `<textarea id="msgCopyAjax" style="width:100%; height:150px; background:#121519; border:1px solid #3a4149; 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: '#25D366',
                        denyButtonText: '<i class="fas fa-copy"></i> Copiar',
                        denyButtonColor: '#0ea5e9',
                        cancelButtonText: 'Fechar',
                        cancelButtonColor: '#6c757d',
                        background: '#272c33', color: '#fff'
                    }).then((res) => {
                        if(res.isConfirmed) {
                            window.open(`https://wa.me/?text=${encodeURIComponent(data.msg_zap)}`, '_blank');
                            setTimeout(() => { location.reload(); }, 500); // Atualiza o dashboard sem mudar de página
                        } else if (res.isDenied) {
                            const copyText = document.getElementById("msgCopyAjax");
                            copyText.select(); document.execCommand("copy");
                            Swal.fire({icon: 'success', title: 'Copiado!', background: '#272c33', color: '#fff', timer:1500, showConfirmButton:false}).then(() => { location.reload(); });
                        } else {
                            location.reload();
                        }
                    });
                }
            })
            .catch(err => {
                Swal.fire({icon: 'error', title: 'Erro!', text: 'Falha na comunicação.', background: '#272c33', color: '#fff'});
            });
        }

        // LÓGICA DA TABELA E RENOVAÇÃO RÁPIDA
        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: '#8a94a1' } } },
                yaxis: { labels: { style: { colors: '#8a94a1' } } },
                fill: { type: 'gradient', gradient: { shadeIntensity: 1, opacityFrom: 0.6, opacityTo: 0.1 } }, 
                colors: ['#0ea5e9']
            };
            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: '#0ea5e9',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Sim, Renovar!',
                background: '#272c33',
                color: '#fff'
            }).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: '#272c33', color: '#fff'});
                        } 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:#121519; border:1px solid #3a4149; 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: '#25D366',
                                denyButtonText: '<i class="fas fa-copy"></i> Copiar',
                                denyButtonColor: '#0ea5e9',
                                cancelButtonText: 'Fechar',
                                cancelButtonColor: '#6c757d',
                                background: '#272c33', color: '#fff'
                            }).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: '#272c33', color: '#fff'}).then(() => { location.reload(); });
                                } else { location.reload(); }
                            });
                        }
                    })
                    .catch(err => Swal.fire({icon: 'error', title: 'Erro!', text: 'Falha na comunicação.', background: '#272c33', color: '#fff'}));
                }
            });
        }

        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: white;">${cli.nome}</span>
                            <span style="font-size:12px; color:var(--danger); font-weight:bold;"><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>