<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit(0);

require_once 'wallet_common.php';

try {
    $pdo = getDBConnection();
    walletEnsureSchema($pdo);

    $userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
    if ($userId <= 0) {
        walletJson(['success' => false, 'message' => 'User ID is required', 'transactions' => []], 400);
    }

    $stmt = $pdo->prepare("
        SELECT
            id, type, amount, description, payment_method,
            COALESCE(transaction_time, created_at) AS transaction_time,
            balance_after, transaction_id, reference_id, status, created_at
        FROM wallet_transactions
        WHERE user_id = ?
        ORDER BY created_at DESC
        LIMIT 50
    ");
    $stmt->execute([$userId]);

    $transactions = [];
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $transaction) {
        $transactions[] = [
            'id' => (int)$transaction['id'],
            'type' => $transaction['type'],
            'amount' => (float)$transaction['amount'],
            'description' => $transaction['description'],
            'payment_method' => $transaction['payment_method'],
            'timestamp' => $transaction['transaction_time'],
            'balance_after' => (float)$transaction['balance_after'],
            'transaction_id' => $transaction['transaction_id'],
            'reference_id' => $transaction['reference_id'],
            'status' => $transaction['status'],
            'created_at' => $transaction['created_at']
        ];
    }

    walletJson([
        'success' => true,
        'message' => 'Transactions retrieved successfully',
        'transactions' => $transactions,
        'user_id' => $userId,
        'count' => count($transactions)
    ]);
} catch (Exception $e) {
    walletJson(['success' => false, 'message' => $e->getMessage(), 'transactions' => []], 500);
}
?>
