Most Helpful Guy
Seems like you already know what to do.
You have to tell Z about your feelings and act from there. If he likes you back then go for it. If you give up on Z now and just start going for M you may regret it in the future because the opportunity for "What could have been" is gone. If you feel like your hurt M, dont. He may be your friend but in situations like this YOUR happiness comes first.
However if Z does not like you back, give yourself some time and if you truly like M then go for him. Show him you truly like him and aren't just dating him because Z rejected you. You will have to figure that out yourself.
Best of luck!