<?php
require __DIR__ . '/../../vendor/autoload.php';

use Google\Cloud\RecaptchaEnterprise\V1\Client\RecaptchaEnterpriseServiceClient;
use Google\Cloud\RecaptchaEnterprise\V1\Event;
use Google\Cloud\RecaptchaEnterprise\V1\Assessment;
use Google\Cloud\RecaptchaEnterprise\V1\CreateAssessmentRequest;
use Google\Cloud\RecaptchaEnterprise\V1\TokenProperties\InvalidReason;
 
class RecaptchaResponse
{
    public $success = true;
    public $message = '';
}

class RecaptchaEnterprise
{
    /**
     * Crie uma avaliação para analisar o risco de uma ação da interface.
     * @param string $token O token gerado obtido do cliente.
     * @param string $action Nome da ação correspondente ao token.
     */
    public function createAssessment(string $token, string $action): RecaptchaResponse
    {
        try {
            $recaptchaResponse = new RecaptchaResponse();
            $client = new RecaptchaEnterpriseServiceClient(['credentials' => APPLICATION_PATH . '/config/captchas-489816-e639e8b503a1.json']);
            $projectName = $client->projectName(RECAPTCHA_PROJECT_ID);
            $event = (new Event())->setSiteKey(RECAPTCHA_SITE_KEY)->setToken($token);
            $assessment = (new Assessment())->setEvent($event);
            $request = (new CreateAssessmentRequest())->setParent($projectName)->setAssessment($assessment);
            $response = $client->createAssessment($request);
        
            // Verifique se o token é válido.
            if ($response->getTokenProperties()->getValid() == false) {
                $error = 'The CreateAssessment() call failed because the token was invalid for the following reason: ';
                $error .= InvalidReason::name($response->getTokenProperties()->getInvalidReason());
                throw new Exception($error);
            }
        
            // Verifique se a ação esperada foi executada.
            if ($response->getTokenProperties()->getAction() != $action) {
                $error = 'The action attribute in your reCAPTCHA tag does not match the action you are expecting to score.';
                throw new Exception($error);
            }

        } catch (exception $e) {
            $recaptchaResponse->success = false;
            $recaptchaResponse->message = $e->getMessage();
            $this->enviarEmailErro($recaptchaResponse->message);
        }

        if (!empty($client)) {
            $client->close();
        }

        return $recaptchaResponse;
    }

    /**
     * Envia um e-mail informado o erro que aconteceu ao tentar realizar o ReCaptcha
     * @param string $mensagem
     */
    private function enviarEmailErro(string $mensagem): void
    {
        $body  = "Foi detectado um erro no sistema. Informações sobre o ocorrido:";
        $body .= "<br><br><strong>Erro(s) encontrado(s):</strong>";
        $body .= $mensagem;

        $mail = new Agro_Mail();
        $mail->inicioTextoPadrao(false);
        $mail->setBodyHtml($body);
        $mail->addTo('tonismar.bernardo@agrobrasilseguros.com.br');
        $mail->setSubject('AgroNet 2.0 - ERRO AO VALIDAR RECAPTCHA');
        $mail->send();
    }
}
