Files
trf_certest/public/userarea/update_mapping_flag.php
T
2026-07-01 12:19:11 +02:00

109 lines
3.2 KiB
PHP

<?php
header('Content-Type: application/json');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once(__DIR__ . '/class/db-functions.php');
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$data = json_decode(file_get_contents("php://input"), true);
if (!$data || !isset($data['id'], $data['field'])) {
echo json_encode(["success" => false, "message" => "Invalid or missing parameters"]);
exit;
}
$mappingId = (int)$data['id'];
$field = $data['field'];
$value = isset($data['value']) && $data['value'] ? 1 : 0;
// Whitelist rigorosa dei campi aggiornabili: evita SQL injection sul nome colonna
$allowedFields = ['main_field', 'is_visible_import', 'is_visible_parts'];
if (!in_array($field, $allowedFields, true)) {
echo json_encode(["success" => false, "message" => "Invalid field"]);
exit;
}
try {
// Recupero il template_id della riga per poter applicare i vincoli a livello di template
$stmt = $pdo->prepare("SELECT template_id FROM template_mapping WHERE id = ?");
$stmt->execute([$mappingId]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
echo json_encode(["success" => false, "message" => "Mapping not found"]);
exit;
}
$templateId = (int)$row['template_id'];
// Vincolo: max 2 righe con main_field = 1 per template
if ($field === 'main_field' && $value === 1) {
$stmt = $pdo->prepare("
SELECT COUNT(*)
FROM template_mapping
WHERE template_id = ? AND main_field = '1' AND id != ?
");
$stmt->execute([$templateId, $mappingId]);
$count = (int)$stmt->fetchColumn();
if ($count >= 2) {
echo json_encode([
"success" => false,
"limit_reached" => true,
"message" => "Massimo 2 campi Main consentiti per questo template"
]);
exit;
}
}
$pdo->beginTransaction();
$uncheckedOthers = false;
// Vincolo: solo 1 riga con is_visible_parts = 1 per template (comportamento radio)
if ($field === 'is_visible_parts' && $value === 1) {
$stmt = $pdo->prepare("
UPDATE template_mapping
SET is_visible_parts = 0
WHERE template_id = ? AND id != ? AND is_visible_parts = 1
");
$stmt->execute([$templateId, $mappingId]);
$uncheckedOthers = $stmt->rowCount() > 0;
}
$bindValue = ($field === 'main_field') ? (string)$value : $value;
$stmt = $pdo->prepare("UPDATE template_mapping SET {$field} = ? WHERE id = ?");
$result = $stmt->execute([$bindValue, $mappingId]);
if (!$result) {
$pdo->rollBack();
echo json_encode(["success" => false, "message" => "Database update failed"]);
exit;
}
$pdo->commit();
echo json_encode([
"success" => true,
"message" => "Flag updated successfully",
"unchecked_others" => $uncheckedOthers,
"saved" => [
"id" => $mappingId,
"field" => $field,
"value" => $value
]
]);
} catch (Throwable $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
echo json_encode(["success" => false, "message" => "Error: " . $e->getMessage()]);
}
exit;