<?php

namespace Ignite\Core\Validators;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Http\Request;
use ReCaptcha\ReCaptcha;

class RecaptchaV2RobotRule implements Rule
{
    private Request $request;

    /**
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if (empty($this->request->input('g-recaptcha-response'))) {
            return false;
        }

        $recaptcha = new ReCaptcha(config('services.recaptcha.secret'));
        $hostname = str_replace(['https://', 'http://', '/'], '', config('app.url'));

        $resp = $recaptcha
            ->setExpectedHostname($hostname)
            ->verify(request()->input('g-recaptcha-response'), request()->ip());

        if ($resp->isSuccess()) {
            return true;
        }

        $errors = $resp->getErrorCodes();
        $data = $this->request->all();
        // obscure the ssn first
        $data['ssn'] = $data['ssn'] ?? '';
        $data['ssn'] = !empty($data['ssn']) ? str_repeat('*', strlen($data['ssn'])) : '';
        logger()->debug('Recaptcha failed', [$errors, $data]);

        return false;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Please remember to prove you are human!';
    }
}
