Bound-state expansion method for calculating resonance and nonresonance contributions to continuum processes: Theoretical development and application to the photoionization of helium and the hydrogen negative ion