<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use App\Models\ExchangeRate;
use App\Models\Setting;
use Carbon\Carbon;

class ExchangeRateService
{


    public static function addRecord(): bool
    {
        $systemCurrency = Setting::getValue('system_currency');
        $websiteCurrencyTypes = Setting::getValue('website_currency_types');

        $url = 'https://api.exchangerate-api.com/v4/latest/' . $systemCurrency;

        $response = Http::withoutVerifying()->get($url);

        if (!$response->successful()) {
            return false;
        }

        $data = $response->json();

        $isHaveSys = $data['rates'][$systemCurrency] ?? null;

        if (!$isHaveSys) {
            return false;
        }

        $rates = [];

        foreach ($websiteCurrencyTypes as $currency) {
            $code = $currency['code'];

            if (!isset($data['rates'][$code])) {
                continue;
            }

            $rate = $data['rates'][$code] / $isHaveSys;
            $rates[$code] = round($rate, 6);
        }

        $timestamp = $response['time_last_updated'];
        $lastUpdated = Carbon::createFromTimestamp($timestamp)->setTimezone('Asia/Colombo');


        // $rates[$systemCurrency] = 1;

        ExchangeRate::create([
            'base_currency' => $systemCurrency,
            'rates' => $rates,
            'updated_by' => 'system',
            'recorded_at' => now(),
            'last_updated_at' => $lastUpdated
        ]);

        return true;
    }
}
