<?php

use App\Models\Currency;

if (!function_exists('format_currency')) {
    /**
     * Format amount with active currency
     */
    function format_currency($amount, $currency = null): string
    {
        if (!$currency) {
            // Try to get from shared view data first
            if (view()->shared('activeCurrency')) {
                $currency = view()->shared('activeCurrency');
            } else {
                $currency = Currency::getDefault() ?? new Currency([
                    'code' => 'USD',
                    'symbol' => '$',
                    'symbol_position' => 'left',
                ]);
            }
        }

        return $currency->formatAmount($amount);
    }
}

if (!function_exists('get_active_currency')) {
    /**
     * Get the active/default currency
     */
    function get_active_currency(): Currency
    {
        // Try to get from shared view data first
        if (view()->shared('activeCurrency')) {
            return view()->shared('activeCurrency');
        }

        return Currency::getDefault() ?? new Currency([
            'code' => 'USD',
            'name' => 'US Dollar',
            'symbol' => '$',
            'symbol_position' => 'left',
            'exchange_rate' => 1.000000,
        ]);
    }
}

if (!function_exists('currency_symbol')) {
    /**
     * Get just the currency symbol
     */
    function currency_symbol(): string
    {
        $currency = get_active_currency();
        return $currency->symbol;
    }
}

if (!function_exists('currency_code')) {
    /**
     * Get the currency code
     */
    function currency_code(): string
    {
        $currency = get_active_currency();
        return $currency->code;
    }
}
