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

if ( ! function_exists( 'wp_powersuite_is_license_valid' ) || ! wp_powersuite_is_license_valid() ) {
	$license_page_url = admin_url( 'admin.php?page=powersuite-license' );
	?>
	<div class="wp-powersuite-module-settings wpps-settings-panel" data-module-id="<?php echo esc_attr( $module_id ?? 'public-preview-for-drafts' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Share Draft Preview Links requires an active license. Activate your license to generate expiring preview URLs for unpublished content.', 'wppowersuite-lite' ); ?>
				<a href="<?php echo esc_url( $license_page_url ); ?>"><?php esc_html_e( 'Activate license', 'wppowersuite-lite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'public-preview-for-drafts';
}

$raw      = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
$settings = class_exists( '\PublicPreviewForDrafts\Module' )
	? \PublicPreviewForDrafts\Module::normalizeSettings( is_array( $raw ) ? $raw : [] )
	: [
		'enabled_post_types' => [],
		'max_days'           => 3,
	];

$enabled_post_types = $settings['enabled_post_types'];
$max_days           = (int) $settings['max_days'];

$post_types = get_post_types( [ 'public' => true ], 'objects' );
$excluded_types = [ 'attachment', 'revision', 'nav_menu_item' ];
$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" data-module-id="<?php echo esc_attr( $module_id ); ?>">
	<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( 'Enable for Post Types:', 'wppowersuite-lite' ); ?></label>
					</th>
					<td>
						<?php if ( empty( $available_post_types ) ) : ?>
							<p class="description"><?php esc_html_e( 'No public post types found.', 'wppowersuite-lite' ); ?></p>
						<?php else : ?>
							<p class="description" style="margin-bottom: 8px;"><?php esc_html_e( 'Choose post types that may use public preview. Drafts show a link in the post list, in the block editor sidebar (Document), and in the classic Publish box.', 'wppowersuite-lite' ); ?></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...', 'wppowersuite-lite' ) ); ?>"
								data-label-single="<?php echo esc_attr( __( '1 selected', 'wppowersuite-lite' ) ); ?>"
								<?php /* translators: %d: number value. */ ?>
								data-label-multi="<?php echo esc_attr( __( '%d selected', 'wppowersuite-lite' ) ); ?>">
								<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...', 'wppowersuite-lite' ); ?></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...', 'wppowersuite-lite' ); ?>" 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', 'wppowersuite-lite' ); ?></button>
										<button type="button" class="wpps-ct-multiselect__action" data-action="clear"><?php esc_html_e( 'Clear', 'wppowersuite-lite' ); ?></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="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>
						<?php endif; ?>
					</td>
				</tr>

				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_max_days">
							<?php esc_html_e( 'Preview Link Expiry (Days)', 'wppowersuite-lite' ); ?>
						</label>
					</th>
					<td>
						<input
							type="number"
							id="<?php echo esc_attr( $module_id ); ?>_max_days"
							name="max_days"
							value="<?php echo esc_attr( $max_days ); ?>"
							min="1"
							max="30"
							class="small-text wp-powersuite-advanced-setting"
							data-setting-key="max_days"
						/>
						<p class="description">
							<?php esc_html_e( 'Number of days before the preview link expires. Default is 3 days.', 'wppowersuite-lite' ); ?>
						</p>
					</td>
				</tr>
			</tbody>
		</table>
	</form>

	<?php if ( ! empty( $available_post_types ) ) : ?>
	<?php ob_start(); ?>
		(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();
		})();
<?php \WP_PowerSuite\Core\InlineAssets::script( 'wpps-ia-modules-public-preview-for-drafts-admin-php-script-1', (string) ob_get_clean() ); ?>
	<?php endif; ?>
</div>

