<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Currency extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'code',
        'name',
        'symbol',
        'symbol_position',
        'decimal_places',
        'exchange_rate',
        'is_default',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'exchange_rate' => 'decimal:6',
            'is_default' => 'boolean',
            'is_active' => 'boolean',
        ];
    }

    /**
     * Get default currency
     */
    public static function getDefault(): ?self
    {
        return static::where('is_default', true)->where('is_active', true)->first();
    }

    /**
     * Get default currency code
     * Admin "Default Currency" (localization) wins so it matches Settings → General.
     * Then the active currency row marked default, then USD.
     */
    public static function getDefaultCode(): string
    {
        try {
            $localizationSettings = \App\Models\LocalizationSetting::getSettings();
            if ($localizationSettings && is_string($localizationSettings->default_currency) && $localizationSettings->default_currency !== '') {
                return strtoupper($localizationSettings->default_currency);
            }
        } catch (\Exception $e) {
            // Settings table might not exist
        }

        $default = static::getDefault();
        if ($default) {
            return $default->code;
        }

        return 'USD';
    }

    /**
     * Symbol for an ISO code when no matching row exists in `currencies` (aligns with settings dropdown labels).
     */
    public static function symbolForIsoCode(string $code): string
    {
        return match (strtoupper(trim($code))) {
            'USD', 'AUD', 'CAD', 'SGD', 'HKD', 'NZD', 'MXN' => '$',
            'EUR' => '€',
            'GBP' => '£',
            'JPY', 'CNY' => '¥',
            'CHF' => 'Fr',
            'INR' => '₹',
            'BRL' => 'R$',
            'ZAR' => 'R',
            'RUB' => '₽',
            'TRY' => '₺',
            'KRW' => '₩',
            'THB' => '฿',
            'MYR' => 'RM',
            'IDR' => 'Rp',
            'PHP' => '₱',
            'AED' => 'د.إ',
            'SAR' => '﷼',
            'ILS' => '₪',
            'PLN' => 'zł',
            'SEK', 'NOK', 'DKK' => 'kr',
            'DOP' => 'RD$',
            default => strtoupper($code).' ',
        };
    }

    /**
     * Format amount with currency
     */
    public function format(float $amount): string
    {
        $formatted = number_format($amount, $this->decimal_places);

        if ($this->symbol_position === 'before') {
            return $this->symbol.$formatted;
        }

        return $formatted.' '.$this->symbol;
    }

    /**
     * Format amount with currency by code
     * Static helper to format amounts using currency code
     */
    public static function formatAmount(float $amount, ?string $currencyCode = null): string
    {
        $code = $currencyCode ?? static::getDefaultCode();
        $currency = static::where('code', $code)->where('is_active', true)->first();

        if (! $currency) {
            $sym = static::symbolForIsoCode($code);

            return $sym.number_format($amount, 2);
        }

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

    /**
     * Get currency symbol by code
     */
    public static function getSymbol(?string $currencyCode = null): string
    {
        $code = $currencyCode ?? static::getDefaultCode();
        $currency = static::where('code', $code)->where('is_active', true)->first();

        if ($currency) {
            return $currency->symbol;
        }

        return static::symbolForIsoCode($code);
    }
}
