<?php

namespace App\Services;

use GuzzleHttp\Client;

class CoinMarketCapService
{
    protected $client;
    protected $apiKey;

    public function __construct()
    {
        $this->client = new Client();
        $this->apiKey = '58175107-67b6-43e9-84b5-f0c59f9ff3e2'; // Replace with your CoinMarketCap API key
    }

    public function getCoinPrice($symbol)
    {
        try {
            $response = $this->client->request('GET', "https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest", [
                'query' => [
                    'symbol' => $symbol,
                    'convert' => 'USD'
                ],
                'headers' => [
                    'X-CMC_PRO_API_KEY' => $this->apiKey
                ]
            ]);

            $data = json_decode($response->getBody(), true);
            return $data['data'][$symbol]['quote']['USD']['price'] ?? null;
        } catch (\Exception $e) {
            \Log::error('Error fetching coin price: ' . $e->getMessage());
            return null;
        }
    }
}
