Plants contain a wide variety of compounds, some are useful to the plant, some are not. Not everything had to have a use. If a gene mutation in a plant causes it to secrete, say, salicilic acid (willow bark) as long as it has no harmful effect on the plant the offspring will also have that chemical. Given the thousands of possible chemicals, the fact that a few dozen of them have medicinal effects on humans seems unremarkable.
Certain plant compounds contain enzymes that have a beneficial effect when extracted from the organism. Aboriginals, through trial and error, used these plants for homeopathic cures and scientist improved on it or synthesized the compounds, (Amazon Rainforest is one big pharmacy).