false, "message" => ""]; try { if ($_SERVER["REQUEST_METHOD"] !== "POST") { throw new Exception("Invalid request method."); } $input = json_decode(file_get_contents('php://input'), true); $template_id = isset($input['template_id']) ? intval($input['template_id']) : null; $schemajson = isset($input['schemajson']) ? trim($input['schemajson']) : ''; if (empty($template_id) || empty($schemajson)) { throw new Exception("All fields marked with * are required, including schemajson."); } $decoded_json = json_decode($schemajson, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new Exception("Invalid JSON format for schemajson."); } $db = DBHandlerSelect::getInstance(); $pdo = $db->getConnection(); $stmt = $pdo->prepare("SELECT target_table FROM excel_templates WHERE id = ?"); $stmt->execute([$template_id]); $template = $stmt->fetch(PDO::FETCH_ASSOC); if (!$template) { throw new Exception("Template not found."); } $target_table = $template['target_table']; $schema_id = $decoded_json['IdSchemaCustomFields'] ?? null; $schema_fields = $decoded_json['SchemiCustomFieldsDettagli'] ?? []; if (empty($schema_id)) { throw new Exception("Schema ID not found in schemajson."); } if (empty($schema_fields)) { throw new Exception("No fields found in schema."); } $pdo->beginTransaction(); /* * 1) Update raw schema JSON in excel_templates */ $stmt = $pdo->prepare(" UPDATE excel_templates SET schemajson = ?, updated_at = NOW() WHERE id = ? "); $stmt->execute([$schemajson, $template_id]); /* * Prepare reusable statements */ // Check if mapping already exists $checkStmt = $pdo->prepare(" SELECT id, data_type FROM template_mapping WHERE template_id = ? AND field_id = ? LIMIT 1 "); // Insert new field $insertStmt = $pdo->prepare(" INSERT INTO template_mapping ( template_id, schema_id, field_id, data_type, is_required, default_value, has_list, length, decimals, min_value, max_value, default_curr_date, tablename, field_label ) VALUES ( :template_id, :schema_id, :field_id, :data_type, :is_required, :default_value, :has_list, :length, :decimals, :min_value, :max_value, :default_curr_date, :tablename, :field_label ) "); // Update existing field WITHOUT clearing manual_default $updateSameTypeStmt = $pdo->prepare(" UPDATE template_mapping SET schema_id = :schema_id, data_type = :data_type, is_required = :is_required, default_value = :default_value, has_list = :has_list, length = :length, decimals = :decimals, min_value = :min_value, max_value = :max_value, default_curr_date = :default_curr_date, tablename = :tablename, field_label = :field_label WHERE id = :id "); // Update existing field AND clear user-entered value if type changed $updateChangedTypeStmt = $pdo->prepare(" UPDATE template_mapping SET schema_id = :schema_id, data_type = :data_type, is_required = :is_required, default_value = :default_value, has_list = :has_list, length = :length, decimals = :decimals, min_value = :min_value, max_value = :max_value, default_curr_date = :default_curr_date, tablename = :tablename, field_label = :field_label, manual_default = NULL, auto_value = 'none' WHERE id = :id "); $currentFieldIds = []; /* * 2) Insert new fields and update existing fields */ foreach ($schema_fields as $field) { $custom_field = $field['CustomField'] ?? []; if (empty($custom_field['IdCustomField'])) { continue; } $fieldId = (int)$custom_field['IdCustomField']; $currentFieldIds[] = $fieldId; $newDataType = $custom_field['Tipo'] ?? 'Testo'; $data = [ ':schema_id' => $schema_id, ':data_type' => $newDataType, ':is_required' => !empty($custom_field['ObbligatorioWeb']) ? 1 : 0, ':default_value' => $custom_field['ValoreDefault'] ?? null, ':has_list' => !empty($custom_field['Elenco']) ? 1 : 0, ':length' => $custom_field['Lunghezza'] ?? 0, ':decimals' => $custom_field['Decimali'] ?? 0, ':min_value' => $custom_field['Minimo'] ?? null, ':max_value' => $custom_field['Massimo'] ?? null, ':default_curr_date' => !empty($custom_field['DefaultCurrDate']) ? 1 : 0, ':tablename' => $target_table, ':field_label' => $custom_field['TitoloTraduzione'] ?? '' ]; $checkStmt->execute([$template_id, $fieldId]); $existing = $checkStmt->fetch(PDO::FETCH_ASSOC); if (!$existing) { // New field: insert it $insertData = $data; $insertData[':template_id'] = $template_id; $insertData[':field_id'] = $fieldId; $insertStmt->execute($insertData); } else { // Existing field: update schema details $oldDataType = $existing['data_type'] ?? ''; $updateData = $data; $updateData[':id'] = (int)$existing['id']; if ($oldDataType !== $newDataType) { // Type changed: clear manual value because it may no longer be valid $updateChangedTypeStmt->execute($updateData); } else { // Same type: keep manual_default, excel/json mapping, visibility, main field, etc. $updateSameTypeStmt->execute($updateData); } } } /* * 3) Remove fields no longer present in the schema */ $currentFieldIds = array_values(array_unique(array_filter($currentFieldIds))); if (!empty($currentFieldIds)) { $placeholders = implode(',', array_fill(0, count($currentFieldIds), '?')); $deleteParams = array_merge([$template_id], $currentFieldIds); $deleteStmt = $pdo->prepare(" DELETE FROM template_mapping WHERE template_id = ? AND field_id NOT IN ($placeholders) "); $deleteStmt->execute($deleteParams); } $pdo->commit(); $response["success"] = true; $response["message"] = "Schema JSON updated, mappings synchronized, removed fields deleted, and changed fields updated successfully."; } catch (Exception $e) { if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollback(); } $response["message"] = $e->getMessage(); } echo json_encode($response);