<?php

namespace WPDesk\FakturyKSEF\Api;

use WPDeskKSEFVendor\Psr\Http\Message\ResponseInterface;

/**
 * Class Response
 *
 * @package WPDesk\FakturyKSEFWooCommerce\Api
 */
class Response {

	private ResponseInterface $api_response;

	public function __construct( ResponseInterface $response ) {
		$this->api_response = $response;
	}

	public function get_status_code(): int {
		return (int) $this->api_response->getStatusCode();
	}

	public function get_body(): array {

		$contents = $this->api_response->getBody()->getContents();
		if ( $this->is_json() ) {
			$result = json_decode( $contents );
			if ( isset( $result->data ) ) {
				return (array) $result->data;
			}

			return (array) $result;
		}

		return [];
	}

	private function get_content_type(): string {
		$content_type          = $this->api_response->getHeaderLine( 'Content-Type' );
		$content_type_as_array = explode( ';', $content_type );
		if ( ! empty( $content_type_as_array[0] ) ) {
			return trim( $content_type_as_array[0] );
		}

		return $content_type;
	}

	public function is_json(): bool {
		return $this->get_content_type() === 'application/json';
	}

	public function is_error(): bool {
		return ( $this->get_status_code() < 200 || $this->get_status_code() >= 300 );
	}
}
