This was explained to me many years ago, by a physics teacher, with the following analogy:
"If someone on the beach wants to reach someone else that is in the water, they will try to travel as much as they can on the beach and as little as possible on the water, because this way they will get there faster."
I'm paraphrasing of course, but this is as accurate as I recall it.
This explanation makes no sense to me. Was he telling me the light knows where it is going? It wants to get there faster? It chooses a different direction?
(No need to answer these questions, this was just me trying to understand the analogy.)
My attempts to clarify the issue were without success and many years later I still don't know.
Why does light change direction when it travels through glass?