<?php
/**
 * Admin sync page template.
 * This page is shown when syncing all pages to MaplePress (initial or manual sync).
 *
 * @package    MaplePress
 * @subpackage MaplePress/includes
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

$options = get_option( 'maplepress_settings', array() );
?>

<div class="wrap">
	<h1><?php esc_html_e( 'Syncing Pages', 'maplepress' ); ?></h1>

	<div style="max-width: 800px; margin: 40px auto; text-align: center;">
		<div style="background: #fff; border: 1px solid #dcdcde; padding: 40px; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
			<!-- Loading animation -->
			<div style="margin-bottom: 30px;">
				<span class="spinner is-active" style="float: none; width: 40px; height: 40px; margin: 0 auto; background-size: 40px 40px;"></span>
			</div>

			<!-- Status heading -->
			<h2 id="maplepress-sync-status" style="margin: 20px 0; color: #2271b1; font-size: 24px;">
				<?php esc_html_e( 'Preparing to sync your content...', 'maplepress' ); ?>
			</h2>

			<!-- Details text -->
			<p id="maplepress-sync-details" style="color: #666; font-size: 16px; margin: 15px 0;">
				<?php esc_html_e( 'This will only take a moment.', 'maplepress' ); ?>
			</p>

			<!-- Progress bar -->
			<div id="maplepress-sync-progressbar" style="margin: 30px 0;">
				<div style="background: #f0f0f1; border-radius: 4px; height: 30px; position: relative; overflow: hidden;">
					<div id="maplepress-sync-progressbar-fill" style="background: linear-gradient(90deg, #2271b1 0%, #135e96 100%); height: 100%; width: 0%; transition: width 0.5s ease;">
						<span id="maplepress-sync-progressbar-text" style="color: #fff; font-size: 14px; font-weight: 600; line-height: 30px; display: block; text-align: center;"></span>
					</div>
				</div>
			</div>

			<!-- Batch information -->
			<div id="maplepress-sync-batch-info" style="background: #f9f9f9; border: 1px solid #e0e0e0; border-radius: 4px; padding: 20px; margin: 20px 0; display: none;">
				<div style="display: flex; justify-content: space-around; text-align: center;">
					<div>
						<div style="font-size: 28px; font-weight: 600; color: #2271b1;" id="maplepress-sync-pages-synced">0</div>
						<div style="color: #666; font-size: 14px;"><?php esc_html_e( 'Pages Synced', 'maplepress' ); ?></div>
					</div>
					<div>
						<div style="font-size: 28px; font-weight: 600; color: #2271b1;" id="maplepress-sync-current-batch">0</div>
						<div style="color: #666; font-size: 14px;"><?php esc_html_e( 'Current Batch', 'maplepress' ); ?></div>
					</div>
					<div>
						<div style="font-size: 28px; font-weight: 600; color: #2271b1;" id="maplepress-sync-total-batches">0</div>
						<div style="color: #666; font-size: 14px;"><?php esc_html_e( 'Total Batches', 'maplepress' ); ?></div>
					</div>
				</div>
			</div>

			<!-- Important note -->
			<div style="background: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; padding: 15px; margin-top: 30px; text-align: left;">
				<p style="margin: 0; color: #856404;">
					<strong><?php esc_html_e( 'Please do not close this page.', 'maplepress' ); ?></strong><br>
					<?php esc_html_e( 'We are syncing all your published content to MaplePress.', 'maplepress' ); ?>
				</p>
			</div>
		</div>
	</div>
</div>

<script>
jQuery(document).ready(function($) {
	var statusText = $('#maplepress-sync-status');
	var detailsText = $('#maplepress-sync-details');
	var progressBar = $('#maplepress-sync-progressbar-fill');
	var progressText = $('#maplepress-sync-progressbar-text');
	var batchInfo = $('#maplepress-sync-batch-info');
	var pagesSynced = $('#maplepress-sync-pages-synced');
	var currentBatch = $('#maplepress-sync-current-batch');
	var totalBatches = $('#maplepress-sync-total-batches');

	// Start the sync
	function startSync() {
		statusText.text('<?php esc_html_e( 'Counting pages to sync...', 'maplepress' ); ?>');
		detailsText.text('<?php esc_html_e( 'Analyzing your content...', 'maplepress' ); ?>');
		progressBar.css('width', '5%');
		progressText.text('5%');

		$.ajax({
			url: ajaxurl,
			type: 'POST',
			data: {
				action: 'maplepress_initial_sync',
				nonce: '<?php echo wp_create_nonce( 'maplepress_initial_sync' ); ?>'
			},
			timeout: 600000, // 10 minute timeout
			success: function(response) {
				if (response.success) {
					// Show completion
					progressBar.css('width', '100%');
					progressText.text('100%');
					statusText.html('<span style="color: #008a00;">✓ ' + response.data.message + '</span>');
					detailsText.html(response.data.details || '');

					// Redirect to dashboard after 2 seconds
					setTimeout(function() {
						window.location.href = '<?php echo admin_url( 'admin.php?page=maplepress&sync_status=success&synced_count=' ); ?>' + (response.data.synced_count || 0);
					}, 2000);
				} else {
					// Show error
					statusText.html('<span style="color: #d63638;">✗ Sync failed</span>');
					detailsText.html('<strong><?php esc_html_e( 'Error:', 'maplepress' ); ?></strong> ' + (response.data || '<?php esc_html_e( 'Unknown error', 'maplepress' ); ?>'));

					// Show retry button
					$('<div style="margin-top: 20px;"><a href="<?php echo admin_url( 'admin.php?page=maplepress-settings' ); ?>" class="button button-primary"><?php esc_html_e( 'Return to Settings', 'maplepress' ); ?></a></div>').insertAfter('#maplepress-sync-progressbar');
				}
			},
			error: function(xhr, status, error) {
				statusText.html('<span style="color: #d63638;">✗ Network error</span>');
				detailsText.html('<strong><?php esc_html_e( 'Error:', 'maplepress' ); ?></strong> ' + error);

				// Show retry button
				$('<div style="margin-top: 20px;"><a href="<?php echo admin_url( 'admin.php?page=maplepress-settings' ); ?>" class="button button-primary"><?php esc_html_e( 'Return to Settings', 'maplepress' ); ?></a></div>').insertAfter('#maplepress-sync-progressbar');
			},
			xhr: function() {
				var xhr = new window.XMLHttpRequest();
				var progressSimulator;
				var startTime = Date.now();

				// Start progress simulation
				progressSimulator = setInterval(function() {
					var elapsed = (Date.now() - startTime) / 1000;

					if (elapsed < 5) {
						// 5-15% - Analyzing content
						var progress = 5 + (elapsed / 5) * 10;
						progressBar.css('width', progress + '%');
						progressText.text(Math.round(progress) + '%');
						statusText.text('<?php esc_html_e( 'Analyzing your content...', 'maplepress' ); ?>');
					} else if (elapsed < 10) {
						// 15-30% - Preparing batches
						var progress = 15 + ((elapsed - 5) / 5) * 15;
						progressBar.css('width', progress + '%');
						progressText.text(Math.round(progress) + '%');
						statusText.text('<?php esc_html_e( 'Preparing batches for sync...', 'maplepress' ); ?>');
						batchInfo.show();
					} else if (elapsed < 60) {
						// 30-80% - Syncing batches
						var progress = 30 + ((elapsed - 10) / 50) * 50;
						progressBar.css('width', Math.min(progress, 80) + '%');
						progressText.text(Math.round(Math.min(progress, 80)) + '%');
						statusText.text('<?php esc_html_e( 'Syncing pages to MaplePress...', 'maplepress' ); ?>');
						detailsText.html('<?php esc_html_e( 'Processing batches...', 'maplepress' ); ?><br><small><?php esc_html_e( 'This may take a moment for large sites.', 'maplepress' ); ?></small>');

						// Simulate batch progress
						var estimatedBatches = Math.ceil(elapsed / 3);
						currentBatch.text(estimatedBatches);
						totalBatches.text(estimatedBatches + Math.ceil((60 - elapsed) / 3));
						pagesSynced.text(estimatedBatches * 950);
					} else {
						// 80-95% - Finalizing
						var progress = 80 + ((elapsed - 60) / 60) * 15;
						progressBar.css('width', Math.min(progress, 95) + '%');
						progressText.text(Math.round(Math.min(progress, 95)) + '%');
						statusText.text('<?php esc_html_e( 'Finalizing sync...', 'maplepress' ); ?>');
						detailsText.html('<?php esc_html_e( 'Almost done!', 'maplepress' ); ?>');
					}
				}, 500);

				xhr.addEventListener('loadend', function() {
					clearInterval(progressSimulator);
				});

				return xhr;
			}
		});
	}

	// Auto-start sync when page loads
	setTimeout(startSync, 500);
});
</script>
