Origin of the half-metallic properties of graphitic carbon nitride in bulk and confined forms