<?php

namespace AppBundle\Security;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;

/**
 * Override the authentication handler.
 * 
 * @see http://www.reecefowell.com/2011/10/26/redirecting-on-loginlogout-in-symfony2-using-loginhandlers/
 */
class GRecaptchaHandler
{
    protected $router;

    /**
     * Constructor
     * 
     * @param RouterInterface $router 
     */
    public function __construct(RouterInterface $router, $securityKey = null)
    {
        $this->router = $router;
        $this->securityKey = $securityKey;
    }

    /**
     *
     * @param Request $request
     * @param TokenInterface $token
     * @return RedirectResponse
     */
    public function validateGRecaptchaResponse(Request $request)
    {
        $responseClientSide = $request->get('g-recaptcha-response');

		if (!empty($responseClientSide) && !empty($this->securityKey)) {
			$opts = ['http' =>
				[
					'method' => 'POST',
					'header' => 'Content-type: application/x-www-form-urlencoded',
					'content' => http_build_query([
						'secret' => $this->securityKey,
						'response' => $responseClientSide,
						'remoteip' => $request->getClientIp()
					])
				]
			];
			$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, stream_context_create($opts));
            $result = json_decode($response, true);
            
			if ($result["success"]) {
				return true;
            }
            else {
                return $result["error-codes"];
            }
        }
        
		return array( "missing-input-response" );
    }
}
