Electronic structure and magnetic coupling of pure and Mg-doped KCuF3