<?php

namespace App\Models;

use App\Models\BaseModel;

class ExchangeRate extends BaseModel
{
    protected $fillable = ['company_id','currency_id','rate_date','rate'];

    protected $casts = [
        'rate_date' => 'date',
        'rate'      => 'decimal:6',
    ];

    public function company()  { return $this->belongsTo(Company::class); }
    public function currency() { return $this->belongsTo(Currency::class); }

    /**
     * Get the exchange rate for a currency on a given date.
     * Falls back to the most recent rate if no exact match.
     */
    public static function getRateForDate(int $companyId, int $currencyId, string $date): float
    {
        $rate = static::withoutGlobalScopes()
            ->where('company_id', $companyId)
            ->where('currency_id', $currencyId)
            ->where('rate_date', '<=', $date)
            ->orderByDesc('rate_date')
            ->value('rate');

        return $rate ? (float) $rate : 1.0;
    }
}
