<?php
/**
 * Shared form-context guards for captcha stand-down decisions.
 *
 * Skip rules must not be forgeable from an unauthenticated POST. A client can
 * add `pmpro_login_form_used` or `woocommerce-register-nonce` to any request;
 * those fields only mean "a replacement verifier owns this submit" when the
 * owning plugin is loaded and the request is actually that form.
 *
 * @package WP_PowerSuite\Captcha\Shared
 */

namespace WP_PowerSuite\Captcha\Shared;

final class CaptchaFormContext {

	/**
	 * PMPro frontend login / lost-password posts this flag. Require the plugin
	 * so a forged field cannot skip core captcha when the replacement check
	 * was never registered.
	 */
	public static function isPmproFrontendAuthPost(): bool {
		if ( ! defined( 'PMPRO_VERSION' ) ) {
			return false;
		}

		return ! empty( $_POST['pmpro_login_form_used'] );
	}

	/**
	 * Core `/wp-login.php?action=register` — never treat this as Woo My Account.
	 */
	public static function isWpLoginRegisterScreen(): bool {
		if ( ! self::isRequestPathWpLogin() ) {
			return false;
		}

		$action = isset( $_REQUEST['action'] ) ? sanitize_key( wp_unslash( (string) $_REQUEST['action'] ) ) : '';

		return $action === 'register';
	}

	public static function isRequestPathWpLogin(): bool {
		if ( ! function_exists( 'wp_login_url' ) ) {
			return false;
		}

		$login_path = wp_parse_url( wp_login_url(), PHP_URL_PATH );
		$req_uri    = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( (string) $_SERVER['REQUEST_URI'] ) : '';
		$req_path   = wp_parse_url( $req_uri, PHP_URL_PATH );
		if ( ! is_string( $login_path ) || $login_path === '' || ! is_string( $req_path ) || $req_path === '' ) {
			return false;
		}

		return untrailingslashit( $login_path ) === untrailingslashit( $req_path );
	}

	/**
	 * Real Woo My Account registration: valid Woo nonce, and not the core
	 * register screen. Presence of `woocommerce-register-nonce` is not enough.
	 */
	public static function isWooMyAccountRegistrationPost(): bool {
		if ( self::isWpLoginRegisterScreen() ) {
			return false;
		}

		if ( ! isset( $_POST['woocommerce-register-nonce'] ) ) {
			return false;
		}

		$nonce = sanitize_text_field( wp_unslash( (string) $_POST['woocommerce-register-nonce'] ) );
		if ( $nonce === '' ) {
			return false;
		}

		return wp_verify_nonce( $nonce, 'woocommerce-register' ) !== false;
	}
}
