<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use App\Models\Setting;

class RecaptchaService
{
    /**
     * Verify the reCAPTCHA token submitted from a form.
     * Returns true if valid OR if reCAPTCHA is disabled.
     */
    public static function verify(?string $token, ?string $userIp = null): bool
    {
        // If reCAPTCHA is disabled in settings, skip verification entirely
        if (!recaptcha_enabled()) {
            return true;
        }

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

        $secret = Setting::get('recaptcha_secret_key');
        if (empty($secret)) {
            return false;
        }

        try {
            $response = Http::timeout(8)->asForm()->post('https://www.google.com/recaptcha/api/siteverify', [
                'secret'   => $secret,
                'response' => $token,
                'remoteip' => $userIp ?? request()->ip(),
            ]);

            $body = $response->json();
            return is_array($body) && !empty($body['success']);
        } catch (\Throwable $e) {
            return false;
        }
    }

    public static function siteKey(): ?string
    {
        return Setting::get('recaptcha_site_key');
    }
}
