<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Currency;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class UpdateCryptoPrices extends Command
{
    protected $signature = 'crypto:update';
    protected $description = 'Update cryptocurrency prices from API and store them in the database';

    protected string $userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36';

    public function handle()
    {
        $currencies = Currency::pluck('currency_name')->toArray();

        if (empty($currencies)) {
            $this->info('No currencies found.');
            return;
        }

        $cryptoSymbol = urlencode(implode(',', $currencies));

        $fiatCurrencies = [
            "usd", "aed", "ars", "aud", "bdt", "bhd", "bmd", "brl", "cad", "chf",
            "clp", "cny", "czk", "dkk", "eur", "gbp", "hkd", "huf", "idr", "ils",
            "inr", "jpy", "krw", "kwd", "lkr", "mmk", "mxn", "myr", "ngn", "nok",
            "nzd", "php", "pkr", "pln", "rub", "sar", "sek", "sgd", "thb", "try",
            "twd", "uah", "vef", "vnd", "zar", "xdr", "xag", "xau"
        ];

        $fiatSymbol = implode(',', $fiatCurrencies);

        $response = Http::withHeaders([
            'User-Agent' => $this->userAgent,
            'Accept'     => 'application/json',
        ])->get("https://api.coingecko.com/api/v3/simple/price?ids=$cryptoSymbol&vs_currencies=$fiatSymbol");

        $data = $response->json();

        if (!$data) {
            $this->error('Failed to fetch crypto prices.');
            return;
        }

        foreach ($data as $cryptoName => $prices) {
            $updateRow = ['currency_name' => $cryptoName];
            foreach ($fiatCurrencies as $fiat) {
                $updateRow[$fiat] = $prices[$fiat] ?? null;
            }
            Currency::updateOrCreate(['currency_name' => $cryptoName], $updateRow);
        }

        $this->info('Crypto prices updated successfully.');
    }
}