<?php
namespace QuizPress\Ajax;

use QuizPress\API\Controller\Questions;

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

class Import extends Questions {
	public static function init() {
		$self = new self();
		add_action( 'wp_ajax_quizpress/import_quiz', [ $self, 'import_quizpress_quiz' ] );
	}

	public function import_quizpress_quiz() {
		global $wpdb;

		check_admin_referer( 'quizpress_nonce', 'security' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action.', 'quizpress' ) );
		}

		if ( empty( $_FILES['upload_file']['tmp_name'] ) ) {
			wp_send_json_error( __( 'No file uploaded.', 'quizpress' ) );
		}

		$file = $_FILES['upload_file'];// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

		// Validate CSV file type and extension.
		$file_ext = strtolower( pathinfo( $file['name'], PATHINFO_EXTENSION ) );
		if ( 'csv' !== $file_ext ) {
			wp_send_json_error( __( 'Invalid file format. Please upload a CSV file.', 'quizpress' ) );
		}

		// Safely open uploaded CSV.
		$handle = fopen( $file['tmp_name'], 'r' );// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen 
		if ( false === $handle ) {
			wp_send_json_error( __( 'Unable to read uploaded file.', 'quizpress' ) );
		}

		$question_header = [];
		$answer_header   = [];
		$has_question    = false;
		$has_answer      = false;
		$new_question_id = 0;
		$question_ids    = [];

		while ( ( $row = fgetcsv( $handle, null, ',', '"', '\\' ) ) !== false ) {

			// Detect question header.
			if ( in_array( 'question_title', $row, true ) ) {
				$question_header = array_map( 'strtolower', array_map( 'trim', $row ) );
				$has_question    = true;
				$has_answer      = false;
				continue;
			}

			// Detect answer header.
			if ( in_array( 'answer_title', $row, true ) ) {
				$answer_header = array_map( 'strtolower', array_map( 'trim', $row ) );
				$has_question  = false;
				$has_answer    = true;
				continue;
			}

			if ( $has_question ) {
				$question_item = array_combine( $question_header, $row );

				$question_title = sanitize_text_field( $question_item['question_title'] ?? '' );
				if ( empty( $question_title ) ) {
					continue;
				}

				$question_array = [
					'question_title'          => $question_title,
					'question_name'           => '',
					'question_content'        => sanitize_textarea_field( $question_item['question_description'] ?? '' ),
					'question_explanation'    => sanitize_textarea_field( $question_item['question_explanation'] ?? '' ),
					'question_status'         => sanitize_text_field( $question_item['question_status'] ?? '' ),
					'question_level'          => '',
					'question_type'           => sanitize_text_field( $question_item['question_type'] ?? '' ),
					'answer_type'             => sanitize_text_field( $question_item['answer_type'] ?? '' ),
					'question_score'          => floatval( $question_item['question_score'] ?? 5 ),
					'question_order'          => intval( $question_item['question_order'] ?? 0 ),
					'question_negative_score' => floatval( $question_item['question_negative_score'] ?? 0 ),
					'question_settings'       => wp_json_encode(
						[
							'display_points'  => filter_var( $question_item['question_display_points'] ?? false, FILTER_VALIDATE_BOOLEAN ),
							'answer_required' => filter_var( $question_item['question_answer_required'] ?? false, FILTER_VALIDATE_BOOLEAN ),
							'random_answer'   => filter_var( $question_item['question_random_answer'] ?? false, FILTER_VALIDATE_BOOLEAN ),
						]
					),
					'category_ids'            => null,
				];

				// Check for duplicate questions.
				$existing = (int) $wpdb->get_var(
					$wpdb->prepare(
						"SELECT question_id FROM {$wpdb->prefix}quizpress_questions WHERE question_title = %s",
						$question_title
					)
				);

				if ( ! $existing ) {
					$new_question_id = \QuizPress\API\Query\Questions::quiz_question_insert( $question_array );
				}

				$question_ids[] = $new_question_id ?? $existing;

				$has_question = false;
			} elseif ( $has_answer && ! empty( $new_question_id ) ) {
				$answer_item = array_combine( $answer_header, $row );
				$answer_title = sanitize_text_field( $answer_item['answer_title'] ?? '' );

				if ( empty( $answer_title ) ) {
					continue;
				}

				$exists = $wpdb->get_var(
					$wpdb->prepare(
						"SELECT answer_id FROM {$wpdb->prefix}quizpress_answers WHERE answer_title = %s AND question_id = %d",
						$answer_title,
						$new_question_id
					)
				);

				if ( $exists ) {
					continue;
				}

				\QuizPress\API\Query\Answers::quiz_answer_insert( [
					'question_id'   => $new_question_id,
					'answer_title'  => $answer_title,
					'image_id'      => 0,
					'answer_content' => sanitize_textarea_field( $answer_item['answer_content'] ?? '' ),
					'is_correct'    => (int) filter_var( $answer_item['is_correct'] ?? false, FILTER_VALIDATE_BOOLEAN ),
					'answer_order'  => '',
				] );
			}//end if
		}//end while

		fclose( $handle );// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose

		$questions_data = \QuizPress\API\Query\Questions::get_questions_by_ids( $question_ids );

		foreach ( $questions_data as &$question_data ) {
			$question_data = (object) $this->rest_prepare_item( $question_data );
			$question_data->answers = \QuizPress\API\Query\Answers::get_question_answers_by_question_id( $question_data->question_id );
			foreach ( $question_data->answers as &$answer ) {
				$answer = \QuizPress\API\Controller\Answers::prepare_answer_for_response( (object) $answer );
			}
		}
		unset( $question_data ); // break reference

		wp_send_json_success( $questions_data );
	}

}
