<?php

namespace App\Http\Middleware;

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

/**
 * Guards the Employee Self-Service portal: the authenticated user must be
 * linked to an employee record. Managers without a linked employee are sent
 * to the admin dashboard instead.
 */
class EnsureHasEmployee
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if (! $user || ! $user->employee()->exists()) {
            abort_unless($user !== null, 403);

            return redirect()->route('dashboard');
        }

        return $next($request);
    }
}
