<?php
/**
 * Code Snippet Revisions Page (compare UI).
 *
 * @package CodeSnippet
 * @since 1.0.0
 */

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

$revisions_instance = $revisions_instance ?? null;
$snippet_id         = $snippet_id ?? 0;
$revision_id        = $revision_id ?? 0;
$compare            = $compare ?? false;
$compare_title      = $compare_title ?? '';
$back_url           = $back_url ?? admin_url( 'admin.php?page=powersuite-code-snippet' );

if ( ! $revisions_instance || $snippet_id <= 0 ) {
	echo '<div class="wrap"><p>' . esc_html__( 'Invalid revision.', 'wp-powersuite' ) . '</p></div>';
	return;
}

$revisions = array_reverse( $revisions_instance->get_snippet_revisions( $snippet_id ) );
$current_revision = 0;
$revision_ids = [];
foreach ( $revisions as $key => $rev ) {
	if ( (int) $rev->revision_id === (int) $revision_id ) {
		$current_revision = $key;
	}
	$revision_ids[] = (int) $rev->revision_id;
}
$total = count( $revisions ) - 1;

$default_data = [
	'title'             => '',
	'code'              => '',
	'code_type'         => '',
	'location'          => '',
	'location_label'    => '',
	'auto_insert'       => false,
	'priority'           => '',
	'notes'             => '',
	'custom_shortcode'  => '',
];

$base_url = defined( 'WP_POWERSUITE_PLUGIN_URL' ) ? WP_POWERSUITE_PLUGIN_URL : '';
wp_enqueue_script( 'jquery-ui-slider' );
wp_enqueue_style( 'wpps-cs-admin', $base_url . 'modules/code-snippet/assets/cs-admin.css', [], \CodeSnippet\Module::MODULE_VERSION );
?>
<div class="wrap wpps-cs-wrap wpps-cs-revisions-wrap">
	<hr class="wp-header-end">
	<div class="wpps-cs-revisions-header">
		<div>
			<h1 class="wpps-cs-revisions-title">
				<?php
				printf(
					/* translators: %s: snippet title */
					esc_html__( 'Compare Revisions of "%s"', 'wp-powersuite' ),
					esc_html( $compare_title )
				);
				?>
			</h1>
		</div>
		<div>
			<a href="<?php echo esc_url( $back_url ); ?>" class="wpps-cs-btn wpps-cs-btn-secondary">&larr; <?php esc_html_e( 'Go back to editor', 'wp-powersuite' ); ?></a>
		</div>
	</div>

	<?php if ( empty( $revisions ) ) : ?>
		<p><?php esc_html_e( 'No revisions found for this snippet.', 'wp-powersuite' ); ?></p>
	<?php else : ?>
		<div class="wpps-cs-compare-checkbox">
			<label>
				<input type="checkbox" id="wpps-cs-compare-two" <?php echo $compare ? 'checked' : ''; ?>>
				<?php esc_html_e( 'Compare any two revisions', 'wp-powersuite' ); ?>
			</label>
			<span class="wpps-cs-compare-checkbox-help"><?php esc_html_e( 'When checked, use two handles to pick any two revisions to compare side-by-side.', 'wp-powersuite' ); ?></span>
		</div>
		<div class="wpps-cs-revisions-timeline">
			<div class="wpps-cs-revisions-timeline-left">
				<button type="button" class="wpps-cs-btn wpps-cs-btn-secondary" id="wpps-cs-revision-prev"><?php esc_html_e( 'Previous', 'wp-powersuite' ); ?></button>
			</div>
			<div class="wpps-cs-revisions-timeline-center">
				<span class="wpps-cs-revisions-slider-label wpps-cs-revisions-slider-oldest"><?php esc_html_e( 'Oldest', 'wp-powersuite' ); ?></span>
				<div class="wpps-cs-revisions-slider"
					data-value="<?php echo absint( $current_revision ); ?>"
					data-total="<?php echo absint( $total ); ?>"
					data-revisions='<?php echo wp_json_encode( $revision_ids ); ?>'
					data-snippet-id="<?php echo absint( $snippet_id ); ?>"
					data-compare="<?php echo $compare ? '1' : '0'; ?>"></div>
				<span class="wpps-cs-revisions-slider-label wpps-cs-revisions-slider-latest"><?php esc_html_e( 'Latest', 'wp-powersuite' ); ?></span>
				<span class="wpps-cs-revisions-slider-position" id="wpps-cs-revisions-slider-position"></span>
			</div>
			<div class="wpps-cs-revisions-timeline-right">
				<button type="button" class="wpps-cs-btn wpps-cs-btn-secondary" id="wpps-cs-revision-next"><?php esc_html_e( 'Next', 'wp-powersuite' ); ?></button>
			</div>
		</div>
		<div class="wpps-cs-revisions-diff-display">
			<?php
			$previous_data = $default_data;
			foreach ( $revisions as $key => $revision ) {
				$revision_data = json_decode( $revision->revision_data, true );
				$revision_data = is_array( $revision_data ) ? wp_parse_args( $revision_data, $default_data ) : $default_data;
				$is_current = ( $key === count( $revisions ) - 1 );
				?>
				<div class="wpps-cs-revision-display" data-slider-id="<?php echo absint( $key ); ?>">
					<?php
					\CodeSnippet\Wpps_Revisions_Display::render_header( $revision, $is_current );
					\CodeSnippet\Wpps_Revisions_Display::render_compare_content( $previous_data, $revision_data );
					?>
				</div>
				<?php
				$previous_data = wp_parse_args( $revision_data, $default_data );
			}
			?>
			<div id="wpps-cs-revision-compare-any"></div>
		</div>
		<script>
		jQuery(function($) {
			var slider = $('.wpps-cs-revisions-slider');
			var total = slider.data('total');
			var value = slider.data('value');
			var revisions = slider.data('revisions');
			var snippetId = slider.data('snippet-id');
			var isCompare = slider.data('compare') === 1;
			var allRevisions = $('.wpps-cs-revision-display');
			var anyDisplay = $('#wpps-cs-revision-compare-any');
			var prevBtn = $('#wpps-cs-revision-prev');
			var nextBtn = $('#wpps-cs-revision-next');
			var compareCheck = $('#wpps-cs-compare-two');

			function showRevision(idx) {
				allRevisions.hide();
				allRevisions.filter('[data-slider-id="' + idx + '"]').show();
				prevBtn.prop('disabled', idx <= 0);
				nextBtn.prop('disabled', idx >= total);
				$('#wpps-cs-revisions-slider-position').text((idx + 1) + ' / ' + (total + 1));
			}

			if (total >= 0) {
				slider.slider({
					value: value,
					min: 0,
					max: total,
					step: 1,
					change: function(e, ui) {
						showRevision(ui.value);
					},
					slide: function(e, ui) {
						showRevision(ui.value);
					}
				});
				showRevision(value);
				prevBtn.prop('disabled', value <= 0);
				nextBtn.prop('disabled', value >= total);
			}

			prevBtn.on('click', function() {
				var v = slider.slider('value');
				if (v > 0) slider.slider('value', v - 1);
			});
			nextBtn.on('click', function() {
				var v = slider.slider('value');
				if (v < total) slider.slider('value', v + 1);
			});

			compareCheck.on('change', function() {
				if ($(this).prop('checked')) {
					slider.slider('destroy');
					slider.slider({
						range: true,
						min: 0,
						max: total,
						values: [Math.max(0, value - 1), value],
						slide: function(e, ui) {
							if (ui.values[0] === ui.values[1]) return false;
						},
						change: function(e, ui) {
							loadCompareRevisions(ui.values[0], ui.values[1]);
						}
					});
					anyDisplay.show();
					allRevisions.hide();
					loadCompareRevisions(slider.slider('values', 0), slider.slider('values', 1));
					prevBtn.add(nextBtn).css('opacity', 0.5).css('pointer-events', 'none');
				} else {
					slider.slider('destroy');
					slider.slider({
						value: value,
						min: 0,
						max: total,
						step: 1,
						change: function(e, ui) { showRevision(ui.value); }
					});
					anyDisplay.hide().empty();
					showRevision(slider.slider('value'));
					prevBtn.add(nextBtn).css('opacity', 1).css('pointer-events', '');
				}
			});

			if (isCompare) {
				compareCheck.trigger('change');
			}

			function loadCompareRevisions(idx1, idx2) {
				var id1 = revisions[idx1];
				var id2 = revisions[idx2];
				if (!id1 || !id2) return;
				$.post(ajaxurl, {
					action: 'wpps_cs_load_revisions_compare',
					nonce: <?php echo wp_json_encode( wp_create_nonce( 'wpps_cs_nonce' ) ); ?>,
					ids: [id1, id2],
					snippet_id: snippetId
				}).done(function(r) {
					if (r.success && r.data && r.data.markup) {
						anyDisplay.html(r.data.markup);
					}
				});
			}
		});
		</script>
	<?php endif; ?>
</div>
