<?php
/**
 * Detects WordPress and third-party login / credential requests.
 *
 * @package WP_PowerSuite\Auth
 * @since 1.2.0
 */

namespace WP_PowerSuite\Auth;

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

/**
 * Shared login-request detection for credential enforcement modules.
 */
final class LoginRequestDetector {

	/**
	 * Whether the current POST carries login credentials.
	 */
	public static function isCredentialPostRequest(): bool {
		if ( strtoupper( (string) ( $_SERVER['REQUEST_METHOD'] ?? '' ) ) !== 'POST' ) {
			return false;
		}

		if ( isset( $_POST['log'], $_POST['pwd'] ) ) {
			return true;
		}

		if ( isset( $_POST['woocommerce-login-nonce'], $_POST['username'], $_POST['password'] ) ) {
			return true;
		}

		return (bool) apply_filters( 'wp_powersuite_is_credential_login_request', false )
			|| (bool) apply_filters( 'wp_powersuite_limit_login_count_failed_login_body', false );
	}

	/**
	 * Whether the current AJAX request is a credential login attempt.
	 */
	public static function isCredentialAjaxRequest(): bool {
		if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) {
			return false;
		}

		$action = isset( $_REQUEST['action'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['action'] ) ) : '';
		if ( $action === 'wpps_2fa_login' ) {
			return true;
		}

		return (bool) apply_filters( 'wp_powersuite_is_credential_login_request', false );
	}

	/**
	 * Whether login authentication hooks should register during module bootstrap.
	 */
	public static function shouldRegisterAuthHooksImmediately(): bool {
		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
			return true;
		}

		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
			return true;
		}

		if ( function_exists( 'is_login' ) && is_login() ) {
			return true;
		}

		if ( apply_filters( 'wp_powersuite_is_custom_login_url_request', false ) ) {
			return true;
		}

		if ( self::isCredentialPostRequest() ) {
			return true;
		}

		return self::isCredentialAjaxRequest();
	}

	/**
	 * Whether the current request is the main login form (not register, lost password, 2FA, etc.).
	 */
	public static function isMainLoginForm(): bool {
		$action = isset( $_REQUEST['action'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['action'] ) ) : '';
		if ( $action === 'wpps_2fa' ) {
			return false;
		}

		return $action === '' || $action === 'login';
	}
}
