<?php

namespace ChangeLoginURL;

use WP_PowerSuite\Core\NetworkScope;
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;
use WP_PowerSuite\Core\WhiteLabel;

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

if ( ! function_exists( 'wp_powersuite_is_license_valid' ) || ! wp_powersuite_is_license_valid() ) {
	$license_page_url = WhiteLabel::licenseDirectUrl();
	$brand_name       = WhiteLabel::pluginName();
	?>
	<div class="wp-powersuite-module-settings wpps-settings-panel" data-module-id="<?php echo esc_attr( $module_id ?? 'change-login-url' ); ?>">
		<div class="wpps-settings-alert wpps-settings-alert--warning" role="alert">
			<p>
				<?php
				echo esc_html(
					sprintf(
						/* translators: %s: plugin brand name */
						__( 'Change Login URL requires an active %s license.', 'wp-powersuite' ),
						$brand_name
					)
				);
				?>
				<a href="<?php echo esc_url( $license_page_url ); ?>"><?php esc_html_e( 'Activate license', 'wp-powersuite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

if ( ! isset( $module_id ) || $module_id === '' ) {
	$module_id = 'change-login-url';
}

$default_password_mode = Module::defaultPasswordUrlMode();

$default_settings = [
	'login_slug'                 => '',
	'blocked_behavior'           => '404',
	'blocked_redirect_url'       => '',
	'redirect_wp_login_actions'  => false,
	'woocommerce_guest_redirect' => false,
	'password_url_mode'          => $default_password_mode,
	'rewrite_woocommerce_emails' => false,
];

$settings = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
$settings = array_merge( $default_settings, is_array( $settings ) ? $settings : [] );

$stored_slug = sanitize_key( (string) ( $settings['login_slug'] ?? '' ) );
if ( $stored_slug === '' && OptionStoreModuleSettingsRepository::isModuleEnabled( $module_id ) ) {
	Module::ensurePersistedLoginSlug();
	$settings    = array_merge( $default_settings, OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] ) );
	$stored_slug = sanitize_key( (string) ( $settings['login_slug'] ?? '' ) );
}
$custom_slug = $stored_slug;
$login_url   = $custom_slug !== '' ? home_url( '/' . $custom_slug ) : home_url( '/your-site-crew' );

$blocked_behavior           = in_array( (string) ( $settings['blocked_behavior'] ?? '404' ), [ '404', 'redirect' ], true )
	? (string) $settings['blocked_behavior']
	: '404';
$blocked_redirect_url       = (string) ( $settings['blocked_redirect_url'] ?? '' );
$redirect_wp_login_actions  = ! empty( $settings['redirect_wp_login_actions'] );
$woocommerce_guest_redirect = ! empty( $settings['woocommerce_guest_redirect'] );
$password_url_mode          = in_array( (string) ( $settings['password_url_mode'] ?? $default_password_mode ), [ 'auto', 'custom', 'woocommerce' ], true )
	? (string) $settings['password_url_mode']
	: $default_password_mode;
$rewrite_woocommerce_emails = ! empty( $settings['rewrite_woocommerce_emails'] );

$slug_is_weak    = in_array( $custom_slug, Module::discouragedSlugs(), true );
$woo_active      = class_exists( 'WooCommerce', false );
$dpr_active      = OptionStoreModuleSettingsRepository::isModuleEnabled( 'disable-password-reset' );
$show_email_leak = $rewrite_woocommerce_emails && $password_url_mode === 'custom';
$show_redirect   = $blocked_behavior === 'redirect';

$copy_label   = __( 'Copy', 'wp-powersuite' );
$copied_label = __( 'Copied', 'wp-powersuite' );

$uid = $module_id;
?>

<div class="wp-powersuite-module-settings wpps-clu-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 wpps-module-settings-lead">
			<?php esc_html_e( 'Replace wp-login.php with a private URL. Bookmark it — default login paths return a 404.', 'wp-powersuite' ); ?>
		</p>

		<?php if ( NetworkScope::usesNetworkStorage() ) : ?>
			<div class="wpps-settings-alert wpps-settings-alert--info" role="status">
				<p>
					<?php
					echo esc_html(
						sprintf(
							/* translators: %s: plugin brand name */
							__( 'Network-wide %s settings: this slug applies to every site.', 'wp-powersuite' ),
							WhiteLabel::pluginName()
						)
					);
					?>
				</p>
			</div>
		<?php endif; ?>

		<?php if ( $dpr_active ) : ?>
			<div class="wpps-settings-alert wpps-settings-alert--warning" role="status">
				<p>
					<?php esc_html_e( 'Disable Password Reset is on — public lost-password forms stay blocked; keyed email links still work.', 'wp-powersuite' ); ?>
				</p>
			</div>
		<?php endif; ?>

		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $uid . '_login_slug' ); ?>">
							<?php esc_html_e( 'Login slug', 'wp-powersuite' ); ?>
						</label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: login slug', 'wp-powersuite' ),
							__( 'Use an uncommon phrase (lowercase letters, numbers, hyphens). Avoid words like login or admin. Bookmark the new URL — if you lose access, disable this module via database/WP-CLI or ask another admin to reset the slug.', 'wp-powersuite' )
						);
						?>
					</th>
					<td>
						<input type="text"
							id="<?php echo esc_attr( $uid . '_login_slug' ); ?>"
							name="login_slug"
							class="wp-powersuite-advanced-setting regular-text"
							data-setting-key="login_slug"
							value="<?php echo esc_attr( $custom_slug ); ?>"
							placeholder="<?php echo esc_attr( __( 'your-site-crew', 'wp-powersuite' ) ); ?>"
							pattern="[a-z0-9\-]+"
							<?php echo $custom_slug !== '' ? 'required' : ''; ?>
							autocomplete="off"
							spellcheck="false"
						/>
						<div class="wpps-clu-url-row">
							<code id="<?php echo esc_attr( $uid . '_login_url' ); ?>" class="wpps-clu-url-row__code"><?php echo esc_url( $login_url ); ?></code>
							<button type="button"
								class="button button-secondary wpps-clu-copy-login-url"
								id="<?php echo esc_attr( $uid . '_copy_login_url' ); ?>"
								data-url="<?php echo esc_attr( $login_url ); ?>"
								data-copy-label="<?php echo esc_attr( $copy_label ); ?>"
								data-copied-label="<?php echo esc_attr( $copied_label ); ?>"
								aria-label="<?php esc_attr_e( 'Copy login URL', 'wp-powersuite' ); ?>"
							><?php echo esc_html( $copy_label ); ?></button>
							<span class="screen-reader-text" id="<?php echo esc_attr( $uid . '_copy_status' ); ?>" aria-live="polite"></span>
						</div>
						<?php if ( $slug_is_weak ) : ?>
							<p class="wpps-clu-inline-warn">
								<?php esc_html_e( 'This slug is easy to guess. Prefer an uncommon phrase.', 'wp-powersuite' ); ?>
							</p>
						<?php endif; ?>
					</td>
				</tr>
			</tbody>
		</table>

		<details class="wpps-clu-advanced">
			<summary><?php esc_html_e( 'Advanced options', 'wp-powersuite' ); ?></summary>

			<table class="form-table" role="presentation">
				<tbody>
					<tr>
						<th scope="row">
							<label for="<?php echo esc_attr( $uid . '_blocked_behavior' ); ?>">
								<?php esc_html_e( 'Blocked URLs', 'wp-powersuite' ); ?>
							</label>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: blocked URLs', 'wp-powersuite' ),
								__( 'What happens on wp-login.php or logged-out wp-admin. 404 hides the login surface; Redirect sends visitors elsewhere.', 'wp-powersuite' )
							);
							?>
						</th>
						<td>
							<select
								id="<?php echo esc_attr( $uid . '_blocked_behavior' ); ?>"
								name="blocked_behavior"
								class="wp-powersuite-advanced-setting"
								data-setting-key="blocked_behavior"
							>
								<option value="404" <?php selected( $blocked_behavior, '404' ); ?>><?php esc_html_e( 'Show 404 (recommended)', 'wp-powersuite' ); ?></option>
								<option value="redirect" <?php selected( $blocked_behavior, 'redirect' ); ?>><?php esc_html_e( 'Redirect to a URL', 'wp-powersuite' ); ?></option>
							</select>
							<div
								id="<?php echo esc_attr( $uid . '_redirect_wrap' ); ?>"
								class="wpps-clu-redirect-wrap"
								<?php echo $show_redirect ? '' : ' hidden'; ?>
							>
								<input type="url"
									id="<?php echo esc_attr( $uid . '_blocked_redirect_url' ); ?>"
									name="blocked_redirect_url"
									class="wp-powersuite-advanced-setting regular-text"
									data-setting-key="blocked_redirect_url"
									value="<?php echo esc_attr( $blocked_redirect_url ); ?>"
									placeholder="<?php echo esc_attr( home_url( '/' ) ); ?>"
									aria-label="<?php esc_attr_e( 'Redirect URL', 'wp-powersuite' ); ?>"
								/>
								<p class="description"><?php esc_html_e( 'Optional — defaults to homepage.', 'wp-powersuite' ); ?></p>
							</div>
						</td>
					</tr>

					<tr>
						<th scope="row">
							<?php esc_html_e( 'Legacy links', 'wp-powersuite' ); ?>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: legacy links', 'wp-powersuite' ),
								__( 'Redirects password-reset, logout, and similar wp-login.php?action=… links to your custom URL. Reveals the slug to probers — leave off unless you need that compatibility.', 'wp-powersuite' )
							);
							?>
						</th>
						<td>
							<label class="wpps-clu-check" for="<?php echo esc_attr( $uid . '_redirect_wp_login_actions' ); ?>">
								<input
									type="checkbox"
									id="<?php echo esc_attr( $uid . '_redirect_wp_login_actions' ); ?>"
									name="redirect_wp_login_actions"
									class="wp-powersuite-advanced-setting"
									data-setting-key="redirect_wp_login_actions"
									value="1"
									<?php checked( $redirect_wp_login_actions ); ?>
								/>
								<?php esc_html_e( 'Redirect reset / logout / register links to the custom URL', 'wp-powersuite' ); ?>
							</label>
						</td>
					</tr>

					<tr>
						<th scope="row">
							<label for="<?php echo esc_attr( $uid . '_password_url_mode' ); ?>">
								<?php esc_html_e( 'Password reset URLs', 'wp-powersuite' ); ?>
							</label>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: password URLs', 'wp-powersuite' ),
								__( 'Auto keeps WooCommerce resets on My Account and uses your custom login URL elsewhere. Custom forces all reset links through the private login address.', 'wp-powersuite' )
							);
							?>
						</th>
						<td>
							<select
								id="<?php echo esc_attr( $uid . '_password_url_mode' ); ?>"
								name="password_url_mode"
								class="wp-powersuite-advanced-setting"
								data-setting-key="password_url_mode"
							>
								<option value="auto" <?php selected( $password_url_mode, 'auto' ); ?>><?php esc_html_e( 'Auto (recommended)', 'wp-powersuite' ); ?></option>
								<option value="custom" <?php selected( $password_url_mode, 'custom' ); ?>><?php esc_html_e( 'Always custom login URL', 'wp-powersuite' ); ?></option>
								<option value="woocommerce" <?php selected( $password_url_mode, 'woocommerce' ); ?> <?php disabled( ! $woo_active ); ?>><?php esc_html_e( 'Always WooCommerce My Account', 'wp-powersuite' ); ?></option>
							</select>
						</td>
					</tr>

					<?php if ( $woo_active ) : ?>
						<tr>
							<th scope="row">
								<?php esc_html_e( 'WooCommerce', 'wp-powersuite' ); ?>
								<?php
								wpps_render_modal_settings_tip(
									__( 'Help: WooCommerce', 'wp-powersuite' ),
									__( 'Guest My Account redirect sends shoppers to your custom login, then back after sign-in. Email rewrite puts the private slug in customer emails — leave off for better obscurity (My Account lost-password links still work).', 'wp-powersuite' )
								);
								?>
							</th>
							<td>
								<label class="wpps-clu-check" for="<?php echo esc_attr( $uid . '_woocommerce_guest_redirect' ); ?>">
									<input
										type="checkbox"
										id="<?php echo esc_attr( $uid . '_woocommerce_guest_redirect' ); ?>"
										name="woocommerce_guest_redirect"
										class="wp-powersuite-advanced-setting"
										data-setting-key="woocommerce_guest_redirect"
										value="1"
										<?php checked( $woocommerce_guest_redirect ); ?>
									/>
									<?php esc_html_e( 'Redirect guest My Account login', 'wp-powersuite' ); ?>
								</label>
								<label class="wpps-clu-check" for="<?php echo esc_attr( $uid . '_rewrite_woocommerce_emails' ); ?>">
									<input
										type="checkbox"
										id="<?php echo esc_attr( $uid . '_rewrite_woocommerce_emails' ); ?>"
										name="rewrite_woocommerce_emails"
										class="wp-powersuite-advanced-setting"
										data-setting-key="rewrite_woocommerce_emails"
										value="1"
										<?php checked( $rewrite_woocommerce_emails ); ?>
									/>
									<?php esc_html_e( 'Rewrite links in WooCommerce emails', 'wp-powersuite' ); ?>
								</label>
								<div
									id="<?php echo esc_attr( $uid . '_email_leak_warning' ); ?>"
									class="wpps-settings-alert wpps-settings-alert--warning"
									role="alert"
									<?php echo $show_email_leak ? '' : ' hidden'; ?>
								>
									<p>
										<?php esc_html_e( 'Email rewrite + “Always custom” exposes your private login slug in customer emails.', 'wp-powersuite' ); ?>
									</p>
								</div>
							</td>
						</tr>
					<?php else : ?>
						<input type="hidden" class="wp-powersuite-advanced-setting" data-setting-key="woocommerce_guest_redirect" value="0" />
						<input type="hidden" class="wp-powersuite-advanced-setting" data-setting-key="rewrite_woocommerce_emails" value="0" />
					<?php endif; ?>
				</tbody>
			</table>
		</details>
	</form>
</div>

<script>
(function () {
	var slugInput = document.getElementById(<?php echo wp_json_encode( $uid . '_login_slug' ); ?>);
	var urlCode = document.getElementById(<?php echo wp_json_encode( $uid . '_login_url' ); ?>);
	var copyBtn = document.getElementById(<?php echo wp_json_encode( $uid . '_copy_login_url' ); ?>);
	var copyStatus = document.getElementById(<?php echo wp_json_encode( $uid . '_copy_status' ); ?>);
	var behaviorSelect = document.getElementById(<?php echo wp_json_encode( $uid . '_blocked_behavior' ); ?>);
	var redirectWrap = document.getElementById(<?php echo wp_json_encode( $uid . '_redirect_wrap' ); ?>);
	var modeSelect = document.getElementById(<?php echo wp_json_encode( $uid . '_password_url_mode' ); ?>);
	var rewriteBox = document.getElementById(<?php echo wp_json_encode( $uid . '_rewrite_woocommerce_emails' ); ?>);
	var leakWarning = document.getElementById(<?php echo wp_json_encode( $uid . '_email_leak_warning' ); ?>);

	function homeBase() {
		var code = urlCode ? urlCode.textContent : '';
		if (!code) {
			return '';
		}
		return code.replace(/\/[^/]+\/?$/, '/');
	}

	function updatePreviewUrl() {
		if (!slugInput || !urlCode || !copyBtn) {
			return;
		}
		var slug = (slugInput.value || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '');
		if (!slug) {
			slug = 'your-site-crew';
		}
		var base = homeBase() || window.location.origin + '/';
		var next = base.replace(/\/?$/, '/') + slug;
		urlCode.textContent = next;
		copyBtn.setAttribute('data-url', next);
	}

	function updateRedirectWrap() {
		if (!redirectWrap || !behaviorSelect) {
			return;
		}
		redirectWrap.hidden = behaviorSelect.value !== 'redirect';
	}

	function updateEmailLeakWarning() {
		if (!leakWarning) {
			return;
		}
		var mode = modeSelect ? modeSelect.value : '';
		var rewriteOn = !!(rewriteBox && rewriteBox.checked);
		leakWarning.hidden = !(rewriteOn && mode === 'custom');
	}

	if (slugInput) {
		slugInput.addEventListener('input', updatePreviewUrl);
	}
	if (behaviorSelect) {
		behaviorSelect.addEventListener('change', updateRedirectWrap);
	}
	if (modeSelect) {
		modeSelect.addEventListener('change', updateEmailLeakWarning);
	}
	if (rewriteBox) {
		rewriteBox.addEventListener('change', updateEmailLeakWarning);
	}

	if (copyBtn) {
		copyBtn.addEventListener('click', function () {
			var url = copyBtn.getAttribute('data-url') || '';
			if (!url) {
				return;
			}
			var copiedLabel = copyBtn.getAttribute('data-copied-label') || 'Copied';
			var copyLabel = copyBtn.getAttribute('data-copy-label') || 'Copy';
			var done = function () {
				copyBtn.textContent = copiedLabel;
				if (copyStatus) {
					copyStatus.textContent = copiedLabel;
				}
				window.setTimeout(function () {
					copyBtn.textContent = copyLabel;
					if (copyStatus) {
						copyStatus.textContent = '';
					}
				}, 2000);
			};
			if (navigator.clipboard && navigator.clipboard.writeText) {
				navigator.clipboard.writeText(url).then(done).catch(function () {
					window.prompt(<?php echo wp_json_encode( __( 'Copy this login URL:', 'wp-powersuite' ) ); ?>, url);
				});
				return;
			}
			window.prompt(<?php echo wp_json_encode( __( 'Copy this login URL:', 'wp-powersuite' ) ); ?>, url);
			done();
		});
	}
})();
</script>
