<?php

namespace App\Http\Middleware;

use Closure;

use Illuminate\Support\Facades\Cache;

class RouteLockMiddleware
{
    public function handle($request, Closure $next)
    {
        $id = $request->route('id'); // route parameter
        $userId = auth()->id();

        $lockKey = "route_lock_{$id}";

        // check if locked by someone else
        $lockedBy = Cache::get($lockKey);

        if ($lockedBy && $lockedBy != $userId) {
            return back()->with('error', 'This record is currently opened by another user.');
        }

        // lock for current user (30 minutes example)
        Cache::put($lockKey, $userId, now()->addMinutes(60));

        return $next($request);
    }
}
