<?php

namespace App\Helpers;

use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;

class RatesHelper
{
    public function getRates(){
        return $this->_retrieveRates();
    }

    private function _retrieveRates() {
        $apiUrl = 'https://www.live-rates.com/rates?key=' . env('LIVE_RATES');

        $client = new \GuzzleHttp\Client();
        try {
            $response = $client->request('GET', $apiUrl);
            if ($response->getStatusCode() == '200') {
                $stockPricesArray = json_decode($response->getBody(), true);
                //$stockPrices = Storage::get('tmp/rates.json');
                //$stockPricesArray = json_decode($stockPrices, true);
                $rates = [];
                if(isset($stockPricesArray[0]['currency'])) {
                    foreach ($stockPricesArray as $stockPrice) {
                        $rates[$stockPrice['currency']] = $stockPrice;
                    }
                }
                
            }
            
            if(auth()->check()) {
                
                $apiUrl1 = 'https://api.coinlore.net/api/tickers/';
                
                $client1 = new \GuzzleHttp\Client();
                $response1 = $client1->request('GET', $apiUrl1);
                if ($response1->getStatusCode() == '200') {
                    $stockPricesArray1 = json_decode($response1->getBody(), true);
                    foreach ($stockPricesArray1['data'] as $key) {
                        $rates[$key['nameid']]['rate'] = $key['price_usd'];
                    }
                }
            }
            
            return $rates;

        } catch (Exception $e) {
            //
        }
        
        return false;
    }
}