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

namespace App\Lib;


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


class Backend
{
    protected $url;

    public function __construct()
    {
        $this->url = env('BACKEND_URL', "http://localhost:8080/api");
    }


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

    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();
    }
}
