<?php


namespace App\Services;


class HotspotService {
    private $baseUrl;
    private $username;
    private $password;

    public function __construct() {
        $this->baseUrl = env('HOTSPOT_BASE_URL');
        $this->username = env('HOTSPOT_USERNAME');
        $this->password = env('HOTSPOT_PASSWORD');
    }

    

    private function executeCurl($url, $method, $data = null, $queryParams = array()) {
        $fullUrl = $this->baseUrl . $url;

        if (!empty($queryParams) && $method === 'GET') {
            $fullUrl .= '?' . http_build_query($queryParams);
        }

        $ch = curl_init($fullUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Ignorer la vérification SSL (utiliser avec précaution)
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, "{$this->username}:{$this->password}");
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        if ($method === 'PUT') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

        $response = curl_exec($ch);

        if(curl_errno($ch)){
            echo 'Erreur cURL : ' . curl_error($ch);
        }

        curl_close($ch);

        return $response;
    }
    public function get($url) {
        return $this->executeCurl($url, 'GET');
    }

    public function post($url, $data) {
        $payload = json_encode($data);
        return $this->executeCurl($url, 'POST', $payload);
    }
  
    public function put($url, $data, $queryParams = array()) {
        $payload = json_encode($data);
        return $this->executeCurl($url, 'PUT', $payload, $queryParams);
    }
}