<?php

/*
 * This file is part of the VitiCore 2.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Utils;

use CpCreation\VitiCore\Contact\Repository\ContactRepository;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\NoResultException;

class ReCaptcha
{
    private string $keyPrivate;

    /**
     * @throws NoResultException
     * @throws NonUniqueResultException
     */
    public function __construct(ContactRepository $repository)
    {
        $this->keyPrivate = $repository->findReCaptchaKeyPrivate();
    }

    public function verify(string $reCaptcha): bool
    {
        $url = 'https://www.google.com/recaptcha/api/siteverify';

        $ch = curl_init();

        curl_setopt_array($ch, [
            \CURLOPT_URL => $url,
            \CURLOPT_HEADER => false,
            \CURLOPT_RETURNTRANSFER => true,
            \CURLOPT_POST => true,
            \CURLOPT_POSTFIELDS => [
                'secret' => $this->keyPrivate,
                'response' => $reCaptcha,
            ],
        ]);

        $response = curl_exec($ch);
        curl_close($ch);

        if (false === $response) {
            return false;
        }

        $data = json_decode($response);

        return (bool) ($data->success ?? false);
    }
}
