<?php
// admin_finances.php (Ubicado en la raíz htdocs/vvault/)
require 'config/db.php'; // CORREGIDO: Sin el ../

if (session_status() === PHP_SESSION_NONE) { session_start(); }

// Seguridad: Solo admin
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: index.php");
    exit;
}

try {
    // 1. BALANCE TOTAL: Lo que ya es tuyo (comisiones del 10%)
    $net_earnings = $pdo->query("SELECT SUM(amount) FROM admin_earnings")->fetchColumn() ?? 0;

    // 2. DINERO EN ESCROW: Órdenes pagadas pero NO completadas aún
    $escrow_funds = $pdo->query("SELECT SUM(total_price) FROM orders WHERE status = 'paid' OR status = 'dispute'")->fetchColumn() ?? 0;

    // 3. VOLUMEN HISTÓRICO: Todo lo que ha pasado por el sitio
    $total_volume = $pdo->query("SELECT SUM(total_price) FROM orders WHERE status = 'completed'")->fetchColumn() ?? 0;

    // 4. HISTORIAL DE COMISIONES RECIENTES
    $stmt = $pdo->query("
        SELECT ae.*, o.total_price as order_amount, u.username as seller_name 
        FROM admin_earnings ae
        JOIN orders o ON ae.order_id = o.id
        JOIN users u ON o.seller_id = u.id
        ORDER BY ae.created_at DESC 
        LIMIT 20
    ");
    $history = $stmt->fetchAll();

} catch (PDOException $e) {
    // Si la tabla admin_earnings no existe aún, evitamos el crash
    $history = []; $net_earnings = 0; $escrow_funds = 0; $total_volume = 0;
}

include 'includes/header.php'; // CORREGIDO: Sin el ../
?>

<style>
    :root {
        --admin-bg: #0d1117;
        --admin-card: #161b22;
        --admin-accent: #00ff88; 
        --admin-border: #30363d;
    }
    body { background-color: var(--admin-bg); color: white; font-family: 'Inter', sans-serif; }
    .admin-container { max-width: 1100px; margin: 40px auto; padding: 0 20px; }

    /* Cards de Finanzas */
    .finance-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 40px; }
    .f-card { background: var(--admin-card); border: 1px solid var(--admin-border); padding: 25px; border-radius: 15px; position: relative; }
    .f-label { color: #8b949e; font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 1px; display: block; margin-bottom: 5px; }
    .f-value { font-family: 'Syncopate', sans-serif; font-size: 20px; font-weight: 800; color: white; }
    .f-accent { color: var(--admin-accent); }

    /* Tabla de Transacciones */
    .history-section { background: var(--admin-card); border: 1px solid var(--admin-border); border-radius: 15px; overflow: hidden; }
    .section-title { padding: 20px; border-bottom: 1px solid var(--admin-border); font-size: 14px; font-weight: 800; text-transform: uppercase; display: flex; align-items: center; justify-content: space-between; }
    
    table { width: 100%; border-collapse: collapse; font-size: 13px; }
    th { text-align: left; background: rgba(0,0,0,0.2); color: #8b949e; padding: 15px 20px; text-transform: uppercase; font-size: 11px; }
    td { padding: 15px 20px; border-bottom: 1px solid var(--admin-border); }
    
    .badge-fee { background: rgba(0, 255, 136, 0.1); color: var(--admin-accent); padding: 4px 8px; border-radius: 6px; font-weight: 800; font-size: 11px; }
    .btn-back { color: var(--admin-accent); text-decoration: none; font-size: 12px; font-weight: 800; margin-bottom: 20px; display: inline-block; }
    
    /* Reutilizamos el estilo de navegación del index para consistencia */
    .admin-nav-top { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; margin-top: 20px; }
    .btn-nav { background: rgba(255,255,255,0.03); color: #c9d1d9; border: 1px solid var(--admin-border); padding: 10px 15px; border-radius: 10px; text-decoration: none; font-size: 10px; font-weight: 800; transition: 0.3s; display: flex; align-items: center; gap: 8px; text-transform: uppercase; }
</style>

<div class="admin-container">
    <div class="admin-nav-top">
        <a href="admin/index.php" class="btn-nav"> <i class="fa-solid fa-house"></i> Dashboard </a>
        <a href="admin_servers.php" class="btn-nav"> <i class="fa-solid fa-server"></i> Servers </a>
        <a href="admin/products.php" class="btn-nav"> <i class="fa-solid fa-box"></i> Products </a>
        <a href="admin/users.php" class="btn-nav"> <i class="fa-solid fa-users"></i> Users </a>
        <a href="admin/disputes.php" class="btn-nav"> <i class="fa-solid fa-gavel"></i> Disputes </a>
    </div>

    <div style="margin: 30px 0;">
        <h1 style="font-family: 'Syncopate', sans-serif; font-weight: 900; font-size: 22px; margin: 0;">FINANCIAL<span>.TRACKER</span></h1>
    </div>

    <div class="finance-grid">
        <div class="f-card">
            <span class="f-label">Net Earnings (10%)</span>
            <span class="f-value f-accent">$<?php echo number_format($net_earnings, 2); ?></span>
        </div>
        <div class="f-card">
            <span class="f-label">Funds in Escrow</span>
            <span class="f-value">$<?php echo number_format($escrow_funds, 2); ?></span>
        </div>
        <div class="f-card">
            <span class="f-label">Historical Volume</span>
            <span class="f-value">$<?php echo number_format($total_volume, 2); ?></span>
        </div>
    </div>

    <div class="history-section">
        <div class="section-title">
            <span>Recent Commission History</span>
            <i class="fa-solid fa-clock-rotate-left"></i>
        </div>
        <table>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Order ID</th>
                    <th>Seller</th>
                    <th>Sale Amount</th>
                    <th>Your Fee (10%)</th>
                </tr>
            </thead>
            <tbody>
                <?php if(empty($history)): ?>
                    <tr><td colspan="5" style="text-align:center; padding: 40px; color: #8b949e;">No history found.</td></tr>
                <?php else: ?>
                    <?php foreach($history as $row): ?>
                        <tr>
                            <td><?php echo date('M d, H:i', strtotime($row['created_at'])); ?></td>
                            <td>#<?php echo $row['order_id']; ?></td>
                            <td><?php echo htmlspecialchars($row['seller_name']); ?></td>
                            <td>$<?php echo number_format($row['order_amount'], 2); ?></td>
                            <td><span class="badge-fee">+$<?php echo number_format($row['amount'], 2); ?></span></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include 'includes/footer.php'; ?>