<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

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

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'content-expiration';
}

$defaults = class_exists( \ContentExpiration\Module::class )
	? \ContentExpiration\Module::getDefaultSettings()
	: [ 'post_types' => [ 'post', 'page' ] ];

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

$settings = class_exists( \ContentExpiration\Module::class )
	? \ContentExpiration\Module::normalizeSettings( array_merge( $defaults, $settings ) )
	: array_merge( $defaults, $settings );

$post_types = $settings['post_types'] ?? [ 'post', 'page' ];

$exclude   = class_exists( \ContentExpiration\Module::class )
	? \ContentExpiration\Module::getSettingsExcludedPostTypes()
	: [ 'attachment', 'wp_block', 'wp_template', 'wp_template_part', 'wp_navigation' ];
$available = get_post_types( [ 'public' => true ], 'objects' );
$available = array_diff_key( $available, array_flip( $exclude ) );
?>

<div class="wp-powersuite-module-settings">
	<p class="description">
		<?php esc_html_e( 'Enable content expiration for selected post types. Use Save expiration in the editor sidebar (or Quick Edit). Expired posts are automatically unpublished.', '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( 'Post Types', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<p class="description" style="margin-bottom: 8px;">
							<?php esc_html_e( 'Show the expiration field and list column for these post types.', 'wp-powersuite' ); ?>
						</p>
						<?php if ( ! empty( $available ) ) : ?>
							<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 as $slug => $obj ) : ?>
											<?php
											$label   = $obj->labels->name ?? ( $obj->labels->singular_name ?? $slug );
											$checked = in_array( $slug, $post_types, true );
											?>
											<label class="wpps-ct-multiselect__option" data-slug="<?php echo esc_attr( $slug ); ?>" 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( $slug ); ?>"
													<?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( $slug ); ?>)</span>
											</label>
										<?php endforeach; ?>
									</div>
								</div>
							</div>
						<?php else : ?>
							<p class="description"><?php esc_html_e( 'No public post types found.', 'wp-powersuite' ); ?></p>
						<?php endif; ?>
					</td>
				</tr>
			</tbody>
		</table>
	</form>

	<p class="description" style="margin-top: 16px;">
		<?php esc_html_e( 'Expiration is checked on page view (instant), about every 5 minutes while in admin, and hourly via WP-Cron. Only the post types selected above are scanned.', 'wp-powersuite' ); ?>
	</p>
	<script>
		(function() {
			var root = document.getElementById(<?php echo wp_json_encode( $module_id . '_post_types_ms' ); ?>);
			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 || '';
				var single = root.dataset.labelSingle || '';
				var multi = (root.dataset.labelMulti || '%d selected').replace('%d', String(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();
					var show = !q || label.indexOf(q) !== -1 || slug.indexOf(q) !== -1;
					o.classList.toggle('wpps-ct-multiselect__option--hidden', !show);
				});
			}
			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>
</div>
