<?php
/**
 * Redirect Manager Admin Page
 *
 * @package RedirectManager
 * @since 1.0.0
 */

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

if ( ! function_exists( 'wp_powersuite_is_license_valid' ) || ! wp_powersuite_is_license_valid() ) {
	?>
	<div class="wrap">
		<h1><?php esc_html_e( 'Redirect Manager', 'wp-powersuite' ); ?></h1>
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Redirect Manager requires an active license. Activate your license to create and manage redirect rules.', 'wp-powersuite' ); ?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite-license' ) ); ?>"><?php esc_html_e( 'Activate license', 'wp-powersuite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

// Prefer passed-in module, then ModuleManager's loaded instance (has correct table_name), fallback to new instance
if ( ! isset( $module ) || ! $module instanceof \RedirectManager\Module ) {
	$manager = \WP_PowerSuite\Core\ModuleManager::getInstance();
	$module  = $manager->getModule( 'redirect-manager' );
}
$module        = $module ?? new \RedirectManager\Module();
$all_redirects = $module->getAllRedirects();
$nonce         = wp_create_nonce( 'wpps_redirect_manager' );
$edit_id       = isset( $_GET['edit'] ) ? sanitize_text_field( wp_unslash( $_GET['edit'] ) ) : '';
$add_new       = isset( $_GET['action'] ) && $_GET['action'] === 'add';
$editing       = null;
if ( $edit_id ) {
	foreach ( $all_redirects as $r ) {
		if ( ( $r['id'] ?? '' ) === $edit_id ) {
			$editing = $r;
			break;
		}
	}
}
$show_form      = $editing || $add_new;
$status_filter  = isset( $_GET['status'] ) ? sanitize_key( wp_unslash( $_GET['status'] ) ) : 'all';
if ( ! in_array( $status_filter, [ 'all', 'active', 'inactive' ], true ) ) {
	$status_filter = 'all';
}
$search = isset( $_REQUEST['s'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ) : '';

require_once __DIR__ . '/class-redirect-manager-list-table.php';
$list_table = new Redirect_Manager_List_Table( $module, $status_filter, $search, $nonce );
$list_table->prepare_items();
$list_url   = admin_url( 'admin.php?page=powersuite-redirect-manager' );
$add_url    = admin_url( 'admin.php?page=powersuite-redirect-manager&action=add' );
$export_url = wp_nonce_url( admin_url( 'admin-post.php?action=wpps_redirect_manager_export' ), 'wpps_redirect_export' );
$sample_csv = ( defined( 'WP_POWERSUITE_PLUGIN_URL' ) ? WP_POWERSUITE_PLUGIN_URL : '' ) . 'modules/redirect-manager/sample-redirects-import.csv';
?>
<div class="wrap wpps-redirect-manager<?php echo $show_form ? ' wpps-rm-edit' : ''; ?>">
	<hr class="wp-header-end" style="margin:0;padding:0;border:none;height:0;overflow:hidden;">
	<?php
	if ( $show_form ) {
		\WP_PowerSuite\Admin\PageHero::render_for_module(
			[
				'icon'    => 'dashicons-randomize',
				'title'   => $editing
					? __( 'Edit Redirect', 'wp-powersuite' )
					: __( 'Add Redirect', 'wp-powersuite' ),
				'tagline' => $editing
					? __( 'Update this redirect rule, match type, and conditions.', 'wp-powersuite' )
					: __( 'Create a redirect rule to fix broken links or handle URL changes.', 'wp-powersuite' ),
				'actions' => [
					[
						'label' => __( 'All Redirects', 'wp-powersuite' ),
						'url'   => $list_url,
						'icon'  => 'dashicons-arrow-left-alt',
					],
				],
			]
		);
	} else {
		$rm_meta = sprintf(
			'<a href="%1$s" class="button button-secondary">%2$s</a> <button type="button" class="button button-secondary" id="wpps-rm-import-toggle">%3$s</button>',
			esc_url( $export_url ),
			esc_html__( 'Export CSV', 'wp-powersuite' ),
			esc_html__( 'Import', 'wp-powersuite' )
		);
		\WP_PowerSuite\Admin\PageHero::render_for_module(
			[
				'icon'      => 'dashicons-randomize',
				'title'     => __( 'Redirect Manager', 'wp-powersuite' ),
				'tagline'   => __( 'Manage URL redirects, fix broken links, and improve SEO with 301, 302, and custom redirects.', 'wp-powersuite' ),
				'actions'   => [
					[
						'label' => __( 'Add Redirect', 'wp-powersuite' ),
						'url'   => $add_url,
						'icon'  => 'dashicons-plus-alt',
					],
				],
				'meta_html' => $rm_meta,
			]
		);
	}
	?>

	<?php if ( isset( $_GET['saved'] ) ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Redirect saved successfully.', 'wp-powersuite' ); ?></p></div>
	<?php endif; ?>
	<?php if ( isset( $_GET['deleted'] ) ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Redirect deleted.', 'wp-powersuite' ); ?></p></div>
	<?php endif; ?>
	<?php if ( isset( $_GET['bulk'] ) ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Bulk action completed.', 'wp-powersuite' ); ?></p></div>
	<?php endif; ?>
	<?php if ( isset( $_GET['imported'] ) ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php echo esc_html( sprintf( __( 'Imported %s redirects.', 'wp-powersuite' ), sanitize_text_field( wp_unslash( $_GET['imported'] ) ) ) ); ?></p></div>
	<?php endif; ?>
	<?php if ( isset( $_GET['cache_cleared'] ) ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Cache cleared.', 'wp-powersuite' ); ?></p></div>
	<?php endif; ?>
	<?php if ( isset( $_GET['message'] ) && $_GET['message'] === 'duplicated' ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Redirect duplicated. Edit the duplicate to change the source URL.', 'wp-powersuite' ); ?></p></div>
	<?php endif; ?>
	<?php if ( isset( $_GET['error'] ) ) : ?>
		<?php
		$err_msg = match ( $_GET['error'] ) {
			'missing_source' => __( 'Source URL is required.', 'wp-powersuite' ),
			'missing_target' => __( 'Target URL is required for redirects.', 'wp-powersuite' ),
			'invalid_regex' => __( 'Invalid regex pattern. Check your syntax.', 'wp-powersuite' ),
			'duplicate_source' => __( 'A redirect with this source URL already exists. Edit the existing one or use a different source.', 'wp-powersuite' ),
			'redirect_loop' => __( 'This redirect would create a loop or chain back to a previous URL. Choose a different target.', 'wp-powersuite' ),
			'import_empty' => __( 'Import failed. Select a CSV file to upload.', 'wp-powersuite' ),
			'import_too_large' => __( 'Import file is too large. Maximum size is 1 MB.', 'wp-powersuite' ),
			'import_too_many' => __( 'Import file has too many rows. Maximum is 1,000 redirects per import.', 'wp-powersuite' ),
			default => __( 'An error occurred.', 'wp-powersuite' ),
		};
		?>
		<div class="notice notice-error is-dismissible"><p><?php echo esc_html( $err_msg ); ?></p></div>
	<?php endif; ?>

	<?php if ( ! $show_form ) : ?>
	<div class="rm-import-panel" id="wpps-rm-import-panel" hidden>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" enctype="multipart/form-data">
			<input type="hidden" name="action" value="wpps_redirect_manager_import" />
			<?php wp_nonce_field( 'wpps_redirect_import', 'wpps_import_nonce' ); ?>
			<h2><?php esc_html_e( 'Import Redirects', 'wp-powersuite' ); ?></h2>
			<p class="description"><?php esc_html_e( 'Upload a CSV file with source, target, type, and match_type columns. Duplicates and invalid rows are skipped.', 'wp-powersuite' ); ?></p>
			<p>
				<input type="file" name="import_file" id="wpps-rm-import-file" accept=".csv,text/csv,text/plain">
			</p>
			<p class="description">
				<?php esc_html_e( 'Sample:', 'wp-powersuite' ); ?>
				<a href="<?php echo esc_url( $sample_csv ); ?>" download><?php esc_html_e( 'Download sample CSV', 'wp-powersuite' ); ?></a>
			</p>
			<p>
				<button type="submit" class="button button-primary"><?php esc_html_e( 'Import', 'wp-powersuite' ); ?></button>
			</p>
		</form>
	</div>

	<?php if ( empty( $all_redirects ) ) : ?>
	<div class="rm-empty">
		<span class="dashicons dashicons-randomize" aria-hidden="true"></span>
		<h3><?php esc_html_e( 'No redirects yet', 'wp-powersuite' ); ?></h3>
		<p class="description"><?php esc_html_e( 'Create your first redirect to fix broken links, handle URL changes, or improve SEO.', 'wp-powersuite' ); ?></p>
		<a href="<?php echo esc_url( $add_url ); ?>" class="button button-primary button-hero"><?php esc_html_e( 'Add your first redirect', 'wp-powersuite' ); ?></a>
	</div>
	<?php else : ?>
		<form method="post" id="wpps-rm-list-form">
			<?php wp_nonce_field( 'bulk-redirects' ); ?>
			<input type="hidden" name="page" value="powersuite-redirect-manager" />
			<input type="hidden" name="status" value="<?php echo esc_attr( $status_filter ); ?>" />
			<div class="wpps-rm-list-header rm-list-header">
				<?php $list_table->views(); ?>
				<?php $list_table->search_box( __( 'Search redirects', 'wp-powersuite' ), 'redirect' ); ?>
			</div>
			<?php $list_table->display(); ?>
		</form>
	<?php endif; ?>

	<!-- Test URL -->
	<div class="rm-import-panel rm-test-panel">
		<h2><?php esc_html_e( 'Test URL', 'wp-powersuite' ); ?></h2>
		<p class="description"><?php esc_html_e( 'Enter a URL to see which redirect would match. Login-status conditions are ignored here so you can test while logged in; query params in the test URL are used for URL-param conditions.', 'wp-powersuite' ); ?></p>
		<div class="rm-test-row">
			<label for="wpps-rm-test-url" class="screen-reader-text"><?php esc_html_e( 'URL to test', 'wp-powersuite' ); ?></label>
			<input type="text" id="wpps-rm-test-url" class="regular-text" placeholder="<?php echo esc_attr( home_url( '/sample-page/' ) ); ?>" />
			<button type="button" id="wpps-rm-test-btn" class="button"><?php esc_html_e( 'Test', 'wp-powersuite' ); ?></button>
		</div>
		<div id="wpps-rm-test-result" class="rm-test-result" style="display:none;"></div>
	</div>
	<?php endif; ?>

	<!-- Add/Edit Form -->
	<div class="wpps-rm-form-wrap" <?php echo $show_form ? '' : 'style="display:none"'; ?>>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" id="wpps-rm-form" class="wpps-rm-form">
			<input type="hidden" name="action" value="wpps_redirect_manager_save" />
			<?php wp_nonce_field( 'wpps_redirect_save', 'wpps_redirect_nonce' ); ?>
			<?php if ( $editing ) : ?>
				<input type="hidden" name="id" value="<?php echo esc_attr( $editing['id'] ); ?>" />
			<?php endif; ?>

			<div class="rm-actions-bar">
				<a href="<?php echo esc_url( $list_url ); ?>" class="button"><?php esc_html_e( 'Cancel', 'wp-powersuite' ); ?></a>
				<button type="submit" id="wpps-rm-save-btn" class="button button-primary wpps-rm-save-btn">
					<?php echo $editing ? esc_html__( 'Save Changes', 'wp-powersuite' ) : esc_html__( 'Create Redirect', 'wp-powersuite' ); ?>
				</button>
			</div>

			<?php
			$redirect_types = [ '301', '302', '303', '307', '308' ];
			$error_types = [ '401', '402', '403', '404', '405', '410', '501', '502', '503' ];
			$ed = $editing ?? [];
			$current_type = $ed['type'] ?? '301';
			$is_error = in_array( $current_type, $error_types, true );
			$when_matched = $is_error ? 'error' : 'redirect';
			?>
			<div class="rm-panel">
				<h2 class="rm-panel-title"><?php esc_html_e( 'Basic settings', 'wp-powersuite' ); ?></h2>
				<p class="description rm-panel-desc"><?php esc_html_e( 'Define the source URL to match and where to redirect', 'wp-powersuite' ); ?></p>

				<div class="wpps-rm-form-grid wpps-rm-form-grid-2col">
					<div class="wpps-rm-form-group wpps-rm-form-full">
						<label for="wpps-rm-source"><?php esc_html_e( 'Source URL', 'wp-powersuite' ); ?> <span class="wpps-rm-required">*</span></label>
						<input type="text" id="wpps-rm-source" name="source" value="<?php echo esc_attr( $ed['source'] ?? '' ); ?>" class="wpps-rm-input" placeholder="/old-page/" required />
						<span class="wpps-rm-help"><?php esc_html_e( 'Path or full URL to match (full URLs use the path). For Wildcard use *, for Regex use a full pattern like #^/path$#.', 'wp-powersuite' ); ?></span>
						<?php if ( $editing && ( $dup = $module->findDuplicateSource( $ed['source'] ?? '', $ed['id'] ?? null, $ed['match_type'] ?? 'exact' ) ) ) : ?>
							<span class="wpps-rm-warning"><?php esc_html_e( 'Warning: Another redirect with this source already exists.', 'wp-powersuite' ); ?></span>
						<?php endif; ?>
					</div>
					<div class="wpps-rm-target-row">
						<div class="wpps-rm-form-group wpps-rm-target-input-wrap">
							<label for="wpps-rm-target"><?php esc_html_e( 'Target URL', 'wp-powersuite' ); ?></label>
							<input type="text" id="wpps-rm-target" name="target" value="<?php echo esc_attr( $ed['target'] ?? '' ); ?>" class="wpps-rm-input" placeholder="/new-page/ or https://example.com" <?php echo $is_error ? '' : 'required'; ?> />
							<span class="wpps-rm-help"><?php esc_html_e( 'Where to redirect. Use $1, $2 for wildcard captures. Leave empty for Show Error.', 'wp-powersuite' ); ?></span>
						</div>
						<?php if ( $show_form ) : ?>
							<div class="wpps-rm-form-group wpps-rm-page-picker-wrap">
								<label for="wpps-rm-page-picker-input"><?php esc_html_e( 'Or select:', 'wp-powersuite' ); ?></label>
								<div class="wpps-rm-page-picker-combobox">
									<input type="text" id="wpps-rm-page-picker-input" class="wpps-rm-input wpps-rm-page-picker-input" placeholder="<?php esc_attr_e( 'Search pages or posts...', 'wp-powersuite' ); ?>" autocomplete="off" aria-label="<?php esc_attr_e( 'Search pages or posts', 'wp-powersuite' ); ?>" />
									<div id="wpps-rm-page-picker-dropdown" class="wpps-rm-page-picker-dropdown" role="listbox" aria-hidden="true"></div>
								</div>
							</div>
						<?php endif; ?>
					</div>
				</div>

				<div class="wpps-rm-form-grid wpps-rm-form-grid-4col">
					<div class="wpps-rm-form-group">
						<label for="wpps-rm-match"><?php esc_html_e( 'Match Type', 'wp-powersuite' ); ?></label>
						<select id="wpps-rm-match" name="match_type" class="wpps-rm-select">
							<option value="exact" <?php selected( $ed['match_type'] ?? 'exact', 'exact' ); ?>><?php esc_html_e( 'Exact', 'wp-powersuite' ); ?></option>
							<option value="wildcard" <?php selected( $ed['match_type'] ?? 'exact', 'wildcard' ); ?>><?php esc_html_e( 'Wildcard (*)', 'wp-powersuite' ); ?></option>
							<option value="regex" <?php selected( $ed['match_type'] ?? 'exact', 'regex' ); ?>><?php esc_html_e( 'Regex', 'wp-powersuite' ); ?></option>
						</select>
						<span class="wpps-rm-help"><?php esc_html_e( 'Exact: /blog/post. Wildcard: /blog/* (includes /blog). Regex: #^/blog/(\d+)/?$#', 'wp-powersuite' ); ?></span>
					</div>
					<div class="wpps-rm-form-group">
						<label for="wpps-rm-when-matched"><?php esc_html_e( 'When Matched', 'wp-powersuite' ); ?></label>
						<select id="wpps-rm-when-matched" name="when_matched" class="wpps-rm-select">
							<option value="redirect" <?php selected( $when_matched, 'redirect' ); ?>><?php esc_html_e( 'Redirect', 'wp-powersuite' ); ?></option>
							<option value="error" <?php selected( $when_matched, 'error' ); ?>><?php esc_html_e( 'Show Error', 'wp-powersuite' ); ?></option>
						</select>
					</div>
					<div class="wpps-rm-form-group wpps-rm-type-redirect-wrap" <?php echo $is_error ? 'style="display:none"' : ''; ?>>
						<label for="wpps-rm-redirect-type"><?php esc_html_e( 'Redirect Type', 'wp-powersuite' ); ?></label>
						<select id="wpps-rm-redirect-type" class="wpps-rm-select">
							<option value="301" <?php selected( $current_type, '301' ); ?>><?php esc_html_e( '301 Permanent', 'wp-powersuite' ); ?></option>
							<option value="302" <?php selected( $current_type, '302' ); ?>><?php esc_html_e( '302 Found', 'wp-powersuite' ); ?></option>
							<option value="303" <?php selected( $current_type, '303' ); ?>><?php esc_html_e( '303 See Other', 'wp-powersuite' ); ?></option>
							<option value="307" <?php selected( $current_type, '307' ); ?>><?php esc_html_e( '307 Temporary', 'wp-powersuite' ); ?></option>
							<option value="308" <?php selected( $current_type, '308' ); ?>><?php esc_html_e( '308 Permanent', 'wp-powersuite' ); ?></option>
						</select>
					</div>
					<?php
					$error_type_labels = [
						'401' => __( '401 Unauthorized', 'wp-powersuite' ),
						'402' => __( '402 Payment Required', 'wp-powersuite' ),
						'403' => __( '403 Forbidden', 'wp-powersuite' ),
						'404' => __( '404 Not Found', 'wp-powersuite' ),
						'405' => __( '405 Method Not Allowed', 'wp-powersuite' ),
						'410' => __( '410 Gone', 'wp-powersuite' ),
						'501' => __( '501 Not Implemented', 'wp-powersuite' ),
						'502' => __( '502 Bad Gateway', 'wp-powersuite' ),
						'503' => __( '503 Service Unavailable', 'wp-powersuite' ),
					];
					?>
					<div class="wpps-rm-form-group wpps-rm-type-error-wrap" <?php echo $is_error ? '' : 'style="display:none"'; ?>>
						<label for="wpps-rm-error-type"><?php esc_html_e( 'Error Type', 'wp-powersuite' ); ?></label>
						<select id="wpps-rm-error-type" class="wpps-rm-select">
							<?php foreach ( $error_types as $t ) : ?>
								<option value="<?php echo esc_attr( $t ); ?>" <?php selected( $current_type, $t ); ?>><?php echo esc_html( $error_type_labels[ $t ] ?? $t ); ?></option>
							<?php endforeach; ?>
						</select>
					</div>
					<input type="hidden" name="type" id="wpps-rm-type" value="<?php echo esc_attr( $current_type ); ?>" />
					<div class="wpps-rm-form-group">
						<label for="wpps-rm-priority"><?php esc_html_e( 'Priority', 'wp-powersuite' ); ?></label>
						<input type="number" id="wpps-rm-priority" name="priority" value="<?php echo esc_attr( (string) ( $ed['priority'] ?? 10 ) ); ?>" class="wpps-rm-input" data-wpps-min="0" data-wpps-max="999" data-wpps-step="1" />
						<span class="wpps-rm-help"><?php esc_html_e( 'Lower = higher priority. Default: 10.', 'wp-powersuite' ); ?></span>
					</div>
				</div>

				<?php
				$error_defaults = [
					'401' => __( 'You do not have permission to access this page.', 'wp-powersuite' ),
					'402' => __( 'Payment required.', 'wp-powersuite' ),
					'403' => __( 'You do not have permission to access this page.', 'wp-powersuite' ),
					'404' => __( 'Page not found.', 'wp-powersuite' ),
					'405' => __( 'Method not allowed.', 'wp-powersuite' ),
					'410' => __( 'This resource is no longer available.', 'wp-powersuite' ),
					'501' => __( 'Not implemented.', 'wp-powersuite' ),
					'502' => __( 'Bad gateway.', 'wp-powersuite' ),
					'503' => __( 'Service temporarily unavailable.', 'wp-powersuite' ),
				];
				$error_message_value = $ed['message'] ?? '';
				if ( $error_message_value === '' && $is_error ) {
					$error_message_value = $error_defaults[ $current_type ] ?? __( 'Page not found.', 'wp-powersuite' );
				}
				?>
				<div class="wpps-rm-form-group wpps-rm-error-message-row wpps-rm-form-full" <?php echo $is_error ? '' : 'style="display:none"'; ?>>
					<label for="wpps-rm-message"><?php esc_html_e( 'Error Message', 'wp-powersuite' ); ?></label>
					<input type="text" id="wpps-rm-message" name="message" value="<?php echo esc_attr( $error_message_value ); ?>" class="wpps-rm-input" placeholder="<?php esc_attr_e( 'Custom message for error response', 'wp-powersuite' ); ?>" />
					<span class="wpps-rm-help"><?php esc_html_e( 'The message shown when this error is triggered. Edit to customize.', 'wp-powersuite' ); ?></span>
				</div>

				<div class="wpps-rm-form-grid wpps-rm-form-grid-3col">
					<div class="wpps-rm-form-group">
						<label class="wpps-rm-checkbox-label" for="wpps-rm-strip-params">
							<input type="checkbox" name="strip_params" id="wpps-rm-strip-params" value="1" <?php checked( ! empty( $ed['strip_params'] ) ); ?> class="wpps-rm-checkbox" />
							<?php esc_html_e( 'Strip query parameters when redirecting', 'wp-powersuite' ); ?>
						</label>
					</div>
				</div>

				<div class="wpps-rm-form-group wpps-rm-form-full">
					<label for="wpps-rm-notes"><?php esc_html_e( 'Notes', 'wp-powersuite' ); ?></label>
					<textarea id="wpps-rm-notes" name="notes" rows="2" class="wpps-rm-input wpps-rm-textarea" placeholder="<?php esc_attr_e( 'Optional internal notes', 'wp-powersuite' ); ?>"><?php echo esc_textarea( $ed['notes'] ?? '' ); ?></textarea>
				</div>
			</div>

			<!-- How to set up redirects accordion -->
			<div class="rm-panel wpps-rm-accordion">
				<button type="button" class="wpps-rm-accordion-header" aria-expanded="false" aria-controls="wpps-rm-howto-body">
					<span class="wpps-rm-accordion-title">
						<?php esc_html_e( 'How to set up redirects', 'wp-powersuite' ); ?>
						<span class="wpps-rm-accordion-tooltip" aria-label="<?php esc_attr_e( 'Help', 'wp-powersuite' ); ?>"><span class="wpps-rm-accordion-tooltip-trigger">?</span><span class="wpps-rm-accordion-tooltip-panel"><?php esc_html_e( 'Learn how to use wildcards and regular expressions to match URLs and build flexible redirect rules.', 'wp-powersuite' ); ?></span></span>
					</span>
					<span class="dashicons dashicons-arrow-down-alt2 wpps-rm-accordion-chevron"></span>
				</button>
				<div id="wpps-rm-howto-body" class="wpps-rm-accordion-body" hidden>
					<div class="wpps-rm-howto-inner">
						<!-- Nested: Wildcards -->
						<div class="wpps-rm-accordion wpps-rm-accordion-nested">
							<button type="button" class="wpps-rm-accordion-header wpps-rm-accordion-header-nested" aria-expanded="false" aria-controls="wpps-rm-wildcard-body">
								<span class="wpps-rm-accordion-title"><?php esc_html_e( 'How to use wildcards', 'wp-powersuite' ); ?></span>
								<span class="dashicons dashicons-arrow-down-alt2 wpps-rm-accordion-chevron"></span>
							</button>
							<div id="wpps-rm-wildcard-body" class="wpps-rm-accordion-body wpps-rm-accordion-body-nested" hidden>
								<p class="wpps-rm-howto-desc"><?php esc_html_e( 'Wildcards let you match many URLs with one rule. Use the asterisk (*) to match any characters in the path. Choose "Wildcard (*)" in Match Type. A pattern ending in /* also matches the base path (e.g. /blog/* matches /blog, /blog/, and /blog/post).', 'wp-powersuite' ); ?></p>
								<div class="wpps-rm-howto-example">
									<div class="wpps-rm-howto-example-row">
										<label><?php esc_html_e( 'Source URL', 'wp-powersuite' ); ?>:</label>
										<code>/blog/*</code>
									</div>
									<div class="wpps-rm-howto-example-row">
										<label><?php esc_html_e( 'Target URL', 'wp-powersuite' ); ?>:</label>
										<code>/news/$1</code>
									</div>
									<p class="wpps-rm-howto-example-desc"><?php esc_html_e( 'Matches /blog and /blog/ (with empty $1), /blog/first-post → /news/first-post, and /blog/2024/my-article → /news/2024/my-article. The * captures everything after /blog/ and $1 inserts it in the target.', 'wp-powersuite' ); ?></p>
								</div>
								<div class="wpps-rm-howto-example">
									<div class="wpps-rm-howto-example-row">
										<label><?php esc_html_e( 'Source URL', 'wp-powersuite' ); ?>:</label>
										<code>/products/*</code>
									</div>
									<div class="wpps-rm-howto-example-row">
										<label><?php esc_html_e( 'Target URL', 'wp-powersuite' ); ?>:</label>
										<code>/shop/$1</code>
									</div>
									<p class="wpps-rm-howto-example-desc"><?php esc_html_e( 'Matches /products/widget-a and redirects to /shop/widget-a. Use multiple * for multiple captures: /category/*/* matches /category/electronics/phone with $1 and $2.', 'wp-powersuite' ); ?></p>
								</div>
							</div>
						</div>
						<!-- Nested: Regex -->
						<div class="wpps-rm-accordion wpps-rm-accordion-nested">
							<button type="button" class="wpps-rm-accordion-header wpps-rm-accordion-header-nested" aria-expanded="false" aria-controls="wpps-rm-regex-body">
								<span class="wpps-rm-accordion-title"><?php esc_html_e( 'How to use regular expressions', 'wp-powersuite' ); ?></span>
								<span class="dashicons dashicons-arrow-down-alt2 wpps-rm-accordion-chevron"></span>
							</button>
							<div id="wpps-rm-regex-body" class="wpps-rm-accordion-body wpps-rm-accordion-body-nested" hidden>
								<p class="wpps-rm-howto-desc"><?php esc_html_e( 'Regular expressions give you precise pattern matching. Use parentheses () for capturing groups and $1, $2, etc. in the target to insert them. Choose "Regex" in Match Type. Patterns must be wrapped in # and use ^ and $ as anchors.', 'wp-powersuite' ); ?></p>
								<div class="wpps-rm-howto-notice">
									<?php esc_html_e( 'Important: Regex patterns must start with ^ and end with $ to match the full path. Wrap your pattern in # delimiters, e.g. #^/blog/(\d+)/?$#', 'wp-powersuite' ); ?>
								</div>
								<div class="wpps-rm-howto-example">
									<div class="wpps-rm-howto-example-row">
										<label><?php esc_html_e( 'Source URL', 'wp-powersuite' ); ?>:</label>
										<code>#^/news-(\d+)/?$#</code>
									</div>
									<div class="wpps-rm-howto-example-row">
										<label><?php esc_html_e( 'Target URL', 'wp-powersuite' ); ?>:</label>
										<code>/news/$1</code>
									</div>
									<p class="wpps-rm-howto-example-desc"><?php esc_html_e( 'Matches /news-123 and redirects to /news/123. The (\d+) captures one or more digits as $1.', 'wp-powersuite' ); ?></p>
								</div>
								<div class="wpps-rm-howto-example">
									<div class="wpps-rm-howto-example-row">
										<label><?php esc_html_e( 'Source URL', 'wp-powersuite' ); ?>:</label>
										<code>#^/blog/(\d{4})/(\d{2})/(\d{2})/(.*)$#</code>
									</div>
									<div class="wpps-rm-howto-example-row">
										<label><?php esc_html_e( 'Target URL', 'wp-powersuite' ); ?>:</label>
										<code>/articles/$4</code>
									</div>
									<p class="wpps-rm-howto-example-desc"><?php esc_html_e( 'Matches /blog/2024/01/15/post-slug and redirects to /articles/post-slug. $1=year, $2=month, $3=day, $4=slug.', 'wp-powersuite' ); ?></p>
								</div>
								<div class="wpps-rm-howto-example">
									<div class="wpps-rm-howto-example-row">
										<label><?php esc_html_e( 'Source URL', 'wp-powersuite' ); ?>:</label>
										<code>#^/category/(product|service)s?/(.*)$#</code>
									</div>
									<div class="wpps-rm-howto-example-row">
										<label><?php esc_html_e( 'Target URL', 'wp-powersuite' ); ?>:</label>
										<code>/$1/$2</code>
									</div>
									<p class="wpps-rm-howto-example-desc"><?php esc_html_e( 'Matches /category/products/item-name to /product/item-name and /category/services/consulting to /service/consulting. (product|service) captures the word as $1, s? makes the s optional, (.*) captures the rest as $2.', 'wp-powersuite' ); ?></p>
								</div>
								<div class="wpps-rm-howto-example">
									<div class="wpps-rm-howto-example-row">
										<label><?php esc_html_e( 'Source URL', 'wp-powersuite' ); ?>:</label>
										<code>#^/support(/.*)?$#</code>
									</div>
									<div class="wpps-rm-howto-example-row">
										<label><?php esc_html_e( 'Target URL', 'wp-powersuite' ); ?>:</label>
										<code>https://example.com/clientarea</code>
									</div>
									<p class="wpps-rm-howto-example-desc"><?php esc_html_e( 'Matches /support, /support/, and /support/anything. Prefer Wildcard /support/* for the same behavior when you do not need custom capture logic.', 'wp-powersuite' ); ?></p>
								</div>
								<p class="wpps-rm-howto-tools-title"><?php esc_html_e( 'Tools to build regex patterns:', 'wp-powersuite' ); ?></p>
								<ul class="wpps-rm-howto-tools">
									<li><a href="https://regex101.com/" target="_blank" rel="noopener noreferrer">regex101.com</a></li>
									<li><a href="https://regexr.com/" target="_blank" rel="noopener noreferrer">regexr.com</a></li>
									<li><a href="https://www.regextester.com/" target="_blank" rel="noopener noreferrer">regextester.com</a></li>
								</ul>
							</div>
						</div>
					</div>
				</div>
			</div>

			<?php
			$has_conditions = ! empty( $ed['conditions']['login_status']['enabled'] ) || ! empty( $ed['conditions']['referrer']['enabled'] ) || ! empty( $ed['conditions']['url_param']['enabled'] ) || ! empty( $ed['conditions']['language']['enabled'] );
			?>
			<div class="rm-panel wpps-rm-accordion<?php echo $has_conditions ? ' is-open' : ''; ?>">
				<button type="button" class="wpps-rm-accordion-header" aria-expanded="<?php echo $has_conditions ? 'true' : 'false'; ?>" aria-controls="wpps-rm-conditions-body">
					<span class="wpps-rm-accordion-title">
						<?php esc_html_e( 'Conditions (optional)', 'wp-powersuite' ); ?>
						<span class="wpps-rm-accordion-tooltip" aria-label="<?php esc_attr_e( 'Help', 'wp-powersuite' ); ?>"><span class="wpps-rm-accordion-tooltip-trigger">?</span><span class="wpps-rm-accordion-tooltip-panel"><?php esc_html_e( 'Restrict when this redirect applies. All enabled conditions must match. Use login status, referrer, URL parameters, or browser language to target specific visitors.', 'wp-powersuite' ); ?></span></span>
					</span>
					<span class="dashicons dashicons-arrow-down-alt2 wpps-rm-accordion-chevron"></span>
				</button>
				<div id="wpps-rm-conditions-body" class="wpps-rm-accordion-body" <?php echo $has_conditions ? '' : 'hidden'; ?>>
					<p class="wpps-rm-panel-desc"><?php esc_html_e( 'All enabled conditions must match. Leave all disabled for unconditional redirects.', 'wp-powersuite' ); ?></p>
					<div class="wpps-rm-form-grid wpps-rm-form-grid-3col">
						<div class="wpps-rm-form-group wpps-rm-condition-row">
							<label class="wpps-rm-checkbox-label">
								<input type="checkbox" name="cond_login_enabled" value="1" id="cond_login_enabled" <?php checked( ! empty( $ed['conditions']['login_status']['enabled'] ) ); ?> class="wpps-rm-checkbox" />
								<?php esc_html_e( 'Login Status', 'wp-powersuite' ); ?>
							</label>
							<label for="cond_login_status" class="screen-reader-text"><?php esc_html_e( 'Login status condition', 'wp-powersuite' ); ?></label>
							<select name="cond_login_status" id="cond_login_status" class="wpps-rm-select" aria-label="<?php esc_attr_e( 'Require user to be logged in or logged out', 'wp-powersuite' ); ?>">
								<option value="logged_in" <?php selected( $ed['conditions']['login_status']['status'] ?? 'logged_out', 'logged_in' ); ?>><?php esc_html_e( 'Logged in', 'wp-powersuite' ); ?></option>
								<option value="logged_out" <?php selected( $ed['conditions']['login_status']['status'] ?? 'logged_out', 'logged_out' ); ?>><?php esc_html_e( 'Logged out', 'wp-powersuite' ); ?></option>
							</select>
						</div>
						<div class="wpps-rm-form-group wpps-rm-condition-row">
							<label class="wpps-rm-checkbox-label">
								<input type="checkbox" name="cond_referrer_enabled" value="1" id="cond_referrer_enabled" <?php checked( ! empty( $ed['conditions']['referrer']['enabled'] ) ); ?> class="wpps-rm-checkbox" />
								<?php esc_html_e( 'Referrer', 'wp-powersuite' ); ?>
							</label>
							<label for="cond_referrer_pattern" class="screen-reader-text"><?php esc_html_e( 'Referrer pattern', 'wp-powersuite' ); ?></label>
							<input type="text" name="cond_referrer_pattern" id="cond_referrer_pattern" value="<?php echo esc_attr( $ed['conditions']['referrer']['pattern'] ?? '' ); ?>" class="wpps-rm-input" placeholder="facebook.com" aria-label="<?php esc_attr_e( 'Referrer URL pattern to match', 'wp-powersuite' ); ?>" />
						</div>
						<div class="wpps-rm-form-group wpps-rm-condition-row">
							<label class="wpps-rm-checkbox-label">
								<input type="checkbox" name="cond_language_enabled" value="1" id="cond_language_enabled" <?php checked( ! empty( $ed['conditions']['language']['enabled'] ) ); ?> class="wpps-rm-checkbox" />
								<?php esc_html_e( 'Browser Language', 'wp-powersuite' ); ?>
							</label>
							<label for="cond_language_codes" class="screen-reader-text"><?php esc_html_e( 'Browser language codes', 'wp-powersuite' ); ?></label>
							<input type="text" name="cond_language_codes" id="cond_language_codes" value="<?php echo esc_attr( $ed['conditions']['language']['codes'] ?? '' ); ?>" class="wpps-rm-input" placeholder="en, es, fr" aria-label="<?php esc_attr_e( 'Browser language codes to match', 'wp-powersuite' ); ?>" />
						</div>
					</div>
					<div class="wpps-rm-form-group wpps-rm-condition-row wpps-rm-form-full">
						<label class="wpps-rm-checkbox-label">
								<input type="checkbox" name="cond_param_enabled" value="1" id="cond_param_enabled" <?php checked( ! empty( $ed['conditions']['url_param']['enabled'] ) ); ?> class="wpps-rm-checkbox" />
								<?php esc_html_e( 'URL Parameter', 'wp-powersuite' ); ?>
							</label>
							<div class="wpps-rm-inline-fields">
								<label for="cond_param_name" class="screen-reader-text"><?php esc_html_e( 'URL parameter name', 'wp-powersuite' ); ?></label>
								<input type="text" name="cond_param_name" id="cond_param_name" value="<?php echo esc_attr( $ed['conditions']['url_param']['name'] ?? '' ); ?>" class="wpps-rm-input" placeholder="utm_source" aria-label="<?php esc_attr_e( 'URL parameter name', 'wp-powersuite' ); ?>" />
								<label for="cond_param_value" class="screen-reader-text"><?php esc_html_e( 'URL parameter value', 'wp-powersuite' ); ?></label>
								<input type="text" name="cond_param_value" id="cond_param_value" value="<?php echo esc_attr( $ed['conditions']['url_param']['value'] ?? '' ); ?>" class="wpps-rm-input" placeholder="<?php esc_attr_e( 'Value (optional)', 'wp-powersuite' ); ?>" aria-label="<?php esc_attr_e( 'URL parameter value (optional)', 'wp-powersuite' ); ?>" />
						</div>
					</div>
				</div>
			</div>
		</form>

		<div class="rm-actions-bar rm-actions-bar--bottom">
			<a href="<?php echo esc_url( $list_url ); ?>" class="button"><?php esc_html_e( 'Cancel', 'wp-powersuite' ); ?></a>
			<button type="submit" form="wpps-rm-form" class="button button-primary"><?php echo $editing ? esc_html__( 'Save Changes', 'wp-powersuite' ) : esc_html__( 'Create Redirect', 'wp-powersuite' ); ?></button>
		</div>
	</div>
</div>

<script>
(function() {
	var importToggle = document.getElementById('wpps-rm-import-toggle');
	var importPanel = document.getElementById('wpps-rm-import-panel');
	if (importToggle && importPanel) {
		importToggle.addEventListener('click', function() {
			importPanel.hidden = !importPanel.hidden;
		});
	}
	var nonce = '<?php echo esc_js( $nonce ); ?>';
	var saveBtn = document.getElementById('wpps-rm-save-btn');
	var saveForm = document.getElementById('wpps-rm-form');
	if (saveBtn && saveForm) {
		saveForm.addEventListener('submit', function() {
			saveBtn.disabled = true;
			saveBtn.classList.add('is-loading');
			saveBtn.innerHTML = '<span class="wpps-rm-spinner"></span> <span class="wpps-rm-save-text"><?php echo esc_js( __( 'Saving...', 'wp-powersuite' ) ); ?></span>';
		});
	}
	document.querySelectorAll('.wpps-rm-toggle-input').forEach(function(cb) {
		cb.addEventListener('change', function() {
			var id = this.dataset.id, row = this.closest('tr');
			if (!id || !nonce) return;
			fetch(ajaxurl, {
				method: 'POST',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
				body: 'action=wpps_redirect_manager_toggle&nonce=' + encodeURIComponent(nonce) + '&id=' + encodeURIComponent(id)
			})
			.then(function(r) { return r.json(); })
			.then(function(data) {
				if (data.success) {
					row.classList.toggle('wpps-rm-inactive', !data.data.active);
				}
			});
		});
	});
	document.getElementById('wpps-rm-list-form')?.addEventListener('submit', function(e) {
		var action = this.querySelector('[name="action"]')?.value || this.querySelector('[name="action2"]')?.value;
		if (action && action !== '-1') {
			var checked = this.querySelectorAll('input[name="ids[]"]:checked');
			if (checked.length === 0) {
				e.preventDefault();
				alert('<?php echo esc_js( __( 'Please select at least one redirect.', 'wp-powersuite' ) ); ?>');
			}
		}
	});
	(function() {
		var whenMatched = document.getElementById('wpps-rm-when-matched');
		var redirectWrap = document.querySelector('.wpps-rm-type-redirect-wrap');
		var errorWrap = document.querySelector('.wpps-rm-type-error-wrap');
		var errorMessageRow = document.querySelector('.wpps-rm-error-message-row');
		var redirectType = document.getElementById('wpps-rm-redirect-type');
		var errorType = document.getElementById('wpps-rm-error-type');
		var typeHidden = document.getElementById('wpps-rm-type');
		var target = document.getElementById('wpps-rm-target');
		var messageInput = document.getElementById('wpps-rm-message');
		var errorDefaults = <?php echo wp_json_encode( $error_defaults ); ?>;
		function sync() {
			var isError = whenMatched && whenMatched.value === 'error';
			if (redirectWrap) redirectWrap.style.display = isError ? 'none' : '';
			if (errorWrap) errorWrap.style.display = isError ? '' : 'none';
			if (errorMessageRow) errorMessageRow.style.display = isError ? '' : 'none';
			if (typeHidden && redirectType && errorType) {
				typeHidden.value = isError ? errorType.value : redirectType.value;
			}
			if (target) target.required = !isError;
			if (isError) updateMessageDefault();
		}
		function updateMessageDefault() {
			if (!messageInput || !errorType) return;
			var code = errorType.value;
			var def = errorDefaults[code] || '';
			var current = messageInput.value.trim();
			var isDefault = Object.values(errorDefaults).indexOf(current) >= 0;
			if (isDefault || current === '') {
				messageInput.value = def;
			}
		}
		whenMatched?.addEventListener('change', sync);
		redirectType?.addEventListener('change', function() { if (typeHidden) typeHidden.value = this.value; });
		errorType?.addEventListener('change', function() {
			if (typeHidden) typeHidden.value = this.value;
			updateMessageDefault();
		});
		sync();
	})();
	document.querySelectorAll('.wpps-rm-accordion-header').forEach(function(header) {
		header.addEventListener('click', function(e) {
			if (e.target.closest('.wpps-rm-accordion-tooltip')) return;
			var controlsId = this.getAttribute('aria-controls');
			var body = controlsId ? document.getElementById(controlsId) : null;
			if (!body) return;
			var expanded = this.getAttribute('aria-expanded') === 'true';
			this.setAttribute('aria-expanded', !expanded);
			body.hidden = expanded;
			this.closest('.wpps-rm-accordion')?.classList.toggle('is-open', !expanded);
		});
	});
	(function() {
		var input = document.getElementById('wpps-rm-page-picker-input');
		var dropdown = document.getElementById('wpps-rm-page-picker-dropdown');
		var targetInput = document.getElementById('wpps-rm-target');
		if (!input || !dropdown || !targetInput) return;
		var pages = [];
		function showDropdown(show) {
			dropdown.style.display = show ? 'block' : 'none';
			dropdown.setAttribute('aria-hidden', !show);
		}
		function filterAndRender(query) {
			var q = (query || '').toLowerCase().trim();
			var filtered = q ? pages.filter(function(p) { return (p.title || '').toLowerCase().indexOf(q) >= 0; }) : pages;
			dropdown.innerHTML = '';
			if (filtered.length === 0) {
				dropdown.innerHTML = '<div class="wpps-rm-page-picker-empty"><?php echo esc_js( __( 'No matches found', 'wp-powersuite' ) ); ?></div>';
			} else {
				filtered.forEach(function(p) {
					var div = document.createElement('div');
					div.className = 'wpps-rm-page-picker-option';
					div.setAttribute('role', 'option');
					div.textContent = p.title;
					div.dataset.url = p.url;
					div.tabIndex = -1;
					div.addEventListener('click', function() {
						targetInput.value = p.url;
						input.value = '';
						showDropdown(false);
						input.blur();
					});
					dropdown.appendChild(div);
				});
			}
		}
		input.addEventListener('focus', function() {
			filterAndRender(input.value);
			showDropdown(true);
		});
		input.addEventListener('input', function() {
			filterAndRender(input.value);
			showDropdown(true);
		});
		input.addEventListener('keydown', function(e) {
			if (e.key === 'Escape') { showDropdown(false); input.blur(); }
		});
		document.addEventListener('click', function(e) {
			if (!input.contains(e.target) && !dropdown.contains(e.target)) showDropdown(false);
		});
		fetch(ajaxurl, {
			method: 'POST',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			body: 'action=wpps_redirect_manager_get_pages&nonce=' + encodeURIComponent(nonce)
		})
		.then(function(r) { return r.json(); })
		.then(function(data) {
			if (data.success && data.data) {
				pages = data.data;
			}
		});
	})();
	document.getElementById('wpps-rm-test-btn')?.addEventListener('click', function() {
		var url = document.getElementById('wpps-rm-test-url').value.trim();
		var result = document.getElementById('wpps-rm-test-result');
		function setResult(className, buildContent) {
			result.style.display = 'block';
			result.className = 'rm-test-result ' + className;
			result.replaceChildren();
			buildContent(result);
		}
		function appendParagraph(parent, text) {
			var p = document.createElement('p');
			p.textContent = text;
			parent.appendChild(p);
		}
		if (!url) {
			setResult('rm-test-error', function(el) {
				appendParagraph(el, '<?php echo esc_js( __( 'Enter a URL to test.', 'wp-powersuite' ) ); ?>');
			});
			return;
		}
		setResult('rm-test-loading', function(el) {
			appendParagraph(el, '<?php echo esc_js( __( 'Testing...', 'wp-powersuite' ) ); ?>');
		});
		fetch(ajaxurl, {
			method: 'POST',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			body: 'action=wpps_redirect_manager_test_url&nonce=' + encodeURIComponent(nonce) + '&url=' + encodeURIComponent(url)
		})
		.then(function(r) { return r.json(); })
		.then(function(data) {
			if (data.success && data.data) {
				if (data.data.match) {
					setResult('rm-test-success', function(el) {
						var p1 = document.createElement('p');
						var strong = document.createElement('strong');
						strong.textContent = '<?php echo esc_js( __( 'Match found!', 'wp-powersuite' ) ); ?>';
						p1.appendChild(strong);
						el.appendChild(p1);
						var p2 = document.createElement('p');
						if (data.data.is_error) {
							p2.appendChild(document.createTextNode('<?php echo esc_js( __( 'Shows error:', 'wp-powersuite' ) ); ?> '));
							var code = document.createElement('code');
							code.textContent = data.data.type || '';
							p2.appendChild(code);
						} else {
							p2.appendChild(document.createTextNode('<?php echo esc_js( __( 'Redirects to:', 'wp-powersuite' ) ); ?> '));
							var code = document.createElement('code');
							code.textContent = data.data.target || '';
							p2.appendChild(code);
							p2.appendChild(document.createTextNode(' (<?php echo esc_js( __( 'Type', 'wp-powersuite' ) ); ?>: ' + (data.data.type || '301') + ')'));
						}
						el.appendChild(p2);
						if (data.data.login_condition_ignored) {
							appendParagraph(el, '<?php echo esc_js( __( 'Note: Login status condition was ignored for this test.', 'wp-powersuite' ) ); ?>');
						}
					});
				} else {
					setResult('rm-test-info', function(el) {
						appendParagraph(el, data.data.message || '<?php echo esc_js( __( 'No matching redirect found.', 'wp-powersuite' ) ); ?>');
					});
				}
			} else {
				setResult('rm-test-error', function(el) {
					appendParagraph(el, (data.data && data.data.message) ? data.data.message : '<?php echo esc_js( __( 'Error.', 'wp-powersuite' ) ); ?>');
				});
			}
		});
	});
})();
</script>
