<?php
/**
 * Forumax Login & Registration Form Shortcode
 *
 * Renders a tabbed Login / Sign Up form. Uses wp_login_form() to ensure
 * Google Site Kit (and any plugin that hooks into `login_form`) works.
 *
 * @package Forumax
 */

/**
 * Render the tabbed login and registration form.
 *
 * @param array $atts Shortcode attributes.
 *
 * @return string HTML output.
 */
function forumax_login_form_shortcode( $atts ) {
	// If user already logged in, return a message.
	if ( is_user_logged_in() ) {
		return '<div class="frmx-auth-logged-in">' . esc_html__( 'You are already logged in.', 'forumax' ) . '</div>';
	}

	// Extract shortcode attributes with defaults.
	$atts = shortcode_atts( array(
		'redirect' => '',
	), $atts );

	// Set redirect URL.
	$redirect_url = ! empty( $atts['redirect'] ) ? $atts['redirect'] : get_permalink();

	$can_register = get_option( 'users_can_register' );

	ob_start();
	?>
	<div class="frmx-auth-tabs">

		<?php if ( $can_register ) : ?>
			<div class="frmx-auth-tabs-header">
				<button type="button" class="frmx-auth-tab frmx-auth-tab-active" data-frmx-tab="login">
					<?php esc_html_e( 'Sign In', 'forumax' ); ?>
				</button>
				<button type="button" class="frmx-auth-tab" data-frmx-tab="register">
					<?php esc_html_e( 'Create Account', 'forumax' ); ?>
				</button>
			</div>
		<?php endif; ?>

		<!-- Login Tab -->
		<div class="frmx-auth-panel frmx-auth-panel-active" data-frmx-panel="login">
			<?php
			$form_html = wp_login_form( array(
				'redirect'       => $redirect_url,
				'label_username' => esc_html__( 'Username or Email', 'forumax' ),
				'label_password' => esc_html__( 'Password', 'forumax' ),
				'label_remember' => esc_html__( 'Remember Me', 'forumax' ),
				'label_log_in'   => esc_html__( 'Sign In', 'forumax' ),
				'form_id'        => 'forumax_login_form',
				'remember'       => true,
				'echo'           => false,
			) );

			// Add placeholders to core login form fields.
			$username_placeholder = esc_attr__( 'Username or Email', 'forumax' );
			$password_placeholder = esc_attr__( 'Password', 'forumax' );

			$form_html = preg_replace(
				'/(<input\b(?![^>]*\bplaceholder=)[^>]*\bname=["\']log["\'][^>]*)(\/?\s*>)/i',
				'$1 placeholder="' . $username_placeholder . '"$2',
				$form_html
			);
			$form_html = preg_replace(
				'/(<input\b(?![^>]*\bplaceholder=)[^>]*\bname=["\']pwd["\'][^>]*)(\/?\s*>)/i',
				'$1 placeholder="' . $password_placeholder . '"$2',
				$form_html
			);

			echo $form_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			?>

			<?php
			/**
			 * Hook to display social login buttons (e.g. Google Site Kit).
			 */
			do_action( 'forumax_login_form_social_buttons' );
			?>
		</div>

		<?php if ( $can_register ) : ?>
			<!-- Registration Tab -->
			<div class="frmx-auth-panel" data-frmx-panel="register">
				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="frmx-auth-register-form">
					<input type="hidden" name="action" value="forumax_register" />
					<input type="hidden" name="redirect_to" value="<?php echo esc_url( $redirect_url ); ?>" />

					<div class="frmx-auth-field">
						<label for="frmx_reg_user_login"><?php esc_html_e( 'Username', 'forumax' ); ?></label>
						<input type="text" name="user_login" id="frmx_reg_user_login" placeholder="<?php esc_attr_e( 'Username', 'forumax' ); ?>" autocomplete="username" required />
					</div>

					<div class="frmx-auth-field">
						<label for="frmx_reg_user_email"><?php esc_html_e( 'Email', 'forumax' ); ?></label>
						<input type="email" name="user_email" id="frmx_reg_user_email" placeholder="<?php esc_attr_e( 'Email', 'forumax' ); ?>" autocomplete="email" required />
					</div>

					<div class="frmx-auth-field">
						<label for="frmx_reg_user_pass"><?php esc_html_e( 'Password', 'forumax' ); ?></label>
						<input type="password" name="user_pass" id="frmx_reg_user_pass" placeholder="<?php esc_attr_e( 'Password', 'forumax' ); ?>" autocomplete="new-password" required />
					</div>

					<div class="frmx-auth-field">
						<label for="frmx_reg_user_pass_confirm"><?php esc_html_e( 'Confirm Password', 'forumax' ); ?></label>
						<input type="password" name="user_pass_confirm" id="frmx_reg_user_pass_confirm" placeholder="<?php esc_attr_e( 'Confirm Password', 'forumax' ); ?>" autocomplete="new-password" required />
					</div>

					<?php
					/**
					 * Fires inside the registration form.
					 *
					 * This is the standard WordPress hook that plugins (e.g. CAPTCHA,
					 * custom fields) use to inject content into registration forms.
					 */
					do_action( 'register_form' );
					?>

					<div class="frmx-auth-submit">
						<button type="submit" id="frmx-register-submit" name="wp-submit" class="button submit fill-brand">
							<?php esc_html_e( 'Register', 'forumax' ); ?>
						</button>
					</div>

					<?php wp_nonce_field( 'forumax_register', 'forumax_register_nonce' ); ?>
				</form>
			</div>
		<?php endif; ?>

	</div>

	<script>
	( function() {
		var wrapper = document.querySelector( '.frmx-auth-tabs' );
		if ( ! wrapper ) {
			return;
		}

		var tabs   = wrapper.querySelectorAll( '.frmx-auth-tab' );
		var panels = wrapper.querySelectorAll( '.frmx-auth-panel' );

		tabs.forEach( function( tab ) {
			tab.addEventListener( 'click', function() {
				var target = this.getAttribute( 'data-frmx-tab' );

				tabs.forEach( function( t ) {
					t.classList.remove( 'frmx-auth-tab-active' );
				} );
				this.classList.add( 'frmx-auth-tab-active' );

				panels.forEach( function( p ) {
					if ( p.getAttribute( 'data-frmx-panel' ) === target ) {
						p.classList.add( 'frmx-auth-panel-active' );
					} else {
						p.classList.remove( 'frmx-auth-panel-active' );
					}
				} );
			} );
		} );

		/* Password visibility toggle */
		var eyeShow = '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>';
		var eyeHide = '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>';

		wrapper.querySelectorAll( 'input[type="password"]' ).forEach( function( input ) {
			var container = document.createElement( 'div' );
			container.className = 'frmx-auth-password-wrap';
			input.parentNode.insertBefore( container, input );
			container.appendChild( input );

			var toggleBtn = document.createElement( 'button' );
			toggleBtn.type = 'button';
			toggleBtn.className = 'frmx-auth-eye-toggle';
			toggleBtn.setAttribute( 'aria-label', 'Toggle password visibility' );
			toggleBtn.innerHTML = eyeShow;
			container.appendChild( toggleBtn );

			toggleBtn.addEventListener( 'click', function() {
				var isPassword = input.type === 'password';
				input.type = isPassword ? 'text' : 'password';
				this.innerHTML = isPassword ? eyeHide : eyeShow;
				input.focus();
			} );
		} );
	} )();
	</script>
	<?php

	return ob_get_clean();
}

add_shortcode( 'forumax_login_form', 'forumax_login_form_shortcode' );

/**
 * Redirect to the referrer page after a failed login attempt.
 *
 * @param string $username The username that failed login.
 *
 * @return void
 */
function forumax_login_failed_redirect( $username ) {
	$referrer = wp_get_referer();
	if ( ! empty( $referrer ) && ! str_contains( $referrer, 'wp-login.php' ) ) {
		wp_redirect( add_query_arg( 'login', 'failed', $referrer ) );
		exit;
	}
}

add_action( 'wp_login_failed', 'forumax_login_failed_redirect' );

/**
 * Handle the custom registration form submission.
 *
 * Creates a new user with the provided username, email, and password,
 * auto-logs them in, and redirects to the referring page.
 *
 * @return void
 */
function forumax_handle_registration() {
	// Verify nonce.
	if ( ! isset( $_POST['forumax_register_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['forumax_register_nonce'] ) ), 'forumax_register' ) ) {
		wp_die( esc_html__( 'Security check failed.', 'forumax' ), 403 );
	}

	// Check registration is allowed.
	if ( ! get_option( 'users_can_register' ) ) {
		wp_die( esc_html__( 'Registration is currently disabled.', 'forumax' ), 403 );
	}

	$redirect = ! empty( $_POST['redirect_to'] ) ? esc_url_raw( wp_unslash( $_POST['redirect_to'] ) ) : home_url();
	$referrer = wp_get_referer();
	if ( empty( $referrer ) ) {
		$referrer = $redirect;
	}

	$user_login = isset( $_POST['user_login'] ) ? sanitize_user( wp_unslash( $_POST['user_login'] ) ) : '';
	$user_email = isset( $_POST['user_email'] ) ? sanitize_email( wp_unslash( $_POST['user_email'] ) ) : '';
	$user_pass  = isset( $_POST['user_pass'] ) ? $_POST['user_pass'] : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- password must not be sanitized.
	$user_pass_confirm = isset( $_POST['user_pass_confirm'] ) ? $_POST['user_pass_confirm'] : ''; // phpcs:ignore

	// Validate fields.
	$errors = array();

	if ( empty( $user_login ) ) {
		$errors[] = 'empty_username';
	}

	if ( empty( $user_email ) || ! is_email( $user_email ) ) {
		$errors[] = 'invalid_email';
	}

	if ( empty( $user_pass ) ) {
		$errors[] = 'empty_password';
	}

	if ( $user_pass !== $user_pass_confirm ) {
		$errors[] = 'password_mismatch';
	}

	if ( ! empty( $errors ) ) {
		wp_safe_redirect( add_query_arg( 'reg_error', implode( ',', $errors ), $referrer ) );
		exit;
	}

	// Let external plugins validate registration (e.g. Envato license check).
	$sbv_valid = apply_filters( 'sbv_validate_registration', true );
	if ( is_wp_error( $sbv_valid ) ) {
		wp_safe_redirect( add_query_arg( 'reg_error', $sbv_valid->get_error_code(), $referrer ) );
		exit;
	}

	// Create the user.
	$user_id = wp_create_user( $user_login, $user_pass, $user_email );

	if ( is_wp_error( $user_id ) ) {
		$error_code = $user_id->get_error_code();
		wp_safe_redirect( add_query_arg( 'reg_error', $error_code, $referrer ) );
		exit;
	}

	// Fire standard WordPress registration action.
	do_action( 'user_register', $user_id );

	// Auto-login the new user.
	wp_set_current_user( $user_id );
	wp_set_auth_cookie( $user_id, true );

	wp_safe_redirect( $redirect );
	exit;
}

add_action( 'admin_post_nopriv_forumax_register', 'forumax_handle_registration' );
add_action( 'admin_post_forumax_register', 'forumax_handle_registration' );
