<?php
/**
 * Assignment replies controller class.
 *
 * @since 2.3.5
 *
 * @package Masteriyo\Addons\Assignment\RestApi;
 */

namespace Masteriyo\Addons\Assignment\RestApi;

defined( 'ABSPATH' ) || exit;

use Masteriyo\Addons\Assignment\Enums\AssignmentReplyStatus;
use Masteriyo\Enums\PostStatus;
use Masteriyo\Helper\Permission;
use Masteriyo\RestApi\Controllers\Version1\PostsController;
use WP_Error;

/**
 * Main class for assignment replies controller.
 */
class AssignmentRepliesController extends PostsController {
	/**
	 * Endpoint namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'masteriyo/pro/v1';

	/**
	 * Route base.
	 *
	 * @var string
	 */
	protected $rest_base = 'assignment/replies';

	/**
	 * Object Type.
	 *
	 * @var string
	 */
	protected $object_type = 'assignment_reply';

	/**
	 * Post Type.
	 *
	 * @var string
	 */
	protected $post_type = 'mto-assignment-reply';

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


	/**
	 * Constructor.
	 *
	 * @since 2.3.5
	 *
	 * @param Permission $permission Permission instance.
	 */
	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 . '/delete',
			array(
				array(
					'methods'             => \WP_REST_Server::DELETABLE,
					'callback'            => array( $this, 'delete_items' ),
					'permission_callback' => array( $this, 'delete_items_permissions_check' ),
					'args'                => array(
						'ids'      => array(
							'required'    => true,
							'description' => __( 'AssignmentReply IDs.', 'learning-management-system' ),
							'type'        => 'array',
						),
						'force'    => array(
							'default'     => false,
							'description' => __( 'Whether to bypass trash and force deletion.', 'learning-management-system' ),
							'type'        => 'boolean',
						),
						'children' => array(
							'default'     => false,
							'description' => __( 'Whether to delete the children under the assignment replies.', 'learning-management-system' ),
							'type'        => 'boolean',
						),
					),
				),
			)
		);

		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_delete' => array(
							'description' => __( 'Whether to bypass trash and force deletion.', 'learning-management-system' ),
							'type'        => 'boolean',
							'default'     => true,
						),
					),
				),
				'schema' => array( $this, 'get_public_item_schema' ),
			)
		);
	}

	/**
	 * 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_reply = masteriyo_get_assignment_reply( $id );

		$user_id = get_current_user_id();

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

		if ( ! current_user_can( 'edit_assignment_replies' ) ) {
			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(),
				)
			);
		}

		if ( ! is_wp_error( $user_id ) && ! is_wp_error( $assignment_reply ) && $user_id === $assignment_reply->get_user_id() ) {
			return true;
		}
		return false;
	}

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

		unset( $params['post'] );

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

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

		$params['status'] = array(
			'default'           => 'any',
			'description'       => __( 'Limit result set to courses assigned a specific status.', 'learning-management-system' ),
			'type'              => 'string',
			'enum'              => array_merge( AssignmentReplyStatus::all(), array( PostStatus::ANY ) ),
			'sanitize_callback' => 'sanitize_key',
			'validate_callback' => 'rest_validate_request_arg',
		);

		/**
		 * Filters REST API collection parameters for the Assignment Replies 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.3.5
		 *
		 * @param array $params JSON Schema-formatted collection parameters.
		 */
		return apply_filters( 'masteriyo_rest_assignment_reply_collection_params', $params );
	}

	/**
	 * Get object.
	 *
	 * @since 2.3.5
	 *
	 * @param int|\WP_Comment|\Masteriyo\Addons\Assignment\Models\AssignmentReply $object Object ID or WP_Comment or Model.
	 *
	 * @return \Masteriyo\Addons\Assignment\Models\AssignmentReply 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_reply = masteriyo( 'assignment-reply' );
			$assignment_reply->set_id( $id );
			$assignment_reply_repo = masteriyo( 'assignment-reply.store' );
			$assignment_reply_repo->read( $assignment_reply );
		} catch ( \Exception $e ) {
			return false;
		}

		return $assignment_reply;
	}

	/**
	 * Prepares the object for the REST Reply.
	 *
	 * @since  2.3.5
	 *
	 * @param  Masteriyo\Database\Model $object  Model object.
	 * @param  WP_REST_Request $request Request object.
	 *
	 * @return WP_Error|WP_REST_Reply Reply 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_reply_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->object_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 Reply data.
	 *
	 * @since 2.3.5
	 *
	 * @param \Masteriyo\Addons\Assignment\Models\AssignmentReply $assignment_reply Assignment Reply instance.
	 * @param string       $context Request context.
	 *                             Options: 'view' and 'edit'.
	 *
	 * @return array
	 */
	protected function get_assignment_reply_data( $assignment_reply, $context = 'view' ) {
		$data = array(
			'id'            => $assignment_reply->get_id(),
			'created_at'    => masteriyo_rest_prepare_date_response( $assignment_reply->get_created_at( $context ) ),
			'modified_at'   => masteriyo_rest_prepare_date_response( $assignment_reply->get_modified_at( $context ) ),
			'note'          => $assignment_reply->get_note( $context ),
			'result'        => $assignment_reply->get_result(),
			'answer'        => $assignment_reply->get_answer( $context ),
			'reviewed'      => $assignment_reply->is_reviewed( $context ),
			'status'        => $assignment_reply->get_status( $context ),
			'earned_points' => $assignment_reply->get_earned_points( $context ),
			'parent_id'     => $assignment_reply->get_parent_id( $context ),
			'attachments'   => $this->get_attachments( $assignment_reply, $context ),
			'assignment'    => null,
			'user'          => null,
		);

		$user = masteriyo_get_user( $assignment_reply->get_user_id( $context ) );
		if ( ! is_null( $user ) && ! is_wp_error( $user ) ) {
			$data['user'] = array(
				'id'           => $user->get_id(),
				'display_name' => $user->get_display_name(),
				'avatar_url'   => $user->get_avatar_url(),
				'first_name'   => $user->get_first_name(),
				'last_name'    => $user->get_last_name(),
				'email'        => $user->get_email(),
			);
		}

		$assignment = masteriyo_get_assignment( $assignment_reply->get_assignment_id() );

		if ( $assignment ) {
			$course             = masteriyo_get_course( $assignment->get_course_id() );
			$data['assignment'] = array(
				'id'           => $assignment->get_id(),
				'name'         => $assignment->get_name(),
				'due_date'     => masteriyo_rest_prepare_date_response( $assignment->get_due_date( $context ) ),
				'total_points' => $assignment->get_total_points(),
				'pass_points'  => $assignment->get_pass_points(),
				'course_name'  => $course ? $course->get_name() : '',
			);
		}

		/**
		 * Filter Assignment reply rest Reply data.
		 *
		 * @since 2.3.5
		 *
		 * @param array $data Assignment Reply data.
		 * @param Masteriyo\Addons\Assignment\Models\AssignmentReply $assignment_reply Assignment Reply object.
		 * @param string $context What the value is for. Valid values are view and edit.
		 * @param Masteriyo\RestApi\Controllers\Version1\AssignmentRepliesController $controller REST courses controller object.
		 */
		return apply_filters( "masteriyo_rest_assignment_reply_{$this->object_type}_data", $data, $assignment_reply, $context, $this );
	}

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

		$args['post_status'] = $request['status'];

		// Manager and Administrator can see all replies of all assignments.
		if ( current_user_can( 'edit_others_assignment_replies' ) && current_user_can( 'manage_masteriyo_settings' ) ) {
			if ( $request['assignment'] ) {
				$args['post_parent__in'] = $request['assignment'];
			}

			if ( $request['user'] ) {
				$args['author__in'] = $request['user'];
			}
		} elseif ( current_user_can( 'edit_others_assignment_replies' ) ) { // Instructor can see replies to their assignments and their replies only.
			if ( $request['assignment'] ) {
				$assignments = array_filter(
					array_map(
						function( $id ) {
							$post = get_post( $id );

							if ( $post && 'mto-assignment' === $post->post_type && get_current_user_id() === absint( $post->post_author ) ) {
								return $id;
							}

							return null;
						},
						$request['assignment']
					)
				);
			} else {
				$assignments = masteriyo_get_assignments_ids_for_instructor( get_current_user_id() );
			}

			// If the instructor doesn't have any assignment, set empty assignment array.
			$args['post_parent__in'] = empty( $assignments ) ? array( 0 ) : $assignments;

			if ( $request['user'] ) {
				$args['author__in'] = $request['user'];
			}
		} else {
			$args['author__in']      = array( get_current_user_id() );
			$args['post_parent__in'] = $request['assignment'];
		}

		return $args;
	}

	/**
	 * Get the Assignment Reply's 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,
				),
				'assignment'    => array(
					'description' => __( 'Parent/Assignment ID', 'learning-management-system' ),
					'type'        => 'integer',
					'required'    => true,
					'context'     => array( 'view', 'edit' ),
				),
				'created_at'    => array(
					'description' => __( "The date the course was created, in the site's timezone.", 'learning-management-system' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
					'readonly'    => true,
				),
				'answer'        => array(
					'description' => __( 'Assignment Reply Answer.', 'learning-management-system' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'note'          => array(
					'description' => __( 'Assignment Reply note.', 'learning-management-system' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'answer'        => array(
					'description' => __( 'Assignment Reply answer.', 'learning-management-system' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
					'required'    => true,
				),
				'reviewed'      => array(
					'description' => __( 'Whether assignment submission is reviewed or not.', 'learning-management-system' ),
					'type'        => 'boolean',
					'context'     => array( 'view', 'edit' ),
				),
				'status'        => array(
					'description' => __( 'Assignment Reply status.', 'learning-management-system' ),
					'type'        => 'string',
					'enum'        => AssignmentReplyStatus::all(),
					'context'     => array( 'view', 'edit' ),
				),
				'parent'        => array(
					'description' => __( 'Assignment Reply Parent.', 'learning-management-system' ),
					'type'        => 'integer',
					'context'     => array( 'view', 'edit' ),
				),
				'user_id'       => array(
					'description' => __( 'The User ID.', 'learning-management-system' ),
					'type'        => 'integer',
					'context'     => array( 'view', 'edit' ),
					'readonly'    => true,
				),
				'earned_points' => array(
					'description' => __( 'Earned points', 'learning-management-system' ),
					'type'        => 'numeric',
					'context'     => array( 'view', 'edit' ),
				),
				'attachments'   => array(
					'description' => __( 'Course attachments', 'learning-management-system' ),
					'type'        => 'array',
					'context'     => array( 'view', 'edit' ),
					'items'       => array(
						'type'       => 'object',
						'properties' => array(
							'id'                  => array(
								'description' => __( 'Course attachment ID', 'learning-management-system' ),
								'type'        => 'integer',
								'default'     => 0,
								'context'     => array( 'view', 'edit' ),
							),
							'title'               => array(
								'description' => __( 'Course attachment title', 'learning-management-system' ),
								'type'        => 'string',
								'context'     => array( 'view', 'edit' ),
								'readonly'    => true,
							),
							'url'                 => array(
								'description' => __( 'Course attachment URL', 'learning-management-system' ),
								'type'        => 'string',
								'format'      => 'uri',
								'context'     => array( 'view', 'edit' ),
								'readonly'    => true,
							),
							'mime_type'           => array(
								'description' => __( 'Course attachment mime type', 'learning-management-system' ),
								'type'        => 'string',
								'context'     => array( 'view', 'edit' ),
								'readonly'    => true,
							),
							'file_size'           => array(
								'description' => __( 'Course attachment file size', 'learning-management-system' ),
								'type'        => 'integer',
								'context'     => array( 'view', 'edit' ),
								'readonly'    => true,
							),
							'formatted_file_size' => array(
								'description' => __( 'Course attachment formatted file size', 'learning-management-system' ),
								'type'        => 'string',
								'context'     => array( 'view', 'edit' ),
								'readonly'    => true,
							),
							'created_at'          => array(
								'description' => __( 'Course attachment 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 Reply object 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\Addons\Assignment\Models\AssignmentReply
	 */
	protected function prepare_object_for_database( $request, $creating = false ) {
		$id               = isset( $request['id'] ) ? absint( $request['id'] ) : 0;
		$assignment_reply = masteriyo( 'assignment-reply' );
		$user             = masteriyo_get_current_user();

		if ( 0 !== $id ) {
			$assignment_reply->set_id( $id );
			$assignment_reply_repo = masteriyo( 'assignment-reply.store' );
			$assignment_reply_repo->read( $assignment_reply );
		}
		// Assignment Reply Date.
		if ( isset( $request['created_at'] ) ) {
			$assignment_reply->set_created_at( $request['created_at'] );
		}

		// Assignment Reply note.
		if ( isset( $request['note'] ) ) {
			$assignment_reply->set_note( $request['note'] );
		}

		// Assignment Reply Content.
		if ( isset( $request['answer'] ) ) {
			$assignment_reply->set_answer( $request['answer'] );
		}

		// Assignment Reply earned points..
		if ( isset( $request['earned_points'] ) ) {
			$assignment_reply->set_earned_points( $request['earned_points'] );
		}

		// Assignment reply reviewed.
		if ( isset( $request['reviewed'] ) ) {
			$assignment_reply->set_reviewed( $request['reviewed'] );
		}

		// Assignment Reply Parent.
		if ( isset( $request['parent'] ) ) {
			$assignment_reply->set_parent( $request['parent'] );
		}

		// Assignment Reply assignment.
		if ( isset( $request['assignment'] ) ) {
			$assignment_reply->set_assignment_id( $request['assignment'] );
		}

		// Assignment Reply attachments.
		if ( isset( $request['attachments'] ) ) {
			$attachment_ids = wp_list_pluck( $request['attachments'], 'id' );
			$attachment_ids = array_filter(
				$attachment_ids,
				function( $attachment_id ) {
					$post = get_post( $attachment_id );
					return $post && 'attachment' === $post->post_type;
				}
			);
			$assignment_reply->set_attachments( $attachment_ids );
		}

		// User ID.
		if ( isset( $request['author_id'] ) ) {
			$assignment_reply->set_author_id( $request['author_id'] );
		}

		// User ID.
		if ( isset( $request['author_id'] ) ) {
			$assignment_reply->set_author_id( $request['author_id'] );
		}

		// Allow set meta_data.
		if ( isset( $request['meta_data'] ) && is_array( $request['meta_data'] ) ) {
			foreach ( $request['meta_data'] as $meta ) {
				$assignment_reply->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.3.5
		 *
		 * @param Masteriyo\Addons\Assignment\Models\AssignmentReply $comment Assignment Reply 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", $assignment_reply, $request, $creating );
	}

	/**
	 * Restore assignment reply.
	 *
	 * @since 2.3.5
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 *
	 * @return WP_Error|WP_REST_Response
	 */
	public function restore_item( $request ) {
		$object = $this->get_object( (int) $request['id'] );

		if ( ! $object || 0 === $object->get_id() ) {
			return new \WP_Error( "masteriyo_rest_{$this->object_type}_invalid_id", __( 'Invalid ID.', 'learning-management-system' ), array( 'status' => 404 ) );
		}

		wp_untrash_post( $object->get_id() );

		// Read object again.
		$object = $this->get_object( (int) $request['id'] );

		$data     = $this->prepare_object_for_response( $object, $request );
		$response = rest_ensure_response( $data );

		if ( $this->public ) {
			$response->link_header( 'alternate', $this->get_permalink( $object ), array( 'type' => 'text/html' ) );
		}

		return $response;
	}

	/**
	 * Process objects collection.
	 *
	 * @since 2.3.5
	 *
	 * @param array $objects Assignment replies data.
	 * @param array $query_args Query arguments.
	 * @param array $query_results Assignment replies 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['posts_per_page'],
				'assignment_replies_count' => $this->get_posts_count(),
			),
		);
	}

	/**
	 * Get assignment reply attachments
	 *
	 * @since 2.3.5
	 *
	 * @param \Masteriyo\Addons\Assignment\Models\AssignmentReply $assignment_reply Assignment reply object.
	 * @param string $context Request context.
	 *
	 * @return array
	 */
	protected function get_attachments( $assignment_reply, $context ) {
		// Filter invalid attachments.
		$attachments = array_filter(
			array_map(
				function( $attachment ) {
					$post = get_post( $attachment );

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

					return false;
				},
				(array) $assignment_reply->get_meta( '_attachments' )
			)
		);

		// Convert the attachments to the response format.
		$attachments = (array) array_reduce(
			$attachments,
			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 reply attachment filter.
		 *
		 * @since 2.3.5
		 *
		 * @return array[] $attachments Assignment attachments.
		 * @param \Masteriyo\Addons\Assignment\Models\AssignmentReply $assignment_reply Assignment reply object.
		 * @param string $context Context.
		 */
		return apply_filters( 'masteriyo_rest_assignment_reply_attachments', $attachments, $assignment_reply, $context );
	}

	/**
	 * Check if a given request has access to create an item.
	 *
	 * Check due date as well.
	 *
	 * @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 ) {
		$result = parent::create_item_permissions_check( $request );

		if ( false === $result ) {
			return false;
		}

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

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

		if ( $assignment->get_due_date() && time() > $assignment->get_due_date()->getTimestamp() ) {
			return new \WP_Error(
				'masteriyo_rest_assignment_due_date_expired',
				__( 'Assignment due date expired.', 'learning-management-system' ),
				array(
					'status' => 400,
				)
			);
		}

		return true;
	}
}
