<?php
/**
 * Resource handler for Assignment Reply.
 *
 * @since 2.8.3
 */

namespace Masteriyo\Addons\Assignment\Resources;

use Masteriyo\Helper\Utils;
use Masteriyo\Resources\CourseResource;
use Masteriyo\Resources\UserResource;

defined( 'ABSPATH' ) || exit;

/**
 * Resource handler for Course data.
 *
 * @since 2.8.3
 */
class AssignmentReplyResource {


	/**
	 * Transform the resource into an array.
	 *
	 * @since 2.8.3
	 *
	 * @param \Masteriyo\Addons\Assignment\Models\AssignmentReply $assignment_reply AssignmentReply object.
	 *
	 * @return array
	 */
	public static function to_array( $assignment_reply, $context = 'view' ) {

		$user = masteriyo_get_user( $assignment_reply->get_user_id( $context ) );

		if ( ! is_wp_error( $user ) ) {
			$author = array(
				'id'           => $user->get_id(),
				'display_name' => $user->get_display_name(),
				'avatar_url'   => $user->profile_image_url(),
			);
		}

		$data = array(
			'answer'        => $assignment_reply->get_answer(),
			'menu_order'    => $assignment_reply->get_menu_order(),
			'parent_id'     => $assignment_reply->get_parent_id(), // Parent ID is Assignment ID.
			'created_at'    => masteriyo_rest_prepare_date_response( $assignment_reply->get_created_at() ),
			'user_id'       => $assignment_reply->get_user_id(),
			'modified_at'   => masteriyo_rest_prepare_date_response( $assignment_reply->get_modified_at() ),
			'status'        => $assignment_reply->get_status(),
			'earned_points' => $assignment_reply->get_earned_points(),
			'note'          => $assignment_reply->get_note(),
			'attachments'   => array( $assignment_reply->get_attachments() ),
			'auhtor'        => $author,
			'user'          => UserResource::to_array( $user ),
		);

		/**
		 * Filter assignment reply data array resource.
		 *
		 * @since 2.8.3
		 *
		 * @param array $data assignment reply.
		 * @param \Masteriyo\Addons\Assignment\Models\AssignmentReply $assignment_reply AssignmentReply object.
		 * @param string $context What the value is for. Valid values are view and edit.
		 */
		return apply_filters( 'masteriyo_assignment_reply_resource_array', $data, $assignment_reply, $context );
	}

	/**
	 * Get taxonomy terms if a course.
	 *
	 * @since 2.8.3
	 *
	 * @param \Masteriyo\Addons\Assignment\Models\AssignmentReply $assignment_reply AssignmentReply object.
	 * @param string $taxonomy Taxonomy slug.
	 *
	 * @return array
	 */
	protected static function get_taxonomy_terms( $assignment_reply, $taxonomy = 'cat' ) {
		$terms = Utils::get_object_terms( $assignment_reply->get_id(), 'assignment_reply_' . $taxonomy );

		$terms = array_map(
			function ( $term ) {
				return array(
					'id'   => $term->term_id,
					'name' => $term->name,
					'slug' => $term->slug,
				);
			},
			$terms
		);

		$terms = 'difficulty' === $taxonomy ? array_shift( $terms ) : $terms;

		return $terms;
	}
}
