<?php

namespace Actigraph\ActipageBaseBundle\Services;

use GuzzleHttp\Client;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class CaptchaProsopoService implements CaptchaImplementationInterface
{
    private $http,$config,$contentSecurityPolicyNonceService;

    public function __construct(SessionInterface $session,ContentSecurityPolicyNonceService $contentSecurityPolicyNonceService, $config)
    {
        $this->config = $config;
        $this->contentSecurityPolicyNonceService = $contentSecurityPolicyNonceService;
        $this->http = new Client();
    }

    public function getHtmlCaptcha()
    {
        return "
            <script nonce='".$this->contentSecurityPolicyNonceService->getNonce()."'>
                var script = document.createElement('script');
                script.src = \"https://js.prosopo.io/js/procaptcha.bundle.js?l=fr\";
                script.async = true;
                script.defer = true;
                script.type = \"module\";
                script.nonce = \"".$this->contentSecurityPolicyNonceService->getNonce()."\";
                document.head.appendChild(script);
            </script>
            <div class=\"procaptcha\" data-sitekey=\"".$this->config["public"]."\"></div>
        ";
    }

    public function isCaptchaValid($postData)
    {
        if(strlen(trim($postData["procaptcha-response"]))==0)
            return false;
        $responseAPI = $this->http->post("https://api.prosopo.io/siteverify", array(
            'json' => array(
                "secret" => $this->config["secret"],
                "token" => $postData["procaptcha-response"],
            ),
            'timeout' => 2,
        ));
        if($responseAPI->getStatusCode() != 200)
            return true; //J'accepte le captcha si j'ai pas de réponse de google

        $response = json_decode($responseAPI->getBody()->getContents(),true);

        if(isset($response["verified"]) && $response["verified"] == true && isset($response["status"]) && $response["status"] == 'ok')
            return true;
        return false;
    }

    public function removeCaptchaParamFromPostData($data)
    {
        if (isset($data['procaptcha-response']))
            unset($data['procaptcha-response']);
        return $data;
    }
}
