getConnection(); header("Content-Type: application/json"); try { $iddatadb = $_POST['iddatadb'] ?? null; if (!$iddatadb) { throw new Exception("Missing iddatadb"); } // ⚠️ Simulation ON (change it to false to enable real API calls) $simulate = true; // 🔹 STEP 1+2: Fetch Cliente ID + Schema ID $stmt = $pdo->prepare(" SELECT et.idclient AS clienteId, et.idschema AS schemaId FROM datadb as d INNER JOIN excel_templates as et ON d.templateid = et.id WHERE d.iddatadb = :iddatadb LIMIT 1 "); $stmt->execute(['iddatadb' => $iddatadb]); $result = $stmt->fetch(PDO::FETCH_ASSOC); if (!$result) { throw new Exception("No Cliente/Schema found for iddatadb {$iddatadb}"); } $clienteId = (int) $result['clienteId']; $schemaId = (int) $result['schemaId']; // 🔹 STEP 3: Fetch Parts $stmt = $pdo->prepare(" SELECT part_number, part_description, material, color, mix FROM identification_parts WHERE iddatadb = :iddatadb "); $stmt->execute(['iddatadb' => $iddatadb]); $parts = $stmt->fetchAll(PDO::FETCH_ASSOC); // 🔹 STEP 4: Fetch Field Values with Labels $stmt = $pdo->prepare(" SELECT idd.field_value, m.field_label, m.schema_id, m.field_id FROM import_data_details as idd JOIN template_mapping m ON idd.mapping_id = m.id WHERE idd.id = :iddatadb "); $stmt->execute(['iddatadb' => $iddatadb]); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); $fieldValues = []; foreach ($rows as $row) { $fieldValues[] = [ "FieldLabel" => $row['field_label'], "FieldValue" => $row['field_value'], "SchemaId" => (int) $row['schema_id'], "FieldId" => (int) $row['field_id'] ]; } // 🔹 Initialize API client (even in simulation mode for consistency) $api = null; if (!$simulate) { $api = VisualLimsApiClient::getInstance(); } // 🔹 STEP 5: Create WebOrder $webOrderPayload = [ "Customer" => $clienteId ]; if ($simulate) { // Simulate WebOrder creation $webOrder = [ "Id" => 999999, "Code" => "TEST-WO-001", "Customer" => $clienteId, "CreatedDate" => date('c'), "Status" => "Draft" ]; } else { // Real API call $webOrder = $api->post("odata/WebOrder", $webOrderPayload); } $webOrderId = $webOrder["Id"]; // 🔹 STEP 6: Create Samples for each part $samples = []; foreach ($parts as $index => $part) { $samplePayload = [ "OrderId" => $webOrderId, "Description" => $part["part_description"] ?? "", "SampleCode" => $part["part_number"] ?? "", "Material" => $part["material"] ?? "", "Color" => $part["color"] ?? "", "Mix" => $part["mix"] ?? "" ]; if ($simulate) { // Simulate Sample creation $sample = [ "Id" => 888000 + $index, "OrderId" => $webOrderId, "Description" => $part["part_description"] ?? "", "SampleCode" => $part["part_number"] ?? "", "Material" => $part["material"] ?? "", "Color" => $part["color"] ?? "", "Mix" => $part["mix"] ?? "", "Status" => "Created", "CreatedDate" => date('c') ]; } else { // Real API call $sample = $api->post("odata/Sample", $samplePayload); } $samples[] = $sample; } // 🔹 STEP 7: Handle Custom Fields for each sample $samplesWithCustomFields = []; foreach ($samples as $sample) { $sampleId = $sample["Id"]; if ($simulate) { // Simulate getting sample with custom fields $sampleWithFields = $sample; $sampleWithFields["CustomFieldSamples"] = []; // Simulate custom field updates foreach ($fieldValues as $fieldIndex => $fieldValue) { $customField = [ "Id" => 777000 + $fieldIndex, "SampleId" => $sampleId, "FieldLabel" => $fieldValue["FieldLabel"], "FieldValue" => $fieldValue["FieldValue"], "UpdatedDate" => date('c') ]; $sampleWithFields["CustomFieldSamples"][] = $customField; } } else { // Real API calls // Get sample with custom fields expanded $sampleWithFields = $api->get("odata/Sample({$sampleId})?$expand=CustomFieldSamples"); // Update custom fields (this depends on the actual API structure) foreach ($fieldValues as $fieldValue) { // This might need to be adjusted based on the actual Custom Fields API structure $customFieldPayload = [ "SampleId" => $sampleId, "FieldLabel" => $fieldValue["FieldLabel"], "FieldValue" => $fieldValue["FieldValue"] ]; try { $customFieldResult = $api->post("odata/CustomFieldSample", $customFieldPayload); } catch (Exception $e) { // Log custom field error but don't fail the entire process error_log("Custom Field Error for Sample {$sampleId}: " . $e->getMessage()); } } // Re-fetch sample with updated custom fields $sampleWithFields = $api->get("odata/Sample({$sampleId})?$expand=CustomFieldSamples"); } $samplesWithCustomFields[] = $sampleWithFields; } // 🔹 STEP 8: Optionally send the order to laboratory $orderSent = false; if (!$simulate) { try { $sendResult = $api->post("odata/WebOrder({$webOrderId})/SendOrder", []); $orderSent = true; } catch (Exception $e) { // Log error but don't fail the process error_log("Send Order Error: " . $e->getMessage()); } } // 🔹 STEP 9: Prepare final response $finalWebOrder = [ "IdCommessa" => $webOrderId, "CodiceCommessa" => $webOrder["Code"] ?? "N/A", "IdCliente" => $clienteId, "IdSchema" => $schemaId, "Customer" => $webOrder["Customer"] ?? $clienteId, "Status" => $webOrder["Status"] ?? "Draft", "CreatedDate" => $webOrder["CreatedDate"] ?? date('c'), "Fields" => $fieldValues, "Samples" => $samplesWithCustomFields, "Inviato" => $orderSent ? 1 : 0 ]; // 🔹 Final Response echo json_encode([ "success" => true, "webOrder" => $finalWebOrder, "totalSamples" => count($samplesWithCustomFields), "totalCustomFields" => count($fieldValues), "simulation" => $simulate, "orderSent" => $orderSent ]); } catch (Exception $e) { // Log the error for debugging error_log("LIMS Export Error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString()); echo json_encode([ "success" => false, "message" => "Export failed: " . $e->getMessage(), "simulation" => $simulate ?? true ]); }