I noticed you have a variable $pages and a variable $page. Is there a typo?
I would suggest initializing all your variables before the if-statements, rather than on the last else or within each if-statement. Then you would just set values to the ones you needed later. That’s so you don’t lose track of what variables were created where and what default value they were assigned.