Shouldn't the bottom event send the item back to their assigned slot not a random slot? Otherwise what's the point in assigning the item's ID to the inventory slot?
Also what I mentioned above will not fix all the bugs but it will at least get the function to work. If the function doesn't work then it doesn't set a slot to occupied which is part of your logic.
You could also share the file and I can fix it, just tell me what the problem is.