<?php
/**
 * Currency Management System
 * Handles multi-currency support for BoostWithKagujje
 * Primary: UGX | Secondary: USD, KSH
 */

namespace App\Classes\Currency;

class CurrencyManager {
    private static $instance;
    private $currencies = [];
    private $rates = [];
    private $primaryCurrency = 'UGX';
    
    // Currency metadata
    private $currencyMetadata = [
        'UGX' => ['symbol' => '₨', 'name' => 'Uganda Shilling', 'decimal' => 0, 'country' => 'Uganda'],
        'USD' => ['symbol' => '$', 'name' => 'US Dollar', 'decimal' => 2, 'country' => 'United States'],
        'KSH' => ['symbol' => 'KSh', 'name' => 'Kenyan Shilling', 'decimal' => 2, 'country' => 'Kenya'],
    ];
    
    private function __construct() {
        $this->primaryCurrency = env('PRIMARY_CURRENCY', 'UGX');
        $supportedCurrencies = env('SUPPORTED_CURRENCIES', 'UGX,USD,KSH');
        $this->currencies = array_map('trim', explode(',', $supportedCurrencies));
        
        // Initialize exchange rates (should be fetched from external API in production)
        $this->initializeRates();
    }
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Get all supported currencies
     */
    public function getCurrencies() {
        return $this->currencies;
    }
    
    /**
     * Get currency metadata
     */
    public function getCurrencyMetadata($currency) {
        return $this->currencyMetadata[$currency] ?? null;
    }
    
    /**
     * Get currency symbol
     */
    public function getSymbol($currency) {
        return $this->currencyMetadata[$currency]['symbol'] ?? $currency;
    }
    
    /**
     * Get formatted price
     */
    public function formatPrice($amount, $currency = null, $Symbol = true) {
        $currency = $currency ?: $this->primaryCurrency;
        $metadata = $this->getCurrencyMetadata($currency);
        $decimal = $metadata['decimal'] ?? 2;
        
        $formatted = number_format($amount, $decimal, '.', ',');
        
        if ($symbol) {
            return $this->getSymbol($currency) . ' ' . $formatted;
        }
        
        return $formatted;
    }
    
    /**
     * Convert amount from one currency to another
     */
    public function convert($amount, $fromCurrency, $toCurrency) {
        if ($fromCurrency === $toCurrency) {
            return $amount;
        }
        
        if (!isset($this->rates[$fromCurrency]) || !isset($this->rates[$toCurrency])) {
            throw new \Exception('Exchange rate not available for ' . $fromCurrency . ' or ' . $toCurrency);
        }
        
        // Convert to base currency (USD) first, then to target
        $inUSD = $amount / $this->rates[$fromCurrency];
        $converted = $inUSD * $this->rates[$toCurrency];
        
        return round($converted, 2);
    }
    
    /**
     * Initialize exchange rates (mock data - replace with API call in production)
     */
    private function initializeRates() {
        // Rates relative to USD (1 USD = X currency)
        $this->rates = [
            'USD' => 1.0,
            'UGX' => 3700.0,  // 1 USD = 3700 UGX (approximate)
            'KSH' => 130.0,   // 1 USD = 130 KSH (approximate)
        ];
    }
    
    /**
     * Update exchange rates (should be called periodically)
     */
    public function updateRates($rates) {
        foreach ($rates as $currency => $rate) {
            if (in_array($currency, $this->currencies)) {
                $this->rates[$currency] = $rate;
            }
        }
    }
    
    /**
     * Get current primary currency
     */
    public function getPrimaryCurrency() {
        return $this->primaryCurrency;
    }
    
    /**
     * Check if currency is supported
     */
    public function isSupported($currency) {
        return in_array($currency, $this->currencies);
    }
    
    /**
     * Get exchange rate for currency
     */
    public function getRate($currency) {
        return $this->rates[$currency] ?? null;
    }
    
    /**
     * Get all exchange rates
     */
    public function getAllRates() {
        return $this->rates;
    }
}

// Global helper function
if (!function_exists('currency')) {
    function currency($amount, $currency = null, $symbol = true) {
        return CurrencyManager::getInstance()->formatPrice($amount, $currency, $symbol);
    }
}
?>
