<?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.
		$num_questions = max( 3, min( 12, $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 );
		$job_data = array(
			'id'         => $job_id,
			'status'     => 'queued',
			'progress'   => 0,
			'message'    => esc_html__( 'Quiz generation queued...', 'masterquiz-ai' ),
			'user_id'    => get_current_user_id(),
			'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,
			'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' ) ) );
		}

		// Fallback: if job is still queued after 3 seconds, run inline.
		// WP Cron loopback is unreliable on most hosts; processing inline early
		// avoids a ~15-second dead wait and speeds up quiz generation significantly.
		if ( 'queued' === $job_data['status'] && ( time() - $job_data['created_at'] ) > 3 ) {
			// 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 );
	}

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