# =============================================================================
# Supplementary Code
# Classroom Disruption and Teacher Workplace Well-Being in Uzbekistan:
# The Mediating Role of Behaviour-Related Stress in TALIS 2024
#
# This script reproduces all statistical results reported in the manuscript
# (Tables 3-6 and Table S1) from the OECD TALIS 2024 Uzbekistan teacher
# public-use file. It uses only base R (no external packages required).
#
# Data source: OECD TALIS 2024 Database (public-use file), filtered to
# CNTRY == "UZB", ISCED Level 2 teacher file (btgintt4.csv).
# https://www.oecd.org/en/data/datasets/talis-2024-database.html
#
# Coding directions used below (TT4G01, T4TYEXPTT) were verified against the
# official OECD TALIS 2024 Statistical Compendium and Codebook (Power BI
# dashboard) in August 2026: TT4G01 1 = Female, 2 = Male; T4TYEXPTT
# 1 = <=5 years, 2 = 6-10 years, 3 = 11-20 years, 4 = >20 years.
#
# Fay's BRR perturbation factor k = 0.5 is confirmed in the OECD TALIS 2024
# Technical Standards (GB(2023)11): "100 replicates are created for each
# Participant with a Fay factor of 0.5."
# =============================================================================

# ---- 0. Settings -----------------------------------------------------------
data_path <- "UZB_TALIS2024_mediation_subset.csv"  # adjust path as needed
G <- 100   # number of TALIS replicate weights (TRWGT1...TRWGT100)
k <- 0.5   # Fay perturbation factor (OECD, 2023, TALIS 2024 Technical Standards)

# Fay's BRR variance/SE function, used throughout:
#   Var(theta) = sum((theta_g - theta)^2) / (G * (1-k)^2)
brr_se <- function(full_est, rep_ests, k = 0.5, G = 100) {
  sqrt(sum((rep_ests - full_est)^2) / (G * (1 - k)^2))
}

# ---- 1. Load and clean data -------------------------------------------------
df <- read.csv(data_path, sep = ";", dec = ".", stringsAsFactors = FALSE)
cat("Rows loaded:", nrow(df), "\n")

miss_codes <- c(9998, 9999, 9997, 9996, 8888)  # TALIS missing-value codes
scale_vars <- c("T4CLSDIS", "T4STBEH", "T4WELS", "T4WLOADT", "T4JOBSAT",
                "T4JSENVT", "T4JSPROT", "T4SECLS", "T4CLASM")
for (v in scale_vars) {
  df[[v]] <- suppressWarnings(as.numeric(df[[v]]))
  df[[v]][df[[v]] %in% miss_codes] <- NA
}

# Gender (TT4G01): 1 = Female, 2 = Male (confirmed; see header note above)
df$gender <- suppressWarnings(as.numeric(df$TT4G01))
df$gender[df$gender == 9] <- NA
df$female <- ifelse(df$gender == 1, 1, ifelse(df$gender == 2, 0, NA))

# Teaching experience, grouped (T4TYEXPTT): higher code = more experience
# 1 = <=5 yrs, 2 = 6-10 yrs, 3 = 11-20 yrs, 4 = >20 yrs (confirmed; see header)
df$exp_grp <- suppressWarnings(as.numeric(df$T4TYEXPTT))
df$exp_grp[df$exp_grp == 9] <- NA

# =============================================================================
# TABLE 3. Unstandardized Path Coefficients for the Mediation Model (H1-H3)
# =============================================================================
needed <- c("T4CLSDIS", "T4STBEH", "T4WELS", "TCHWGT")
model_df <- df[stats::complete.cases(df[, needed]), ]
cat("\n[Table 3] Analytic N (complete X, M, Y, TCHWGT):", nrow(model_df), "\n")
# Expected: N ~ 1,466 (reduced sample size is due to TALIS's rotated
# questionnaire design; see manuscript Section 2.4)

mod_a <- lm(T4STBEH ~ T4CLSDIS,           data = model_df, weights = TCHWGT)
mod_b <- lm(T4WELS  ~ T4STBEH + T4CLSDIS, data = model_df, weights = TCHWGT)

a_hat  <- unname(coef(mod_a)["T4CLSDIS"])
b_hat  <- unname(coef(mod_b)["T4STBEH"])
cp_hat <- unname(coef(mod_b)["T4CLSDIS"])
indirect_hat <- a_hat * b_hat
total_hat    <- indirect_hat + cp_hat

# Fay's BRR replication across all 100 replicate weights
rep_a <- rep_b <- rep_cp <- numeric(G)
for (g in 1:G) {
  w_g <- model_df[[paste0("TRWGT", g)]]
  m_a_g <- lm(T4STBEH ~ T4CLSDIS,           data = model_df, weights = w_g)
  m_b_g <- lm(T4WELS  ~ T4STBEH + T4CLSDIS, data = model_df, weights = w_g)
  rep_a[g]  <- unname(coef(m_a_g)["T4CLSDIS"])
  rep_b[g]  <- unname(coef(m_b_g)["T4STBEH"])
  rep_cp[g] <- unname(coef(m_b_g)["T4CLSDIS"])
}
rep_indirect <- rep_a * rep_b

table3 <- data.frame(
  Path = c("a: Disruption -> Stress",
           "b: Stress -> Well-being",
           "c': Disruption -> Well-being (direct)",
           "a x b: Indirect effect"),
  b  = c(a_hat, b_hat, cp_hat, indirect_hat),
  SE = c(brr_se(a_hat, rep_a, k, G), brr_se(b_hat, rep_b, k, G),
         brr_se(cp_hat, rep_cp, k, G), brr_se(indirect_hat, rep_indirect, k, G))
)
table3$t  <- table3$b / table3$SE
table3$p  <- 2 * pnorm(-abs(table3$t))
table3$CI_low  <- table3$b - 1.96 * table3$SE
table3$CI_high <- table3$b + 1.96 * table3$SE

cat("\n===== TABLE 3: Main mediation model (H1-H3) =====\n")
print(round(table3[, -1], 4)); print(table3$Path)
cat(sprintf("Indirect effect mediated share: %.1f%%\n", 100 * indirect_hat / total_hat))
write.csv(table3, "Table3_main_mediation_model.csv", row.names = FALSE)

# =============================================================================
# TABLE 4. Mediation Path Coefficients Controlling for Gender, Experience,
#          and Self-Efficacy (robustness check)
# =============================================================================
needed_full <- c("T4CLSDIS", "T4STBEH", "T4WELS", "T4SECLS", "female",
                  "exp_grp", "TCHWGT")
model_df_full <- df[stats::complete.cases(df[, needed_full]), ]
cat("\n[Table 4] Analytic N (with covariates):", nrow(model_df_full), "\n")

mod_a_full <- lm(T4STBEH ~ T4CLSDIS + female + exp_grp + T4SECLS,
                  data = model_df_full, weights = TCHWGT)
mod_b_full <- lm(T4WELS ~ T4STBEH + T4CLSDIS + female + exp_grp + T4SECLS,
                  data = model_df_full, weights = TCHWGT)

a_full  <- unname(coef(mod_a_full)["T4CLSDIS"])
b_full  <- unname(coef(mod_b_full)["T4STBEH"])
cp_full <- unname(coef(mod_b_full)["T4CLSDIS"])
indirect_full <- a_full * b_full

rep_a_full <- rep_b_full <- rep_cp_full <- numeric(G)
for (g in 1:G) {
  w_g <- model_df_full[[paste0("TRWGT", g)]]
  m_a_g <- lm(T4STBEH ~ T4CLSDIS + female + exp_grp + T4SECLS,
              data = model_df_full, weights = w_g)
  m_b_g <- lm(T4WELS ~ T4STBEH + T4CLSDIS + female + exp_grp + T4SECLS,
              data = model_df_full, weights = w_g)
  rep_a_full[g]  <- unname(coef(m_a_g)["T4CLSDIS"])
  rep_b_full[g]  <- unname(coef(m_b_g)["T4STBEH"])
  rep_cp_full[g] <- unname(coef(m_b_g)["T4CLSDIS"])
}
rep_indirect_full <- rep_a_full * rep_b_full

table4 <- data.frame(
  Path = c("a (controlled)", "b (controlled)", "c' (controlled)",
           "a x b (controlled)"),
  b  = c(a_full, b_full, cp_full, indirect_full),
  SE = c(brr_se(a_full, rep_a_full, k, G), brr_se(b_full, rep_b_full, k, G),
         brr_se(cp_full, rep_cp_full, k, G),
         brr_se(indirect_full, rep_indirect_full, k, G))
)
table4$t <- table4$b / table4$SE
table4$p <- 2 * pnorm(-abs(table4$t))
table4$CI_low  <- table4$b - 1.96 * table4$SE
table4$CI_high <- table4$b + 1.96 * table4$SE

cat("\n===== TABLE 4: Robustness check with covariates =====\n")
print(round(table4[, -1], 4)); print(table4$Path)
write.csv(table4, "Table4_robustness_covariates.csv", row.names = FALSE)

# =============================================================================
# TABLE 5. Tests of Moderation on the Disruption-Stress Association
#          (H4a: self-efficacy; H4b: experience)
# =============================================================================
model_df_full$secls_c <- model_df_full$T4SECLS - mean(model_df_full$T4SECLS)
model_df_full$exp_c   <- model_df_full$exp_grp  - mean(model_df_full$exp_grp)

# H4a: Disruption x Self-efficacy -> Stress
mod_a_mod <- lm(T4STBEH ~ T4CLSDIS * secls_c + female + exp_grp,
                 data = model_df_full, weights = TCHWGT)
inter_se_coef <- unname(coef(mod_a_mod)["T4CLSDIS:secls_c"])

# H4b: Disruption x Experience -> Stress
mod_a_exp <- lm(T4STBEH ~ T4CLSDIS * exp_c + female + T4SECLS,
                 data = model_df_full, weights = TCHWGT)
inter_exp_coef <- unname(coef(mod_a_exp)["T4CLSDIS:exp_c"])

rep_inter_se <- rep_inter_exp <- numeric(G)
for (g in 1:G) {
  w_g <- model_df_full[[paste0("TRWGT", g)]]
  m_se_g  <- lm(T4STBEH ~ T4CLSDIS * secls_c + female + exp_grp,
                data = model_df_full, weights = w_g)
  m_exp_g <- lm(T4STBEH ~ T4CLSDIS * exp_c + female + T4SECLS,
                data = model_df_full, weights = w_g)
  rep_inter_se[g]  <- unname(coef(m_se_g)["T4CLSDIS:secls_c"])
  rep_inter_exp[g] <- unname(coef(m_exp_g)["T4CLSDIS:exp_c"])
}

table5 <- data.frame(
  Interaction = c("H4a: Disruption x Self-efficacy -> Stress",
                  "H4b: Disruption x Experience -> Stress"),
  b  = c(inter_se_coef, inter_exp_coef),
  SE = c(brr_se(inter_se_coef, rep_inter_se, k, G),
         brr_se(inter_exp_coef, rep_inter_exp, k, G))
)
table5$t <- table5$b / table5$SE
table5$p <- 2 * pnorm(-abs(table5$t))
table5$CI_low  <- table5$b - 1.96 * table5$SE
table5$CI_high <- table5$b + 1.96 * table5$SE

cat("\n===== TABLE 5: Moderation tests (H4a, H4b) =====\n")
print(round(table5[, -1], 4)); print(table5$Interaction)
write.csv(table5, "Table5_moderation_tests.csv", row.names = FALSE)

# =============================================================================
# TABLE S1 (Supplementary). Indirect Effect by Teaching-Experience Group
# (descriptive only; interaction test in Table 5 was non-significant)
# =============================================================================
cat("\n===== TABLE S1: Indirect effect by experience group (descriptive) =====\n")
tableS1 <- data.frame(exp_grp = sort(unique(model_df_full$exp_grp)),
                       n = NA, a = NA, b = NA, indirect = NA)
for (i in seq_len(nrow(tableS1))) {
  eg  <- tableS1$exp_grp[i]
  sub <- model_df_full[model_df_full$exp_grp == eg, ]
  if (nrow(sub) < 30) next   # minimum-cell-size rule
  m_a <- lm(T4STBEH ~ T4CLSDIS,           data = sub, weights = TCHWGT)
  m_b <- lm(T4WELS  ~ T4STBEH + T4CLSDIS, data = sub, weights = TCHWGT)
  a_i <- unname(coef(m_a)["T4CLSDIS"])
  b_i <- unname(coef(m_b)["T4STBEH"])
  tableS1[i, c("n", "a", "b", "indirect")] <- c(nrow(sub), a_i, b_i, a_i * b_i)
}
print(tableS1)
write.csv(tableS1, "TableS1_experience_group_breakdown.csv", row.names = FALSE)

cat("\nAll tables reproduced and saved as CSV files.\n")
