<?php

namespace Miladmodaresi\Taamito\Base;


class Api
{
    protected $baseApi = "https://taamito.com";
    protected $centeralApi = "taamito.com";
    protected $prefix  = "/api/v1/";
    protected $baseHeaders  = ["timeout" => 45, 'headers' => (['Accept' => 'application/json'])];

    public function setAuth($token)
    {
        $this->baseHeaders['headers']['Authorization'] = 'Bearer ' . $token;
        return $this;
    }
    public function setBaseApi($url)
    {
        $this->baseApi = $url;
        return $this;
    }
    public function setSubDomain($url)
    {
        $this->baseApi = 'https://' . $url . '.' . $this->centeralApi;
        return $this;
    }
    public function makeRequest($url, $method, $params = [], $headers = [])
    {
        $this->baseHeaders['headers'] =  $this->baseHeaders['headers'] + $headers;
        $response = null;
        if ($method == 'get') {
            $query = '';
            if (count($params))
                $query = '?' . build_query($params);
            $response = wp_remote_get($this->baseApi . $this->prefix . $url . $query, $this->baseHeaders);
        } else {
            $this->baseHeaders['headers']['Content-Type'] = 'application/json';
            $this->baseHeaders['body'] = json_encode($params);
            $response = wp_remote_post($this->baseApi . $this->prefix . $url, $this->baseHeaders);
        }
        \Sentry\captureMessage($this->baseApi . $this->prefix . $url);
        $body     = wp_remote_retrieve_body($response);
        $code     = wp_remote_retrieve_response_code($response);
        $body     = json_decode($body);
        if ($code < 199 || $code >= 300) (new HttpException($body, $code))->abort();
        return $body;
    }

    public function get($url, $params = [], $headers = [])
    {
        return $this->makeRequest($url, 'get', $params, $headers);
    }
    public function post($url, $params = [], $headers = [])
    {
        return $this->makeRequest($url, 'post', $params, $headers);
    }
}
