<?php
/**
 * @package   BaForms
 * @author    Balbooa http://www.balbooa.com/
 * @copyright Copyright @ Balbooa
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace Balbooa\Component\Forms\Site\Helper\Captcha;

use Balbooa\Component\Forms\Site\Helper\ServiceHelper;

defined('_JEXEC') or die;

abstract class FormsCaptcha
{
    protected static string $type;
    protected static FormsCaptcha $instance;
    protected ?object $settings;
    protected ServiceHelper $service;
    protected string $url;
    protected string $responseKey;

    protected function __construct()
    {
        $this->service = ServiceHelper::getInstance();
        $this->settings = $this->loadSettings();
    }

    public static function getInstance(): static
    {
        if (!isset(self::$instance)) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    public static function getType(): string
    {
        return static::$type;
    }

    public function getSettings(): ?object
    {
        return $this->settings;
    }

    protected function loadSettings(): ?object
    {
        $settings = $this->service->get(static::$type);
        if (empty($settings->site_key) || empty($settings->secret_key)) {
            $settings = null;
        }

        return $settings;
    }

    public function checkResponse(array $post)
    {
        $response = $post[$this->responseKey] ?? '';
        $headers = ['application/x-www-form-urlencoded'];
        $curl = curl_init();
        $options = [];
        $options[CURLOPT_POST] = 1;
        $options[CURLOPT_POSTFIELDS] = 'secret=' . $this->settings->secret_key . '&response=' . $response;
        $options[CURLOPT_URL] = $this->url;
        $options[CURLOPT_CONNECTTIMEOUT] = 30;
        $options[CURLOPT_TIMEOUT] = 80;
        $options[CURLOPT_RETURNTRANSFER] = true;
        $options[CURLOPT_HTTPHEADER] = $headers;
        $options[CURLOPT_SSL_VERIFYPEER] = false;
        curl_setopt_array($curl, $options);
        $body = curl_exec($curl);

        return json_decode($body);
    }
}