vernova/app/Helpers/CurrencyHelper.php
2026-07-26 19:58:27 +03:30

97 lines
2.6 KiB
PHP

<?php
namespace App\Helpers;
use App\Models\Currency;
use Illuminate\Support\Facades\Cache;
class CurrencyHelper
{
/**
* Convert an amount from one currency to another using USD as pivot.
*/
public static function convert(float $amount, string $fromCode, string $toCode): float
{
if ($fromCode === $toCode) {
return $amount;
}
$fromRate = static::getExchangeRate($fromCode);
$toRate = static::getExchangeRate($toCode);
if ($fromRate <= 0 || $toRate <= 0) {
return 0;
}
// Convert to USD first, then to target currency
$usdAmount = $amount / $fromRate;
return round($usdAmount * $toRate, 2);
}
/**
* Get the exchange rate for a currency relative to USD.
* Cached for 24 hours.
*/
public static function getExchangeRate(string $currencyCode): float
{
return Cache::remember("exchange_rate_{$currencyCode}", now()->addHours(24), function () use ($currencyCode) {
$currency = Currency::where('code', $currencyCode)
->where('is_active', true)
->first();
return $currency?->exchange_rate_to_usd ?? 1;
});
}
/**
* Get the symbol for a currency.
*/
public static function getCurrencySymbol(string $currencyCode): string
{
$currency = Currency::where('code', $currencyCode)->first();
return $currency?->symbol ?? $currencyCode;
}
/**
* Get the decimal places for a currency.
*/
public static function getDecimalPlaces(string $currencyCode): int
{
$currency = Currency::where('code', $currencyCode)->first();
return $currency?->decimal_places ?? 0;
}
/**
* Format an amount with the currency symbol.
*/
public static function formatWithSymbol(float $amount, string $currencyCode, string $locale = 'fa_IR'): string
{
$symbol = static::getCurrencySymbol($currencyCode);
$decimals = static::getDecimalPlaces($currencyCode);
$formatted = NumberHelper::formatNumber($amount, $decimals, $locale);
return $formatted . ' ' . $symbol;
}
/**
* Get the base currency for the current tenant.
*/
public static function getBaseCurrency(): ?Currency
{
$tenantId = session('tenant_id');
if (!$tenantId) {
return null;
}
return Cache::remember("base_currency_{$tenantId}", now()->addHours(24), function () use ($tenantId) {
$tenant = \App\Models\Tenant::find($tenantId);
return $tenant?->baseCurrency;
});
}
}