#' Combined estimating equations: moment correction and phase function
#'
#' Constructs a stacked system of estimating equations combining
#' moment-corrected score equations and phase-function score equations.
#'
#' @param Wbar Numeric matrix of dimension \code{n x p} containing averaged
#'   error-prone covariates.
#' @param Zmat Numeric matrix of dimension \code{n x q} containing error-free
#'   covariates (including an intercept if required).
#' @param y Numeric vector of length \code{n} containing the response.
#' @param S_y Numeric vector containing precomputed sine terms for the phase
#'   function.
#' @param C_y Numeric vector containing precomputed cosine terms for the phase
#'   function.
#' @param b_in Numeric vector of length \code{p + q} at which the estimating
#'   equations are evaluated.
#' @param estWeight Numeric vector of weights used in the phase-function
#'   component.
#' @param estSigmaU_bar Numeric array of dimension \code{n x p x p} containing
#'   measurement error covariance estimates.
#' @param t Numeric vector of frequency values used in the phase function.
#'
#' @return Numeric vector containing the stacked estimating equations of length
#'   \code{2 * (p + q)}.
#'
#'
#'@keywords internal

estim_eq_correctedAndPhase <- function(
    Wbar, Zmat, y, S_y, C_y, b_in, estWeight, estSigmaU_bar, t
) {
  # Wbar          : n × p averaged error-prone covariates
  # Zmat          : n × q error-free covariates (incl. intercept)
  # y             : n × 1 response
  # estSigmaU_bar : n × p × p (NA for single-replicate obs)

  n <- length(y)
  p <- ncol(Wbar)
  q <- ncol(Zmat)

  ## Moment-corrected score function
  Score_moment = estim_eq_corrected(y, Wbar, Zmat, b_in, estSigmaU_bar)

  ## phase-function score
  S_phase <- PhaseGradient(b_in, S_y, C_y, cbind(Wbar, Zmat), t, estWeight)

  ## Stack equations
  E <- c(
    as.vector(Score_moment),
    as.vector(S_phase)
  )

  return(E)
}
