# =============================================================================
# KARANGURA CFCT BASELINE
# PAPER 1 ANALYSIS SCRIPT
#
# Manuscript:
# Household Water Sources, Drinking-Water Treatment and Diarrhoeal Illness
# in Karangura Sub-County, Uganda:
# Implications for Safe Water Governance and Public Health
#
# Purpose:
#   Generate the analysis outputs, tables, figures, model results and draft
#   manuscript for Paper 1 of the Karangura BMC Public Health six-paper package.
#
# Input:
#   Master cleaned dataset created by:
#   Karangura_BMC_6_Papers_Master_Analysis_Script_MEMORY_SAFE.R
#
# Main input expected:
#   C:/Users/Stephen/Documents/Researches/Karangura_BMC_6_Papers/
#     Karangura_BMC_6_Paper_Sprint/
#       00_Master_Dataset/Karangura_BMC_master_cleaned_household_dataset.csv
#
# Outputs:
#   1. Paper 1 analysis dataset
#   2. Publication-ready Excel workbook
#   3. Figures
#   4. Draft Word manuscript
#   5. RDS analysis objects
#
# Author: Olet Stephen Charles
# =============================================================================


# -----------------------------------------------------------------------------
# 0. CLEAN SESSION AND LOAD PACKAGES
# -----------------------------------------------------------------------------

rm(list = ls())
gc()

required_packages <- c(
  "tidyverse", "janitor", "openxlsx", "flextable", "officer",
  "broom", "sandwich", "lmtest", "scales", "stringr", "forcats"
)

new_packages <- required_packages[!required_packages %in% installed.packages()[, "Package"]]

if (length(new_packages) > 0) {
  install.packages(new_packages, dependencies = TRUE)
}

suppressPackageStartupMessages({
  library(tidyverse)
  library(janitor)
  library(openxlsx)
  library(flextable)
  library(officer)
  library(broom)
  library(sandwich)
  library(lmtest)
  library(scales)
  library(stringr)
  library(forcats)
})


# -----------------------------------------------------------------------------
# 1. USER SETTINGS
# -----------------------------------------------------------------------------
# Folder seen in your screenshot:
# C:/Users/Stephen/Documents/Researches/Karangura Papers/01_Paper_Water_Treatment_Diarrhoea
#
# The master cleaned dataset and this R script are inside the same paper folder.

project_root <- "C:/Users/Stephen/Documents/Researches/Karangura Papers"

paper_dir <- file.path(
  project_root,
  "01_Paper_Water_Treatment_Diarrhoea"
)

master_csv <- file.path(
  paper_dir,
  "Karangura_BMC_master_cleaned_household_dataset.csv"
)

# Fallback, in case Windows/R reads the copied CSV with a slightly different name.
if (!file.exists(master_csv)) {
  possible_master_files <- list.files(
    paper_dir,
    pattern = "Karangura_BMC_master_cleaned_household_dataset.*\\.csv$|Karangura_BMC_master_cleaned_household_dataset$",
    full.names = TRUE,
    ignore.case = TRUE
  )

  if (length(possible_master_files) > 0) {
    master_csv <- possible_master_files[1]
  }
}

# All outputs will be kept inside one dedicated output folder within the working folder.
# This avoids mixing generated outputs with the input dataset and R script.
output_dir <- file.path(
  paper_dir,
  paste0("Paper1_Outputs_", format(Sys.Date(), "%Y%m%d"))
)

tables_dir <- file.path(output_dir, "Tables")
figures_dir <- file.path(output_dir, "Figures")
manuscript_dir <- file.path(output_dir, "Manuscript")
objects_dir <- file.path(output_dir, "R_objects")
logs_dir <- file.path(output_dir, "Logs")

purrr::walk(
  c(paper_dir, tables_dir, figures_dir, manuscript_dir, objects_dir, logs_dir),
  ~ dir.create(.x, recursive = TRUE, showWarnings = FALSE)
)

if (!file.exists(master_csv)) {
  stop(
    "Master cleaned dataset was not found at:\n", master_csv,
    "\nRun the memory-safe master script first, or update master_csv in Section 1."
  )
}


# -----------------------------------------------------------------------------
# 2. HELPER FUNCTIONS
# -----------------------------------------------------------------------------

safe_mean <- function(x) {
  if (all(is.na(x))) return(NA_real_)
  mean(x, na.rm = TRUE)
}

safe_sd <- function(x) {
  if (sum(!is.na(x)) <= 1) return(NA_real_)
  sd(x, na.rm = TRUE)
}

fmt_n_pct <- function(n, denom, digits = 1) {
  ifelse(
    is.na(n) | is.na(denom) | denom == 0,
    NA_character_,
    paste0(n, " (", round(100 * n / denom, digits), "%)")
  )
}

fmt_pct <- function(x, digits = 1) {
  ifelse(is.na(x), NA_character_, paste0(round(x, digits), "%"))
}

fmt_num <- function(x, digits = 2) {
  ifelse(
    is.na(x),
    NA_character_,
    formatC(x, format = "f", digits = digits, big.mark = ",")
  )
}

fmt_p <- function(p) {
  case_when(
    is.na(p) ~ NA_character_,
    p < 0.001 ~ "<0.001",
    TRUE ~ formatC(p, format = "f", digits = 3)
  )
}

binary_label <- function(x) {
  case_when(
    x == 1 ~ "Yes",
    x == 0 ~ "No",
    TRUE ~ NA_character_
  )
}

safe_chisq_p <- function(x, y) {
  tab <- table(x, y, useNA = "no")

  if (nrow(tab) < 2 | ncol(tab) < 2) {
    return(NA_real_)
  }

  out <- tryCatch(
    suppressWarnings(chisq.test(tab)$p.value),
    error = function(e) NA_real_
  )

  out
}

make_binary_distribution <- function(data, vars, labels) {
  map2_dfr(vars, labels, function(v, lab) {
    if (!v %in% names(data)) {
      return(tibble(
        variable = v,
        indicator = lab,
        denominator = NA_integer_,
        yes_n = NA_integer_,
        yes_percent = NA_real_,
        display = NA_character_
      ))
    }

    x <- data[[v]]
    denom <- sum(!is.na(x))
    yes_n <- sum(x == 1, na.rm = TRUE)

    tibble(
      variable = v,
      indicator = lab,
      denominator = denom,
      yes_n = yes_n,
      yes_percent = round(100 * yes_n / denom, 1),
      display = fmt_n_pct(yes_n, denom)
    )
  })
}

make_outcome_by_exposure <- function(data, outcome, outcome_label, exposure, exposure_label) {
  if (!all(c(outcome, exposure) %in% names(data))) {
    return(tibble())
  }

  model_data <- data %>%
    select(all_of(c(outcome, exposure))) %>%
    filter(!is.na(.data[[outcome]]), !is.na(.data[[exposure]])) %>%
    mutate(
      exposure_group = binary_label(.data[[exposure]])
    )

  p <- safe_chisq_p(model_data[[exposure]], model_data[[outcome]])

  model_data %>%
    group_by(exposure_group) %>%
    summarise(
      denominator = n(),
      outcome_yes_n = sum(.data[[outcome]] == 1, na.rm = TRUE),
      outcome_percent = round(100 * outcome_yes_n / denominator, 1),
      .groups = "drop"
    ) %>%
    mutate(
      outcome = outcome_label,
      exposure = exposure_label,
      display = fmt_n_pct(outcome_yes_n, denominator),
      p_value = p,
      p_value_display = fmt_p(p)
    ) %>%
    select(
      outcome, exposure, exposure_group,
      denominator, outcome_yes_n, outcome_percent, display,
      p_value, p_value_display
    )
}

modified_poisson <- function(data, outcome, exposures, covariates = NULL, model_label = "Model") {
  all_vars <- c(outcome, exposures, covariates)
  all_vars <- all_vars[all_vars %in% names(data)]

  model_data <- data %>%
    select(all_of(all_vars)) %>%
    drop_na()

  if (nrow(model_data) < 30) {
    return(tibble(
      model = model_label,
      outcome = outcome,
      term = NA_character_,
      prevalence_ratio = NA_real_,
      conf_low = NA_real_,
      conf_high = NA_real_,
      p_value = NA_real_,
      p_value_display = NA_character_,
      pr_ci = NA_character_,
      complete_case_n = nrow(model_data),
      note = "Model not run: fewer than 30 complete observations"
    ))
  }

  if (length(unique(model_data[[outcome]])) < 2) {
    return(tibble(
      model = model_label,
      outcome = outcome,
      term = NA_character_,
      prevalence_ratio = NA_real_,
      conf_low = NA_real_,
      conf_high = NA_real_,
      p_value = NA_real_,
      p_value_display = NA_character_,
      pr_ci = NA_character_,
      complete_case_n = nrow(model_data),
      note = "Model not run: outcome has no variation"
    ))
  }

  rhs <- paste(c(exposures, covariates), collapse = " + ")
  f <- as.formula(paste(outcome, "~", rhs))

  fit <- tryCatch(
    glm(f, family = poisson(link = "log"), data = model_data),
    error = function(e) e
  )

  if (inherits(fit, "error")) {
    return(tibble(
      model = model_label,
      outcome = outcome,
      term = NA_character_,
      prevalence_ratio = NA_real_,
      conf_low = NA_real_,
      conf_high = NA_real_,
      p_value = NA_real_,
      p_value_display = NA_character_,
      pr_ci = NA_character_,
      complete_case_n = nrow(model_data),
      note = paste("Model failed:", fit$message)
    ))
  }

  robust <- lmtest::coeftest(fit, vcov. = sandwich::vcovHC(fit, type = "HC0"))

  broom::tidy(robust) %>%
    filter(term != "(Intercept)") %>%
    mutate(
      model = model_label,
      outcome = outcome,
      prevalence_ratio = exp(estimate),
      conf_low = exp(estimate - 1.96 * std.error),
      conf_high = exp(estimate + 1.96 * std.error),
      p_value = p.value,
      p_value_display = fmt_p(p_value),
      pr_ci = paste0(fmt_num(prevalence_ratio, 2), " (", fmt_num(conf_low, 2), "-", fmt_num(conf_high, 2), ")"),
      complete_case_n = nrow(model_data),
      note = "Modified Poisson regression with robust standard errors"
    ) %>%
    select(
      model, outcome, term, prevalence_ratio, conf_low, conf_high,
      p_value, p_value_display, pr_ci, complete_case_n, note
    )
}


# -----------------------------------------------------------------------------
# 3. LOAD AND PREPARE PAPER 1 DATASET
# -----------------------------------------------------------------------------

master <- read_csv(master_csv, show_col_types = FALSE) %>%
  clean_names()

paper1_data <- master %>%
  filter(paper1_water_treatment_diarrhea_eligible == 1) %>%
  mutate(
    parish = as.factor(parish),
    respondent_age_group = as.factor(respondent_age_group),
    asset_tertile_label = factor(
      asset_tertile_label,
      levels = c("Lowest asset tertile", "Middle asset tertile", "Highest asset tertile")
    ),
    high_risk_water_source_label = binary_label(high_risk_water_source_any),
    improved_water_source_label = binary_label(improved_water_source_any),
    treats_drinking_water_label = binary_label(treats_drinking_water),
    regular_water_treatment_label = binary_label(regular_water_treatment),
    improved_sanitation_label = binary_label(improved_sanitation),
    handwashing_label = binary_label(handwashing_with_soap_regular),
    household_diarrhea_recent_label = binary_label(household_diarrhea_recent),
    under5_diarrhea_any_label = binary_label(under5_diarrhea_any_combined)
  )

analysis_dataset_csv <- file.path(paper_dir, "paper1_water_treatment_diarrhoea_analysis_dataset.csv")
write_csv(paper1_data, analysis_dataset_csv)


# -----------------------------------------------------------------------------
# 4. SAMPLE CHARACTERISTICS
# -----------------------------------------------------------------------------

sample_size <- nrow(paper1_data)

sample_summary <- tibble(
  characteristic = c(
    "Households included in Paper 1 analysis",
    "Households with recent household diarrhoea outcome available",
    "Households with under-five diarrhoea outcome available",
    "Mean respondent age",
    "Female respondents",
    "Households with orphanhood vulnerability",
    "Households with disability vulnerability",
    "Vulnerable households, orphanhood or disability",
    "Households in lowest asset tertile",
    "Households with under-five children in roster"
  ),
  value = c(
    as.character(sample_size),
    as.character(sum(!is.na(paper1_data$household_diarrhea_recent))),
    as.character(sum(!is.na(paper1_data$under5_diarrhea_any_combined))),
    paste0(fmt_num(safe_mean(paper1_data$respondent_age), 1), " ± ", fmt_num(safe_sd(paper1_data$respondent_age), 1)),
    fmt_n_pct(sum(paper1_data$respondent_female == 1, na.rm = TRUE), sum(!is.na(paper1_data$respondent_female))),
    fmt_n_pct(sum(paper1_data$orphan_household == 1, na.rm = TRUE), sum(!is.na(paper1_data$orphan_household))),
    fmt_n_pct(sum(paper1_data$disability_household == 1, na.rm = TRUE), sum(!is.na(paper1_data$disability_household))),
    fmt_n_pct(sum(paper1_data$vulnerable_household == 1, na.rm = TRUE), sum(!is.na(paper1_data$vulnerable_household))),
    fmt_n_pct(sum(paper1_data$asset_tertile_label == "Lowest asset tertile", na.rm = TRUE), sum(!is.na(paper1_data$asset_tertile_label))),
    fmt_n_pct(sum(paper1_data$hh_under5_members_n > 0, na.rm = TRUE), sum(!is.na(paper1_data$hh_under5_members_n)))
  )
)

parish_distribution <- paper1_data %>%
  count(parish, name = "households_n") %>%
  mutate(
    percent = round(100 * households_n / sum(households_n), 1),
    display = fmt_n_pct(households_n, sum(households_n))
  ) %>%
  arrange(desc(households_n))

asset_distribution <- paper1_data %>%
  count(asset_tertile_label, name = "households_n") %>%
  mutate(
    percent = round(100 * households_n / sum(households_n), 1),
    display = fmt_n_pct(households_n, sum(households_n))
  )


# -----------------------------------------------------------------------------
# 5. WASH AND DIARRHOEA DESCRIPTIVE RESULTS
# -----------------------------------------------------------------------------

wash_indicators <- make_binary_distribution(
  paper1_data,
  vars = c(
    "improved_water_source_any",
    "unimproved_water_source_any",
    "improved_water_source_only",
    "high_risk_water_source_any",
    "treats_drinking_water",
    "regular_water_treatment",
    "improved_sanitation",
    "no_sanitation_facility",
    "handwashing_with_soap_regular",
    "high_wash_risk"
  ),
  labels = c(
    "Any improved water source",
    "Any unimproved or high-risk water source",
    "Improved water source only",
    "Any high-risk water source",
    "Treats drinking water",
    "Regular drinking-water treatment",
    "Improved sanitation",
    "No sanitation facility",
    "Regular handwashing with soap",
    "High WASH risk"
  )
)

diarrhea_outcomes <- make_binary_distribution(
  paper1_data,
  vars = c(
    "household_diarrhea_recent",
    "under5_diarrhea_any_combined"
  ),
  labels = c(
    "Recent household diarrhoea",
    "Under-five diarrhoea"
  )
)

diarrhea_prevention <- make_binary_distribution(
  paper1_data,
  vars = c(
    "diarrhea_prevention_ors",
    "diarrhea_prevention_clean_water",
    "diarrhea_prevention_improved_sanitation",
    "diarrhea_prevention_handwashing_soap",
    "diarrhea_prevention_breastfeeding",
    "diarrhea_prevention_zinc"
  ),
  labels = c(
    "ORS used for prevention or management",
    "Clean drinking water reported as prevention measure",
    "Improved sanitation reported as prevention measure",
    "Handwashing with soap reported as prevention measure",
    "Breastfeeding reported as prevention measure",
    "Zinc supplementation reported as prevention measure"
  )
)

wash_risk_distribution <- paper1_data %>%
  count(wash_risk_score, name = "households_n") %>%
  mutate(
    percent = round(100 * households_n / sum(households_n), 1),
    display = fmt_n_pct(households_n, sum(households_n))
  ) %>%
  arrange(wash_risk_score)

wash_by_parish <- paper1_data %>%
  group_by(parish) %>%
  summarise(
    households_n = n(),
    high_risk_water_source_percent = round(100 * mean(high_risk_water_source_any == 1, na.rm = TRUE), 1),
    treats_drinking_water_percent = round(100 * mean(treats_drinking_water == 1, na.rm = TRUE), 1),
    regular_water_treatment_percent = round(100 * mean(regular_water_treatment == 1, na.rm = TRUE), 1),
    improved_sanitation_percent = round(100 * mean(improved_sanitation == 1, na.rm = TRUE), 1),
    regular_handwashing_percent = round(100 * mean(handwashing_with_soap_regular == 1, na.rm = TRUE), 1),
    high_wash_risk_percent = round(100 * mean(high_wash_risk == 1, na.rm = TRUE), 1),
    household_diarrhea_percent = round(100 * mean(household_diarrhea_recent == 1, na.rm = TRUE), 1),
    under5_diarrhea_percent = round(100 * mean(under5_diarrhea_any_combined == 1, na.rm = TRUE), 1),
    .groups = "drop"
  ) %>%
  arrange(desc(household_diarrhea_percent))


# -----------------------------------------------------------------------------
# 6. BIVARIATE ASSOCIATIONS
# -----------------------------------------------------------------------------

exposures <- c(
  "improved_water_source_any",
  "high_risk_water_source_any",
  "treats_drinking_water",
  "regular_water_treatment",
  "improved_sanitation",
  "handwashing_with_soap_regular",
  "high_wash_risk",
  "vulnerable_household"
)

exposure_labels <- c(
  "Any improved water source",
  "Any high-risk water source",
  "Treats drinking water",
  "Regular drinking-water treatment",
  "Improved sanitation",
  "Regular handwashing with soap",
  "High WASH risk",
  "Vulnerable household"
)

bivariate_household_diarrhea <- map2_dfr(
  exposures,
  exposure_labels,
  ~ make_outcome_by_exposure(
    paper1_data,
    outcome = "household_diarrhea_recent",
    outcome_label = "Recent household diarrhoea",
    exposure = .x,
    exposure_label = .y
  )
)

bivariate_under5_diarrhea <- map2_dfr(
  exposures,
  exposure_labels,
  ~ make_outcome_by_exposure(
    paper1_data,
    outcome = "under5_diarrhea_any_combined",
    outcome_label = "Under-five diarrhoea",
    exposure = .x,
    exposure_label = .y
  )
)

bivariate_combined <- bind_rows(
  bivariate_household_diarrhea,
  bivariate_under5_diarrhea
)


# -----------------------------------------------------------------------------
# 7. MODIFIED POISSON REGRESSION MODELS
# -----------------------------------------------------------------------------

# Model 1: recent household diarrhoea
model_household_diarrhea_crude <- bind_rows(
  modified_poisson(paper1_data, "household_diarrhea_recent", "high_risk_water_source_any", NULL, "Crude: high-risk water source"),
  modified_poisson(paper1_data, "household_diarrhea_recent", "treats_drinking_water", NULL, "Crude: treats drinking water"),
  modified_poisson(paper1_data, "household_diarrhea_recent", "regular_water_treatment", NULL, "Crude: regular water treatment"),
  modified_poisson(paper1_data, "household_diarrhea_recent", "improved_sanitation", NULL, "Crude: improved sanitation"),
  modified_poisson(paper1_data, "household_diarrhea_recent", "handwashing_with_soap_regular", NULL, "Crude: handwashing with soap"),
  modified_poisson(paper1_data, "household_diarrhea_recent", "high_wash_risk", NULL, "Crude: high WASH risk")
)

model_household_diarrhea_adjusted <- modified_poisson(
  data = paper1_data,
  outcome = "household_diarrhea_recent",
  exposures = c(
    "high_risk_water_source_any",
    "treats_drinking_water",
    "improved_sanitation",
    "handwashing_with_soap_regular",
    "high_wash_risk"
  ),
  covariates = c(
    "respondent_female",
    "respondent_age",
    "vulnerable_household",
    "asset_index_simple",
    "parish"
  ),
  model_label = "Adjusted model: recent household diarrhoea"
)

# Model 2: under-five diarrhoea
model_under5_diarrhea_crude <- bind_rows(
  modified_poisson(paper1_data, "under5_diarrhea_any_combined", "high_risk_water_source_any", NULL, "Crude: high-risk water source"),
  modified_poisson(paper1_data, "under5_diarrhea_any_combined", "treats_drinking_water", NULL, "Crude: treats drinking water"),
  modified_poisson(paper1_data, "under5_diarrhea_any_combined", "regular_water_treatment", NULL, "Crude: regular water treatment"),
  modified_poisson(paper1_data, "under5_diarrhea_any_combined", "improved_sanitation", NULL, "Crude: improved sanitation"),
  modified_poisson(paper1_data, "under5_diarrhea_any_combined", "handwashing_with_soap_regular", NULL, "Crude: handwashing with soap"),
  modified_poisson(paper1_data, "under5_diarrhea_any_combined", "high_wash_risk", NULL, "Crude: high WASH risk")
)

model_under5_diarrhea_adjusted <- modified_poisson(
  data = paper1_data,
  outcome = "under5_diarrhea_any_combined",
  exposures = c(
    "high_risk_water_source_any",
    "treats_drinking_water",
    "improved_sanitation",
    "handwashing_with_soap_regular",
    "high_wash_risk"
  ),
  covariates = c(
    "respondent_female",
    "respondent_age",
    "vulnerable_household",
    "asset_index_simple",
    "parish"
  ),
  model_label = "Adjusted model: under-five diarrhoea"
)

models_combined <- bind_rows(
  model_household_diarrhea_crude,
  model_household_diarrhea_adjusted,
  model_under5_diarrhea_crude,
  model_under5_diarrhea_adjusted
)

model_term_labels <- tibble(
  term = c(
    "high_risk_water_source_any",
    "treats_drinking_water",
    "regular_water_treatment",
    "improved_sanitation",
    "handwashing_with_soap_regular",
    "high_wash_risk",
    "respondent_female",
    "respondent_age",
    "vulnerable_household",
    "asset_index_simple"
  ),
  term_label = c(
    "Any high-risk water source",
    "Treats drinking water",
    "Regular drinking-water treatment",
    "Improved sanitation",
    "Regular handwashing with soap",
    "High WASH risk",
    "Female respondent",
    "Respondent age",
    "Vulnerable household",
    "Asset index score"
  )
)

models_publication <- models_combined %>%
  left_join(model_term_labels, by = "term") %>%
  mutate(
    term_label = ifelse(is.na(term_label), term, term_label),
    `PR or APR (95% CI)` = pr_ci,
    `p-value` = p_value_display
  ) %>%
  select(
    Model = model,
    Outcome = outcome,
    `Variable` = term_label,
    `PR or APR (95% CI)`,
    `p-value`,
    `Complete-case N` = complete_case_n,
    Note = note
  )


# -----------------------------------------------------------------------------
# 8. PUBLICATION TABLES
# -----------------------------------------------------------------------------

table_1 <- sample_summary

table_2 <- parish_distribution %>%
  transmute(
    Parish = parish,
    `Households, n (%)` = display,
    `Households, n` = households_n,
    Percent = percent
  )

table_3 <- wash_indicators %>%
  transmute(
    Indicator = indicator,
    Denominator = denominator,
    `Yes, n (%)` = display,
    `Yes (%)` = yes_percent
  )

table_4 <- diarrhea_outcomes %>%
  transmute(
    Outcome = indicator,
    Denominator = denominator,
    `Yes, n (%)` = display,
    `Yes (%)` = yes_percent
  )

table_5 <- wash_by_parish

table_6 <- bivariate_combined %>%
  transmute(
    Outcome = outcome,
    Exposure = exposure,
    `Exposure category` = exposure_group,
    Denominator = denominator,
    `Diarrhoea, n (%)` = display,
    `Diarrhoea (%)` = outcome_percent,
    `Chi-square p-value` = p_value_display
  )

table_7 <- models_publication

table_8 <- diarrhea_prevention %>%
  transmute(
    `Prevention or management measure` = indicator,
    Denominator = denominator,
    `Yes, n (%)` = display,
    `Yes (%)` = yes_percent
  )

table_9 <- wash_risk_distribution %>%
  transmute(
    `WASH risk score` = wash_risk_score,
    `Households, n (%)` = display,
    `Households, n` = households_n,
    Percent = percent
  )

# Compact manuscript table versions
table_manuscript_1 <- table_3
table_manuscript_2 <- table_4
table_manuscript_3 <- table_6 %>%
  filter(Exposure %in% c("Any high-risk water source", "Treats drinking water", "Improved sanitation", "Regular handwashing with soap", "High WASH risk"))
table_manuscript_4 <- table_7


# Additional publication-ready tables for manuscript submission
# These tables are formatted with clear labels, denominators, n (%), p-values,
# and model estimates suitable for direct review by co-authors.

publication_tables_dir <- file.path(output_dir, "Publication_Tables")
dir.create(publication_tables_dir, recursive = TRUE, showWarnings = FALSE)

format_mean_sd <- function(x) {
  if (all(is.na(x))) return(NA_character_)
  paste0(fmt_num(safe_mean(x), 1), " ± ", fmt_num(safe_sd(x), 1))
}

safe_wilcox_p <- function(x, y) {
  dat <- tibble(x = x, y = y) %>% filter(!is.na(x), !is.na(y))
  if (nrow(dat) < 3 || length(unique(dat$y)) < 2) return(NA_real_)
  tryCatch(
    suppressWarnings(wilcox.test(x ~ y, data = dat)$p.value),
    error = function(e) NA_real_
  )
}

make_pub_continuous_by_outcome <- function(data, vars, labels, outcome, outcome_label) {
  map2_dfr(vars, labels, function(v, lab) {
    if (!all(c(v, outcome) %in% names(data))) return(tibble())

    x <- data[[v]]
    y <- data[[outcome]]
    p <- safe_wilcox_p(x, y)

    tibble(
      Outcome = outcome_label,
      Characteristic = lab,
      Category = "Mean ± SD",
      Overall = format_mean_sd(x),
      `No diarrhoea` = format_mean_sd(x[y == 0]),
      Diarrhoea = format_mean_sd(x[y == 1]),
      `p-value` = fmt_p(p),
      `Analysis note` = "Wilcoxon rank-sum test"
    )
  })
}

make_pub_binary_by_outcome <- function(data, vars, labels, outcome, outcome_label) {
  map2_dfr(vars, labels, function(v, lab) {
    if (!all(c(v, outcome) %in% names(data))) return(tibble())

    x <- data[[v]]
    y <- data[[outcome]]
    p <- safe_chisq_p(x, y)

    denom_all <- sum(!is.na(x) & !is.na(y))
    denom_no <- sum(!is.na(x) & y == 0, na.rm = TRUE)
    denom_yes <- sum(!is.na(x) & y == 1, na.rm = TRUE)

    n_all <- sum(x == 1 & !is.na(y), na.rm = TRUE)
    n_no <- sum(x == 1 & y == 0, na.rm = TRUE)
    n_yes <- sum(x == 1 & y == 1, na.rm = TRUE)

    tibble(
      Outcome = outcome_label,
      Characteristic = lab,
      Category = "Yes",
      Overall = fmt_n_pct(n_all, denom_all),
      `No diarrhoea` = fmt_n_pct(n_no, denom_no),
      Diarrhoea = fmt_n_pct(n_yes, denom_yes),
      `p-value` = fmt_p(p),
      `Analysis note` = "Chi-square test"
    )
  })
}

make_pub_factor_by_outcome <- function(data, var, label, outcome, outcome_label) {
  if (!all(c(var, outcome) %in% names(data))) return(tibble())

  dat <- data %>%
    select(all_of(c(var, outcome))) %>%
    filter(!is.na(.data[[var]]), !is.na(.data[[outcome]])) %>%
    mutate(group_value = as.character(.data[[var]]))

  if (nrow(dat) == 0) return(tibble())

  p <- safe_chisq_p(dat$group_value, dat[[outcome]])

  levels_found <- sort(unique(dat$group_value))

  map_dfr(levels_found, function(lv) {
    denom_all <- nrow(dat)
    denom_no <- sum(dat[[outcome]] == 0, na.rm = TRUE)
    denom_yes <- sum(dat[[outcome]] == 1, na.rm = TRUE)

    n_all <- sum(dat$group_value == lv, na.rm = TRUE)
    n_no <- sum(dat$group_value == lv & dat[[outcome]] == 0, na.rm = TRUE)
    n_yes <- sum(dat$group_value == lv & dat[[outcome]] == 1, na.rm = TRUE)

    tibble(
      Outcome = outcome_label,
      Characteristic = label,
      Category = lv,
      Overall = fmt_n_pct(n_all, denom_all),
      `No diarrhoea` = fmt_n_pct(n_no, denom_no),
      Diarrhoea = fmt_n_pct(n_yes, denom_yes),
      `p-value` = fmt_p(p),
      `Analysis note` = "Chi-square test"
    )
  })
}

make_pub_model_table <- function(model_df, title) {
  model_df %>%
    left_join(model_term_labels, by = "term") %>%
    mutate(
      term_label = ifelse(is.na(term_label), term, term_label),
      Estimate = pr_ci,
      `p-value` = p_value_display,
      Model = model,
      Outcome = case_when(
        outcome == "household_diarrhea_recent" ~ "Recent household diarrhoea",
        outcome == "under5_diarrhea_any_combined" ~ "Under-five diarrhoea",
        TRUE ~ outcome
      )
    ) %>%
    transmute(
      Table = title,
      Model,
      Outcome,
      Variable = term_label,
      `PR/APR (95% CI)` = Estimate,
      `p-value`,
      `Complete-case N` = complete_case_n,
      Note = note
    )
}

pub_sample_continuous <- make_pub_continuous_by_outcome(
  paper1_data,
  vars = c("respondent_age", "hh_roster_members_n", "hh_under5_members_n", "asset_index_simple"),
  labels = c("Respondent age", "Household members", "Under-five children in household", "Asset index score"),
  outcome = "household_diarrhea_recent",
  outcome_label = "Recent household diarrhoea"
)

pub_sample_binary <- make_pub_binary_by_outcome(
  paper1_data,
  vars = c("respondent_female", "orphan_household", "disability_household", "vulnerable_household"),
  labels = c("Female respondent", "Household with orphans", "Household with disability", "Vulnerable household"),
  outcome = "household_diarrhea_recent",
  outcome_label = "Recent household diarrhoea"
)

pub_sample_factors <- bind_rows(
  make_pub_factor_by_outcome(paper1_data, "parish", "Parish", "household_diarrhea_recent", "Recent household diarrhoea"),
  make_pub_factor_by_outcome(paper1_data, "asset_tertile_label", "Household asset tertile", "household_diarrhea_recent", "Recent household diarrhoea")
)

pub_table_1_baseline_by_diarrhoea <- bind_rows(
  pub_sample_continuous,
  pub_sample_binary,
  pub_sample_factors
)

pub_table_2_wash_by_household_diarrhoea <- make_pub_binary_by_outcome(
  paper1_data,
  vars = c(
    "improved_water_source_any",
    "unimproved_water_source_any",
    "high_risk_water_source_any",
    "treats_drinking_water",
    "regular_water_treatment",
    "improved_sanitation",
    "no_sanitation_facility",
    "handwashing_with_soap_regular",
    "high_wash_risk"
  ),
  labels = c(
    "Any improved water source",
    "Any unimproved or high-risk water source",
    "Any high-risk water source",
    "Treats drinking water",
    "Regular drinking-water treatment",
    "Improved sanitation",
    "No sanitation facility",
    "Regular handwashing with soap",
    "High WASH risk"
  ),
  outcome = "household_diarrhea_recent",
  outcome_label = "Recent household diarrhoea"
)

pub_table_3_wash_by_under5_diarrhoea <- make_pub_binary_by_outcome(
  paper1_data,
  vars = c(
    "improved_water_source_any",
    "unimproved_water_source_any",
    "high_risk_water_source_any",
    "treats_drinking_water",
    "regular_water_treatment",
    "improved_sanitation",
    "no_sanitation_facility",
    "handwashing_with_soap_regular",
    "high_wash_risk"
  ),
  labels = c(
    "Any improved water source",
    "Any unimproved or high-risk water source",
    "Any high-risk water source",
    "Treats drinking water",
    "Regular drinking-water treatment",
    "Improved sanitation",
    "No sanitation facility",
    "Regular handwashing with soap",
    "High WASH risk"
  ),
  outcome = "under5_diarrhea_any_combined",
  outcome_label = "Under-five diarrhoea"
)

pub_table_4_crude_models <- make_pub_model_table(
  bind_rows(model_household_diarrhea_crude, model_under5_diarrhea_crude),
  "Crude modified Poisson regression models"
)

pub_table_5_adjusted_models <- make_pub_model_table(
  bind_rows(model_household_diarrhea_adjusted, model_under5_diarrhea_adjusted),
  "Adjusted modified Poisson regression models"
)

pub_table_6_parish_profile <- wash_by_parish %>%
  transmute(
    Parish = parish,
    `Households, n` = households_n,
    `High-risk water source (%)` = high_risk_water_source_percent,
    `Treats drinking water (%)` = treats_drinking_water_percent,
    `Regular water treatment (%)` = regular_water_treatment_percent,
    `Improved sanitation (%)` = improved_sanitation_percent,
    `Regular handwashing (%)` = regular_handwashing_percent,
    `High WASH risk (%)` = high_wash_risk_percent,
    `Recent household diarrhoea (%)` = household_diarrhea_percent,
    `Under-five diarrhoea (%)` = under5_diarrhea_percent
  )

pub_table_7_prevention_measures <- table_8

publication_table_list <- list(
  "Table 1 Baseline by diarrhoea" = pub_table_1_baseline_by_diarrhoea,
  "Table 2 WASH HH diarrhoea" = pub_table_2_wash_by_household_diarrhoea,
  "Table 3 WASH U5 diarrhoea" = pub_table_3_wash_by_under5_diarrhoea,
  "Table 4 Crude models" = pub_table_4_crude_models,
  "Table 5 Adjusted models" = pub_table_5_adjusted_models,
  "Table 6 Parish profile" = pub_table_6_parish_profile,
  "Table 7 Prevention" = pub_table_7_prevention_measures
)


# -----------------------------------------------------------------------------
# 9. FIGURES
# -----------------------------------------------------------------------------

theme_pub <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(
      plot.title = element_text(face = "bold", size = base_size + 3),
      plot.subtitle = element_text(size = base_size),
      axis.title = element_text(face = "bold"),
      axis.text.x = element_text(angle = 30, hjust = 1),
      panel.grid.minor = element_blank(),
      legend.position = "bottom",
      legend.title = element_text(face = "bold")
    )
}

fig1 <- wash_indicators %>%
  ggplot(aes(x = reorder(indicator, yes_percent), y = yes_percent)) +
  geom_col(width = 0.72, fill = "#1F4E79") +
  geom_text(aes(label = paste0(yes_percent, "%")), hjust = -0.1, size = 3.8) +
  coord_flip() +
  scale_y_continuous(limits = c(0, 100)) +
  labs(
    title = "Household WASH conditions in Karangura",
    subtitle = "Paper 1 analysis dataset",
    x = NULL,
    y = "Percentage of households"
  ) +
  theme_pub()

ggsave(
  file.path(figures_dir, "Figure_1_household_wash_conditions.png"),
  fig1,
  width = 10,
  height = 6.5,
  dpi = 300
)

fig2 <- diarrhea_outcomes %>%
  ggplot(aes(x = indicator, y = yes_percent, fill = indicator)) +
  geom_col(width = 0.6, color = "black", linewidth = 0.25) +
  geom_text(aes(label = paste0(yes_percent, "%")), vjust = -0.35, size = 4.2) +
  scale_y_continuous(limits = c(0, max(diarrhea_outcomes$yes_percent, na.rm = TRUE) + 10)) +
  labs(
    title = "Prevalence of diarrhoeal illness",
    subtitle = "Recent household diarrhoea and under-five diarrhoea",
    x = NULL,
    y = "Percentage"
  ) +
  theme_pub() +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5), legend.position = "none")

ggsave(
  file.path(figures_dir, "Figure_2_diarrhoea_prevalence.png"),
  fig2,
  width = 8,
  height = 5,
  dpi = 300
)

fig3 <- wash_by_parish %>%
  select(
    parish,
    high_risk_water_source_percent,
    treats_drinking_water_percent,
    improved_sanitation_percent,
    regular_handwashing_percent,
    household_diarrhea_percent
  ) %>%
  pivot_longer(-parish, names_to = "indicator", values_to = "percent") %>%
  mutate(
    indicator = case_when(
      indicator == "high_risk_water_source_percent" ~ "High-risk water source",
      indicator == "treats_drinking_water_percent" ~ "Treats drinking water",
      indicator == "improved_sanitation_percent" ~ "Improved sanitation",
      indicator == "regular_handwashing_percent" ~ "Regular handwashing",
      indicator == "household_diarrhea_percent" ~ "Recent diarrhoea",
      TRUE ~ indicator
    )
  ) %>%
  ggplot(aes(x = parish, y = percent, fill = indicator)) +
  geom_col(position = position_dodge(width = 0.75), width = 0.68) +
  labs(
    title = "WASH conditions and recent diarrhoea by parish",
    subtitle = "Karangura CFCT household baseline",
    x = "Parish",
    y = "Percentage",
    fill = "Indicator"
  ) +
  theme_pub()

ggsave(
  file.path(figures_dir, "Figure_3_wash_and_diarrhoea_by_parish.png"),
  fig3,
  width = 10,
  height = 6,
  dpi = 300
)

fig4 <- paper1_data %>%
  mutate(
    wash_risk_score = factor(wash_risk_score)
  ) %>%
  group_by(wash_risk_score) %>%
  summarise(
    households_n = n(),
    household_diarrhea_percent = round(100 * mean(household_diarrhea_recent == 1, na.rm = TRUE), 1),
    under5_diarrhea_percent = round(100 * mean(under5_diarrhea_any_combined == 1, na.rm = TRUE), 1),
    .groups = "drop"
  ) %>%
  pivot_longer(
    cols = c(household_diarrhea_percent, under5_diarrhea_percent),
    names_to = "outcome",
    values_to = "percent"
  ) %>%
  mutate(
    outcome = case_when(
      outcome == "household_diarrhea_percent" ~ "Recent household diarrhoea",
      outcome == "under5_diarrhea_percent" ~ "Under-five diarrhoea",
      TRUE ~ outcome
    )
  ) %>%
  ggplot(aes(x = wash_risk_score, y = percent, group = outcome, color = outcome)) +
  geom_line(linewidth = 1) +
  geom_point(size = 2.8) +
  labs(
    title = "Diarrhoea prevalence by WASH risk score",
    subtitle = "Higher scores represent more household WASH risks",
    x = "WASH risk score",
    y = "Diarrhoea prevalence (%)",
    color = "Outcome"
  ) +
  theme_pub() +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5))

ggsave(
  file.path(figures_dir, "Figure_4_diarrhoea_by_wash_risk_score.png"),
  fig4,
  width = 9,
  height = 5.5,
  dpi = 300
)

fig5 <- models_combined %>%
  filter(str_detect(model, "Adjusted"), !is.na(prevalence_ratio)) %>%
  left_join(model_term_labels, by = "term") %>%
  mutate(
    term_label = ifelse(is.na(term_label), term, term_label),
    outcome_label = case_when(
      outcome == "household_diarrhea_recent" ~ "Recent household diarrhoea",
      outcome == "under5_diarrhea_any_combined" ~ "Under-five diarrhoea",
      TRUE ~ outcome
    )
  ) %>%
  ggplot(aes(x = prevalence_ratio, y = reorder(term_label, prevalence_ratio))) +
  geom_vline(xintercept = 1, linetype = "dashed") +
  geom_errorbarh(aes(xmin = conf_low, xmax = conf_high), height = 0.2) +
  geom_point(size = 2.8) +
  facet_wrap(~ outcome_label, scales = "free_y") +
  scale_x_log10() +
  labs(
    title = "Adjusted associations between WASH conditions and diarrhoeal illness",
    subtitle = "Modified Poisson regression with robust standard errors",
    x = "Adjusted prevalence ratio, log scale",
    y = NULL
  ) +
  theme_pub()

ggsave(
  file.path(figures_dir, "Figure_5_adjusted_prevalence_ratios.png"),
  fig5,
  width = 11,
  height = 6,
  dpi = 300
)


# -----------------------------------------------------------------------------
# 10. EXPORT EXCEL WORKBOOK
# -----------------------------------------------------------------------------

excel_output <- file.path(tables_dir, "Paper1_Water_Treatment_Diarrhoea_Tables.xlsx")

wb <- createWorkbook()

sheet_list <- list(
  "Sample summary" = table_1,
  "Parish distribution" = table_2,
  "WASH indicators" = table_3,
  "Diarrhoea outcomes" = table_4,
  "WASH by parish" = table_5,
  "Bivariate associations" = table_6,
  "Regression models" = table_7,
  "Diarrhoea prevention" = table_8,
  "WASH risk distribution" = table_9,
  "Pub T1 baseline" = pub_table_1_baseline_by_diarrhoea,
  "Pub T2 WASH HH diarrhoea" = pub_table_2_wash_by_household_diarrhoea,
  "Pub T3 WASH U5 diarrhoea" = pub_table_3_wash_by_under5_diarrhoea,
  "Pub T4 crude models" = pub_table_4_crude_models,
  "Pub T5 adjusted models" = pub_table_5_adjusted_models,
  "Pub T6 parish profile" = pub_table_6_parish_profile,
  "Pub T7 prevention" = pub_table_7_prevention_measures
)

header_style <- createStyle(
  textDecoration = "bold",
  fgFill = "#1F4E79",
  fontColour = "white",
  halign = "center",
  valign = "center",
  border = "TopBottomLeftRight",
  wrapText = TRUE
)

body_style <- createStyle(
  border = "TopBottomLeftRight",
  valign = "center",
  wrapText = TRUE
)

for (sheet_name in names(sheet_list)) {
  addWorksheet(wb, sheet_name)
  writeData(wb, sheet_name, sheet_list[[sheet_name]])

  n_rows <- max(1, nrow(sheet_list[[sheet_name]]) + 1)
  n_cols <- max(1, ncol(sheet_list[[sheet_name]]))

  addStyle(wb, sheet_name, header_style, rows = 1, cols = 1:n_cols, gridExpand = TRUE)

  if (n_rows >= 2) {
    addStyle(wb, sheet_name, body_style, rows = 2:n_rows, cols = 1:n_cols, gridExpand = TRUE)
  }

  setColWidths(wb, sheet_name, cols = 1:n_cols, widths = "auto")
  freezePane(wb, sheet_name, firstRow = TRUE)
}

saveWorkbook(wb, excel_output, overwrite = TRUE)

rm(wb)
gc()

# Export a second workbook containing only publication-ready manuscript tables
publication_excel_output <- file.path(publication_tables_dir, "Paper1_Publication_Ready_Tables.xlsx")

pub_wb <- createWorkbook()

pub_title_style <- createStyle(
  textDecoration = "bold",
  fgFill = "#D9EAF7",
  fontColour = "#1F4E79",
  halign = "left",
  valign = "center",
  wrapText = TRUE,
  fontSize = 12
)

pub_header_style <- createStyle(
  textDecoration = "bold",
  fgFill = "#1F4E79",
  fontColour = "white",
  halign = "center",
  valign = "center",
  border = "TopBottomLeftRight",
  wrapText = TRUE
)

pub_body_style <- createStyle(
  border = "TopBottomLeftRight",
  valign = "center",
  wrapText = TRUE
)

pub_alt_style <- createStyle(
  fgFill = "#F7F7F7",
  border = "TopBottomLeftRight",
  valign = "center",
  wrapText = TRUE
)

pub_note_style <- createStyle(
  textDecoration = "italic",
  fontColour = "#666666",
  wrapText = TRUE
)

publication_captions <- c(
  "Table 1 Baseline by diarrhoea" = "Table 1. Baseline household and respondent characteristics by recent household diarrhoea status",
  "Table 2 WASH HH diarrhoea" = "Table 2. Household WASH conditions by recent household diarrhoea status",
  "Table 3 WASH U5 diarrhoea" = "Table 3. Household WASH conditions by under-five diarrhoea status",
  "Table 4 Crude models" = "Table 4. Crude prevalence ratios for diarrhoeal illness",
  "Table 5 Adjusted models" = "Table 5. Adjusted prevalence ratios for diarrhoeal illness",
  "Table 6 Parish profile" = "Table 6. Parish-level profile of WASH conditions and diarrhoeal illness",
  "Table 7 Prevention" = "Table 7. Reported diarrhoea prevention and management measures"
)

for (sheet_name in names(publication_table_list)) {
  addWorksheet(pub_wb, sheet_name)
  pub_dat <- publication_table_list[[sheet_name]]
  caption <- publication_captions[[sheet_name]]

  writeData(pub_wb, sheet_name, caption, startRow = 1, startCol = 1)
  mergeCells(pub_wb, sheet_name, cols = 1:max(1, ncol(pub_dat)), rows = 1)
  addStyle(pub_wb, sheet_name, pub_title_style, rows = 1, cols = 1:max(1, ncol(pub_dat)), gridExpand = TRUE)

  writeData(pub_wb, sheet_name, pub_dat, startRow = 3, startCol = 1)

  n_rows <- max(1, nrow(pub_dat) + 3)
  n_cols <- max(1, ncol(pub_dat))

  addStyle(pub_wb, sheet_name, pub_header_style, rows = 3, cols = 1:n_cols, gridExpand = TRUE)

  if (n_rows >= 4) {
    body_rows <- 4:n_rows
    addStyle(pub_wb, sheet_name, pub_body_style, rows = body_rows, cols = 1:n_cols, gridExpand = TRUE)
    alt_rows <- body_rows[seq_along(body_rows) %% 2 == 0]
    if (length(alt_rows) > 0) {
      addStyle(pub_wb, sheet_name, pub_alt_style, rows = alt_rows, cols = 1:n_cols, gridExpand = TRUE)
    }
  }

  note_row <- n_rows + 2
  writeData(pub_wb, sheet_name, "Notes: Percentages are based on non-missing denominators. P-values are from chi-square tests for categorical variables and Wilcoxon rank-sum tests for continuous variables. PR/APR estimates are from modified Poisson regression with robust standard errors.", startRow = note_row, startCol = 1)
  mergeCells(pub_wb, sheet_name, cols = 1:n_cols, rows = note_row)
  addStyle(pub_wb, sheet_name, pub_note_style, rows = note_row, cols = 1:n_cols, gridExpand = TRUE)

  setColWidths(pub_wb, sheet_name, cols = 1:n_cols, widths = "auto")
  freezePane(pub_wb, sheet_name, firstActiveRow = 4)
}

saveWorkbook(pub_wb, publication_excel_output, overwrite = TRUE)
rm(pub_wb)
gc()

# Export each publication-ready table to its own standalone Word document.
# This avoids placing all publication tables in one Word file.
publication_word_dir <- file.path(publication_tables_dir, "Standalone_Word_Tables")
dir.create(publication_word_dir, recursive = TRUE, showWarnings = FALSE)

make_pub_table_for_word <- function(data, caption) {
  flextable(data) %>%
    set_caption(caption) %>%
    theme_booktabs() %>%
    autofit() %>%
    fontsize(size = 8.5, part = "all") %>%
    bold(part = "header") %>%
    align(align = "center", part = "all") %>%
    align(j = 1, align = "left", part = "body") %>%
    valign(valign = "center", part = "all")
}

safe_file_name <- function(x) {
  x %>%
    str_replace_all("[^A-Za-z0-9]+", "_") %>%
    str_replace_all("_+", "_") %>%
    str_replace_all("^_|_$", "")
}

publication_word_outputs <- character(0)

for (sheet_name in names(publication_table_list)) {
  pub_dat <- publication_table_list[[sheet_name]]
  caption <- publication_captions[[sheet_name]]

  table_file <- file.path(
    publication_word_dir,
    paste0("Paper1_", safe_file_name(sheet_name), ".docx")
  )

  table_doc <- read_docx() %>%
    body_add_par(caption, style = "heading 1") %>%
    body_add_par(
      "Household Water Sources, Drinking-Water Treatment and Diarrhoeal Illness in Karangura Sub-County, Uganda",
      style = "Normal"
    ) %>%
    body_add_flextable(make_pub_table_for_word(pub_dat, caption)) %>%
    body_add_par(
      "Notes: Percentages are based on non-missing denominators. P-values are from chi-square tests for categorical variables and Wilcoxon rank-sum tests for continuous variables. PR/APR estimates are from modified Poisson regression with robust standard errors.",
      style = "Normal"
    )

  print(table_doc, target = table_file)
  publication_word_outputs <- c(publication_word_outputs, table_file)
}

# Also write a simple index file listing all standalone Word tables.
publication_word_index <- file.path(publication_word_dir, "Paper1_Standalone_Word_Tables_Index.txt")
writeLines(publication_word_outputs, publication_word_index)


# -----------------------------------------------------------------------------
# 11. RESULT NARRATIVE FOR MANUSCRIPT
# -----------------------------------------------------------------------------

get_prev <- function(tbl, var_name) {
  tbl %>%
    filter(variable == var_name) %>%
    pull(yes_percent)
}

prev_improved_water <- get_prev(wash_indicators, "improved_water_source_any")
prev_high_risk_water <- get_prev(wash_indicators, "high_risk_water_source_any")
prev_treats_water <- get_prev(wash_indicators, "treats_drinking_water")
prev_regular_treatment <- get_prev(wash_indicators, "regular_water_treatment")
prev_improved_sanitation <- get_prev(wash_indicators, "improved_sanitation")
prev_handwashing <- get_prev(wash_indicators, "handwashing_with_soap_regular")
prev_high_wash_risk <- get_prev(wash_indicators, "high_wash_risk")

prev_household_diarrhea <- get_prev(diarrhea_outcomes, "household_diarrhea_recent")
prev_under5_diarrhea <- get_prev(diarrhea_outcomes, "under5_diarrhea_any_combined")

abstract_results <- paste0(
  "Among ", sample_size, " households included in the analysis, ",
  prev_improved_water, "% reported at least one improved water source, while ",
  prev_high_risk_water, "% reported at least one high-risk or unimproved water source. ",
  "Only ", prev_treats_water, "% reported treating drinking water and ",
  prev_regular_treatment, "% reported regular drinking-water treatment. ",
  "Improved sanitation was reported by ", prev_improved_sanitation, "% of households and regular handwashing with soap by ",
  prev_handwashing, "%. Recent household diarrhoea was reported by ",
  prev_household_diarrhea, "% of households, while under-five diarrhoea was reported by ",
  prev_under5_diarrhea, "%. Overall, ", prev_high_wash_risk,
  "% of households were classified as high WASH risk."
)

results_paragraph_1 <- paste0(
  "The Paper 1 analysis included ", sample_size, " households with recent household diarrhoea outcome data. ",
  "Access to WASH services was mixed. Although ", prev_improved_water,
  "% of households reported at least one improved water source, ", prev_high_risk_water,
  "% also reported at least one high-risk or unimproved source. Drinking-water treatment was limited, with ",
  prev_treats_water, "% of households reporting any treatment and only ", prev_regular_treatment,
  "% reporting regular treatment."
)

results_paragraph_2 <- paste0(
  "Sanitation coverage was comparatively higher, with ", prev_improved_sanitation,
  "% of households reporting improved sanitation. Regular handwashing with soap was reported by ",
  prev_handwashing, "% of households. The composite WASH risk score classified ",
  prev_high_wash_risk, "% of households as high risk."
)

results_paragraph_3 <- paste0(
  "Recent household diarrhoea was reported by ", prev_household_diarrhea,
  "% of households, while under-five diarrhoea was reported by ", prev_under5_diarrhea,
  "%. These results show that diarrhoeal illness remains an important public-health outcome in the study population, in a context where drinking-water treatment and consistent hygiene practices were limited."
)

discussion_core <- paste0(
  "This baseline analysis shows that safe water governance and household WASH practices remain important public-health priorities in Karangura Sub-County. ",
  "The coexistence of improved and high-risk water sources suggests that access alone may not guarantee safe household water use. ",
  "Low levels of drinking-water treatment and regular handwashing with soap further point to gaps in household-level water safety and hygiene practices. ",
  "The observed burden of recent household and under-five diarrhoea supports integrated action combining safe water access, water-treatment promotion, sanitation improvement, hygiene behaviour change and community-level WASH governance."
)


# -----------------------------------------------------------------------------
# 12. WORD MANUSCRIPT DRAFT
# -----------------------------------------------------------------------------

make_pub_table <- function(data, caption) {
  flextable(data) %>%
    set_caption(caption) %>%
    theme_booktabs() %>%
    autofit() %>%
    fontsize(size = 8.5, part = "all") %>%
    bold(part = "header") %>%
    align(align = "center", part = "all") %>%
    align(j = 1, align = "left", part = "body") %>%
    valign(valign = "center", part = "all")
}

add_image_if_exists <- function(doc, img_path, title, width = 6.5, height = 4.5) {
  if (file.exists(img_path)) {
    doc <- doc %>%
      body_add_par(title, style = "heading 2") %>%
      body_add_img(src = img_path, width = width, height = height)
  } else {
    doc <- doc %>%
      body_add_par(title, style = "heading 2") %>%
      body_add_par(paste("Figure not found:", img_path), style = "Normal")
  }

  doc
}

ft1 <- make_pub_table(table_manuscript_1, "Table 1. Household water, sanitation and hygiene conditions")
ft2 <- make_pub_table(table_manuscript_2, "Table 2. Prevalence of diarrhoeal illness")
ft3 <- make_pub_table(table_manuscript_3, "Table 3. Bivariate associations between WASH conditions and diarrhoeal illness")
ft4 <- make_pub_table(table_manuscript_4, "Table 4. Modified Poisson regression models for diarrhoeal illness")

manuscript_output <- file.path(
  manuscript_dir,
  "Paper1_Water_Treatment_Diarrhoea_Manuscript_Draft.docx"
)

doc <- read_docx()

doc <- doc %>%
  body_add_par("Household Water Sources, Drinking-Water Treatment and Diarrhoeal Illness in Karangura Sub-County, Uganda: Implications for Safe Water Governance and Public Health", style = "heading 1") %>%
  body_add_par("Draft manuscript prepared from the Karangura CFCT household baseline survey", style = "Normal") %>%

  body_add_par("Abstract", style = "heading 1") %>%
  body_add_par("Background", style = "heading 2") %>%
  body_add_par(
    "Unsafe water, inadequate sanitation and poor hygiene remain important contributors to diarrhoeal illness in rural settings. This study assessed household water sources, drinking-water treatment, sanitation and hygiene practices in Karangura Sub-County, Uganda, and examined their relationship with diarrhoeal illness.",
    style = "Normal"
  ) %>%
  body_add_par("Methods", style = "heading 2") %>%
  body_add_par(
    "We analysed cross-sectional household baseline survey data from the Karangura Child Focused Community Transformation baseline. The analysis described household WASH conditions and estimated the prevalence of recent household diarrhoea and under-five diarrhoea. Bivariate comparisons and modified Poisson regression with robust standard errors were used to examine associations between WASH conditions and diarrhoeal outcomes.",
    style = "Normal"
  ) %>%
  body_add_par("Results", style = "heading 2") %>%
  body_add_par(abstract_results, style = "Normal") %>%
  body_add_par("Conclusion", style = "heading 2") %>%
  body_add_par(
    "The findings highlight important gaps in household drinking-water treatment, hygiene and WASH risk reduction. Strengthening safe water governance, household water treatment, sanitation and hygiene promotion may contribute to diarrhoeal disease prevention in Karangura.",
    style = "Normal"
  ) %>%

  body_add_par("Introduction", style = "heading 1") %>%
  body_add_par(
    "Access to safe water, sanitation and hygiene is central to public health and sustainable development. In rural communities, diarrhoeal illness is shaped not only by physical access to water sources but also by the safety of those sources, household drinking-water treatment, sanitation facilities and hygiene behaviours. Understanding these household-level conditions provides evidence for local water governance and public-health planning.",
    style = "Normal"
  ) %>%
  body_add_par(
    "Karangura Sub-County is a rural setting where the Child Focused Community Transformation baseline survey collected household data on socio-economic conditions, healthcare access, disaster resilience and related community needs. This paper uses the household WASH and health components of the baseline to assess water sources, drinking-water treatment, sanitation and diarrhoeal illness.",
    style = "Normal"
  ) %>%

  body_add_par("Methods", style = "heading 1") %>%
  body_add_par("Study design and setting", style = "heading 2") %>%
  body_add_par(
    "This was a cross-sectional analysis of household baseline survey data collected in Karangura Sub-County, Kabarole District, Uganda. The baseline survey was conducted to generate evidence for project monitoring, evaluation, learning and intervention planning.",
    style = "Normal"
  ) %>%
  body_add_par("Study population", style = "heading 2") %>%
  body_add_par(
    "The analysis included households with available recent household diarrhoea outcome data. Household-level information was used to construct WASH exposures, vulnerability indicators and diarrhoeal illness outcomes.",
    style = "Normal"
  ) %>%
  body_add_par("Variables", style = "heading 2") %>%
  body_add_par(
    "Key exposure variables included improved water source, high-risk or unimproved water source, drinking-water treatment, regular drinking-water treatment, improved sanitation, regular handwashing with soap and a composite WASH risk score. Outcomes were recent household diarrhoea and under-five diarrhoea. Covariates included respondent sex, respondent age, household vulnerability, asset index and parish.",
    style = "Normal"
  ) %>%
  body_add_par("Statistical analysis", style = "heading 2") %>%
  body_add_par(
    "Descriptive statistics were used to summarise household characteristics, WASH conditions and diarrhoeal outcomes. Bivariate associations were assessed using cross-tabulations and chi-square tests. Modified Poisson regression with robust standard errors was used to estimate prevalence ratios and adjusted prevalence ratios for diarrhoeal illness.",
    style = "Normal"
  ) %>%

  body_add_par("Results", style = "heading 1") %>%
  body_add_par("Household WASH conditions", style = "heading 2") %>%
  body_add_par(results_paragraph_1, style = "Normal") %>%
  body_add_par(results_paragraph_2, style = "Normal") %>%
  body_add_par("Diarrhoeal illness", style = "heading 2") %>%
  body_add_par(results_paragraph_3, style = "Normal") %>%
  body_add_par("Tables", style = "heading 2") %>%
  body_add_flextable(ft1) %>%
  body_add_par("", style = "Normal") %>%
  body_add_flextable(ft2) %>%
  body_add_par("", style = "Normal") %>%
  body_add_flextable(ft3) %>%
  body_add_par("", style = "Normal") %>%
  body_add_flextable(ft4) %>%

  body_add_par("Figures", style = "heading 1")

doc <- add_image_if_exists(
  doc,
  file.path(figures_dir, "Figure_1_household_wash_conditions.png"),
  "Figure 1. Household WASH conditions in Karangura",
  width = 6.5,
  height = 4.5
)

doc <- add_image_if_exists(
  doc,
  file.path(figures_dir, "Figure_2_diarrhoea_prevalence.png"),
  "Figure 2. Prevalence of diarrhoeal illness",
  width = 6.2,
  height = 3.8
)

doc <- add_image_if_exists(
  doc,
  file.path(figures_dir, "Figure_3_wash_and_diarrhoea_by_parish.png"),
  "Figure 3. WASH conditions and recent diarrhoea by parish",
  width = 6.5,
  height = 4.2
)

doc <- add_image_if_exists(
  doc,
  file.path(figures_dir, "Figure_4_diarrhoea_by_wash_risk_score.png"),
  "Figure 4. Diarrhoea prevalence by WASH risk score",
  width = 6.5,
  height = 4.0
)

doc <- add_image_if_exists(
  doc,
  file.path(figures_dir, "Figure_5_adjusted_prevalence_ratios.png"),
  "Figure 5. Adjusted associations between WASH conditions and diarrhoeal illness",
  width = 6.5,
  height = 4.2
)

doc <- doc %>%
  body_add_par("Discussion", style = "heading 1") %>%
  body_add_par(discussion_core, style = "Normal") %>%
  body_add_par(
    "The analysis should be interpreted as a cross-sectional baseline assessment. The findings identify associations and priority areas for intervention, but do not establish causality. Because several indicators were self-reported, recall and social desirability bias are possible. Nevertheless, the results provide locally relevant evidence for safe water governance and diarrhoeal disease prevention.",
    style = "Normal"
  ) %>%
  body_add_par("Conclusion", style = "heading 1") %>%
  body_add_par(
    "Karangura households reported mixed WASH conditions, with limited drinking-water treatment and a high composite WASH risk burden. Diarrhoeal illness was reported among both households and under-five children. Integrated action on safe water access, household water treatment, sanitation, handwashing and community-level WASH governance is needed to protect public health.",
    style = "Normal"
  ) %>%
  body_add_par("Declarations", style = "heading 1") %>%
  body_add_par("Ethics approval and consent to participate: To be completed using the approved Karangura CFCT baseline documentation.", style = "Normal") %>%
  body_add_par("Consent for publication: Not applicable.", style = "Normal") %>%
  body_add_par("Availability of data and materials: To be completed after author and institutional decision on data sharing.", style = "Normal") %>%
  body_add_par("Competing interests: The authors declare no competing interests.", style = "Normal") %>%
  body_add_par("Funding: To be completed.", style = "Normal") %>%
  body_add_par("Authors' contributions: To be completed after authorship confirmation.", style = "Normal") %>%
  body_add_par("Acknowledgements: To be completed.", style = "Normal")

print(doc, target = manuscript_output)


# -----------------------------------------------------------------------------
# 13. SAVE OBJECTS AND LOG
# -----------------------------------------------------------------------------

analysis_objects <- list(
  paper1_data = paper1_data,
  sample_summary = sample_summary,
  parish_distribution = parish_distribution,
  asset_distribution = asset_distribution,
  wash_indicators = wash_indicators,
  diarrhea_outcomes = diarrhea_outcomes,
  diarrhea_prevention = diarrhea_prevention,
  wash_risk_distribution = wash_risk_distribution,
  wash_by_parish = wash_by_parish,
  bivariate_combined = bivariate_combined,
  models_combined = models_combined,
  models_publication = models_publication,
  tables = list(
    table_1 = table_1,
    table_2 = table_2,
    table_3 = table_3,
    table_4 = table_4,
    table_5 = table_5,
    table_6 = table_6,
    table_7 = table_7,
    table_8 = table_8,
    table_9 = table_9
  )
)

saveRDS(
  analysis_objects,
  file.path(objects_dir, "Paper1_Water_Treatment_Diarrhoea_Analysis_Objects.rds")
)

log_text <- c(
  "PAPER 1 ANALYSIS COMPLETED",
  paste0("Date/time: ", Sys.time()),
  paste0("Sample size: ", sample_size),
  paste0("Analysis dataset: ", analysis_dataset_csv),
  paste0("Excel workbook: ", excel_output),
  paste0("Publication-ready Excel tables: ", publication_excel_output),
  paste0("Publication-ready standalone Word tables folder: ", publication_word_dir),
  paste0("Manuscript draft: ", manuscript_output),
  paste0("Figures directory: ", figures_dir)
)

writeLines(log_text, file.path(logs_dir, "Paper1_analysis_log.txt"))


# -----------------------------------------------------------------------------
# 14. CONSOLE SUMMARY
# -----------------------------------------------------------------------------

cat("\n====================================================================\n")
cat("PAPER 1 ANALYSIS COMPLETED\n")
cat("====================================================================\n\n")

cat("Sample size:", sample_size, "\n")
cat("Output folder:", output_dir, "\n")
cat("Analysis dataset:", analysis_dataset_csv, "\n")
cat("Excel workbook:", excel_output, "\n")
cat("Publication-ready Excel tables:", publication_excel_output, "\n")
cat("Publication-ready standalone Word tables folder:", publication_word_dir, "\n")
cat("Manuscript draft:", manuscript_output, "\n")
cat("Figures:", figures_dir, "\n\n")

cat("Key WASH indicators:\n")
print(table_3)

cat("\nDiarrhoeal outcomes:\n")
print(table_4)

cat("\nModel results are saved in the Excel workbook and Word draft.\n")

gc()
