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

require_once 'config.php';
$pdo = getConexaoAtiva(); // Banco Principal (Xtream ou XUI)
$pdo_int = getConexaoInterna(); // Banco Local (Garante que configurações salvem na sua hospedagem)

$pdo->exec("SET NAMES utf8mb4");
$pdo_int->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 = "";

// ====================================================================
// 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`';
$cond_p2p = ($modo_ativo === 'xui') ? "1=1" : "(is_p2p = 0 OR is_p2p IS NULL)";

// --- LÓGICA DE AUTO-CORREÇÃO DO BANCO (Preço Base e Pagamentos) ---
try {
    // 1. Verifica coluna preco_base na painel_config
    $check_preco = $pdo_int->query("SHOW COLUMNS FROM `painel_config` LIKE 'preco_base'");
    if (!$check_preco->fetch()) { 
        $pdo_int->exec("ALTER TABLE `painel_config` ADD COLUMN `preco_base` DECIMAL(10,2) DEFAULT 35.00"); 
    }
    
    // 2. Garante que a tabela de pagamentos exista no banco interno
    $pdo_int->exec("CREATE TABLE IF NOT EXISTS `pagamentos` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `valor` decimal(10,2) DEFAULT 0.00,
        `status` varchar(50) DEFAULT 'pendente',
        `data_criacao` datetime DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
    )");
} 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_int->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 PARA O MENU E PARA OS CÁLCULOS ---
$nome_painel = 'TOP IPTV'; $logo_url = ''; $cor_primaria = '#007bff'; $preco_base = 35.00;
$api_conf = ['api_binstream_url' => ''];

try {
    $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;
        $preco_base = isset($config_painel['preco_base']) ? floatval($config_painel['preco_base']) : 35.00;
        $api_conf['api_binstream_url'] = $config_painel['api_binstream_url'] ?? '';
    }
} catch (Exception $e) {}

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

// =================================================================================
// CÁLCULOS FINANCEIROS INTELIGENTES (COMPATÍVEIS COM XUI E XTREAM)
// =================================================================================

$agora = time();

// 1. Total de Clientes (Focando em clientes reais ou vencidos)
$total_clientes = $pdo->query("SELECT COUNT(id) FROM $tabela_clientes WHERE $cond_p2p")->fetchColumn() ?: 0;

// 2. Assinaturas Ativas (Não vencidos e habilitados)
$assinaturas_ativas = $pdo->query("SELECT COUNT(id) FROM $tabela_clientes WHERE $cond_p2p 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. Puxar pagamentos reais do mês da tabela do Mercado Pago no Banco Interno
$pagamentos_pagos = 0;
try {
    $mes_atual = date('m');
    $ano_atual = date('Y');
    $stmt_pag = $pdo_int->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>
    <link rel="stylesheet" href="tema.css">
    <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; }
        
        /* CSS OBRIGATÓRIO PARA A LOGO E MENU (Evita o bug da logo gigante) */
        .sidebar { width: 260px; background-color: var(--bg-sidebar); border-right: 1px solid var(--border-color); display: flex; flex-direction: column; transition: 0.3s; 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 { 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(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-category { padding: 20px 20px 8px; font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: bold; letter-spacing: 1px; }
        .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); }
        .logout-btn { padding: 15px; background-color: var(--danger); color: white; text-align: center; text-decoration: none; font-weight: bold; margin-top: auto;}

        .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; 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: 100px;}
            .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" 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>
            </div>
            <div class="topbar-right">
                <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="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; ?>

            <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>

            <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>

            <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>
        function toggleMenu() { 
            document.getElementById('sidebar').classList.toggle('active'); 
            document.getElementById('overlay').classList.toggle('active'); 
        }

        // 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>
    <script src="tema.js"></script>
</body>
</html>