<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

/**
 * A session outlives a deactivation.
 *
 * Somebody who left the company yesterday still has a valid cookie today, and
 * this panel can activate subscriptions, so the check is made on every request
 * rather than only at sign-in.
 */
class EnsureStaffIsActive
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = Auth::user();

        if ($user && ! $user->is_active) {
            Auth::logout();

            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return redirect()
                ->route('login')
                ->with('error', 'Your account has been deactivated. Contact a super admin.');
        }

        return $next($request);
    }
}
