<?php
/**
 * Regenerate Thumbnails module settings template.
 *
 * @package RegenerateThumbnails
 */

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

if ( ! \WP_PowerSuite\Core\NetworkScope::canManagePlugin() ) {
	return;
}

$module_id = $module_id ?? 'regenerate-thumbnails';
$nonce     = wp_create_nonce( 'wpps_regenerate_thumbnails' );
$ajax_url  = admin_url( 'admin-ajax.php' );
?>
<div class="wp-powersuite-module-settings wpps-rt-settings" data-module-id="<?php echo esc_attr( $module_id ); ?>">
	<p class="description">
		<?php esc_html_e( 'Regenerate thumbnails for all images in your media library. Fix missing or broken thumbnails, generate theme-required sizes, and update metadata. Processing runs one image at a time to avoid timeouts.', 'wp-powersuite' ); ?>
	</p>

	<div class="wpps-rt-stats wpps-rt-card">
		<h3><?php esc_html_e( 'Overview', 'wp-powersuite' ); ?></h3>
		<div class="wpps-rt-stat-row">
			<span class="wpps-rt-stat-label"><?php esc_html_e( 'Image count', 'wp-powersuite' ); ?>:</span>
			<span class="wpps-rt-stat-value" id="wpps-rt-image-count">—</span>
		</div>
		<div class="wpps-rt-stat-row">
			<span class="wpps-rt-stat-label"><?php esc_html_e( 'Registered sizes', 'wp-powersuite' ); ?>:</span>
			<span class="wpps-rt-stat-value" id="wpps-rt-sizes-count">—</span>
		</div>
	</div>

	<div class="wpps-rt-sizes wpps-rt-card">
		<h3><?php esc_html_e( 'Registered Image Sizes', 'wp-powersuite' ); ?></h3>
		<p id="wpps-rt-sizes-note" class="wpps-rt-sizes-note description" style="display: none; margin-bottom: 8px;">
			<?php esc_html_e( 'Some sizes are excluded by Disable Thumbnail Generation. Only the sizes listed below will be regenerated.', 'wp-powersuite' ); ?>
		</p>
		<ul id="wpps-rt-sizes-list" class="wpps-rt-sizes-list"></ul>
	</div>

	<div class="wpps-rt-actions wpps-rt-card">
		<h3><?php esc_html_e( 'Run Regeneration', 'wp-powersuite' ); ?></h3>
		<div class="wpps-rt-buttons">
			<button type="button" class="button button-primary" id="wpps-rt-start" disabled>
				<?php esc_html_e( 'Start Regenerating', 'wp-powersuite' ); ?>
			</button>
			<button type="button" class="button button-secondary" id="wpps-rt-stop" style="display: none;">
				<?php esc_html_e( 'Stop', 'wp-powersuite' ); ?>
			</button>
		</div>

		<div id="wpps-rt-progress-wrap" class="wpps-rt-progress-wrap" style="display: none;">
			<div class="wpps-rt-progress-bar">
				<div class="wpps-rt-progress-fill" id="wpps-rt-progress-fill" style="width: 0%;"></div>
			</div>
			<div class="wpps-rt-progress-meta">
				<span class="wpps-rt-counter" id="wpps-rt-counter">0 / 0</span>
				<span class="wpps-rt-current" id="wpps-rt-current"></span>
			</div>
		</div>

		<div id="wpps-rt-log-wrap" class="wpps-rt-log-wrap" style="display: none;">
			<h4><?php esc_html_e( 'Activity Log', 'wp-powersuite' ); ?></h4>
			<div class="wpps-rt-log" id="wpps-rt-log"></div>
		</div>
	</div>

	<div class="wpps-rt-info-box wpps-module-callout">
		<p>
			<strong><?php esc_html_e( 'Note', 'wp-powersuite' ); ?></strong><br>
			<?php esc_html_e( 'If you stop mid-process and restart later, regeneration begins from the first image again. Images already processed will be regenerated again but this is safe. Do not close this modal while processing—a warning will appear if you try.', 'wp-powersuite' ); ?>
		</p>
	</div>
</div>

<script>
(function() {
	'use strict';
	var container = document.querySelector('.wpps-rt-settings');
	if (!container) return;

	var startBtn = container.querySelector('#wpps-rt-start');
	var stopBtn = container.querySelector('#wpps-rt-stop');
	var imageCountEl = container.querySelector('#wpps-rt-image-count');
	var sizesCountEl = container.querySelector('#wpps-rt-sizes-count');
	var sizesListEl = container.querySelector('#wpps-rt-sizes-list');
	var sizesNoteEl = container.querySelector('#wpps-rt-sizes-note');
	var progressWrap = container.querySelector('#wpps-rt-progress-wrap');
	var progressFill = container.querySelector('#wpps-rt-progress-fill');
	var counterEl = container.querySelector('#wpps-rt-counter');
	var currentEl = container.querySelector('#wpps-rt-current');
	var logWrap = container.querySelector('#wpps-rt-log-wrap');
	var logEl = container.querySelector('#wpps-rt-log');

	var nonce = <?php echo wp_json_encode( $nonce ); ?>;
	var ajaxUrl = <?php echo wp_json_encode( $ajax_url ); ?>;

	var state = {
		imageCount: 0,
		cursor: 0,
		sizes: [],
		processed: 0,
		failed: 0,
		running: false,
		stopped: false
	};

	function clearChildren(el) {
		while (el.firstChild) {
			el.removeChild(el.firstChild);
		}
	}

	function timeStr() {
		var d = new Date();
		return ('0' + d.getHours()).slice(-2) + ':' + ('0' + d.getMinutes()).slice(-2) + ':' + ('0' + d.getSeconds()).slice(-2);
	}

	function logEntry(ok, msg) {
		var className = ok ? 'success' : 'fail';
		var icon = ok ? '✓' : '✗';
		var div = document.createElement('div');
		div.className = 'wpps-rt-log-entry ' + className;
		div.textContent = '[' + timeStr() + '] ' + icon + ' ' + msg;
		logEl.appendChild(div);
		logEl.scrollTop = logEl.scrollHeight;
	}

	function loadData() {
		var fd = new FormData();
		fd.append('action', 'wpps_rt_get_data');
		fd.append('nonce', nonce);
		fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(data) {
				if (data.success && data.data) {
					state.imageCount = typeof data.data.image_count === 'number' ? data.data.image_count : 0;
					state.sizes = data.data.sizes || [];
					var sizesFiltered = !!data.data.sizes_filtered;
					imageCountEl.textContent = state.imageCount;
					sizesCountEl.textContent = state.sizes.length;
					if (sizesNoteEl) sizesNoteEl.style.display = sizesFiltered ? 'block' : 'none';
					clearChildren(sizesListEl);
					state.sizes.forEach(function(s) {
						var li = document.createElement('li');
						var dim = (s.width && s.height) ? s.width + '×' + s.height : (s.width || s.height || '—');
						li.textContent = s.name + ' (' + dim + (s.crop ? ', crop' : '') + ')';
						sizesListEl.appendChild(li);
					});
					if (state.sizes.length === 0 && sizesFiltered) {
						var li = document.createElement('li');
						li.textContent = '<?php echo esc_js( __( 'All sizes disabled by Disable Thumbnail Generation.', 'wp-powersuite' ) ); ?>';
						li.style.color = '#646970';
						sizesListEl.appendChild(li);
					}
					startBtn.disabled = state.imageCount === 0 || (state.sizes.length === 0 && sizesFiltered);
				} else {
					imageCountEl.textContent = '—';
					sizesCountEl.textContent = '—';
					startBtn.disabled = true;
				}
			})
			.catch(function() {
				imageCountEl.textContent = '—';
				sizesCountEl.textContent = '—';
				startBtn.disabled = true;
			});
	}

	function updateProgress() {
		var total = state.imageCount;
		var done = state.processed + state.failed;
		var pct = total ? Math.round((done / total) * 100) : 0;
		progressFill.style.width = pct + '%';
		counterEl.textContent = done + ' / ' + total;
	}

	function resetUI() {
		state.running = false;
		stopBtn.style.display = 'none';
		stopBtn.disabled = false;
		stopBtn.textContent = '<?php echo esc_js( __( 'Stop', 'wp-powersuite' ) ); ?>';
		startBtn.disabled = state.imageCount === 0;
		window.removeEventListener('beforeunload', beforeUnloadHandler);
	}

	function processNext() {
		if (state.stopped || !state.running) {
			resetUI();
			return;
		}
		var done = state.processed + state.failed;
		if (done >= state.imageCount) {
			resetUI();
			logEntry(true, '<?php echo esc_js( __( 'Done.', 'wp-powersuite' ) ); ?>');
			return;
		}
		currentEl.textContent = '<?php echo esc_js( __( 'Processing image', 'wp-powersuite' ) ); ?> ' + (done + 1) + ' <?php echo esc_js( __( 'of', 'wp-powersuite' ) ); ?> ' + state.imageCount + '…';
		var fd = new FormData();
		fd.append('action', 'wpps_rt_regenerate');
		fd.append('nonce', nonce);
		fd.append('cursor', String(state.cursor));
		fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(data) {
				if (state.stopped || !state.running) { resetUI(); return; }
				if (data.success && data.data && data.data.done) {
					resetUI();
					logEntry(true, '<?php echo esc_js( __( 'Done.', 'wp-powersuite' ) ); ?>');
					return;
				}
				var id = data.data && data.data.attachment_id ? data.data.attachment_id : 0;
				var filename = data.data && data.data.filename ? data.data.filename : '#' + id;
				if (data.success) {
					state.processed++;
					if (data.data && typeof data.data.next_cursor === 'number') {
						state.cursor = data.data.next_cursor;
					}
					logEntry(true, filename);
				} else {
					state.failed++;
					if (data.data && typeof data.data.next_cursor === 'number') {
						state.cursor = data.data.next_cursor;
					}
					var msg = data.data && data.data.message ? data.data.message : '<?php echo esc_js( __( 'Unknown error', 'wp-powersuite' ) ); ?>';
					logEntry(false, '<?php echo esc_js( __( 'Failed', 'wp-powersuite' ) ); ?>: ' + filename + ' — ' + msg);
				}
				updateProgress();
				processNext();
			})
			.catch(function() {
				if (state.stopped || !state.running) { resetUI(); return; }
				state.failed++;
				logEntry(false, '<?php echo esc_js( __( 'Failed', 'wp-powersuite' ) ); ?>: #' + (state.cursor || '?') + ' — <?php echo esc_js( __( 'Request failed', 'wp-powersuite' ) ); ?>');
				updateProgress();
				processNext();
			});
	}

	function beforeUnloadHandler(e) {
		if (state.running) {
			e.preventDefault();
			e.returnValue = '';
		}
	}

	startBtn.addEventListener('click', function() {
		if (!confirm('<?php echo esc_js( __( 'Regenerate thumbnails for all images? This may take a while for large libraries.', 'wp-powersuite' ) ); ?>')) return;
		state.running = true;
		state.stopped = false;
		state.processed = 0;
		state.failed = 0;
		state.cursor = 0;
		startBtn.disabled = true;
		stopBtn.style.display = 'inline-block';
		progressWrap.style.display = 'block';
		logWrap.style.display = 'block';
		clearChildren(logEl);
		progressFill.style.width = '0%';
		counterEl.textContent = '0 / ' + state.imageCount;
		currentEl.textContent = '';
		window.addEventListener('beforeunload', beforeUnloadHandler);
		processNext();
	});

	stopBtn.addEventListener('click', function() {
		state.stopped = true;
		stopBtn.disabled = true;
		stopBtn.textContent = '<?php echo esc_js( __( 'Stopping…', 'wp-powersuite' ) ); ?>';
	});

	var modal = document.getElementById('wp-powersuite-modal');
	if (modal) {
		var closeBtn = modal.querySelector('.wp-powersuite-modal__close');
		var cancelBtn = modal.querySelector('.wp-powersuite-modal__cancel');
		var overlay = modal.querySelector('.wp-powersuite-modal__overlay');
		function maybeWarnClose(e) {
			if (state.running) {
				if (!confirm('<?php echo esc_js( __( 'Regeneration is in progress. Closing will stop it. Are you sure?', 'wp-powersuite' ) ); ?>')) {
					e.preventDefault();
					e.stopPropagation();
					return;
				}
				state.stopped = true;
				window.removeEventListener('beforeunload', beforeUnloadHandler);
			}
		}
		if (closeBtn) closeBtn.addEventListener('click', maybeWarnClose);
		if (cancelBtn) cancelBtn.addEventListener('click', maybeWarnClose);
		if (overlay) overlay.addEventListener('click', maybeWarnClose);
		document.addEventListener('keydown', function(e) {
			if (e.key === 'Escape' && state.running && modal && modal.style.display !== 'none') {
				if (!confirm('<?php echo esc_js( __( 'Regeneration is in progress. Closing will stop it. Are you sure?', 'wp-powersuite' ) ); ?>')) {
					e.preventDefault();
					e.stopImmediatePropagation();
					return;
				}
				state.stopped = true;
				window.removeEventListener('beforeunload', beforeUnloadHandler);
			}
		}, true);
	}

	loadData();
})();
</script>
