<?php
/**
 * Bank List Helper
 * 
 * This file fetches bank list from Fingpay API.
 * Falls back to static list if API is unavailable.
 */

require_once __DIR__ . '/FingpayAEPS.php';

// Static fallback bank codes (used only if API fails)
// These are common AEPS Bank Codes (NPCI Standard)
$FALLBACK_BANK_CODES = [
    '607094' => 'State Bank of India (SBI)',
    '607027' => 'Punjab National Bank (PNB)',
    '606985' => 'Bank of Baroda (BOB)',
    '607057' => 'ICICI Bank',
    '607010' => 'HDFC Bank',
    '607034' => 'Axis Bank',
    '607005' => 'Canara Bank',
    '607003' => 'Union Bank of India',
    '607024' => 'Indian Bank',
    '607002' => 'Indian Overseas Bank',
    '607013' => 'IDBI Bank',
    '607039' => 'Bank of India',
    '607014' => 'Oriental Bank of Commerce',
    '607026' => 'Andhra Bank',
    '607022' => 'Central Bank of India',
    '607040' => 'Corporation Bank',
    '607032' => 'Syndicate Bank',
    '607015' => 'UCO Bank',
    '607031' => 'United Bank of India',
    '607035' => 'Vijaya Bank',
    '607041' => 'Dena Bank',
    '607042' => 'IDFC First Bank', 
    '607043' => 'Yes Bank',
    '607044' => 'Kotak Mahindra Bank',
    '607045' => 'IndusInd Bank',
    '607046' => 'Federal Bank',
    '607047' => 'Karur Vysya Bank',
    '607048' => 'South Indian Bank',
    '607049' => 'DCB Bank',
    '607050' => 'RBL Bank',
    '607051' => 'Bandhan Bank',
    '607052' => 'Punjab & Sind Bank',
    '607053' => 'Jammu & Kashmir Bank',
    '607054' => 'Allahabad Bank',
    '607055' => 'Andhra Bank',
    '607056' => 'Indian Bank',
];

/**
 * Fetch bank list from Fingpay API
 * 
 * @param string $certPath Path to certificate file
 * @param string|null $merchantId Merchant ID (optional)
 * @return array Bank list as associative array with code => name
 */
function fetchBankListFromAPI($certPath, $merchantId = null) {
    try {
        if (!file_exists($certPath)) {
            return [];
        }
        
        $fingpay = new FingpayAEPS($certPath, 30);
        $response = $fingpay->getBankList($merchantId);
        
        // Check for HTTP errors
        if (isset($response['http_code'])) {
            $httpCode = $response['http_code'];
            if ($httpCode >= 400) {
                // HTTP error (4xx, 5xx) - return empty to use fallback
                return [];
            }
        }
        
        // Check if response indicates an error
        if (isset($response['status']) && $response['status'] === 'error') {
            return [];
        }
        
        // Check for common error indicators
        if ((isset($response['error']) || (isset($response['message']) && 
            (stripos($response['message'], 'not found') !== false || 
             stripos($response['message'], 'error') !== false)))) {
            return [];
        }
        
        // Check if response contains error-like structure (path, error keys)
        if (isset($response['path']) || isset($response['error'])) {
            // This looks like an error response, not bank data
            return [];
        }
        
        // Parse response - format may vary based on actual API
        // Try common response formats
        $banks = [];
        
        if (isset($response['banks']) && is_array($response['banks'])) {
            // Format: { "banks": [{"code": "...", "name": "..."}, ...] }
            foreach ($response['banks'] as $bank) {
                if (isset($bank['code']) && isset($bank['name']) && 
                    is_string($bank['code']) && is_string($bank['name']) &&
                    !empty($bank['code']) && !empty($bank['name']) &&
                    $bank['code'] !== 'path' && $bank['code'] !== 'error') {
                    $banks[$bank['code']] = $bank['name'];
                }
            }
        } elseif (isset($response['data']) && is_array($response['data'])) {
            // Format: { "data": [{"code": "...", "name": "..."}, ...] }
            foreach ($response['data'] as $bank) {
                if (isset($bank['code']) && isset($bank['name']) && 
                    is_string($bank['code']) && is_string($bank['name']) &&
                    !empty($bank['code']) && !empty($bank['name']) &&
                    $bank['code'] !== 'path' && $bank['code'] !== 'error') {
                    $banks[$bank['code']] = $bank['name'];
                }
            }
        } elseif (is_array($response)) {
            // Format: [{"code": "...", "name": "..."}, ...] or {"607094": "SBI", ...}
            foreach ($response as $key => $value) {
                // Skip error-related keys
                if (in_array($key, ['status', 'error', 'message', 'path', 'http_code', 'raw_response'])) {
                    continue;
                }
                
                if (is_array($value) && isset($value['code']) && isset($value['name'])) {
                    if (is_string($value['code']) && is_string($value['name']) &&
                        !empty($value['code']) && !empty($value['name']) &&
                        $value['code'] !== 'path' && $value['code'] !== 'error') {
                        $banks[$value['code']] = $value['name'];
                    }
                } elseif (is_string($value) && is_string($key)) {
                    // Already in code => name format
                    // Validate: key should be numeric (bank code) and value should be bank name
                    if (ctype_digit($key) && strlen($key) >= 4 && strlen($key) <= 8) {
                        $banks[$key] = $value;
                    }
                }
            }
        }
        
        // Only return if we have valid banks (more than 0)
        if (count($banks) > 0) {
            return $banks;
        }
        
        // If we got here but no valid banks, return empty to use fallback
        return [];
    } catch (Exception $e) {
        // Log error if needed
        error_log("Bank list API error: " . $e->getMessage());
        return [];
    }
}

/**
 * Get all bank codes from API, fallback to static list
 * 
 * @param string|null $certPath Path to certificate file (optional, uses default if not provided)
 * @param string|null $merchantId Merchant ID (optional)
 * @param bool $useAPI Whether to try API first (default: true)
 * @return array Associative array with bank code as key and bank name as value
 */
function getBankList($certPath = null, $merchantId = null, $useAPI = true) {
    global $FALLBACK_BANK_CODES;
    
    $bankList = [];
    
    // Try to fetch from API if enabled
    if ($useAPI) {
        if ($certPath === null) {
            $certPath = __DIR__ . '/../fingpay_public_production.txt';
        }
        
        $bankList = fetchBankListFromAPI($certPath, $merchantId);
    }
    
    // Fallback to static list if API failed or not enabled
    if (empty($bankList)) {
        $bankList = $FALLBACK_BANK_CODES;
    }
    
    return $bankList;
}

/**
 * Get bank name by code
 * 
 * @param string $bankCode Bank code
 * @param string|null $certPath Path to certificate file (optional)
 * @param string|null $merchantId Merchant ID (optional)
 * @return string|null Bank name or null if not found
 */
function getBankName($bankCode, $certPath = null, $merchantId = null) {
    $bankList = getBankList($certPath, $merchantId);
    return isset($bankList[$bankCode]) ? $bankList[$bankCode] : null;
}

