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


// 1. Security: Check login
if (!isset($_SESSION['user_id'])) { 
    die("Unauthorized access."); 
}

// Ensure the request is POST for security
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['order_id'])) {
    header("Location: dashboard.php");
    exit;
}

$order_id = (int)$_POST['order_id'];
$seller_id = $_SESSION['user_id']; // Direct numeric ID

try {
    $pdo->beginTransaction();

    // 2. Fetch order and verify that the CURRENT user is the SELLER
    // Added FOR UPDATE to lock the rows and prevent "double-refund" race conditions.
    $stmt = $pdo->prepare("
        SELECT o.*, u.balance as seller_balance 
        FROM orders o 
        JOIN users u ON o.seller_id = u.id 
        WHERE o.id = ? AND o.seller_id = ? 
        FOR UPDATE
    ");
    $stmt->execute([$order_id, $seller_id]);
    $order = $stmt->fetch();

    // 3. Validation
    if (!$order) { 
        throw new Exception("Order not found or you are not the authorized seller."); 
    }

    if ($order['status'] === 'refunded') { 
        throw new Exception("This transaction has already been refunded."); 
    }
    
    // Safety: Only allow refunds for completed or pending orders
    if ($order['status'] === 'cancelled') {
        throw new Exception("Cannot refund a cancelled order.");
    }

    $refund_amount = $order['total_price'];

    // 4. Verify Seller has enough balance to cover the refund
    if ($order['seller_balance'] < $refund_amount) {
        throw new Exception("Insufficient Vault balance to process this refund. Please deposit funds.");
    }

    // --- EXECUTE TRANSACTION ---

    // A. Deduct from Seller
    $deduct = $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
    $deduct->execute([$refund_amount, $seller_id]);

    // B. Credit the Buyer
    $credit = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
    $credit->execute([$refund_amount, $order['buyer_id']]);

    // C. Update Order Status
    $update_order = $pdo->prepare("UPDATE orders SET status = 'refunded', updated_at = NOW() WHERE id = ?");
    $update_order->execute([$order_id]);

    // D. Log the transaction (Optional but highly recommended for a marketplace)
    // $pdo->prepare("INSERT INTO transactions (user_id, amount, type) VALUES (?, ?, 'refund')")->execute([$seller_id, -$refund_amount]);

    $pdo->commit();
    
    // Redirect with success flag
    header("Location: my_sales.php?refund_success=1");
    exit;

} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    // Log the error for the admin and show a clean message to the user
    error_log("Refund Error: " . $e->getMessage());
    die("<div style='color: #ff4d4d; font-family: sans-serif; text-align: center; margin-top: 50px;'>
            <strong>Vault Error:</strong> " . htmlspecialchars($e->getMessage()) . "
         </div>");
}