<?php

namespace App\Http\Middleware;

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

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

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

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

        $branchCode = $user->branch_code;

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

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