<?php

namespace App\Services;
use App\Traits\GlobalApiResponse;
use GuzzleHttp\Client;
use Exception;
class ServiceClient
{
    use GlobalApiResponse;
    private $client;
    private $baseUrl;
    private $headers;
    /**
     * Create a new class instance.
     */
    public function __construct($baseUrl = '', $headers = [])
    {
        $this->client = new Client();
        $this->baseUrl = $baseUrl;
        $this->headers = array_merge(
            [
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ],
            $headers
        );
    }

    public function makeRequest($url, $method = 'GET', $body = null, $headers = [], $timeout = 14400){
        try {

            $headers = array_merge($this->headers, $headers);

            $options = [
                'headers' => $headers,
                'timeout' => $timeout,
                'connect_timeout' => 60
            ];

            if ($body) {
                $options['json'] = $body; // Guzzle akan mengonversi array ke JSON
            }

            $response = $this->client->request($method, $this->baseUrl . $url, $options);

            $resultResponse = json_decode($response->getBody(), true);
            return $this->resSuccess($resultResponse);
        } catch (Exception $e) {
            return $this->resError($e->getMessage());
        }
    }

    // Fungsi untuk melakukan permintaan GET
    public function get($url, $headers = [])
    {
        return $this->makeRequest($url, 'GET', null, $headers);
    }

    // Fungsi untuk melakukan permintaan POST
    public function post($url, $body, $headers = [])
    {
        return $this->makeRequest($url, 'POST', $body, $headers);
    }

    // Fungsi untuk melakukan permintaan PUT
    public function put($url, $body, $headers = [])
    {
        return $this->makeRequest($url, 'PUT', $body, $headers);
    }

    // Fungsi untuk melakukan permintaan DELETE
    public function delete($url, $headers = [])
    {
        return $this->makeRequest($url, 'DELETE', null, $headers);
    }
}
