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

// 1. SEGURIDAD DE SESIÓN
if (session_status() === PHP_SESSION_NONE) { session_start(); }

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

$current_user_id = $_SESSION['user_id'];
$commission_percent = 0.10; // 10% de comisión para ti

try {
    // --- AUTOLIBERACIÓN DE ESCROW (48 HORAS) ---
    $old_orders_stmt = $pdo->prepare("SELECT id, seller_id, total_price FROM orders WHERE status = 'pending' AND created_at < NOW() - INTERVAL 48 HOUR");
    $old_orders_stmt->execute();
    $to_release = $old_orders_stmt->fetchAll();

    foreach ($to_release as $auto_order) {
        $total_price = $auto_order['total_price'];
        $fee_amount  = $total_price * $commission_percent;
        $seller_net  = $total_price - $fee_amount;

        try {
            $pdo->beginTransaction();

            // A. Crédito al VENDEDOR (Neto)
            $stmt_l = $pdo->prepare("INSERT INTO ledger (user_id, order_id, amount, entry_type, category, description) VALUES (?, ?, ?, 'credit', 'sale_payout', ?)");
            $desc_v = "Auto-Release (48h): Order #" . $auto_order['id'];
            $stmt_l->execute([$auto_order['seller_id'], $auto_order['id'], $seller_net, $desc_v]);

            // B. Crédito al ADMIN (Tu comisión)
            $stmt_a = $pdo->prepare("INSERT INTO ledger (user_id, order_id, amount, entry_type, category, description) VALUES (?, ?, ?, 'credit', 'commission', ?)");
            $desc_a = "Auto-Fee (10%): Order #" . $auto_order['id'];
            $stmt_a->execute([1, $auto_order['id'], $fee_amount, $desc_a]);

            // C. Registrar en admin_earnings
            $stmt_ae = $pdo->prepare("INSERT INTO admin_earnings (order_id, amount) VALUES (?, ?)");
            $stmt_ae->execute([$auto_order['id'], $fee_amount]);

            // D. Marcar como completada
            $stmt_u = $pdo->prepare("UPDATE orders SET status = 'completed' WHERE id = ?");
            $stmt_u->execute([$auto_order['id']]);

            $pdo->commit();
        } catch (Exception $inner_e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            error_log("Error in Auto-Release for order " . $auto_order['id'] . ": " . $inner_e->getMessage());
        }
    }

    // 2. CÁLCULO DE SALDO REAL
    $stmt_bal = $pdo->prepare("
        SELECT SUM(CASE WHEN entry_type = 'credit' THEN amount ELSE -amount END) 
        FROM ledger 
        WHERE user_id = ?
    ");
    $stmt_bal->execute([$current_user_id]);
    $real_balance = $stmt_bal->fetchColumn() ?: 0.00;

    // 3. CONSULTA DE ÓRDENES
    $stmt = $pdo->prepare("
        SELECT o.*, p.title as product_name, p.server_name, p.auto_delivery_content, u.username as seller_name, u.id as seller_id,
               (SELECT COUNT(*) FROM reviews r WHERE r.order_id = o.id) as already_reviewed
        FROM orders o
        JOIN products p ON o.product_id = p.id
        JOIN users u ON o.seller_id = u.id
        WHERE o.buyer_id = ? 
        ORDER BY o.created_at DESC
    ");
    $stmt->execute([$current_user_id]);
    $purchases = $stmt->fetchAll();

} catch (Exception $e) {
    error_log("Audit Error: " . $e->getMessage());
    $purchases = [];
    $real_balance = 0.00;
}

include 'includes/header.php';
?>