validate([ 'version' => 'required|string|max:100', 'os_group_id' => 'required|integer|exists:os_group,id', 'template_id' => 'nullable|string|max:255', 'module_host_id' => 'nullable|integer|exists:module_host,id', 'is_active' => 'boolean', ]); $os = Os::create([ 'version' => $validated['version'], 'os_group_id' => $validated['os_group_id'], 'template_id' => $validated['template_id'] ?? null, 'module_host_id' => $validated['module_host_id'] ?? null, 'status' => ($validated['is_active'] ?? true) ? 1 : 0, ]); return response()->json([ 'error' => false, 'message' => 'Thêm OS thành công.', 'data' => $this->formatOs($os), ], 201); } public function update(Request $request, int $id): JsonResponse { $os = Os::find($id); if (! $os) { return response()->json(['error' => true, 'message' => 'Không tìm thấy OS.'], 404); } $validated = $request->validate([ 'version' => 'sometimes|required|string|max:100', 'os_group_id' => 'sometimes|integer|exists:os_group,id', 'template_id' => 'nullable|string|max:255', 'module_host_id' => 'nullable|integer|exists:module_host,id', 'is_active' => 'boolean', ]); $os->update([ 'version' => $validated['version'] ?? $os->version, 'os_group_id' => $validated['os_group_id'] ?? $os->os_group_id, 'template_id' => array_key_exists('template_id', $validated) ? $validated['template_id'] : $os->template_id, 'module_host_id' => array_key_exists('module_host_id', $validated) ? $validated['module_host_id'] : $os->module_host_id, 'status' => isset($validated['is_active']) ? ($validated['is_active'] ? 1 : 0) : $os->status, ]); return response()->json([ 'error' => false, 'message' => 'Cập nhật OS thành công.', 'data' => $this->formatOs($os->fresh()), ]); } public function destroy(int $id): JsonResponse { $os = Os::find($id); if (! $os) { return response()->json(['error' => true, 'message' => 'Không tìm thấy OS.'], 404); } $os->delete(); return response()->json(['error' => false, 'message' => 'Xoá OS thành công.']); } // ── helpers ────────────────────────────────────────────────────────────── private function formatOs(Os $os): array { $os->loadMissing('host.datacenter.vCenter'); $host = $os->host; return [ 'id' => $os->id, 'version' => $os->version, 'template_id' => $os->template_id, 'is_active' => (bool) $os->status, 'os_group_id' => $os->os_group_id, 'module_host_id' => $os->module_host_id, 'host_name' => $host ? $host->name : null, 'datacenter_name' => $host?->datacenter?->name, 'vcenter_name' => $host?->datacenter?->vCenter?->host, ]; } }