<?php

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

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

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

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 );
$premium_unlocked    = FeatureGate::isPremiumLicensed();
$post_types_selected = $settings['post_types'];
$settings            = FeatureGate::applyPremiumTierLimits( $settings );
$post_type_objects   = PostTypeHelper::getAvailablePostTypeObjects();

$capability_options = [
	'edit_others_posts' => __( 'Edit others\' posts (edit_others_posts)', 'wppowersuite-lite' ),
	'edit_posts'        => __( 'Edit posts (edit_posts)', 'wppowersuite-lite' ),
	'edit_pages'        => __( 'Edit pages (edit_pages)', 'wppowersuite-lite' ),
	'publish_posts'     => __( 'Publish posts (publish_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 items to control their display order. This order can be applied to frontend 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 changes the WordPress menu_order value for selected content.', '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' ); ?>

		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'Supported post types', 'wppowersuite-lite' ); ?>
						<?php
						if ( ! $premium_unlocked && function_exists( 'wpps_render_premium_badge' ) ) {
							wpps_render_premium_badge();
						}
						?>
					</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.', 'wppowersuite-lite' ); ?></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...', '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 ( $post_type_objects as $slug => $object ) : ?>
											<?php
											$checked      = in_array( $slug, $post_types_selected, true );
											$is_free_type = FeatureGate::isFreePostType( $slug );
											$lock_type    = ! $premium_unlocked && ! $is_free_type;
											?>
											<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 ); ?>
													<?php disabled( $lock_type ); ?>
												/>
												<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_type && 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( 'Posts and Pages are included. Custom post types require Premium.', 'wppowersuite-lite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Reorder interface', 'wppowersuite-lite' ); ?></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', 'wppowersuite-lite' ); ?>
						</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.', 'wppowersuite-lite' ); ?></p>
					</td>
				</tr>
				<?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>
							<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)', 'wppowersuite-lite' ); ?></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 disabled( ! $premium_unlocked ); ?> /> <?php esc_html_e( 'Frontend archive queries', 'wppowersuite-lite' ); ?></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 disabled( ! $premium_unlocked ); ?> /> <?php esc_html_e( 'Search results', 'wppowersuite-lite' ); ?></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 disabled( ! $premium_unlocked ); ?> /> <?php esc_html_e( 'Admin list tables', 'wppowersuite-lite' ); ?></label><br />
						</fieldset>
					</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>
						<p class="description"><?php esc_html_e( 'When enabled, queries that already define orderby are left unchanged.', '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 edit access to each post type and individual item.', 'wppowersuite-lite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>
	</form>

	<?php if ( ! empty( $post_type_objects ) ) : ?>
	<hr />
	<h3>
		<?php esc_html_e( 'Reset ordering', '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 menu_order to 0 for all items in a selected post type. This action cannot be undone.', 'wppowersuite-lite' ); ?></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', 'wppowersuite-lite' ); ?></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 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>
	<?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_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.', 'wppowersuite-lite' ) ); ?>)) {
				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.', 'wppowersuite-lite' ) ); ?>;
				})
				.finally(function () {
					btn.disabled = false;
				});
		});
	})();
<?php \WP_PowerSuite\Core\InlineAssets::script( 'wpps-ia-modules-custom-post-order-admin-php-script-1', (string) ob_get_clean() ); ?>
	<?php endif; ?>
</div>

