<?php
/**
 * Assignments Controller class.
 *
 * @since 2.3.5
 *
 * @package Masteriyo\Addons\Assignment\RestApi
 */

namespace Masteriyo\Addons\Assignment\RestApi;

defined( 'ABSPATH' ) || exit;

use Masteriyo\Enums\PostStatus;
use Masteriyo\Enums\SectionChildrenPostType;
use Masteriyo\Helper\Permission;
use Masteriyo\Pro\Addons;
use Masteriyo\RestApi\Controllers\Version1\PostsController;

/**
 * AssignmentsController class.
 */
class AssignmentsController extends PostsController {
	/**
	 * Endpoint namespace.
	 *
	 * @since 2.3.5
	 *
	 * @var string
	 */
	protected $namespace = 'masteriyo/pro/v1';

	/**
	 * Route base.
	 *
	 * @since 2.3.5
	 *
	 * @var string
	 */
	protected $rest_base = 'assignments';

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

	/**
	 * Object type.
	 *
	 * @since 2.3.5
	 *
	 * @var string
	 */
	protected $object_type = 'assignment';

	/**
	 * If object is hierarchical.
	 *
	 * @since 2.3.5
	 *
	 * @var bool
	 */
	protected $hierarchical = true;

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

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

	/**
	 * Register routes.
	 *
	 * @since 2.3.5
	 *
	 * @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' ),
					'args'                => array(
						'force' => array(
							'default'     => true,
							'description' => __( 'Whether to bypass trash and force deletion.', 'learning-management-system' ),
							'type'        => 'boolean',
						),
					),
				),
				'schema' => array( $this, 'get_public_item_schema' ),
			)
		);

		// @since 2.5.7 Added clone endpoint to lessons REST API.
		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, 'clone_item_permissions_check' ),
				),
			)
		);
	}

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

		// The assignments should be order by menu which is the sort order.
		$params['order']['default']   = 'asc';
		$params['orderby']['default'] = 'menu_order';

		$params['course_id'] = array(
			'description'       => __( 'Limit result by course id.', 'learning-management-system' ),
			'type'              => 'integer',
			'validate_callback' => 'rest_validate_request_arg',
			'sanitize_callback' => 'absint',
		);

		return $params;
	}

	/**
	 * Get object.
	 *
	 * @since 2.3.5
	 *
	 * @param  int|Model|WP_Post $object Object ID or Model or WP_Post 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_Post' ) ? $object->ID : $object->get_id();
			}
			$assignment = masteriyo( 'assignment' );
			$assignment->set_id( $id );
			$assignment_repo = masteriyo( 'assignment.store' );
			$assignment_repo->read( $assignment );
		} catch ( \Exception $e ) {
			return false;
		}

		return $assignment;
	}


	/**
	 * Prepares the object for the REST response.
	 *
	 * @since  2.3.5
	 *
	 * @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_assignment_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.3.5
		 *
		 * @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 assignment description data
	 *
	 * @since 2.7.3
	 *
	 * @param \Masteriyo\Models\Assignment $assignment Lesson instance.
	 * @param string $context Request context.
	 *
	 * @return object
	 */
	protected function description_data( $assignment, $context ) {
		$default_editor_option = masteriyo_get_setting( 'advance.editor.default_editor' );
		$description           = '';
		if ( 'classic_editor' === $default_editor_option ) {
			$description = 'view' === $context ? wpautop( do_shortcode( $assignment->get_answer() ) ) : $assignment->get_answer( $context );
		}
		if ( 'block_editor' === $default_editor_option ) {
			$description = 'view' === $context ? do_shortcode( $assignment->get_answer() ) : $assignment->get_answer( $context );
		}
		return $description;
	}

	/**
	 * Get assignment data.
	 *
	 * @since 2.3.5
	 *
	 * @param Masteriyo\Addons\Assignment\Models\Assignment $assignment assignment instance.
	 * @param string  $context Request context.
	 *                         Options: 'view' and 'edit'.
	 *
	 * @return array
	 */
	protected function get_assignment_data( $assignment, $context = 'view' ) {
		$section = masteriyo_get_section( $assignment->get_parent_id() );
		$author  = masteriyo_get_user( $assignment->get_author_id( $context ) );
		$author  = is_wp_error( $author ) || is_null( $author ) ? null : array(
			'id'           => $author->get_id(),
			'display_name' => $author->get_display_name(),
			'avatar_url'   => $author->get_avatar_url(),
		);

		$course = masteriyo_get_course( $assignment->get_course_id( $context ) );

		$data = array(
			'id'                         => $assignment->get_id(),
			'name'                       => wp_specialchars_decode( $assignment->get_name( $context ) ),
			'permalink'                  => $assignment->get_permalink( $context ),
			'preview_link'               => $assignment->get_preview_link( $context ),
			'menu_order'                 => $assignment->get_menu_order( $context ),
			'parent_menu_order'          => $section ? $section->get_menu_order( $context ) : 0,
			'parent_id'                  => $assignment->get_parent_id( $context ),
			'course_id'                  => $assignment->get_course_id( $context ),
			'created_at'                 => masteriyo_rest_prepare_date_response( $assignment->get_created_at( $context ) ),
			'modified_at'                => masteriyo_rest_prepare_date_response( $assignment->get_modified_at( $context ) ),
			'status'                     => $assignment->get_status( $context ),
			'course_name'                => $course ? $course->get_name( $context ) : '',
			'answer'                     => $this->description_data( $assignment, $context ),
			'total_points'               => $assignment->get_total_points( $context ),
			'pass_points'                => $assignment->get_pass_points( $context ),
			'due_date'                   => masteriyo_rest_prepare_date_response( $assignment->get_due_date( $context ) ),
			'max_file_upload_size'       => $assignment->get_max_file_upload_size( $context ),
			'author'                     => $author,
			'navigation'                 => $this->get_navigation_items( $assignment, $context ),
			'restrict_completion_button' => masteriyo_bool_to_string( get_post_meta( $course ? $course->get_id() : 0, '_assignment_completion', true ) ),
			'assignment_retake'          => masteriyo_bool_to_string( get_post_meta( $course ? $course->get_id() : 0, '_assignment_retake', true ) ),
			'download_materials'         => $this->get_download_materials( $assignment, $context ),
			'video_source'               => $this->get_video_source( $assignment->get_video_source( $context ) ),
			'video_source_url'           => $this->get_video_source_url( $assignment, $context ),
			'video_source_id'            => $assignment->get_video_source_id( $context ),
		);

		/**
		 * Filter assignment rest response data.
		 *
		 * @since 2.3.5
		 *
		 * @param array $data Assignment data.
		 * @param Masteriyo\Models\Assignment $assignment Assignment object.
		 * @param string $context What the value is for. Valid values are view and edit.
		 * @param Masteriyo\RestApi\Controllers\Version1\AssignmentsController $controller REST Assignments controller object.
		 */
		return apply_filters( "masteriyo_rest_response_{$this->object_type}_data", $data, $assignment, $context, $this );
	}

	/**
	 * Get video source.
	 *
	 * @since 2.15.0
	 *
	 * @param \Masteriyo\Models\Assignment $Assignment assignment instance.
	 * @param string $context Request context.
	 *
	 * @return array
	 */
	protected function get_video_source( $video_source ) {
		if ( ( new Addons() )->is_addon( $video_source ) ) {
			if ( ! ( new Addons() )->is_active( $video_source ) ) {
				return 'self-hosted';
			}
		}
		return $video_source;
	}

	/**
	 * Get video source url.
	 *
	 * @since 2.15.0
	 *
	 * @param \Masteriyo\Models\Assignment $Assignment assignment instance.
	 * @param string $context Request context.
	 *
	 * @return array
	 */
	protected function get_video_source_url( $lesson, $context ) {
		if ( ( new Addons() )->is_addon( $lesson->get_video_source( $context ) ) ) {
			if ( ! ( new Addons() )->is_active( $lesson->get_video_source() ) ) {
				return '';
			}
		}
		return $lesson->get_video_source_url( $context );
	}


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

		// Set post_status.
		$args['post_status'] = $request['status'];

		if ( ! empty( $request['course_id'] ) ) {
			$args['meta_query'] = array(
				'relation' => 'AND',
				array(
					'key'     => '_course_id',
					'value'   => absint( $request['course_id'] ),
					'compare' => '=',
				),
			);
		}

		// For instructor show only their assignments.
		if ( masteriyo_is_current_user_instructor() ) {
			$args['author__in'] = array( get_current_user_id() );
		}

		return $args;
	}

	/**
	 * Get the assignments'schema, conforming to JSON Schema.
	 *
	 * @since 2.3.5
	 *
	 * @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,
				),
				'name'                 => array(
					'description' => __( 'Assignment name', 'learning-management-system' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'created_at'           => array(
					'description' => __( "The date the assignment was created, in the site's timezone.", 'learning-management-system' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'created_at_gmt'       => array(
					'description' => __( 'The date the assignment was created, as GMT.', 'learning-management-system' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'modified_at'          => array(
					'description' => __( "The date the assignment was last modified, in the site's timezone.", 'learning-management-system' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
					'readonly'    => true,
				),
				'modified_at_gmt'      => array(
					'description' => __( 'The date the assignment was last modified, as GMT.', 'learning-management-system' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
					'readonly'    => true,
				),
				'status'               => array(
					'description' => __( 'Assignment status (post status).', 'learning-management-system' ),
					'type'        => 'string',
					'default'     => PostStatus::PUBLISH,
					'enum'        => array_merge( array_keys( get_post_statuses() ), array( 'future' ) ),
					'context'     => array( 'view', 'edit' ),
				),
				'answer'               => array(
					'description' => __( 'Assignment answer', 'learning-management-system' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'parent_id'            => array(
					'description' => __( 'Assignment parent ID', 'learning-management-system' ),
					'type'        => 'integer',
					'required'    => true,
					'context'     => array( 'view', 'edit' ),
				),
				'course_id'            => array(
					'description' => __( 'Course ID', 'learning-management-system' ),
					'type'        => 'integer',
					'required'    => true,
					'context'     => array( 'view', 'edit' ),
				),
				'course_name'          => array(
					'description' => __( 'Course name', 'learning-management-system' ),
					'type'        => 'string',
					'readonly'    => true,
					'context'     => array( 'view', 'edit' ),
				),
				'menu_order'           => array(
					'description' => __( 'Menu order, used to custom sort assignments.', 'learning-management-system' ),
					'type'        => 'integer',
					'context'     => array( 'view', 'edit' ),
				),
				'total_points'         => array(
					'description' => __( 'Assignment total points', 'learning-management-system' ),
					'type'        => 'integer',
					'context'     => array( 'view', 'edit' ),
				),
				'pass_points'          => array(
					'description' => __( 'Assignment pass points', 'learning-management-system' ),
					'type'        => 'integer',
					'context'     => array( 'view', 'edit' ),
				),
				'due_date'             => array(
					'description' => __( 'Assignment due date', 'learning-management-system' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'max_file_upload_size' => array(
					'description' => __( 'Assignment max file upload size', 'learning-management-system' ),
					'type'        => 'integer',
					'context'     => array( 'view', 'edit' ),
				),
				'download_materials'   => array(
					'description' => __( 'download_materials', 'learning-management-system' ),
					'type'        => 'array',
					'context'     => array( 'view', 'edit' ),
					'items'       => array(
						'type'       => 'object',
						'properties' => array(
							'id'                  => array(
								'description' => __( 'Download material ID', 'learning-management-system' ),
								'type'        => 'integer',
								'default'     => 0,
								'context'     => array( 'view', 'edit' ),
							),
							'title'               => array(
								'description' => __( 'Download material title', 'learning-management-system' ),
								'type'        => 'string',
								'context'     => array( 'view', 'edit' ),
								'readonly'    => true,
							),
							'url'                 => array(
								'description' => __( 'Download material URL', 'learning-management-system' ),
								'type'        => 'string',
								'format'      => 'uri',
								'context'     => array( 'view', 'edit' ),
								'readonly'    => true,
							),
							'mime_type'           => array(
								'description' => __( 'Download material mime type', 'learning-management-system' ),
								'type'        => 'string',
								'context'     => array( 'view', 'edit' ),
								'readonly'    => true,
							),
							'file_size'           => array(
								'description' => __( 'Download material file size', 'learning-management-system' ),
								'type'        => 'integer',
								'context'     => array( 'view', 'edit' ),
								'readonly'    => true,
							),
							'formatted_file_size' => array(
								'description' => __( 'Download material formatted file size', 'learning-management-system' ),
								'type'        => 'string',
								'context'     => array( 'view', 'edit' ),
								'readonly'    => true,
							),
							'created_at'          => array(
								'description' => __( 'Download material creation/upload date.', 'learning-management-system' ),
								'type'        => 'string',
								'format'      => 'date-time',
								'context'     => array( 'view', 'edit' ),
								'readonly'    => true,
							),
						),
					),
				),
				'meta_data'            => array(
					'description' => __( 'Meta data', 'learning-management-system' ),
					'type'        => 'array',
					'context'     => array( 'view', 'edit' ),
					'items'       => array(
						'type'       => 'object',
						'properties' => array(
							'id'    => array(
								'description' => __( 'Meta ID', 'learning-management-system' ),
								'type'        => 'integer',
								'context'     => array( 'view', 'edit' ),
								'readonly'    => true,
							),
							'key'   => array(
								'description' => __( 'Meta key', 'learning-management-system' ),
								'type'        => 'string',
								'context'     => array( 'view', 'edit' ),
							),
							'value' => array(
								'description' => __( 'Meta value', 'learning-management-system' ),
								'type'        => 'mixed',
								'context'     => array( 'view', 'edit' ),
							),
						),
					),
				),
			),
		);

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

	/**
	 * Prepare a single assignment for create or update.
	 *
	 * @since 2.3.5
	 *
	 * @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;
		$assignment = masteriyo( 'assignment' );

		if ( 0 !== $id ) {
			$assignment->set_id( $id );
			$assignment_repo = masteriyo( 'assignment.store' );
			$assignment_repo->read( $assignment );
		}

		// Post name.
		if ( isset( $request['name'] ) ) {
			$assignment->set_name( $request['name'] );
		}

		// Post content.
		if ( isset( $request['answer'] ) ) {
			$assignment->set_answer( wp_slash( $request['answer'] ) );
		}

		// Post status.
		if ( isset( $request['status'] ) ) {
			$assignment->set_status( get_post_status_object( $request['status'] ) ? $request['status'] : 'draft' );
		}

		// Automatically set the menu order if it's not set and the operation is POST.
		if ( ! isset( $request['menu_order'] ) && $creating ) {
			$query = new \WP_Query(
				array(
					'post_type'      => SectionChildrenPostType::all(),
					'post_status'    => PostStatus::all(),
					'posts_per_page' => 1,
					'post_parent'    => $request['parent_id'],
				)
			);

			$assignment->set_menu_order( $query->found_posts );
		}

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

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

		// Total points.
		if ( isset( $request['total_points'] ) ) {
			$assignment->set_total_points( $request['total_points'] );
		}

		// assignment download_materials.
		if ( isset( $request['download_materials'] ) ) {
			$assignment->set_download_materials( wp_list_pluck( $request['download_materials'], 'id' ) );
		}

		// Pass points.
		if ( isset( $request['pass_points'] ) ) {
			$assignment->set_pass_points( $request['pass_points'] );
		}

		// due_date.
		if ( isset( $request['due_date'] ) ) {
			$assignment->set_due_date( $request['due_date'] );
		}

		// Max file upload size.
		if ( isset( $request['max_file_upload_size'] ) ) {
			$assignment->set_max_file_upload_size( $request['max_file_upload_size'] );
		}

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

		// assignment video source.
		if ( isset( $request['video_source'] ) ) {
			$assignment->set_video_source( $request['video_source'] );
		}

		// assignment video source url.
		if ( isset( $request['video_source_url'] ) ) {
			$old_video_source_url = $assignment->get_video_source_url();
			$new_video_source_url = $request['video_source_url'];

			$assignment->set_video_source_url( $new_video_source_url );
		}

		/**
		 * Filters an object before it is inserted via the REST API.
		 *
		 * The dynamic portion of the hook name, `$this->post_type`,
		 * refers to the object type slug.
		 *
		 * @since 2.3.5
		 *
		 * @param Masteriyo\Database\Model $assignment Assignment 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->post_type}_object", $assignment, $request, $creating );
	}


	/**
	 * Retrieve all users related to a specific assignment.
	 *
	 * @since 2.15.0
	 *
	 * @param int $assignment_id The assignment ID.
	 *
	 * @return array The array of user IDs.
	 */
	private function get_users_related_to_assignment( $assignment_id ) {
		global $wpdb;

		$user_ids = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT DISTINCT user_id FROM {$wpdb->prefix}masteriyo_user_activities
					WHERE item_id = %d
					AND activity_type = %s",
				$assignment_id,
				'assignment'
			)
		);

		return $user_ids;
	}

	/**
	 * Checks if a given request has access to get a specific item.
	 *
	 * @since 2.11.0
	 *
	 * @param \WP_REST_Request $request Full details about the request.
	 * @return boolean|\WP_Error True if the request has read access for the item, WP_Error object otherwise.
	 */
	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' )
			);
		}

		$assignment = masteriyo_get_assignment( $request['id'] );

		if ( is_null( $assignment ) ) {
			return new \WP_Error(
				'masteriyo_rest_invalid_assignment_id',
				__( 'Invalid assignment ID.', 'learning-management-system' ),
				array(
					'status' => 400,
				)
			);
		}

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

		if ( is_null( $course ) ) {
			return new \WP_Error(
				'masteriyo_rest_invalid_course_id',
				__( 'Invalid course ID.', 'learning-management-system' ),
				array(
					'status' => 400,
				)
			);
		}

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

		return true;
	}

	/**
	 * Check if a given request has access to create an item.
	 *
	 * @since 2.3.5
	 *
	 * @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' )
			);
		}

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

		if ( ! $this->permission->rest_check_post_permissions( $this->post_type, 'create' ) ) {
			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(),
				)
			);
		}

		$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 ( ( new Addons() )->is_active( MASTERIYO_MULTIPLE_INSTRUCTORS_ADDON_SLUG ) ) {
			if ( masteriyo_is_instructor_or_additional_instructor( $course_id ) ) {
				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 assignment for others 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.3.5
	 *
	 * @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' )
			);
		}

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

		$id         = absint( $request['id'] );
		$assignment = masteriyo_get_assignment( $id );

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

		if ( ! $this->permission->rest_check_post_permissions( $this->post_type, 'delete', $id ) ) {
			return new \WP_Error(
				'masteriyo_rest_cannot_delete',
				__( 'Sorry, you are not allowed to delete resources.', 'learning-management-system' ),
				array(
					'status' => rest_authorization_required_code(),
				)
			);
		}

		return true;
	}

	/**
	 * Check if a given request has access to update an item.
	 *
	 * @since 2.3.5
	 *
	 * @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_admin() || masteriyo_is_current_user_manager() ) {
			return true;
		}

		$id         = absint( $request['id'] );
		$assignment = masteriyo_get_assignment( $id );

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

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

		return true;
	}

	/**
	 * Prepare links for the request.
	 *
	 * @since 2.3.5
	 *
	 * @param Model           $object  Object data.
	 * @param WP_REST_Request $request Request object.
	 * @return array                   Links for the given post.
	 */
	protected function prepare_links( $object, $request ) {
		$links = parent::prepare_links( $object, $request );

		$next_prev_links = $this->get_navigation_links( $object, $request );

		return $links + $next_prev_links;
	}

	/**
	 * Get assignment download_materials.
	 *
	 * @since 2.12.0
	 *
	 * @param Assignment $assignment Assignment object.
	 * @param string $context Request context.
	 *
	 * @return array
	 */
	protected function get_download_materials( $assignment, $context ) {
		// Filter invalid download_materials.
		$download_materials = array_filter(
			array_map(
				function( $attachment ) {
					$post = get_post( $attachment );

					if ( $post && 'attachment' === $post->post_type ) {
						return $post;
					}

					return false;
				},
				$assignment->get_download_materials( $context )
			)
		);

		// Convert the download_materials to the response format.
		$download_materials = array_reduce(
			$download_materials,
			function( $result, $attachment ) {
				$file_size = absint( filesize( get_attached_file( $attachment->ID ) ) );

				$result[] = array(
					'id'                  => $attachment->ID,
					'url'                 => wp_get_attachment_url( $attachment->ID ),
					'title'               => $attachment->post_title,
					'mime_type'           => $attachment->post_mime_type,
					'file_size'           => $file_size,
					'formatted_file_size' => size_format( $file_size ),
					'created_at'          => masteriyo_rest_prepare_date_response( $attachment->post_date_gmt ),
				);
				return $result;
			},
			array()
		);

		/**
		 * assignment attachment filter.
		 *
		 * @since 2.12.0
		 *
		 * @return array[] download_materials array.
		 */
		return apply_filters( "masteriyo_rest_{$this->object_type}_download_materials", $download_materials, $assignment, $context );
	}
}
