<?php
namespace ShowIds;

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

require_once __DIR__ . '/FeatureGate.php';

if ( ! current_user_can( 'manage_options' ) ) {
	return;
}

if ( ! isset( $module_id ) ) {
	$module_id = 'show-ids';
}

$premium_unlocked = FeatureGate::isPremiumLicensed();
$license_page_url = admin_url( 'admin.php?page=powersuite-license' );
$default_settings = FeatureGate::getDefaultSettings();

$settings = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
$settings = is_array( $settings ) ? $settings : [];
$settings = array_merge( $default_settings, $settings );
$settings = FeatureGate::applyPremiumTierLimits( $settings );

if ( ! is_array( $settings['enabled_post_types'] ) ) {
	$settings['enabled_post_types'] = $default_settings['enabled_post_types'];
}

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

?>
<div class="wp-powersuite-module-settings">
	<p class="description">
		<?php esc_html_e( 'Configure which post types and taxonomies should display ID columns in admin lists.', '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( 'Select which post types should display an ID column in their admin list screens. The ID column appears just before the title with a fixed width of 60px.', 'wp-powersuite' ); ?></p>
						<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, $settings['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="enabled_post_types[]"
												class="wp-powersuite-advanced-setting"
												data-setting-key="enabled_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>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'Taxonomies', 'wp-powersuite' ); ?>
					</th>
					<td>
						<label>
							<input
								type="checkbox"
								name="show_taxonomy_ids"
								value="1"
								<?php checked( ! empty( $settings['show_taxonomy_ids'] ) ); ?>
								class="wp-powersuite-advanced-setting"
								data-setting-key="show_taxonomy_ids"
							/>
							<?php esc_html_e( 'Show ID column for all public taxonomies', 'wp-powersuite' ); ?>
						</label>
						<p class="description">
							<?php esc_html_e( 'When enabled, ID columns will be displayed on every public taxonomy admin screen, including custom taxonomies.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<?php if ( ! $premium_unlocked ) : ?>
				<tr>
					<td colspan="2">
						<div class="notice notice-info inline" style="margin: 0; padding: 8px 12px;">
							<p style="margin:0;">
								<?php
								echo wp_kses_post(
									sprintf(
										/* translators: %s: URL to license page */
										__( 'User, media, and comment IDs, action-row IDs, and the frontend admin bar are Premium features. <a href="%s">Activate your license</a> to enable them. Post types and taxonomies remain free.', 'wp-powersuite' ),
										esc_url( $license_page_url )
									)
								);
								?>
							</p>
						</div>
					</td>
				</tr>
				<?php endif; ?>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'Users', 'wp-powersuite' ); ?>
						<?php if ( ! $premium_unlocked ) : ?>
							<span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span>
						<?php endif; ?>
					</th>
					<td>
						<label>
							<input
								type="checkbox"
								name="show_user_ids"
								value="1"
								<?php checked( ! empty( $settings['show_user_ids'] ) ); ?>
								<?php disabled( ! $premium_unlocked ); ?>
								class="wp-powersuite-advanced-setting"
								data-setting-key="show_user_ids"
							/>
							<?php esc_html_e( 'Show ID column for Users', 'wp-powersuite' ); ?>
						</label>
						<p class="description">
							<?php esc_html_e( 'When enabled, an ID column will be displayed in the Users admin screen.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'Media Library', 'wp-powersuite' ); ?>
						<?php if ( ! $premium_unlocked ) : ?>
							<span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span>
						<?php endif; ?>
					</th>
					<td>
						<label>
							<input
								type="checkbox"
								name="show_media_ids"
								value="1"
								<?php checked( ! empty( $settings['show_media_ids'] ) ); ?>
								<?php disabled( ! $premium_unlocked ); ?>
								class="wp-powersuite-advanced-setting"
								data-setting-key="show_media_ids"
							/>
							<?php esc_html_e( 'Show ID column for Media Library', 'wp-powersuite' ); ?>
						</label>
						<p class="description">
							<?php esc_html_e( 'When enabled, an ID column will be displayed in the Media Library list.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'Comments', 'wp-powersuite' ); ?>
						<?php if ( ! $premium_unlocked ) : ?>
							<span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span>
						<?php endif; ?>
					</th>
					<td>
						<label>
							<input
								type="checkbox"
								name="show_comment_ids"
								value="1"
								<?php checked( ! empty( $settings['show_comment_ids'] ) ); ?>
								<?php disabled( ! $premium_unlocked ); ?>
								class="wp-powersuite-advanced-setting"
								data-setting-key="show_comment_ids"
							/>
							<?php esc_html_e( 'Show ID column for Comments', 'wp-powersuite' ); ?>
						</label>
						<p class="description">
							<?php esc_html_e( 'When enabled, an ID column will be displayed in the Comments admin screen.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'Action Rows', 'wp-powersuite' ); ?>
						<?php if ( ! $premium_unlocked ) : ?>
							<span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span>
						<?php endif; ?>
					</th>
					<td>
						<label>
							<input
								type="checkbox"
								name="show_id_in_action_row"
								value="1"
								<?php checked( ! empty( $settings['show_id_in_action_row'] ) ); ?>
								<?php disabled( ! $premium_unlocked ); ?>
								class="wp-powersuite-advanced-setting"
								data-setting-key="show_id_in_action_row"
							/>
							<?php esc_html_e( 'Show ID in action rows (Edit, View, etc.)', 'wp-powersuite' ); ?>
						</label>
						<p class="description">
							<?php esc_html_e( 'Adds the item ID next to row action links. Useful when columns are hidden or on smaller screens.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'Frontend Admin Bar', 'wp-powersuite' ); ?>
						<?php if ( ! $premium_unlocked ) : ?>
							<span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span>
						<?php endif; ?>
					</th>
					<td>
						<label>
							<input
								type="checkbox"
								name="show_frontend_admin_bar"
								value="1"
								<?php checked( ! empty( $settings['show_frontend_admin_bar'] ) ); ?>
								<?php disabled( ! $premium_unlocked ); ?>
								class="wp-powersuite-advanced-setting"
								data-setting-key="show_frontend_admin_bar"
							/>
							<?php esc_html_e( 'Show page/post ID in frontend admin bar', 'wp-powersuite' ); ?>
						</label>
						<p class="description">
							<?php esc_html_e( 'When enabled, the current page/post ID will be displayed in the WordPress admin bar on the frontend. Works for posts, pages, categories, tags, and author pages.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
			</tbody>
		</table>
	</form>

	<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>
</div>
