[]]); exit; } try { $cacheDir = __DIR__ . '/cache'; $cacheFile = $cacheDir . '/customfield_' . $fieldId . '.json'; if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 3600)) { $values = json_decode(file_get_contents($cacheFile), true); } else { $api = VisualLimsApiClient::getInstance(); $data = $api->get("CustomField($fieldId)?\$expand=CustomFieldsValues"); $values = $data['CustomFieldsValues'] ?? []; if (!is_dir($cacheDir)) mkdir($cacheDir, 0777, true); file_put_contents($cacheFile, json_encode($values)); } // Lookup by ID if ($id !== null) { foreach ($values as $v) { if ((int)($v['IdCustomFieldsValue'] ?? 0) === $id) { echo json_encode(['results' => [['id' => $v['IdCustomFieldsValue'], 'text' => $v['Valore'] ?? '']]]); exit; } } echo json_encode(['results' => []]); exit; } // Search by query $results = []; foreach ($values as $v) { $text = $v['Valore'] ?? ''; if ($q === '' || mb_strpos(mb_strtolower($text), $q) !== false) { $results[] = ['id' => $v['IdCustomFieldsValue'], 'text' => $text]; if (count($results) >= $limit) break; } } // Sort alphabetically usort($results, fn($a, $b) => strcasecmp($a['text'], $b['text'])); echo json_encode(['results' => $results]); } catch (Exception $e) { http_response_code(500); echo json_encode(['error' => $e->getMessage()]); }