<?php

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

use CustomTaxonomyOrder\FeatureGate;
use CustomTaxonomyOrder\Includes\TaxonomyHelper;
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

require_once __DIR__ . '/includes/class-taxonomy-helper.php';
require_once __DIR__ . '/FeatureGate.php';

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

if ( ! isset( $module_id ) || $module_id === '' ) {
	$module_id = 'custom-taxonomy-order';
}

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

$defaults = \CustomTaxonomyOrder\Module::getDefaultSettings();
$settings = array_merge( $defaults, $settings );
$settings = \CustomTaxonomyOrder\Module::normalizeSettings( $settings );
$premium_unlocked    = FeatureGate::isPremiumLicensed();
$taxonomies_selected = $settings['taxonomies'];
$settings            = FeatureGate::applyPremiumTierLimits( $settings );
$taxonomy_objects    = TaxonomyHelper::getAvailableTaxonomyObjects();

$capability_options = [
	'manage_categories' => __( 'Manage categories (manage_categories)', 'wppowersuite-lite' ),
	'manage_terms'      => __( 'Manage terms (manage_terms)', 'wppowersuite-lite' ),
	'edit_posts'        => __( 'Edit posts (edit_posts)', 'wppowersuite-lite' ),
	'manage_options'    => __( 'Manage options (manage_options)', 'wppowersuite-lite' ),
];

?>
<div class="wp-powersuite-module-settings" data-module-id="<?php echo esc_attr( $module_id ); ?>">
	<p class="description">
		<?php esc_html_e( 'Drag terms to control their display order. This order can be applied to frontend term lists, widgets, menus, archives, and supported queries depending on your settings.', 'wppowersuite-lite' ); ?>
	</p>
	<p class="description">
		<strong><?php esc_html_e( 'Note:', 'wppowersuite-lite' ); ?></strong>
		<?php esc_html_e( 'This module stores custom order values in term meta for selected taxonomies.', 'wppowersuite-lite' ); ?>
	</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' ); ?>

		<h3><?php esc_html_e( 'General', 'wppowersuite-lite' ); ?></h3>
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><?php esc_html_e( 'Reorder interface', 'wppowersuite-lite' ); ?></th>
					<td>
						<input type="hidden" name="enable_list_table_column" class="wp-powersuite-advanced-setting" data-setting-key="enable_list_table_column" value="0" />
						<label>
							<input type="checkbox" name="enable_list_table_column" class="wp-powersuite-advanced-setting" data-setting-key="enable_list_table_column" value="1" <?php checked( ! empty( $settings['enable_list_table_column'] ) ); ?> />
							<?php esc_html_e( 'Show order column on term list tables', 'wppowersuite-lite' ); ?>
						</label>
						<br />
						<input type="hidden" name="enable_list_table_dnd" class="wp-powersuite-advanced-setting" data-setting-key="enable_list_table_dnd" value="0" />
						<label>
							<input type="checkbox" name="enable_list_table_dnd" class="wp-powersuite-advanced-setting" data-setting-key="enable_list_table_dnd" value="1" <?php checked( ! empty( $settings['enable_list_table_dnd'] ) ); ?> />
							<?php esc_html_e( 'Enable list table drag-and-drop', 'wppowersuite-lite' ); ?>
						</label>
						<p class="description"><?php esc_html_e( 'Adds a drag handle to each row on the taxonomy list table so you can reorder terms by dragging. Changes save automatically on drop. Works when no search is active.', 'wppowersuite-lite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_reorder_capability"><?php esc_html_e( 'Capability required to reorder', 'wppowersuite-lite' ); ?></label>
					</th>
					<td>
						<select id="<?php echo esc_attr( $module_id ); ?>_reorder_capability" name="reorder_capability" class="wp-powersuite-advanced-setting" data-setting-key="reorder_capability">
							<?php foreach ( $capability_options as $cap => $label ) : ?>
								<option value="<?php echo esc_attr( $cap ); ?>" <?php selected( $settings['reorder_capability'], $cap ); ?>><?php echo esc_html( $label ); ?></option>
							<?php endforeach; ?>
						</select>
						<p class="description"><?php esc_html_e( 'Users must also have manage/edit access for each taxonomy and term.', 'wppowersuite-lite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>

		<h3><?php esc_html_e( 'Taxonomies', 'wppowersuite-lite' ); ?></h3>
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'Supported taxonomies', 'wppowersuite-lite' ); ?>
						<?php
						if ( ! $premium_unlocked && function_exists( 'wpps_render_premium_badge' ) ) {
							wpps_render_premium_badge();
						}
						?>
					</th>
					<td>
						<?php if ( empty( $taxonomy_objects ) ) : ?>
							<p class="description"><?php esc_html_e( 'No manageable public taxonomies are available for your account.', 'wppowersuite-lite' ); ?></p>
						<?php else : ?>
							<div class="wpps-ct-multiselect" id="<?php echo esc_attr( $module_id ); ?>_taxonomies_ms"
								data-label-none="<?php echo esc_attr( __( 'Select taxonomies...', '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 ); ?>_taxonomies_list">
									<span class="wpps-ct-multiselect__trigger-text"><?php esc_html_e( 'Select taxonomies...', '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 ); ?>_taxonomies_list" role="listbox" hidden>
									<input type="text" class="wpps-ct-multiselect__search" placeholder="<?php esc_attr_e( 'Search taxonomies...', '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 ( $taxonomy_objects as $slug => $object ) : ?>
											<?php
											$checked         = in_array( $slug, $taxonomies_selected, true );
											$is_free_taxonomy = FeatureGate::isFreeTaxonomy( $slug );
											$lock_taxonomy    = ! $premium_unlocked && ! $is_free_taxonomy;
											?>
											<label class="wpps-ct-multiselect__option" data-slug="<?php echo esc_attr( $slug ); ?>" data-label="<?php echo esc_attr( $object->labels->name ); ?>">
												<input type="checkbox"
													name="taxonomies[]"
													class="wp-powersuite-advanced-setting"
													data-setting-key="taxonomies"
													value="<?php echo esc_attr( $slug ); ?>"
													<?php checked( $checked ); ?>
													<?php disabled( $lock_taxonomy ); ?>
												/>
												<span class="wpps-ct-multiselect__option-label"><?php echo esc_html( $object->labels->name ); ?></span>
												<span class="wpps-ct-multiselect__option-slug">(<?php echo esc_html( $slug ); ?>)</span>
												<?php
												if ( $lock_taxonomy && function_exists( 'wpps_render_premium_badge' ) ) {
													wpps_render_premium_badge();
												}
												?>
											</label>
										<?php endforeach; ?>
									</div>
								</div>
							</div>
						<?php endif; ?>
						<p class="description"><?php esc_html_e( 'Categories and Tags are included. Custom taxonomies require Premium.', 'wppowersuite-lite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>

		<h3><?php esc_html_e( 'Query behavior', 'wppowersuite-lite' ); ?></h3>
		<table class="form-table" role="presentation">
			<tbody>
				<?php if ( ! $premium_unlocked && function_exists( 'wpps_render_premium_upsell_notice' ) ) : ?>
				<tr>
					<td colspan="2">
						<?php wpps_render_premium_upsell_notice(); ?>
					</td>
				</tr>
				<?php endif; ?>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'Apply custom order', 'wppowersuite-lite' ); ?>
						<?php
						if ( ! $premium_unlocked && function_exists( 'wpps_render_premium_badge' ) ) {
							wpps_render_premium_badge();
						}
						?>
					</th>
					<td>
						<fieldset>
							<?php
							$apply_flags = [
								'apply_frontend' => __( 'Frontend term lists', 'wppowersuite-lite' ),
								'apply_widgets'  => __( 'Widgets (e.g. Categories)', 'wppowersuite-lite' ),
								'apply_archives' => __( 'Archive pages', 'wppowersuite-lite' ),
								'apply_menus'    => __( 'Menus (term pickers in menu editor)', 'wppowersuite-lite' ),
								'apply_admin'    => __( 'Admin term tables', 'wppowersuite-lite' ),
							];
							foreach ( $apply_flags as $key => $label ) :
								$lock_flag = ! $premium_unlocked && in_array( $key, FeatureGate::PREMIUM_KEYS, true );
								?>
								<input type="hidden" name="<?php echo esc_attr( $key ); ?>" class="wp-powersuite-advanced-setting" data-setting-key="<?php echo esc_attr( $key ); ?>" value="0" />
								<label><input type="checkbox" name="<?php echo esc_attr( $key ); ?>" class="wp-powersuite-advanced-setting" data-setting-key="<?php echo esc_attr( $key ); ?>" value="1" <?php checked( ! empty( $settings[ $key ] ) ); ?> <?php disabled( $lock_flag ); ?> /> <?php echo esc_html( $label ); ?></label><br />
							<?php endforeach; ?>
						</fieldset>
						<p class="description"><?php esc_html_e( 'Does not change nav menu item order inside WordPress menus.', 'wppowersuite-lite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Query behavior', 'wppowersuite-lite' ); ?></th>
					<td>
						<input type="hidden" name="respect_existing_order" class="wp-powersuite-advanced-setting" data-setting-key="respect_existing_order" value="0" />
						<label>
							<input type="checkbox" name="respect_existing_order" class="wp-powersuite-advanced-setting" data-setting-key="respect_existing_order" value="1" <?php checked( ! empty( $settings['respect_existing_order'] ) ); ?> />
							<?php esc_html_e( 'Respect existing query order (recommended)', 'wppowersuite-lite' ); ?>
						</label>
					</td>
				</tr>
			</tbody>
		</table>

		<h3>
			<?php esc_html_e( 'Reset', 'wppowersuite-lite' ); ?>
			<?php
			if ( ! $premium_unlocked && function_exists( 'wpps_render_premium_badge' ) ) {
				wpps_render_premium_badge();
			}
			?>
		</h3>
		<?php
		if ( ! $premium_unlocked && function_exists( 'wpps_render_premium_upsell_notice' ) ) {
			wpps_render_premium_upsell_notice();
		}
		?>
		<p class="description"><?php esc_html_e( 'Reset term order meta for all terms in a selected taxonomy. This action cannot be undone.', 'wppowersuite-lite' ); ?></p>
		<p>
			<label for="<?php echo esc_attr( $module_id ); ?>_reset_taxonomy" class="screen-reader-text"><?php esc_html_e( 'Taxonomy to reset', 'wppowersuite-lite' ); ?></label>
			<select id="<?php echo esc_attr( $module_id ); ?>_reset_taxonomy">
				<?php foreach ( $taxonomy_objects as $slug => $object ) : ?>
					<?php if ( ! in_array( $slug, $taxonomies_selected, true ) ) { continue; } ?>
					<option value="<?php echo esc_attr( $slug ); ?>"><?php echo esc_html( $object->labels->name ); ?></option>
				<?php endforeach; ?>
			</select>
			<button type="button" class="button button-secondary" id="<?php echo esc_attr( $module_id ); ?>_reset_order_btn" <?php disabled( ! $premium_unlocked ); ?>><?php esc_html_e( 'Reset all ordering', 'wppowersuite-lite' ); ?></button>
			<span id="<?php echo esc_attr( $module_id ); ?>_reset_status" class="description" aria-live="polite"></span>
		</p>
	</form>

	<?php if ( ! empty( $taxonomy_objects ) ) : ?>
	<?php ob_start(); ?>
	(function () {
		var btn = document.getElementById(<?php echo wp_json_encode( $module_id . '_reset_order_btn' ); ?>);
		var select = document.getElementById(<?php echo wp_json_encode( $module_id . '_reset_taxonomy' ); ?>);
		var status = document.getElementById(<?php echo wp_json_encode( $module_id . '_reset_status' ); ?>);
		if (!btn || !select) return;
		btn.addEventListener('click', function () {
			if (!window.confirm(<?php echo wp_json_encode( __( 'Reset term order for this taxonomy? Stored order values will be deleted.', 'wppowersuite-lite' ) ); ?>)) return;
			btn.disabled = true;
			status.textContent = '';
			var body = new URLSearchParams();
			body.set('action', 'wpps_cto_reset_order');
			body.set('nonce', <?php echo wp_json_encode( wp_create_nonce( 'wpps_custom_taxonomy_order' ) ); ?>);
			body.set('taxonomy', select.value || '');
			body.set('parent_id', '0');
			body.set('reset_all', '1');
			fetch(<?php echo wp_json_encode( admin_url( 'admin-ajax.php' ) ); ?>, {
				method: 'POST', credentials: 'same-origin',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
				body: body.toString()
			}).then(function (r) { return r.json(); }).then(function (data) {
				status.textContent = (data && data.data && data.data.message) || (data && data.success ? 'OK' : 'Error');
			}).catch(function () {
				status.textContent = <?php echo wp_json_encode( __( 'Request failed.', 'wppowersuite-lite' ) ); ?>;
			}).finally(function () { btn.disabled = false; });
		});
	})();
<?php \WP_PowerSuite\Core\InlineAssets::script( 'wpps-ia-modules-custom-taxonomy-order-admin-php-script-1', (string) ob_get_clean() ); ?>
	<?php endif; ?>
</div>

