# ---------------------------------------------------------------------
# Fitting a GlmmTMB model
# event30 - camera trap event separated by at least 30 minutes
# ---------------------------------------------------------------------
library(dplyr)
library(glmmTMB)

mod <- glmmTMB(
     event30 ~ habitat +
         sin_t + cos_t +
         sin_t:habitat + cos_t:habitat +
         (1 | BIOKORIDOR)+offset(log(Nactive30minIntervals)),
     family = nbinom2,
     data = x
 )

Anova(mod, type = "II", test.statistic = "Chisq")

# ---------------------------------------------------------------------
# Exponentiated coefficients, expressed as incidence rate ratios (IRRs)
# ---------------------------------------------------------------------

coefs <- summary(mod)$coefficients$cond
 
RR <- exp(coefs[, "Estimate"])
 
 # 95% CI
 SE <- coefs[, "Std. Error"]
 lower <- exp(coefs[, "Estimate"] - 1.96 * SE)
 upper <- exp(coefs[, "Estimate"] + 1.96 * SE)
 
 # vytvoření tabulky bez term sloupce
 df <- data.frame(
     IRR = RR,
     CI_low = lower,
     CI_high = upper
 )
 df

# ----------------------------------------------------------------------------------------------------------------------
# Aggregation of data by camera trap ID, year, and month, with calculation of the median and IQR of the event30 variable.
# ----------------------------------------------------------------------------------------------------------------------

 df_station_summary <- x %>%
     group_by(fotopastID, rok, měsíc) %>%
     summarise(
         median_event30 = median(event30, na.rm = TRUE),
         IQR_event30 = IQR(event30, na.rm = TRUE),
         .groups = "drop"
     )
 
 df_station_summary



# --------------------
# Sensitivity analysis
# --------------------
library(purrr)
library(dplyr)
library(data.table)
library(writexl)

# 1) Robust vectorized function (for handling NAs in logic)
# *********************************************************

make_events_robust <- function(times, threshold) {
    if (length(times) <= 1) {
        # For groups with 0 or 1 record, it returns 1 or 0, respectively.
        return(rep(1, length(times)))
    }
    
    # Time differences between consecutive events
    time_diff <- diff(times)
    
    # Creating a TRUE/FALSE vector: Where is the time difference ≥ threshold?
    # We assume that the time difference contains no NAs (because times has no NAs).
    is_new_event <- time_diff >= threshold
    
    # We add TRUE at the beginning (the first record is always a new event).
    is_new_event <- c(TRUE, is_new_event)
    
    #The cumulative sum of TRUE (1) and FALSE (0) creates event IDs.
    return(cumsum(is_new_event))
}


# 2) Generating camera trap events using a robust function with 15, 30, and 60-minute thresholds
# **********************************************************************************************
df_events_final <- x %>%
    # 1. nsuring that sorting is not done based on columns with NAs
    arrange(BIOKORIDOR, fotopastID, rok, měsíc, DRUH, time_min) %>%
    
    # 2. Grouping
    group_by(BIOKORIDOR, fotopastID, rok, měsíc, DRUH) %>%
    
    # 3. Mutate s make_events_robust
    mutate(
        event15 = make_events_robust(time_min, 15),
        event30 = make_events_robust(time_min, 30),
        event60 = make_events_robust(time_min, 60)
    ) %>%
    ungroup()

# Result check:
# head(df_events_final %>% select(time_min, event15, event30, event60), 20)

df_events_final %>% 
  select(BIOKORIDOR, DRUH, time_min, event15, event30, event60) %>% 
  head(30)

write_xlsx(df_events_final,"sensitivity.xlsx")




