<?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');

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

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

try {
    $pdo = getDBConnection();
    
    // Get all successful payments
    $payments = $pdo->query("
        SELECT 
            transaction_id,
            amount,
            status,
            payment_method,
            created_at
        FROM payments
        WHERE status = 'SUCCESS'
        ORDER BY created_at DESC
        LIMIT 50
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Format the payments
    foreach ($payments as &$payment) {
        $payment['created_at'] = date('M d, Y H:i', strtotime($payment['created_at']));
    }
    
    echo json_encode([
        'success' => true,
        'payments' => $payments,
        'count' => count($payments)
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
