<?php

namespace App\Http\Middleware;

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

class EnsureRole
{
    /**
     * Gate a route by role. Usage: ->middleware('role:admin,manager').
     * The special value "staff" allows any staff role.
     * Admin passes every gate.
     */
    public function handle(Request $request, Closure $next, string ...$roles): Response
    {
        $user = $request->user();

        if (! $user) {
            return redirect()->route('login');
        }

        if ($user->status !== 'active') {
            auth()->logout();

            return redirect()->route('login')->withErrors(['email' => 'Your account has been suspended. Contact an administrator.']);
        }

        if ($user->role === 'super_admin') {
            return $next($request);
        }

        // Hotel admins pass every gate except platform-owner-only areas.
        if ($user->role === 'admin' && $roles !== ['super_admin']) {
            return $next($request);
        }

        foreach ($roles as $role) {
            if ($role === 'staff' && $user->isStaff()) {
                return $next($request);
            }

            if ($user->role === $role) {
                return $next($request);
            }
        }

        abort(403, 'You do not have permission to access this area.');
    }
}
