<?php
/**
 * Merge page.
 *
 * @package EaLab\WP_Deployer
 */

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

/**
 * Requires.
 */
require_once __DIR__ . '/component/deployment-item--diff.php';
require_once __DIR__ . '/utility/deployment-item.php';

use EaLab\WP_Deployer\vendor\Ealab\Deployer\Diff\Differ;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Exception\WpDeployException;

/**
 * Merge page.
 *
 * @throws WpDeployException If the Deploy & Sync Content plugin is not ready.
 */
function deploy_sync_content__admin_merge(): void {
	$form_context = sanitize_text_field( wp_unslash( $_GET['form_context'] ?? '' ) );
	$subdirectory = sanitize_text_field( wp_unslash( $_GET['deployment_bundle'] ) );
	$all_uuids    = sanitize_text_field( wp_unslash( $_GET['uuid'] ) );
	$diff_mode    = sanitize_text_field( wp_unslash( $_GET['tab'] ?? 'diff' ) ) === 'merge' ? 'InteractiveSideBySide' : 'DscSideBySide';

	$all_uuids         = is_array( $all_uuids ) ? $all_uuids : explode( ',', $all_uuids );
	$primary_item_uuid = reset( $all_uuids );

	if ( empty( $subdirectory ) || empty( $primary_item_uuid ) ) {
		return;
	}

	if ( ! in_array( $form_context, array( 'import', 'export' ) ) ) {
		return;
	}

	$items_for_import = deploy_sync_content__get_items_for_import( $subdirectory, $all_uuids );

	$context = array(
		'form_context' => $form_context,
		'bundle_id'    => $subdirectory,
		'diff_mode'    => $diff_mode,
	);

	if ( '1' !== sanitize_text_field( wp_unslash( $_GET['embed_mode'] ?? '' ) ) ) {
		// We are not in an embed mode.
		// Build the return button.
		$args = array(
			'page' => 'deploy-sync-content',
		);

		if ( 'import' === $form_context ) {
			$args['tab']            = $form_context;
			$args['bundletoimport'] = $subdirectory;
		} elseif ( 'export' === $form_context ) {
			$args['tab']       = $form_context;
			$args['bundle_id'] = $subdirectory;
		}

		$url = add_query_arg(
			$args,
			admin_url( 'admin.php' )
		);

		?>
		<a data-return href="<?php echo esc_url( $url ) ?>"
			class="button button-primary mt-2"><?php echo esc_html__( 'Return', 'deploy-sync-content' ) ?></a>
		<?php
	}

	$is_merging = 'InteractiveSideBySide' === $context['diff_mode'];

	if ( $is_merging ) {
		$endpoint_args = array(
			'deployment_bundle' => $context['bundle_id'],
			'form_context'      => $context['form_context'] ?? null,
			'page'              => 'deploy-sync-content',
			'tab'               => 'merge',
			'uuid'              => $all_uuids,
		);

		if ( ! empty( sanitize_text_field( wp_unslash( $_GET['embed_mode'] ?? '' ) ) ) ) {
			// Transfer the embed mode to the form submission.
			$endpoint_args['embed_mode'] = sanitize_text_field( $_GET['embed_mode'] );
		}

		$action = add_query_arg(
			$endpoint_args,
			admin_url( 'admin.php' )
		);

		// Add the nonce to the URL. This is a requirement to be in the URL and not in the form input values.
		// Putting the nonce in a form input is possible, but the form input values are
		// encapsulated into a json encoded object on submit, and not sent in the form data format ($_POST),
		// so it would require from us to move the nonce verification from the route manager level
		// to the route implementation (which is meh).
		$action = wp_nonce_url( $action, DEPLOY_SYNC_CONTENT__SLUG . 'merge' );

		?>
		<form action="<?php echo esc_attr( $action ) ?>" class="mt-3 submitted-as-json" id="deploy-sync-content--merge" method="post">
		<button type="submit"
			class="button button-primary loader"><?php echo esc_html__( 'Merge', 'deploy-sync-content' ) ?></button>
		<?php
	}

	$page_description = $is_merging
		? __( 'You are currently merging the following differences.', 'deploy-sync-content' )
		: __( 'You are currently viewing the following differences.', 'deploy-sync-content' );

	?>
	<div><?php echo esc_html( $page_description ) ?></div>
	<?php

	foreach ( $items_for_import as $item_full_uuid => $item ) {
		$differ_result = new Deploy_Sync_Content__State();

		// Compute the diff right now.
		$diff_output = deploy_sync_content__deployment_item__diff( $item, array_merge( $context, array( 'differ_result' => $differ_result ) ) );

		switch ( $differ_result->result ) {
			case Differ::DIFF_RESULT__NEW:
				$differ_result_label          = esc_html__( 'New', 'deploy-sync-content' );
				$differ_result_bg_color_class = 'alert-success';
				break;

			case Differ::DIFF_RESULT__MODIFIED:
				$differ_result_label          = esc_html__( 'Modified', 'deploy-sync-content' );
				$differ_result_bg_color_class = 'alert-warning';
				break;

			case Differ::DIFF_RESULT__SAME:
				$differ_result_label          = esc_html__( 'Identical', 'deploy-sync-content' );
				$differ_result_bg_color_class = 'alert-info';
				break;

			case Differ::DIFF_RESULT__ERROR:
			default:
				$differ_result_label          = esc_html__( 'Error', 'deploy-sync-content' );
				$differ_result_bg_color_class = 'alert-error';
				break;
		}

		?>
		<div class="my-4">
			<div>
				<div
					class="border border-bottom-0 d-flex rounded-top sticky-top deploy-sync-content--sticky p-2 <?php echo esc_attr( $differ_result_bg_color_class ) ?>">
					<div class="col">
						<div class="item-label">
							<?php deploy_sync_content__deployment_item__label_uuid( deploy_sync_content__deployment_item__label_from_item( $item, $context ), $item_full_uuid, $context ) ?>
						</div>
					</div>
					<div class='align-items-center d-flex'><?php echo esc_html( $differ_result_label ) ?></div>
				</div>
				<div class="border border-top-0 border-bottom-0 p-3">
					<?php echo wp_kses( $diff_output, 'deploy_sync_content__diff_output' ) ?>
				</div>
			</div>
			<div class="border border-top-0 rounded-bottom pb-1"></div>
		</div>
		<?php
	}

	if ( $is_merging ) {
		?>
		</form>
		<?php
	}
}
