<?php

use Joomla\CMS\Factory;
use Joomla\CMS\Http\Http;
use Joomla\Registry\Registry;

defined('_JEXEC') or die('Restricted access');
class HcaptchaCCaptchaHelper
{
    public  $enabled = false;
    public  $ip;
    private $privateKey;
    private $publicKey;
    
    private $theme;

    private $apiUrl;
    private $verifyUrl;

    /*
     * Load config data and object vars
     */
    public function __construct()
    {
        // Config data
        $config             = CFactory::getConfig();
        $this->enabled      = $config->get('nohcaptcha', false);
        $this->privateKey   = $config->get('hcaptchaprivate');
        $this->publicKey    = $config->get('hcaptchapublic');
        $this->theme        = $config->get('hcaptchatheme');
        $this->apiUrl       = $config->get('hcaptcha_server');
        $this->verifyUrl    = $config->get('hcaptcha_server_verify');

        // Grab the IP, remember load balancers
        // @todo is there a framework way to do it?
        $this->ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];

        // If any of the vital vars is missing, disable the whole thing
        if (!$this->privateKey || !$this->publicKey || !$this->apiUrl || !$this->verifyUrl) {
            $this->enabled = false;
        }
    }
    public function html()
    {
        if (!$this->enabled) {
            return '';
        }
        // start output buffer, if hcaptcha is enabled add HTML and JS to the buffer
        ob_start(); ?>
        <div id="joms-hcaptcha"></div>
        <script type="text/javascript">
            const form = document.getElementsByTagName('form');
            var jomshCaptchaCallback = function() {
                hcaptcha.render("joms-hcaptcha", {
                    "sitekey": "<?php echo $this->publicKey; ?>",
                    "theme": "<?php echo $this->theme; ?>",
                    callback: function(token) {
                        jQuery(form).append('<input name="h-captcha-response" type="hidden" value="' + token + '" />');
                    },
                })
            };
        </script>
        <script src="<?php echo $this->apiUrl; ?>?onload=jomshCaptchaCallback" async></script>
        <?php
        // get the contents of te buffer and return it
        $html = ob_get_clean();

        return $html;
    }
    public function verify()
    {

        // get the Hcaptcha response from the form data
        $token = Factory::getApplication()->input->get('h-captcha-response');

        if (!$token) return false;

        $http = new Http();
        try {
            $response = $http->post(
                $this->verifyUrl,
                array(
                    'secret' => $this->privateKey,
                    'remoteip' => $this->ip,
                    'response' => $token,
                )
            );
        } catch (Exception $e) {
            return false;
        }
        if ($response->code !== 200) {
            return false;
        }
        $result = new Registry($response->body);

        if ($result->get('success')) {
            return true;
        }



        return false;
    }
}
