<?php
/**
 * This class should handle all hooks (actions or filters) related to the Forms Submissions on the website.
 *
 * @author     FutrX
 * @year       2023
 * @package    futrx.com
 * @subpackage NoMoreBots\Hooks
 */

namespace NoMoreBots\Hooks;

use NoMoreBots\Hooks\Forms\WP;

class Forms {
	public function __construct() {
		add_action( 'wp_footer', array( $this, 'addHoneyPotFieldsToFormsJS' ) );

		// Hook to WP forms
		WP::instance();

		// Check if OTP is active before injecting the OTP field into the forms.
		if ( get_option( NOMOREBOTS_OTP_FIELD_PREFIX . '_activate' ) ) {
			add_action(
				'wp_enqueue_scripts',
				function () {
					wp_enqueue_style(
						'nmb-otp-style',
						NOMOREBOTS_PLUGINURL . 'assets/css/otp.css',
						array(),
						NOMOREBOTS_PLUGINVERSION
					);
					add_action( 'wp_footer', array( $this, 'addOTPFieldToFormsJS' ) );
				}
			);
		}
	}

	/**
	 * This will be loaded on the pages that are selected with `nmb_hp_pages_to_filter` with the Settings Page.
	 * This will add the honeypot fields to the forms on the selected pages using Javascript.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function addHoneyPotFieldsToFormsJS(): void {
		// Check if the current page is part of the pages that are selected with to have the special fields injected into it.
		$current_page_id = get_the_ID();
		if ( ! self::shouldInjectPage( $current_page_id ) ) {
			return;
		}
		// Add nonce field to the form
		wp_nonce_field( NOMOREBOTS_HONEYPOT_FIELD_PREFIX . '_nonce', NOMOREBOTS_HONEYPOT_FIELD_PREFIX . '_nonce' );

		// Add CSS in their own Style tag.
		$field_class = NOMOREBOTS_HONEYPOT_FIELD_PREFIX;
		?>
		<style>
			<?php echo esc_html( ".{$field_class} { display: none !important; }" ); ?>
		</style>
		<?php

		// Pick random field type from NOMOREBOTS_INPUT_TYPES
		$random_field_type = array_rand( NOMOREBOTS_INPUT_TYPES );
		$random_field      = NOMOREBOTS_INPUT_TYPES[ $random_field_type ];
		?>
		<script>
			const fieldName = '<?php echo esc_attr( NOMOREBOTS_HONEYPOT_FIELD_PREFIX ); ?>';
			const fieldClass = '<?php echo esc_attr( $field_class ); ?>';
			const fieldType = '<?php echo esc_attr( $random_field['type'] ); ?>';
			const fieldLabel = '<?php echo esc_attr( $random_field['label'] ); ?>';
			const fieldPlaceholder = '<?php echo esc_attr( $random_field['placeholder'] ); ?>';

			const nmbHPForms = document.querySelectorAll('form');
			nmbHPForms.forEach((form) => {
				const inputId = fieldName + '-' + Math.floor(Math.random() * 1000);
				const input = document.createElement('input');
				input.type = fieldType;
				input.placholder = fieldPlaceholder;
				input.name = inputId;
				input.setAttribute('class', fieldClass);
				input.value = "";
				input.id = inputId;
				input.setAttribute('aria-label', fieldLabel);
				input.setAttribute('autocomplete', 'off');
				const firstInput = form.querySelector('input');
				firstInput.insertAdjacentElement('afterend', input);
			});
		</script>
		<?php
	}

	public function addOTPFieldToFormsJS(): void {
		// Check if the current page is part of the pages that are selected with to have the special fields injected into it.
		$current_page_id = get_the_ID();
		if ( ! self::shouldInjectPage( $current_page_id, 'otp' ) ) {
			return;
		}
		// Add nonce field to the form
		wp_nonce_field( NOMOREBOTS_OTP_FIELD_PREFIX . '_nonce', NOMOREBOTS_OTP_FIELD_PREFIX . '_nonce' );
		?>
		<script id="<?php echo esc_attr( NOMOREBOTS_PLUGINTEXTDOMAIN ); ?>"
				src="<?php echo esc_attr( NOMOREBOTS_PLUGINURL . 'assets/js/OTP.js' ); ?>"
				data-nonce="<?php echo esc_attr( wp_create_nonce( NOMOREBOTS_OTP_FIELD_PREFIX . '_nonce' ) ); ?>"
				data-rest-url="<?php echo esc_attr( esc_url( rest_url() ) ); ?>"
				data-page-id="<?php echo esc_attr( $current_page_id ); ?>"></script>

		<?php
	}


	/**
	 * Helper function to return True/False if the current page id is part of the pages that are selected with to have the special fields injected into it.
	 *
	 * @param int $page_id
	 * @param string $type
	 *
	 * @return bool
	 * @since 1.0.0
	 */
	public static function shouldInjectPage( int $page_id, string $type = 'hp' ): bool {
		switch ( $type ) {
			case 'hp':
				$pages_to_filter = get_option( NOMOREBOTS_HONEYPOT_FIELD_PREFIX . NOMOREBOTS_PAGES_TO_FILTER_META_KEY );
				break;
			case 'otp':
				$pages_to_filter = get_option( NOMOREBOTS_OTP_FIELD_PREFIX . NOMOREBOTS_PAGES_TO_FILTER_META_KEY );
				break;
		}
		if ( empty( $pages_to_filter ) || ! is_array( $pages_to_filter ) ) {
			return false;
		}
		$page_id = (string) $page_id;

		return in_array( $page_id, $pages_to_filter, true );
	}
}
