<?php
require_once __DIR__ . '/../includes/db.php';

// Fetch pending transfers that have expired
$stmt = $pdo->prepare("
    SELECT t.id, t.user_id, t.amount
    FROM transactions t
    WHERE t.status = 'pending'
    AND t.expires_at IS NOT NULL
    AND t.expires_at <= NOW()
");
$stmt->execute();
$expiredTransfers = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!$expiredTransfers) {
    exit; // No expired transfers
}

foreach ($expiredTransfers as $transfer) {
    $user_id = $transfer['user_id'];
    $amount = $transfer['amount'];
    $transaction_id = $transfer['id'];

    // Refund back to user balance in USERS TABLE
    $updateBalance = $pdo->prepare("
        UPDATE users
        SET account_balance = account_balance + ?
        WHERE id = ?
    ");
    $updateBalance->execute([$amount, $user_id]);

    // Mark transaction as reversed
    $updateTxn = $pdo->prepare("
        UPDATE transactions
        SET status = 'reversed'
        WHERE id = ?
    ");
    $updateTxn->execute([$transaction_id]);
}
