<?php
// Modern ReCaptcha Validator for WordPress (v2/v3 compatible)

if (!class_exists('ReCaptchaResponse')) {
    class ReCaptchaResponse {
        public $success = false;
        public $errorCodes = [];
    }
}

if (!class_exists('ReCaptcha')) {
    class ReCaptcha {
        private $secretKey;

        public function __construct($secret) {
            if (empty($secret)) {
                die("To use reCAPTCHA you must provide a secret key.");
            }
            $this->secretKey = $secret;
        }

        public function verifyResponse($remoteIp, $responseToken) {
            $recaptchaResponse = new ReCaptchaResponse();

            if (empty($responseToken)) {
                $recaptchaResponse->errorCodes[] = 'missing-input';
                return $recaptchaResponse;
            }

            $apiResponse = wp_remote_post('https://www.google.com/recaptcha/api/siteverify', [
                'timeout' => 10,
                'body' => [
                    'secret'   => $this->secretKey,
                    'response' => $responseToken,
                    'remoteip' => $remoteIp,
                ]
            ]);

            if (is_wp_error($apiResponse)) {
                $recaptchaResponse->errorCodes[] = 'connection-failed: ' . $apiResponse->get_error_message();
                return $recaptchaResponse;
            }

            $body = json_decode(wp_remote_retrieve_body($apiResponse), true);

            if (isset($body['success']) && $body['success'] === true) {
                $recaptchaResponse->success = true;
            } else {
                $recaptchaResponse->errorCodes = $body['error-codes'] ?? ['invalid-response'];
            }

            return $recaptchaResponse;
        }
    }
}