<?php

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

class AuthServiceClient
{

    public function __construct()
    { }

    private static function getToken($name)
    {
        $token = get_cookie($name);
        if (empty($token)) {
            AuthServiceClient::setToken();
        }
        $token = get_cookie($name);
        return $token;
    }

    protected function getTokenFromCookie()
    {
        return AuthServiceClient::getToken('bs_token');
    }

    private static function setCookie($cookie)
    {
        return set_cookie($cookie);
    }

    public static function setToken()
    {
        $client = new Client();
        try {
            $response = $client->request('GET', API_GATEWAY_URI . '/oauth/token', [
                'query' => [
                    'client_id' => 'F8Nbz9gGUvLgdn8T',
                    'grant_type' => 'client_credentials',
                    'client_secret' => 'Fesmx7hHCCMx7Cby7FhV2fAtf2NYEFzP5fCKuwEEdpf8hpnsnnQn9qYhNHt6SsDD',
                    'code' => 'a9c6380a-9e34-467f-a1ae-514bb51a7724',
                    'scope' => 'api'
                ],
                'defaults' => ['verify' => false]
            ]);
            $body = $response->getBody();
            self::setCookieToken(json_decode($body));
        } catch (\GuzzleHttp\Exception\ConnectException $e) {
            error_log('Connection errir....');
            error_log($e->getMessage()); exit();
        } catch (ClientException $e) {
            error_log($e->getMessage());
            redirect('/sign/logout');
        }
    }

    private static function setCookieToken($token)
    {
        self::setCookie([
            'name'   => 'token',
            'value'  => $token->access_token,
            'expire' => '86500',
            'domain' => $_SERVER['SERVER_NAME'],
            'path'   => '/',
            'prefix' => 'bs_'
        ]);
        self::setCookie([
            'name'   => 'token_expires',
            'value'  => $token->expires_in,
            'expire' => '86500',
            'domain' => $_SERVER['SERVER_NAME'],
            'path'   => '/',
            'prefix' => 'bs_'
        ]);
    }
}
