Origin of the stability of two-dimensional perovskites: a first-principles study