<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class CheckIpAccessMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (!isset($request->payments)) {
            return response()->json([
                "status" => 0,
                "message" => "No ha seleccionado metodo de pago"
            ], 403);
        }
        // If the payments is with prepaid card, sleep the thread a random nanoseconds
        if (count($request->payments)) {
            if ($request->payments[0]['id'] == 6){

                // Sleep the thread
                $time = random_int(10000, 500000);
                usleep($time);

                // Obtain last access ip + time
                $lastAccess = Cache::get('lastAccess');

                // Calculate this access ip + time
                $ip = request()->ip();
                $now = new \DateTime();
                $thisAccess = $ip . $now->format("H:i:s");

                // Compare the access
                if ($lastAccess == $thisAccess) {
                    return response()->json([
                        "status" => 0,
                        "message" => "Operacion duplicada"
                    ], 403);
                }

                // Save this acces like a last access
                Cache::put('lastAccess', $thisAccess);
            }
        }
        return $next($request);
    }
}
