<?php
/**
 * Controller for the "synchronize" route.
 */

namespace EaLab\WP_Deployer\includes\controller;

use EaLab\WP_Deployer\vendor\Dakwamine\Component\RootDependencyDefinition;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Exception\WpDeployException;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Utility\FileManager;

/**
 * Controller for the "synchronize" route.
 */
class SynchronizePageController extends PageControllerBase {
	/**
	 * Deploy & Sync Content file manager.
	 *
	 * @var FileManager|null
	 */
	private ?FileManager $file_manager = null;

	/**
	 * The import controller.
	 *
	 * @var Import_Form_Handler|null
	 */
	private ?Import_Form_Handler $import_form_handler = null;

	public function getDependencyDefinitions(): array {
		$definitions = parent::getDependencyDefinitions();

		$definitions[] = new RootDependencyDefinition( FileManager::class, $this->file_manager );
		$definitions[] = new RootDependencyDefinition( Import_Form_Handler::class, $this->import_form_handler );

		return $definitions;
	}

	public function handle( array $route_info ): void {
		if ( ! sanitize_text_field( wp_unslash( $_GET['bundletoimport'] ?? '' ) ) ) {
			// There is no bundle to show. It's probably an error.
			// Redirect to the plugin base page.
			wp_safe_redirect( admin_url( DEPLOY_SYNC_CONTENT__BASIC_URI ) );
			exit;
		}

		// Show the bundle content to the user.
		$this->show_bundle_content();
	}

	private function show_bundle_content(): void {
		$context = array(
			'date_field_id' => 'bundletoimport',
		);

		?>
		<div class="container-deploy-sync-content-options">
			<?php
			require_once DEPLOY_SYNC_CONTENT__PLUGIN_DIR . 'admin/partials/utility/date.php';
			$datetime = deploy_sync_content__get_datetime_from_url_param( $context['date_field_id'] );

			if ( ! empty( $datetime ) ) :
				try {
					// At this point, we have a valid datetime, so we don't need to check it again.
					$bundle_id = sanitize_text_field( wp_unslash( $_GET[ $context['date_field_id'] ] ) );

					require_once DEPLOY_SYNC_CONTENT__PLUGIN_DIR . 'admin/partials/bundle-ui-v2-assets.php';

					$reactive_json_data_endpoint = add_query_arg(
						array(
							'bundle_id' => $bundle_id,
						),
						get_rest_url( null, 'deploy-sync-content/v1/deployment-bundle/synchronize-form-data' )
					);
					?>
					<hr>
					<reactive-json data-url="<?php echo esc_attr( $reactive_json_data_endpoint ); ?>">
						<data-source-request-header data-header-field="X-WP-Nonce"
							data-header-value="<?php echo esc_attr( wp_create_nonce( 'wp_rest' ) ) ?>"></data-source-request-header>
					</reactive-json>
					<?php
				} catch ( WpDeployException $e ) {
					// The given bundle subdirectory is invalid.
					?>
					<div><?php wp_kses_post( $e->getMessage() ); ?></div>
					<?php
				}
			endif;
			?>
		</div>
		<?php
	}
}
