<?php

namespace EaLab\WP_Deployer\includes\Rest\DeploymentBundle;

use EaLab\WP_Deployer\includes\Rest\RestBase;

class SynchronizeFormDataRest extends RestBase {
	static public function registerRestHooks(): void {
		parent::registerRestHooks();

		// Special code to alter item data only for synchronize form data.
		add_filter(
			'deploy_sync_content__interactive_form_blueprint_item_data_alter',
			static function ( array $current_item_output, array $context, object $build_info, array $deployment_item ): array {
				if ( ( $context['form_context'] ?? null ) !== 'import' ) {
					return $current_item_output;
				}

				if ( ! in_array( 'display:synchronize', $context['form_context_tags'] ?? array(), true ) ) {
					return $current_item_output;
				}

				switch ( $deployment_item['tracker'] ?? null ) {
					case 'posts':
						// Append the post_type.
						$current_item_output['contentType'] = $deployment_item['fields']['posts.post_type'] ?? '';

						// Assign a fake post type if there is none.
						$content_type = $deployment_item['fields']['posts.post_type'] ?? 'other';
						break;

					case 'terms':
					case 'term_relationships':
					case 'term_taxonomy':
						$current_item_output['contentType'] = 'terms';
						$content_type                       = 'terms';
						break;

					case 'comments':
						$current_item_output['contentType'] = 'comments';
						$content_type                       = 'comments';
						break;
				}

				if ( ! empty( $content_type ) ) {
					$build_info->SynchronizeFormDataRest                                           = $build_info->SynchronizeFormDataRest ?? array();
					$build_info->SynchronizeFormDataRest['availableContentTypes'][ $content_type ] = $content_type;
				}

				return $current_item_output;
			},
			-10,
			4
		);

		// Special code to alter item data only for synchronize form data.
		add_filter(
			'deploy_sync_content__interactive_form_blueprint_alter',
			static function ( array $blueprint, array $context, object $build_info ): array {
				if ( ( $context['form_context'] ?? null ) !== 'import' ) {
					return $blueprint;
				}

				if ( ! in_array( 'display:synchronize', $context['form_context_tags'] ?? array(), true ) ) {
					return $blueprint;
				}

				if ( property_exists( $build_info, 'SynchronizeFormDataRest' ) ) {
					foreach ( $build_info->SynchronizeFormDataRest['availableContentTypes'] ?? array() as $post_type ) {
						// This is needed for post type tabs.
						$blueprint['data']['contentTypes'][] = array(
							'label' => strtoupper( $post_type ),
							'type'  => $post_type,
						);
					}

					if ( ! empty( $blueprint['data']['contentTypes'] ) ) {
						// Display the first item by default.
						$blueprint['data']['__state']['displayedPostType'] = reset( $blueprint['data']['contentTypes'] )['type'];
					}
				}

				return $blueprint;
			},
			-10,
			3
		);
	}

	static public function getRegisterRestRouteDefinitions(): array {
		$args = parent::getRegisterRestRouteDefinitions();

		$args[] = array(
			'route' => '/deployment-bundle/synchronize-form-data',
			'args'  => array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( static::class, 'handle' ),
				'permission_callback' => static function () {
					// If the request is from the admin, we allow it.
					return in_array( 'administrator', wp_get_current_user()->roles ?? array(), true );
				},
			),
		);

		return $args;
	}

	static public function handle( \WP_REST_Request $request ) {
		$response    = array();
		$status_code = 200;

		try {
			$bundle_id = $request->get_param( 'bundle_id' );

			require_once DEPLOY_SYNC_CONTENT__PLUGIN_DIR . 'includes/interactive-form--get-data--import.php';
			$response = deploy_sync_content__interactive_form__get_data__import(
				$bundle_id,
				array(
					'form_context_tags' => array( 'display:synchronize' ),
				)
			);
		} catch ( \Throwable $t ) {
			$status_code         = 500;
			$response['message'] = esc_html( $t->getMessage() );
		}

		return new \WP_REST_Response( $response, $status_code );
	}
}
