<?php
/**
 * Recaptcha Helper.
 *
 * @package tripzzy
 */

namespace Tripzzy\Core\Helpers;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

if ( ! class_exists( 'Tripzzy\Core\Helpers\Recaptcha' ) ) {
	/**
	 * Recaptcha Helper Class.
	 *
	 * @since 1.4.0
	 */
	class Recaptcha {

		/**
		 * Check if reCAPTCHA is configured with both site key and secret key.
		 *
		 * @since 1.4.0
		 *
		 * @return bool True if both keys are configured, false otherwise.
		 */
		public static function is_configured() {
			$settings   = Settings::get();
			$site_key   = $settings['recaptcha_site_key'] ?? '';
			$secret_key = $settings['recaptcha_secret_key'] ?? '';

			return ! empty( $site_key ) && ! empty( $secret_key );
		}

		/**
		 * Verify reCAPTCHA token with Google.
		 *
		 * @param string $token The reCAPTCHA token received from the frontend.
		 * @since 1.4.0
		 * @return bool True if verification is successful, false otherwise.
		 */
		public static function verify_recaptcha_token( $token ) {
			$settings   = Settings::get();
			$secret_key = $settings['recaptcha_secret_key'] ?? '';

			if ( empty( $secret_key ) ) {
				return false;
			}

			if ( empty( $token ) ) {
				return false;
			}
			$remote_ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ?? '' ) );
			$response  = wp_remote_post(
				'https://www.google.com/recaptcha/api/siteverify',
				array(
					'body' => array(
						'secret'   => $secret_key,
						'response' => $token,
						'remoteip' => $remote_ip,
					),
				)
			);

			if ( is_wp_error( $response ) ) {
				return false;
			}

			$body = wp_remote_retrieve_body( $response );
			$data = json_decode( $body, true );

			if ( ! $data || ! isset( $data['success'] ) || true !== $data['success'] ) {
				return false;
			}

			// You can also check $data['score'] for reCAPTCHA v3 if needed.
			// For example: if ( $data['score'] < 0.5 ) return false;.
			return true;
		}
	}
}
