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 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'] ]; } // 🔹 Simulation Mode if ($simulate) { $commessaId = 999999; $commessa = [ "IdCommessa" => $commessaId, "CodiceCommessa" => "TEST001", "IdCliente" => $clienteId, "Fields" => $fieldValues ]; } else { // 🔹 REAL API FLOW $api = VisualLimsApiClient::getInstance(); // 1. Create CommessaWeb $commessaPayload = [ "IdCliente" => $clienteId, "IdSchemaCustomFields" => $schemaId, "Inviato" => 1 ]; $commessa = $api->post("CommessaWeb", $commessaPayload); $commessaId = $commessa["IdCommessa"]; // 2. Push Fields $fields = []; foreach ($fieldValues as $f) { $fieldPayload = [ "Commessa" => $commessaId, "FieldLabel" => $f["FieldLabel"], "FieldValue" => $f["FieldValue"] ]; $res = $api->post("CommessaField", $fieldPayload); $fields[] = $res; } $commessa["Fields"] = $fields; } echo json_encode([ "success" => true, "commessa" => $commessa, "parts" => $parts, "simulation" => $simulate ]); } catch (Exception $e) { echo json_encode([ "success" => false, "message" => $e->getMessage() ]); }