'inv_equipment_files', 'maintenance' => 'maint_maintenance_files', 'intervention' => 'maint_intervention_files', ]; if (!isset($tables[$scope])) { mnt_json_fail('Scope non valido.'); } if ($id <= 0) { mnt_json_fail('ID non valido.'); } $stmt = $pdo->prepare("SELECT * FROM {$tables[$scope]} WHERE id = ?"); $stmt->execute([$id]); $file = $stmt->fetch(PDO::FETCH_ASSOC); if (!$file) { mnt_json_fail('File non trovato.'); } // Clear the cover reference first — the FK would block the delete if ($scope === 'equipment') { $pdo->prepare("UPDATE inv_equipment SET cover_file_id = NULL WHERE cover_file_id = ?")->execute([$id]); } $pdo->prepare("DELETE FROM {$tables[$scope]} WHERE id = ?")->execute([$id]); mnt_delete_stored_file((string)$file['stored_name']); mnt_log( $pdo, 'file_deleted', $scope === 'equipment' ? (int)$file['equipment_id'] : null, $scope === 'maintenance' ? (int)$file['maintenance_id'] : null, $scope === 'intervention' ? (int)$file['intervention_id'] : null, $currentUserId, null, (string)$file['original_name'] ); mnt_json_ok(); } catch (Throwable $e) { mnt_json_fail('Errore: ' . $e->getMessage()); }