<?php
// Currency Configuration for Multi-Currency Support

// Supported currencies with their details
define('SUPPORTED_CURRENCIES', [
    'USD' => [
        'name' => 'US Dollar',
        'symbol' => '$',
        'symbol_position' => 'before',
        'decimal_places' => 2,
        'paypal_supported' => true,
        'paynow_supported' => false
    ],
    'EUR' => [
        'name' => 'Euro',
        'symbol' => '€',
        'symbol_position' => 'after',
        'decimal_places' => 2,
        'paypal_supported' => true,
        'paynow_supported' => false
    ],
    'GBP' => [
        'name' => 'British Pound',
        'symbol' => '£',
        'symbol_position' => 'before',
        'decimal_places' => 2,
        'paypal_supported' => true,
        'paynow_supported' => false
    ],
    'ZAR' => [
        'name' => 'South African Rand',
        'symbol' => 'R',
        'symbol_position' => 'before',
        'decimal_places' => 2,
        'paypal_supported' => true,
        'paynow_supported' => true
    ],
    'ZWD' => [
        'name' => 'Zimbabwe Dollar',
        'symbol' => 'Z$',
        'symbol_position' => 'before',
        'decimal_places' => 2,
        'paypal_supported' => false,
        'paynow_supported' => true
    ],
    'KES' => [
        'name' => 'Kenyan Shilling',
        'symbol' => 'KSh',
        'symbol_position' => 'before',
        'decimal_places' => 2,
        'paypal_supported' => true,
        'paynow_supported' => false
    ],
    'NGN' => [
        'name' => 'Nigerian Naira',
        'symbol' => '₦',
        'symbol_position' => 'before',
        'decimal_places' => 2,
        'paypal_supported' => true,
        'paynow_supported' => false
    ],
    'GHS' => [
        'name' => 'Ghanaian Cedi',
        'symbol' => '₵',
        'symbol_position' => 'before',
        'decimal_places' => 2,
        'paypal_supported' => true,
        'paynow_supported' => false
    ]
]);

// Default currency
define('DEFAULT_CURRENCY', 'USD');

// Currency exchange rates (base: USD)
// These should be updated regularly from a reliable API
define('CURRENCY_RATES', [
    'USD' => 1.0000,
    'EUR' => 0.8500,
    'GBP' => 0.7300,
    'ZAR' => 18.5000,
    'ZWD' => 300.0000, // Example rate, should be updated
    'KES' => 130.0000,
    'NGN' => 1500.0000,
    'GHS' => 12.0000
]);

/**
 * Currency Helper Class
 */
class CurrencyHelper {
    /**
     * Format currency amount with symbol
     */
    public static function format($amount, $currency = null) {
        if ($currency === null) {
            $currency = DEFAULT_CURRENCY;
        }

        if (!isset(SUPPORTED_CURRENCIES[$currency])) {
            throw new Exception("Unsupported currency: {$currency}");
        }

        $currencyInfo = SUPPORTED_CURRENCIES[$currency];
        $formatted = number_format($amount, $currencyInfo['decimal_places'], '.', ',');

        if ($currencyInfo['symbol_position'] === 'before') {
            return $currencyInfo['symbol'] . $formatted;
        } else {
            return $formatted . ' ' . $currencyInfo['symbol'];
        }
    }

    /**
     * Convert amount from one currency to another
     */
    public static function convert($amount, $fromCurrency, $toCurrency) {
        if ($fromCurrency === $toCurrency) {
            return $amount;
        }

        if (!isset(CURRENCY_RATES[$fromCurrency]) || !isset(CURRENCY_RATES[$toCurrency])) {
            throw new Exception("Currency conversion not supported for {$fromCurrency} to {$toCurrency}");
        }

        // Convert to USD first, then to target currency
        $usdAmount = $amount / CURRENCY_RATES[$fromCurrency];
        $convertedAmount = $usdAmount * CURRENCY_RATES[$toCurrency];

        return round($convertedAmount, 2);
    }

    /**
     * Get currency information
     */
    public static function getCurrencyInfo($currency) {
        if (!isset(SUPPORTED_CURRENCIES[$currency])) {
            throw new Exception("Unsupported currency: {$currency}");
        }

        return SUPPORTED_CURRENCIES[$currency];
    }

    /**
     * Check if currency is supported by gateway
     */
    public static function isSupportedByGateway($currency, $gateway) {
        if (!isset(SUPPORTED_CURRENCIES[$currency])) {
            return false;
        }

        $gatewaySupport = $gateway . '_supported';
        return SUPPORTED_CURRENCIES[$currency][$gatewaySupport] ?? false;
    }

    /**
     * Get currencies supported by a specific gateway
     */
    public static function getGatewaySupportedCurrencies($gateway) {
        $supported = [];
        $gatewaySupport = $gateway . '_supported';

        foreach (SUPPORTED_CURRENCIES as $code => $info) {
            if ($info[$gatewaySupport] ?? false) {
                $supported[$code] = $info;
            }
        }

        return $supported;
    }

    /**
     * Get all supported currencies
     */
    public static function getAllCurrencies() {
        return SUPPORTED_CURRENCIES;
    }

    /**
     * Validate currency code
     */
    public static function isValidCurrency($currency) {
        return isset(SUPPORTED_CURRENCIES[$currency]);
    }

    /**
     * Get currency symbol
     */
    public static function getSymbol($currency) {
        if (!isset(SUPPORTED_CURRENCIES[$currency])) {
            return $currency;
        }

        return SUPPORTED_CURRENCIES[$currency]['symbol'];
    }

    /**
     * Update exchange rates (should be called periodically)
     * In production, this would fetch from an API like fixer.io or currencyapi.com
     */
    public static function updateExchangeRates($rates = null) {
        // For demo purposes, we'll use static rates
        // In production, implement API calls to get live rates
        if ($rates === null) {
            $rates = CURRENCY_RATES;
        }

        // Store in database or cache
        $db = getDB();
        foreach ($rates as $currency => $rate) {
            $stmt = $db->prepare("
                INSERT INTO site_settings (setting_key, setting_value)
                VALUES (?, ?)
                ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
            ");
            $stmt->execute(["currency_rate_{$currency}", $rate]);
        }

        return true;
    }

    /**
     * Get current exchange rate for a currency
     */
    public static function getExchangeRate($currency) {
        if ($currency === 'USD') {
            return 1.0;
        }

        // Try to get from database first
        $db = getDB();
        $stmt = $db->prepare("SELECT setting_value FROM site_settings WHERE setting_key = ?");
        $stmt->execute(["currency_rate_{$currency}"]);
        $result = $stmt->fetch();

        if ($result) {
            return (float) $result['setting_value'];
        }

        // Fallback to static rates
        return CURRENCY_RATES[$currency] ?? 1.0;
    }

    /**
     * Get currency selector HTML
     */
    public static function getCurrencySelector($selected = null, $name = 'currency', $class = 'form-select') {
        if ($selected === null) {
            $selected = DEFAULT_CURRENCY;
        }

        $html = "<select name=\"{$name}\" class=\"{$class}\">";
        foreach (SUPPORTED_CURRENCIES as $code => $info) {
            $selectedAttr = ($code === $selected) ? ' selected' : '';
            $html .= "<option value=\"{$code}\"{$selectedAttr}>{$info['symbol']} {$info['name']} ({$code})</option>";
        }
        $html .= "</select>";

        return $html;
    }
}

/**
 * Helper functions for currency operations
 */
function formatCurrency($amount, $currency = null) {
    return CurrencyHelper::format($amount, $currency);
}

function convertCurrency($amount, $from, $to) {
    return CurrencyHelper::convert($amount, $from, $to);
}

function getCurrencySymbol($currency) {
    return CurrencyHelper::getSymbol($currency);
}

function isValidCurrency($currency) {
    return CurrencyHelper::isValidCurrency($currency);
}