<?php
namespace Prodigy\Includes\Content;

use Prodigy\admin\Prodigy_Admin_Setup_Wizard;
use Prodigy\Includes\Helpers\Prodigy_Cookies;
use Prodigy\Includes\Prodigy_User;
use WP_Error;

defined( 'ABSPATH' ) || exit;

/**
 * Class Prodigy_Api_Client
 */
class Prodigy_Api_Client {

	public const API_PROTOCOL                  = PRODIGY_PROTOCOL_DOMAIN;
	public const PRODUCTS_URL                  = '/api/v1/plugin/products';
	public const CATALOG_URL                   = '/api/v1/plugin/catalog/filters';
	public const API_CONNECTION_URL            = '/api/v1/plugin/connection';
	public const CATEGORY_URL                  = '/api/v1/plugin/categories';
	public const ORDER_URL                     = '/api/v1/plugin/orders/';
	public const CART_URL                      = '/api/v1/plugin/cart';
	public const LINE_ITEM_URL                 = '/api/v1/plugin/cart/line_items/';
	public const  SEND_RATING_URL              = '/api/v1/plugin/products/:product_id/rating';
	public const SYNC_CONTENT_URL              = '/api/v1/plugin/synchronization_processes';
	public const SYNC_DEMO_URL                 = '/api/v1/plugin/demo_contents';
	public const RELATED_PRODUCTS_URL          = '/api/v1/plugin/products/related_products';
	public const USER_SESSION_TOKEN_URL        = '/api/v1/plugin/paired_session_tokens';
	public const HS_CUSTOMER_LOGIN_URL         = '/customer/login';
	public const HS_CUSTOMER_MAIN_INFO_URL     = '/api/v1/customer/main_information';
	public const HS_SETTINGS_URL               = '/api/v1/plugin/settings';
	public const HS_LOGOUT_URL                 = '/api/v1/plugin/session';
	public const HS_BRANDS_URL                 = '/api/v1/plugin/brands';
	public const PRODUCTS_ADMIN_URL            = '/api/v1/plugin/admin/products';
	public const PRODUCTS_PROPERTIES_ADMIN_URL = '/api/v1/plugin/admin/products/properties';
	public const CATEGORY_ADMIN_URL            = '/api/v1/plugin/admin/categories';
	public const CATALOG_ADMIN_URL             = '/api/v1/plugin/admin/catalog';
	public const ORDER_ADMIN_URL               = '/api/v1/plugin/admin/orders/';
	public const RELATED_PRODUCTS_ADMIN_URL    = '/api/v1/plugin/admin/products/related_products';
	public const PRODUCT_BRANDS_PREFIX         = '%s%s%s/%d/brands';
	public const HS_USER_IMPERSONATION_URL     = '/api/v1/account/impersonations';
	public const HS_REDEMPTION_RULES_URL       = '/api/v1/plugin/redemption_code';

	/** @var array $request */
	private array $request;

	/**
	 * @param array $headers
	 * @param bool  $blocking
	 * @param int   $timeout
	 * @param bool  $sslverify
	 */
	public function __construct(
		array $headers = array( 'Content-Type' => 'application/json' ),
		bool $blocking = true,
		int $timeout = 10,
		bool $sslverify = false
	) {
		$access_token = Prodigy_Cookies::get_cookie( Prodigy_User::ACCESS_COOKIE_NAME );
		if ( ! empty( $access_token ) ) {
			$headers['x-Authorization-Customer'] = $access_token;
		}

		$this->request = compact( 'headers', 'blocking', 'timeout', 'sslverify' );
	}

	/**
	 * @param string $api_url
	 * @param array  $params
	 * @param string $headers
	 *
	 * @return array|WP_Error
	 */
	public function post_remote_content( string $api_url, array $params = array(), string $headers = '' ) {
		$this->request['body']                 = wp_json_encode( $params );
		$this->request['method']               = 'POST';
		$request                               = ! empty( $headers ) ? $headers : $this->request;
		$request['headers']['x-Authorization'] = get_option( Prodigy_Admin_Setup_Wizard::OPTION_STORE_KEY );
		return wp_remote_post( $api_url, $request );
	}

	/**
	 * @param string $api_url
	 * @param array  $params
	 * @param string $headers
	 *
	 * @return array|WP_Error
	 */
	public function patch_remote_content( string $api_url, array $params = array(), string $headers = '' ) {
		$this->request['method']               = 'PATCH';
		$this->request['body']                 = wp_json_encode( $params );
		$request                               = ! empty( $headers ) ? $headers : $this->request;
		$request['headers']['x-Authorization'] = get_option( Prodigy_Admin_Setup_Wizard::OPTION_STORE_KEY );
		return wp_remote_request( $api_url, $request );
	}

	/**
	 * @param string $api_url
	 * @param array  $headers
	 *
	 * @return array|WP_Error
	 */
	public function delete_remote_content( string $api_url, array $headers = array() ) {
		$this->request['method'] = 'DELETE';

		if ( is_array( $headers ) ) {
			$this->request['headers'] += $headers;
		}

		$payload = array(
			'wp_user_id' => get_current_user_id(),
			'ts'         => time(),
			'request_id' => wp_generate_uuid4(),
		);

		$payload['trace_string'] = wp_json_encode(
			debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 8 )
		);

		$this->request['body'] = wp_json_encode( $payload );

		$this->request['headers']['x-Authorization'] = get_option( Prodigy_Admin_Setup_Wizard::OPTION_STORE_KEY );

		return wp_remote_request( $api_url, $this->request );
	}

	/**
	 * @param   string $api_url
	 * @param   array  $params
	 * @param   string $headers
	 *
	 * @return array|\WP_Error
	 */
	public function put_remote_content( string $api_url, array $params = array(), string $headers = '' ) {
		$this->request['method']               = 'PUT';
		$this->request['body']                 = wp_json_encode( $params );
		$request                               = ! empty( $headers ) ? $headers : $this->request;
		$request['headers']['x-Authorization'] = get_option( Prodigy_Admin_Setup_Wizard::OPTION_STORE_KEY );
		return wp_remote_request( $api_url, $request );
	}

	/**
	 * @param   string      $api_url
	 * @param   string|null $headers
	 *
	 * @return array|WP_Error
	 */
	public function get_remote_content( string $api_url, ?string $headers = null ) {
		$request                               = $headers ?? array( 'headers' => $this->request['headers'] );
		$request['headers']['x-Authorization'] = get_option( Prodigy_Admin_Setup_Wizard::OPTION_STORE_KEY );
		return wp_remote_get( $api_url, $request );
	}
}
