<?php
/**
 * This handles all functionality related to remote requests.
 *
 *
 * @author     FutrX
 * @year       2023
 * @package    NoMoreBots
 * @subpackage NoreMoreBotsModules\HP
 */

namespace NoMoreBots\Modules\Remote;


class Controller {

	public function __construct() {
		foreach ( Register::$loginForms as $form ) {
			// Add nonce per each predefined form.
			add_action( "{$form}_form", array( $this, 'addNonce' ) );

			// Validates the requests incoming to the predefined forms.
			add_action( "login_form_{$form}", array( $this, 'validateRequest' ) );
		}
	}


	/**
	 * Creates a nonce field that will be used to validate the request.
	 *
	 * @return void
	 */
	public static function addNonce() {
		wp_nonce_field( 'nmb_nonce', 'nmb_nonce' );
	}

	/**
	 * This validates the incoming request if it is valid, or it deserves some punishment!
	 *
	 * @return void
	 */
	public static function validateRequest() {
		// Check if the request is a POST request.
		$http_post = ( 'POST' === $_SERVER['REQUEST_METHOD'] );
		if ( $http_post ) {
			// Check if the request has _wp_http_referer
			if ( ! isset( $_REQUEST['_wp_http_referer'] ) ) {
				// if not, then it is a bot.
				self::punish();
			}

			// Check if the nonce does not exist or invalid.
			if ( ! isset( $_REQUEST['nmb_nonce'] ) || ! wp_verify_nonce( $_REQUEST['nmb_nonce'], 'nmb_nonce' ) ) {
				// if not, then it is a bot.
				self::punish();
			}
		}
	}

	/**
	 * Punishes the bot by preventing their access for now.
	 *
	 * // TODO block them!
	 *
	 * @return void
	 */
	public static function punish() {
		wp_die( esc_html( NOMOREBOTS_ERROR_MESSAGE ), '', array( 'response' => 403 ) );
	}
}
