Self-consistent Green-function method for the calculation of electronic properties of localized defects at surfaces and in the bulk