<?php
/**
 * Cloudfare Turnstile field
 *
 * @package EverestForms\Fields
 * @since   1.0.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * EVF_Field_Turnstile Class.
 */
class EVF_Field_Turnstile extends \EVF_Form_Fields {

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->name     = esc_html__( 'Turnstile', 'everest-forms' );
		$this->type     = 'turnstile';
		$this->icon     = 'evf-icon evf-icon-turnstile';
		$this->order    = 243;
		$this->class    = $this->get_turnstile_class();
		$this->group    = 'advanced';
		$this->settings = array(
			'basic-options'    => array(
				'field_options' => array(
					'label',
				),
			),
			'advanced-options' => array(
				'field_options' => array(
					'meta',
				),
			),
		);

		parent::__construct();
	}

	/**
	 * Get Turnstile class.
	 *
	 * @return string
	 */
	private function get_turnstile_class() {
		$site_key       = get_option( 'everest_forms_recaptcha_turnstile_site_key' );
		$secret_key     = get_option( 'everest_forms_recaptcha_turnstile_secret_key' );
		$recaptcha_type = get_option( 'everest_forms_recaptcha_type', 'v2' );
		return ( empty( $site_key ) || empty( $secret_key ) || 'turnstile' !== $recaptcha_type ) ? 'turnstile_empty_key_validate' : '';
	}

	/**
	 * Field preview inside the builder.
	 *
	 * @since 1.0.0
	 *
	 * @param array $field Field data and settings.
	 */
	public function field_preview( $field ) {
		$recaptcha_type    = get_option( 'everest_forms_recaptcha_type', '' );
		$turnstile_enabled = get_option( 'everest_forms_recaptcha_turnstile_enable', 'no' );

		if ( 'turnstile' !== $recaptcha_type || 'yes' !== $turnstile_enabled ) {
			return;
		}

		$site_key   = get_option( 'everest_forms_recaptcha_turnstile_site_key' );
		$secret_key = get_option( 'everest_forms_recaptcha_turnstile_secret_key' );

		if ( empty( $site_key ) || empty( $secret_key ) ) {
			return;
		}
		
		// Label.
		$this->field_preview_option( 'label', $field );

		// Default value.
		$default_value = isset( $field['default_value'] ) && ! empty( $field['default_value'] ) ? $field['default_value'] : '';

		$image_url = plugins_url( 'assets/images/captcha/turnstile.png', EVF_PLUGIN_FILE );
		echo '<img src="' . esc_url( $image_url ) . '" class="widefat" disabled />';
	}


	/**
	 * Field display on the form front-end.
	 *
	 * @since 1.0.0
	 *
	 * @param array $field Field Data.
	 * @param array $field_atts Field attributes.
	 * @param array $form_data All Form Data.
	 */
	public function field_display( $field, $field_atts, $form_data ) {
		$recaptcha_type    = get_option( 'everest_forms_recaptcha_type', '' );
		$turnstile_enabled = get_option( 'everest_forms_recaptcha_turnstile_enable', 'no' );

		if ( 'turnstile' !== $recaptcha_type || 'yes' !== $turnstile_enabled ) {
			return;
		}

		$site_key   = get_option( 'everest_forms_recaptcha_turnstile_site_key' );
		$secret_key = get_option( 'everest_forms_recaptcha_turnstile_secret_key' );

		if ( empty( $site_key ) || empty( $secret_key ) ) {
			return;
		}

		$form_id = isset( $form_data['id'] ) ? absint( $form_data['id'] ) : 0;
		$visible = ! empty( self::$parts[ $form_id ] ) ? 'style="display:none;"' : '';
		$data    = apply_filters(
			'everest_forms_frontend_recaptcha',
			array(
				'sitekey' => trim( sanitize_text_field( $site_key ) ),
			),
			$form_data
		);

		if ( $site_key && $secret_key ) {
			$theme = get_option( 'everest_forms_recaptcha_turnstile_theme' );
			$lang  = get_option( 'everest_forms_recaptcha_recaptcha_language', 'en-GB' );

			$recaptcha_api     = apply_filters( 'everest_forms_frontend_recaptcha_url', 'https://challenges.cloudflare.com/turnstile/v0/api.js?onload=EVFTurnstileLoad&render=explicit', 'turnstile', $form_id );
			$recaptcha_inline  = 'var EVFTurnstileLoad = function(){jQuery(".g-recaptcha").each(function(index, el){var recaptchaID =  turnstile.render(el,{theme:"' . $theme . '",language:"' . $lang . '",callback:function(){EVFRecaptchaCallback(el);}},true);jQuery(el).attr( "data-recaptcha-id", recaptchaID);});};';
			$recaptcha_inline .= 'var EVFRecaptchaCallback = function(el){jQuery(el).parent().find(".evf-recaptcha-hidden").val("1").trigger("change").valid();};';

			wp_enqueue_script(
				'evf-recaptcha',
				$recaptcha_api,
				array( 'jquery' ),
				'2.0.0',
				true
			);

			static $count = 1;
			if ( 1 === $count ) {
				wp_add_inline_script( 'evf-recaptcha', $recaptcha_inline );
				++$count;
			}

			echo '<div class="evf-recaptcha-container" style="display:' . ( ! empty( self::$parts[ $form_id ] ) ? 'none' : 'block' ) . '">';
			echo '<div ' . evf_html_attributes( '', array( 'g-recaptcha' ), $data ) . '></div>';
			echo '<input type="text" name="g-recaptcha-hidden" class="evf-recaptcha-hidden" style="position:absolute!important;clip:rect(0,0,0,0)!important;height:1px!important;width:1px!important;border:0!important;overflow:hidden!important;padding:0!important;margin:0!important;" required>';
			echo '</div>';
		}
	}
}
