<?php
/**
 * Created by PhpStorm.
 * User: damien
 * Date: 10/03/2018
 * Time: 19:47
 */

namespace Actigraph\ActipageBaseBundle\Services;


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

class CaptchaGoogleRecaptcha 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()."'>
            function isCaptchaFilled(formId){
                return grecaptcha && grecaptcha.getResponse().length !== 0;
            }
            </script>
            <div class=\"g-recaptcha\" data-sitekey=\"".$this->config["public"]."\"></div>
        ";
    }

    public function isCaptchaValid($postData)
    {
        if (!isset($postData['g-recaptcha-response'])) {
            return false;
        }
        if(strlen(trim($postData["g-recaptcha-response"]))==0)
            return false;
        $responseAPI = $this->http->post("https://www.google.com/recaptcha/api/siteverify", array(
            'form_params'=>array(
                "secret"=>$this->config["secret"],
                "response"=>$postData["g-recaptcha-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['g-recaptcha-response']))
            unset($data['g-recaptcha-response']);
        return $data;
    }
}
