A first principles theory of magnetocrystalline anisotropy in metals