<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Country;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use DB;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check Exchange Price';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => "https://data.fixer.io/api/latest?access_key=fe3e9dc62837a155bf08a5b34193ef4e",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
        ]);

        $response = curl_exec($curl);
        curl_close($curl);

        // Convert JSON to array
        $data = json_decode($response, true);

        $rates = $data['rates'];

        $countries = Country::all();

        foreach ($countries as $country) {
            $currencyCode = $country->currency; // e.g., "INR", "USD"

            if (isset($rates[$currencyCode])) {
                $country->rates = $rates[$currencyCode];
                $country->save();
            }
        }

        \Log::info("Exchange Price Cronjob Run" . now());
    }
}