library(dplyr)
library(haven)
library(psych)
library(PerformanceAnalytics)
library(corrplot)
library(Hmisc)
library(lavaan)
library(semTools)

CRS_dec <- read_sav("CRS_dec.sav") %>%
  filter(COUNTRY == 2 | COUNTRY ==  3) %>%
  select(starts_with("CRS_"), COUNTRY)

CRS_dec$COUNTRY = plyr::revalue(factor(CRS_dec$COUNTRY), c(
  `2` = "CH",
  `3` = "PL"
))

CRS_dec <- rename(CRS_dec, cntry = COUNTRY) %>%
  as.data.frame()

###DEFINING THE MODEL###

CRS_full_RW_withoutDIV2 <- 'agree =~ CRS_6 + CRS_9r + CRS_11r + CRS_15r
          close =~ CRS_2 + CRS_17 + CRS_24 + CRS_28r + CRS_30
          exp =~ CRS_31 + CRS_32 + CRS_33 + CRS_34 + CRS_35
          supp =~ CRS_3 + CRS_10 + CRS_19 + CRS_25 + CRS_26 + CRS_27
          und =~ CRS_8 + CRS_12 + CRS_13 + CRS_16 + CRS_21 + CRS_22
          par =~ CRS_1 + CRS_4 + CRS_7r + CRS_14 + CRS_18 + CRS_23 + CRS_29r
          RW =~ CRS_7r + CRS_9r +
          CRS_11r + CRS_15r + CRS_28r + CRS_29r + CRS_31 + CRS_32 + 
          CRS_33 + CRS_34 + CRS_35 +
          CRS_8 + CRS_12 + CRS_13 + CRS_16 + CRS_21 + CRS_22
RW ~~ 0*agree
RW ~~ 0*close
  RW ~~ 0*exp
  RW ~~ 0*supp
  RW ~~ 0*und
  RW ~~ 0*par'

###LEGEND###
# agree = Coparenting agreement
# close = Coparenting closeness
# exp = Exposure to conflict
# supp = Coparenting support
# und = 	Coparenting undermining	
# par = Endorsement partner’s parenting
# RW = Reverse worded items

###Measurement invariance: Poland-CH###

#Configural
cfa.config <- cfa(CRS_full_RW_withoutDIV2, data = CRS_dec, estimator = "MLR", group = "cntry")
summary(cfa.config, fit.measures = TRUE, standardized = TRUE)

#Metric

cfa.metric <- cfa(CRS_full_RW_withoutDIV2, data = CRS_dec, estimator = "MLR", group = "cntry", 
                  group.equal = "loadings")
summary(cfa.metric, fit.measures = TRUE, standardized = TRUE)

compareFit(cfa.config, cfa.metric)
summary(compareFit(cfa.config, cfa.metric))

#Scalar

cfa.scalar <- cfa(CRS_full_RW_withoutDIV2, data = CRS_dec, estimator = "MLR", group = "cntry", group.equal = c("loadings","intercepts"))
summary(cfa.scalar, fit.measures = TRUE, standardized = TRUE)

compareFit(cfa.metric, cfa.scalar)
summary(compareFit(cfa.metric, cfa.scalar))

#Strict

cfa.strict <- cfa(CRS_full_RW_withoutDIV2, data = CRS_dec, estimator = "MLR", group = "cntry", group.equal = c("loadings","intercepts", "residuals"))
summary(cfa.strict, fit.measures = TRUE, standardized = TRUE)

compareFit(cfa.scalar, cfa.strict)
summary(compareFit(cfa.scalar, cfa.strict))