<?php
/**
 * @author     FutrX
 * @year       2023
 * @package    NoMoreBots
 * @subpackage NoMoreBots\Utils\HP
 */

namespace NoMoreBots\Utils\HP;

class HP {

	/**
	 * Validates the incoming Honeypot field.
	 *
	 * @return void
	 */
	public static function validateHPField(): void {
		if ( empty( $_REQUEST ) ) {
			return;
		}

		// Loop through each form field to check for filled honeypot fields using NOMOREBOTS_HONEYPOT_FIELD_PREFIX
		foreach ( $_POST as $key => $value ) {
			if ( ! str_contains( $key, NOMOREBOTS_HONEYPOT_FIELD_PREFIX ) ) {
				continue;
			}
			if ( empty( $value ) ) {
				continue;
			}
			// If the honeypot field is filled, add the IP to the blocked IPs list
			$remote_address = sanitize_text_field( $_SERVER['REMOTE_ADDR'] );

			// 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 ( empty( $blocked_ips ) || ! is_array( $blocked_ips ) ) {
				$blocked_ips = array();
			}

			$blocked_ips[ $remote_address ] = time();
			// Update the blocked IPs list in the WordPress options table
			update_option( NOMOREBOTS_HONEYPOT_FIELD_PREFIX . NOMOREBOTS_BLOCKED_IPS_META_KEY, $blocked_ips );
			// Return status error.
			wp_die( esc_html( NOMOREBOTS_ERROR_MESSAGE ), '', array( 'response' => 403 ) );
		}
	}
}
