<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class BetfairService
{
    protected $baseUrl = 'http://172.105.54.97:8085/api/new/';

    public function getCompetitions($sportId = 4)
    {
        $url = $this->baseUrl . "getCompetitions?id=$sportId";
        return $this->fetch($url);
    }

    public function getEvents($sid, $sportId = 4)
    {
        $url = $this->baseUrl . "getEvents?sid=$sid&sportid=$sportId";
        return $this->fetch($url);
    }

    public function getMarketsList($eventId, $sportId = 4)
    {
        $url = $this->baseUrl . "geMarketsList?EventID=$eventId&sportid=$sportId";
        return $this->fetch($url);
    }

    public function getRunners($marketId, $sportId = 4)
    {
        $url = $this->baseUrl . "gerunners?MarketID=$marketId&sportid=$sportId";
        return $this->fetch($url);
    }

    public function getMarketOdds($marketId)
    {
        $url = $this->baseUrl . "GetMarketOdds?market_id=$marketId";
        return $this->fetch($url);
    }

    private function fetch($url)
    {
        try {
            $response = Http::timeout(10)->get($url);
            return $response->successful() ? $response->json() : ['error' => 'Failed to fetch'];
        } catch (\Exception $e) {
            return ['error' => $e->getMessage()];
        }
    }
}
