<?php

namespace WeeConnectPay\Integrations;


/**
 * WeeConnectPay's own Google reCAPTCHA **v3** fraud check (score-based, invisible,
 * `grecaptcha.execute()`), configured in the plugin settings and stored locally in
 * `wp_options` via {@see IntegrationSettings}.
 *
 * This is DISTINCT from Clover's hosted-iframe reCAPTCHA, which is **v2**, toggled
 * at the Clover merchant/app level, and carried in `ecomm_payment_configs`. The two
 * are unrelated: enabling Clover's v2 does not enable this v3, and this class never
 * reads Clover config. Do not conflate them in support or docs.
 */
class GoogleRecaptcha {

	public static function isEnabledAndReady(): bool {
		$integrationSettings = new IntegrationSettings();

		// Check that it is enabled
		$isEnabled = $integrationSettings->getGoogleRecaptchaOrDefault();
		if ( ! $isEnabled ) {
			return false;
		}

		// Check for site key
		$siteKey = $integrationSettings->getGoogleRecaptchaSiteKeyOrDefault();
		if ( ! $siteKey ) {
			LogService::error('Google Recaptcha Site Key is not set.');
			return false;
		}

		// Check for secret key
		$secretKey = $integrationSettings->getGoogleRecaptchaSecretKeyOrDefault();
		if ( ! $secretKey ) {
			LogService::error('Google Recaptcha Secret Key is not set.');
			return false;
		}

		// Check for minimum human score key. Validate numerically within reCAPTCHA's
		// 0..1 score range rather than a truthiness check — a legitimately-saved
		// '0' is valid (and a plain `! $score` would wrongly reject it).
		$minimumHumanScore = $integrationSettings->getGoogleRecaptchaMinimumHumanScoreThresholdOrDefault();
		if ( ! is_numeric( $minimumHumanScore ) || (float) $minimumHumanScore < 0 || (float) $minimumHumanScore > 1 ) {
			LogService::error( 'Google Recaptcha Minimum Human Score Threshold is not set or out of range (0-1): ' . var_export( $minimumHumanScore, true ) );
			return false;
		}

		return true;
	}

	/**
	 * Get the Google reCAPTCHA SDK source URL
	 *
	 * @return string
	 */
	public static function getSdkSrc(): string {
		$integrationSetting = new IntegrationSettings();
		$recaptchaSiteKey = $integrationSetting->getGoogleRecaptchaSiteKeyOrDefault();

		return "https://www.google.com/recaptcha/api.js?render=$recaptchaSiteKey";
	}

	/**
	 * Check if a recaptcha token contains error JSON
	 * 
	 * @param string $recaptchaToken
	 * @since 3.6.0
	 * @return bool
	 */
	public static function tokenContainsErrorJson(string $recaptchaToken): bool {
		$cleanedRecaptchaToken = stripslashes($recaptchaToken);
		$exceptionCheck = json_decode( $cleanedRecaptchaToken );

		if ( isset( $exceptionCheck->exception ) ) {
			LogService::error("Google Recaptcha token contains error JSON: $recaptchaToken");
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Extract error message from a recaptcha token
	 * 
	 * @param string $recaptchaToken
	 * @since 3.6.0
	 * @return string
	 */
	public static function extractErrorMessageFromToken(string $recaptchaToken): string {
		$cleanedRecaptchaToken = stripslashes($recaptchaToken);
		$exceptionCheck = json_decode( $cleanedRecaptchaToken );

		return $exceptionCheck->exception ?? '';
	}
}
