Your code is failing because the first term is the parent term, caused by checking both the parent and the child term.
You dont need to do that, if I have a heirarchy A->B->C->post, and I add the post to the C category, it’s automatically a part of its parents