<?php

use ForceSslAdmin\Module;
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'force-ssl-admin';
}

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

$force_admin   = ! empty( $settings['force_admin'] );
$force_login   = ! empty( $settings['force_login'] );
$redirect_code = isset( $settings['redirect_code'] ) && in_array( $settings['redirect_code'], [ '301', '302' ], true ) ? $settings['redirect_code'] : '301';

$emergency_key = isset( $settings['emergency_key'] ) ? (string) $settings['emergency_key'] : '';
if ( strlen( $emergency_key ) < 20 && class_exists( Module::class ) ) {
	$module_instance = new Module();
	if ( method_exists( $module_instance, 'persistEmergencyKeyIfMissing' ) ) {
		$module_instance->persistEmergencyKeyIfMissing();
		$settings      = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
		$emergency_key = is_array( $settings ) && isset( $settings['emergency_key'] ) ? (string) $settings['emergency_key'] : '';
	}
}

$disable_url = $emergency_key !== '' ? Module::buildEmergencyDisableUrl( $emergency_key ) : '';
$is_ssl      = Module::isHttpsRequest();
$both_on     = $force_admin && $force_login;
$none_on     = ! $force_admin && ! $force_login;
?>

<div class="wp-powersuite-module-settings" data-module-id="<?php echo esc_attr( $module_id ); ?>">
	<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' ); ?>

		<p class="description" style="margin-top:0;">
			<?php esc_html_e( 'Keeps your sign-in page and dashboard on secure HTTPS links. If someone visits the old http:// address, they are sent to https:// automatically.', 'wp-powersuite' ); ?>
		</p>

		<?php if ( $none_on ) : ?>
			<div class="wpps-settings-alert wpps-settings-alert--info" role="note">
				<p style="margin:0;">
					<?php esc_html_e( 'Choose at least one area below and save. Redirects do not start until you save your settings.', 'wp-powersuite' ); ?>
				</p>
			</div>
		<?php endif; ?>

		<?php if ( ! $is_ssl ) : ?>
			<div class="wpps-settings-alert wpps-settings-alert--warning" role="alert">
				<p style="margin:0;">
					<strong><?php esc_html_e( 'Before you turn this on', 'wp-powersuite' ); ?></strong><br />
					<?php esc_html_e( 'Your site does not appear to be using HTTPS yet. Ask your host to install an SSL certificate first. Turning this on without HTTPS can lock you out of the dashboard.', 'wp-powersuite' ); ?>
				</p>
			</div>
		<?php endif; ?>

		<?php if ( $both_on ) : ?>
			<div class="wpps-settings-alert wpps-settings-alert--info" role="note">
				<p style="margin:0;">
					<strong><?php esc_html_e( 'Recommended', 'wp-powersuite' ); ?>:</strong>
					<?php esc_html_e( 'Both options are on — your dashboard and sign-in page are protected.', 'wp-powersuite' ); ?>
				</p>
			</div>
		<?php endif; ?>

		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'Protect these areas', 'wp-powersuite' ); ?>
						<?php
						wpps_render_modal_settings_tip(
							__( 'What to protect', 'wp-powersuite' ),
							__( 'Leave both checked unless you have a specific reason to protect only one. Most sites should protect both.', 'wp-powersuite' )
						);
						?>
					</th>
					<td>
						<fieldset>
							<label for="<?php echo esc_attr( $module_id ); ?>_force_admin" style="display: block; margin-bottom: 10px;">
								<input
									type="checkbox"
									id="<?php echo esc_attr( $module_id ); ?>_force_admin"
									name="force_admin"
									class="wp-powersuite-advanced-setting"
									data-setting-key="force_admin"
									value="1"
									<?php checked( $force_admin ); ?>
								/>
								<?php esc_html_e( 'WordPress dashboard', 'wp-powersuite' ); ?>
								<span class="description"><?php esc_html_e( '(wp-admin)', 'wp-powersuite' ); ?></span>
							</label>
							<label for="<?php echo esc_attr( $module_id ); ?>_force_login" style="display: block;">
								<input
									type="checkbox"
									id="<?php echo esc_attr( $module_id ); ?>_force_login"
									name="force_login"
									class="wp-powersuite-advanced-setting"
									data-setting-key="force_login"
									value="1"
									<?php checked( $force_login ); ?>
								/>
								<?php esc_html_e( 'Sign-in page', 'wp-powersuite' ); ?>
								<span class="description"><?php esc_html_e( '(login screen)', 'wp-powersuite' ); ?></span>
							</label>
						</fieldset>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_redirect_code"><?php esc_html_e( 'Redirect type', 'wp-powersuite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Redirect type', 'wp-powersuite' ),
							__( 'Permanent (301) is best for most sites. Use temporary (302) only while testing.', 'wp-powersuite' )
						);
						?>
					</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="301" <?php selected( $redirect_code, '301' ); ?>><?php esc_html_e( 'Permanent (301) — recommended', 'wp-powersuite' ); ?></option>
							<option value="302" <?php selected( $redirect_code, '302' ); ?>><?php esc_html_e( 'Temporary (302) — for testing only', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'How visitors are sent from http:// to https://.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>

		<div class="wpps-settings-alert wpps-settings-alert--info" role="note">
			<p style="margin:0 0 8px;">
				<strong><?php esc_html_e( 'Safety link — save this somewhere', 'wp-powersuite' ); ?></strong>
			</p>
			<ol style="margin:0 0 12px 1.2em; padding:0;">
				<li><?php esc_html_e( 'Copy the full link below and save it somewhere safe (password manager, email, or a note).', 'wp-powersuite' ); ?></li>
				<li><?php esc_html_e( 'If the sign-in page stops working or you see a redirect loop, open this link in your browser — you do not need to be signed in.', 'wp-powersuite' ); ?></li>
				<li><?php esc_html_e( 'The module turns off right away so you can sign in again. Open WP PowerSuite afterward to copy a new safety link.', 'wp-powersuite' ); ?></li>
			</ol>
			<?php if ( $disable_url !== '' ) : ?>
				<div class="wpps-force-ssl-safety-link">
					<label for="wpps-force-ssl-emergency-url" class="screen-reader-text"><?php esc_html_e( 'Safety link', 'wp-powersuite' ); ?></label>
					<input
						type="text"
						id="wpps-force-ssl-emergency-url"
						readonly
						class="large-text code wpps-force-ssl-safety-link__url"
						value="<?php echo esc_url( $disable_url ); ?>"
						onclick="this.select();"
					/>
					<div class="wpps-force-ssl-safety-link__actions">
						<button
							type="button"
							class="button button-secondary wpps-force-ssl-safety-link__copy"
							id="wpps-force-ssl-copy-link"
						>
							<span class="dashicons dashicons-admin-page" aria-hidden="true"></span>
							<span class="wpps-force-ssl-copy-label"><?php esc_html_e( 'Copy link', 'wp-powersuite' ); ?></span>
						</button>
						<button
							type="button"
							class="button button-secondary wpps-force-ssl-safety-link__regenerate"
							id="wpps-force-ssl-regenerate-key"
						>
							<span class="dashicons dashicons-update" aria-hidden="true"></span>
							<span class="wpps-force-ssl-regenerate-label"><?php esc_html_e( 'Create new link', 'wp-powersuite' ); ?></span>
						</button>
						<span id="wpps-force-ssl-regenerate-msg" class="wpps-force-ssl-safety-link__feedback description" aria-live="polite"></span>
					</div>
				</div>
				<p class="description" style="margin:8px 0 0;">
					<?php esc_html_e( 'Treat this link like a password — anyone with the full link can turn this module off. Each link works once; after use, save a new link from these settings. “Create new link” invalidates the previous one.', 'wp-powersuite' ); ?>
				</p>
			<?php else : ?>
				<p class="description" style="margin:0;">
					<?php esc_html_e( 'Save your settings once to generate your personal safety link.', 'wp-powersuite' ); ?>
				</p>
			<?php endif; ?>
		</div>
	</form>
</div>
<script>
(function () {
	var copyBtn = document.getElementById('wpps-force-ssl-copy-link');
	var regenBtn = document.getElementById('wpps-force-ssl-regenerate-key');
	var urlInput = document.getElementById('wpps-force-ssl-emergency-url');
	var regenMsg = document.getElementById('wpps-force-ssl-regenerate-msg');
	var copyLabel = copyBtn ? copyBtn.querySelector('.wpps-force-ssl-copy-label') : null;
	var regenLabel = regenBtn ? regenBtn.querySelector('.wpps-force-ssl-regenerate-label') : null;
	var i18n = {
		copied: <?php echo wp_json_encode( __( 'Copied!', 'wp-powersuite' ) ); ?>,
		copyLink: <?php echo wp_json_encode( __( 'Copy link', 'wp-powersuite' ) ); ?>,
		createNewLink: <?php echo wp_json_encode( __( 'Create new link', 'wp-powersuite' ) ); ?>,
		creating: <?php echo wp_json_encode( __( 'Creating…', 'wp-powersuite' ) ); ?>,
		confirm: <?php echo wp_json_encode( __( 'Create a new safety link? Your old link will stop working.', 'wp-powersuite' ) ); ?>,
		error: <?php echo wp_json_encode( __( 'Could not create a new safety link. Try again.', 'wp-powersuite' ) ); ?>
	};

	function setFeedback(message, type) {
		if (!regenMsg) {
			return;
		}
		regenMsg.textContent = message || '';
		regenMsg.className = 'wpps-force-ssl-safety-link__feedback description' + (type ? ' is-' + type : '');
	}

	if (copyBtn && urlInput) {
		copyBtn.addEventListener('click', function () {
			urlInput.select();
			if (navigator.clipboard && navigator.clipboard.writeText) {
				navigator.clipboard.writeText(urlInput.value).catch(function () {
					try { document.execCommand('copy'); } catch (e) {}
				});
			} else {
				try { document.execCommand('copy'); } catch (e) {}
			}
			if (copyLabel) {
				copyLabel.textContent = i18n.copied;
				setTimeout(function () {
					copyLabel.textContent = i18n.copyLink;
				}, 2000);
			}
		});
	}

	if (regenBtn) {
		regenBtn.addEventListener('click', function () {
			if (!window.confirm(i18n.confirm)) {
				return;
			}

			regenBtn.disabled = true;
			regenBtn.classList.add('is-busy');
			if (regenLabel) {
				regenLabel.textContent = i18n.creating;
			}
			setFeedback('', '');

			var fd = new FormData();
			fd.append('action', 'wpps_fsa_regenerate_emergency_key');
			fd.append('nonce', (window.wpPowerSuite && window.wpPowerSuite.nonce) || '');

			fetch((window.wpPowerSuite && window.wpPowerSuite.ajaxUrl) || ajaxurl, {
				method: 'POST',
				body: fd,
				credentials: 'same-origin'
			})
				.then(function (response) { return response.json(); })
				.then(function (data) {
					if (data.success && data.data && data.data.disable_url && urlInput) {
						urlInput.value = data.data.disable_url;
						urlInput.focus();
						urlInput.select();
					}
					if (data.success) {
						setFeedback((data.data && data.data.message) ? data.data.message : '', 'success');
					} else {
						setFeedback((data.data && data.data.message) ? data.data.message : i18n.error, 'error');
					}
				})
				.catch(function () {
					setFeedback(i18n.error, 'error');
				})
				.finally(function () {
					regenBtn.disabled = false;
					regenBtn.classList.remove('is-busy');
					if (regenLabel) {
						regenLabel.textContent = i18n.createNewLink;
					}
				});
		});
	}
})();
</script>
