<?php
session_start();
date_default_timezone_set('America/Sao_Paulo');

require_once 'config.php';
$pdo = getConexaoAtiva();
$pdo->exec("SET NAMES utf8mb4");
$pdo->exec("SET SESSION sql_mode = ''");

// Verificação de segurança padrão
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') { 
    header("Location: login.php"); 
    exit; 
}

$user_id_logado = $_SESSION['user_id']; 
$role = $_SESSION['user_role'];
$nome_usuario = $_SESSION['username']; 
$mensagem = "";

// --- LÓGICA DE AUTO-CORREÇÃO DO BANCO (Adicionando o Preço Base) ---
try {
    $check_preco = $pdo->query("SHOW COLUMNS FROM `painel_config` LIKE 'preco_base'");
    if (!$check_preco->fetch()) { 
        $pdo->exec("ALTER TABLE `painel_config` ADD COLUMN `preco_base` DECIMAL(10,2) DEFAULT 35.00"); 
    }
} catch (Exception $e) {}

// --- SALVAR CONFIGURAÇÃO DO PREÇO BASE ---
if (isset($_POST['action_update_price'])) {
    $novo_preco = floatval(str_replace(',', '.', $_POST['preco_base']));
    if ($novo_preco > 0) {
        $pdo->prepare("UPDATE painel_config SET preco_base = ?")->execute([$novo_preco]);
        $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Preço médio atualizado com sucesso! As métricas foram recalculadas.</div>";
    }
}

// --- BUSCA DADOS DE CONFIGURAÇÃO ---
$nome_painel = 'TOP IPTV'; $logo_url = ''; $cor_primaria = '#007bff'; $preco_base = 35.00;
try {
    $config_painel = $pdo->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($config_painel) {
        $nome_painel = !empty($config_painel['nome_painel']) ? $config_painel['nome_painel'] : $nome_painel;
        $logo_url = !empty($config_painel['logo_url']) ? $config_painel['logo_url'] : $logo_url;
        $cor_primaria = !empty($config_painel['cor_primaria']) ? $config_painel['cor_primaria'] : $cor_primaria;
        $preco_base = isset($config_painel['preco_base']) ? floatval($config_painel['preco_base']) : 35.00;
    }
} catch (Exception $e) {}

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

// =================================================================================
// CÁLCULOS FINANCEIROS INTELIGENTES
// =================================================================================

$agora = time();

// 1. Total de Clientes (Desconsiderando Testes Curtos de 4h, focando em clientes reais ou vencidos)
$total_clientes = $pdo->query("SELECT COUNT(id) FROM users WHERE is_p2p = 0 OR is_p2p IS NULL")->fetchColumn() ?: 0;

// 2. Assinaturas Ativas (Não vencidos e habilitados)
$assinaturas_ativas = $pdo->query("SELECT COUNT(id) FROM users WHERE (is_p2p = 0 OR is_p2p IS NULL) AND enabled = 1 AND exp_date > $agora")->fetchColumn() ?: 0;

// 3. Taxa de Ativos (%)
$taxa_ativos = ($total_clientes > 0) ? round(($assinaturas_ativas / $total_clientes) * 100, 1) : 0;

// 4. Receita Potencial (Se todos os ativos pagarem o preço base)
$receita_potencial = $assinaturas_ativas * $preco_base;

// 5. Receita Total (Estimativa de todos os clientes registrados * preço base)
$receita_total = $total_clientes * $preco_base;

// 6. Tentar puxar pagamentos reais do mês (Caso exista a tabela de pagamentos do Mercado Pago)
$pagamentos_pagos = 0;
try {
    // Verifica se a tabela pagamentos existe
    if ($pdo->query("SHOW TABLES LIKE 'pagamentos'")->rowCount() > 0) {
        $mes_atual = date('m');
        $ano_atual = date('Y');
        // Soma os pagamentos aprovados no mês atual
        $stmt_pag = $pdo->query("SELECT SUM(valor) FROM pagamentos WHERE status IN ('approved', 'pago', 'aprovado') AND MONTH(data_criacao) = '$mes_atual' AND YEAR(data_criacao) = '$ano_atual'");
        $pag_reais = $stmt_pag->fetchColumn();
        if ($pag_reais > 0) {
            $pagamentos_pagos = $pag_reais;
        }
    }
} catch (Exception $e) {}

// Se não tiver pagamentos registrados, a "Receita do Mês" estima que pelo menos os ativos renovaram.
// Se tiver pagamentos reais, usa eles.
$receita_do_mes = ($pagamentos_pagos > 0) ? $pagamentos_pagos : $receita_potencial;

// Formatação para Moeda Brasileira
function formatarMoeda($valor) {
    return 'R$ ' . number_format($valor, 2, ',', '.');
}

?>
<!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 Financeiro - <?php echo htmlspecialchars($nome_painel); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { 
            --bg-dark: #121519; 
            --bg-sidebar: #1e2227; 
            --bg-card: #272c33; 
            --bg-card-hover: #2d333b;
            --text-main: #d1d5da; 
            --text-muted: #8a94a1; 
            --accent: <?php echo $cor_primaria; ?>; 
            --border-color: #3a4149; 
            --success: #2ecc71; 
            --danger: #e74c3c; 
            --warning: #f1c40f; 
            --info: #3498db;
            --purple: #9b59b6;
        }
        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); display: flex; flex-direction: column; transition: 0.3s; border-right: 1px solid var(--border-color); z-index: 1001; 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 { max-width: 180px; max-height: 55px; object-fit: contain; }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(255, 255, 255, 0.05); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .credits-badge { display: block; margin-top: 10px; color: var(--success); font-weight: bold; font-size: 13px; }
        
        .menu-list { list-style: none; padding: 0; margin: 0; overflow-y: auto; flex: 1; }
        .menu-item { padding: 14px 20px; color: var(--text-main); text-decoration: none; display: flex; align-items: center; transition: 0.2s; border-left: 3px solid transparent; font-size: 14px; 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: var(--danger); color: white; text-align: center; text-decoration: none; font-weight: bold; }

        .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: 30px; flex: 1; }

        /* HEADER DO DASHBOARD */
        .page-header { margin-bottom: 30px; }
        .page-header h2 { margin: 0 0 5px 0; color: white; font-size: 24px; display: flex; align-items: center; gap: 10px; }
        .page-header p { margin: 0; color: var(--text-muted); font-size: 14px; }

        /* GRIDS DO FINANCEIRO */
        .fin-grid-4 { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 20px; margin-bottom: 20px; }
        .fin-grid-3 { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 20px; }
        .fin-grid-2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 20px; margin-bottom: 20px; }

        /* CARDS ESTILO PREMIUM */
        .fin-card { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 12px; padding: 25px; display: flex; justify-content: space-between; align-items: center; transition: 0.3s; }
        .fin-card:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.2); background: var(--bg-card-hover); }
        
        .fin-info { display: flex; flex-direction: column; gap: 5px; }
        .fin-title { font-size: 13px; color: var(--text-muted); text-transform: uppercase; font-weight: bold; letter-spacing: 0.5px; }
        .fin-value { font-size: 28px; font-weight: 800; color: white; }
        .fin-sub { font-size: 12px; color: var(--text-muted); }

        /* ÍCONES COM FUNDO SUAVE */
        .fin-icon-box { width: 60px; height: 60px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 24px; flex-shrink: 0; }
        
        .icon-warning { background: rgba(241, 196, 15, 0.15); color: var(--warning); }
        .icon-primary { background: rgba(0, 123, 255, 0.15); color: var(--accent); }
        .icon-info { background: rgba(52, 152, 219, 0.15); color: var(--info); }
        .icon-purple { background: rgba(155, 89, 182, 0.15); color: var(--purple); }
        .icon-success { background: rgba(46, 204, 113, 0.15); color: var(--success); }
        .icon-danger { background: rgba(231, 76, 60, 0.15); color: var(--danger); }

        /* CARDS GRANDES (INFERIORES) */
        .fin-panel { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 12px; padding: 25px; }
        .fin-panel h3 { margin: 0 0 20px 0; color: white; font-size: 16px; display: flex; justify-content: space-between; align-items: center; }

        /* PROGRESS BAR CUSTOMIZADA */
        .progress-container { margin-top: 15px; }
        .progress-header { display: flex; justify-content: space-between; font-size: 13px; font-weight: bold; margin-bottom: 8px; color: var(--text-muted); }
        .progress-header span:last-child { color: white; }
        .progress-bar-bg { width: 100%; height: 10px; background: #121519; border-radius: 10px; overflow: hidden; border: 1px solid var(--border-color); }
        .progress-bar-fill { height: 100%; background: var(--accent); border-radius: 10px; }

        /* FORMULÁRIO DE CONFIGURAÇÃO DE PREÇO */
        .price-form { display: flex; gap: 10px; align-items: flex-end; }
        .price-form .form-group { flex: 1; }
        .price-form label { display: block; font-size: 12px; color: var(--text-muted); font-weight: bold; margin-bottom: 5px; }
        .price-form input { width: 100%; padding: 12px; background: #121519; border: 1px solid var(--border-color); color: white; border-radius: 6px; box-sizing: border-box; font-size: 16px; font-weight: bold; }
        .price-form input:focus { border-color: var(--accent); outline: none; }
        .price-form button { background: var(--success); color: white; border: none; padding: 12px 20px; border-radius: 6px; cursor: pointer; font-weight: bold; transition: 0.2s; height: 45px; }
        .price-form button:hover { filter: brightness(1.1); }

        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: bold; font-size: 14px; transition: opacity 0.5s ease; }
        .alert.success { background: rgba(46, 204, 113, 0.15); border: 1px solid var(--success); color: var(--success); }

        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; }

        @media (max-width: 768px) {
            .menu-toggle { display: block; }
            .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; }
            .content-area { padding: 15px; }
            .fin-grid-4, .fin-grid-3, .fin-grid-2 { grid-template-columns: 1fr; }
            .price-form { flex-direction: column; align-items: stretch; }
            .price-form button { width: 100%; }
        }
    </style>
</head>
<body>
    <div class="sidebar-overlay" id="overlay"></div>
    <nav class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <?php if(!empty($logo_url) && file_exists($logo_url)): ?>
                <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" class="sidebar-logo">
            <?php else: ?>
                <?php echo htmlspecialchars($nome_painel); ?>
            <?php endif; ?>
        </div>
        <div class="user-info">
            <div style="color:white; font-size: 14px;">Olá, <strong><?php echo htmlspecialchars($nome_usuario); ?></strong></div>
            <span class="badge"><?php echo $role === 'admin' ? 'Administrador' : 'Revendedor'; ?></span>
            <div class="credits-badge"><i class="fas fa-coins"></i> Saldo: <?php echo number_format($user_credits, 1); ?></div>
        </div>
        
        <div class="menu-list">
            <a href="dashboard.php" class="menu-item active"><i class="fas fa-chart-line"></i> Dashboard</a>
            <a href="perfil.php" class="menu-item active"><i class="fas fa-user-circle"></i> Meu Perfil</a>
            
            <a href="lancamentos.php" class="menu-item active"><i class="fas fa-fire"></i> Últimos Adicionados</a>
            
            <a href="ajuda.php" class="menu-item active"><i class="fas fa-question-circle"></i> Material de Ajuda</a>
            
            <div class="menu-category">Gestão</div>
            <a href="clientes.php" class="menu-item active"><i class="fas fa-users"></i> Clientes IPTV</a>
            <a href="testes.php" class="menu-item active"><i class="fas fa-vial"></i> Gerenciar Testes</a>
            <a href="online.php" class="menu-item active"><i class="fas fa-plug"></i> Clientes Online</a>
            <a href="revendedores.php" class="menu-item active"><i class="fas fa-user-tie"></i> Revendedores</a>
            <a href="migrar_clientes.php" class="menu-item active"><i class="fas fa-exchange-alt"></i> Migrar Clientes</a>
            <a href="logs_creditos.php" class="menu-item active"><i class="fas fa-list-alt"></i> Extrato de Créditos</a>
            <a href="marketing.php" class="menu-item active"><i class="fas fa-bullhorn"></i> Central de Marketing</a>
            
            
            <div class="menu-category">Clientes P2P</div>
            <a href="p2p_clientes.php" class="menu-item active"><i class="fas fa-tv"></i> Clientes P2P</a>
            
            <?php if (!empty($api_conf['api_binstream_url'])): ?>
                <a href="binstream_p2p.php" class="menu-item active"><i class="fas fa-tv"></i> Binstream P2P</a>
            <?php endif; ?>

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

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

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

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

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

    <div class="main-content">
        <header class="topbar">
            <div style="display: flex; align-items: center; gap: 10px;">
                <button class="menu-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            </div>
            <div class="topbar-right">
                <span style="color:var(--text-muted); font-size:13px; font-weight:bold;"><i class="far fa-calendar-alt"></i> <?php echo date('d \d\e M. Y'); ?></span>
            </div>
        </header>

        <div class="content-area">
            
            <div class="page-header">
                <h2><i class="fas fa-hand-holding-usd" style="color: var(--warning);"></i> Dashboard Financeiro</h2>
                <p>Visão geral e projeção das finanças do painel</p>
            </div>

            <?php echo $mensagem; ?>

            <!-- LINHA 1: 4 CARDS -->
            <div class="fin-grid-4">
                
                <div class="fin-card">
                    <div class="fin-info">
                        <span class="fin-title">Receita Total</span>
                        <span class="fin-value" style="color: var(--warning);"><?php echo formatarMoeda($receita_total); ?></span>
                        <span class="fin-sub">Projeção Máxima</span>
                    </div>
                    <div class="fin-icon-box icon-warning">
                        <i class="fas fa-money-bag"></i>
                    </div>
                </div>

                <div class="fin-card" style="border-color: var(--accent); background: rgba(0, 123, 255, 0.05);">
                    <div class="fin-info">
                        <span class="fin-title">Receita Potencial</span>
                        <span class="fin-value" style="color: var(--accent);"><?php echo formatarMoeda($receita_potencial); ?></span>
                        <span class="fin-sub">Apenas Clientes Ativos</span>
                    </div>
                    <div class="fin-icon-box icon-primary">
                        <i class="fas fa-chart-line"></i>
                    </div>
                </div>

                <div class="fin-card">
                    <div class="fin-info">
                        <span class="fin-title">Receita do Mês</span>
                        <span class="fin-value"><?php echo formatarMoeda($receita_do_mes); ?></span>
                        <span class="fin-sub">Este mês</span>
                    </div>
                    <div class="fin-icon-box icon-info">
                        <i class="fas fa-calendar-check"></i>
                    </div>
                </div>

                <div class="fin-card">
                    <div class="fin-info">
                        <span class="fin-title">Assinaturas Ativas</span>
                        <span class="fin-value"><?php echo $assinaturas_ativas; ?></span>
                        <span class="fin-sub">Não vencidas</span>
                    </div>
                    <div class="fin-icon-box icon-purple">
                        <i class="fas fa-users"></i>
                    </div>
                </div>

            </div>

            <!-- LINHA 2: 3 CARDS -->
            <div class="fin-grid-3">
                
                <div class="fin-card">
                    <div class="fin-info">
                        <span class="fin-title">Total de Clientes</span>
                        <span class="fin-value"><?php echo $total_clientes; ?></span>
                        <span class="fin-sub">Ativos e Inativos</span>
                    </div>
                    <div class="fin-icon-box icon-primary">
                        <i class="fas fa-user"></i>
                    </div>
                </div>

                <div class="fin-card">
                    <div class="fin-info">
                        <span class="fin-title">Pagamentos Reais (Mês)</span>
                        <span class="fin-value" style="color: var(--success);"><?php echo formatarMoeda($pagamentos_pagos); ?></span>
                        <span class="fin-sub">Puxado do Mercado Pago</span>
                    </div>
                    <div class="fin-icon-box icon-success">
                        <i class="fas fa-check-circle"></i>
                    </div>
                </div>

                <div class="fin-card">
                    <div class="fin-info">
                        <span class="fin-title">Taxa de Ativos</span>
                        <span class="fin-value"><?php echo $taxa_ativos; ?>%</span>
                        <span class="fin-sub">Clientes gerando lucro</span>
                    </div>
                    <div class="fin-icon-box <?php echo $taxa_ativos >= 70 ? 'icon-success' : 'icon-danger'; ?>">
                        <i class="fas fa-chart-pie"></i>
                    </div>
                </div>

            </div>

            <!-- LINHA 3: 2 PAINEIS GRANDES -->
            <div class="fin-grid-2">
                
                <div class="fin-panel">
                    <h3>Receita Mensal (Mês Atual) <span style="font-size:12px; font-weight:normal; color:var(--text-muted);">Baseado na Receita Potencial</span></h3>
                    
                    <div class="progress-container">
                        <div class="progress-header">
                            <span><?php echo date('m/Y'); ?></span>
                            <span><?php echo formatarMoeda($receita_potencial); ?></span>
                        </div>
                        <div class="progress-bar-bg">
                            <div class="progress-bar-fill" style="width: <?php echo $taxa_ativos; ?>%; <?php echo $taxa_ativos < 50 ? 'background: var(--danger);' : ''; ?>"></div>
                        </div>
                    </div>
                </div>

                <div class="fin-panel">
                    <h3><i class="fas fa-cog" style="color:var(--text-muted);"></i> Configurar Preço Médio</h3>
                    <p style="font-size: 13px; color: var(--text-muted); margin-bottom: 20px;">Defina o valor médio cobrado por cada tela. Isso ajustará a métrica de "Receita Potencial" automaticamente.</p>
                    
                    <form method="POST" class="price-form">
                        <input type="hidden" name="action_update_price" value="1">
                        <div class="form-group">
                            <label>Valor Base por Cliente (R$)</label>
                            <input type="text" name="preco_base" value="<?php echo number_format($preco_base, 2, ',', ''); ?>" required placeholder="Ex: 35,00">
                        </div>
                        <button type="submit"><i class="fas fa-save"></i> Atualizar Métricas</button>
                    </form>
                </div>

            </div>

        </div>
        
        <?php if(file_exists('rodape.php')) include 'rodape.php'; ?>
    </div>

    <script>
        // Funcionalidade do Menu Mobile e Submenus
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('overlay');
        function toggleMenu() { sidebar.classList.toggle('active'); overlay.classList.toggle('active'); }
        overlay.onclick = toggleMenu;

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

        // Script para fazer a mensagem de alerta (sucesso/erro) sumir sozinha
        document.addEventListener('DOMContentLoaded', function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alertMsg) {
                setTimeout(function() {
                    alertMsg.style.opacity = '0';
                    setTimeout(function() { alertMsg.remove(); }, 500);
                }, 4000);
            });
        });
    </script>
</body>
</html>