header('X-Tenant-Code'); $headerId = $request->header('X-Tenant-Id'); $tenant = null; if ($headerCode) { $tenant = Tenant::where('code', strtoupper((string) $headerCode))->first(); \Log::info("ResolveTenant: Code: {$headerCode}, Resolved: " . ($tenant ? 'YES' : 'NO') . ", Path: " . $request->path() . ", Match tenants: " . ($request->is('*/tenants') ? 'YES' : 'NO') . ", Match lookup: " . ($request->is('*/tenants/lookup') ? 'YES' : 'NO')); if (! $tenant) { if ($request->is('*/tenants') || $request->is('*/tenants/lookup')) { return $next($request); } \Log::info("ResolveTenant: Header code not found: {$headerCode}"); return response()->json([ 'success' => false, 'data' => null, 'message' => "Unknown LGU code: {$headerCode}", 'errors' => null, 'meta' => null, ], 404); } } elseif ($headerId) { $tenant = Tenant::where('uuid', $headerId)->first(); if (! $tenant) { \Log::info("ResolveTenant: Header ID not found: {$headerId}"); } } // Fall back to the authenticated user's tenant. if (! $tenant) { $user = $request->user(); if ($user instanceof User && $user->tenant_id) { $tenant = Tenant::find($user->tenant_id); } } if ($tenant) { if ($tenant->status !== Tenant::STATUS_ACTIVE) { return response()->json([ 'success' => false, 'data' => null, 'message' => "LGU '{$tenant->name}' is not currently active.", 'errors' => null, 'meta' => null, ], 403); } Tenancy::setCurrent($tenant); } return $next($request); } }