The answer is there in your question: Charles II was a Habsburg because he was descended from Philip of Castile, whose name is slightly misleading.
Philip was the son of Maximilian I, who was then Holy Roman Emperor and Archduke of Austria - and also a Habsburg. Philip was, however, married off to Joanna of Castile and eventually became King of Castile as a result. Thus, as dynastic ties ran through the male line, the royal Trastamara line was effectively ended in Spain with the accession of Charles I/V, and descendants of Philip up until Charles II were all part of the House of Habsburg.