You have 237 "{" and only 234 "}". I suspect there are some other errors, too, but I'm not going to wade through all of that code myself.
This is a good example of why you should try to modularize your code via the use of functions, classes, and/or include files rather than trying to cram everything into one "stream of consciousness" script. If you must do it this way, then you need to pay very careful attention to consistent formatting and indenting so that you can be sure everything is correct. (And when you find you have code with many layers of nested ifs/elses and loops, it should be a red flag to you that things need to be broken up into more atomic pieces that can be more easily debugged separately.)