<?php
/**
 * Single login_message filter for all social OAuth providers.
 *
 * @package WP_PowerSuite\OAuth\UI
 */

namespace WP_PowerSuite\OAuth\UI;

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

final class SocialLoginErrorHandler {

	private static bool $registered = false;

	/** @var array<string, list<string>> Primary query arg => legacy fallbacks. */
	private const ERROR_ARGS = [
		'wpps_google_error'   => [],
		'wpps_facebook_error' => [ 'fb_login_error' ],
		'wpps_github_error'   => [],
	];

	public static function register(): void {
		if ( self::$registered ) {
			return;
		}
		self::$registered = true;
		add_filter( 'login_message', [ self::class, 'appendErrors' ], 10 );
	}

	/**
	 * @param string $message Existing login message HTML.
	 */
	public static function appendErrors( $message ): string {
		$message = (string) $message;
		foreach ( self::ERROR_ARGS as $primary => $legacy ) {
			$err = self::readErrorParam( $primary );
			if ( $err === '' ) {
				foreach ( $legacy as $legacy_key ) {
					$err = self::readErrorParam( $legacy_key, true );
					if ( $err !== '' ) {
						break;
					}
				}
			}
			if ( $err !== '' ) {
				return '<div id="login_error" class="message wpps-sl-login-error">' . esc_html( $err ) . '</div>' . $message;
			}
		}
		return $message;
	}

	private static function readErrorParam( string $key, bool $decode = false ): string {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! isset( $_GET[ $key ] ) ) {
			return '';
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$raw = (string) wp_unslash( (string) $_GET[ $key ] );
		if ( $decode ) {
			$raw = rawurldecode( $raw );
		}
		return sanitize_text_field( $raw );
	}
}
