<?php

namespace App\Service;
use App\Models\Organisation;
use Log;
use Auth;

class CurrencyConvertService
{
    public function getlatestCurrency($currency)
    {
        $user=Auth::user();

        $organisation=Organisation::where('organisation_id',$user['active_organisation'])->first();

        $base_currency=strtoupper($organisation['currency'])??'INR';

        $currency=strtoupper($currency);

        $curl = curl_init();

        Log::info("Curreny Converter");

        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://api.freecurrencyapi.com/v1/latest?apikey=fca_live_1yRc9pgaBesgAiUGUfn6KFOjb5fw98mNnml7F29z&base_currency={$base_currency}&currencies={$currency}",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/json",
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            Log::error("cURL Error #: ". $err);
            Log::info("cURL Error #: ". $err);
            return null;
        } else {
            // Log::info("Get Latest currency : {$response}");
            Log::info($response);

            $sanitized_currency = filter_var($currency, FILTER_SANITIZE_STRING);

            $currency_object=json_decode($response);

            return json_decode($currency_object->data->$sanitized_currency);
        }
    }
}