<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class TurnstileCaptchaValidate
{
    /**
     * Handle an incoming request.
     *
     * @param Request  $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (null !== $request->input('turnstile_token')) {
            $token = $request->input('turnstile_token');
            $data = [
                'secret' => env('TURNSTILE_SECRET'),
                'response' => $token
            ];

            $verify = curl_init();
            curl_setopt($verify, CURLOPT_URL, "https://challenges.cloudflare.com/turnstile/v0/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);
            curl_close($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);
    }
}
