54 lines
1.8 KiB
PHP
54 lines
1.8 KiB
PHP
<?php
|
|
|
|
require_once __DIR__ . '/auth_check.php';
|
|
|
|
mnt_require_permission('maintenance.manage');
|
|
|
|
try {
|
|
$pdo = mnt_pdo();
|
|
|
|
$id = (int)($_POST['id'] ?? 0);
|
|
$name = trim((string)($_POST['name'] ?? ''));
|
|
$code = trim((string)($_POST['code'] ?? ''));
|
|
$color = trim((string)($_POST['color'] ?? '#6c757d'));
|
|
$requiresLine = !empty($_POST['requires_line']) ? 1 : 0;
|
|
$sortOrder = (int)($_POST['sort_order'] ?? 999);
|
|
$isActive = !empty($_POST['is_active']) ? 1 : 0;
|
|
$description = trim((string)($_POST['description'] ?? ''));
|
|
|
|
if ($name === '') {
|
|
mnt_json_fail('Il nome è obbligatorio.');
|
|
}
|
|
if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $color)) {
|
|
$color = '#6c757d';
|
|
}
|
|
|
|
// name is UNIQUE — check first so the user gets a readable message
|
|
$stmt = $pdo->prepare("SELECT id FROM inv_categories WHERE name = ? AND id <> ?");
|
|
$stmt->execute([$name, $id]);
|
|
if ($stmt->fetchColumn()) {
|
|
mnt_json_fail('Esiste già una categoria con questo nome.');
|
|
}
|
|
|
|
if ($id > 0) {
|
|
$stmt = $pdo->prepare("
|
|
UPDATE inv_categories
|
|
SET name = ?, code = ?, color = ?, requires_line = ?, sort_order = ?, is_active = ?, description = ?
|
|
WHERE id = ?
|
|
");
|
|
$stmt->execute([$name, $code ?: null, $color, $requiresLine, $sortOrder, $isActive, $description ?: null, $id]);
|
|
|
|
mnt_json_ok(['id' => $id]);
|
|
}
|
|
|
|
$stmt = $pdo->prepare("
|
|
INSERT INTO inv_categories (name, code, color, requires_line, sort_order, is_active, description)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
");
|
|
$stmt->execute([$name, $code ?: null, $color, $requiresLine, $sortOrder, $isActive, $description ?: null]);
|
|
|
|
mnt_json_ok(['id' => (int)$pdo->lastInsertId()]);
|
|
} catch (Throwable $e) {
|
|
mnt_json_fail('Errore: ' . $e->getMessage());
|
|
}
|