<?php
/**
 * Currency helper (server-side, safe for both localhost + cPanel)
 * Base currency: EUR
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

function currency_exchange_rates(): array {
    // Keep in sync with api_set_preference.php
    return [
        'eur' => 1.0,
        'usd' => 1.10,
        'gbp' => 0.87,
        'cad' => 1.48,
    ];
}

function currency_symbols(): array {
    return [
        'eur' => '€',
        'usd' => '$',
        'gbp' => '£',
        'cad' => 'C$',
    ];
}

function get_selected_currency(): string {
    $curr = strtolower((string)($_SESSION['selected_currency'] ?? 'eur'));
    $rates = currency_exchange_rates();
    return isset($rates[$curr]) ? $curr : 'eur';
}

function convert_amount_from_eur(float $amountEur, ?string $currency = null): float {
    $rates = currency_exchange_rates();
    $curr = $currency ? strtolower($currency) : get_selected_currency();
    $rate = $rates[$curr] ?? 1.0;
    return $amountEur * $rate;
}

function format_currency(float $amountEur, ?string $currency = null): string {
    $curr = $currency ? strtolower($currency) : get_selected_currency();
    $symbols = currency_symbols();
    $symbol = $symbols[$curr] ?? '€';
    $converted = convert_amount_from_eur($amountEur, $curr);
    return $symbol . number_format($converted, 2, '.', '');
}

