<?php
/**
 * License controller class.
 *
 * @since 2.5.0
 */

namespace Masteriyo\Pro\Controllers;

use Masteriyo\Pro\License;

defined( 'ABSPATH' ) || exit;

class LicenseControllers {
	/**
	 * Endpoint namespace.
	 *
	 * @since 2.5.0
	 *
	 * @var string
	 */
	protected $namespace = 'masteriyo/pro';

	/**
	 *
	 * Instance of license class.
	 *
	 * @since 2.5.0
	 *
	 * @var Masteriyo\License
	 *
	 */
	public $license;

	/**
	 * Constructor
	 *
	 * @since 2.5.0
	 *
	 * @param \Masteriyo\Pro\License $license
	 */
	public function __construct( License $license ) {
		$this->license = $license;
	}

	/**
	 * Add REST API routes.
	 *
	 * @since 2.5.0
	 *
	 * @return void
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/activate',
			array(
				array(
					'methods'             => \WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_activate_information' ),
					'permission_callback' => array( $this, 'activate_permission_check' ),
				),
				array(
					'methods'             => \WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'activate' ),
					'permission_callback' => array( $this, 'activate_permission_check' ),
					'args'                => array(
						'key' => array(
							'default'     => '',
							'description' => __( 'License key.', 'learning-management-system' ),
							'type'        => 'string',
							'required'    => true,
						),
					),
				),
			)
		);

		register_rest_route(
			'masteriyo/pro',
			'/deactivate',
			array(
				array(
					'methods'             => \WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'deactivate' ),
					'permission_callback' => array( $this, 'deactivate_permission_check' ),
				),
			)
		);
	}


	/*
	|--------------------------------------------------------------------------
	| Permission check
	|--------------------------------------------------------------------------
	*/

	/**
	 * Deactivate license permission check.
	 *
	 * @since 2.5.0
	 *
	 * @return boolean
	 */
	public function deactivate_permission_check() {
		return is_super_admin() || current_user_can( 'manage_masteriyo_settings' );
	}

	/**
	 * Save license key permission check.
	 *
	 * @since 2.5.0
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 *
	 * @return boolean
	 */
	public function activate_permission_check( $request ) {
		return is_super_admin() || current_user_can( 'manage_masteriyo_settings' );
	}


	/**
	 * Deactivate license key.
	 *
	 * @since 2.5.0
	 *
	 * @since 2.0.1 Added $request parameter.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 *
	 * @return WP_Rest_Response
	 */
	public function deactivate( $request ) {
		$license_key = $this->license->get_license_key();
		$instance_id = $this->license->get_instance_id();

		$result = masteriyo_pro_deactivate_license( $license_key, $instance_id );

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

		$this->license->set_activation_data( null );
		$this->license->set_license_key( '' );

		return new \WP_REST_Response(
			array(
				'license_key' => $this->license->get_license_key(),
				'status'      => $this->license->get_license_status(),
				'message'     => esc_html__( 'Deactivated successfully.', 'learning-management-system' ),
			)
		);
	}

	/**
	 * Activate.
	 *
	 * @since 2.5.0
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 *
	 * @return string
	 */
	public function activate( $request ) {
		if ( ! isset( $request['license_key'] ) || empty( $request['license_key'] ) ) {
			return new \WP_Error(
				'masteriyo_pro_rest_license_key_null',
				esc_html__( 'License key is required.', 'learning-management-system' ),
				array( 'status' => 400 )
			);
		}

		$license_key   = sanitize_text_field( $request['license_key'] );
		$instance_name = masteriyo_pro_get_instance_name();
		$data          = masteriyo_pro_activate_license( $license_key, $instance_name );

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

		// Set license key.
		$this->license->set_license_key( $license_key );
		$this->license->set_activation_data( $data );

		$current_plan = isset( $data['meta']['variant_name'] ) ? $data['meta']['variant_name'] : '';
		$all_addons   = get_option( 'masteriyo_active_addons', array() );
		foreach ( $all_addons as $slug => $addon ) {
			if ( isset( $addon['Plan'] ) && ! empty( $addon['Plan'] ) ) {
				$allowed_plans = array_map( 'trim', explode( ',', $addon['Plan'] ) );

				if ( ! in_array( 'Free', $allowed_plans, true ) && ! in_array( $current_plan, $allowed_plans, true ) ) {
					unset( $all_addons[ $slug ] );
				}
			}
		}

		update_option( 'masteriyo_active_addons', $all_addons );

		$response = $this->get_activate_information( $request );
		$response = array_merge( $response, array( 'message' => esc_html__( 'License key activated successfully.', 'learning-management-system' ) ) );

		return $response;
	}

	/**
	 * Return activated information..
	 *
	 * @since 2.5.0
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 *
	 * @return array
	 */
	public function get_activate_information( $request ) {
		$data = array(
			'status'      => $this->license->get_license_status(),
			'license_key' => $this->hide_license_key( $this->license->get_license_key() ),
		);

		/**
		 * Filters whether extra license data should be append.
		 *
		 * @since 2.5.14
		 * @param \Masteriyo\Pro\Controllers\LicenseControllers $controller
		 */
		$allow_extra_data = apply_filters( 'masteriyo_pro_allow_license_extra_data', false );

		if ( $allow_extra_data ) {
			$data['data'] = masteriyo_array_add( $this->license->get_activation_data(), 'data.meta.variant_name', $this->license->get_variant_name() );
		}

		/**
		 * Filter license data.
		 *
		 * @since 2.5.14
		 *
		 * @param array $data License data.
		 * @param \Masteriyo\Pro\Controllers\LicenseControllers $controller
		 */
		return apply_filters( 'masteriyo_pro_prepare_license_data_for_response', $data, $this );
	}

	/**
	 * Return obfuscated license key.
	 *
	 * @since 2.5.14
	 *
	 * @param ] $license_key
	 * @return void
	 */
	protected function hide_license_key( $license_key ) {
		$length = min( 36, strlen( $license_key ) );
		return wp_generate_password( $length, false );
	}
}
