<?php
// admin/index.php

// 1. Configurações
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
require '../includes/conexao.php';

// 2. SEGURANÇA
if (!isset($_SESSION['account_id'])) {
    header("Location: ../login.php");
    exit;
}

$stmt = $pdo->prepare("SELECT page_access, name FROM accounts WHERE id = ?");
$stmt->execute([$_SESSION['account_id']]);
$account = $stmt->fetch();

if (!$account || $account['page_access'] < 3) { 
    die("Acesso Negado."); 
}

$page_title = "Dashboard Financeiro";
include '../includes/admin_header.php'; 

$msg = '';

// 3. PROCESSAR LANÇAMENTO MANUAL (Despesas do Servidor)
if (isset($_POST['add_finance'])) {
    $type = $_POST['type']; // Apenas 'expense' recomendado aqui, já que income vem automático
    $category = $_POST['category'];
    $desc = $_POST['description'];
    $value = str_replace(',', '.', str_replace('.', '', $_POST['value']));
    
    if ($value > 0 && !empty($desc)) {
        $stmt = $pdo->prepare("INSERT INTO server_finances (type, category, description, value, date) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$type, $category, $desc, $value, time()]);
        $msg = '<div class="alert alert-success border-0 shadow-lg text-white fw-bold" style="background: #10b981;"><i class="fas fa-check-circle me-2"></i> Lançamento salvo!</div>';
    }
}

// 4. ESTATÍSTICAS DE DOAÇÕES (DINHEIRO REAL - payments_history)
// Status 'approved' é crucial

// A. Totais por Período
$now = time();
$todayStart = strtotime("today", $now);
$weekStart = strtotime("-7 days", $now);
$monthStart = strtotime(date('Y-m-01')); // Primeiro dia do mês atual

// Hoje
$donateDay = $pdo->query("SELECT COALESCE(SUM(value_brl), 0) FROM payments_history WHERE status = 'approved' AND date_processed >= $todayStart")->fetchColumn();

// Semana
$donateWeek = $pdo->query("SELECT COALESCE(SUM(value_brl), 0) FROM payments_history WHERE status = 'approved' AND date_processed >= $weekStart")->fetchColumn();

// Mês
$donateMonth = $pdo->query("SELECT COALESCE(SUM(value_brl), 0) FROM payments_history WHERE status = 'approved' AND date_processed >= $monthStart")->fetchColumn();

// Total Geral (Lifetime)
$donateTotal = $pdo->query("SELECT COALESCE(SUM(value_brl), 0) FROM payments_history WHERE status = 'approved'")->fetchColumn();


// B. Despesas (Manual - server_finances)
$totalExpenses = $pdo->query("SELECT COALESCE(SUM(value), 0) FROM server_finances WHERE type = 'expense'")->fetchColumn();

// Lucro Real
$realProfit = $donateTotal - $totalExpenses;


// C. Lista de Últimas Doações (Quem e Quanto)
try {
    $lastDonations = $pdo->query("
        SELECT p.*, a.name as char_name, a.email 
        FROM payments_history p 
        LEFT JOIN accounts a ON p.account_id = a.id 
        WHERE p.status = 'approved' 
        ORDER BY p.date_processed DESC LIMIT 10
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $lastDonations = []; }


// D. Gráfico: Entradas (Automático) vs Saídas (Manual) - Últimos 7 dias
$chartLabels = [];
$chartIncome = [];
$chartExpense = [];

for ($i = 6; $i >= 0; $i--) {
    $timestamp = strtotime("-$i days");
    $dayStart = strtotime("today", $timestamp);
    $dayEnd = strtotime("tomorrow", $dayStart) - 1;
    $chartLabels[] = date('d/m', $timestamp);
    
    // Entradas vêm do payments_history (Automático)
    $stmtInc = $pdo->prepare("SELECT COALESCE(SUM(value_brl), 0) FROM payments_history WHERE status='approved' AND date_processed BETWEEN ? AND ?");
    $stmtInc->execute([$dayStart, $dayEnd]);
    $chartIncome[] = $stmtInc->fetchColumn();

    // Saídas vêm do server_finances (Manual)
    $stmtExp = $pdo->prepare("SELECT COALESCE(SUM(value), 0) FROM server_finances WHERE type='expense' AND date BETWEEN ? AND ?");
    $stmtExp->execute([$dayStart, $dayEnd]);
    $chartExpense[] = $stmtExp->fetchColumn();
}
?>

<style>
    :root {
        --bg-deep: #0f172a;
        --card-bg: #1e293b;
        --text-white: #ffffff;
        --text-gray: #cbd5e1;
        --neon-green: #10b981;
        --neon-blue: #3b82f6;
    }

    body { background-color: var(--bg-deep); color: var(--text-white); font-family: 'Segoe UI', sans-serif; }
    
    .admin-container { padding: 40px 0; }

    /* Cards */
    .stat-card {
        background: var(--card-bg);
        border: 1px solid rgba(255,255,255,0.05);
        border-radius: 16px;
        padding: 25px;
        position: relative;
        overflow: hidden;
        transition: transform 0.3s;
        height: 100%;
    }
    .stat-card:hover { transform: translateY(-5px); border-color: rgba(255,255,255,0.2); }
    
    .stat-icon {
        position: absolute; right: 20px; top: 20px;
        font-size: 3rem; opacity: 0.1; transform: rotate(-15deg);
    }
    
    .stat-value { font-size: 2rem; font-weight: 800; margin-bottom: 5px; color: var(--text-white); }
    .stat-label { text-transform: uppercase; font-size: 0.8rem; letter-spacing: 1px; color: var(--text-gray); font-weight: 600; }
    
    .text-income { color: #34d399; } /* Verde Claro */
    .text-expense { color: #f87171; } /* Vermelho Claro */

    /* Tables */
    .custom-table { width: 100%; border-collapse: separate; border-spacing: 0 10px; }
    .custom-table th { text-align: left; padding: 15px; color: var(--text-gray); text-transform: uppercase; font-size: 0.8rem; border-bottom: 1px solid rgba(255,255,255,0.1); }
    .custom-table td { background: var(--card-bg); padding: 15px; vertical-align: middle; border-top: 1px solid rgba(255,255,255,0.05); border-bottom: 1px solid rgba(255,255,255,0.05); }
    .custom-table tr td:first-child { border-top-left-radius: 10px; border-bottom-left-radius: 10px; border-left: 1px solid rgba(255,255,255,0.05); }
    .custom-table tr td:last-child { border-top-right-radius: 10px; border-bottom-right-radius: 10px; border-right: 1px solid rgba(255,255,255,0.05); }

    /* Inputs */
    .form-dark { background: #0f172a; border: 1px solid rgba(255,255,255,0.1); color: white; border-radius: 8px; padding: 10px; }
    .form-dark:focus { background: #0f172a; border-color: var(--neon-blue); color: white; box-shadow: none; }
</style>

<div class="container admin-container">

    <div class="d-flex justify-content-between align-items-center mb-5">
        <div>
            <h2 class="fw-bold text-white m-0">Painel Financeiro</h2>
            <p class="text-gray m-0 opacity-75">Visão geral de doações e despesas.</p>
        </div>
        <div>
            <a href="../index.php" class="btn btn-outline-light me-2">Voltar ao Site</a>
            <a href="logout.php" class="btn btn-danger">Sair</a>
        </div>
    </div>

    <?php echo $msg; ?>

    <div class="row g-4 mb-5">
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-label text-income">Doações Hoje</div>
                <div class="stat-value">R$ <?php echo number_format($donateDay, 2, ',', '.'); ?></div>
                <i class="fas fa-calendar-day stat-icon text-success"></i>
                <div class="small text-gray mt-2">Acumulado em 24h</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-label text-info">Esta Semana</div>
                <div class="stat-value">R$ <?php echo number_format($donateWeek, 2, ',', '.'); ?></div>
                <i class="fas fa-calendar-week stat-icon text-info"></i>
                <div class="small text-gray mt-2">Últimos 7 dias</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-label text-warning">Este Mês</div>
                <div class="stat-value">R$ <?php echo number_format($donateMonth, 2, ',', '.'); ?></div>
                <i class="fas fa-calendar-alt stat-icon text-warning"></i>
                <div class="small text-gray mt-2">Desde dia 01</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card" style="border-color: rgba(16, 185, 129, 0.3);">
                <div class="stat-label text-success">Lucro Líquido</div>
                <div class="stat-value">R$ <?php echo number_format($realProfit, 2, ',', '.'); ?></div>
                <i class="fas fa-wallet stat-icon text-white"></i>
                <div class="small text-gray mt-2">Total - Despesas</div>
            </div>
        </div>
    </div>

    <div class="row g-4">
        
        <div class="col-lg-8">
            
            <div class="stat-card mb-4 p-4">
                <h5 class="fw-bold text-white mb-4"><i class="fas fa-chart-line text-primary me-2"></i> Fluxo Recente (Entrada vs Saída)</h5>
                <div style="height: 300px;">
                    <canvas id="financeChart"></canvas>
                </div>
            </div>

            <div class="mb-4">
                <h5 class="fw-bold text-white mb-3 d-flex align-items-center">
                    <i class="fas fa-hand-holding-usd text-success me-2"></i> Últimas 10 Doações Recebidas
                </h5>
                <div class="table-responsive">
                    <table class="custom-table">
                        <thead>
                            <tr>
                                <th>Data</th>
                                <th>Doador (Conta)</th>
                                <th>Método</th>
                                <th>Pontos</th>
                                <th class="text-end">Valor (R$)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(empty($lastDonations)): ?>
                                <tr><td colspan="5" class="text-center text-gray py-4">Nenhuma doação registrada ainda.</td></tr>
                            <?php else: ?>
                                <?php foreach($lastDonations as $d): ?>
                                <tr>
                                    <td>
                                        <div class="fw-bold text-white"><?php echo date('d/m', $d['date_processed']); ?></div>
                                        <small class="text-gray"><?php echo date('H:i', $d['date_processed']); ?></small>
                                    </td>
                                    <td>
                                        <div class="fw-bold text-white"><?php echo htmlspecialchars($d['char_name'] ?? 'ID: '.$d['account_id']); ?></div>
                                        <small class="text-gray" style="font-size: 0.75rem;"><?php echo $d['email']; ?></small>
                                    </td>
                                    <td>
                                        <span class="badge bg-dark border border-secondary">Automático</span>
                                    </td>
                                    <td class="text-warning fw-bold">+<?php echo $d['points_amount']; ?> PPS</td>
                                    <td class="text-end">
                                        <span class="badge bg-success bg-opacity-25 text-success border border-success fs-6">
                                            R$ <?php echo number_format($d['value_brl'], 2, ',', '.'); ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            
            <div class="stat-card mb-4 border-danger">
                <h5 class="fw-bold text-white mb-3"><i class="fas fa-minus-circle text-danger me-2"></i> Lançar Despesa</h5>
                <p class="small text-gray mb-3">Registre gastos com VPS, Devs ou Marketing para abater no lucro.</p>
                
                <form method="POST">
                    <input type="hidden" name="type" value="expense">
                    
                    <div class="mb-3">
                        <label class="small text-gray mb-1">Categoria</label>
                        <select name="category" class="form-select form-dark">
                            <option value="VPS/Dedicado">Hospedagem / VPS</option>
                            <option value="Marketing">Tráfego / Ads</option>
                            <option value="Equipe">Pagamento Equipe</option>
                            <option value="Outros">Outros Gastos</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="small text-gray mb-1">Descrição</label>
                        <input type="text" name="description" class="form-control form-dark" placeholder="Ex: Mensalidade OVH" required>
                    </div>

                    <div class="mb-3">
                        <label class="small text-gray mb-1">Valor (R$)</label>
                        <input type="text" name="value" class="form-control form-dark fw-bold text-danger" placeholder="0,00" required>
                    </div>

                    <button type="submit" name="add_finance" class="btn btn-danger w-100 fw-bold">
                        REGISTRAR SAÍDA
                    </button>
                </form>
            </div>

            <div class="stat-card">
                <h6 class="fw-bold text-gray mb-3 text-uppercase">Histórico de Gastos</h6>
                <ul class="list-unstyled m-0">
                    <?php 
                    $lastExp = $pdo->query("SELECT * FROM server_finances WHERE type='expense' ORDER BY date DESC LIMIT 5")->fetchAll();
                    foreach($lastExp as $ex): ?>
                    <li class="d-flex justify-content-between align-items-center mb-3 pb-3 border-bottom border-secondary border-opacity-25">
                        <div>
                            <div class="text-white fw-bold"><?php echo htmlspecialchars($ex['description']); ?></div>
                            <small class="text-gray"><?php echo date('d/m/Y', $ex['date']); ?></small>
                        </div>
                        <div class="text-danger fw-bold">- R$ <?php echo number_format($ex['value'], 2, ',', '.'); ?></div>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>

        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    const ctx = document.getElementById('financeChart').getContext('2d');
    
    // Gradientes
    let gradInc = ctx.createLinearGradient(0, 0, 0, 300);
    gradInc.addColorStop(0, 'rgba(16, 185, 129, 0.4)');
    gradInc.addColorStop(1, 'rgba(16, 185, 129, 0)');

    let gradExp = ctx.createLinearGradient(0, 0, 0, 300);
    gradExp.addColorStop(0, 'rgba(239, 68, 68, 0.4)');
    gradExp.addColorStop(1, 'rgba(239, 68, 68, 0)');

    Chart.defaults.color = '#94a3b8';
    Chart.defaults.borderColor = 'rgba(255,255,255,0.05)';

    new Chart(ctx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($chartLabels); ?>,
            datasets: [
                {
                    label: 'Doações (R$)',
                    data: <?php echo json_encode($chartIncome); ?>,
                    borderColor: '#10b981',
                    backgroundColor: gradInc,
                    borderWidth: 2,
                    tension: 0.4,
                    fill: true
                },
                {
                    label: 'Despesas (R$)',
                    data: <?php echo json_encode($chartExpense); ?>,
                    borderColor: '#ef4444',
                    backgroundColor: gradExp,
                    borderWidth: 2,
                    tension: 0.4,
                    fill: true
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { position: 'top', labels: { color: 'white' } } },
            scales: { y: { beginAtZero: true } }
        }
    });
</script>

