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

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

/**
 * Class MasterQuiz_Shortcode
 *
 * Registers and renders the [masterquiz_ai] shortcode.
 *
 * @since 1.0.0
 */
class MasterQuiz_Shortcode {

	/**
	 * Render the shortcode output.
	 *
	 * @since 1.0.0
	 *
	 * @param array $atts Shortcode attributes.
	 * @return string Shortcode HTML output.
	 */
	public function render( $atts ) {
		$atts = shortcode_atts(
			array(
				'title'          => __( 'PDF to Quiz Generator', 'masterquiz-ai' ),
				'show_header'    => 'true',
				'show_learndash' => 'auto',
				'max_questions'  => '',
			),
			$atts,
			'masterquiz_ai'
		);

		// Enqueue assets only when shortcode is actually used.
		wp_enqueue_style( 'masterquiz-public' );
		wp_enqueue_script( 'masterquiz-public' );

		// Determine LearnDash visibility.
		$learndash_active = class_exists( 'SFWD_LMS' ) && defined( 'LEARNDASH_VERSION' );
		$show_learndash   = 'auto' === $atts['show_learndash'] ? $learndash_active : ( 'true' === $atts['show_learndash'] );

		// Max questions from shortcode attribute or settings.
		$max_questions = ! empty( $atts['max_questions'] )
			? absint( $atts['max_questions'] )
			: absint( get_option( 'masterquiz_default_num_questions', 5 ) );

		// Build JavaScript configuration object.
		// Rendered inline via wp_print_inline_script_tag() in the shortcode HTML
		// for reliable output in block themes (FSE) where wp_localize_script and
		// wp_add_inline_script data can be lost during block rendering.
		$config = array(
			'ajaxUrl'         => admin_url( 'admin-ajax.php' ),
			'nonce'           => wp_create_nonce( 'masterquiz_nonce' ),
			'maxFileSize'     => absint( get_option( 'masterquiz_max_pdf_size', 10 ) ) * 1024 * 1024,
			'maxQuestions'    => $max_questions,
			'minQuestions'    => 3,
			'defaultMode'     => sanitize_text_field( get_option( 'masterquiz_default_quiz_mode', 'fast' ) ),
			'defaultTypes'    => get_option( 'masterquiz_default_question_types', array( 'mcq', 'true_false', 'essay' ) ),
			'learndashActive' => $learndash_active,
			'showLearndash'   => $show_learndash,
			'autoCreateLd'    => (bool) get_option( 'masterquiz_auto_create_quiz', 1 ),
			'samplePdfUrl'    => MASTERQUIZ_PLUGIN_URL . 'public/sample/sample.pdf',
			// i18n strings use __() instead of esc_html__() because they are output
			// inside a <script> tag via wp_json_encode(), which handles JS escaping.
			// HTML-escaping would double-encode entities (e.g. &amp; instead of &).
			'i18n'            => array(
				'dropzoneText'       => __( 'Drop your PDF here or browse', 'masterquiz-ai' ),
				'uploading'          => __( 'Uploading PDF...', 'masterquiz-ai' ),
				'generating'         => __( 'Generating quiz...', 'masterquiz-ai' ),
				'completed'          => __( 'Quiz generated successfully!', 'masterquiz-ai' ),
				'failed'             => __( 'Quiz generation failed. Please try again.', 'masterquiz-ai' ),
				'downloadAll'        => __( 'Download All Formats', 'masterquiz-ai' ),
				'createLdQuiz'       => __( 'Create LearnDash Quiz', 'masterquiz-ai' ),
				'ldQuizCreated'      => __( 'LearnDash quiz created!', 'masterquiz-ai' ),
				'previous'           => __( 'Previous', 'masterquiz-ai' ),
				'next'               => __( 'Next', 'masterquiz-ai' ),
				'question'           => __( 'Question', 'masterquiz-ai' ),
				'of'                 => __( 'of', 'masterquiz-ai' ),
				'points'             => __( 'points', 'masterquiz-ai' ),
				'correct'            => __( 'Correct', 'masterquiz-ai' ),
				'incorrect'          => __( 'Incorrect', 'masterquiz-ai' ),
				'modelAnswer'        => __( 'Model Answer', 'masterquiz-ai' ),
				'hint'               => __( 'Hint', 'masterquiz-ai' ),
				'fileTooLarge'       => __( 'File is too large. Maximum size is', 'masterquiz-ai' ),
				'invalidFileType'    => __( 'Please select a PDF file.', 'masterquiz-ai' ),
				'selectFile'         => __( 'Please select a PDF file first.', 'masterquiz-ai' ),
				'generateQuiz'       => __( 'Generate Quiz', 'masterquiz-ai' ),
				'generating_btn'     => __( 'Generating...', 'masterquiz-ai' ),
				'exportFormats'      => __( 'Export Formats', 'masterquiz-ai' ),
				'fast'               => __( 'Fast', 'masterquiz-ai' ),
				'quality'            => __( 'Quality', 'masterquiz-ai' ),
				'mcq'                => __( 'Multiple Choice', 'masterquiz-ai' ),
				'trueFalse'          => __( 'True / False', 'masterquiz-ai' ),
				'essay'              => __( 'Essay', 'masterquiz-ai' ),
				'numQuestions'       => __( 'Number of Questions', 'masterquiz-ai' ),
				'quizMode'           => __( 'Generation Mode', 'masterquiz-ai' ),
				'questionTypes'      => __( 'Question Types', 'masterquiz-ai' ),
			),
		);

		// Set template variables.
		$title       = sanitize_text_field( $atts['title'] );
		$show_header = 'true' === $atts['show_header'];

		// JSON-encode config for inline output via wp_print_inline_script_tag().
		// Output directly in shortcode HTML because wp_localize_script and
		// wp_add_inline_script data can be lost in block-theme (FSE) rendering
		// pipelines where the template is rendered before wp_footer fires.
		$config_json = wp_json_encode( $config );

		ob_start();
		wp_print_inline_script_tag(
			'var masterquizConfig = ' . $config_json . ';',
			array( 'id' => 'masterquiz-public-config' )
		);
		include MASTERQUIZ_PLUGIN_DIR . 'public/views/shortcode-template.php';
		return ob_get_clean();
	}
}
