<?php

if ( ! function_exists( 'academy_pro_assignments_added_frontend_dashboard_menu' ) ) {
	function academy_pro_assignments_added_frontend_dashboard_menu( $menu ) {
		if ( current_user_can( 'manage_academy_instructor' ) ) {
			$menu['assignments'] = array(
				'label' => __( 'Assignments', 'academy-pro' ),
				'icon'  => 'academy-icon academy-icon--assignment-stoke',
				'public' => true,
				'priority' => 38,
				'child_items' => [
					'submitted-assignments'           => array(
						'label'         => __( 'Submitted Assign.', 'academy-pro' ),
						'public' => true,
						'priority' => 38,
					),
				]
			);
		}
		return $menu;
	}
}

if ( ! function_exists( 'academy_pro_assignments_frontend_dashboard_assignments_page' ) ) {
	function academy_pro_assignments_frontend_dashboard_assignments_page() {
		\AcademyPro\Helper::get_template(
			'frontend-dashboard/pages/assignment.php',
		);
	}
}

/**
 * Php lesson rendering template functions goes here
 */

if ( ! function_exists( 'academy_pro_assignment_curriculum_assignment_content' ) ) {
	function academy_pro_assignment_curriculum_assignment_content( $course_id, $assignment_id ) {

		$assignment = get_post( $assignment_id );

		do_action( 'academy/templates/curriculums/before_render_assignment_content', $assignment, $course_id, $assignment_id );

		$has_permission = \Academy\Helper::has_permission_to_access_curriculum( $course_id );

		if ( ! apply_filters( 'academy/templates/curriculums/has_access_assignment_content', $has_permission ) ) {
			return;
		}

		if ( $assignment ) {
			\AcademyPro\Helper::get_template(
				'curriculums/assignment.php',
				array(
					'course_id' => $course_id,
					'assignment_id' => $assignment_id,
				)
			);
		} else {
			\Academy\Helper::get_template( 'curriculums/not-found.php' );
		}

		do_action( 'academy/templates/curriculums/after_render_assignment_content', $assignment, $course_id, $assignment_id );
	}
}//end if

if ( ! function_exists( 'academy_pro_assignment_start_assignment' ) ) {
	function academy_pro_assignment_start_assignment() {
		$security = isset( $_POST['security'] ) ? sanitize_text_field( wp_unslash( $_POST['security'] ) ) : '';
		if ( ! wp_verify_nonce( $security, 'academy_nonce' ) ) {
			wp_die( 'Nonce Verification Failed.' );
		}

		$assignment_id    = isset( $_POST['assignment_id'] ) ? sanitize_text_field( wp_unslash( $_POST['assignment_id'] ) ) : '';
		$course_id        = isset( $_POST['course_id'] ) ? sanitize_text_field( wp_unslash( $_POST['course_id'] ) ) : '';
		$current_user     = wp_get_current_user();
		$submitting_time  = gmdate( 'Y-m-d h:i:s' );
		$referer_url = \Academy\Helper::sanitize_referer_url( wp_get_referer() );
		$is_administrator = current_user_can( 'administrator' );
		$is_instructor    = \Academy\Helper::is_instructor_of_this_course( $current_user->ID, $course_id );
		$is_enrolled      = \Academy\Helper::is_enrolled( $course_id, $current_user->ID );
		$is_public_course = \Academy\Helper::is_public_course( $course_id );

		if ( ! $assignment_id || ! $course_id ) {
			wp_die( 'Course or assignment id not found' );
		}

		$submitting_assignments = get_comments( array(
			'post_id'      => $assignment_id,
			'parent'       => $course_id,
			'user_id'      => $current_user->ID,
			'comment_type' => 'academy_assignments',
			'status'       => array( 'submitted', 'submitting', 'pass', 'failed' )
		) );

		if ( $submitting_assignments ) {
			wp_die( 'Assignmnet already started' );
		}

		if ( $is_administrator || $is_instructor || $is_enrolled || $is_public_course ) {
			$commentdata = array(
				'comment_post_ID'      => $assignment_id,
				'comment_parent'       => $course_id,
				'user_id'              => $current_user->ID,
				'comment_author'       => $current_user->user_login,
				'comment_author_email' => $current_user->user_email,
				'comment_author_url'   => $current_user->user_url,
				'comment_approved'     => 'submitting',
				'comment_agent'        => 'academy',
				'comment_type'         => 'academy_assignments',
				'comment_meta'         => array(
					'academy_pro_assignment_start_time' => $submitting_time,
				)
			);

			if ( wp_insert_comment( $commentdata ) ) {
				wp_safe_redirect( $referer_url );
				exit;
			}
		}//end if
	}
}//end if

if ( ! function_exists( 'academy_pro_assignment_submit_assignment' ) ) {
	function academy_pro_assignment_submit_assignment() {
		$security = isset( $_POST['security'] ) ? sanitize_text_field( wp_unslash( $_POST['security'] ) ) : '';
		if ( ! wp_verify_nonce( $security, 'academy_nonce' ) ) {
			wp_die( 'Nonce verification failed.' );
		}

		$course_id = isset( $_POST['course_id'] ) ? sanitize_text_field( wp_unslash( $_POST['course_id'] ) ) : '';
		$assignment_id = isset( $_POST['assignment_id'] ) ? sanitize_text_field( wp_unslash( $_POST['assignment_id'] ) ) : '';
		$assignment_ans = isset( $_POST['assignment_ans'] ) ? sanitize_text_field( wp_unslash( $_POST['assignment_ans'] ) ) : '';
		$assignment_comment_id = isset( $_POST['assignment_comment_id'] ) ? sanitize_text_field( wp_unslash( $_POST['assignment_comment_id'] ) ) : '';
		$submitting_time = gmdate( 'Y-m-d h:i:s' );
		$referer_url = \Academy\Helper::sanitize_referer_url( wp_get_referer() );

		if ( empty( $assignment_ans ) && empty( $_FILES['attachment']['name'] ) ) {
			wp_die(
				esc_html__( 'Please provide an Assignment answer or attachment', 'academy-pro' )
			);
		}

		$current_user           = wp_get_current_user();
		$is_administrator       = current_user_can( 'administrator' );
		$is_instructor          = \Academy\Helper::is_instructor_of_this_course( $current_user->ID, $course_id );
		$is_enrolled               = \Academy\Helper::is_enrolled( $course_id, $current_user->ID );
		$is_public_course = \Academy\Helper::is_public_course( $course_id );

		$started_assignment = get_comment( $assignment_comment_id );

		if ( ! $started_assignment ) {
			wp_die( esc_html( $assignment_comment_id ) );
		}

		if ( $is_administrator || $is_instructor || $is_enrolled || $is_public_course ) {
			// first check submission is expired or not
			$assignment           = get_post( $assignment_id );
			$assignment->settings = get_post_meta( $assignment_id, 'academy_assignment_settings', true );
			$enable_resubmit      = get_post_meta( $assignment_id, 'academy_assignment_enable_resubmit', true );

			$assignment_attachment = 0;
			if ( ! empty( sanitize_text_field( $_FILES['attachment']['name'] ) ) ) {
				$allowed_extension = array( 'jpg', 'jpeg', 'gif', 'png', 'pdf', 'docx', 'zip' );

				// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized 
				$extension = pathinfo( $_FILES['attachment']['name'], PATHINFO_EXTENSION );

				if ( ! in_array( strtolower( $extension ), $allowed_extension, true ) ) {
					wp_die( esc_html( $extension . ' extension is not allowed.' ) );
				}

				$assignment_attachment = media_handle_upload( 'attachment', $assignment_id );
			}

			// Update comment
			$data = array(
				'comment_ID'       => $assignment_comment_id,
				'comment_post_ID'  => $assignment_id,
				'comment_content'  => $assignment_ans,
				'comment_date_gmt' => $started_assignment->comment_date_gmt,
				'comment_approved' => 'submitted',
				'comment_meta'     => array(
					'academy_pro_assignment_end_time'   => $submitting_time,
					'academy_pro_assignment_attachment' => $assignment_attachment,
				)
			);

			if ( ! $assignment_attachment ) {
				unset( $data['comment_meta']['academy_pro_assignment_attachment'] );
			}
			$resubmit_limit = get_post_meta( $assignment_id, 'academy_assignment_resubmit_limit', true );
			if ( $enable_resubmit && $resubmit_limit > 0 ) {
				$option_key = 'academy_pro_assignment_' . $assignment_comment_id . '_submission_attempt';
				$assignment_attempt = get_option( $option_key, 0 );
				if ( $assignment_attempt >= $resubmit_limit ) {
					wp_send_json_error( __( 'You have reached the maximum number of submission attempts.', 'academy-pro' ) );
				}
				$assignment_attempt++;
				update_option( $option_key, $assignment_attempt );
			}
			wp_update_comment( $data );
			wp_safe_redirect( $referer_url );
			exit;
		}//end if
	}
}//end if
