on the other hand this would have been worth nothing in such an undemocratic matter ...
I find that notion odd. Yes, Erdogan won the last election... after systematically silencing the opposition and dissenting voices in the media. So the democratic legitimacy of his government seems dubious, at best.
Anyways, as a laiman it seems that the coup attempt was not particularly well thought out - the time it began, the fact that they didn't start with arresting Erdogan and shutting down the media, etc.
I can see a few reasons why it might have gone that way. Either they were naive and genuinely thought their plan would be sufficient, or they knew they were in a suboptimal position but still decided to go ahead, e.g. because they thought their position would only become worse going forward.
But I also wouldn't be surprised if Erdogan used his intelligence apparatus to identify the dissenting elements within the military, and goaded them into action. I know, sounds like a conspiracy theory, but he is looking to profit from this immensely. Support both nationally and internationally surged, and he will have carte blanche to weed out any remaining dissenting elements within the military now, something he's already started doing in the past. After all, nobody will challenge him on that in the wake of a coup attempt.
Because of that, this was likely the only chance for the military to challenge Erdogan's rule. Erdogan will have known this too, and even after his past efforts to get the military on his side, he must have known that a military coup was still a real possibility. So I don't think it's very far fetched that he would try and provoke such a coup attempt in a situation where he has the advantage. Which on the surface of it, seems to be pretty much what has happened.