<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ExchangeRate extends Model
{
    use HasFactory;

    protected $fillable = [
        'currency_code',
        'currency_name',
        'rate',
        'usd_rate',
        'ngn_rate',
        'is_active',
        'updated_by',
    ];

    protected $casts = [
        'rate' => 'decimal:4',
        'usd_rate' => 'decimal:4',
        'ngn_rate' => 'decimal:4',
        'is_active' => 'boolean',
    ];

    public function updatedByUser()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public static function getRate($currencyCode = 'USD')
    {
        $rate = self::where('currency_code', $currencyCode)
            ->where('is_active', true)
            ->first();

        return $rate ? $rate->rate : null;
    }

    public static function convertToNaira($amount, $currencyCode = 'USD')
    {
        $rate = self::getRate($currencyCode);
        return $rate ? $amount * $rate : null;
    }

    public static function convertFromNaira($amountInNaira, $currencyCode = 'USD')
    {
        $rate = self::getRate($currencyCode);
        return $rate ? $amountInNaira / $rate : null;
    }
}
