<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Yajny\Member\Models\Currencies;
use Yajny\Member\Models\CurrencyRate;

class CurrencyExchangeRateCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'currency:exchange';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Get currency exchange rates';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $startTime = microtime(true);
        $currencies = Currencies::all();
        $currency_codes = $currencies->pluck('iso_code')->toArray();
        $client = new Client();
        $response = $client->request(
            'GET',
            'https://v6.exchangerate-api.com/v6/7018278ff29b09e3d1843f7d/latest/USD',
            [
                'query' => ['base' => 'USD', 'symbols' => implode(',', $currency_codes)],
            ]
        );
        $currencyRates = json_decode($response->getBody());
        foreach ($currencyRates->conversion_rates as $code => $rate) {
            if (in_array($code,['USD','EGP','SAR','AED','KWD','TRY','EUR','MYR','UAH']) ){
                $currency = $currencies->where('iso_code', $code)->first();
                $currencyRate = new CurrencyRate();
                $currencyRate->currency_id = $currency->id;
                $currencyRate->currency_code = $code;
                $currencyRate->start_date = Carbon::now();
                $currencyRate->conversion_rate = $currency->conversion_rate = $rate;
                $currencyRate->save();
                $currency->save();
            }

        }
        $endTime = microtime(true);
        $executionTime = $endTime - $startTime;
        Log::channel("separated_file")->info("The Script".class_basename($this)."   Took : $executionTime");
    }
}
