false, 'message' => '']; try { if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['iddatadb'])) { throw new Exception('Richiesta non valida'); } $iddatadb = intval($_POST['iddatadb']); $idclient = isset($_POST['idclient']) ? (is_numeric($_POST['idclient']) ? intval($_POST['idclient']) : null) : null; $db = DBHandlerSelect::getInstance(); $pdo = $db->getConnection(); $data = $_POST; $details = []; // 1. Estrarre i dettagli da POST foreach ($data as $key => $value) { if (preg_match('/^details(\d+)field_value$/', $key, $matches)) { $id = $matches[1]; $details[$id] = $value; } } // 2. Recupera i valori esistenti da import_data_details $stmt = $pdo->prepare("SELECT mapping_id, field_value FROM import_data_details WHERE id = ?"); $stmt->execute([$iddatadb]); $currentValues = []; while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $currentValues[$row['mapping_id']] = $row['field_value']; } // 3. Confronta i valori nuovi con quelli esistenti $changed = []; foreach ($details as $id => $newValue) { $oldValue = $currentValues[$id] ?? null; if ($oldValue !== $newValue) { $changed[$id] = [ 'old' => $oldValue, 'new' => $newValue ]; } } // 4. Aggiorna i dettagli se ci sono modifiche if (!empty($changed)) { $updateStmt = $pdo->prepare(" UPDATE import_data_details SET field_value = :newValue WHERE id = :iddatadb AND mapping_id = :mappingId "); foreach ($changed as $mappingId => $values) { $updateStmt->execute([ ':newValue' => $values['new'], ':iddatadb' => $iddatadb, ':mappingId' => $mappingId ]); } } // 5. Aggiorna idclient in datadb if (isset($idclient)) { $updateStmt = $pdo->prepare(" UPDATE datadb SET idclient = :idclient WHERE iddatadb = :iddatadb "); $updateStmt->execute([ ':idclient' => $idclient, ':iddatadb' => $iddatadb ]); $response['message'] = !empty($changed) ? "Updated details and idclient successfully" : "Updated idclient successfully"; } else { $response['message'] = !empty($changed) ? "Updated details successfully" : "No changes found"; } $response['success'] = true; $response['changed'] = $changed; // Debug / optional } catch (Exception $e) { $response['success'] = false; $response['message'] = $e->getMessage(); error_log("Errore in save_edited_row.php: " . $e->getMessage()); } echo json_encode($response); exit;