<?php
namespace DisableComments;

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

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

if ( array_key_exists( 'disabled_post_types', $settings ) && is_array( $settings['disabled_post_types'] ) ) {
	$disabled_post_types = $settings['disabled_post_types'];
} else {
	$disabled_post_types = empty( $settings ) ? [ 'post', 'page' ] : [];
}
if ( ! is_array( $disabled_post_types ) ) {
	$disabled_post_types = [];
}

$post_types_raw = get_post_types( [ 'public' => true ], 'objects' );
$excluded_types = [ 'attachment', 'revision', 'nav_menu_item', 'custom_css', 'customize_changeset', 'oembed_cache', 'user_request', 'wp_block' ];
$post_types = [];
foreach ( $post_types_raw as $post_type_name => $post_type_object ) {
	if ( in_array( $post_type_name, $excluded_types, true ) ) {
		continue;
	}
	// Do not filter by post_type_supports() here: this module removes comment
	// support at runtime, which would hide already-selected types from the picker.
	$post_types[ $post_type_name ] = $post_type_object;
}

$remove_menu = array_key_exists( 'remove_menu', $settings ) ? ! empty( $settings['remove_menu'] ) : true;
$remove_dashboard_widget = array_key_exists( 'remove_dashboard_widget', $settings ) ? ! empty( $settings['remove_dashboard_widget'] ) : true;
$remove_comments_column = array_key_exists( 'remove_comments_column', $settings ) ? ! empty( $settings['remove_comments_column'] ) : true;

?>
<div class="wp-powersuite-module-settings">
	<h3><?php esc_html_e( 'Comments Settings', 'wp-powersuite' ); ?></h3>
	<p class="description">
		<?php esc_html_e( 'Configure which post types should have comments disabled. Comment metaboxes, REST submissions, and theme comment areas are handled automatically for selected types.', '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">
						<?php esc_html_e( 'Disable Comments On', 'wp-powersuite' ); ?>
					</th>
					<td>
						<p class="description" style="margin-bottom: 8px;"><?php esc_html_e( 'Select which post types should have comments disabled.', 'wp-powersuite' ); ?></p>
						<?php if ( empty( $post_types ) ) : ?>
							<p class="description"><?php esc_html_e( 'No post types 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 ( $post_types as $post_type_name => $post_type_object ) : ?>
											<?php
											$label     = $post_type_object->labels->name ?? $post_type_name;
											$is_checked = in_array( $post_type_name, $disabled_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="disabled_post_types[]"
													class="wp-powersuite-advanced-setting"
													data-setting-key="disabled_post_types"
													value="<?php echo esc_attr( $post_type_name ); ?>"
													<?php checked( $is_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>

				<tr>
					<th scope="row">
						<?php esc_html_e( 'Admin Cleanup', 'wp-powersuite' ); ?>
					</th>
					<td>
						<fieldset>
							<legend class="screen-reader-text">
								<span><?php esc_html_e( 'Admin comment cleanup options', 'wp-powersuite' ); ?></span>
							</legend>

							<label>
								<input
									type="checkbox"
									name="remove_menu"
									value="1"
									class="wp-powersuite-advanced-setting"
									data-setting-key="remove_menu"
									<?php checked( $remove_menu ); ?>
								/>
								<?php esc_html_e( 'Remove Comments menu from admin', 'wp-powersuite' ); ?>
							</label>
							<p class="description"><?php esc_html_e( 'The admin bar comments icon is always removed while this module is active with at least one post type selected.', 'wp-powersuite' ); ?></p>
							<br />

							<label>
								<input
									type="checkbox"
									name="remove_dashboard_widget"
									value="1"
									class="wp-powersuite-advanced-setting"
									data-setting-key="remove_dashboard_widget"
									<?php checked( $remove_dashboard_widget ); ?>
								/>
								<?php esc_html_e( 'Remove Recent Comments widget from dashboard', 'wp-powersuite' ); ?>
							</label>
							<br />

							<label>
								<input
									type="checkbox"
									name="remove_comments_column"
									value="1"
									class="wp-powersuite-advanced-setting"
									data-setting-key="remove_comments_column"
									<?php checked( $remove_comments_column ); ?>
								/>
								<?php esc_html_e( 'Remove Comments column from selected post type lists', 'wp-powersuite' ); ?>
							</label>
						</fieldset>
					</td>
				</tr>
			</tbody>
		</table>
	</form>

	<?php if ( ! empty( $post_types ) ) : ?>
	<style>
		.wpps-ct-multiselect { position: relative; max-width: 360px; }
		.wpps-ct-multiselect__trigger {
			display: flex; align-items: center; justify-content: space-between;
			width: 100%; padding: 8px 12px; border: 1px solid #8c8f94; border-radius: 4px;
			background: #fff; font-size: 14px; text-align: left; cursor: pointer;
			line-height: 1.4; color: #1d2327;
		}
		.wpps-ct-multiselect__trigger:hover { border-color: #2271b1; }
		.wpps-ct-multiselect__chevron { font-size: 18px; width: 18px; height: 18px; color: #787c82; flex-shrink: 0; margin-left: 8px; }
		.wpps-ct-multiselect__trigger[aria-expanded="true"] .wpps-ct-multiselect__chevron { transform: rotate(180deg); }
		.wpps-ct-multiselect__dropdown {
			position: absolute; top: 100%; left: 0; right: 0; margin-top: 4px;
			border: 1px solid #8c8f94; border-radius: 4px; background: #fff;
			box-shadow: 0 2px 8px rgba(0,0,0,.12); z-index: 100;
			max-height: 280px; display: flex; flex-direction: column;
		}
		.wpps-ct-multiselect__dropdown[hidden] { display: none !important; }
		.wpps-ct-multiselect__search {
			width: 100%; padding: 8px 12px; border: none; border-bottom: 1px solid #dcdcde;
			font-size: 13px; box-sizing: border-box; outline: none;
		}
		.wpps-ct-multiselect__search::placeholder { color: #a7aaad; }
		.wpps-ct-multiselect__actions { padding: 6px 10px; border-bottom: 1px solid #dcdcde; display: flex; gap: 12px; flex-shrink: 0; }
		.wpps-ct-multiselect__action {
			background: none; border: none; color: #2271b1; cursor: pointer; font-size: 12px; padding: 0;
		}
		.wpps-ct-multiselect__action:hover { color: #135e96; text-decoration: underline; }
		.wpps-ct-multiselect__options {
			overflow-y: auto; padding: 4px 0; max-height: 200px;
		}
		.wpps-ct-multiselect__option {
			display: flex; align-items: center; gap: 6px; padding: 6px 12px; cursor: pointer;
			font-size: 13px; white-space: nowrap;
		}
		.wpps-ct-multiselect__option:hover { background: #f0f0f1; }
		.wpps-ct-multiselect__option input { flex-shrink: 0; margin: 0; }
		.wpps-ct-multiselect__option-slug { color: #646970; font-size: 12px; }
		.wpps-ct-multiselect__option.wpps-ct-multiselect__option--hidden { display: none; }
	</style>
	<script>
		(function() {
			var root = document.querySelector('.wp-powersuite-module-settings .wpps-ct-multiselect');
			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 post types...';
				var single = root.dataset.labelSingle || '1 selected';
				var multi = (root.dataset.labelMulti || '%d 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();
					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>
	<?php endif; ?>
</div>
