<?php
/**
 * MainWP Jetpack Protect REST API
 *
 * This class handles the REST API
 *
 * @package MainWP/Extensions
 */

namespace MainWP\Extensions\JetpackProtect;

/**
 * Class Rest_Api
 *
 * @package MainWP/Extensions
 */
class Rest_Api {

	/**
	 * Protected variable to hold the API version.
	 *
	 * @var string API version
	 */
	protected $api_version = '1';

	/**
	 * Protected static variable to hold the single instance of the class.
	 *
	 * @var mixed Default null
	 */
	private static $instance = null;

	/**
	 * Method instance()
	 *
	 * Create public static instance.
	 *
	 * @static
	 * @return self::$instance
	 */
	public static function instance() {
		if ( null == self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Method init()
	 *
	 * Adds an action to create the rest API endpoints if activated in the plugin settings.
	 */
	public function init() {
		add_action( 'init', array( &$this, 'init_rest_api' ) );
	}

	/**
	 * Method init_rest_api()
	 *
	 * Adds an action to create the rest API endpoints if activated in the plugin settings.
	 */
	public function init_rest_api() {
		if ( has_filter( 'mainwp_rest_api_enabled' ) ) {
			$activated = apply_filters( 'mainwp_rest_api_enabled', false );
		} else {
			$activated = true; // to compatible.
		}
		// only activate the api if enabled in the dashboard plugin.
		if ( $activated ) {
			// init APIs.
			add_action( 'rest_api_init', array( &$this, 'mainwp_register_routes' ) );
		}
	}

	/**
	 * Method mainwp_rest_api_init()
	 *
	 * Creates the necessary endpoints for the api.
	 * Note, for a request to be successful the URL query parameters consumer_key and consumer_secret need to be set and correct.
	 */
	public function mainwp_register_routes() {
		// Create an array which holds all the endpoints. Method can be GET, POST, PUT, DELETE.
		$endpoints = array(
			array(
				'route'    => 'jetpack-protect',
				'method'   => 'GET',
				'callback' => 'result',
			),
		);
		// loop through the endpoints.
		foreach ( $endpoints as $endpoint ) {
			$function_name = str_replace( '-', '_', $endpoint['callback'] );
			register_rest_route(
				'mainwp/v' . $this->api_version,
				'/' . $endpoint['route'] . '/' . $endpoint['callback'],
				array(
					'methods'             => $endpoint['method'],
					'callback'            => array( &$this, 'protect_rest_api_' . $function_name . '_callback' ),
					'permission_callback' => '__return_true',
				)
			);
		}
	}

	/**
	 * Method mainwp_authentication_error()
	 *
	 * Common error message when consumer key and secret are wrong.
	 *
	 * @return array $response Array with an error message explaining that the credentials are wrong.
	 */
	public function mainwp_authentication_error() {

		$data = array( 'ERROR' => esc_html__( 'Incorrect or missing consumer key and/or secret. If the issue persists please reset your authentication details from the MainWP > Settings > REST API page, on your MainWP Dashboard site.', 'mainwp-jetpack-protect-extension' ) );

		$response = new \WP_REST_Response( $data );
		$response->set_status( 401 );

		return $response;
	}

	/**
	 * Method mainwp_missing_data_error()
	 *
	 * Common error message when data is missing from the request.
	 *
	 * @return array $response Array with an error message explaining details are missing.
	 */
	public function mainwp_missing_data_error() {

		$data = array( 'ERROR' => esc_html__( 'Required parameter is missing.', 'mainwp-jetpack-protect-extension' ) );

		$response = new \WP_REST_Response( $data );
		$response->set_status( 400 );

		return $response;
	}

	/**
	 * Method mainwp_invalid_data_error()
	 *
	 * Common error message when data in request is ivalid.
	 *
	 * @return array $response Array with an error message explaining details are missing.
	 */
	public function mainwp_invalid_data_error() {

		$data = array( 'ERROR' => esc_html__( 'Required parameter data is is not valid.', 'mainwp-jetpack-protect-extension' ) );

		$response = new \WP_REST_Response( $data );
		$response->set_status( 400 );

		return $response;
	}

	/**
	 * Method protect_rest_api_result_callback()
	 *
	 * Callback function for managing the response to API requests made for the endpoint: scan
	 * Can be accessed via a request like: https://yourdomain.com/wp-json/mainwp/v1/jetpack-protect/result
	 * API Method: GET
	 *
	 * @param array $request The request made in the API call which includes all parameters.
	 *
	 * @return object $response An object that contains the return data and status of the API request.
	 */
	public function protect_rest_api_result_callback( $request ) {
		// first validate the request.
		if ( apply_filters( 'mainwp_rest_api_validate', false, $request ) ) {
			$data  = array();
			$error = '';
			// get parameters.
			if ( isset( $request['site_id'] ) && null != $request['site_id'] ) {
				$website_id = $request['site_id'];
				/**
				 * Extension Activator object.
				 *
				 * @global object
				 */
				global $mainJetpackProtectExtensionActivator;
				$website = apply_filters( 'mainwp_getsites', $mainJetpackProtectExtensionActivator->get_child_file(), $mainJetpackProtectExtensionActivator->get_child_key(), $website_id );
				if ( $website && is_array( $website ) ) {
					$website = current( $website );
				}

				$error               = '';
				$last_protect_status = array();

				if ( empty( $website ) ) {
					$error = __( 'Site not found.', 'mainwp-jetpack-protect-extension' );
				} else {
					$last_protect_status = MainWP_Jetpack_Protect_DB::get_instance()->get_protect_status_by( 'wpid', $website_id );
					if ( empty( $last_protect_status ) ) {
						$error = esc_html__( 'Jetpack Protect result empty.', 'mainwp-jetpack-protect-extension' );
					} else {
						$data[ $last_protect_status->wpid ] = array(
							'site_id'   => $last_protect_status->wpid,
							'scan_time' => $last_protect_status->scan_time,
							'data'      => ( '' != $last_protect_status->status_data ) ? json_decode( $last_protect_status->status_data, true ) : array(),
						);
					}
				}
			} else {
				$last_statuses = MainWP_Jetpack_Protect_DB::get_instance()->get_protect_status_last_sites();
				if ( ! empty( $last_statuses ) ) {
					foreach ( $last_statuses as $status ) {
						$data[ $status->wpid ] = array(
							'site_id'   => $status->wpid,
							'scan_time' => $status->scan_time,
							'data'      => ( '' != $status->status_data ) ? json_decode( $status->status_data, true ) : array(),
						);

					}
				} else {
					$error = esc_html__( 'Jetpack Protect result empty.', 'mainwp-jetpack-protect-extension' );
				}
			}

			$result = array();
			if ( empty( $data ) ) {
				$result['ERROR'] = $error;
			} else {
				$result['data'] = $data;
			}

			$response = new \WP_REST_Response( $result );
			$response->set_status( 200 );

		} else {
			// throw common error.
			$response = $this->mainwp_authentication_error();
		}
		return $response;
	}
}

// End of class.
