<?php

namespace Actigraph\ActipageBaseBundle\Services;

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

class CaptchaHcaptchaService 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()."' src='https://js.hcaptcha.com/1/api.js?hl=fr' async defer></script>
            <div
  class='h-captcha'
  data-sitekey=\"".$this->config["public"]."\"
  data-theme='light'
  data-error-callback='onError'
></div>
        ";
    }

    public function isCaptchaValid($postData)
    {
        if(strlen(trim($postData["h-captcha-response"]))==0)
            return false;
        $responseAPI = $this->http->post("https://hcaptcha.com/siteverify", array(
            'form_params'=>array(
                "secret"=>$this->config["secret"],
                "response"=>$postData["h-captcha-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(),true);

        if( (isset($response["success"]) && $response["success"]=="1") )
            return true;
        return false;
    }

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