I wonder --- if you did a little "clean up", would the issues be easier to find?
For example, I see opening (<?php) and closing tags interspersed throughout. Unnecessary.
I don't see that you indented code blocks. Obviously, PHP could care less, but for humans like us, it's a Good Thing(tm).
So are comments, for that matter.