<?php
/**
 * Course Faqs Controller class.
 *
 * @since 2.2.7
 *
 * @package Masteriyo\Addons\CourseFaq
 */

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

defined( 'ABSPATH' ) || exit;

use Masteriyo\Enums\CommentStatus;
use Masteriyo\Helper\Permission;
use Masteriyo\RestApi\Controllers\Version1\CommentsController;

/**
 * Course FAQs controller class.
 */
class CourseFaqsController 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';

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

	/**
	 * Post type.
	 *
	 * @var string
	 */
	protected $post_type = 'mto_course_faq';

	/**
	 * Object type.
	 *
	 * @since 2.2.7
	 *
	 * @var string
	 */
	protected $object_type = '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 routes.
	 *
	 * @since 2.2.7
	 *
	 * @return void
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base,
			array(
				array(
					'methods'             => \WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_items' ),
					'permission_callback' => array( $this, 'get_items_permissions_check' ),
					'args'                => $this->get_collection_params(),
				),
				array(
					'methods'             => \WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'create_item' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
					'args'                => $this->get_endpoint_args_for_item_schema( \WP_REST_Server::CREATABLE ),
				),
			)
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<id>[\d]+)',
			array(
				'args'   => array(
					'id' => array(
						'description' => __( 'Unique identifier for the resource.', '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 ),
				),
				array(
					'methods'             => \WP_REST_Server::DELETABLE,
					'callback'            => array( $this, 'delete_item' ),
					'permission_callback' => array( $this, 'delete_item_permissions_check' ),
				),
				'schema' => array( $this, 'get_public_item_schema' ),
			)
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<id>[\d]+)/clone',
			array(
				'args' => array(
					'id' => array(
						'description' => __( 'Unique identifier for the resource.', 'learning-management-system' ),
						'type'        => 'integer',
					),
				),
				array(
					'methods'             => \WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'clone_item' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
				),
			)
		);
	}

	/**
	 * Get the query params for collections of attachments.
	 *
	 * @since 2.2.7
	 *
	 * @return array
	 */
	public function get_collection_params() {
		$params = parent::get_collection_params();

		unset( $params['post'] );

		$params['course'] = array(
			'default'     => array(),
			'description' => __( 'Limit result set to course faqs assigned to specific course IDs.', 'learning-management-system' ),
			'type'        => 'array',
			'items'       => array(
				'type' => 'integer',
			),
		);

		/**
		 * Filters REST API collection parameters for the course faqs controller.
		 *
		 * This filter registers the collection parameter, but does not map the
		 * collection parameter to an internal WP_Comment_Query parameter. Use the
		 * `rest_comment_query` filter to set WP_Comment_Query parameters.
		 *
		 * @since 2.2.7
		 *
		 * @param array $params JSON Schema-formatted collection parameters.
		 */
		return apply_filters( 'masteriyo_rest_course_review_collection_params', $params );
	}

	/**
	 * Prepare objects query.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 *
	 * @since  2.2.7
	 *
	 * @return array
	 */
	protected function prepare_objects_query( $request ) {
		$args = parent::prepare_objects_query( $request );

		$args['post__in'] = $request['course'];

		return $args;
	}

	/**
	 * Get object.
	 *
	 * @since 2.2.7
	 *
	 * @param  int|Model|WP_Comment $object Object ID or Model or WP_Comment object.
	 * @return object Model object or WP_Error object.
	 */
	protected function get_object( $object ) {
		try {
			if ( is_int( $object ) ) {
				$id = $object;
			} else {
				$id = is_a( $object, '\WP_Comment' ) ? $object->comment_ID : $object->get_id();
			}
			$course_faq = masteriyo( 'course-faq' );
			$course_faq->set_id( $id );
			$course_faq_repo = masteriyo( 'course-faq.store' );
			$course_faq_repo->read( $course_faq );
		} catch ( \Exception $e ) {
			return false;
		}

		return $course_faq;
	}

	/**
	 * 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_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 );
		$response->add_links( $this->prepare_links( $object, $request ) );

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

	/**
	 * Get faq data.
	 *
	 * @param Masteriyo\Addons\CourseFaq\Models\CourseFaq $course_faq Faq instance.
	 * @param string  $context Request context.
	 *                         Options: 'view' and 'edit'.
	 *
	 * @return array
	 */
	protected function get_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 faqs rest response data.
		 *
		 * @since 1.4.10
		 *
		 * @param array $data FAQ data.
		 * @param Masteriyo\Addons\CourseFaq\Models\CourseFaq $course_faq FAQ object.
		 * @param string $context What the value is for. Valid values are view and edit.
		 * @param Masteriyo\RestApi\Controllers\Version1\FaqsController $controller REST faqs controller object.
		 */
		return apply_filters( "masteriyo_rest_response_{$this->object_type}_data", $data, $course_faq, $context, $this );
	}

	/**
	 * Get the Faqs'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(
				'id'             => array(
					'description' => __( 'Unique identifier for the resource.', 'learning-management-system' ),
					'type'        => 'integer',
					'context'     => array( 'view', 'edit' ),
					'readonly'    => true,
				),
				'title'          => array(
					'description' => __( 'FAQ title.', 'learning-management-system' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'created_at'     => array(
					'description' => __( "The date the FAQ was created, in the site's timezone.", 'learning-management-system' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'created_at_gmt' => array(
					'description' => __( 'The date the FAQ was created, as GMT.', 'learning-management-system' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'content'        => array(
					'description' => __( 'FAQ content.', 'learning-management-system' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'course_id'      => array(
					'description' => __( 'Course ID', 'learning-management-system' ),
					'type'        => 'integer',
					'context'     => array( 'view', 'edit' ),
					'required'    => true,
				),
				'user_id'        => array(
					'description' => __( 'User ID', 'learning-management-system' ),
					'type'        => 'integer',
					'context'     => array( 'view', 'edit' ),
				),
				'menu_order'     => array(
					'description' => __( 'Menu/sort order, used to custom sort FAQs.', 'learning-management-system' ),
					'type'        => 'integer',
					'context'     => array( 'view', 'edit' ),
				),
			),
		);

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

	/**
	 * Prepare a single Faq for create or update.
	 *
	 * @since 2.2.7
	 *
	 * @param WP_REST_Request $request Request object.
	 * @param bool            $creating If is creating a new object.
	 *
	 * @return WP_Error|Masteriyo\Database\Model
	 */
	protected function prepare_object_for_database( $request, $creating = false ) {
		$id         = isset( $request['id'] ) ? absint( $request['id'] ) : 0;
		$course_faq = masteriyo( 'course-faq' );

		if ( 0 !== $id ) {
			$course_faq->set_id( $id );
			$course_faq_repo = masteriyo( 'course-faq.store' );
			$course_faq_repo->read( $course_faq );
		}

		// FAQ title.
		if ( isset( $request['title'] ) ) {
			$course_faq->set_title( wp_kses_post( $request['title'] ) );
		}

		// FAQ content.
		if ( isset( $request['content'] ) ) {
			$course_faq->set_content( wp_kses_post( $request['content'] ) );
		}

		// Automatically set the menu order if it's not set and the operation is POST.
		if ( ! isset( $request['menu_order'] ) && $creating ) {
			$query = new \WP_Comment_Query(
				array(
					'type'          => 'mto_course_faq',
					'status'        => CommentStatus::ALL,
					'post_id'       => isset( $request['course_id'] ) ? $request['course_id'] : 0,
					'no_found_rows' => false,
					'number'        => 1,
				)
			);

			$course_faq->set_menu_order( $query->found_comments );
		}

		// Faq parent ID.
		if ( isset( $request['parent_id'] ) ) {
			$course_faq->set_parent_id( $request['parent_id'] );
		}

		// Faq user ID.
		if ( isset( $request['user_id'] ) ) {
			$course_faq->set_author_id( $request['user_id'] );
		}

		// Course ID.
		if ( isset( $request['course_id'] ) ) {
			$course_faq->set_course_id( $request['course_id'] );
		}

		// Allow set meta_data.
		if ( isset( $request['meta_data'] ) && is_array( $request['meta_data'] ) ) {
			foreach ( $request['meta_data'] as $meta ) {
				$course_faq->update_meta_data( $meta['key'], $meta['value'], isset( $meta['id'] ) ? $meta['id'] : '' );
			}
		}

		/**
		 * Filters an object before it is inserted via the REST API.
		 *
		 * The dynamic portion of the hook name, `$this->object_type`,
		 * refers to the object type slug.
		 *
		 * @since 2.2.7
		 *
		 * @param Masteriyo\Database\Model $course_faq  FAQ object.
		 * @param WP_REST_Request $request  Request object.
		 * @param bool            $creating If is creating a new object.
		 */
		return apply_filters( "masteriyo_rest_pre_insert_{$this->object_type}_object", $course_faq, $request, $creating );
	}

	/**
	 * Get objects.
	 *
	 * @since  2.2.7
	 * @param  array $query_args Query args.
	 * @return array
	 */
	protected function get_objects( $query_args ) {
		$query            = new \WP_Comment_Query( $query_args );
		$course_faq_posts = $query->comments;
		$total_posts      = count( $course_faq_posts );

		if ( $total_posts < 1 ) {
			// Out-of-bounds, run the query again without LIMIT for total count.
			unset( $query_args['paged'] );
			$course_faq_posts = new \WP_Comment_Query( $query_args );
			$course_faq_posts = $query->comments;
			$total_posts      = count( $course_faq_posts );
		}

		return array(
			'objects' => array_filter( array_map( array( $this, 'get_object' ), $course_faq_posts ) ),
			'total'   => (int) $total_posts,
			'pages'   => (int) ceil( $total_posts / (int) 10 ),
		);
	}

	/**
	 * 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 create_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' )
			);
		}

		$pervious_faq_id = absint( $request['id'] ) ?? 0;
		if ( $pervious_faq_id ) {
			$course_faq_obj = get_comment( $pervious_faq_id );
			$course_id      = $course_faq_obj->comment_post_ID;
		} else {
			$course_id = absint( $request['course_id'] );
		}

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

		if ( masteriyo_is_current_user_admin() || masteriyo_is_current_user_manager() ) {
			return true;
		}

		if ( $course->get_author_id() !== get_current_user_id() ) {
			return new \WP_Error(
				'masteriyo_rest_cannot_create',
				__( "Sorry, you are not allowed to create FAQs for other's course.", 'learning-management-system' ),
				array(
					'status' => rest_authorization_required_code(),
				)
			);
		}

		return true;
	}

	/**
	 * Check if a given request has access to delete an item.
	 *
	 * @since 2.2.7
	 *
	 * @param  WP_REST_Request $request Full details about the request.
	 * @return WP_Error|boolean
	 */
	public function delete_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' )
			);
		}

		$id         = absint( $request['id'] );
		$course_faq = masteriyo_get_faq( $id );

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

		if ( masteriyo_is_current_user_admin() || masteriyo_is_current_user_manager() ) {
			return true;
		}

		$course = masteriyo_get_course( $course_faq->get_course_id() );

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

		if ( $course->get_author_id() !== get_current_user_id() ) {
			return new \WP_Error(
				'masteriyo_rest_cannot_create',
				__( 'Sorry, you are not allowed to delete FAQs of others courses.', 'learning-management-system' ),
				array(
					'status' => rest_authorization_required_code(),
				)
			);
		}

		return true;
	}

	/**
	 * Check if a given request has access to update 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' )
			);
		}

		$id         = absint( $request['id'] );
		$course_faq = masteriyo_get_faq( $id );

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

		if ( masteriyo_is_current_user_admin() || masteriyo_is_current_user_manager() ) {
			return true;
		}

		$course = masteriyo_get_course( $course_faq->get_course_id() );

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

		if ( $course->get_author_id() !== get_current_user_id() ) {
			return new \WP_Error(
				'masteriyo_rest_cannot_create',
				__( 'Sorry, you are not allowed to update FAQs of others courses.', 'learning-management-system' ),
				array(
					'status' => rest_authorization_required_code(),
				)
			);
		}

		return true;
	}

	/**
	 * 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 ) {
		return true;
	}

	/**
	 * Process objects collection.
	 *
	 * @since 2.2.7
	 *
	 * @param array $objects Course FAQs data.
	 * @param array $query_args Query arguments.
	 * @param array $query_results Course FAQs query result data.
	 *
	 * @return array
	 */
	protected function process_objects_collection( $objects, $query_args, $query_results ) {
		return array(
			'data' => $objects,
			'meta' => array(
				'total'             => $query_results['total'],
				'pages'             => $query_results['pages'],
				'current_page'      => $query_args['paged'],
				'per_page'          => $query_args['number'],
				'course_faqs_count' => $this->get_comments_count(),
			),
		);
	}
}
