<?php

class Inoby_Http {
  private $base_url;
  private $default_headers = [
    "Accept" => "application/json",
    "Content-Type" => "application/json",
  ];
  public $raw_response = null;

  public function __construct($base_url, $headers = []) {
    $this->base_url = $base_url;
    $this->set_default_headers($headers);
  }

  public function post($api_path, $body = null, $headers = []) {
    $url = $this->get_api_url($api_path);
    $headers = wp_parse_args($headers, $this->default_headers);

    $response = wp_remote_post($url, [
      "headers" => $headers,
      "body" => json_encode($body),
    ]);

    $this->raw_response = $response;
    if (is_wp_error($response)) {
      return false;
    }

    return json_decode(wp_remote_retrieve_body($response));
  }

  public function get($api_path, $headers = []) {
    $url = $this->get_api_url($api_path);
    $headers = wp_parse_args($headers, $this->default_headers);

    $response = wp_remote_get($url, [
      "headers" => $headers,
    ]);

    $this->raw_response = $response;
    if (is_wp_error($response)) {
      return false;
    }

    return json_decode(wp_remote_retrieve_body($response));
  }

  public function set_default_headers($headers) {
    $this->default_headers = wp_parse_args($headers, $this->default_headers);
  }

  public function get_api_url($api_path) {
    return rtrim($this->base_url, "/") . "/" . ltrim($api_path, "/");
  }
}
