<?php

namespace App\Controller\Component;

use Cake\Controller\Component;
use Cake\Network\Http\Client;
use Exception;

class RecaptchaComponent extends Component
{

    public $error = null;

    public function verify($response = null)
    {
        $recaptchaSecretKey = get_option('reCAPTCHA_secret_key');
        if (empty($recaptchaSecretKey)) {
            throw new Exception(__("You must set your Recaptcha secret key!"));
        }

        $http = new Client();

        $data = array(
            'secret' => $recaptchaSecretKey,
            'response' => $response,
        );

        $results = $http->post('https://www.google.com/recaptcha/api/siteverify', $data);
        $responseData = json_decode($results->body, true);

        if ($responseData['success'] == false) {
            $recaptchaError = '';
            foreach ($responseData['error-codes'] as $code) {
                $recaptchaError .= $code . ' ';
            }

            $this->error = $recaptchaError;
        }

        return $responseData['success'];
    }
}
