<?php

namespace App\Http\Middleware;

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

class ClientPortalMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = auth()->user();

        if ($user->role !== 'client' || ! $user->active) {
            auth()->logout();

            return redirect()->route('portal.login')->withErrors(['email' => 'Unauthorized access.']);
        }

        if (! $user->active_branch_id) {
            return redirect()->route('portal.branches.select');
        }

        return $next($request);
    }
}
