<?php

namespace App\Support;

class Currency
{
    protected static array $currencies = [];

    protected static function load()
    {
        if (!empty(self::$currencies)) {
            return;
        }

        $data = json_decode(file_get_contents(resource_path('data/currencies.json')), true);

        foreach ($data as $currency) {
            self::$currencies[$currency['code']] = $currency;
        }
    }


    public static function symbol(string $code): string
    {
        self::load();

        return self::$currencies[$code]['symbol'] ?? $code;
    }

    public static function decimals(string $code): int
    {
        self::load();

        return self::$currencies[$code]['decimal_digits'] ?? 2;
    }

    // ← Add this method
    public static function all(): array
    {
        self::load();
        return array_keys(self::$currencies);
    }

    public static function format(float|string $amount, string $currencyCode = 'USD'): string
    {
        self::load();

        $symbol = self::symbol($currencyCode);
        $decimals = self::decimals($currencyCode);

        // Ensure amount is float for number_format
        $amount = (float) $amount;

        // Format number with correct decimal digits
        $formattedAmount = number_format($amount, $decimals, '.', ',');

        return $symbol . $formattedAmount;
    }

}
