Yes, I know PHP is not the best (not even close) language to do this, but I just had to...
The code is not even close to be the best one, it was made with the first ideas that came in mind (probably the entire code could be better), but all I need is to make this work, and I do not have much time to think.