<?php

namespace App\Http\Middleware;

use Closure;

class RecaptchaValidate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(null !== $request->input('recaptcha_token')){
            $token = $request->input('recaptcha_token');
            $data = array(
                'secret' => env('RECAPTCHA_PRIVKEY'),
                'response' => $token
            );
            $verify = curl_init();
            curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
            curl_setopt($verify, CURLOPT_POST, true);
            curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($verify);
            $responseData = json_decode($response);
            if($responseData->success) {
                $request->attributes->add(['captcha' => true]);
            } 
            else {
                $request->attributes->add(['captcha' => false]);
            }
        }else{
            $request->attributes->add(['captcha' => false]);
        }
        return $next($request);
    }
}
