<?php

namespace App\Rules;

use App\Facades\Flash;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Http;

class RecaptchaValidationRule implements ValidationRule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if ($value && config('extension.recaptcha.is_enabled')) {
            $response = Http::post('https://www.google.com/recaptcha/api/siteverify?secret='.config('extension.recaptcha.secret_key').'&response='.$value);
            if (! $response->json()['success']) {
                Flash::error(__('Captcha verification failed'));
                $fail(__('Captcha verification failed'));
            }
        }
    }
}
