<?php

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

add_filter(
	'deploy_sync_content__routes',
	static function ( array $routes = array() ): array {
		$handle_route_callback = static function () {
			wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['deploy_sync_content__nonce'] ) ), DEPLOY_SYNC_CONTENT__SLUG . 'importpost' );

			if ( isset( $_POST['submit-updatepost'] ) && isset( $_POST['redirect-url'] ) && isset( $_POST['data-to-import'] ) ) {
				// Note: the data-to-import value is base64 encoded to
				// work around the WP issue which slashes the POST values.
				$b64_decoded     = base64_decode( sanitize_text_field( wp_unslash( $_POST['data-to-import'] ) ) );
				$items_to_import = json_decode( $b64_decoded ?? '[]', true );

				if ( ! empty( $items_to_import ) ) {
					$importer = \EaLab\WP_Deployer\vendor\Dakwamine\Component\ComponentBasedObject::getRootComponentByClassName( \EaLab\WP_Deployer\vendor\Ealab\Deployer\Import\Importer::class, true );
					$rest_ret = $importer->importItems( $items_to_import, true );
				}
				wp_redirect( esc_url_raw( wp_unslash( $_POST['redirect-url'] ) ) );
				exit();
			}
		};

		$routes['importpost'] = [
			'id'                    => 'importpost',
			'label'                 => __( 'Import post', 'deploy-sync-content' ),
			'handle_route_callback' => $handle_route_callback,
		];

		return $routes;
	},
	-10
);
