<?php
declare(strict_types=1);
if ( ! defined( 'ABSPATH' ) ) { exit; }
/**
 * reCAPTCHA v3 Ajax Handler.
 * @package WTE_Business_Card
 */
function wte_verify_recaptcha(): void {
	check_ajax_referer( 'wte_recaptcha_nonce', 'nonce' );
	$token  = sanitize_text_field( $_POST['token'] ?? '' );
	$secret = get_theme_mod( 'wte_recaptcha_secret_key', '' );
	$thresh = (float) get_theme_mod( 'wte_recaptcha_score_threshold', 0.5 );
	if ( empty( $secret ) || empty( $token ) ) {
		wp_send_json_error( [ 'message' => 'Missing token or secret.' ] );
	}
	$response = wp_remote_post( 'https://www.google.com/recaptcha/api/siteverify', [
		'body' => [ 'secret' => $secret, 'response' => $token ],
	] );
	if ( is_wp_error( $response ) ) {
		wp_send_json_error( [ 'message' => 'Verification failed.' ] );
	}
	$body  = json_decode( wp_remote_retrieve_body( $response ), true );
	$score = (float) ( $body['score'] ?? 0 );
	if ( ( $body['success'] ?? false ) && $score >= $thresh ) {
		wp_send_json_success( [ 'score' => $score ] );
	} else {
		wp_send_json_error( [ 'score' => $score ] );
	}
}
add_action( 'wp_ajax_nopriv_wte_verify_recaptcha', 'wte_verify_recaptcha' );
add_action( 'wp_ajax_wte_verify_recaptcha', 'wte_verify_recaptcha' );
