<?php
/**
 * Disable Thumbnail Generation module settings template.
 *
 * @package DisableThumbnailGeneration
 */

use DisableThumbnailGeneration\Module;
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

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

$module_id = $module_id ?? 'disable-thumbnail-generation';
$settings  = Module::normalizeSettings(
	OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] ) ?: []
);

$disable_all      = $settings['disable_all'];
$disabled_sizes   = $settings['disabled_sizes'];
$registered_sizes = Module::getRegisteredImageSizes();

?>
<div class="wp-powersuite-module-settings wpps-dtg-settings" data-module-id="<?php echo esc_attr( $module_id ); ?>">
	<p class="description">
		<?php esc_html_e( 'Choose between disabling all thumbnails or selecting specific sizes to disable. Existing images keep their thumbnails; new uploads only keep the original.', '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">
			<tbody>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'Mode', 'wp-powersuite' ); ?>
					</th>
					<td>
						<fieldset>
							<label>
								<input type="radio"
									name="disable_all"
									class="wp-powersuite-advanced-setting wpps-dtg-mode-radio"
									data-setting-key="disable_all"
									value="0"
									<?php checked( ! $disable_all ); ?>
								/>
								<?php esc_html_e( 'Disable specific sizes only', 'wp-powersuite' ); ?>
							</label>
							<br>
							<label>
								<input type="radio"
									name="disable_all"
									class="wp-powersuite-advanced-setting wpps-dtg-mode-radio"
									data-setting-key="disable_all"
									value="1"
									<?php checked( $disable_all ); ?>
								/>
								<?php esc_html_e( 'Disable all thumbnails (keep original only)', 'wp-powersuite' ); ?>
							</label>
						</fieldset>
					</td>
				</tr>
				<tr id="wpps-dtg-sizes-row" class="<?php echo $disable_all ? 'wpps-dtg-sizes-disabled' : ''; ?>">
					<th scope="row">
						<label><?php esc_html_e( 'Sizes to disable', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<?php if ( empty( $registered_sizes ) ) : ?>
							<p class="description">
								<?php esc_html_e( 'No registered image sizes found. WordPress core sizes (thumbnail, medium, large) may not be configured yet.', 'wp-powersuite' ); ?>
							</p>
						<?php else : ?>
							<p class="description" style="margin-bottom: 8px;">
								<?php esc_html_e( 'Select which image sizes should not be generated on upload:', 'wp-powersuite' ); ?>
							</p>
							<div class="wpps-ct-multiselect wpps-dtg-multiselect" id="<?php echo esc_attr( $module_id ); ?>_sizes_ms"
								data-label-none="<?php echo esc_attr( __( 'Select image sizes...', 'wp-powersuite' ) ); ?>"
								data-label-single="<?php echo esc_attr( __( '1 size selected', 'wp-powersuite' ) ); ?>"
								data-label-multi="<?php echo esc_attr( __( '%d sizes 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 ); ?>_sizes_list">
									<span class="wpps-ct-multiselect__trigger-text"><?php echo esc_html( __( 'Select image sizes...', '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 ); ?>_sizes_list" role="listbox" hidden>
									<input type="text" class="wpps-ct-multiselect__search" placeholder="<?php esc_attr_e( 'Search sizes...', '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 ( $registered_sizes as $size ) : ?>
											<?php
											$size_name = (string) ( $size['name'] ?? '' );
											if ( $size_name === '' ) {
												continue;
											}
											$label = $size_name;
											if ( ( $size['width'] ?? 0 ) > 0 || ( $size['height'] ?? 0 ) > 0 ) {
												$label .= ' (' . (int) $size['width'] . '×' . (int) $size['height'];
												if ( ! empty( $size['crop'] ) ) {
													$label .= ', ' . __( 'cropped', 'wp-powersuite' );
												}
												$label .= ')';
											}
											$checked = in_array( $size_name, $disabled_sizes, true );
											?>
											<label class="wpps-ct-multiselect__option" data-slug="<?php echo esc_attr( $size_name ); ?>" data-label="<?php echo esc_attr( $label ); ?>">
												<input type="checkbox"
													name="disabled_sizes[]"
													class="wp-powersuite-advanced-setting"
													data-setting-key="disabled_sizes"
													value="<?php echo esc_attr( $size_name ); ?>"
													<?php checked( $checked ); ?>
												/>
												<span class="wpps-ct-multiselect__option-label"><?php echo esc_html( $label ); ?></span>
											</label>
										<?php endforeach; ?>
									</div>
								</div>
							</div>
						<?php endif; ?>
					</td>
				</tr>
			</tbody>
		</table>

		<p class="description notice notice-warning inline wpps-module-callout" style="margin-top: 20px;">
			<strong><?php esc_html_e( 'Note:', 'wp-powersuite' ); ?></strong>
			<?php esc_html_e( 'This only affects new uploads. Existing images retain their thumbnails. If you use a CDN or external image resizing service, disabling thumbnails saves disk space and speeds up uploads.', 'wp-powersuite' ); ?>
		</p>
	</form>
</div>

<?php if ( ! empty( $registered_sizes ) ) : ?>
<script>
(function() {
	var form = document.querySelector('.wpps-dtg-settings .wp-powersuite-module-settings-form');
	if (!form) return;

	var modeRadios = form.querySelectorAll('.wpps-dtg-mode-radio');
	var sizesRow = document.getElementById('wpps-dtg-sizes-row');
	var root = document.querySelector('.wpps-dtg-settings .wpps-dtg-multiselect');

	function updateSizesRow() {
		var disableAll = form.querySelector('.wpps-dtg-mode-radio[value="1"]')?.checked;
		if (sizesRow) {
			sizesRow.classList.toggle('wpps-dtg-sizes-disabled', disableAll);
			sizesRow.querySelectorAll('input, button').forEach(function(inp) {
				inp.disabled = disableAll;
			});
		}
	}

	modeRadios.forEach(function(radio) {
		radio.addEventListener('change', updateSizesRow);
	});
	updateSizesRow();

	if (!root) return;

	var trigger = root.querySelector('.wpps-ct-multiselect__trigger');
	var triggerText = root.querySelector('.wpps-ct-multiselect__trigger-text');
	var dropdown = root.querySelector('.wpps-ct-multiselect__dropdown');
	var search = root.querySelector('.wpps-ct-multiselect__search');
	var options = root.querySelectorAll('.wpps-ct-multiselect__option');

	function countChecked() {
		var n = 0;
		options.forEach(function(o) {
			var cb = o.querySelector('input[type="checkbox"]');
			if (cb && cb.checked) n++;
		});
		return n;
	}
	function updateTriggerText() {
		var n = countChecked();
		var none = root.dataset.labelNone || 'Select image sizes...';
		var single = root.dataset.labelSingle || '1 size selected';
		var multi = (root.dataset.labelMulti || '%d sizes selected').replace('%d', n);
		triggerText.textContent = n === 0 ? none : (n === 1 ? single : multi);
	}
	function filterOptions(q) {
		q = (q || '').toLowerCase().trim();
		options.forEach(function(o) {
			var label = (o.dataset.label || '').toLowerCase();
			var slug = (o.dataset.slug || '').toLowerCase();
			o.classList.toggle('wpps-ct-multiselect__option--hidden', q !== '' && label.indexOf(q) === -1 && slug.indexOf(q) === -1);
		});
	}
	function toggleDropdown(open) {
		var isOpen = open === undefined ? dropdown.hasAttribute('hidden') : !!open;
		if (isOpen) {
			dropdown.removeAttribute('hidden');
			trigger.setAttribute('aria-expanded', 'true');
			search.value = '';
			filterOptions('');
			search.focus();
		} else {
			dropdown.setAttribute('hidden', '');
			trigger.setAttribute('aria-expanded', 'false');
		}
	}

	trigger.addEventListener('click', function() { toggleDropdown(); });
	search.addEventListener('input', function() { filterOptions(this.value); });
	search.addEventListener('keydown', function(e) {
		if (e.key === 'Escape') { toggleDropdown(false); }
	});

	root.querySelectorAll('.wpps-ct-multiselect__action').forEach(function(btn) {
		btn.addEventListener('click', function() {
			var action = btn.dataset.action;
			var visible = Array.prototype.filter.call(options, function(o) { return !o.classList.contains('wpps-ct-multiselect__option--hidden'); });
			if (action === 'select-all') {
				visible.forEach(function(o) {
					var cb = o.querySelector('input[type="checkbox"]');
					if (cb) cb.checked = true;
				});
			} else if (action === 'clear') {
				options.forEach(function(o) {
					var cb = o.querySelector('input[type="checkbox"]');
					if (cb) cb.checked = false;
				});
			}
			updateTriggerText();
		});
	});

	options.forEach(function(o) {
		var cb = o.querySelector('input[type="checkbox"]');
		if (cb) cb.addEventListener('change', updateTriggerText);
	});

	document.addEventListener('click', function(e) {
		if (!root.contains(e.target)) toggleDropdown(false);
	});

	updateTriggerText();
})();
</script>
<?php endif; ?>
