<?php
namespace Api\Core;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class HttpClient {
    private $client;

    private function client() {
        if ($this->client === null) {
            $this->client = new Client([
                'timeout' => 10.0,
                'http_errors' => false
            ]);
        }
        return $this->client;
    }

    public function get(string $url, array $headers = []) {
        return $this->request('GET', $url, null, $headers);
    }

    public function post(string $url, $data = null, array $headers = []) {
        return $this->request('POST', $url, $data, $headers);
    }

    private function request(string $method, string $url, $data, array $headers) {
        try {
            $options = ['headers' => $headers];
            if ($data !== null) {
                $options['json'] = $data;
            }

            $resp = $this->client()->request($method, $url, $options);

            $status = $resp->getStatusCode();
            $bodyRaw = $resp->getBody()->getContents();
            $contentType = $resp->getHeaderLine('Content-Type');

            $isJson = stripos($contentType, 'application/json') !== false;

            return [
                'status' => $status,
                'headers' => $resp->getHeaders(),
                'body' => $bodyRaw,
                'is_json' => $isJson,
                'json' => $isJson ? json_decode($bodyRaw, true) : null
            ];

        } catch (RequestException $e) {
            return [
                'status' => 500,
                'headers' => [],
                'body' => null,
                'is_json' => false,
                'json' => null,
                'error' => $e->getMessage()
            ];
        }
    }
}
