<?php
/**
 * This class should block bots that are part of the blocked IPs list.
 *
 * @author     FutrX
 * @year       2023
 * @package    futrx.com
 * @subpackage NoMoreBots\Hooks
 */

namespace NoMoreBots\Hooks;

use NoMoreBots\Utils\HP\HP as HPUtils;
use NoMoreBots\Utils\Modules;

class Access {
	public function __construct() {
		add_action( 'init', array( $this, 'block_access_for_blocked_ips' ), 0 );
		add_action( 'init', array( $this, 'check_for_honeypot_in_post_submission' ), 999 );

		// check for successful login, registration, and password reset
		add_action( 'wp_login', array( $this, 'checkHPAfterWPForms' ), 999 );
		add_action( 'user_register', array( $this, 'checkHPAfterWPForms' ), 999 );
		add_action( 'validate_password_reset', array( $this, 'checkHPAfterWPForms' ), 999 );
	}

	/**
	 * This will check for any honeypot fields that are filled in the $_POST array.
	 *
	 * This should run against each server submission
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function check_for_honeypot_in_post_submission(): void {
		// Exit early if the HP module is not active.
		if ( ! Modules::isActive( 'hp' ) ) {
			return;
		}
		// Validate the HP field against all requests.
		HPUtils::validateHPField();
	}


	/**
	 * This will check if the current IP is part of the blocked IPs list.
	 * If it is, it will show a blank page to the user.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function block_access_for_blocked_ips(): void {
		// Exit early if the HP module is not active.
		if ( ! Modules::isActive( 'hp' ) ) {
			return;
		}
		// Get the list of blocked IPs from the WordPress options table
		$blocked_ips = get_option( NOMOREBOTS_HONEYPOT_FIELD_PREFIX . NOMOREBOTS_BLOCKED_IPS_META_KEY, array() );
		if ( ! is_array( $blocked_ips ) ) {
			$blocked_ips = array();
		}
		$current_ip = sanitize_text_field( $_SERVER['REMOTE_ADDR'] );

		// Check if the current IP is part of the blocked IPs list
		foreach ( $blocked_ips as $ip => $time ) {
			if ( ! $ip === $current_ip ) {
				continue;
			}
			$allowed_time = get_option( NOMOREBOTS_HONEYPOT_FIELD_PREFIX . NOMOREBOTS_BLOCKED_DURATION_META_KEY );
			// Check if now - the time the IP was blocked is greater than the allowed time
			if ( time() - (int) $time > $allowed_time ) {
				// Let the user access the site again
				return;
			} else {
				// Return status error.
				wp_die( esc_html( NOMOREBOTS_ERROR_MESSAGE ), '', array( 'response' => 403 ) );
			}
		}
	}

	/**
	 * This will check for any honeypot fields that are filled in the $_POST array,
	 * after a successful login, register or password reset.
	 *
	 * @return void
	 */
	public function checkHPAfterWPForms(): void {
		// Exit early if the HP module is not active.
		if ( ! Modules::isActive( 'hp' ) ) {
			return;
		}
		HPUtils::validateHPField();
	}
}
