Here’s how to post code on the forums: Using code tags properly (you can edit your post).
Nnobody can debug this for you in their heads so you’ll need to understand how to debug it yourself before coming to the forums and then, if you cannot find the issue, say what results you got from debugging it. You’ve added debug above but we have no idea what happens.
This stuff is pretty much always bad logic; something you can debug yourself. Put more debug.log in there to verify it’s doing what you expect it to be doing, don’t assume anything.
Thanks.