<?php

namespace App\Http\Middleware;

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

class TenantAuthMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = auth()->user();

        if (!$user || (!$user->tenant_id && !$user->is_super_admin)) {
            abort(403, 'No tenant assigned.');
        }

        if ($user->tenant_id && !$user->tenant?->is_active) {
            auth()->logout();
            return redirect()->route('login')->with('error', 'حساب شركتك معطل. تواصل مع المسؤول.');
        }

        return $next($request);
    }
}
