<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Include database configuration
require_once '../config/database.php';

try {
    // Get user ID from query parameters
    $userId = isset($_GET['user_id']) ? intval($_GET['user_id']) : null;
    
    if (!$userId) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'User ID is required',
            'transactions' => []
        ]);
        exit();
    }
    
    // Prepare and execute query to get transactions
    $stmt = $pdo->prepare("
        SELECT 
            id,
            type,
            amount,
            description,
            payment_method,
            transaction_time,
            balance_after,
            created_at
        FROM wallet_transactions 
        WHERE user_id = ?
        ORDER BY created_at DESC
        LIMIT 50
    ");
    
    $stmt->execute([$userId]);
    $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format transactions for response
    $formattedTransactions = [];
    foreach ($transactions as $transaction) {
        $formattedTransactions[] = [
            'id' => $transaction['id'],
            'type' => $transaction['type'],
            'amount' => floatval($transaction['amount']),
            'description' => $transaction['description'],
            'payment_method' => $transaction['payment_method'],
            'timestamp' => $transaction['transaction_time'],
            'balance_after' => floatval($transaction['balance_after']),
            'created_at' => $transaction['created_at']
        ];
    }
    
    // Return success response
    echo json_encode([
        'success' => true,
        'message' => 'Transactions retrieved successfully',
        'transactions' => $formattedTransactions,
        'user_id' => $userId,
        'count' => count($formattedTransactions)
    ]);
    
} catch (PDOException $e) {
    // Database error
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage(),
        'transactions' => []
    ]);
} catch (Exception $e) {
    // General error
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Server error: ' . $e->getMessage(),
        'transactions' => []
    ]);
}
?> 