<?php
class EscrowManager {
    private $pdo;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    /**
     * Paso 1: El comprador paga. El dinero sale de su cuenta y queda "en el aire" (FUNDS_HELD).
     */
    public function holdFunds($order_id, $buyer_id, $amount) {
        try {
            $this->pdo->beginTransaction();

            // 1. Verificar saldo del comprador (vía Ledger)
            $stmt = $this->pdo->prepare("SELECT SUM(CASE WHEN entry_type = 'credit' THEN amount ELSE -amount END) FROM ledger WHERE user_id = ?");
            $stmt->execute([$buyer_id]);
            $balance = $stmt->fetchColumn() ?: 0;

            if ($balance < $amount) throw new Exception("Insufficient balance.");

            // 2. Registrar Débito en el Ledger (Salida de dinero del comprador)
            $stmt_l = $this->pdo->prepare("INSERT INTO ledger (user_id, amount, entry_type, category, description) VALUES (?, ?, 'debit', 'escrow_hold', ?)");
            $stmt_l->execute([$buyer_id, $amount, "Funds held in Escrow for Order #$order_id"]);

            // 3. Cambiar estado a FUNDS_HELD
            $stmt_e = $this->pdo->prepare("UPDATE escrow_orders SET status = 'FUNDS_HELD' WHERE id = ?");
            $stmt_e->execute([$order_id]);

            $this->pdo->commit();
            return true;
        } catch (Exception $e) {
            $this->pdo->rollBack();
            return $e->getMessage();
        }
    }

    /**
     * Paso 2: Confirmación Final. El dinero se libera al vendedor.
     */
    public function settleOrder($order_id) {
        try {
            $this->pdo->beginTransaction();

            // 1. Obtener datos de la orden
            $stmt = $this->pdo->prepare("SELECT seller_id, amount, status FROM escrow_orders WHERE id = ?");
            $stmt->execute([$order_id]);
            $order = $stmt->fetch();

            if ($order['status'] !== 'FUNDS_HELD' && $order['status'] !== 'DELIVERY_PENDING') {
                throw new Exception("Order is not in a settleable state.");
            }

            // 2. Registrar Crédito en el Ledger (El vendedor recibe el dinero)
            $stmt_l = $this->pdo->prepare("INSERT INTO ledger (user_id, amount, entry_type, category, description) VALUES (?, ?, 'credit', 'sale_settled', ?)");
            $stmt_l->execute([$order['seller_id'], $order['amount'], "Escrow released for Order #$order_id"]);

            // 3. Estado Final: SETTLED
            $stmt_e = $this->pdo->prepare("UPDATE escrow_orders SET status = 'SETTLED' WHERE id = ?");
            $stmt_e->execute([$order_id]);

            $this->pdo->commit();
            return true;
        } catch (Exception $e) {
            $this->pdo->rollBack();
            return $e->getMessage();
        }
    }
}