<?php

namespace App\Http\Middleware;

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

class RoleMiddleware
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next, string ...$roles): Response
    {
        if (!auth()->check()) {
            return redirect()->route('login');
        }

        $user = auth()->user();
        $branchCode = $user->branch_code;

        // Check if user has any of the required roles
        if ($user->hasAnyRole($roles, $branchCode)) {
            return $next($request);
        }

        // Check for super admin role (bypass branch restrictions)
        if ($user->hasRole('admin')) {
            return $next($request);
        }

        abort(403, 'Access denied. Required role: ' . implode(' or ', $roles));
    }
}
