255) { $p = mb_substr($p, 0, 255); } $cleanParts[] = $p; } $cleanParts = array_values(array_unique($cleanParts)); if (count($cleanParts) === 0) { throw new Exception('Part description is empty'); } $db = DBHandlerSelect::getInstance(); $pdo = $db->getConnection(); $pdo->beginTransaction(); try { // prende il prossimo part_number per iddatadb $stmtMax = $pdo->prepare("SELECT COALESCE(MAX(part_number), 0) AS maxnum FROM identification_parts WHERE iddatadb = ?"); $stmtMax->execute([$iddatadb]); $nextNumber = (int)$stmtMax->fetchColumn() + 1; $stmtIns = $pdo->prepare(" INSERT INTO identification_parts (iddatadb, part_number, part_description) VALUES (?, ?, ?) "); $insertedIds = []; foreach ($cleanParts as $p) { $ok = $stmtIns->execute([$iddatadb, $nextNumber, $p]); if (!$ok) { throw new Exception('Insert failed'); } $insertedIds[] = $pdo->lastInsertId(); $nextNumber++; } $pdo->commit(); echo json_encode([ 'success' => true, 'message' => 'Parts added', 'count' => count($insertedIds), 'ids' => $insertedIds ]); } catch (Exception $e) { if ($pdo->inTransaction()) $pdo->rollBack(); throw $e; } } catch (Exception $e) { echo json_encode(['success' => false, 'message' => $e->getMessage()]); } exit;