<?php
/**
 * Created by PhpStorm.
 * User: tatu
 * Date: 6/22/20
 * Time: 9:58 PM
 */

namespace App\Lib;


use GuzzleHttp\Client as Guzzle;
use GuzzleHttp\Cookie\CookieJar;
use Psr\Http\Message\StreamInterface;
use GuzzleHttp\Exception\ClientException;


class Backend
{
    protected $url;

    public function __construct()
    {
        $this->url = config('stag.backendUrl');
    }


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

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


    /**
     * @param string $url
     * @param string $method HTTP request method eg POST, GET.
     * @param array $options
     * @return StreamInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function sendRequest(string $url, string $method,  array $options = []) : StreamInterface
    {
        $url = sprintf('%s/%s', rtrim($this->url, '/'), trim($url, '/'));

        $response = null;
        $client = new Guzzle();

        try {
            $response = $client->request($method, $url, $options);
        }
        catch (ClientException $clientException)  {
            $response = $clientException->getResponse();
        }

        return $response->getBody();
    }
}
