<?php
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

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

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'auto-set-featured-image';
}

$settings     = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
if ( ! is_array( $settings ) ) {
	$settings = [];
}

$defaults = [
	'post_types' => [ 'post', 'page' ],
];
$settings = array_merge( $defaults, $settings );

$enabled_post_types = $settings['post_types'] ?? [ 'post', 'page' ];
if ( ! is_array( $enabled_post_types ) ) {
	$enabled_post_types = [ 'post', 'page' ];
}

$excluded_types   = [ 'attachment', 'revision', 'nav_menu_item', 'custom_css', 'customize_changeset', 'oembed_cache', 'user_request', 'wp_block' ];
$post_types       = get_post_types( [ 'public' => true ], 'objects' );
$available_post_types = [];
foreach ( $post_types as $post_type_name => $post_type_object ) {
	if ( ! in_array( $post_type_name, $excluded_types, true ) && post_type_supports( $post_type_name, 'thumbnail' ) ) {
		$available_post_types[ $post_type_name ] = $post_type_object;
	}
}

$scan_nonce   = wp_create_nonce( 'wpps_asfi_scan' );
$apply_nonce  = wp_create_nonce( 'wpps_asfi_apply' );
$ajax_url     = admin_url( 'admin-ajax.php' );
?>

<div class="wp-powersuite-module-settings wpps-asfi-settings">
	<p class="description">
		<?php esc_html_e( 'Automatically set the first image from your post content as the featured image when saving. Only uses images from your media library. Does not override existing featured images.', 'wp-powersuite' ); ?>
	</p>

	<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>">
		<?php wp_nonce_field( 'wp_powersuite_save_module_settings_' . $module_id, 'wp_powersuite_nonce' ); ?>

		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row">
						<label><?php esc_html_e( 'Select Post Types', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<p class="description" style="margin-bottom: 8px;">
							<?php esc_html_e( 'Choose which post types trigger auto-featured image when saving.', 'wp-powersuite' ); ?>
						</p>
						<?php if ( empty( $available_post_types ) ) : ?>
							<p class="description"><?php esc_html_e( 'No post types with thumbnail support found.', 'wp-powersuite' ); ?></p>
						<?php else : ?>
							<div class="wpps-ct-multiselect" id="<?php echo esc_attr( $module_id ); ?>_post_types_ms"
								data-label-none="<?php echo esc_attr( __( 'Select post types...', 'wp-powersuite' ) ); ?>"
								data-label-single="<?php echo esc_attr( __( '1 selected', 'wp-powersuite' ) ); ?>"
								data-label-multi="<?php echo esc_attr( __( '%d selected', 'wp-powersuite' ) ); ?>">
								<button type="button" class="wpps-ct-multiselect__trigger" aria-expanded="false" aria-haspopup="listbox" aria-controls="<?php echo esc_attr( $module_id ); ?>_post_types_list">
									<span class="wpps-ct-multiselect__trigger-text"><?php esc_html_e( 'Select post types...', 'wp-powersuite' ); ?></span>
									<span class="dashicons dashicons-arrow-down-alt2 wpps-ct-multiselect__chevron"></span>
								</button>
								<div class="wpps-ct-multiselect__dropdown" id="<?php echo esc_attr( $module_id ); ?>_post_types_list" role="listbox" hidden>
									<input type="text" class="wpps-ct-multiselect__search" placeholder="<?php esc_attr_e( 'Search post types...', 'wp-powersuite' ); ?>" autocomplete="off" />
									<div class="wpps-ct-multiselect__actions">
										<button type="button" class="wpps-ct-multiselect__action" data-action="select-all"><?php esc_html_e( 'Select all', 'wp-powersuite' ); ?></button>
										<button type="button" class="wpps-ct-multiselect__action" data-action="clear"><?php esc_html_e( 'Clear', 'wp-powersuite' ); ?></button>
									</div>
									<div class="wpps-ct-multiselect__options">
										<?php foreach ( $available_post_types as $post_type_name => $post_type_object ) : ?>
											<?php
											$label   = $post_type_object->labels->name ?? $post_type_name;
											$checked = in_array( $post_type_name, $enabled_post_types, true );
											?>
											<label class="wpps-ct-multiselect__option" data-slug="<?php echo esc_attr( $post_type_name ); ?>" data-label="<?php echo esc_attr( $label ); ?>">
												<input type="checkbox"
													name="post_types[]"
													class="wp-powersuite-advanced-setting"
													data-setting-key="post_types"
													value="<?php echo esc_attr( $post_type_name ); ?>"
													<?php checked( $checked ); ?>
												/>
												<span class="wpps-ct-multiselect__option-label"><?php echo esc_html( $label ); ?></span>
												<span class="wpps-ct-multiselect__option-slug">(<?php echo esc_html( $post_type_name ); ?>)</span>
											</label>
										<?php endforeach; ?>
									</div>
								</div>
							</div>
						<?php endif; ?>
					</td>
				</tr>
			</tbody>
		</table>
	</form>

	<hr style="margin: 24px 0;" />

	<h3><?php esc_html_e( 'Bulk Apply to Existing Content', 'wp-powersuite' ); ?></h3>
	<p class="description">
		<?php esc_html_e( 'Retroactively add featured images to existing posts that have images in their content but no featured image set. Scan and apply only include posts you are allowed to edit. Large applies run in batches automatically.', 'wp-powersuite' ); ?>
	</p>

	<div class="wpps-asfi-bulk-actions" style="margin: 16px 0;">
		<button type="button" class="button button-secondary wpps-asfi-scan" data-nonce="<?php echo esc_attr( $scan_nonce ); ?>" data-ajax-url="<?php echo esc_attr( $ajax_url ); ?>">
			<?php esc_html_e( 'Scan for Posts Without Featured Images', 'wp-powersuite' ); ?>
		</button>
	</div>

	<div class="wpps-asfi-loading" style="display: none;">
		<span class="spinner is-active"></span>
		<span class="wpps-asfi-loading-text"><?php esc_html_e( 'Scanning...', 'wp-powersuite' ); ?></span>
	</div>

	<div class="wpps-asfi-results" style="display: none;">
		<div class="wpps-asfi-summary" style="margin-bottom: 12px; font-weight: 600;"></div>
		<button type="button" class="button button-primary wpps-asfi-apply" data-nonce="<?php echo esc_attr( $apply_nonce ); ?>" data-ajax-url="<?php echo esc_attr( $ajax_url ); ?>" data-batch-max="200">
			<?php esc_html_e( 'Apply Featured Images', 'wp-powersuite' ); ?>
		</button>
	</div>

	<div class="wpps-asfi-apply-progress" style="display: none; margin-top: 16px;">
		<span class="spinner is-active"></span>
		<span class="wpps-asfi-progress-text"><?php esc_html_e( 'Processing...', 'wp-powersuite' ); ?></span>
	</div>

	<div class="wpps-asfi-apply-done wpps-module-notice--success" style="display: none; margin-top: 16px;"></div>
</div>



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

	var scanBtn = container.querySelector('.wpps-asfi-scan');
	var loading = container.querySelector('.wpps-asfi-loading');
	var results = container.querySelector('.wpps-asfi-results');
	var summary = container.querySelector('.wpps-asfi-summary');
	var applyBtn = container.querySelector('.wpps-asfi-apply');
	var applyProgress = container.querySelector('.wpps-asfi-apply-progress');
	var applyDone = container.querySelector('.wpps-asfi-apply-done');

	var state = { postIds: [], total: 0, withImages: 0 };

	function showLoading(show, text) {
		loading.style.display = show ? 'flex' : 'none';
		var txt = loading.querySelector('.wpps-asfi-loading-text');
		if (txt) txt.textContent = text || '<?php echo esc_js( __( 'Scanning...', 'wp-powersuite' ) ); ?>';
	}

	function finishScan() {
		showLoading(false);
		summary.textContent = state.total + ' <?php echo esc_js( __( 'posts without featured images', 'wp-powersuite' ) ); ?> — ' + state.withImages + ' <?php echo esc_js( __( 'have usable images in content', 'wp-powersuite' ) ); ?>';
		results.style.display = 'block';
		applyBtn.disabled = (state.postIds.length === 0);
	}

	function scanBatch(offset) {
		var nonce = scanBtn.getAttribute('data-nonce');
		var url = scanBtn.getAttribute('data-ajax-url');
		var formData = new FormData();
		formData.append('action', 'wpps_asfi_scan');
		formData.append('nonce', nonce);
		formData.append('offset', String(offset || 0));
		return fetch(url, { method: 'POST', body: formData, credentials: 'same-origin' }).then(function(r) { return r.json(); });
	}

	function doScan() {
		showLoading(true, '<?php echo esc_js( __( 'Scanning...', 'wp-powersuite' ) ); ?>');
		results.style.display = 'none';
		applyDone.style.display = 'none';
		state.postIds = [];
		state.total = 0;
		state.withImages = 0;

		function next(offset) {
			scanBatch(offset)
				.then(function(data) {
					if (!data.success || !data.data) {
						showLoading(false);
						alert(data.data && data.data.message ? data.data.message : '<?php echo esc_js( __( 'Scan failed.', 'wp-powersuite' ) ); ?>');
						return;
					}
					if (offset === 0) {
						state.total = data.data.total || 0;
					}
					state.withImages += data.data.with_images || 0;
					if (Array.isArray(data.data.post_ids)) {
						state.postIds = state.postIds.concat(data.data.post_ids);
					}
					if (data.data.next_offset !== null && data.data.next_offset !== undefined) {
						showLoading(true, '<?php echo esc_js( __( 'Scanning...', 'wp-powersuite' ) ); ?> ' + data.data.next_offset + ' / ' + state.total);
						next(data.data.next_offset);
						return;
					}
					finishScan();
				})
				.catch(function() {
					showLoading(false);
					alert('<?php echo esc_js( __( 'Request failed.', 'wp-powersuite' ) ); ?>');
				});
		}

		next(0);
	}

	function doApply() {
		if (state.postIds.length === 0) return;
		var nonce = applyBtn.getAttribute('data-nonce');
		var url = applyBtn.getAttribute('data-ajax-url');
		var batchMax = parseInt(applyBtn.getAttribute('data-batch-max') || '200', 10) || 200;
		var queue = state.postIds.slice();
		var totalPlanned = queue.length;
		var totalOk = 0;
		var totalFail = 0;

		applyBtn.disabled = true;
		applyProgress.style.display = 'flex';
		applyDone.style.display = 'none';

		function nextBatch() {
			var batch = queue.splice(0, batchMax);
			if (batch.length === 0) {
				applyProgress.style.display = 'none';
				applyDone.style.display = 'block';
				applyDone.textContent = totalOk + ' <?php echo esc_js( __( 'featured images applied.', 'wp-powersuite' ) ); ?>' + (totalFail ? ' ' + totalFail + ' <?php echo esc_js( __( 'failed.', 'wp-powersuite' ) ); ?>' : '');
				applyDone.className = 'wpps-asfi-apply-done wpps-module-notice--' + (totalFail ? 'warning' : 'success');
				state.postIds = [];
				results.style.display = 'none';
				applyBtn.disabled = false;
				return;
			}
			var formData = new FormData();
			formData.append('action', 'wpps_asfi_apply');
			formData.append('nonce', nonce);
			batch.forEach(function(id) { formData.append('post_ids[]', id); });
			var prog = applyProgress.querySelector('.wpps-asfi-progress-text');
			var end = totalPlanned - queue.length;
			var start = end - batch.length + 1;
			if (prog) prog.textContent = '<?php echo esc_js( __( 'Processing…', 'wp-powersuite' ) ); ?> ' + start + '–' + end + ' / ' + totalPlanned;
			fetch(url, { method: 'POST', body: formData, credentials: 'same-origin' })
				.then(function(r) { return r.json(); })
				.then(function(data) {
					if (data.success && data.data) {
						totalOk += data.data.success || 0;
						totalFail += (data.data.failed && data.data.failed.length) ? data.data.failed.length : 0;
						nextBatch();
					} else {
						applyProgress.style.display = 'none';
						applyDone.style.display = 'block';
						applyDone.textContent = (data.data && data.data.message) ? data.data.message : '<?php echo esc_js( __( 'Apply failed.', 'wp-powersuite' ) ); ?>';
						applyDone.className = 'wpps-asfi-apply-done wpps-module-notice--error';
						applyBtn.disabled = false;
					}
				})
				.catch(function() {
					applyProgress.style.display = 'none';
					applyDone.style.display = 'block';
					applyDone.textContent = '<?php echo esc_js( __( 'Request failed.', 'wp-powersuite' ) ); ?>';
					applyDone.className = 'wpps-asfi-apply-done wpps-module-notice--error';
					applyBtn.disabled = false;
				});
		}
		nextBatch();
	}

	if (scanBtn) scanBtn.addEventListener('click', doScan);
	if (applyBtn) applyBtn.addEventListener('click', doApply);
})();
</script>
