<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureBranchAccess
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        $branchId = (int) ($request->route('branch')?->id ?? $request->input('branch_id') ?? $user?->branch_id);

        abort_unless($user && ($branchId === 0 || $user->canAccessBranch($branchId)), 403);

        return $next($request);
    }
}
