<?php
require 'config/db.php';

if (!isset($_SESSION['user_id'])) { 
    header("Location: login.php"); 
    exit; 
}

$user_id = $_SESSION['user_id'];

try {
    // 1. CÁLCULO DE SALDO REAL (Partida Doble)
    // Sumamos créditos (entradas) y restamos débitos (salidas)
    $stmt_bal = $pdo->prepare("
        SELECT SUM(CASE WHEN entry_type = 'credit' THEN amount ELSE -amount END) 
        FROM ledger 
        WHERE user_id = ?
    ");
    $stmt_bal->execute([$user_id]);
    $real_balance = $stmt_bal->fetchColumn() ?: 0.00;

    // 2. OBTENER HISTORIAL DESDE EL LEDGER (Últimas 15 operaciones)
    $stmt_h = $pdo->prepare("
        SELECT * FROM ledger 
        WHERE user_id = ? 
        ORDER BY created_at DESC 
        LIMIT 15
    ");
    $stmt_h->execute([$user_id]);
    $history = $stmt_h->fetchAll();

} catch (PDOException $e) {
    error_log("Ledger Error: " . $e->getMessage());
    $real_balance = 0.00;
    $history = [];
}

include 'includes/header.php';
?>

<style>
    .balance-container { max-width: 950px; margin: 40px auto; padding: 0 20px; }
    
    /* Card Principal tipo Fintech */
    .balance-card { 
        background: linear-gradient(145deg, #111418 0%, #1a1e23 100%);
        border: 1px solid var(--border); 
        border-radius: 24px; 
        padding: 50px; 
        text-align: center;
        box-shadow: 0 20px 50px rgba(0,0,0,0.6);
        position: relative;
        overflow: hidden;
    }
    .balance-card::after {
        content: ''; position: absolute; top: -50%; left: -50%; width: 200%; height: 200%;
        background: radial-gradient(circle, rgba(0,255,136,0.03) 0%, transparent 70%);
        pointer-events: none;
    }

    .balance-amount { 
        font-family: 'Syncopate', sans-serif;
        font-size: 56px; 
        font-weight: 900; 
        color: white; 
        margin: 10px 0;
        letter-spacing: -2px;
    }
    .balance-amount span { color: var(--primary); }
    
    .balance-label { 
        text-transform: uppercase; 
        letter-spacing: 3px; 
        color: var(--text-gray); 
        font-size: 11px; 
        font-weight: 800;
    }

    /* Grid de Métodos */
    .add-funds-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; margin-top: 30px; }
    .method-card { 
        background: rgba(255,255,255,0.02); 
        border: 1px solid var(--border); 
        padding: 25px; 
        border-radius: 16px; 
        cursor: pointer; 
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 12px;
    }
    .method-card:hover { 
        border-color: var(--primary); 
        background: rgba(0, 255, 136, 0.04); 
        transform: translateY(-5px);
    }
    .method-card i { font-size: 28px; color: var(--primary); }
    .method-card span { font-weight: 700; color: white; font-size: 14px; }

    /* Tabla de Actividad Inmutable */
    .history-section { margin-top: 60px; }
    .history-table { width: 100%; border-collapse: separate; border-spacing: 0 8px; }
    .history-table th { text-align: left; color: var(--text-gray); font-size: 10px; text-transform: uppercase; padding: 10px 15px; letter-spacing: 1px; }
    .history-table tr td { background: rgba(255,255,255,0.01); border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); padding: 18px 15px; }
    .history-table tr td:first-child { border-left: 1px solid var(--border); border-radius: 12px 0 0 12px; }
    .history-table tr td:last-child { border-right: 1px solid var(--border); border-radius: 0 12px 12px 0; text-align: right; }
    
    .category-badge {
        font-size: 9px;
        padding: 3px 8px;
        background: rgba(255,255,255,0.05);
        border-radius: 4px;
        color: var(--text-gray);
        text-transform: uppercase;
        font-weight: 800;
    }

    .amt-pos { color: var(--primary); font-weight: 800; }
    .amt-neg { color: #ff4d4d; font-weight: 800; }
</style>

<div class="balance-container">
    
    <div class="balance-card">
        <div class="balance-label">Total Verified Funds</div>
        <div class="balance-amount"><span>$</span><?php echo number_format($real_balance, 2); ?></div>
        <div style="display: inline-flex; align-items: center; gap: 8px; color: #00ff88; background: rgba(0,255,136,0.1); padding: 5px 15px; border-radius: 100px; font-size: 11px; font-weight: 700;">
            <i class="fa-solid fa-shield-halved"></i> SECURED BY VVAULT LEDGER
        </div>
    </div>

    <div class="history-section">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3 style="font-family: 'Syncopate'; font-size: 14px; color: white; margin: 0;">Add Liquidity</h3>
        </div>

        <div class="add-funds-grid">
            <div class="method-card" onclick="openDeposit('PayPal')">
                <i class="fa-brands fa-paypal"></i>
                <span>PayPal</span>
                <small style="color: var(--text-gray); font-size: 10px;">Fees: 2.9% + $0.30</small>
            </div>
            <div class="method-card" onclick="openDeposit('Crypto')">
                <i class="fa-brands fa-bitcoin"></i>
                <span>Crypto Assets</span>
                <small style="color: var(--text-gray); font-size: 10px;">0% Fee Deposit</small>
            </div>
            <div class="method-card" onclick="openDeposit('Skins')">
                <i class="fa-solid fa-vest"></i>
                <span>Steam Skins</span>
                <small style="color: var(--text-gray); font-size: 10px;">Market Trade-in</small>
            </div>
        </div>
    </div>

    <div class="history-section">
        <h3 style="font-family: 'Syncopate'; font-size: 14px; color: white; margin-bottom: 25px;">Verified Ledger Activity</h3>
        
        <?php if($history): ?>
        <table class="history-table">
            <thead>
                <tr>
                    <th>Timestamp</th>
                    <th>Reference / Description</th>
                    <th>Category</th>
                    <th>Status</th>
                    <th>Amount</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($history as $t): ?>
                <tr>
                    <td style="color: var(--text-gray); font-size: 12px; font-family: monospace;">
                        <?php echo date('d.m.y | H:i', strtotime($t['created_at'])); ?>
                    </td>
                    <td>
                        <div style="color: white; font-size: 13px; font-weight: 600;"><?php echo htmlspecialchars($t['description']); ?></div>
                        <?php if($t['order_id']): ?>
                            <small style="color: var(--text-gray); font-size: 10px;">ORDER REF: #<?php echo $t['order_id']; ?></small>
                        <?php endif; ?>
                    </td>
                    <td><span class="category-badge"><?php echo $t['category']; ?></span></td>
                    <td style="font-size: 11px; font-weight: 700; color: var(--status-completed);">
                        <i class="fa-solid fa-circle-check"></i> SETTLED
                    </td>
                    <td class="<?php echo ($t['entry_type'] == 'credit') ? 'amt-pos' : 'amt-neg'; ?>">
                        <?php echo ($t['entry_type'] == 'credit') ? '+' : '-'; ?>
                        $<?php echo number_format($t['amount'], 2); ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php else: ?>
            <div style="padding: 40px; text-align: center; background: rgba(255,255,255,0.01); border: 1px dashed var(--border); border-radius: 15px;">
                <p style="color: var(--text-gray); font-size: 13px;">No movements found in the digital vault.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
function openDeposit(method) {
    let amount = prompt("Enter amount to deposit via " + method + " ($):", "10.00");
    if (amount != null && !isNaN(amount) && amount > 0) {
        // Enviar a un procesador simulado (Asegúrate de actualizar process_add_funds.php)
        window.location.href = "includes/process_add_funds.php?method=" + encodeURIComponent(method) + "&amount=" + amount;
    }
}
</script>

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