<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\Company;

class ActiveCompanyMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = auth()->user();

        if ($user) {
            if ($user->role_id == 2) {
                // Client Admin - force active company to their own users.id
                session(['active_company_id' => $user->id]);
            } else if ($user->role_id == 1) {
                // Superadmin
                // active_company_id is the Company Admin's users.id (role_id=2)
                $activeCompanyId = session('active_company_id');
                
                // Validate if this active company (company admin) belongs to this superadmin
                $isValidCompany = Company::where('user_id', $activeCompanyId)->where('superadmin_id', $user->id)->exists();

                if (!$activeCompanyId || !$isValidCompany) {
                    // Default to the first company they own
                    $firstCompany = Company::where('superadmin_id', $user->id)->orderBy('id')->first();
                    if ($firstCompany) {
                        session(['active_company_id' => $firstCompany->user_id]);
                    } else {
                        // Edge case: Superadmin has no companies at all
                        session()->forget('active_company_id');
                    }
                }
            }
        }

        return $next($request);
    }
}
