<?php

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = '404-redirect';
}

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

$defaults = [
	'redirect_type'                => 'home',
	'custom_url'                   => '',
	'redirect_page_id'             => 0,
	'redirect_code'                => '302',
	'allow_permanent_404_redirect' => false,
	'preserve_query_string'        => true,
];
if ( class_exists( \Redirect404\Module::class ) ) {
	$settings = \Redirect404\Module::normalizeSettings( array_merge( $defaults, $settings ) );
} else {
	$settings = array_merge( $defaults, $settings );
}

$redirect_type                = $settings['redirect_type'] ?? 'home';
$custom_url                   = $settings['custom_url'] ?? '';
$redirect_page_id             = isset( $settings['redirect_page_id'] ) ? (int) $settings['redirect_page_id'] : 0;
$redirect_code                = $settings['redirect_code'] ?? '302';
$allow_permanent_404_redirect = ! empty( $settings['allow_permanent_404_redirect'] );
$preserve_query_string        = ! empty( $settings['preserve_query_string'] );
$show_allow_301_row           = ( $redirect_code === '301' );

// Get pages for dropdown
$pages = get_pages( [
	'sort_column' => 'post_title',
	'sort_order'  => 'ASC',
] );
?>

<div class="wp-powersuite-module-settings">
	<p class="description">
		<?php esc_html_e( 'Automatically redirect visitors who encounter a 404 error to a destination of your choice. Choose to redirect to your homepage, a specific page, or a custom URL.', 'wp-powersuite' ); ?>
	</p>
	<p class="description">
		<?php esc_html_e( 'Works alongside Redirect Manager (explicit rules run first) and 404 Error Log (logs missing URLs and records where this module sent visitors).', 'wp-powersuite' ); ?>
	</p>

	<div class="wp-powersuite-info-box wp-powersuite-info-box--warning">
		<p>
			<strong><?php esc_html_e( 'SEO notice:', 'wp-powersuite' ); ?></strong>
			<?php esc_html_e( 'This module redirects every missing URL to one destination. That helps visitors but can hurt SEO if search engines treat many unrelated URLs as permanently moved. Use 302 (temporary) by default, log 404s with 404 Error Log, and add specific 301 rules in Redirect Manager instead of blanket permanent redirects.', 'wp-powersuite' ); ?>
		</p>
	</div>

	<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">
						<label for="<?php echo esc_attr( $module_id ); ?>_redirect_type"><?php esc_html_e( 'Redirect To', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<select
							id="<?php echo esc_attr( $module_id ); ?>_redirect_type"
							name="redirect_type"
							class="wp-powersuite-advanced-setting"
							data-setting-key="redirect_type"
						>
							<option value="home" <?php selected( $redirect_type, 'home' ); ?>><?php esc_html_e( 'Homepage', 'wp-powersuite' ); ?></option>
							<option value="page" <?php selected( $redirect_type, 'page' ); ?>><?php esc_html_e( 'Specific Page', 'wp-powersuite' ); ?></option>
							<option value="custom" <?php selected( $redirect_type, 'custom' ); ?>><?php esc_html_e( 'Custom URL', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description">
							<?php esc_html_e( 'Choose where to redirect visitors who land on non-existent pages.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr id="<?php echo esc_attr( $module_id ); ?>_page_row" style="display: <?php echo $redirect_type === 'page' ? 'table-row' : 'none'; ?>;">
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_redirect_page_id"><?php esc_html_e( 'Select Page', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<select
							id="<?php echo esc_attr( $module_id ); ?>_redirect_page_id"
							name="redirect_page_id"
							class="wp-powersuite-advanced-setting"
							data-setting-key="redirect_page_id"
						>
							<option value="0"><?php esc_html_e( '— Select —', 'wp-powersuite' ); ?></option>
							<?php foreach ( $pages as $page ) : ?>
								<option value="<?php echo esc_attr( $page->ID ); ?>" <?php selected( $redirect_page_id, $page->ID ); ?>>
									<?php echo esc_html( $page->post_title ); ?>
								</option>
							<?php endforeach; ?>
						</select>
						<p class="description">
							<?php esc_html_e( 'Select a published page to redirect 404 visitors to. Unpublished or missing pages will not redirect (the normal 404 page is shown instead).', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr id="<?php echo esc_attr( $module_id ); ?>_custom_url_row" style="display: <?php echo $redirect_type === 'custom' ? 'table-row' : 'none'; ?>;">
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_custom_url"><?php esc_html_e( 'Custom URL', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<input
							type="url"
							id="<?php echo esc_attr( $module_id ); ?>_custom_url"
							name="custom_url"
							value="<?php echo esc_url( $custom_url ); ?>"
							class="regular-text wp-powersuite-advanced-setting"
							data-setting-key="custom_url"
							placeholder="<?php esc_attr_e( 'https://example.com/page', 'wp-powersuite' ); ?>"
						/>
						<p class="description">
							<?php esc_html_e( 'Enter a full http:// or https:// URL. Invalid or blocked destinations fall back to the normal 404 page instead of redirecting to wp-admin.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_redirect_code"><?php esc_html_e( 'Redirect Status', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<select
							id="<?php echo esc_attr( $module_id ); ?>_redirect_code"
							name="redirect_code"
							class="wp-powersuite-advanced-setting"
							data-setting-key="redirect_code"
						>
							<option value="302" <?php selected( $redirect_code, '302' ); ?>><?php esc_html_e( '302 Temporary Redirect (recommended)', 'wp-powersuite' ); ?></option>
							<option value="301" <?php selected( $redirect_code, '301' ); ?>><?php esc_html_e( '301 Permanent Redirect', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description">
							<?php esc_html_e( '302 tells search engines the missing URL is temporarily handled elsewhere. Choosing 301 requires confirming the SEO risk below.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr id="<?php echo esc_attr( $module_id ); ?>_allow_301_row" style="display: <?php echo $show_allow_301_row ? 'table-row' : 'none'; ?>;">
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_allow_permanent_404_redirect"><?php esc_html_e( 'Allow 301', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<label>
							<input
								type="checkbox"
								id="<?php echo esc_attr( $module_id ); ?>_allow_permanent_404_redirect"
								name="allow_permanent_404_redirect"
								value="1"
								<?php checked( $allow_permanent_404_redirect ); ?>
								class="wp-powersuite-advanced-setting"
								data-setting-key="allow_permanent_404_redirect"
							/>
							<?php esc_html_e( 'I understand the SEO risk and want to use a 301 permanent redirect for this catch-all rule.', 'wp-powersuite' ); ?>
						</label>
						<p id="<?php echo esc_attr( $module_id ); ?>_allow_301_error" class="description wp-powersuite-field-error" style="display:none;">
							<?php esc_html_e( 'You must check this box to save a 301 redirect.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_preserve_query_string"><?php esc_html_e( 'Preserve Query String', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<label>
							<input
								type="checkbox"
								id="<?php echo esc_attr( $module_id ); ?>_preserve_query_string"
								name="preserve_query_string"
								value="1"
								<?php checked( $preserve_query_string ); ?>
								class="wp-powersuite-advanced-setting"
								data-setting-key="preserve_query_string"
							/>
							<?php esc_html_e( 'Append the original query string to the redirect destination (e.g. UTM tags).', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
			</tbody>
		</table>

		<div class="wp-powersuite-info-box wp-powersuite-info-box--accent">
			<p>
				<strong><?php esc_html_e( 'How It Works:', 'wp-powersuite' ); ?></strong><br>
				<?php esc_html_e( 'When a visitor lands on a page that does not exist, they are redirected to your chosen destination. Redirect loops are blocked automatically, and invalid destinations show the normal 404 page instead of redirecting.', 'wp-powersuite' ); ?>
			</p>
		</div>
	</form>
</div>

<script type="text/javascript">
(function($) {
	$(document).ready(function() {
		var moduleId = <?php echo wp_json_encode( $module_id ); ?>;
		var $redirectType = $('#' + moduleId + '_redirect_type');
		var $pageRow = $('#' + moduleId + '_page_row');
		var $customUrlRow = $('#' + moduleId + '_custom_url_row');
		var $allowPermanent = $('#' + moduleId + '_allow_permanent_404_redirect');
		var $redirectCode = $('#' + moduleId + '_redirect_code');
		var $allow301Row = $('#' + moduleId + '_allow_301_row');
		var $allow301Error = $('#' + moduleId + '_allow_301_error');
		var saveBlockedMessage = <?php echo wp_json_encode( __( 'Check the confirmation box below to save a 301 permanent redirect for this catch-all rule.', 'wp-powersuite' ) ); ?>;

		function toggleRows() {
			var type = $redirectType.val();
			if (type === 'page') {
				$pageRow.show();
				$customUrlRow.hide();
			} else if (type === 'custom') {
				$pageRow.hide();
				$customUrlRow.show();
			} else {
				$pageRow.hide();
				$customUrlRow.hide();
			}
		}

		function toggleAllow301Row() {
			var is301 = $redirectCode.val() === '301';
			$allow301Row.toggle(is301);
			if (!is301) {
				$allowPermanent.prop('checked', false);
				$allow301Error.hide();
			}
		}

		function requires301Ack() {
			return $redirectCode.val() === '301' && !$allowPermanent.is(':checked');
		}

		function show301AckError() {
			$allow301Error.show();
			$allow301Row[0]?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
		}

		$redirectType.on('change', toggleRows);
		$redirectCode.on('change', toggleAllow301Row);
		$allowPermanent.on('change', function() {
			if ($allowPermanent.is(':checked')) {
				$allow301Error.hide();
			}
		});
		toggleRows();
		toggleAllow301Row();

		if (window.wpPowerSuite) {
			window.wpPowerSuite.confirmBeforeSave = window.wpPowerSuite.confirmBeforeSave || {};
			window.wpPowerSuite.confirmBeforeSave[moduleId] = function() {
				if (!requires301Ack()) {
					return true;
				}
				show301AckError();
				window.alert(saveBlockedMessage);
				return false;
			};
		}
	});
})(jQuery);
</script>
