<?php
/**
 * AJAX request handler.
 *
 * @package MasterQuiz
 * @since   1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class MasterQuiz_Ajax_Handler
 *
 * Handles all AJAX endpoints for the plugin.
 *
 * @since 1.0.0
 */
class MasterQuiz_Ajax_Handler {

	/**
	 * Verify nonce and check user capability.
	 *
	 * @since 1.0.0
	 *
	 * @return bool True if authorized, sends JSON error and dies otherwise.
	 */
	private function verify_request() {
		check_ajax_referer( 'masterquiz_nonce', 'nonce' );

		// Only enforce capability check for logged-in users.
		// Non-logged-in users are allowed via wp_ajax_nopriv_ hooks (nonce still protects against CSRF).
		if ( is_user_logged_in() ) {
			$required_cap = get_option( 'masterquiz_minimum_capability', 'edit_posts' );

			if ( ! current_user_can( $required_cap ) ) {
				wp_send_json_error(
					array( 'message' => esc_html__( 'You do not have permission to perform this action.', 'masterquiz-ai' ) ),
					403
				);
			}
		}

		return true;
	}

	/**
	 * Handle PDF file upload.
	 *
	 * @since 1.0.0
	 */
	public function handle_upload() {
		$this->verify_request();

		$upload_handler = new MasterQuiz_Upload_Handler();
		$result         = $upload_handler->process_upload();

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success( $result );
	}

	/**
	 * Handle quiz generation request.
	 *
	 * @since 1.0.0
	 */
	public function handle_generate() {
		$this->verify_request();

		// Sanitize inputs (nonce verified in verify_request above).
		// phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce verified via $this->verify_request().
		$quiz_title     = sanitize_text_field( wp_unslash( $_POST['quiz_title'] ?? '' ) );
		$num_questions  = absint( $_POST['num_questions'] ?? get_option( 'masterquiz_default_num_questions', 5 ) );
		$quiz_mode      = sanitize_text_field( wp_unslash( $_POST['quiz_mode'] ?? 'fast' ) );
		$auto_learndash = absint( $_POST['auto_learndash'] ?? 0 );
		$course_id      = absint( $_POST['course_id'] ?? 0 );
		// phpcs:enable WordPress.Security.NonceVerification.Missing

		// Validate quiz mode.
		if ( ! in_array( $quiz_mode, array( 'fast', 'quality' ), true ) ) {
			$quiz_mode = 'fast';
		}

		// Validate num questions (hard cap: 5).
		$num_questions = max( 3, min( 5, $num_questions ) );

		// Sanitize question types (nonce verified by verify_request above).
		$question_types = array();
		// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput -- nonce verified via verify_request; each element sanitized in loop.
		if ( isset( $_POST['question_types'] ) && is_array( $_POST['question_types'] ) ) {
			$valid_types = array( 'mcq', 'true_false', 'essay' );
			foreach ( wp_unslash( $_POST['question_types'] ) as $type ) {
				$type = sanitize_text_field( $type );
				if ( in_array( $type, $valid_types, true ) ) {
					$question_types[] = $type;
				}
			}
		}
		// phpcs:enable WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput

		if ( empty( $question_types ) ) {
			$question_types = get_option( 'masterquiz_default_question_types', array( 'mcq', 'true_false', 'essay' ) );
		}

		// Retrieve upload reference.
		$upload_data = get_transient( 'masterquiz_upload_' . get_current_user_id() );

		if ( empty( $upload_data ) || empty( $upload_data['file_path'] ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'No PDF file found. Please upload a file first.', 'masterquiz-ai' ) ) );
		}

		// Create job.
		$job_id      = 'pqg_' . wp_generate_password( 12, false );
		$owner_token = wp_generate_password( 32, false );
		$job_data    = array(
			'id'          => $job_id,
			'status'      => 'queued',
			'progress'    => 0,
			'message'     => esc_html__( 'Quiz generation queued...', 'masterquiz-ai' ),
			'user_id'     => get_current_user_id(),
			'owner_token' => $owner_token,
			'created_at'  => time(),
			'updated_at'  => time(),
			'input'       => array(
				'file_path'      => $upload_data['file_path'],
				'quiz_title'     => $quiz_title,
				'num_questions'  => $num_questions,
				'question_types' => $question_types,
				'quiz_mode'      => $quiz_mode,
				'auto_learndash' => $auto_learndash,
				'course_id'      => $course_id,
			),
			'result'      => null,
			'error'       => null,
		);

		set_transient( 'masterquiz_job_' . $job_id, $job_data, HOUR_IN_SECONDS );

		// Schedule background processing.
		$background = new MasterQuiz_Background_Process();
		$background->schedule_generation( $job_id );

		wp_send_json_success(
			array(
				'job_id'      => $job_id,
				'owner_token' => $owner_token,
				'message'     => esc_html__( 'Quiz generation started.', 'masterquiz-ai' ),
			)
		);
	}

	/**
	 * Handle job status polling.
	 *
	 * @since 1.0.0
	 */
	public function handle_job_status() {
		$this->verify_request();

		// phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended -- nonce verified via $this->verify_request().
		$job_id   = sanitize_text_field( wp_unslash( $_GET['job_id'] ?? $_POST['job_id'] ?? '' ) );
		$job_data = get_transient( 'masterquiz_job_' . $job_id );

		if ( empty( $job_data ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Job not found.', 'masterquiz-ai' ) ) );
		}

		// Run inline immediately when still queued — WP Cron loopback is unreliable
		// on most hosts and waiting even a few seconds adds noticeable delay.
		if ( 'queued' === $job_data['status'] ) {
			// Extend PHP execution time for inline processing.
			if ( function_exists( 'set_time_limit' ) ) {
				set_time_limit( 120 ); // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- required for long-running AI API calls.
			}

			$background = new MasterQuiz_Background_Process();
			$background->process_job( $job_id );

			// Re-fetch updated job data.
			$job_data = get_transient( 'masterquiz_job_' . $job_id );
		}

		$response = array(
			'status'   => $job_data['status'],
			'progress' => $job_data['progress'],
			'message'  => $job_data['message'] ?? '',
		);

		if ( 'completed' === $job_data['status'] ) {
			$quiz_data           = get_transient( 'masterquiz_quiz_' . $job_id );
			$response['quiz']    = $quiz_data;
			$response['ld_quiz'] = $job_data['result']['ld_quiz'] ?? null;
		}

		if ( 'failed' === $job_data['status'] ) {
			$response['error'] = $job_data['error'];
		}

		wp_send_json_success( $response );
	}

	/**
	 * Save edits made to a generated quiz.
	 *
	 * Only user-editable fields are merged into the existing server-side quiz
	 * so generation metadata and exporter-required structure remain intact.
	 *
	 * @since 1.0.4
	 */
	public function handle_update_quiz() {
		$this->verify_request();

		// Nonce verified above; JSON fields are sanitized individually after decoding.
		// phpcs:disable WordPress.Security.NonceVerification.Missing
		// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$job_id      = sanitize_text_field( wp_unslash( $_POST['job_id'] ?? '' ) );
		$owner_token = sanitize_text_field( wp_unslash( $_POST['owner_token'] ?? '' ) );
		$raw_quiz    = isset( $_POST['quiz'] ) ? wp_unslash( $_POST['quiz'] ) : '';
		// phpcs:enable WordPress.Security.NonceVerification.Missing
		// phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

		if ( empty( $job_id ) || ! is_string( $raw_quiz ) ) {
			wp_send_json_error(
				array( 'message' => esc_html__( 'Invalid quiz update request.', 'masterquiz-ai' ) ),
				400
			);
		}

		if ( strlen( $raw_quiz ) > 262144 ) {
			wp_send_json_error(
				array( 'message' => esc_html__( 'The quiz data is too large to save.', 'masterquiz-ai' ) ),
				413
			);
		}

		$job_data  = get_transient( 'masterquiz_job_' . $job_id );
		$quiz_data = get_transient( 'masterquiz_quiz_' . $job_id );

		if ( empty( $job_data ) || empty( $quiz_data ) ) {
			wp_send_json_error(
				array( 'message' => esc_html__( 'Quiz data not found. It may have expired.', 'masterquiz-ai' ) ),
				404
			);
		}

		$stored_token = isset( $job_data['owner_token'] ) ? (string) $job_data['owner_token'] : '';
		$token_valid  = ( '' !== $stored_token && hash_equals( $stored_token, $owner_token ) );
		$same_user    = (int) ( $job_data['user_id'] ?? 0 ) === get_current_user_id() && is_user_logged_in();

		if ( ! $token_valid && ! $same_user ) {
			wp_send_json_error(
				array( 'message' => esc_html__( 'You do not have permission to edit this quiz.', 'masterquiz-ai' ) ),
				403
			);
		}

		$quiz_edits = json_decode( $raw_quiz, true );

		if ( ! is_array( $quiz_edits ) || JSON_ERROR_NONE !== json_last_error() ) {
			wp_send_json_error(
				array( 'message' => esc_html__( 'The quiz data could not be read.', 'masterquiz-ai' ) ),
				400
			);
		}

		$updated_quiz = $this->sanitize_quiz_edits( $quiz_data, $quiz_edits );

		if ( is_wp_error( $updated_quiz ) ) {
			wp_send_json_error(
				array( 'message' => $updated_quiz->get_error_message() ),
				400
			);
		}

		set_transient( 'masterquiz_quiz_' . $job_id, $updated_quiz, DAY_IN_SECONDS );

		wp_send_json_success(
			array(
				'message' => esc_html__( 'Quiz changes saved.', 'masterquiz-ai' ),
				'quiz'    => $updated_quiz,
			)
		);
	}

	/**
	 * Handle export file download.
	 *
	 * @since 1.0.0
	 */
	public function handle_export() {
		$this->verify_request();

		// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended -- nonce verified via $this->verify_request().
		$job_id = sanitize_text_field( wp_unslash( $_GET['job_id'] ?? $_POST['job_id'] ?? '' ) );
		$format = sanitize_text_field( wp_unslash( $_GET['format'] ?? $_POST['format'] ?? 'json' ) );
		// phpcs:enable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended

		// Validate format.
		$valid_formats = array( 'json', 'xml', 'csv', 'txt', 'gift', 'qti', 'aiken', 'learndash_csv', 'learndash_xml' );
		if ( ! in_array( $format, $valid_formats, true ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Invalid export format.', 'masterquiz-ai' ) ) );
		}

		$quiz_data = get_transient( 'masterquiz_quiz_' . $job_id );

		if ( empty( $quiz_data ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Quiz data not found. It may have expired.', 'masterquiz-ai' ) ) );
		}

		$exporter = new MasterQuiz_Exporter();
		$exporter->export( $quiz_data, $format );
		exit;
	}

	/**
	 * Handle LearnDash quiz creation from generated quiz data.
	 *
	 * @since 1.0.0
	 */
	public function handle_create_learndash_quiz() {
		$this->verify_request();

		if ( ! is_user_logged_in() ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Please log in as an administrator to create LearnDash quizzes.', 'masterquiz-ai' ) ) );
		}

		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'You do not have permission to create quizzes.', 'masterquiz-ai' ) ), 403 );
		}

		if ( ! MasterQuiz_Learndash::is_active() ) {
			wp_send_json_error( array( 'message' => esc_html__( 'LearnDash is not active.', 'masterquiz-ai' ) ) );
		}

		// phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce verified via $this->verify_request().
		$job_id    = sanitize_text_field( wp_unslash( $_POST['job_id'] ?? '' ) );
		$course_id = absint( $_POST['course_id'] ?? 0 );
		// phpcs:enable WordPress.Security.NonceVerification.Missing

		$quiz_data = get_transient( 'masterquiz_quiz_' . $job_id );

		if ( empty( $quiz_data ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Quiz data not found. It may have expired.', 'masterquiz-ai' ) ) );
		}

		$learndash = new MasterQuiz_Learndash();
		$result    = $learndash->create_quiz(
			$quiz_data,
			array(
				'course_id'   => $course_id,
				'passing_pct' => absint( get_option( 'masterquiz_quiz_passing_percentage', 80 ) ),
			)
		);

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success(
			array(
				'quiz_id'  => $result['quiz_post_id'],
				'edit_url' => get_edit_post_link( $result['quiz_post_id'], 'raw' ),
				'view_url' => get_permalink( $result['quiz_post_id'] ),
				'message'  => sprintf(
				/* translators: %d: number of questions created */
					esc_html__( 'LearnDash quiz created with %d questions.', 'masterquiz-ai' ),
					$result['question_count']
				),
			)
		);
	}

	/**
	 * Handle API key testing.
	 *
	 * @since 1.0.0
	 */
	public function handle_test_api_key() {
		check_ajax_referer( 'masterquiz_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Permission denied.', 'masterquiz-ai' ) ), 403 );
		}

		$provider = sanitize_key( wp_unslash( $_POST['provider'] ?? '' ) );

		if ( ! in_array( $provider, array( 'gemini', 'openrouter', 'groq' ), true ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Invalid provider.', 'masterquiz-ai' ) ) );
		}

		// Accept API key from POST (unsaved form input) or fall back to stored key.
		$raw_key = isset( $_POST['api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['api_key'] ) ) : '';
		$api_key = ! empty( $raw_key ) ? $raw_key : MasterQuiz_Settings::get_api_key( $provider );

		if ( empty( $api_key ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Please enter an API key and try again.', 'masterquiz-ai' ) ) );
		}

		$chain  = new MasterQuiz_Provider_Chain();
		$result = $chain->test_provider( $provider, $api_key );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success(
			array(
				'message' => esc_html__( 'Connection successful!', 'masterquiz-ai' ),
			)
		);
	}

	/**
	 * Sanitize editable quiz fields and merge them into stored quiz data.
	 *
	 * @since 1.0.4
	 *
	 * @param array $quiz_data  Existing server-side quiz data.
	 * @param array $quiz_edits Submitted editable quiz fields.
	 * @return array|WP_Error Updated quiz data or validation error.
	 */
	private function sanitize_quiz_edits( $quiz_data, $quiz_edits ) {
		$title = sanitize_text_field( $quiz_edits['quiz_title'] ?? '' );

		if ( '' === $title ) {
			return new WP_Error(
				'masterquiz_empty_title',
				esc_html__( 'Please enter a quiz title.', 'masterquiz-ai' )
			);
		}

		if ( empty( $quiz_data['questions'] ) || ! is_array( $quiz_data['questions'] ) ) {
			return new WP_Error(
				'masterquiz_missing_questions',
				esc_html__( 'The stored quiz does not contain any questions.', 'masterquiz-ai' )
			);
		}

		$edited_questions = $quiz_edits['questions'] ?? array();

		if ( ! is_array( $edited_questions ) || count( $edited_questions ) !== count( $quiz_data['questions'] ) ) {
			return new WP_Error(
				'masterquiz_question_count_mismatch',
				esc_html__( 'The number of quiz questions cannot be changed.', 'masterquiz-ai' )
			);
		}

		$quiz_data['quiz_title'] = $title;

		foreach ( $quiz_data['questions'] as $question_index => &$question ) {
			$edited_question = $edited_questions[ $question_index ] ?? null;

			if ( ! is_array( $edited_question ) ) {
				return new WP_Error(
					'masterquiz_invalid_question',
					esc_html__( 'One or more questions contain invalid data.', 'masterquiz-ai' )
				);
			}

			$question_text = sanitize_textarea_field( $edited_question['question_text'] ?? '' );

			if ( '' === $question_text ) {
				return new WP_Error(
					'masterquiz_empty_question',
					esc_html__( 'Question text cannot be empty.', 'masterquiz-ai' )
				);
			}

			$question['question_text'] = $question_text;
			$question['hint']          = sanitize_textarea_field( $edited_question['hint'] ?? '' );

			if ( array_key_exists( 'explanation', $question ) || array_key_exists( 'explanation', $edited_question ) ) {
				$question['explanation'] = sanitize_textarea_field( $edited_question['explanation'] ?? '' );
			}

			if ( array_key_exists( 'model_answer', $question ) || array_key_exists( 'model_answer', $edited_question ) ) {
				$question['model_answer'] = sanitize_textarea_field( $edited_question['model_answer'] ?? '' );
			}

			if ( array_key_exists( 'rubric_criteria', $question ) || array_key_exists( 'rubric_criteria', $edited_question ) ) {
				$question['rubric_criteria'] = $this->sanitize_string_list( $edited_question['rubric_criteria'] ?? array() );
			}

			$original_options = $question['options'] ?? array();
			$edited_options   = $edited_question['options'] ?? array();

			if (
				! is_array( $original_options )
				|| ! is_array( $edited_options )
				|| count( $original_options ) !== count( $edited_options )
			) {
				return new WP_Error(
					'masterquiz_option_count_mismatch',
					esc_html__( 'The number of answer options cannot be changed.', 'masterquiz-ai' )
				);
			}

			$correct_ids   = array();
			$correct_text  = '';
			$correct_count = 0;

			foreach ( $original_options as $option_index => &$option ) {
				$edited_option = $edited_options[ $option_index ] ?? null;

				if ( ! is_array( $edited_option ) ) {
					return new WP_Error(
						'masterquiz_invalid_option',
						esc_html__( 'One or more answer options contain invalid data.', 'masterquiz-ai' )
					);
				}

				$option_text = sanitize_textarea_field( $edited_option['text'] ?? '' );

				if ( '' === $option_text ) {
					return new WP_Error(
						'masterquiz_empty_option',
						esc_html__( 'Answer options cannot be empty.', 'masterquiz-ai' )
					);
				}

				if ( ! is_array( $option ) ) {
					$option = array(
						'id'      => 'option_' . ( $option_index + 1 ),
						'text'    => $option_text,
						'correct' => false,
					);
				}

				$option['id']      = sanitize_text_field( $option['id'] ?? 'option_' . ( $option_index + 1 ) );
				$option['text']    = $option_text;
				$option['correct'] = ! empty( $edited_option['correct'] );

				if ( array_key_exists( 'rationale', $option ) || array_key_exists( 'rationale', $edited_option ) ) {
					$option['rationale'] = sanitize_textarea_field( $edited_option['rationale'] ?? '' );
				}

				if ( $option['correct'] ) {
					++$correct_count;
					$correct_text  = $option_text;
					$correct_ids[] = $option['id'];
				}
			}
			unset( $option );

			if ( ! empty( $original_options ) && 1 !== $correct_count ) {
				return new WP_Error(
					'masterquiz_invalid_correct_answer',
					esc_html__( 'Each choice question must have exactly one correct answer.', 'masterquiz-ai' )
				);
			}

			$question['options']            = $original_options;
			$question['correct_answer_ids'] = $correct_ids;

			if ( array_key_exists( 'correct_answer', $question ) ) {
				$question['correct_answer'] = $correct_text;
			}
		}
		unset( $question );

		$quiz_data['question_count'] = count( $quiz_data['questions'] );

		return $quiz_data;
	}

	/**
	 * Sanitize a list of plain-text values.
	 *
	 * @since 1.0.4
	 *
	 * @param mixed $values Values to sanitize.
	 * @return array Sanitized non-empty values.
	 */
	private function sanitize_string_list( $values ) {
		if ( ! is_array( $values ) ) {
			return array();
		}

		$sanitized = array();

		foreach ( $values as $value ) {
			$value = sanitize_textarea_field( $value );

			if ( '' !== $value ) {
				$sanitized[] = $value;
			}
		}

		return $sanitized;
	}
}
