<?php
namespace SabaiApps\Directories\Component\Captcha\Api;

use SabaiApps\Directories\Component\Form\Form;

class ReCaptcha3Api extends AbstractReCaptchaApi {

	protected function _captchaApiInfo() {
		return array(
			'label'            => __( 'reCAPTCHA v3', 'directories-pro' ),
			'default_settings' => array(
				'sitekey' => null,
				'secret'  => null,
				'score'   => 0.5,
			),
			'weight'           => 1,
		);
	}

	public function captchaApiSettingsForm( array $settings, array $parents ) {
		return array(
			'sitekey' => array(
				'#title'         => __( 'Site key', 'directories-pro' ),
				'#type'          => 'textfield',
				'#default_value' => $settings['sitekey'],
				'#horizontal'    => true,
			),
			'secret'  => array(
				'#title'         => __( 'Secret key', 'directories-pro' ),
				'#type'          => 'textfield',
				'#default_value' => $settings['secret'],
				'#horizontal'    => true,
			),
			'score'   => array(
				'#title'         => __( 'reCAPTCHA score threshold', 'directories-pro' ),
				'#type'          => 'slider',
				'#min_value'     => 0,
				'#max_value'     => 1,
				'#step'          => 0.1,
				'#default_value' => $settings['score'],
				'#horizontal'    => true,
				'#numeric'       => true,
			),
		);
	}

	public function captchaApiForm( array $settings, $name, $trigger = null ) {
		if ( ! self::$_jsLoaded ) {
			$js = sprintf(
				'var drtsReCaptchaCallback = function() {
    jQuery(".drts-captcha-recaptcha-form-field").each(function(i) {
        var $this = jQuery(this),
            fetchToken = function () {
            grecaptcha.execute("%s", {action: $this.data("action")}).then(function(token) {
                $this.val(token);
                console.log("reCAPTCHA token updated.");
            });
        };
        fetchToken();
        setInterval(function () { fetchToken(); }, 2 * 60 * 1000);
    });
};',
				$this->_application->H( $settings['sitekey'] )
			);
			$this->_application->getPlatform()->addHead(
				'<script type="text/javascript">' . $js . '</script>
<script type="text/javascript" src="https://www.google.com/recaptcha/api.js?onload=drtsReCaptchaCallback&render=' . $this->_application->H( $settings['sitekey'] ) . '" async defer></script>',
				'captcha_recaptcha'
			);
			self::$_jsLoaded = true;
		}

		$id     = 'drts-captcha-recaptcha-form-field-' . $name;
		$action = ! isset( $name ) || is_numeric( $action = preg_replace( '%[^A-Za-z0-9_/]%', '', $name ) ) ? 'default' : $action;
		return array(
			'#type'   => 'markup',
			'#submit' => array(
				9 => array( array( array( $this, '_validateCaptchaV3' ), array( $settings['secret'], $trigger, $id, $action, $settings['score'] ) ) ),
			),
			'#markup' => '<input type="hidden" value="" class="drts-captcha-recaptcha-form-field" name="' . $id . '" data-trigger="' . $this->_application->H( $trigger ) . '"'
				. ' data-action="' . $this->_application->H( $action ) . '"/>',
		);
	}

	public function _validateCaptchaV3( Form $form, $secret, $trigger, $id, $action, $score ) {
		$this->_validateCaptcha( $form, $secret, $trigger, $id, null, $action, $score );
	}
}
