Photochemistry in the inner layers of clumpy circumstellar envelopes: formation of water in C-rich objects and of C-bearing molecules in O-rich objects