<?php

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

require_once __DIR__ . '/AuthServiceClient.php';

class RestServiceClient extends AuthServiceClient
{

    public function __construct()
    { }

    protected function request($method, $url, $body)
    {
        $response = null;
        $client  = new Client();
        $headers = [
            'Authorization' => 'Bearer ' . $this->getTokenFromCookie(),
            'Content-Type' => 'application/json'
        ];
        error_log(sprintf("Request headers: %s", json_encode($headers)));
        $request = new Request($method, API_GATEWAY_URI . $url, $headers, json_encode($body));
        try {
            $response = $client->send($request, ['timeout' => 20]);
        } catch (Exception $e) {
            error_log($e->getMessage());
        }

        if (is_null($response) || $response->getStatusCode() != 200) {
            error_log(print_r($response, true));
            redirect('/sign/logout');
        } else if ($response) {
            $body = $response->getBody();
            $json = json_decode($body);
            if($json->code != 200) {
                if($json->code == 406) {
                    self::setToken();
                    redirect(uri_string());
                }else {
                    error_log(print_r($json, true));
                }                
            }            
            return $json;
        }
    }
}
