<?php

namespace App\Helpers;

use App\Models\Currency;

class CurrencyHelper
{
    /**
     * Convert amount from one currency to another or to base currency.
     *
     * @param float $amount
     * @param Currency|int|null $fromCurrency
     * @param Currency|int|null $toCurrency
     * @return float
     */
    public static function convert($amount, $fromCurrency = null, $toCurrency = null)
    {
        if (!$fromCurrency) {
            // Assume Base Currency
            return $amount;
        }

        if (is_numeric($fromCurrency)) {
            $fromCurrency = Currency::find($fromCurrency);
        }

        if (!$fromCurrency) {
            return $amount; // Fallback
        }

        // Convert to Base First
        // Base = Amount * ExchangeRate (if Rate is "How many Base units for 1 Foreign unit")
        // Check definition: "Relative to base currency" usually means 1 Foreign = X Base.
        // e.g. 1 USD = 50 EGP. Rate = 50.
        $baseAmount = $amount * $fromCurrency->exchange_rate;

        if (!$toCurrency) {
            return $baseAmount;
        }

        if (is_numeric($toCurrency)) {
            $toCurrency = Currency::find($toCurrency);
        }

        if (!$toCurrency) {
            return $baseAmount;
        }

        // Convert from Base to Target
        // Target = Base / TargetRate
        return $baseAmount / ($toCurrency->exchange_rate ?: 1); // Avoid div by zero
    }

    /**
     * Get the Base Currency.
     */
    public static function getBaseCurrency()
    {
        return Currency::where('is_base', true)->first() ?? Currency::first();
    }
}
