<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Currency;
use GuzzleHttp\Client;
use App\CurrencyRate;

class UpdateCurrencyRates extends Command
{
    protected $signature = 'currency-rates:update';
    protected $description = 'Update currency rates daily at 10:00';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $client = new Client();
        $response = $client->get('https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5');
        $rates = json_decode($response->getBody()->getContents(), true);

        foreach ($rates as $rate) {
            $currency = Currency::where('code', $rate['ccy'])->first();
            if ($currency) {
                CurrencyRate::updateOrCreate([
                    'currency_from_id' => $currency->id,
                    'currency_to_id' => Currency::where('code', $rate['base_ccy'])->first()->id,
                ], [
                    'rate' => $rate['buy'],
                ]);
            }
        }

        $this->info('Currency rates updated successfully.');
    }
}
