<?php

namespace App\Http\Controllers;

use App\Models\Setting;
use App\Models\CoinDetail;
use Illuminate\Support\Facades\Http;

class CoinDetailsController extends Controller {
    public $settings;
    public function updateCoinDetails(CoinDetail $detail, array $data) {
        $detail->update([
            'price' => $detail->coin->symbol =='USDT' ? 1 : $data['PRICE'],
            'image' => $data['IMAGEURL'],
            'change_24h' => $data['CHANGE24HOUR'],
            'change_pct_24h' => $data['CHANGEPCT24HOUR'],
            'high_24h' => $data['HIGH24HOUR'],
            'low_24h' => $data['LOW24HOUR'],
            'others' => $data,
            'last_updated' => now(),
        ]);
    }

    public function getData($symbols, $currency = null) {
        $currency = $currency ?? setting('currency_full');
        
        $response = Http::get("https://min-api.cryptocompare.com/data/pricemultifull", [
            'fsyms' => $symbols,
            'tsyms' => $currency,
            'api_key' => setting('cryptocompare_api_key'),
        ]);
        $response = $response->json('RAW');
        return $response;
    }

    public function getDetails() {
        $response = $this->getData(symbols());
        return $response;
    }


    public function getDetailSingle($symbol) {
        $response = $this->getData($symbol);
        return $response[$symbol][setting('currency_full')];
    }

    public function updateDetailSingle(CoinDetail $coinDetail) {
        $coinData = $this->getDetailSingle($coinDetail->coin->symbol);

        $this->updateCoinDetails($coinDetail, $coinData);
    }

    public function updateAllDetails() {
        $coinData = $this->getDetails();
        $coinDetails = CoinDetail::all();

        foreach ($coinDetails as $detail) {
            $data = $coinData[$detail->coin->symbol][setting('currency_full')];
            $this->updateCoinDetails($detail, $data);
        }
    }
}
