<?php
declare(strict_types=1);

/* ===============================
   LOAD CURRENCIES
================================ */
$CURRENCIES = require dirname(__DIR__) . '/config/currencies.php';

/* ===============================
   DEFAULT SYSTEM CURRENCY
================================ */
if (!defined('DEFAULT_CURRENCY')) {
    define('DEFAULT_CURRENCY', 'USD');
}

/* ===============================
   GET ACTIVE CURRENCY
================================ */
if (!function_exists('current_currency')) {
    function current_currency(): array
    {
        global $CURRENCIES;

        // Priority: user → session → default
        if (!empty($_SESSION['currency']) && isset($CURRENCIES[$_SESSION['currency']])) {
            return $CURRENCIES[$_SESSION['currency']];
        }

        return $CURRENCIES[DEFAULT_CURRENCY];
    }
}

/* ===============================
   FORMAT MONEY
================================ */
if (!function_exists('money')) {
    function money(float|int $amount, ?string $currencyCode = null): string
    {
        global $CURRENCIES;

        $currency = $currencyCode && isset($CURRENCIES[$currencyCode])
            ? $CURRENCIES[$currencyCode]
            : current_currency();

        $converted = $amount * $currency['rate'];

        return $currency['symbol'] . number_format($converted, 2);
    }
}

/* ===============================
   RAW CONVERSION (NO SYMBOL)
================================ */
if (!function_exists('convert_currency')) {
    function convert_currency(float|int $amount, string $to): float
    {
        global $CURRENCIES;

        if (!isset($CURRENCIES[$to])) {
            return (float) $amount;
        }

        return $amount * $CURRENCIES[$to]['rate'];
    }
}
