<?php
/**
 * Course FAQ builder REST API controller.
 *
 * Handles requests to the course-faqs/builder endpoint.
 *
 * @author   mi5t4n
 * @category API
 * @package Masteriyo\Addons\CourseFaq
 * @since   2.2.7
 */

namespace Masteriyo\Addons\CourseFaq\RestApi\Controllers\Version1;

defined( 'ABSPATH' ) || exit;

use Masteriyo\Helper\Permission;
use Masteriyo\RestApi\Controllers\Version1\CommentsController;
use WP_Comment_Query;

/**
 * Course FAQ builder REST API Controller class.
 *
 * @package Masteriyo\Addons\CourseFaq
 * @extends CommentsController
 */
class CourseFaqBuilderController extends CommentsController {

	/**
	 * Endpoint namespace.
	 *
	 * @since 2.2.7
	 *
	 * @var string
	 */
	protected $namespace = 'masteriyo/pro/v1';

	/**
	 * Route base.
	 *
	 * @since 2.2.7
	 *
	 * @var string
	 */
	protected $rest_base = 'course-faqs/builder';

	/**
	 * Object type.
	 *
	 * @since 2.2.7
	 *
	 * @var string
	 */
	protected $object_type = 'course_faq_builder';

	/**
	 * Post type.
	 *
	 * @since 2.2.7
	 *
	 * @var string
	 */
	protected $post_type = 'mto-course';

	/**
	 * Post object type.
	 *
	 * @since 2.2.7
	 *
	 * @var string
	 */
	protected $post_object_type = 'course';

	/**
	 * Comment type.
	 *
	 * @since 2.2.7
	 *
	 * @var string
	 */
	protected $comment_type = 'mto_course_faq';

	/**
	 * Permission class.
	 *
	 * @since 2.2.7
	 *
	 * @var \Masteriyo\Helper\Permission;
	 */
	protected $permission = null;

	/**
	 * Constructor.
	 *
	 * @since 2.2.7
	 *
	 * @param Permission $permission
	 */
	public function __construct( ?Permission $permission = null ) {
		$this->permission = $permission;
	}

	/**
	 * Register the routes for terms.
	 *
	 * @since 2.2.7
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<id>[\d]+)',
			array(
				'args'   => array(
					'id' => array(
						'description' => __( 'Course ID', 'learning-management-system' ),
						'type'        => 'integer',
					),
				),
				array(
					'methods'             => \WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_item' ),
					'permission_callback' => array( $this, 'get_item_permissions_check' ),
					'args'                => array(
						'context' => $this->get_context_param(
							array(
								'default' => 'view',
							)
						),
					),
				),
				array(
					'methods'             => \WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_item' ),
					'permission_callback' => array( $this, 'update_item_permissions_check' ),
					'args'                => $this->get_endpoint_args_for_item_schema( \WP_REST_Server::EDITABLE ),
				),
				'schema' => array( $this, 'get_public_item_schema' ),
			)
		);
	}

	/**
	 * Check if a given request has access to read the terms.
	 *
	 * @since 2.2.7
	 *
	 * @param  WP_REST_Request $request Full details about the request.
	 * @return WP_Error|boolean
	 */
	public function get_item_permissions_check( $request ) {
		if ( is_null( $this->permission ) ) {
			return new \WP_Error(
				'masteriyo_null_permission',
				__( 'Sorry, the permission object for this resource is null.', 'learning-management-system' )
			);
		}

		if ( masteriyo_is_current_user_instructor() ) {
			return true;
		}

		if ( ! $this->permission->rest_check_comment_permissions( 'read' ) ) {
			return new \WP_Error(
				'masteriyo_rest_cannot_read',
				__( 'Sorry, you cannot list resources.', 'learning-management-system' ),
				array(
					'status' => rest_authorization_required_code(),
				)
			);
		}

		return true;
	}

	/**
	 * Get the course FAQ builder schema, conforming to JSON Schema.
	 *
	 * @since 2.2.7
	 *
	 * @return array
	 */
	public function get_item_schema() {
		$schema = array(
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
			'title'      => $this->object_type,
			'type'       => 'object',
			'properties' => array(
				'course_faqs' => array(
					'description' => __( 'Course FAQ IDs', 'learning-management-system' ),
					'type'        => 'array',
					'required'    => true,
					'context'     => array( 'view', 'edit' ),
				),
			),
		);

		return $this->add_additional_fields_schema( $schema );
	}

	/**
	 * Get course FAQ contents.
	 *
	 * @since  2.2.7
	 * @param  WP_REST_Request $request Full details about the request.
	 * @return array
	 */
	public function get_item( $request ) {
		$response = array();
		$course   = get_post( absint( $request['id'] ) );

		if ( is_null( $course ) || $this->post_type !== $course->post_type ) {
			return new \WP_Error(
				"masteriyo_rest_{$this->post_object_type}_invalid_id",
				__( 'Invalid ID', 'learning-management-system' ),
				array( 'status' => 400 )
			);
		}

		$course_faqs = $this->get_course_faqs( $request );

		foreach ( $course_faqs as $course_faq ) {
			if ( ! $this->check_item_permission( $this->comment_type, 'read', $course_faq->get_id() ) ) {
				continue;
			}

			$data       = $this->prepare_object_for_response( $course_faq, $request );
			$response[] = $this->prepare_response_for_collection( $data );
		}

		return $response;
	}

	/**
	 * Get course faqs
	 *
	 * @since 2.2.7
	 *
	 * @param  WP_REST_Request $request Full details about the request.
	 *
	 * @return Masteriyo\Addons\CourseFaq\Models\CourseFaq[]
	 */
	protected function get_course_faqs( $request ) {
		$query = new \WP_Comment_Query(
			array(
				'post_id'      => $request['id'],
				'post_type'    => $this->post_type,
				'comment_type' => $this->comment_type,
				'orderby'      => 'comment_karma',
				'order'        => 'asc',
			)
		);

		$course_faqs = array_filter( array_map( array( $this, 'get_object' ), $query->comments ) );

		/**
		 * Filters course faq.
		 *
		 * @since 2.2.7
		 *
		 * @param Masteriyo\Addons\CourseFaq\Models\CourseFaq[] $course_faqs Course FAQs.
		 */
		return apply_filters( "masteriyo_rest_pro_{$this->object_type}_objects", $course_faqs );
	}

	/**
	 * Get object.
	 *
	 * @since 2.2.7
	 *
	 * @param  WP_Comment $comment Comment object.
	 * @return \Masteriyo\Addons\CourseFaq\Models\CourseFaq Model object or WP_Error object.
	 */
	protected function get_object( $comment ) {
		try {
			$item = masteriyo( $comment->comment_type );
			$item->set_id( $comment->comment_ID );
			$item_repo = masteriyo( "{$comment->comment_type}.store" );
			$item_repo->read( $item );
		} catch ( \Exception $e ) {
			return false;
		}

		return $item;
	}

	/**
	 * Prepares the object for the REST response.
	 *
	 * @since  2.2.7
	 *
	 * @param  \Masteriyo\Database\Model $object  Model object.
	 * @param  WP_REST_Request $request Request object.
	 *
	 * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
	 */
	protected function prepare_object_for_response( $object, $request ) {
		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
		$data    = $this->get_course_faq_data( $object, $context );

		$data     = $this->add_additional_fields_to_object( $data, $request );
		$data     = $this->filter_response_by_context( $data, $context );
		$response = rest_ensure_response( $data );

		/**
		 * Filter the data for a response.
		 *
		 * The dynamic portion of the hook name, $this->object_type,
		 * refers to object type being prepared for the response.
		 *
		 * @since 2.2.7
		 *
		 * @param WP_REST_Response $response The response object.
		 * @param \Masteriyo\Addons\CourseFaq\Models\CourseFaq $object Course FAQ object.
		 * @param WP_REST_Request  $request  Request object.
		 */
		return apply_filters( "masteriyo_pro_rest_prepare_{$this->object_type}_object", $response, $object, $request );
	}

	/**
	 * Get course FAQ data.
	 *
	 * @since 2.2.7
	 *
	 * @param \Masteriyo\Addons\CourseFaq\Models\CourseFaq $course_faq Course FAQ object.
	 * @param string     $context Request context.
	 *                            Options: 'view' and 'edit'.
	 *
	 * @return array
	 */
	protected function get_course_faq_data( $course_faq, $context = 'view' ) {
		$data = array(
			'id'         => $course_faq->get_id(),
			'title'      => $course_faq->get_title( $context ),
			'content'    => 'view' === $context ? wpautop( $course_faq->get_content() ) : $course_faq->get_content( $context ),
			'course_id'  => $course_faq->get_course_id( $context ),
			'user_id'    => $course_faq->get_author_id( $context ),
			'menu_order' => $course_faq->get_menu_order( $context ),
			'created_at' => masteriyo_rest_prepare_date_response( $course_faq->get_created_at( $context ) ),
		);

		/**
		 * Filter question rest response data.
		 *
		 * @since 2.2.7
		 *
		 * @param array $data Question data.
		 * @param Masteriyo\Models\Question $course_faq Question object.
		 * @param string $context What the value is for. Valid values are view and edit.
		 * @param Masteriyo\Addons\CourseFaq\RestApi\Controllers\Version1\CourseFaqBuilderController $controller REST Questions controller object.
		 */
		return apply_filters( "masteriyo_pro_rest_response_{$this->object_type}_data", $data, $course_faq, $context, $this );
	}

	/**
	 * Format the quiz items according to the builder format.
	 *
	 * @since 2.2.7
	 *
	 * @param \Masteriyo\Addons\CourseFaq\Models\CourseFaq[] $course_faqs Course FAQs.
	 * @param array $query_args Query arguments.
	 * @param array $query_results Comments query result data.
	 * @return array
	 */
	protected function process_objects_collection( $course_faqs, $query_args, $query_results ) {
		$results['course_faqs']      = $course_faqs;
		$course_faq_ids              = wp_list_pluck( $course_faqs, 'id' );
		$results['course_faq_order'] = $course_faq_ids;

		return $results;
	}

	/**
	 * Check permissions for an item.
	 *
	 * @since 2.2.7
	 * @param string $object_type Object type.
	 * @param string $context   Request context.
	 * @param int    $object_id Post ID.
	 * @return bool
	 */
	protected function check_item_permission( $object_type, $context = 'read', $object_id = 0 ) {
		if ( masteriyo_is_current_user_instructor() ) {
			return true;
		}

		return $this->permission->rest_check_comment_permissions( 'read', $object_id );
	}

	/**
	 * Check if a given request has access to create an item.
	 *
	 * @since 2.2.7
	 *
	 * @param  WP_REST_Request $request Full details about the request.
	 * @return WP_Error|boolean
	 */
	public function update_item_permissions_check( $request ) {
		if ( is_null( $this->permission ) ) {
			return new \WP_Error(
				'masteriyo_null_permission',
				__( 'Sorry, the permission object for this resource is null.', 'learning-management-system' )
			);
		}

		if ( masteriyo_is_current_user_instructor() ) {
			return true;
		}

		if ( ! $this->permission->rest_check_comment_permissions( 'update', $request['id'] ) ) {
			return new \WP_Error(
				'masteriyo_rest_cannot_create',
				__( 'Sorry, you are not allowed to create resources.', 'learning-management-system' ),
				array(
					'status' => rest_authorization_required_code(),
				)
			);
		}

		return true;
	}

	/**
	 * Save an object data.
	 *
	 * @since  2.2.7
	 * @param  WP_REST_Request $request  Full details about the request.
	 * @return Model|WP_Error
	 */
	public function update_item( $request ) {
		$course = get_post( $request['id'] );

		if ( is_null( $course ) || $this->post_type !== $course->post_type ) {
			return new \WP_Error(
				"masteriyo_rest_{$this->post_type_object}_invalid_id",
				__( 'Invalid ID', 'learning-management-system' ),
				array( 'status' => 400 )
			);
		}

		// Save course FAQ order.
		$this->save_course_faq_order( $request );

		return $this->get_item(
			array(
				'id' => $course->ID,
			)
		);
	}

	/**
	 * Filter course faq.
	 *
	 * @since 2.2.7
	 *
	 * @param int $course_faq
	 * @return array
	 */
	protected function filter_course_faqs( $course_faq ) {
		$course_faq = get_comment( absint( $course_faq ) );

		return $course_faq && $this->comment_type === $course_faq->comment_type;
	}

	/**
	 * Save course_faq order.
	 *
	 * @since 2.2.7
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 */
	protected function save_course_faq_order( $request ) {
		$course_faqs = isset( $request['course_faqs'] ) ? $request['course_faqs'] : array();
		$course_faqs = array_filter( $course_faqs, array( $this, 'filter_course_faqs' ) );

		foreach ( $course_faqs as $menu_order => $course_faq ) {
			$this->update_course_faq( $course_faq, $menu_order, $request['id'] );
		}
	}

	/**
	 * Update course FAQ if the parent id or menu order is changed.
	 *
	 * @since 2.2.7
	 *
	 * @param int $id Comment ID.
	 * @param int $menu_order Comment menu/sort order.
	 * @param int $course_id Course ID.
	 */
	private function update_course_faq( $id, $menu_order, $course_id ) {
		$comment = get_comment( $id );

		if ( is_null( $comment ) ) {
			return;
		}
		global $wpdb;
		if ( absint( $comment->comment_karma ) !== $menu_order || $comment->comment_post_ID !== $course_id ) {
			$wpdb->update(
				$wpdb->comments,
				array(
					'comment_karma'   => $menu_order,
					'comment_post_ID' => $course_id,
				),
				array( 'comment_ID' => $comment->comment_ID ),
				array( '%d', '%d' ),
				array( '%d' )
			);
		}
	}
}
