60 lines
1.9 KiB
PHP
60 lines
1.9 KiB
PHP
<?php
|
|
require_once(__DIR__ . '/../../ajax/auth_check.php');
|
|
header('Content-Type: application/json');
|
|
require_once(__DIR__ . '/../../../class/db-functions.php');
|
|
|
|
try {
|
|
$db = DBHandlerSelect::getInstance();
|
|
$pdo = $db->getConnection();
|
|
|
|
$id = isset($_POST['id']) && is_numeric($_POST['id']) ? (int)$_POST['id'] : null;
|
|
$name = trim($_POST['name'] ?? '');
|
|
$color = trim($_POST['color'] ?? '');
|
|
|
|
if ($name === '') {
|
|
echo json_encode(['success' => false, 'message' => 'Il nome è obbligatorio.']);
|
|
exit;
|
|
}
|
|
if (mb_strlen($name) > 100) {
|
|
echo json_encode(['success' => false, 'message' => 'Il nome supera 100 caratteri.']);
|
|
exit;
|
|
}
|
|
if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $color)) {
|
|
$color = '#6c757d';
|
|
}
|
|
|
|
// Uniqueness check
|
|
if ($id) {
|
|
$stmt = $pdo->prepare("SELECT id FROM scad_subjects WHERE name = ? AND id <> ?");
|
|
$stmt->execute([$name, $id]);
|
|
} else {
|
|
$stmt = $pdo->prepare("SELECT id FROM scad_subjects WHERE name = ?");
|
|
$stmt->execute([$name]);
|
|
}
|
|
if ($stmt->fetch()) {
|
|
echo json_encode(['success' => false, 'message' => 'Esiste già un argomento con questo nome.']);
|
|
exit;
|
|
}
|
|
|
|
if ($id) {
|
|
$stmt = $pdo->prepare("UPDATE scad_subjects SET name = ?, color = ? WHERE id = ?");
|
|
$stmt->execute([$name, $color, $id]);
|
|
$savedId = $id;
|
|
} else {
|
|
$stmt = $pdo->prepare("INSERT INTO scad_subjects (name, color) VALUES (?, ?)");
|
|
$stmt->execute([$name, $color]);
|
|
$savedId = (int)$pdo->lastInsertId();
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => $id ? 'Argomento aggiornato.' : 'Argomento creato.',
|
|
'id' => $savedId,
|
|
'name' => $name,
|
|
'color' => $color,
|
|
]);
|
|
|
|
} catch (Exception $e) {
|
|
echo json_encode(['success' => false, 'message' => 'Errore: ' . $e->getMessage()]);
|
|
}
|