<?php 

namespace Hogash\Kallyas;

use Hogash\Kallyas\License;

if (! defined('ABSPATH')) {
	return;
}

class ServerAPI {
	const API_VERSION = '3';

	/**
	 * The static API URL
	 */
	private $static_api_url;

	/**
	 * The API URL
	 */
	private $api_url;

	/**
	 * Constructor
	 * 
	 * @param string $static_api_url The static API URL
	 * @param string $api_url The API URL
	 */
	public function __construct($static_api_url, $api_url) {
		$this->static_api_url = $static_api_url;
		$this->api_url = $api_url;
	}

	/** The method will return a URL based on api base URL
	 * 
	 * @var string $path The path to the file
	 * @return string The full URL path
	 */
	public function get_static_api_url($path = '') {
		return $this->static_api_url . $path;
	}

	/** The method will return a URL based on api base URL
	 * 
	 * @var string $path The path to the endpoint
	 * @return string The full URL path
	 */
	public function get_private_api_url($path = '') {
		return $this->api_url . $path;
	}

	/**
	 * Will return the update version
	 * 
	 * @return array|null
	 */
	public function get_update_version_info() {
		$version_info_request = wp_remote_get( $this->get_static_api_url('version.json') );

		if (is_wp_error($version_info_request)) {
			return null;
		}

		$response = wp_remote_retrieve_body( $version_info_request );
		$version_info = json_decode($response, true);

		if (null === $version_info) {
			return null;
		}

		return $version_info;
	}

	/**
	 * Will return the download URL
	 * 
	 * @return string
	 */
	public function get_download_url() {
		$response = $this->request('get_theme_download_url');
		
		if (is_wp_error($response) || ! isset($response['data']) ) {
			return '';

		}

		return $response['data'];
	}


	/**
	 * Will make a request to the server
	 * 
	 * @param string $endpoint The endpoint to request
	 * @param array $body_args The body arguments
	 * @return array|WP_Error
	 */
	public function request($endpoint, $body_args = array()) {
		// Server URL
		$server_url = $this->get_private_api_url();
		$body_args['action'] = $endpoint;
		$license = isset($body_args['license_key']) ? $body_args['license_key'] : License::get_license_key();

		// Check if the license was provided
		if ( ! $license ) {
			return new \WP_Error('no_license', 'No license key provided');
		}

		// Pass additional data
		$body_args['api_key'] = $license;
		$body_args['version'] = Kallyas::get_instance()->get_version();
		$body_args['api_version'] = self::API_VERSION;
		$body_args['theme'] = Kallyas::get_instance()->get_theme_id();
		$body_args['site_url'] = esc_url( network_home_url( '/' ) );

		$request = wp_remote_post( $server_url, [
			'body' => $body_args,
		] );

		if ( is_wp_error( $request ) ) {
			return $request;
		}

		$response = wp_remote_retrieve_body( $request );

		return json_decode( $response, true );
	}
}