<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Traits\GetCompanyInfo;

class CompanyInfoMiddleware
{
    use GetCompanyInfo;

    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();
        \Log::info("CompanyInfoMiddleware - user: " . ($user ? $user->id : 'null') . ", uri: " . $request->getRequestUri());

        // Si el usuario es SuperAdmin, no establecer companyInfo
        if ($user && $user->hasRole('SuperAdmin')) {
            $request->attributes->set('companyInfo', null);
            return $next($request);
        }

        $userId = $user?->id;
        $companyInfo = $this->getCompanyInfo($userId);
        \Log::info("CompanyInfoMiddleware - resolved company: " . ($companyInfo ? $companyInfo->id : 'null'));
        $request->attributes->set('companyInfo', $companyInfo);
        return $next($request);
    }
}
