<?php

namespace App\Models;

use App\Http\Helpers\CurrencyConversion;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class exchangeRate extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'rate',
    ];

    public static function getCurrentRatesInUSD()
    {
        $rates = CurrencyConversion::getCurrentRatesInUSD();

        foreach ($rates as $key => $value) {
            $rate = self::where('name', $key)->first();
            if($rate) {
                $rate->rate = $value;
                $rate->save();
            } else {
                self::create([
                    'name' => $key,
                    'rate' => $value,
                ]);
            }
        }

        return true;
        
    }
    public static function formattedRates()
    {
        $rates = self::all();
        $formattedRates = [];
        foreach ($rates as $rate) {
            $formattedRates[$rate->name] = $rate->rate;
        }
        return $formattedRates;
    }
}
