getConnection(); $api = VisualLimsApiClient::getInstance(); // Get all schemas currently used in template_mapping $stmtSchemas = $pdo->query(" SELECT DISTINCT schema_id FROM template_mapping WHERE schema_id IS NOT NULL AND schema_id > 0 ORDER BY schema_id ASC "); $schemaIds = $stmtSchemas->fetchAll(PDO::FETCH_COLUMN); if (empty($schemaIds)) { throw new Exception('No schema_id found in template_mapping'); } $stmtUpdate = $pdo->prepare(" UPDATE template_mapping SET field_order = ? WHERE schema_id = ? AND field_id = ? "); $summary = []; $totalUpdated = 0; foreach ($schemaIds as $schemaId) { $schemaId = (int)$schemaId; $endpoint = "SchemaCustomField($schemaId)?\$expand=SchemiCustomFieldsDettagli(\$expand=CustomField)"; $data = $api->get($endpoint); if (empty($data['SchemiCustomFieldsDettagli']) || !is_array($data['SchemiCustomFieldsDettagli'])) { $summary[] = [ 'schema_id' => $schemaId, 'success' => false, 'message' => 'No SchemiCustomFieldsDettagli found' ]; continue; } $schemaUpdated = 0; $notFound = []; foreach ($data['SchemiCustomFieldsDettagli'] as $detail) { $order = intval($detail['Ordine'] ?? 9999); $fieldId = intval($detail['CustomField']['IdCustomField'] ?? 0); if ($fieldId <= 0) { continue; } $stmtUpdate->execute([ $order, $schemaId, $fieldId ]); if ($stmtUpdate->rowCount() > 0) { $schemaUpdated++; $totalUpdated++; } else { $notFound[] = [ 'field_id' => $fieldId, 'order' => $order, 'label' => $detail['CustomField']['Titolo'] ?? '' ]; } } $summary[] = [ 'schema_id' => $schemaId, 'success' => true, 'updated' => $schemaUpdated, 'not_found_count' => count($notFound), 'not_found' => $notFound ]; } echo json_encode([ 'success' => true, 'schemas_processed' => count($schemaIds), 'total_updated' => $totalUpdated, 'summary' => $summary ], JSON_PRETTY_PRINT); } catch (Exception $e) { http_response_code(500); echo json_encode([ 'success' => false, 'message' => $e->getMessage() ], JSON_PRETTY_PRINT); }