<?php
namespace AcademyPro\ExportImport;

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


class Admin {

	public static function init() {
		$self = new self();
		// get topics data
		add_filter( 'academy_pro/export-import/get_quiz_data', [ $self, 'get_quiz_data' ] );
		add_filter( 'academy_pro/export-import/get_assignment_data', [ $self, 'get_assignment_data' ] );
		// insert topics data
		add_filter( 'academy_pro/export-import/insert_assignment_data', [ $self, 'insert_assignment_data' ] );
		add_filter( 'academy_pro/export-import/insert_quiz_data', [ $self, 'insert_quiz_data' ] );
		add_filter( 'academy_pro/export-import/insert_question_data', [ $self, 'insert_question_data' ], 10, 2 );
		add_filter( 'academy_pro/export-import/insert_answer_data', [ $self, 'insert_answer_data' ], 10, 3 );

	}

	public function get_quiz_data( $topic ) {
		$quiz = get_post( $topic['id'] );
		if ( empty( $quiz ) ) {
			return false;
		}
		$quiz_array[] = array(
			'quiz_title' => $quiz->post_title,
			'quiz_content' => $quiz->post_content,
			'quiz_time' => get_post_meta( $quiz->ID, 'academy_quiz_time', true ),
			'quiz_time_unit' => get_post_meta( $quiz->ID, 'academy_quiz_time_unit', true ),
			'quiz_hide_time' => get_post_meta( $quiz->ID, 'academy_quiz_hide_quiz_time', true ),
			'quiz_feedback_mode' => get_post_meta( $quiz->ID, 'academy_quiz_feedback_mode', true ),
			'quiz_passing_grade' => get_post_meta( $quiz->ID, 'academy_quiz_passing_grade', true ),
			'quiz_max_attempts_allowed' => get_post_meta( $quiz->ID, 'academy_quiz_max_attempts_allowed', true ),
			'quiz_questions_order' => get_post_meta( $quiz->ID, 'academy_quiz_questions_order', true ),
			'quiz_hide_question_number' => get_post_meta( $quiz->ID, 'academy_quiz_hide_question_number', true ),
		);

		$questions = \AcademyQuizzes\Classes\Query::get_questions_by_quid_id( $quiz->ID );

		foreach ( $questions as $question ) {
			$quiz_array[] = $this->prepare_question_for_csv( $question );
			$question_answers = $this->get_quiz_answers( $question->question_id, $question->question_type );
			foreach ( $question_answers as $question_answer ) {
				$quiz_array[] = $question_answer;
			}
		}

		return $quiz_array;
	}

	public function prepare_question_for_csv( $question ) {
		$settings = json_decode( $question->question_settings );
		return array(
			'question_title' => $question->question_title,
			'question_type' => $question->question_type,
			'question_points' => $question->question_score,
			'question_content' => $question->question_content,
			'question_status' => $question->question_status,
			'question_display_points' => $settings->display_points,
			'question_answer_required' => $settings->answer_required,
			'question_randomize' => $settings->randomize,
			'question_order' => $question->question_order,
		);
	}

	public function get_quiz_answers( $question_id, $question_type ) {
		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching 
		$answers = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT answer_id, quiz_id, answer_title, is_correct, answer_content, image_id, view_format, answer_order  FROM {$wpdb->prefix}academy_quiz_answers WHERE question_id=%d AND question_type=%s",
				$question_id,
				$question_type
			),
			OBJECT
		);

		$prepare_answers = [];

		foreach ( $answers as $answer ) {
			$prepare_answers[] = [
				'answer_title' => $answer->answer_title,
				'answer_content' => $answer->answer_content,
				'answer_is_correct' => $answer->is_correct,
				// phpcs:ignore Squiz.PHP.CommentedOutCode.Found
				// 'answer_image_id' => $answer->image_id,
				'answer_view_format' => $answer->view_format,
			];
		}

		return $prepare_answers;
	}

	public function get_assignment_data( $topic ) {
		$assignment = get_post( $topic['id'] );
		if ( ! empty( $assignment ) ) {
			$assignment_array = array(
				'assignment_title'       => $assignment->post_title,
				'assignment_content'     => $assignment->post_content,
				'assignment_author'      => $assignment->post_author,
				'assignment_status'      => $assignment->post_status,
				'assignment_attachment'  => 0,
				'assignment_settings'    => wp_json_encode( get_post_meta( $topic['id'], 'academy_assignment_settings', true ) ),
				'assignment_enable_resubmit' => get_post_meta( $topic['id'], 'academy_assignment_enable_resubmit', true ),
				'assignment_resubmit_limit' => get_post_meta( $topic['id'], 'academy_assignment_resubmit_limit', true ),
			);

			return $assignment_array;
		}
	}

	public function insert_assignment_data( $item ) {
		if ( empty( $item['assignment_title'] ) ) {
			return '';
		}

		$new_assignment_id = wp_insert_post( array(
			'post_title'       => sanitize_text_field( $item['assignment_title'] ),
			'post_content'     => sanitize_text_field( $item['assignment_content'] ),
			'post_author'      => sanitize_text_field( $item['assignment_author'] ),
			'post_status'      => sanitize_text_field( $item['assignment_status'] ),
			'post_type'        => 'academy_assignments',
		) );
		if ( $new_assignment_id ) {
			$settings = json_decode( sanitize_text_field( $item['assignment_settings'] ), true );
			add_post_meta( $new_assignment_id, 'assignment_attachment', 0 );
			add_post_meta( $new_assignment_id, 'academy_assignment_settings', $settings );
			$enable_resubmit = isset( $item['assignment_enable_resubmit'] ) ? $item['assignment_enable_resubmit'] : false;
			$resubmit_limit = isset( $item['assignment_resubmit_limit'] ) ? $item['assignment_resubmit_limit'] : 0;
			add_post_meta( $new_assignment_id, 'academy_assignment_enable_resubmit', $enable_resubmit );
			add_post_meta( $new_assignment_id, 'academy_assignment_resubmit_limit', $resubmit_limit );
			return $new_assignment_id;
		}
	}

	public function insert_quiz_data( $quiz_item ) {
		$quiz_title = ( isset( $quiz_item['quiz_title'] ) ? sanitize_text_field( $quiz_item['quiz_title'] ) : '' );
		$quiz_content = ( isset( $quiz_item['quiz_content'] ) ? sanitize_text_field( $quiz_item['quiz_content'] ) : '' );
		$quiz_time = (int) ( isset( $quiz_item['quiz_time'] ) ? sanitize_text_field( $quiz_item['quiz_time'] ) : 0 );
		$quiz_time_unit = ( isset( $quiz_item['quiz_time_unit'] ) ? sanitize_text_field( $quiz_item['quiz_time_unit'] ) : '' );
		$quiz_hide_time = (bool) ( isset( $quiz_item['quiz_hide_time'] ) ? sanitize_text_field( $quiz_item['quiz_hide_time'] ) : false );
		$quiz_feedback_mode = ( isset( $quiz_item['quiz_feedback_mode'] ) ? sanitize_text_field( $quiz_item['quiz_feedback_mode'] ) : '' );
		$quiz_passing_grade = (int) ( isset( $quiz_item['quiz_passing_grade'] ) ? sanitize_text_field( $quiz_item['quiz_passing_grade'] ) : 80 );
		$quiz_max_attempts_allowed = (int) ( isset( $quiz_item['quiz_max_attempts_allowed'] ) ? sanitize_text_field( $quiz_item['quiz_max_attempts_allowed'] ) : 10 );
		$quiz_question_order = ( isset( $quiz_item['quiz_questions_order'] ) ? sanitize_text_field( $quiz_item['quiz_questions_order'] ) : 'rnd' );
		$quiz_hide_question_number = (bool) ( isset( $quiz_item['quiz_hide_question_number'] ) ? sanitize_text_field( $quiz_item['quiz_hide_question_number'] ) : false );
		$quiz_meta = array(
			'academy_quiz_time' => $quiz_time,
			'academy_quiz_time_unit' => $quiz_time_unit,
			'academy_quiz_hide_quiz_time' => $quiz_hide_time,
			'academy_quiz_feedback_mode' => $quiz_feedback_mode,
			'academy_quiz_passing_grade' => $quiz_passing_grade,
			'academy_quiz_max_questions_for_answer' => 0,
			'academy_quiz_max_attempts_allowed' => $quiz_max_attempts_allowed,
			'academy_quiz_auto_start' => false,
			'academy_quiz_questions_order' => $quiz_question_order,
			'academy_quiz_hide_question_number' => $quiz_hide_question_number,
			'academy_quiz_short_answer_characters_limit' => 0,
			'academy_quiz_questions' => []
		);

		$new_quiz_id = wp_insert_post( array(
			'post_title' => $quiz_title,
			'post_type' => 'academy_quiz',
			'post_content' => $quiz_content,
			'post_status' => 'publish'
		) );
		foreach ( $quiz_meta as $key => $value ) {
			add_post_meta( $new_quiz_id, $key, $value, true );
		}
		return $new_quiz_id;
	}

	public function insert_question_data( $question_item, $new_quiz_id ) {
		global $wpdb;
		$question_title = ( isset( $question_item['question_title'] ) ? sanitize_text_field( $question_item['question_title'] ) : '' );
		if ( empty( $question_title ) ) {
			return '';
		}
		$question_type = ( isset( $question_item['question_type'] ) ? sanitize_text_field( $question_item['question_type'] ) : '' );
		$question_points = (float) ( isset( $question_item['question_points'] ) ? sanitize_text_field( $question_item['question_points'] ) : 5 );
		$question_description = ( isset( $question_item['question_description'] ) ? sanitize_text_field( $question_item['question_description'] ) : '' );
		$question_status = ( isset( $question_item['question_status'] ) ? sanitize_text_field( $question_item['question_status'] ) : '' );
		$question_display_points = (bool) ( isset( $question_item['question_display_points'] ) ? sanitize_text_field( $question_item['question_display_points'] ) : false );
		$question_answer_required = (bool) ( isset( $question_item['question_answer_required'] ) ? sanitize_text_field( $question_item['question_answer_required'] ) : false );
		$question_randomize = (bool) ( isset( $question_item['question_randomize'] ) ? sanitize_text_field( $question_item['question_randomize'] ) : false );
		$question_order = (int) ( isset( $question_item['question_order'] ) ? sanitize_text_field( $question_item['question_order'] ) : 0 );
		$question_array = [
			'quiz_id'               => $new_quiz_id,
			'question_title'        => $question_title,
			'question_name'         => '',
			'question_content'      => $question_description,
			'question_status'       => $question_status,
			'question_level'        => '',
			'question_type'         => $question_type,
			'question_score'        => $question_points,
			'question_order'        => $question_order,
			'question_settings'     => wp_json_encode(
				array(
					'display_points' => $question_display_points,
					'answer_required' => $question_answer_required,
					'randomize'  => $question_randomize,
				)
			),
		];
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching 
		$questions = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM {$wpdb->prefix}academy_quiz_questions WHERE quiz_id = %d AND question_title LIKE %s",
				$new_quiz_id,
				'%' . $wpdb->esc_like( sanitize_text_field( $question_title ) ) . '%'
			)
		);
		if ( $questions && count( $questions ) ) {
			foreach ( $questions as $question ) {
				$new_question_id = $question->question_id;
			}
		} else {
			$new_question_id = \AcademyQuizzes\Classes\Query::quiz_question_insert( $question_array );
			$new_quiz_question = (array) get_post_meta( $new_quiz_id, 'academy_quiz_questions', true );
			$new_quiz_question = array_reduce( $new_quiz_question, function( $carry, $item ) use ( $question_title ) {
				if ( isset( $item['question_title'] ) && $item['question_title'] !== $question_title ) {
					$carry[] = $item;
				}
				return $carry;
			}, []);
			$new_quiz_question[] = array(
				'id' => $new_question_id,
				'title' => $question_title,
			);
			// Update the 'academy_quiz_questions' post meta with the updated array of questions
			update_post_meta( $new_quiz_id, 'academy_quiz_questions', $new_quiz_question );
		}//end if
		return $new_question_id;
	}

	public function insert_answer_data( $answer_item, $new_quiz_id, $new_question_id ) {
		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching 
		$answers = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM {$wpdb->prefix}academy_quiz_answers WHERE answer_title LIKE %s AND question_id = %d ",
				'%' . $wpdb->esc_like( sanitize_text_field( $answer_item['answer_title'] ) ) . '%', $new_question_id
			)
		);
		if ( ! $answers && ! count( $answers ) ) {
			$question = \AcademyQuizzes\Classes\Query::get_quiz_question( $new_question_id );
			\AcademyQuizzes\Classes\Query::quiz_answer_insert( [
				'quiz_id' => $new_quiz_id,
				'question_id' => $new_question_id,
				'question_type' => $question->question_type,
				'answer_title' => sanitize_text_field( $answer_item['answer_title'] ),
				'answer_content' => sanitize_text_field( $answer_item['answer_content'] ),
				'is_correct' => (bool) sanitize_text_field( $answer_item['answer_is_correct'] ),
				// phpcs:ignore Squiz.PHP.CommentedOutCode.Found
				// 'image_id' => $answer_items['answer_image_id'],
				'view_format' => sanitize_text_field( $answer_item['answer_view_format'] ),

			] );
		}
	}

}
