<?php
/**
 * Bank List API Endpoint
 * 
 * Returns list of supported banks with their codes from Fingpay API
 * Falls back to static list if API is unavailable
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once 'bank_list.php';

// Load API configuration for credentials
$configFile = __DIR__ . '/api_config.php';
if (file_exists($configFile)) {
    $config = require $configFile;
    $credentials = $config['credentials'] ?? [];
    $defaultMerchantId = $credentials['merchant_id'] ?? $credentials['super_merchant_id'] ?? null;
    $certPath = $config['certificate_path'] ?? (__DIR__ . '/../fingpay_public_production.txt');
} else {
    $defaultMerchantId = null;
    $certPath = __DIR__ . '/../fingpay_public_production.txt';
}

// Get merchant ID from request or config if needed
$merchantId = isset($_GET['merchantId']) ? $_GET['merchantId'] : $defaultMerchantId;

// Try to fetch from API, fallback to static list
// API is enabled - will fetch dynamically from Fingpay API
// Falls back to static list automatically if API fails
$useAPI = true; // Set to true to try API first (DYNAMIC), false to always use static list
$bankList = getBankList($certPath, $merchantId, $useAPI);

// Format for frontend
$formattedBanks = [];
foreach ($bankList as $code => $name) {
    $formattedBanks[] = [
        'code' => $code,
        'name' => $name
    ];
}

// Sort by bank name for better UX
usort($formattedBanks, function($a, $b) {
    return strcmp($a['name'], $b['name']);
});

echo json_encode([
    'status' => 'success',
    'banks' => $formattedBanks,
    'source' => $useAPI ? (count($formattedBanks) > 0 ? 'api' : 'static') : 'static',
    'count' => count($formattedBanks)
]);

