<?php
/**
 * Simple Exchange Rate Helper
 * Fetches real-time exchange rates from a public API and caches them locally.
 */

function get_exchange_rates() {
    if (!function_exists('db')) {
        require_once __DIR__ . '/../db/config.php';
    }
    $cache_file = __DIR__ . '/../db/exchange_rates.json';
    $cache_time = 60; // Cache for 1 minute for better precision

    // Try to load from cache first
    if (file_exists($cache_file) && (time() - filemtime($cache_file) < $cache_time)) {
        return json_decode(file_get_contents($cache_file), true);
    }

    $rates = null;

    // Use a more reliable free public API
    $api_url = 'https://open.er-api.com/v6/latest/USD';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $response = curl_exec($ch);
    curl_close($ch);

    if ($response) {
        $data = json_decode($response, true);
        if ($data && isset($data['rates'])) {
            $rates = $data['rates'];
        }
    }

    // Fallback rates if API fails or returns incomplete data
    // Updated to more realistic 2024/2025 values
    $fallbacks = [
        'USD' => 1.0,
        'EUR' => 0.92,
        'GBP' => 0.79,
        'CNY' => 7.25,
        'JPY' => 151.0,
        'HKD' => 7.83,
        'TWD' => 32.2,
        'KRW' => 1350.0,
        'MYR' => 4.78,
        'THB' => 36.5,
        'VND' => 25000.0,
        'SGD' => 1.35,
        'PHP' => 56.5,
        'IDR' => 16000.0,
        'AUD' => 1.54,
        'CAD' => 1.36,
        'CHF' => 0.90,
        'BRL' => 5.10,
        'RUB' => 93.0,
        'INR' => 83.4,
        'TRY' => 32.8,
        'AED' => 3.67,
    ];

    if (!$rates) {
        $rates = $fallbacks;
    } else {
        // Merge with fallbacks to ensure all required currencies exist
        foreach ($fallbacks as $code => $rate) {
            if (!isset($rates[$code])) {
                $rates[$code] = $rate;
            }
        }
    }

    // Apply manual overrides from database (e.g., rate_MYR = 4.5)
    try {
        $stmt = db()->query("SELECT setting_key, setting_value FROM system_settings WHERE setting_key LIKE 'rate_%'");
        $overrides = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        foreach ($overrides as $key => $val) {
            $currency = strtoupper(str_replace('rate_', '', $key));
            if ($val > 0) {
                $rates[$currency] = (float)$val;
            }
        }
    } catch (Exception $e) {
        // Ignore DB errors during rate fetching
    }

    file_put_contents($cache_file, json_encode($rates));
    return $rates;
}

function get_rate($currency) {
    $rates = get_exchange_rates();
    return $rates[$currency] ?? 1.0;
}

function get_global_currencies() {
    return [
        'USD' => ['name' => __('usd_name'), 'flag' => '🇺🇸'],
        'EUR' => ['name' => __('eur_name'), 'flag' => '🇪🇺'],
        'GBP' => ['name' => __('gbp_name'), 'flag' => '🇬🇧'],
        'JPY' => ['name' => __('jpy_name'), 'flag' => '🇯🇵'],
        'CNY' => ['name' => __('cny_name'), 'flag' => '🇨🇳'],
        'HKD' => ['name' => __('hkd_name'), 'flag' => '🇭🇰'],
        'TWD' => ['name' => __('twd_name'), 'flag' => '🇹🇼'],
        'KRW' => ['name' => __('krw_name'), 'flag' => '🇰🇷'],
        'SGD' => ['name' => __('sgd_name'), 'flag' => '🇸🇬'],
        'MYR' => ['name' => __('myr_name'), 'flag' => '🇲🇾'],
        'THB' => ['name' => __('thb_name'), 'flag' => '🇹🇭'],
        'VND' => ['name' => __('vnd_name'), 'flag' => '🇻🇳'],
        'PHP' => ['name' => __('php_name'), 'flag' => '🇵🇭'],
        'IDR' => ['name' => __('idr_name'), 'flag' => '🇮🇩'],
        'AUD' => ['name' => __('aud_name'), 'flag' => '🇦🇺'],
        'CAD' => ['name' => __('cad_name'), 'flag' => '🇨🇦'],
        'CHF' => ['name' => __('chf_name'), 'flag' => '🇨🇭'],
        'BRL' => ['name' => __('brl_name'), 'flag' => '🇧🇷'],
        'RUB' => ['name' => __('rub_name'), 'flag' => '🇷🇺'],
        'INR' => ['name' => __('inr_name'), 'flag' => '🇮🇳'],
        'ZAR' => ['name' => __('zar_name'), 'flag' => '🇿🇦'],
        'TRY' => ['name' => __('try_name'), 'flag' => '🇹🇷'],
        'AED' => ['name' => __('aed_name'), 'flag' => '🇦🇪'],
        'SAR' => ['name' => __('sar_name'), 'flag' => '🇸🇦'],
        'MXN' => ['name' => __('mxn_name'), 'flag' => '🇲🇽'],
        'NZD' => ['name' => 'NZD', 'flag' => '🇳🇿'],
        'SEK' => ['name' => 'SEK', 'flag' => '🇸🇪'],
        'NOK' => ['name' => 'NOK', 'flag' => '🇳🇴'],
        'DKK' => ['name' => 'DKK', 'flag' => '🇩🇰'],
        'ILS' => ['name' => 'ILS', 'flag' => '🇮🇱'],
        'PLN' => ['name' => 'PLN', 'flag' => '🇵🇱'],
        'PKR' => ['name' => 'PKR', 'flag' => '🇵🇰'],
        'EGP' => ['name' => 'EGP', 'flag' => '🇪🇬'],
        'ARS' => ['name' => 'ARS', 'flag' => '🇦🇷'],
        'CLP' => ['name' => 'CLP', 'flag' => '🇨🇱'],
        'COP' => ['name' => 'COP', 'flag' => '🇨🇴'],
        'PEN' => ['name' => 'PEN', 'flag' => '🇵🇪'],
        'KWD' => ['name' => 'KWD', 'flag' => '🇰🇼'],
        'QAR' => ['name' => 'QAR', 'flag' => '🇶🇦'],
    ];
}
