More manipulations
For the second term, first note that
$$
\begin{align}
\sum_{p\neq q}a_p^{\dagger}a_q
=\sum_{p < q}a_p^{\dagger}a_q+\sum_{q < p}a_p^{\dagger}a_q
=\sum_{p < q}a_p^{\dagger}a_q+a_pa_q^{\dagger},
\tag{23}
\end{align}
$$
which we arrive at by swapping the indices \( p \) and \( q \) in the second sum and combining the sums. Applying the transformation
$$
\begin{align}
a_p^{\dagger}a_q+a_pa_q^{\dagger}
&=\left(\frac{X_p-iY_p}{2}\right)\left(\frac{X_q+iY_q}{2}\right)
\tag{24}\\
&+\left(\frac{X_p+iY_p}{2}\right)\left(\frac{X_q-iY_q}{2}\right)
\tag{25}\\
&=\frac{1}{2}\left(X_pX_q+Y_pY_q\right).
\tag{26}
\end{align}
$$