<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/db.php';

// Find all pending transactions past expiry
$stmt = $pdo->prepare("
    SELECT * FROM transactions
    WHERE validation_status = 'pending' AND expiry_time < NOW()
");
$stmt->execute();
$expired = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($expired as $tx) {
    $pdo->beginTransaction();
    try {
        $senderId = (int)$tx['sender_id'];
        $amount   = (int)$tx['amount_cents'];

        // Refund sender
        $stmt = $pdo->prepare("SELECT id, balance_cents FROM users WHERE id = ? FOR UPDATE");
        $stmt->execute([$senderId]);
        $sender = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($sender) {
            $refundBal = $sender['balance_cents'] + $amount;
            $pdo->prepare("UPDATE users SET balance_cents = ? WHERE id = ?")
                ->execute([$refundBal, $senderId]);
        }

        // Mark as expired
        $pdo->prepare("UPDATE transactions SET validation_status = 'expired' WHERE id = ?")
            ->execute([$tx['id']]);

        $pdo->commit();

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
    }
}

echo "Auto-refund completed: " . count($expired) . " transactions processed.\n";
