<?php
namespace QuizPress;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

use QuizPress;
use QuizPress\API\Controller\Analytics;
use QuizPress\API\Controller\Leaderboard;
use QuizPress\API\Controller\Questions;
use QuizPress\API\Controller\Attempts;
use QuizPress\API\Controller\Answers;
use QuizPress\API\Controller\MagicLogin;

class API {
	public static function init() {
		$self = new self();
		Analytics::init();
		Leaderboard::init();
		Questions::init();
		Attempts::init();
		Answers::init();
		MagicLogin::init();
		API\Settings::init();
		add_filter( 'the_content', [ self::class, 'quizpress_disable_autop_for_rest' ], 0 );
		add_filter( 'rest_prepare_quizpress_quiz', [ $self, 'modify_quiz_rest_response' ], 10, 3 );
	}

	public static function quizpress_disable_autop_for_rest( $content ) {
		if ( defined( 'REST_REQUEST' ) && REST_REQUEST && get_post_type() === 'quizpress_quiz' ) {
			remove_filter( 'the_content', 'wpautop' );
		}
		return $content;
	}

	public function modify_quiz_rest_response( $response, $post, $request ) {
		if ( isset( $response->data['content'] ) ) {
			$response->data['content']['rendered'] = html_entity_decode( $response->data['content']['rendered'] ?? '' );
			$response->data['content']['raw']      = html_entity_decode( $response->data['content']['raw'] ?? '' );
		}

		if( ! current_user_can('manage_options') || 'GET' !== $request->get_method() ) {
			return $response;
		}
		$quiz_id = $post->ID;
		// Get question IDs from post meta
		$questions = get_post_meta( $quiz_id, 'quizpress_quiz_questions', true );
		$question_ids = array_column( (array) $questions, 'id' );

		if ( empty( $question_ids ) ) {
			$data = $response->get_data();
			$data['questions'] = array();
			$response->set_data( $data );
			return $response;
		}

		// Get questions data in a single query
		$questions_data = \QuizPress\API\Query\Questions::get_questions_by_ids( $question_ids );

		foreach ( $questions_data as &$question_data ) {
			$question_data->question_settings = json_decode( $question_data->question_settings, true );
			$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( $answer );
			}
		}
		unset( $question_data ); // break reference

		// Modify REST response
		$data = $response->get_data();
		$data['questions'] = $questions_data;
		$response->set_data( $data );
		
		return $response;
	}

}
