Many-body theory of magnetism for ions with complicated level structure