$code ?: null, 'title' => $title, 'description' => $description ?: null, 'intervention_type' => $interventionType, 'execution_type' => $executionType, 'is_critical' => $isCritical, 'frequency_value' => $frequencyValue, 'frequency_unit' => $frequencyUnit, 'frequency_note' => $frequencyNote ?: null, 'alert_days' => max(0, $alertDays), 'assignee_employee_id' => $assigneeId ?: null, 'supervisor_employee_id' => $supervisorId ?: null, 'supplier_id' => $supplierId ?: null, 'is_active' => $isActive, 'notes' => $notes ?: null, ]; if ($id > 0) { $stmt = $pdo->prepare("SELECT equipment_id FROM maint_maintenances WHERE id = ?"); $stmt->execute([$id]); $equipmentId = (int)$stmt->fetchColumn(); if (!$equipmentId) { mnt_json_fail('Manutenzione non trovata.'); } $assignments = []; foreach (array_keys($values) as $column) { $assignments[] = "$column = :$column"; } $stmt = $pdo->prepare("UPDATE maint_maintenances SET " . implode(', ', $assignments) . " WHERE id = :id"); $stmt->execute($values + ['id' => $id]); // frequency may have changed — the due date must follow mnt_recalc_maintenance($pdo, $id); mnt_log($pdo, 'maintenance_updated', $equipmentId, $id, null, $currentUserId, $values); mnt_json_ok(['id' => $id]); } if ($equipmentId <= 0) { mnt_json_fail('Attrezzatura non valida.'); } $stmt = $pdo->prepare("SELECT id FROM inv_equipment WHERE id = ?"); $stmt->execute([$equipmentId]); if (!$stmt->fetchColumn()) { mnt_json_fail('Attrezzatura non trovata.'); } $values['equipment_id'] = $equipmentId; $values['created_by'] = $currentUserId; $columns = array_keys($values); $placeholders = array_map(fn($column) => ':' . $column, $columns); $stmt = $pdo->prepare( "INSERT INTO maint_maintenances (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $placeholders) . ")" ); $stmt->execute($values); $newId = (int)$pdo->lastInsertId(); mnt_log($pdo, 'maintenance_created', $equipmentId, $newId, null, $currentUserId, $values); mnt_json_ok(['id' => $newId]); } catch (Throwable $e) { mnt_json_fail('Errore: ' . $e->getMessage()); }