<?php

use CustomPostOrder\Includes\PostTypeHelper;
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

require_once __DIR__ . '/includes/class-post-type-helper.php';

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

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

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

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

$defaults = \CustomPostOrder\Module::getDefaultSettings();
$settings = array_merge( $defaults, $settings );
$settings = \CustomPostOrder\Module::normalizeSettings( $settings );

$post_types_selected = $settings['post_types'];
$post_type_objects   = PostTypeHelper::getAvailablePostTypeObjects();

$capability_options = [
	'edit_others_posts' => __( 'Edit others\' posts (edit_others_posts)', 'wp-powersuite' ),
	'edit_posts'        => __( 'Edit posts (edit_posts)', 'wp-powersuite' ),
	'edit_pages'        => __( 'Edit pages (edit_pages)', 'wp-powersuite' ),
	'publish_posts'     => __( 'Publish posts (publish_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 items to control their display order. This order can be applied to frontend 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 changes the WordPress menu_order value for selected content.', '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"><?php esc_html_e( 'Supported post types', 'wp-powersuite' ); ?></th>
					<td>
						<?php if ( empty( $post_type_objects ) ) : ?>
							<p class="description"><?php esc_html_e( 'No editable public post types are available for your account.', 'wp-powersuite' ); ?></p>
						<?php else : ?>
							<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 ( $post_type_objects as $slug => $object ) : ?>
											<?php $checked = in_array( $slug, $post_types_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="post_types[]"
													class="wp-powersuite-advanced-setting"
													data-setting-key="post_types"
													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>
				<tr>
					<th scope="row"><?php esc_html_e( 'Reorder interface', 'wp-powersuite' ); ?></th>
					<td>
						<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 post type list table so you can reorder by dragging. Changes save automatically on drop. Works when no search is active and the list is sorted by menu order.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Apply custom order', 'wp-powersuite' ); ?></th>
					<td>
						<fieldset>
							<input type="hidden" name="apply_frontend_main" class="wp-powersuite-advanced-setting" data-setting-key="apply_frontend_main" value="0" />
							<label><input type="checkbox" name="apply_frontend_main" class="wp-powersuite-advanced-setting" data-setting-key="apply_frontend_main" value="1" <?php checked( ! empty( $settings['apply_frontend_main'] ) ); ?> /> <?php esc_html_e( 'Frontend main query (blog home, post type archives)', 'wp-powersuite' ); ?></label><br />
							<input type="hidden" name="apply_frontend_archive" class="wp-powersuite-advanced-setting" data-setting-key="apply_frontend_archive" value="0" />
							<label><input type="checkbox" name="apply_frontend_archive" class="wp-powersuite-advanced-setting" data-setting-key="apply_frontend_archive" value="1" <?php checked( ! empty( $settings['apply_frontend_archive'] ) ); ?> /> <?php esc_html_e( 'Frontend archive queries', 'wp-powersuite' ); ?></label><br />
							<input type="hidden" name="apply_frontend_search" class="wp-powersuite-advanced-setting" data-setting-key="apply_frontend_search" value="0" />
							<label><input type="checkbox" name="apply_frontend_search" class="wp-powersuite-advanced-setting" data-setting-key="apply_frontend_search" value="1" <?php checked( ! empty( $settings['apply_frontend_search'] ) ); ?> /> <?php esc_html_e( 'Search results', 'wp-powersuite' ); ?></label><br />
							<input type="hidden" name="apply_admin" class="wp-powersuite-advanced-setting" data-setting-key="apply_admin" value="0" />
							<label><input type="checkbox" name="apply_admin" class="wp-powersuite-advanced-setting" data-setting-key="apply_admin" value="1" <?php checked( ! empty( $settings['apply_admin'] ) ); ?> /> <?php esc_html_e( 'Admin list tables', 'wp-powersuite' ); ?></label><br />
						</fieldset>
					</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>
						<p class="description"><?php esc_html_e( 'When enabled, queries that already define orderby are left unchanged.', '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 edit access to each post type and individual item.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>
	</form>

	<?php if ( ! empty( $post_type_objects ) ) : ?>
	<hr />
	<h3><?php esc_html_e( 'Reset ordering', 'wp-powersuite' ); ?></h3>
	<p class="description"><?php esc_html_e( 'Reset menu_order to 0 for all items in a selected post type. This action cannot be undone.', 'wp-powersuite' ); ?></p>
	<p>
		<label for="<?php echo esc_attr( $module_id ); ?>_reset_post_type" class="screen-reader-text"><?php esc_html_e( 'Post type to reset', 'wp-powersuite' ); ?></label>
		<select id="<?php echo esc_attr( $module_id ); ?>_reset_post_type">
			<?php foreach ( $post_type_objects as $slug => $object ) : ?>
				<?php if ( ! in_array( $slug, $post_types_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>
	<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_post_type' ); ?>);
		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 menu order for this post type? This cannot be undone.', 'wp-powersuite' ) ); ?>)) {
				return;
			}
			btn.disabled = true;
			status.textContent = '';
			var body = new URLSearchParams();
			body.set('action', 'wpps_cpo_reset_order');
			body.set('nonce', <?php echo wp_json_encode( wp_create_nonce( 'wpps_custom_post_order' ) ); ?>);
			body.set('post_type', 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>
