<?php



use ReCaptcha\ReCaptcha;

/**
 * Hidden field for Google ReCAPTCHA protection
 * @docs https://developers.google.com/recaptcha/docs/display
 * @since 2.5.0
 *
 * @extends Diller_Base_Field
 *
 */
class Diller_Recaptcha_Field extends Diller_Base_Field {

    private $recaptcha_site_key = '';
    private $recaptcha_site_secret = '';
	private $recaptcha_version = 'v3';

    public function __construct() {
		$args = func_get_args();
	    call_user_func_array( array( Diller_Base_Field::class, '__construct' ), $args );

	   $this->recaptcha_site_key = DillerLoyalty()->get_store()->get_google_recaptcha_site_key();
	   $this->recaptcha_site_secret = DillerLoyalty()->get_store()->get_google_recaptcha_site_secret();
	   $this->recaptcha_version = DillerLoyalty()->get_store()->get_google_recaptcha_version();
	}

	/**
	 * Print out field HTML - intentionally empty as it doesn't apply here.
	 */
	public function get_title() {}

	/**
	 * Print out field HTML.
	 */
	public function html() {
		?>

		<?php if($this->recaptcha_version == 'v2'): ?>
            <input <?php $this->id_attr(); ?> type="hidden" <?php $this->name_attr(); ?> value="" />
			<div class="diller-recaptcha-wrapper"></div>
		<?php endif; ?>

		<?php if($this->recaptcha_version == 'v3'): ?>
            <input <?php $this->id_attr(); ?> type="hidden" <?php $this->name_attr(); ?> value="" />
		<?php endif; ?>

		<?php
	}

	/**
	 * Print out a field.
	 */
	public function display() {
		$this->html();
	}

	public function scripts() {
		$url = "https://www.google.com/recaptcha/api.js";

		if($this->recaptcha_version == 'v3'){
			$url .= '?render=' . esc_attr($this->recaptcha_site_key) . '&onload=dillerRecaptchaOnLoadCallback';
		}

		if($this->recaptcha_version == 'v2'){
			$url .= '?hl=' . esc_attr(get_locale()) . '&render=explicit&onload=dillerRecaptchaOnLoadCallback';
		}

        return array(
            "google-recaptcha" => array(
                "src" => "$url",
                "location" => "header",
            ),
        );
    }

    public function inline_scripts() {
		$script = '
			dillerRecaptchaOnLoadCallback = function() {
                const recaptchaResponseField = document.getElementById("' . esc_attr( $this->get_id() ) . '");
        ';

	    if($this->recaptcha_version == 'v3'){
		    $script .= '
			    grecaptcha.ready(function() {
	                grecaptcha.execute("' . esc_attr($this->recaptcha_site_key) .'", { action: "homepage" }).then(function(token) {
	                    if(recaptchaResponseField){
	                        recaptchaResponseField.value = token;
	                        console.log("Google reCAPTCHA v3 loaded");
	                    }
	                });
	            });
            ';
	    }

	    if($this->recaptcha_version == 'v2'){
		    $script .= '
                const recaptcha = document.getElementsByClassName("diller-recaptcha-wrapper");
		        if(recaptcha.length > 0){
                    grecaptcha.render(recaptcha[0], {
				        sitekey: "' . esc_attr($this->recaptcha_site_key) .'",
				        callback: function(token) {
                            if(recaptchaResponseField){
                                recaptchaResponseField.value = token;
                                console.log("Google reCAPTCHA v2 loaded");
                            }
                        },
                        "expired-callback": function(token) {
                            if(recaptchaResponseField){
                                recaptchaResponseField.value = "";
                                console.log("Google reCAPTCHA v2: response expired");
                            }
                        }
				    });
                    console.log("Google reCAPTCHA v2 rendered");
                }
            ';
	    }

	    return $script . '};';
    }

	/**
	 * Validate recaptcha response for the field
	 *
	 * @param array $value Value to validate.
	 */
	public function validate($value) {
        $result = parent::validate($value);
		if (is_wp_error($result)) {
			return $result;
		}
        return Diller_Loyalty_Helpers::validate_recaptcha_response($value);
	}
}
