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

// Enforce Rate Limiting (Max 20 history fetches per minute per IP)
checkRateLimit('wallet_history', 20, 60);

$userId = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;

if ($userId <= 0) {
    // If not in GET, check POST json body
    $data = json_decode(file_get_contents("php://input"), true);
    if (!empty($data['user_id'])) {
        $userId = intval($data['user_id']);
    }
}

if ($userId <= 0) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "user_id is required."]);
    exit();
}

try {
    $db = getDBConnection();

    // Query immutable ledger
    $stmt = $db->prepare("SELECT id, action, amount, balance_before, balance_after, reference, created_at FROM wallet_transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT 50");
    $stmt->execute([$userId]);
    $transactions = $stmt->fetchAll();

    $formatted = [];
    foreach ($transactions as $t) {
        $formatted[] = [
            "id" => intval($t['id']),
            "action" => $t['action'],
            "amount" => floatval($t['amount']),
            "balance_before" => floatval($t['balance_before']),
            "balance_after" => floatval($t['balance_after']),
            "reference" => $t['reference'],
            "created_at" => $t['created_at']
        ];
    }

    echo json_encode([
        "status" => "success",
        "transactions" => $formatted
    ]);

} catch(PDOException $e) {
    logSecurityError("Fetch Wallet History failure (User ID: $userId): " . $e->getMessage());
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Failed to retrieve transaction history."]);
}
