<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

/**
 * Enforces server-side: disabled users (users.is_disabled = 1) cannot access any authenticated route.
 * Applied after auth; logs out, invalidates session, redirects to login with message.
 */
class EnsureUserIsActive
{
    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();

        if ($user && ($user->is_disabled || (method_exists($user, 'trashed') && $user->trashed()))) {
            Auth::logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return redirect()->route('login')
                ->withErrors(['email' => 'Your account is not active. Please contact support.']);
        }

        return $next($request);
    }
}

