<?php
namespace QuizPress;

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

class Database {
	public static function init() {
		$self = new self();
		add_action( 'init', [ $self, 'create_quizpress_post_types' ] );
		add_action( 'rest_api_init', [ $self, 'register_quizpress_meta' ] );
		// Run late so it overrides third-party REST fields registered at the default priority.
		add_action( 'rest_api_init', [ $self, 'remove_foreign_rest_fields' ], 20 );
	}

	/**
	 * Strip read-only REST fields that other plugins register against every post
	 * type. They are exposed without a `readonly` schema flag, so WP treats them
	 * as writable params on the quiz endpoint and rejects saves with
	 * "Invalid parameter(s)" when the editor round-trips them back.
	 */
	public function remove_foreign_rest_fields() {
		global $wp_rest_additional_fields;

		$post_type = 'quizpress_quiz';

		// Nexter Blocks (the-plus-addons-for-block-editor) computed fields.
		$foreign_fields = [
			'tpgb_post_meta_info',
			'tpgb_post_category',
			'tpgb_featured_images',
		];

		foreach ( $foreign_fields as $field ) {
			unset( $wp_rest_additional_fields[ $post_type ][ $field ] );
		}
	}

	public static function create_initial_custom_table() {
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		global $wpdb;
		$prefix          = $wpdb->prefix;
		$charset_collate = $wpdb->get_charset_collate();
		Database\CreateQuestionsTable::up( $prefix, $charset_collate );
		Database\CreateAnswersTable::up( $prefix, $charset_collate );
		Database\CreateAttemptsTable::up( $prefix, $charset_collate );
		Database\CreateAttemptAnswersTable::up( $prefix, $charset_collate );
		Database\CreateCategoryTable::up( $prefix, $charset_collate );
	}

	public function create_quizpress_post_types() {
		$post_type = 'quizpress_quiz';
		register_post_type(
			$post_type,
			array(
				'labels'                => array(
					'name'                  => esc_html__( 'Quizzes', 'quizpress' ),
					'singular_name'         => esc_html__( 'quiz', 'quizpress' ),
					'search_items'          => esc_html__( 'Search quizzes', 'quizpress' ),
					'parent_item_colon'     => esc_html__( 'Parent quizzes:', 'quizpress' ),
					'not_found'             => esc_html__( 'No quizzes found.', 'quizpress' ),
					'not_found_in_trash'    => esc_html__( 'No quizzes found in Trash.', 'quizpress' ),
					'archives'              => esc_html__( 'quiz archives', 'quizpress' ),
				),
				'public'                => true,
				'publicly_queryable'    => true,
				'show_ui'               => false,
				'show_in_menu'          => false,
				'hierarchical'          => false,
				'rewrite'               => array( 'slug' => 'quiz' ),
				'query_var'             => true,
				'has_archive'           => true,
				'delete_with_user'      => false,
				'map_meta_cap'          => true,
				'supports'              => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'custom-fields', 'comments', 'post-formats' ),
				'show_in_rest'          => true,
				'rest_base'             => $post_type,
				'rest_namespace'        => QUIZPRESS_PLUGIN_SLUG . '/v1',
				'rest_controller_class' => 'WP_REST_Posts_Controller',
				'capability_type'           => 'post',
				'capabilities'              => array(
					'edit_post'             => 'edit_quizpress_quiz',
					'read_post'             => 'read_quizpress_quiz',
					'delete_post'           => 'delete_quizpress_quiz',
					'delete_posts'          => 'delete_quizpress_quizzes',
					'edit_posts'            => 'edit_quizpress_quizzes',
					'edit_others_posts'     => 'edit_others_quizpress_quizzes',
					'publish_posts'         => 'publish_quizpress_quizzes',
					'read_private_posts'    => 'read_private_quizpress_quizzes',
					'create_posts'          => 'edit_quizpress_quizzes',
				),
			)
		);

		register_taxonomy(
			$post_type . '_category',
			$post_type,
			array(
				'hierarchical'          => true,
				'query_var'             => $post_type . '_category',
				'rewrite'               => false,
				'public'                => true,
				'show_ui'               => false,
				'show_admin_column'     => false,
				'capabilities'          => array(
					'manage_terms' => 'manage_categories',
					'edit_terms'   => 'edit_categories',
					'delete_terms' => 'delete_categories',
					'assign_terms' => 'assign_categories',
				),
				'show_in_rest'          => true,
				'rest_base'             => $post_type . '_category',
				'rest_controller_class' => '\QuizPress\API\Controller\Terms',
			)
		);

		register_taxonomy(
			$post_type . '_tag',
			$post_type,
			array(
				'hierarchical'          => false,
				'query_var'             => $post_type . '_tag',
				'rewrite'               => false,
				'public'                => true,
				'show_ui'               => false,
				'show_admin_column'     => false,
				'capabilities'          => array(
					'manage_terms' => 'manage_post_tags',
					'edit_terms'   => 'edit_post_tags',
					'delete_terms' => 'delete_post_tags',
					'assign_terms' => 'assign_post_tags',
				),
				'show_in_rest'          => true,
				'rest_base'             => $post_type . '_tag',
				'rest_controller_class' => '\QuizPress\API\Controller\Terms',
			)
		);
	}

	public function register_quizpress_meta() {
		$quiz_meta = [
			// Quiz Type Identification
			'quizpress_quiz_type'                       => 'string',   // e.g. quiz, poll, survey
			'quizpress_quiz_hint_text'                  => 'string',  // hint text for user

			// Timing & Flow
			'quizpress_quiz_time'                       => 'integer',  // duration value
			'quizpress_quiz_time_unit'                  => 'string',   // seconds, minutes, hours
			'quizpress_quiz_hide_quiz_time'             => 'boolean',
			'quizpress_quiz_auto_start'                 => 'boolean',
			'quizpress_quiz_schedule_enabled'           => 'boolean', // Whether scheduling is active
			'quizpress_quiz_start_datetime'             => 'string',  // Format: YYYY-MM-DD HH:MM:SS
			'quizpress_quiz_end_datetime'               => 'string',
			'quizpress_quiz_force_all_questions_required' => 'boolean', // Forcefully all questions required

			// Grading & Attempts
			'quizpress_quiz_passing_grade'              => 'integer',  // % required to pass
			'quizpress_quiz_grade_system'               => 'string',  // % required grading system like point
			'quizpress_quiz_max_attempts_allowed'       => 'integer',
			'quizpress_quiz_max_questions_for_answer'   => 'integer', // for long quizzes, limits how many are shown

			// Question Behavior
			'quizpress_quiz_questions_order'            => 'string',   // e.g. 'random', 'default', 'reverse'
			'quizpress_quiz_hide_question_number'       => 'boolean',
			'quizpress_quiz_short_answer_characters_limit' => 'integer',

			// Feedback
			'quizpress_quiz_feedback_mode'              => 'string',   // e.g. 'instant', 'after_submit', 'none'
			'quizpress_quiz_explanation_enabled'        => 'boolean', // after_submitted question explanation is show or hide

			// New Suggestions
			'quizpress_quiz_show_correct_answers'       => 'boolean',  // after submission
			'quizpress_quiz_allow_review'               => 'boolean',  // allow user to review questions
			'quizpress_quiz_show_score'                 => 'boolean',  // show score at end
			'quizpress_quiz_anonymous'                  => 'boolean',  // for polls/surveys

			// Display & UI
			'quizpress_quiz_layout'                     => 'string',   // e.g. 'one-per-page', 'all-in-one'
			'quizpress_quiz_start_button_label'         => 'string',   // customizable start button
			'quizpress_quiz_submit_button_label'        => 'string',   // customizable submit button
			'quizpress_quiz_pass_reattempt'             => 'boolean',   // customizable submit button

			// product integration
			'quizpress_quiz_product_id'                 => 'integer',
			'quizpress_quiz_product_type'               => 'string',
			'quizpress_quiz_sale_price'                 => 'integer',
			'quizpress_quiz_regular_price'              => 'integer',
			'quizpress_quiz_product_currency'           => 'string',
		];

		foreach ( $quiz_meta as $meta_key => $meta_value_type ) {
			register_meta(
				'post',
				$meta_key,
				array(
					'object_subtype' => 'quizpress_quiz',
					'type'           => $meta_value_type,
					'single'         => true,
					'show_in_rest'   => true,
				)
			);
		}

		register_meta(
			'post',
			'quizpress_quiz_questions',
			array(
				'object_subtype' => 'quizpress_quiz',
				'type'           => 'array',
				'single'         => true,
				'show_in_rest'   => [
					'schema' => array(
						'items' => array(
							'type'       => 'object',
							'properties' => [
								'id'   => array(
									'type' => 'integer',
								),
								'title' => array(
									'type' => 'string',
								),
							],
						),
					),
				],
			)
		);
	}

}
