<?php
namespace QuizPress\Integration;

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

use QuizPress\Helper;

class NexterBlocks {

	protected $plugin = 'the-plus-addons-for-block-editor/the-plus-addons-for-block-editor.php';

	/**
	 * Top-level REST fields injected by The Plus Addons for all post types.
	 */
	protected $tpgb_rest_fields = array(
		'tpgb_featured_images',
		'tpgb_post_meta_info',
		'tpgb_post_category',
		'tpgb_product_data',
	);

	public static function init() {
		$self = new static();

		if ( ! $self->is_plugin_active() ) {
			return;
		}

		// Strip TPGB fields from GET responses so the React app never echoes them back.
		add_filter( 'rest_prepare_quizpress_quiz', array( $self, 'strip_tpgb_from_response' ), 20, 3 );

		// Strip TPGB fields from POST/PUT/PATCH requests BEFORE WordPress validates the schema.
		// Must use rest_pre_dispatch — rest_request_before_callbacks fires after validation.
		add_filter( 'rest_pre_dispatch', array( $self, 'strip_tpgb_from_request' ), 10, 3 );
	}

	protected function is_plugin_active() {
		return Helper::is_plugin_active( $this->plugin );
	}

	/**
	 * Remove TPGB top-level fields and meta keys from quiz GET responses.
	 */
	public function strip_tpgb_from_response( $response, $post, $request ) {
		$data = $response->get_data();

		// Remove top-level TPGB REST fields.
		foreach ( $this->tpgb_rest_fields as $field ) {
			unset( $data[ $field ] );
		}

		// Remove any tpgb_* meta keys.
		if ( isset( $data['meta'] ) && is_array( $data['meta'] ) ) {
			foreach ( array_keys( $data['meta'] ) as $key ) {
				if ( strpos( $key, 'tpgb' ) !== false ) {
					unset( $data['meta'][ $key ] );
				}
			}
		}

		$response->set_data( $data );
		return $response;
	}

	/**
	 * Remove TPGB top-level fields and meta keys from incoming quiz write requests,
	 * before WordPress validates them against the REST schema.
	 *
	 * rest_pre_dispatch fires before WP_REST_Server::dispatch() validates route args,
	 * so returning null here lets normal processing continue with the cleaned request.
	 */
	public function strip_tpgb_from_request( $result, $server, $request ) {
		$route = $request->get_route();

		if ( strpos( $route, '/quizpress/v1/quizpress_quiz' ) === false ) {
			return $result;
		}

		if ( ! in_array( $request->get_method(), array( 'POST', 'PUT', 'PATCH' ), true ) ) {
			return $result;
		}

		// Remove top-level TPGB REST fields (registered globally via register_rest_field).
		foreach ( $this->tpgb_rest_fields as $field ) {
			unset( $request[ $field ] );
		}

		// Remove any tpgb_* meta keys (registered globally via register_meta without object_subtype).
		$meta = $request->get_param( 'meta' );
		if ( is_array( $meta ) ) {
			foreach ( array_keys( $meta ) as $key ) {
				if ( strpos( $key, 'tpgb' ) !== false ) {
					unset( $meta[ $key ] );
				}
			}
			$request->set_param( 'meta', $meta );
		}

		return $result; // null — continue normal processing.
	}
}
