<?php
/**
 * Advanced settings (modal) for Post Views Counter.
 *
 * @package PostViewsCounter
 */

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

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

$module_id = $module_id ?? 'post-views-counter';

$raw      = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
$settings = class_exists( '\PostViewsCounter\Module' )
	? \PostViewsCounter\Module::normalizeSettings( is_array( $raw ) ? $raw : [] )
	: array_merge( [
		'enabled_post_types'     => [ 'post' ],
		'count_interval_hours'   => 24,
		'exclude_bots'           => true,
		'exclude_empty_ua'       => false,
		'exclude_own_posts'      => true,
		'exclude_password_posts' => true,
		'auto_insert'            => false,
		'position'               => 'after_content',
		'label_template'         => '%views% views',
		'skip_if_shortcode'      => true,
	], is_array( $raw ) ? $raw : [] );

$enabled_post_types = $settings['enabled_post_types'];

$excluded_types       = [ 'attachment', 'revision', 'nav_menu_item', 'custom_css', 'customize_changeset', 'oembed_cache', 'user_request', 'wp_block' ];
$post_types           = get_post_types( [ 'public' => true ], 'objects' );
$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;
	}
}

$exclude_bots           = ! empty( $settings['exclude_bots'] );
$exclude_empty_ua       = ! empty( $settings['exclude_empty_ua'] );
$exclude_own_posts      = ! empty( $settings['exclude_own_posts'] );
$exclude_password_posts = ! empty( $settings['exclude_password_posts'] );
$auto_insert            = ! empty( $settings['auto_insert'] );
$skip_if_shortcode      = ! empty( $settings['skip_if_shortcode'] );
$count_interval_hours   = isset( $settings['count_interval_hours'] ) ? max( 1, min( 168, (int) $settings['count_interval_hours'] ) ) : 24;
$position               = isset( $settings['position'] ) ? (string) $settings['position'] : 'after_content';
$label_template         = (string) $settings['label_template'];
?>

<div class="wp-powersuite-module-settings">
	<p class="description">
		<?php esc_html_e( 'Views are stored in post meta and deduplicated with a transient per visitor (logged-in user ID or a first-party cookie). Counting runs once per full singular request, not in the REST API, AJAX, feeds, or prefetch. Enabled post types get a sortable Views column in the admin list.', '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>
						<?php if ( empty( $available_post_types ) ) : ?>
							<p class="description"><?php esc_html_e( 'No public post types found.', 'wp-powersuite' ); ?></p>
						<?php else : ?>
							<p class="description" style="margin-bottom:8px;"><?php esc_html_e( 'Which types to track, allow in the shortcode, and show a Views column in the admin list.', '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, $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 ); ?>_interval"><?php esc_html_e( 'Count interval (hours)', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<input type="number"
							id="<?php echo esc_attr( $module_id ); ?>_interval"
							name="count_interval_hours"
							class="small-text wp-powersuite-advanced-setting"
							data-setting-key="count_interval_hours"
							value="<?php echo esc_attr( (string) $count_interval_hours ); ?>"
							min="1"
							max="168"
							step="1"
						/>
						<p class="description"><?php esc_html_e( 'Minimum time before the same visitor increments the same post again (1–168 hours).', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Counting rules', 'wp-powersuite' ); ?></th>
					<td>
						<label class="wp-powersuite-toggle-wrap" style="display:block;margin-bottom:8px;">
							<input type="checkbox" name="exclude_bots" value="1" class="wp-powersuite-advanced-setting" data-setting-key="exclude_bots" <?php checked( $exclude_bots ); ?> />
							<span class="description"><?php esc_html_e( 'Skip common crawlers and monitoring user-agents (heuristic)', 'wp-powersuite' ); ?></span>
						</label>
						<label class="wp-powersuite-toggle-wrap" style="display:block;margin-bottom:8px;">
							<input type="checkbox" name="exclude_empty_ua" value="1" class="wp-powersuite-advanced-setting" data-setting-key="exclude_empty_ua" <?php checked( $exclude_empty_ua ); ?> />
							<span class="description"><?php esc_html_e( 'Treat empty User-Agent as a bot (stricter; may block rare clients)', 'wp-powersuite' ); ?></span>
						</label>
						<label class="wp-powersuite-toggle-wrap" style="display:block;margin-bottom:8px;">
							<input type="checkbox" name="exclude_own_posts" value="1" class="wp-powersuite-advanced-setting" data-setting-key="exclude_own_posts" <?php checked( $exclude_own_posts ); ?> />
							<span class="description"><?php esc_html_e( 'Do not count when the viewer can edit the post', 'wp-powersuite' ); ?></span>
						</label>
						<label class="wp-powersuite-toggle-wrap" style="display:block;">
							<input type="checkbox" name="exclude_password_posts" value="1" class="wp-powersuite-advanced-setting" data-setting-key="exclude_password_posts" <?php checked( $exclude_password_posts ); ?> />
							<span class="description"><?php esc_html_e( 'Do not count password-protected posts until unlocked (still skips if required)', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_auto_insert"><?php esc_html_e( 'Auto insert', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<label class="wp-powersuite-toggle-wrap">
							<input type="checkbox"
								id="<?php echo esc_attr( $module_id ); ?>_auto_insert"
								name="auto_insert"
								value="1"
								class="wp-powersuite-advanced-setting"
								data-setting-key="auto_insert"
								<?php checked( $auto_insert ); ?>
							/>
							<span class="description"><?php esc_html_e( 'Show the view count in the content on the main singular query (off by default).', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_position"><?php esc_html_e( 'Position', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<select id="<?php echo esc_attr( $module_id ); ?>_position"
							name="position"
							class="wp-powersuite-advanced-setting"
							data-setting-key="position">
							<option value="before_content" <?php selected( $position, 'before_content' ); ?>><?php esc_html_e( 'Before content', 'wp-powersuite' ); ?></option>
							<option value="before_first_paragraph" <?php selected( $position, 'before_first_paragraph' ); ?>><?php esc_html_e( 'Before first paragraph', 'wp-powersuite' ); ?></option>
							<option value="after_first_paragraph" <?php selected( $position, 'after_first_paragraph' ); ?>><?php esc_html_e( 'After first paragraph', 'wp-powersuite' ); ?></option>
							<option value="after_content" <?php selected( $position, 'after_content' ); ?>><?php esc_html_e( 'After content', 'wp-powersuite' ); ?></option>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_template"><?php esc_html_e( 'Label template', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<input type="text"
							id="<?php echo esc_attr( $module_id ); ?>_template"
							name="label_template"
							class="large-text wp-powersuite-advanced-setting"
							data-setting-key="label_template"
							value="<?php echo esc_attr( $label_template ); ?>"
							maxlength="300"
						/>
						<p class="description"><?php esc_html_e( 'Use %views% for the number. Plain text is escaped on output.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_skip_sc"><?php esc_html_e( 'Shortcode', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<label class="wp-powersuite-toggle-wrap">
							<input type="checkbox"
								id="<?php echo esc_attr( $module_id ); ?>_skip_sc"
								name="skip_if_shortcode"
								value="1"
								class="wp-powersuite-advanced-setting"
								data-setting-key="skip_if_shortcode"
								<?php checked( $skip_if_shortcode ); ?>
							/>
							<span class="description"><?php esc_html_e( 'Skip auto-insert when the post contains [wpps_post_views] or [post_views]', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
			</tbody>
		</table>

		<?php if ( ! empty( $available_post_types ) ) : ?>
		
		<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 || '').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>
		<?php endif; ?>

		<div class="wp-powersuite-info-box wpps-module-callout">
			<p style="margin:0 0 8px 0;"><strong><?php esc_html_e( 'Shortcode', 'wp-powersuite' ); ?></strong></p>
			<p style="margin:0 0 8px 0;"><code>[wpps_post_views]</code> / <code>[post_views]</code> — <?php esc_html_e( 'Current singular post. Legacy tag is registered only if no other plugin already defines [post_views].', 'wp-powersuite' ); ?></p>
			<p style="margin:0 0 8px 0;"><code>[wpps_post_views id="123"]</code> — <?php esc_html_e( 'Specific post ID (published, allowed type).', 'wp-powersuite' ); ?></p>
			<p style="margin:0;"><strong><?php esc_html_e( 'PHP', 'wp-powersuite' ); ?></strong> — <code>PostViewsCounter\Module::getViewCount( $post_id )</code></p>
			<p style="margin:8px 0 0 0;"><strong><?php esc_html_e( 'Meta key', 'wp-powersuite' ); ?></strong> — <code><?php echo esc_html( class_exists( '\PostViewsCounter\Module' ) ? \PostViewsCounter\Module::META_KEY : '_wpps_post_views' ); ?></code></p>
			<p style="margin:8px 0 0 0;"><?php esc_html_e( 'Filters:', 'wp-powersuite' ); ?> <code>wp_powersuite_post_views_should_count</code>, <code>wp_powersuite_post_views_bot_score</code>, <code>wp_powersuite_post_views_line</code>, <code>wp_powersuite_post_views_the_content_priority</code>.</p>
		</div>
	</form>
</div>
