getConnection(); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $data = json_decode(file_get_contents('php://input'), true); $idquotations = $data['idquotations'] ?? null; $parts = $data['parts'] ?? []; if (!$idquotations || empty($parts)) { echo json_encode(['success' => false, 'message' => 'Dati mancanti']); exit; } try { $pdo->beginTransaction(); $results = []; foreach ($parts as $part) { $partId = $part['id'] ?? null; $partNumber = $part['part_number'] ?? null; $partDescription = $part['part_description'] ?? ''; $mix = $part['mix'] ?? 'N'; $idmatrice = $part['idmatrice'] ?? null; $note = $part['note'] ?? null; $dateexpiry = $part['dateexpiry'] ?? null; if ($partId) { // UPDATE se la parte esiste $stmt = $pdo->prepare("UPDATE identification_parts SET part_number = :part_number, part_description = :part_description, mix = :mix, idmatrice = :idmatrice, note = :note, dateexpiry = :dateexpiry, updated_at = NOW() WHERE id = :id AND idquotations = :idquotations"); $stmt->execute([ ':id' => $partId, ':part_number' => $partNumber, ':part_description' => $partDescription, ':mix' => $mix, ':idmatrice' => $idmatrice, ':note' => $note, ':dateexpiry' => $dateexpiry, ':idquotations' => $idquotations, ]); $results[] = [ 'part_id' => $partId, 'part_number' => $partNumber, 'message' => 'Parte aggiornata con successo' ]; } else if ($partDescription || $note || $dateexpiry) { // INSERT per nuova parte (solo se ha contenuto) $stmt = $pdo->prepare("INSERT INTO identification_parts (idquotations, part_number, part_description, mix, idmatrice, note, dateexpiry, created_at, updated_at) VALUES (:idquotations, :part_number, :part_description, :mix, :idmatrice, :note, :dateexpiry, NOW(), NOW())"); $stmt->execute([ ':idquotations' => $idquotations, ':part_number' => $partNumber, ':part_description' => $partDescription, ':mix' => $mix, ':idmatrice' => $idmatrice, ':note' => $note, ':dateexpiry' => $dateexpiry, ]); $newId = (int)$pdo->lastInsertId(); $results[] = [ 'part_id' => $newId, 'part_number' => $partNumber, 'message' => 'Parte salvata con successo' ]; } } $pdo->commit(); echo json_encode(['success' => true, 'results' => $results]); } catch (PDOException $e) { $pdo->rollBack(); echo json_encode(['success' => false, 'message' => 'Errore nel salvataggio: ' . $e->getMessage()]); }