<?php

namespace ChangeLoginURL;

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

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

if ( ! function_exists( 'wp_powersuite_is_license_valid' ) || ! wp_powersuite_is_license_valid() ) {
	$license_page_url = admin_url( 'admin.php?page=powersuite-license' );
	?>
	<div class="wp-powersuite-module-settings wpps-settings-panel" data-module-id="<?php echo esc_attr( $module_id ?? 'change-login-url' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Change Login URL requires an active license. Activate your license to configure a custom login address.', 'wp-powersuite' ); ?>
				<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_settings = [
	'login_slug'                 => 'login',
	'blocked_behavior'           => '404',
	'blocked_redirect_url'       => '',
	'redirect_wp_login_actions'  => true,
	'woocommerce_guest_redirect' => true,
	'password_url_mode'          => 'custom',
	'rewrite_woocommerce_emails' => true,
];

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

$custom_slug = Module::normalizeLoginSlug( (string) ( $settings['login_slug'] ?? 'login' ) );
$login_url   = home_url( '/' . $custom_slug );

$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    = ! array_key_exists( 'redirect_wp_login_actions', $settings ) || ! empty( $settings['redirect_wp_login_actions'] );
$woocommerce_guest_redirect   = ! array_key_exists( 'woocommerce_guest_redirect', $settings ) || ! empty( $settings['woocommerce_guest_redirect'] );
$password_url_mode            = in_array( (string) ( $settings['password_url_mode'] ?? 'custom' ), [ 'auto', 'custom', 'woocommerce' ], true )
	? (string) $settings['password_url_mode']
	: 'custom';
$rewrite_woocommerce_emails   = ! array_key_exists( 'rewrite_woocommerce_emails', $settings ) || ! empty( $settings['rewrite_woocommerce_emails'] );

$discouraged_slugs = Module::discouragedSlugs();
$slug_is_weak      = in_array( $custom_slug, $discouraged_slugs, true );
$woo_active        = class_exists( 'WooCommerce', false );
$dpr_active        = OptionStoreModuleSettingsRepository::isModuleEnabled( 'disable-password-reset' );

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

?>

<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-bottom: 16px;">
			<?php esc_html_e( 'Replace wp-login.php with a private login address. Default login URLs return a 404 (or your chosen redirect). Password reset, logout, and registration links are rewritten to your custom URL.', 'wp-powersuite' ); ?>
		</p>
		<p class="description" style="margin-bottom: 16px;">
			<?php esc_html_e( 'Works with Login Page Customizer—your branded login styling applies on the custom URL as well.', 'wp-powersuite' ); ?>
		</p>

		<?php if ( NetworkScope::usesNetworkStorage() ) : ?>
			<div class="notice notice-info inline" style="margin-bottom: 16px;">
				<p>
					<?php esc_html_e( 'On multisite with network-wide PowerSuite settings, this login slug applies to all sites in the network.', 'wp-powersuite' ); ?>
				</p>
			</div>
		<?php endif; ?>

		<?php if ( $dpr_active ) : ?>
			<div class="notice notice-warning inline" style="margin-bottom: 16px;">
				<p>
					<?php esc_html_e( 'Disable Password Reset is also enabled. Public lost-password forms stay blocked, but keyed reset / new-account links from email still work.', 'wp-powersuite' ); ?>
				</p>
			</div>
		<?php endif; ?>

		<table class="form-table">
			<tbody>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id . '_login_slug' ); ?>">
							<?php esc_html_e( 'Custom Login Slug', 'wp-powersuite' ); ?>
						</label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: custom slug', 'wp-powersuite' ),
							__( 'Choose an uncommon phrase (e.g., your-site-crew) for better obscurity. Avoid common words like "login" or "admin".', 'wp-powersuite' )
						);
						?>
					</th>
					<td>
						<input type="text"
							id="<?php echo esc_attr( $module_id . '_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\-]+"
							required
							autocomplete="off"
							spellcheck="false"
						/>
						<p class="description">
							<?php esc_html_e( 'Only lowercase letters, numbers, and hyphens are allowed.', 'wp-powersuite' ); ?>
						</p>
						<p class="description" style="margin-top: 8px;">
							<strong><?php esc_html_e( 'Your new login URL:', 'wp-powersuite' ); ?></strong>
							<code id="<?php echo esc_attr( $module_id . '_login_url' ); ?>"><?php echo esc_url( $login_url ); ?></code>
							<button type="button"
								class="button button-secondary wpps-clu-copy-login-url"
								id="<?php echo esc_attr( $module_id . '_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 to clipboard', 'wp-powersuite' ); ?>"
							><?php echo esc_html( $copy_label ); ?></button>
							<span class="screen-reader-text" id="<?php echo esc_attr( $module_id . '_copy_status' ); ?>" aria-live="polite"></span>
						</p>
						<?php if ( $slug_is_weak ) : ?>
							<div class="notice notice-warning inline" style="margin-top: 12px;">
								<p>
									<?php esc_html_e( 'This slug is easy to guess or conflicts with core paths. Use an uncommon phrase (e.g. your-site-crew) for better obscurity.', 'wp-powersuite' ); ?>
								</p>
							</div>
						<?php endif; ?>
					</td>
				</tr>

				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id . '_blocked_behavior' ); ?>">
							<?php esc_html_e( 'Blocked URL behavior', 'wp-powersuite' ); ?>
						</label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: blocked URLs', 'wp-powersuite' ),
							__( 'Choose what happens when someone visits wp-login.php or wp-admin while logged out. “404” hides the login surface; “Redirect” sends them elsewhere.', 'wp-powersuite' )
						);
						?>
					</th>
					<td>
						<select
							id="<?php echo esc_attr( $module_id . '_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>
						<p class="description" style="margin-top: 8px;">
							<label for="<?php echo esc_attr( $module_id . '_blocked_redirect_url' ); ?>">
								<?php esc_html_e( 'Redirect URL (optional — defaults to homepage)', 'wp-powersuite' ); ?>
							</label>
						</p>
						<input type="url"
							id="<?php echo esc_attr( $module_id . '_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( '/' ) ); ?>"
						/>
					</td>
				</tr>

				<tr>
					<th scope="row">
						<?php esc_html_e( 'Legacy login links', 'wp-powersuite' ); ?>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: legacy links', 'wp-powersuite' ),
							__( 'When enabled, password-reset, logout, and similar links that still point at wp-login.php are redirected to your custom URL with the same query args. Plain wp-login.php visits still show a 404/redirect.', 'wp-powersuite' )
						);
						?>
					</th>
					<td>
						<label for="<?php echo esc_attr( $module_id . '_redirect_wp_login_actions' ); ?>">
							<input
								type="checkbox"
								id="<?php echo esc_attr( $module_id . '_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 from wp-login.php to the custom URL', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>

				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id . '_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 My Account reset pages on the storefront and uses your custom login URL elsewhere. Custom forces all reset links through your private login address.', 'wp-powersuite' )
						);
						?>
					</th>
					<td>
						<select
							id="<?php echo esc_attr( $module_id . '_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 (WooCommerce on storefront, custom login elsewhere)', 'wp-powersuite' ); ?></option>
							<option value="custom" <?php selected( $password_url_mode, 'custom' ); ?>><?php esc_html_e( 'Always use custom login URL', 'wp-powersuite' ); ?></option>
							<option value="woocommerce" <?php selected( $password_url_mode, 'woocommerce' ); ?> <?php disabled( ! $woo_active ); ?>><?php esc_html_e( 'Always use WooCommerce My Account', 'wp-powersuite' ); ?></option>
						</select>
					</td>
				</tr>

				<?php if ( $woo_active ) : ?>
					<tr>
						<th scope="row">
							<?php esc_html_e( 'WooCommerce My Account', 'wp-powersuite' ); ?>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: WooCommerce login', 'wp-powersuite' ),
								__( 'When enabled, guests visiting My Account are sent to your custom login URL (then returned to My Account after signing in). Lost-password / set-password endpoints with a key are not redirected.', 'wp-powersuite' )
							);
							?>
						</th>
						<td>
							<label for="<?php echo esc_attr( $module_id . '_woocommerce_guest_redirect' ); ?>" style="display:block;margin-bottom:10px;">
								<input
									type="checkbox"
									id="<?php echo esc_attr( $module_id . '_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 to the custom login URL', 'wp-powersuite' ); ?>
							</label>
							<label for="<?php echo esc_attr( $module_id . '_rewrite_woocommerce_emails' ); ?>" style="display:block;">
								<input
									type="checkbox"
									id="<?php echo esc_attr( $module_id . '_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 new-account / reset links in WooCommerce emails to the custom login URL', 'wp-powersuite' ); ?>
							</label>
							<p class="description" style="margin-top:8px;">
								<?php esc_html_e( 'Without rewrite, WooCommerce emails look like /my-account/lost-password/?action=newaccount&key=… — that is normal WooCommerce behavior. Enable rewrite to force your private login slug instead.', 'wp-powersuite' ); ?>
							</p>
						</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="<?php echo $rewrite_woocommerce_emails ? '1' : '0'; ?>" />
				<?php endif; ?>
			</tbody>
		</table>

		<div class="notice notice-warning inline" style="margin-top: 20px;">
			<p>
				<strong><?php esc_html_e( 'Important:', 'wp-powersuite' ); ?></strong>
				<?php esc_html_e( 'After changing your login URL, bookmark the new URL. Plain wp-login.php and logged-out wp-admin visits are blocked.', 'wp-powersuite' ); ?>
			</p>
			<p>
				<?php esc_html_e( 'If you reuse a previous slug, click Save once to refresh routing. Clear your site or browser cache if the old address still shows a 404.', 'wp-powersuite' ); ?>
			</p>
			<p>
				<?php esc_html_e( 'If you lose access, disable the Change Login URL module from WP PowerSuite (via database or WP-CLI) or ask another administrator to reset the slug.', 'wp-powersuite' ); ?>
			</p>
		</div>
	</form>
</div>

<script>
(function () {
	var slugInput = document.getElementById(<?php echo wp_json_encode( $module_id . '_login_slug' ); ?>);
	var urlCode = document.getElementById(<?php echo wp_json_encode( $module_id . '_login_url' ); ?>);
	var copyBtn = document.getElementById(<?php echo wp_json_encode( $module_id . '_copy_login_url' ); ?>);
	var copyStatus = document.getElementById(<?php echo wp_json_encode( $module_id . '_copy_status' ); ?>);

	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 = 'login';
		}
		var base = homeBase() || window.location.origin + '/';
		var next = base.replace(/\/?$/, '/') + slug;
		urlCode.textContent = next;
		copyBtn.setAttribute('data-url', next);
	}

	if (slugInput) {
		slugInput.addEventListener('input', updatePreviewUrl);
	}

	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 URL';
			var done = function () {
				copyBtn.textContent = copiedLabel;
				if (copyStatus) {
					copyStatus.textContent = copiedLabel;
				}
				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>
