customerInfoService = $customerInfoService; } public function customerDeviceInfo(Request $request) { try { $tokenPayload = getTokenFromHeader($request); if (isset($tokenPayload['error'])) { return response()->json($tokenPayload, 401); } $userId = $tokenPayload['sub']; // Get user with assets and devices $user = User::with(['assets' => function($query) { $query->with(['devices:id,name,asset_id']); }]) ->where('id', $userId) ->first(); if (!$user) { return response()->json(['error' => 'User not found'], 404); } try { // Get devices data from ThingsBoard service $devicesArray = $this->customerInfoService->getThingsBoardDevices($user->customer_id); if (!is_array($devicesArray)) { throw new \Exception("Invalid devices data received from service"); } $thingsBoardDevices = collect($devicesArray); // Process devices $deviceDetails = $user->assets->flatMap(function ($asset) use ($thingsBoardDevices) { return $thingsBoardDevices->whereIn('id.id', $asset->devices->pluck('id')->toArray()) ->map(function ($tbDevice) { return [ 'device_id' => $tbDevice['id']['id'], 'active' => $tbDevice['active'] ?? false ]; }); }); // Calculate counts $good = $deviceDetails->where('active', true)->count(); $moderate = $deviceDetails->where('active', false)->count(); $total_count = $good + $moderate; // Successful response return response()->json([ 'good' => $good, 'moderate' => $moderate, 'total_count' => $total_count ], 200); } catch (\Exception $serviceException) { Log::error("ThingsBoard service error: " . $serviceException->getMessage()); return response()->json([ 'error' => 'Failed to fetch device information', 'details' => $serviceException->getMessage() ], 503); } } catch (\Exception $e) { Log::error("Customer device info error: " . $e->getMessage()); return response()->json([ 'error' => 'An unexpected error occurred', 'details' => $e->getMessage() ], 500); } } }