<?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',
];

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

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

$login_url = home_url( '/' . $custom_slug );

$discouraged_slugs = Module::discouragedSlugs();
$slug_is_weak       = in_array( $custom_slug, $discouraged_slugs, true );

$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( 'Change your WordPress login URL to a custom URL. The default URLs (wp-login.php and wp-admin) will show 404 error instead of redirecting.', '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; ?>

		<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( 'Enter a custom slug for your login URL. 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>
			</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. Default URLs (wp-login.php and wp-admin) always show a 404—even for password reset, logout, or registration links. Use your custom URL for those flows.', '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>
