<?php
// process_escrow.php
require_once 'config/db.php';

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

if (!isset($_SESSION['user_id'])) {
    die("Access Denied.");
}

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

$order_id = $_REQUEST['id'] ?? $_REQUEST['order_id'] ?? null;
$action   = $_REQUEST['action'] ?? null;

if (!$order_id || !$action) {
    header("Location: my_orders.php?error=invalid_request");
    exit;
}

try {
    $pdo->beginTransaction();

    // 1. Validar que la orden existe y pertenece al usuario
    $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ? AND buyer_id = ? FOR UPDATE");
    $stmt->execute([$order_id, $current_user_id]);
    $order = $stmt->fetch();

    if (!$order) throw new Exception("Order not found.");
    
    if ($order['status'] !== 'pending') {
        throw new Exception("Order is already " . $order['status']);
    }

    if ($action === 'release' || $action === 'confirm_receipt') {
        // --- LÓGICA DE COMISIÓN Y LIBERACIÓN ---
        
        $total_price = $order['total_price'];
        $fee_amount  = $total_price * $commission_percent;
        $seller_net  = $total_price - $fee_amount;

        // A. Pagar al VENDEDOR (Monto Neto)
        $stmt_v = $pdo->prepare("INSERT INTO ledger (user_id, order_id, amount, entry_type, category, description) VALUES (?, ?, ?, 'credit', 'sale_payout', ?)");
        $desc_v = "Sale Payout (Net): Order #" . $order['id'];
        $stmt_v->execute([$order['seller_id'], $order_id, $seller_net, $desc_v]);

        // B. Registrar GANANCIA ADMIN (Tu comisión)
        // Usamos user_id = 1 (o el ID que tengas como admin principal)
        $stmt_a = $pdo->prepare("INSERT INTO ledger (user_id, order_id, amount, entry_type, category, description) VALUES (?, ?, ?, 'credit', 'commission', ?)");
        $desc_a = "Platform Fee (10%): Order #" . $order['id'];
        $stmt_a->execute([1, $order_id, $fee_amount, $desc_a]);

        // C. Opcional: Insertar en la tabla admin_earnings para reportes rápidos
        $stmt_ae = $pdo->prepare("INSERT INTO admin_earnings (order_id, amount) VALUES (?, ?)");
        $stmt_ae->execute([$order_id, $fee_amount]);

        // D. Cambiar estado a 'completed'
        $stmt_u = $pdo->prepare("UPDATE orders SET status = 'completed' WHERE id = ?");
        $stmt_u->execute([$order_id]);

        $msg = "Funds released! Seller received $" . number_format($seller_net, 2) . " (Fee: $" . number_format($fee_amount, 2) . ")";

    } elseif ($action === 'dispute') {
        $stmt_u = $pdo->prepare("UPDATE orders SET status = 'dispute' WHERE id = ?");
        $stmt_u->execute([$order_id]);
        $msg = "Dispute opened. Our team will review the transaction.";
    }

    $pdo->commit();
    header("Location: my_orders.php?success=" . urlencode($msg));

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    header("Location: my_orders.php?error=" . urlencode($e->getMessage()));
}