<?php
/**
 * Masteriyo zapier api endpoint handler.
 *
 * This handles api API related functionality in Masteriyo.
 *
 * @package Masteriyo
 * @since   2.12.0
 */

namespace Masteriyo\Addons\Zapier;

defined( 'ABSPATH' ) || exit;

/**
 * Masteriyo API class.
 */
class ZapierApi {

	/**
	 * Holds instance of this class.
	 *
	 * @var ZapierApi
	 */
	protected static $instance = null;

	/**
	 * Get single instance of this class.
	 *
	 * @return ZapierApi
	 */
	public static function instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Init the API by setting up action and filter hooks.
	 *
	 * @since 2.12.0
	 */
	public function init() {
		add_filter( 'query_vars', array( $this, 'add_query_vars' ), 0 );
		add_action( 'parse_request', array( $this, 'handle_api_requests' ), 0 );
	}

	/**
	 * Masteriyo API for payment gateway IPNs, etc.
	 *
	 * @since 2.12.0
	 */
	public function add_endpoint() {
		add_rewrite_endpoint( 'masteriyo-zapier-api', EP_ROOT );
	}

	public function add_query_vars( $vars ) {
		$vars[] = 'masteriyo-zapier';
		return $vars;
	}

	/**
	 * API request - Trigger any API requests.
	 *
	 * @since 2.12.0
	 */
	public function handle_api_requests() {
		global $wp;
		if ( isset( $_GET['masteriyo-zapier'] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$wp->query_vars['masteriyo-zapier'] = true;
		}
		if ( isset( $wp->query_vars['masteriyo-zapier'] ) && $wp->query_vars['masteriyo-zapier'] ) {
			$request_data = masteriyo_zapier_retrieve_request_data();
			$authenticate = $this->authenticate( $request_data );

			if ( is_wp_error( $authenticate ) ) {
				masteriyo_zapier_send_message( $authenticate->get_error_message(), 401 );
			}

			$action = masteriyo_array_get( $request_data, 'action' );
			if ( $action ) {
				$handle = 'masteriyo_zapier_action_' . $action;
				if ( ! has_action( $handle ) ) {
					masteriyo_zapier_send_message( __( 'Invalid action', 'learning-management-system' ), 400 );
				}
				do_action( $handle, $request_data );
			}
			masteriyo_zapier_send_message( __( 'Success', 'learning-management-system' ), 200 );
		}
	}

	/**
	 * Authenticate zapier request
	 *
	 * @param array $request_data Request data.
	 * @return true|\WP_Error
	 */
	protected function authenticate( $request_data ) {
		$api_key = masteriyo_array_get( $request_data, 'api_key' );

		if ( ! $api_key ) {
			return new \WP_Error( 'api_key_missing', __( 'API key is missing', 'learning-management-system' ) );
		}

		if ( ! masteriyo_zapier_verify_api_hash( $api_key ) ) {
			return new \WP_Error( 'invalid_api_key', __( 'Invalid API key', 'learning-management-system' ) );
		}

		return true;
	}
}
