<?php

namespace classes;

require_once WD . '/modules/reCAPTCHA/reCAPTCHA_c.php';

use Exception;
use interfaces\recaptcha_i;
use reCAPTCHA\reCAPTCHA_c;

class recaptcha implements recaptcha_i
{
    /**
     * Configuration of the reCAPTCHA module
     * @var recaptcha_c
     */
    public recaptcha_c $config;

    public function __construct()
    {
        $this->config = new recaptcha_c();
    }

    /**
     * Validate the reCAPTCHA response
     * @param string|null $response The response from the reCAPTCHA
     * @return bool Whether the response is valid
     * @throws Exception
     */
    public function validate(string|null $response): bool
    {
        if (!$this->config->enabled->isTrue()) {
            return true;
        }
        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $data = [
            'secret' => $this->config->secret_key_v2->getVariableValue(),
            'response' => $response
        ];
        $options = [
            'http' => [
                'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                'method' => 'POST',
                'content' => http_build_query($data)
            ]
        ];
        $context = stream_context_create($options);
        $response = file_get_contents($url, false, $context);
        $responseKeys = json_decode($response, true);
        return $responseKeys['success'];
    }

    public function getPublicConfig(): array
    {
        return [
            'enabled' => $this->config->enabled->isTrue(),
            'site_key' => $this->config->site_key_v2->getVariableValue()
        ];
    }
}