<?php

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

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

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

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 );

$taxonomies_selected = $settings['taxonomies'];
$taxonomy_objects    = TaxonomyHelper::getAvailableTaxonomyObjects();

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

?>
<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.', 'wp-powersuite' ); ?>
	</p>
	<p class="description">
		<strong><?php esc_html_e( 'Note:', 'wp-powersuite' ); ?></strong>
		<?php esc_html_e( 'This module stores custom order values in term meta for selected taxonomies.', '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' ); ?>

		<h3><?php esc_html_e( 'General', 'wp-powersuite' ); ?></h3>
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><?php esc_html_e( 'Reorder interface', 'wp-powersuite' ); ?></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', 'wp-powersuite' ); ?>
						</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', 'wp-powersuite' ); ?>
						</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.', 'wp-powersuite' ); ?></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', 'wp-powersuite' ); ?></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.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>

		<h3><?php esc_html_e( 'Taxonomies', 'wp-powersuite' ); ?></h3>
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><?php esc_html_e( 'Supported taxonomies', 'wp-powersuite' ); ?></th>
					<td>
						<?php if ( empty( $taxonomy_objects ) ) : ?>
							<p class="description"><?php esc_html_e( 'No manageable public taxonomies are available for your account.', 'wp-powersuite' ); ?></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...', '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 ); ?>_taxonomies_list">
									<span class="wpps-ct-multiselect__trigger-text"><?php esc_html_e( 'Select taxonomies...', '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 ); ?>_taxonomies_list" role="listbox" hidden>
									<input type="text" class="wpps-ct-multiselect__search" placeholder="<?php esc_attr_e( 'Search taxonomies...', '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 ( $taxonomy_objects as $slug => $object ) : ?>
											<?php $checked = in_array( $slug, $taxonomies_selected, true ); ?>
											<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 ); ?>
												/>
												<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>
											</label>
										<?php endforeach; ?>
									</div>
								</div>
							</div>
						<?php endif; ?>
					</td>
				</tr>
			</tbody>
		</table>

		<h3><?php esc_html_e( 'Query behavior', 'wp-powersuite' ); ?></h3>
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><?php esc_html_e( 'Apply custom order', 'wp-powersuite' ); ?></th>
					<td>
						<fieldset>
							<?php
							$apply_flags = [
								'apply_frontend' => __( 'Frontend term lists', 'wp-powersuite' ),
								'apply_archives' => __( 'Archive pages', 'wp-powersuite' ),
								'apply_widgets'  => __( 'Widgets (e.g. Categories)', 'wp-powersuite' ),
								'apply_menus'    => __( 'Menus (term pickers in menu editor)', 'wp-powersuite' ),
								'apply_admin'    => __( 'Admin term tables', 'wp-powersuite' ),
							];
							foreach ( $apply_flags as $key => $label ) :
								?>
								<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 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.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Query behavior', 'wp-powersuite' ); ?></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)', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
			</tbody>
		</table>

		<h3><?php esc_html_e( 'Reset', 'wp-powersuite' ); ?></h3>
		<p class="description"><?php esc_html_e( 'Reset term order meta for all terms in a selected taxonomy. This action cannot be undone.', 'wp-powersuite' ); ?></p>
		<p>
			<label for="<?php echo esc_attr( $module_id ); ?>_reset_taxonomy" class="screen-reader-text"><?php esc_html_e( 'Taxonomy to reset', 'wp-powersuite' ); ?></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 esc_html_e( 'Reset all ordering', 'wp-powersuite' ); ?></button>
			<span id="<?php echo esc_attr( $module_id ); ?>_reset_status" class="description" aria-live="polite"></span>
		</p>
	</form>

	<?php if ( ! empty( $taxonomy_objects ) ) : ?>
	<script>
	(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.', 'wp-powersuite' ) ); ?>)) 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.', 'wp-powersuite' ) ); ?>;
			}).finally(function () { btn.disabled = false; });
		});
	})();
	</script>
	<?php endif; ?>
</div>
