<?php
namespace App\Services;

class CurrencyService {
    protected static $rates = [];
    protected static $cacheFile = __DIR__ . '/../../data/currency_cache.json';
    protected static $currentCurrency = 'TRY';
    protected static $availableCurrencies = ['TRY', 'USD', 'EUR'];

    public static function init() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        $currency = isset($_SESSION['currency']) ? $_SESSION['currency'] : 'TRY';

        if (isset($_GET['currency']) && in_array(strtoupper($_GET['currency']), self::$availableCurrencies)) {
            $currency = strtoupper($_GET['currency']);
            $_SESSION['currency'] = $currency;
        }

        self::$currentCurrency = $currency;
        self::loadRates();
    }

    protected static function loadRates() {
        // Try to load cached rates first
        if (file_exists(self::$cacheFile)) {
            $age = time() - filemtime(self::$cacheFile);
            if ($age < 3600) { // 1 hour cache
                $content = file_get_contents(self::$cacheFile);
                self::$rates = json_decode($content, true) ?: [];
                if (!empty(self::$rates)) {
                    return;
                }
            }
        }

        // Fetch live rates from truncgil
        self::fetchLiveRates();
    }

    protected static function fetchLiveRates() {
        $apiUrl = 'https://finans.truncgil.com/today.json';
        
        $ctx = stream_context_create([
            'http' => [
                'timeout' => 3, // 3 seconds timeout
                'user_agent' => 'Mozilla/5.0'
            ]
        ]);
        
        $json = @file_get_contents($apiUrl, false, $ctx);
        if ($json) {
            $data = json_decode($json, true);
            if (isset($data['ABD Doları']) && isset($data['Euro'])) {
                // Parse Truncgil format:
                // "ABD Doları": { "Alış": "32.4500", "Satış": "32.4800", ... }
                // We'll use "Satış" (selling rate) as the conversion factor to TRY
                $usdToTry = (float)str_replace(',', '.', isset($data['ABD Doları']['Satış']) ? $data['ABD Doları']['Satış'] : (isset($data['ABD Doları']['Buying']) ? $data['ABD Doları']['Buying'] : 32.5));
                $eurToTry = (float)str_replace(',', '.', isset($data['Euro']['Satış']) ? $data['Euro']['Satış'] : (isset($data['Euro']['Buying']) ? $data['Euro']['Buying'] : 35.5));
                
                self::$rates = [
                    'USD_TRY' => $usdToTry,
                    'EUR_TRY' => $eurToTry,
                    'USD' => $usdToTry, // relative to TRY
                    'EUR' => $eurToTry,
                    'TRY' => 1.0,
                    'updated_at' => time()
                ];
                
                // Write cache
                @file_put_contents(self::$cacheFile, json_encode(self::$rates));
                return;
            }
        }

        // Fallback rates if API fails
        if (file_exists(self::$cacheFile)) {
            // Load expired cache if API fails
            self::$rates = json_decode(file_get_contents(self::$cacheFile), true) ?: [];
        }

        if (empty(self::$rates)) {
            self::$rates = [
                'TRY' => 1.0,
                'USD' => 32.5,
                'EUR' => 35.5,
                'updated_at' => time()
            ];
        }
    }

    public static function convert(float $amount, string $from, $to) {
        if (empty(self::$rates)) {
            self::loadRates();
        }

        $from = strtoupper($from);
        $to = strtoupper($to);

        if ($from === $to) {
            return $amount;
        }

        // Standardize everything to TRY first
        $rateFrom = isset(self::$rates[$from]) ? self::$rates[$from] : 1.0;
        $rateTo = isset(self::$rates[$to]) ? self::$rates[$to] : 1.0;

        $amountInTry = $amount * $rateFrom;
        return $amountInTry / $rateTo;
    }

    public static function format(float $amount, $currency = null) {
        $currency = $currency ?: self::$currentCurrency;
        
        switch ($currency) {
            case 'USD':
                return '$' . number_format($amount, 2, '.', ',');
            case 'EUR':
                return '€' . number_format($amount, 2, ',', '.');
            case 'TRY':
            default:
                return '₺' . number_format($amount, 2, ',', '.');
        }
    }

    public static function getSymbol($currency = null) {
        $currency = $currency ?: self::$currentCurrency;
        switch ($currency) {
            case 'USD': return '$';
            case 'EUR': return '€';
            case 'TRY':
            default: return '₺';
        }
    }

    public static function getCurrentCurrency() {
        return self::$currentCurrency;
    }

    public static function getAvailableCurrencies() {
        return self::$availableCurrencies;
    }
}
