92 lines
2.6 KiB
PHP
92 lines
2.6 KiB
PHP
<?php
|
|
header('Content-Type: application/json');
|
|
|
|
ini_set('display_errors', 1);
|
|
error_reporting(E_ALL);
|
|
|
|
require_once(__DIR__ . '/include/headscript.php'); // Auth + $iduserlogin + DBHandlerSelect
|
|
|
|
try {
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
throw new Exception('Invalid request method');
|
|
}
|
|
|
|
$iddatadb = isset($_POST['iddatadb']) ? (int)$_POST['iddatadb'] : 0;
|
|
|
|
if ($iddatadb <= 0) {
|
|
throw new Exception('Missing iddatadb');
|
|
}
|
|
|
|
// ✅ Supporta sia singola stringa (con |) che array part_descriptions[]
|
|
$parts = [];
|
|
|
|
if (isset($_POST['part_descriptions']) && is_array($_POST['part_descriptions'])) {
|
|
$parts = $_POST['part_descriptions'];
|
|
} else {
|
|
$raw = isset($_POST['part_description']) ? (string)$_POST['part_description'] : '';
|
|
// split su "|" per multi-part
|
|
$parts = preg_split('/\s*\|\s*/', $raw);
|
|
}
|
|
|
|
// normalizza: trim + rimuovi vuoti + dedup
|
|
$cleanParts = [];
|
|
foreach ($parts as $p) {
|
|
$p = trim((string)$p);
|
|
if ($p === '') continue;
|
|
|
|
// limita lunghezza come da DB varchar(255)
|
|
if (mb_strlen($p) > 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;
|