<?php
/**
 * ハニーポット
 *
 * @package CF7MasterPro\Security
 */

namespace CF7MasterPro\Security;

defined( 'ABSPATH' ) || exit;

/**
 * 隠しフィールドによるスパム対策
 */
class Honeypot {

	/**
	 * 登録
	 */
	public function register() {
		add_filter( 'wpcf7_form_elements', array( $this, 'inject_honeypot' ) );
		add_filter( 'wpcf7_validate', array( $this, 'check_honeypot' ), 1, 2 );
	}

	/**
	 * 隠しフィールド挿入
	 *
	 * @param string $form HTML.
	 * @return string
	 */
	public function inject_honeypot( $form ) {
		$field = '<div class="cf7mp-honeypot" style="position:absolute;left:-9999px;" aria-hidden="true">';
		$field .= '<input type="text" name="cf7mp_hp_field" value="" tabindex="-1" autocomplete="off">';
		$field .= '</div>';
		return $form . $field;
	}

	/**
	 * 検証
	 *
	 * @param object $result 結果.
	 * @param array  $tags タグ.
	 * @return object
	 */
	public function check_honeypot( $result, $tags ) {
		if ( ! empty( $_POST['cf7mp_hp_field'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Honeypot check runs inside the Contact Form 7 validation flow, which provides its own nonce.
			$result->invalidate( '', __( 'Spam detection', 'frontierline-forms' ) );
		}
		return $result;
	}
}
