source("modules/annova_functions.R")
source("modules/emmeans_functions.R")
source("modules/mixte_model_functions.R")
source("modules/kw_functions.R")
source("modules/shapiro_functions.R")
source("modules/graph.R")
source("modules/sso.R")

readRenviron("./.Renviron")
source("install_packages.R")
base_url <- Sys.getenv("BASE_URL")
client_id <- Sys.getenv("CLIENT_ID")
client_secret <- Sys.getenv("CLIENT_SECRET")
uri_url <- Sys.getenv("URI_URL")
authorize_url = Sys.getenv("AUTHORIZE_URL")
token_url = Sys.getenv("TOKEN_URL")
userinfo_url = Sys.getenv("USERINFO_URL")
response_type <- 'code'
facet_formula = as.formula('.~.')

server <- function(input, output, session) {
  shinylogs::track_usage(
    storage_mode = shinylogs::store_null()
  )
  
  observe({
    if(is.null(session$userData$authorize)) {
      session$userData$authorize <- 0
    }
  })
  
#   random_bytes <- openssl::rand_bytes(16)
#   random_state <- toupper(paste0(sprintf("%02x", as.integer(random_bytes)), collapse = ""))
  
  
#   observeEvent(input$logout, {
#     logout(session=session,
#            access_token=session$userData$access_token,
#            authorization=session$userData$authorization,
#            base_url=base_url,
#            id_token=session$userData$id_token)
#   })
  
#   observe({
#     login(session=session,
#           url_search=session$clientData$url_search,
#           random_bytes=random_bytes,
#           authorize_url=authorize_url,
#           uri_url=uri_url,
#           response_type=response_type,
#           random_state=random_state,
#           client_id=client_id,
#           client_secret=client_secret,
#           output=output,
#           token_url=token_url,
#           userinfo_url=base_url)
#   })
  
  # Partie permettant de fusionner les fichiers
  observe({
    #notConnected(authorize=session$userData$authorize)
            
        merged_data <- eventReactive(input$files, {
        # On lit la liste des fichiers et on les fusionne
        # Charger les données à partir des fichiers sélectionnés
        tables <- lapply(input$files$datapath, function(datapath) {
            # Vérifier l'extension du fichier
            if (tools::file_ext(datapath) %in% c("csv", "CSV")) {
            data <- read.csv(datapath)  
            } else if (tools::file_ext(datapath) %in% c("xlsx")) {
            data <- readxl::read_excel(datapath)  
            } else {
            stop("Type de fichier non pris en charge : ", tools::file_ext(datapath))
            }
            
            filename <- input$files$name[input$files$datapath == datapath]  
            filename <- substr(filename, 1, nchar(filename) - 4)
            return(data)
        })
        
        
        concatenated_table <- bind_rows(tables)
        concatenated_table <- na.omit(concatenated_table)
        
        # Remplacer les espaces dans les noms de colonnes par des "_"
        colnames(concatenated_table) <- gsub("[^[:alnum:]_]", "_", colnames(concatenated_table))
        return(concatenated_table)
        })
        
        columnTypes <- reactiveVal(list())
        
        observe({
        data <- merged_data()
        types <- list()
        for (col in setdiff(colnames(data),input$ignore_columns)) {
            column_class <- class(data[[col]])  # Utilisez class() pour obtenir la classe de la colonne
            default_choice <- switch(
            column_class,
            "Date" = "Date",
            "character" = "Chaine de caractère",
            "integer" = "Quantitative discrète",
            "numeric" = "Quantitative continue",
            "factor" = "Catégorie",
            "logical" = "Binaire",
            "Character"  
            )
            types[[col]] <- selectInput(
            inputId = paste0("type_", col),
            label = col,
            choices = c("Date", "Chaine de caractère", "Quantitative continue", "Catégorie", "Quantitative discrète", "Binaire"),
            selected = default_choice
            )
            
        }
        columnTypes(types)
        })
        
        output$columnTypes <- renderUI({
        types <- columnTypes()
        if (!is.null(types) && length(types) > 0) {
            div(
            lapply(names(types), function(col) {
                types[[col]]
            })
            )
        }
        })
        
        merged_data_type <- eventReactive(input$applyTypes, {
        data <- merged_data()[,setdiff(colnames(merged_data()),input$ignore_columns)]
        types <- columnTypes()
        if (!is.null(types) && length(types) > 0) {
            
            for (col in names(types)) {
            selectedType <- input[[paste0("type_", col)]]
            if (selectedType == "Date") {
                data[[col]] <- as.Date(data[[col]])
            } else if (selectedType == "Chaine de caractère") {
                data[[col]] <- as.character(data[[col]])
            } else if (selectedType == "Quantitative continue") {
                data[[col]] <- as.numeric(data[[col]])
            } else if (selectedType == "Catégorie") {
                data[[col]] <- as.factor(data[[col]])
            } else if (selectedType == "Quantitative discrète") {
                data[[col]] <- as.integer(data[[col]])
            } else if (selectedType == "Binaire") {
                data[[col]] <- as.logical(data[[col]])
            } else {
                data[[col]] <- as.character(data[[col]])
            }
            }
            output$merged_data_table <- renderDataTable(data,
                                                        options = list(
                                                        pageLength = 10,
                                                        autoWidth = TRUE,
                                                        lengthMenu = list(c(10,50,100, -1), c("10","50","100", "All"))
                                                        ))
        }
        return(data)
        })
        
        #On sélectionne les colonnes à ignorer
        observe({
        if (!is.null(merged_data())) {
            
            
            updateSelectInput(session, "ignore_columns", 
                            choices = colnames(merged_data()), selected = NULL)
            
            output$merged_data_table <- renderDataTable(merged_data()[,setdiff(colnames(merged_data()),input$ignore_columns)],
                                                        options = list(
                                                        pageLength = 10,
                                                        autoWidth = TRUE,
                                                        lengthMenu = list(c(10,50,100, -1), c("10","50","100", "All"))
                                                        ))
        }
        })
        
        
        contrast_list <- reactiveValues(ma_liste=list())
        contrast_list_mixte <- reactiveValues(ma_liste=list())
        mixte_models_list <- reactiveValues(
            df = data.frame(
                Nom = character(),
                R2 = numeric(),
                Variables_Explicatives_Aleatoires = character(),
                Variables_Explicatives_Fixes = character(),
                stringsAsFactors = FALSE
            ), 
            models = list()
            )
        
        #On sélectionne les colonnes numériques
        observe({
        updateSelectInput(session, "var_expliquees", 
                            choices = colnames( merged_data_type() %>% select_if(function(x) is.numeric(x) || is.integer(x))))
        updateSelectInput(session, "var_explicatives", 
                            choices = colnames( merged_data_type() %>% select_if(function(x) is.factor(x))))
        updateSelectInput(session, "emmeans_expliquees", 
                            choices = colnames( merged_data_type() %>% select_if(function(x) is.numeric(x) || is.integer(x))))
        updateSelectInput(session, "emmeans_explicatives", 
                            choices = colnames( merged_data_type() %>% select_if(function(x) is.factor(x))))
        updateSelectInput(session, "var_expliquees_kw", 
                            choices = colnames( merged_data_type() %>% select_if(function(x) is.numeric(x) || is.integer(x))))
        updateSelectInput(session, "var_explicatives_kw", 
                            choices = colnames( merged_data_type() %>% select_if(function(x) is.factor(x))))
        updateSelectInput(session, "khi2_cat", 
                            choices = colnames( merged_data_type() %>% select_if(function(x) is.factor(x))))
        updateSelectInput(session, "khi2_num", 
                            choices = colnames( merged_data_type() %>% select_if(function(x) is.numeric(x) || is.integer(x))))
        updateSelectInput(session, "pearson_num", 
                            choices = colnames( merged_data_type() %>% select_if(function(x) is.numeric(x) || is.integer(x))))
        updateSelectInput(session, "pearson_cat", 
                            choices = colnames( merged_data_type() %>% select_if(function(x) is.factor(x))))
        updateSelectInput(session, "wilcox_num", 
                            choices = colnames( merged_data_type() %>% select_if(function(x) is.numeric(x) || is.integer(x))))
        updateSelectInput(session, "wilcox_cat", 
                            choices = colnames( merged_data_type() %>% select_if(function(x) is.factor(x))))
        updateSelectInput(session, "mixte_expliquee", 
                            choices = colnames( merged_data_type()  %>% select_if(function(x) is.numeric(x) || is.integer(x))))
        updateSelectInput(session, "mixte_explicatives_fixes", 
                            choices = colnames( merged_data_type()))
        updateSelectInput(session, "mixte_explicatives_aleas", 
                            choices = colnames( merged_data_type()))
        updateSelectInput(session, "mixte_effet_hypothesisGraph", 
                            choices = colnames( merged_data_type()))
        updateSelectInput(session,"mixte_expliquee_model",choices=names(mixte_models_list$models)) 
        updateSelectInput(session,"mixte_anova",choices=names(mixte_models_list$models)) 
        updateSelectInput(session,"mixte_emmeans",choices=names(mixte_models_list$models))
        updateSelectInput(session, "mixte_emmeans_explicatives", 
                            choices = colnames( merged_data_type() %>% select_if(function(x) is.factor(x))))
        })
        
        #On utilise une fonction permettant d'obternir la liste des variables numériques
        num_columns <- eventReactive(input$applyTypes,{
        numeric_integer_columns <- colnames( merged_data_type() %>% select_if(function(x) is.numeric(x) || is.integer(x)))
        return(numeric_integer_columns)
        })
        
        # Afficher les résultats de la fusion dans une table
        output$merged_data_table <- renderDataTable(merged_data(),
                                                    options = list(
                                                    pageLength = 10,
                                                    autoWidth = TRUE,
                                                    lengthMenu = list(c(10,50,100, -1), c("10","50","100", "All"))
                                                    )
        )
        
        #=============================================================================
        #Cette partie gère la partie "Graphiques"
        
        observe({
        updateSelectInput(session,"dataset_graph", 
                            choices = c("cars","airquality","iris",input$files$name))
        })
        
        
        graph_data <- eventReactive(input$dataset_graph,{
        if (input$dataset_graph == 'cars') {
            return(datasets::cars)
        }
        if (input$dataset_graph == "airquality"){
            return(datasets::airquality)
        }
        if (input$dataset_graph == "iris"){
            return(datasets::iris)
        }
        if (input$dataset_graph == input$files$name) {
            return(merged_data_type())
        }
        })
        
        observe({
        updateSelectInput(session,"graph_x", choices = colnames(graph_data()))
        updateSelectInput(session,"graph_y", choice = colnames(graph_data()))
        updateSelectInput(session,"graph_fill", choices = c("None",colnames(graph_data())),selected = "None")
        updateSelectInput(session,"facet_a", choices = c(".",colnames(graph_data())),selected = ".")
        updateSelectInput(session,"facet_b", choices = c(".",colnames(graph_data())),selected = ".")
        
        })
        
        
        observe({
        facet_formula = as.formula(paste0(input$facet_a, ' ~ ', input$facet_b))
        })
        
        observe({
        output$graph_graph <- renderPlotly({
            
            if (input$type_graph == 'Barplot'){
            if (input$graph_fill == 'None'){
                p <- ggplot(data = graph_data(),aes(x=!!sym(input$graph_x),y=!!sym(input$graph_y))) + geom_bar(stat="identity") + facet_grid(as.formula(paste0(input$facet_a, ' ~ ', input$facet_b))) + labs(x = input$graph_x, y = input$graph_y)
                #p <- plot_ly(data = data(),x=~get(input$graph_x),y=~get(input$graph_y),type='bar')
                #p <- p %>% layout(xaxis=list(title=input$graph_x),yaxis=list(title=input$graph_y)) 
                p <- ggplotly(p)
            } else {
                p <-  ggplot(data = graph_data(), aes(x = !!sym(input$graph_x), y = !!sym(input$graph_y), fill = !!sym(input$graph_fill))) +
                geom_bar(stat = "identity") +
                facet_grid((as.formula(paste0(input$facet_a, ' ~ ', input$facet_b)))) +
                labs(x = input$graph_x, y = input$graph_y)
                #p <- plot_ly(data = data(),x=~get(input$graph_x),y=~get(input$graph_y),color=~get(input$graph_fill),type='bar')
                #p <- p %>% layout(xaxis=list(title=input$graph_x),yaxis=list(title=input$graph_y))
                p <- ggplotly(p)
            }
            
            return(p)
            }
            
            if (input$type_graph == 'Geomline'){
            if (input$graph_fill == 'None'){
                p <- ggplot(data = graph_data(),aes(x=!!sym(input$graph_x),y=!!sym(input$graph_y))) +  stat_summary(fun = "mean", geom = "line") + facet_grid(as.formula(paste0(input$facet_a, ' ~ ', input$facet_b))) + labs(x = input$graph_x, y = input$graph_y)
                #p <- plot_ly(data = data(),x=~get(input$graph_x),y=~get(input$graph_y),type='bar')
                #p <- p %>% layout(xaxis=list(title=input$graph_x),yaxis=list(title=input$graph_y)) 
                p <- ggplotly(p)
            } else {
                p <-  ggplot(data = graph_data(), aes(x = !!sym(input$graph_x), y = !!sym(input$graph_y), colour=!!sym(input$graph_fill))) +  stat_summary(fun = "mean", geom = "line",aes(group=!!sym(input$graph_fill)))  +
                facet_grid((as.formula(paste0(input$facet_a, ' ~ ', input$facet_b)))) + labs(x = input$graph_x, y = input$graph_y)
                #p <- plot_ly(data = data(),x=~get(input$graph_x),y=~get(input$graph_y),color=~get(input$graph_fill),type='bar')
                #p <- p %>% layout(xaxis=list(title=input$graph_x),yaxis=list(title=input$graph_y))
                p <- ggplotly(p)
            }
            
            return(p)
            }
            
            if (input$type_graph == 'Boxplot'){
            if (input$graph_fill == 'None'){
                p <-  ggplot(data = graph_data(), aes(x = !!sym(input$graph_x), y = !!sym(input$graph_y))) +
                geom_boxplot() +
                facet_grid((as.formula(paste0(input$facet_a, ' ~ ', input$facet_b)))) +
                labs(x = input$graph_x, y = input$graph_y)
                p <- ggplotly(p)
            } else {
                p <-  ggplot(data = graph_data(), aes(x = !!sym(input$graph_x), y = !!sym(input$graph_y), fill = !!sym(input$graph_fill))) +
                geom_boxplot() +
                facet_grid((as.formula(paste0(input$facet_a, ' ~ ', input$facet_b)))) +
                labs(x = input$graph_x, y = input$graph_y)
            }
            
            return(ggplotly(p)%>%layout(boxmode = "group"))
            }
            if (input$type_graph == 'Density plot'){
            p <- ggplot(graph_data(), aes_string(x=input$graph_x)) + 
                geom_density() + facet_grid((as.formula(paste0(input$facet_a, ' ~ ', input$facet_b))))
            return(ggplotly(p))
            }
            if (input$type_graph == 'Histograme'){
            if (input$graph_fill == 'None') {
                p <- ggplot(graph_data(), aes_string(x=input$graph_x)) + 
                geom_histogram() + facet_grid((as.formula(paste0(input$facet_a, ' ~ ', input$facet_b))))
            } else {
                p <- ggplot(graph_data(), aes_string(x=input$graph_x,color=input$graph_fill)) + 
                geom_histogram() + facet_grid((as.formula(paste0(input$facet_a, ' ~ ', input$facet_b))))
            }
            
            return(ggplotly(p))
            }
            if (input$type_graph == 'Scatterplot'){
            if (input$graph_fill == 'None') {
                p <-  ggplot(data = graph_data(), aes(x = !!sym(input$graph_x), y = !!sym(input$graph_y))) +
                geom_point() +
                facet_grid((as.formula(paste0(input$facet_a, ' ~ ', input$facet_b)))) +
                labs(x = input$graph_x, y = input$graph_y)
                p <- ggplotly(p)
                
            } else {
                p <-  ggplot(data = graph_data(), aes(x = !!sym(input$graph_x), y = !!sym(input$graph_y), fill = !!sym(input$graph_fill))) +
                geom_point() +
                facet_grid((as.formula(paste0(input$facet_a, ' ~ ', input$facet_b)))) +
                labs(x = input$graph_x, y = input$graph_y)
            }
            
            return(p)
            }
            
        })
        
        })
        
        #=============================================================================
        #Cette partie gère l'analyse des données
        
        
        
        shapiro_table <- eventReactive(input$files,{
        shapiro <- shapiro_table_function(data=merged_data_type(),
                                            num_col=num_col())
        
        return(shapiro)
        })
        
        
        output$shapiro_table <- renderDataTable(shapiro_table(),
                                                options = list(
                                                pageLength = 10,
                                                autoWidth = TRUE,
                                                lengthMenu = list(c(10,50,100, -1), c("10","50","100", "All"))
                                                )
        )
        
        
        
        anova_table <- eventReactive(input$anova_button,{
        anova_table <- anova_table_function(data=merged_data_type(),
                                            var_expliquee=input$var_expliquees, 
                                            var_explicatives=input$var_explicatives,
                                            output=output)
        return(anova_table)
        })
        
        
        
        output$anova_table <- renderDataTable(anova_table(),
                                            extensions = "Buttons",
                                            options = list(
                                                pageLength = 10,
                                                autoWidth = TRUE,
                                                lengthMenu = list(c(10,50,100, -1), c("10","50","100", "All"))
                                            )
        )
        
        output$anova_button_download <- downloadHandler(
        filename = function(){"anova_results.xlsx"}, 
        content = function(fname){
            tab <- anova_table()
            tab <- cbind(RowNames = rownames(tab), tab)
            writexl::write_xlsx(tab, fname)
        }
        )

        Temoins <- reactiveVal(list())
        
        observe({
        temoins <- list()
        if (input$type_comp == "trt.vs.ctrl") {
                for (col in input$emmeans_explicatives) {
                temoins[[col]] <- selectInput(
                inputId = paste0("temoin_", col),
                label = paste0("temoin : ", col),
                choices = unique(merged_data()[[col]]),
                selected = unique(merged_data()[[col]])[1]
                )
            }
            
        } else if (input$type_comp == "personnalisé") {
            emm <- emmeans_function(data=merged_data_type(),
                                        var_expliquee=input$emmeans_expliquees,
                                        var_explicatives=input$emmeans_explicatives)
            temoins$Groupe1 <- selectInput(
                inputId = "groupe1",
                label = "Groupe 1",
                choices = unique(contrast_list_function(emm)),
                multiple = TRUE
            )
            temoins$Groupe2 <- selectInput(
                inputId = "groupe2",
                label = "Groupe 2",
                choices = unique(contrast_list_function(emm)),
                multiple = TRUE
            )
            temoins$name_contrast <- textInput("contrast_name","Nom du contrast")
            temoins$contrast_list_button <- actionButton("contrast_list_button", "Ajouter contraste",class="btn-primary")
            
        }
        Temoins(temoins)
        })
        

        output$Temoins <- renderUI({
        temoins <- Temoins()
        if (!is.null(temoins) && length(temoins) > 0) {
            div(
            lapply(names(temoins), function(col) {
                temoins[[col]]
            })
            )
        }
        })
        

                observeEvent(input$contrast_list_button,{
        contrast_list$ma_liste[[input$contrast_name]] <- contrast_function(input=input,output=output,emm=emm,ref1=input$groupe1,ref2=input$groupe2,data=merged_data_type())
        
        })
        
        ref_index <- eventReactive(input$emmeans_button,{
        
        ref_index <- ref_index_function(data=merged_data_type(),
                                        var_expliquee=input$emmeans_expliquees,
                                        var_explicatives=input$emmeans_explicatives,
                                        input=input,
                                        Temoins=Temoins())
        
        return(ref_index)
        
        })
        
        emmeans_table <- eventReactive(input$emmeans_button,{
        emmeans_table <- emmeans_table_function(data=merged_data_type(),
                                var_expliquee=input$emmeans_expliquees,
                                var_explicatives=input$emmeans_explicatives,
                                type_comp=input$type_comp,
                                ref_index = ref_index(),
                                output=output,
                                input=input)
        return(emmeans_table)
        
        
        })
        
        
        
        
        contrasts_table <- eventReactive(input$emmeans_button,{
        contrasts_table <- contrasts_table_function(data=merged_data_type(),
                                                    var_expliquee=input$emmeans_expliquees,
                                                    var_explicatives=input$emmeans_explicatives,
                                                    type_comp=input$type_comp,
                                                    ref_index = ref_index(),
                                                    output=output, 
                                                    input=input, 
                                                    contrast_list=contrast_list$ma_liste)
        
        return(contrasts_table)
        
        })
        
        
        
        output$emmeans_table <- renderDataTable(datatable(emmeans_table(),
                                                        options = list(
                                                            pageLength = 10,
                                                            autoWidth = TRUE,
                                                            lengthMenu = list(c(10,50,100, -1), c("10","50","100", "All"))
                                                        ),
                                                        caption = "Moyennes ajustées",
        )
        )
        
        
        output$emmeans_button_download <- downloadHandler(
        filename = function(){"emmeans_results.xlsx"}, 
        content = function(fname){
            tab <- emmeans_table()
            tab <- cbind(RowNames = rownames(tab), tab)
            writexl::write_xlsx(tab, fname,row.names = FALSE)
        }
        )
        
        output$contrast_table <- renderDataTable(datatable(contrasts_table(),
                                                        options = list(
                                                            pageLength = 10,
                                                            autoWidth = TRUE,
                                                            lengthMenu = list(c(10,50,100, -1), c("10","50","100", "All"))
                                                        ),
                                                        caption = "Contrasts",
                                                        )
                                                    )
        
        output$contrast_button_download <- downloadHandler(
        filename = function(){"contrast_results.xlsx"}, 
        content = function(fname){
            tab <- contrasts_table()
            tab <- cbind(RowNames = rownames(tab), tab)
            writexl::write_xlsx(tab, fname,row.names = FALSE)
        }
        )
        
        kw_table <- eventReactive(input$kw_button,{
        
        kw_table <- kw_table_function(cat_col=inputvar_explicatives_kw,
                                        num_col=input$var_expliquees_kw,
                                        data=merged_data_type(),
                                        output=output)
        
        return(kw_table)
        
        })
        
        output$kw_table <- renderDataTable(kw_table(),
                                        options = list(
                                            pageLength = 10,
                                            autoWidth = TRUE,
                                            lengthMenu = list(c(10,50,100, -1), c("10","50","100", "All"))
                                        )
        )
        
        
        
        pearson_result <- eventReactive(input$pearson_button,{
        X_level = unique(merged_data()[[input$pearson_cat]])[1]
        Y_level = unique(merged_data()[[input$pearson_cat]])[2]
        X = merged_data()[merged_data()[,input$pearson_cat]==X_level,input$pearson_num]
        Y = merged_data()[merged_data()[,input$pearson_cat]==Y_level,input$pearson_num]
        x = pull(X,1)
        y = pull(Y,1)
        return(cor.test(x,y, method = "pearson"))
        })
        
        output$pearson_result <- renderPrint(pearson_result())
        
        
        wilcox_result <- eventReactive(input$wilcox_button,{
        X_level = unique(merged_data()[[input$wilcox_cat]])[1]
        Y_level = unique(merged_data()[[input$wilcox_cat]])[2]
        X = merged_data()[merged_data()[,input$wilcox_cat]==X_level,input$wilcox_num]
        Y = merged_data()[merged_data()[,input$wilcox_cat]==Y_level,input$wilcox_num]
        x = pull(X,1)
        y = pull(Y,1)
        return(wilcox.test(x,y, paired=TRUE))
        })
        
        output$wilcox_result <- renderPrint(wilcox_result())
        #=============================================================================
        #Cette partie gère la partie "Modèles classiques"
        observe({
        updateSelectInput(session, "acp_col", choices = num_columns())
        })
        
        observe({
        updateSliderInput(session,"pls_slider",max = length(input$pls_x))
        })
        
        observeEvent(input$acp_button,{
        output$plotly_acp_graph <- renderPlotly({
            acp_data <- merged_data()[, input$acp_col]
            res.pca <- prcomp(acp_data, scale = TRUE)
            pl <- fviz_pca_ind(
            res.pca,
            col.ind = merged_data()[["Source"]],  # Color by the quality of representation
            repel = TRUE,  # Avoid text overlapping
            label = "None"
            ) + scale_color_discrete()
            
            # Convertir le graphique ggplot2 en graphique plotly
            pl <- ggplotly(pl)
            
            return(pl)
        })
        
        })
        
        observe({
        updateSelectInput(session, "pls_x", choices = num_columns())
        updateSelectInput(session, "pls_y", choices = num_columns())
        })
        
        
        observeEvent(input$pls_button,{
        output$pls_text <-  renderPrint({
            pls_formula <- as.formula(paste0(input$pls_y,'~',paste(input$pls_x,collapse='*')))
            pls.result <- plsr(pls_formula,data=merged_data_type(),scale=TRUE, validation="CV")
            pls_sum <- summary(pls.result)
            return(pls_sum)
        })
        
        })
        
        observe({
        updateSelectInput(session, "lm_x", choices = num_columns())
        updateSelectInput(session, "lm_y", choices = colnames( merged_data_type() %>% select_if(function(x) is.factor(x))))
        })
        
        
        observeEvent(input$lm_button,{
        output$lm_text <-  renderPrint({
            merged_data <- merged_data_type()
            lm_formula <- as.formula(paste0(input$lm_x,'~',paste(input$lm_y,collapse='*')))
            lm_result <- lm(lm_formula,data = merged_data)
            return(summary(lm_result))
        })
        
        })


        observeEvent(input$mixte_button,{
            new_model <- mixte_model_function(data=merged_data_type(),
                                            var_expliquee=input$mixte_expliquee, 
                                            var_explicatives_fixes=input$mixte_explicatives_fixes,
                                            var_explicatives_alea=input$mixte_explicatives_aleas)
            R2 <- round(r.squaredGLMM(new_model)[2],4)
            name_model <- input$mixte_name
            var_explicatives_aleas <- paste(input$mixte_explicatives_aleas,collapse =" ")
            var_explicatives_fixes <- paste(input$mixte_explicatives_fixes,collapse =" ")
            new_row <- data.frame(
                Nom=name_model,
                R2=R2,
                Variables_Explicatives_Aleatoires=var_explicatives_aleas,
                Variables_Explicatives_Fixes=var_explicatives_fixes 
            )
            mixte_models_list$df <- rbind(mixte_models_list$df, new_row)
            mixte_models_list$models[[name_model]] <- new_model
        })

        mixte_table <- eventReactive(input$mixte_button,{
        mixte_table <- mixte_models_list$df
        return(mixte_table)
        })
        
        
        
        output$mixte_table <- renderDataTable(mixte_table(),
                                            extensions = "Buttons",
                                            options = list(
                                                pageLength = 10,
                                                autoWidth = TRUE,
                                                lengthMenu = list(c(10,50,100, -1), c("10","50","100", "All"))
                                            )
        )
        
        output$mixte_button_download <- downloadHandler(
        filename = function(){"mixte_results.xlsx"}, 
        content = function(fname){
            tab <- mixte_table()
            tab <- cbind(RowNames = rownames(tab), tab)
            writexl::write_xlsx(tab, fname)
        }
        )

        observeEvent(input$mixte_button,{
            if (length(mixte_models_list$models)>1) {
                output$mixte_comparaison_table <-  renderDataTable(mixte_model_comparaison(mixte_models_list$models))

            }            
        })

        observeEvent(input$mixte_anova_button,{
            output$mixte_anova_table <-  renderDataTable(mixte_model_anova(mixte_models_list$models[[input$mixte_anova]]),
                                                        options = list(
                                                        pageLength = 10,
                                                        autoWidth = TRUE,
                                                        lengthMenu = list(c(10,50,100, -1), c("10","50","100", "All"))
                                                        ))
        })
        observeEvent(input$hypothesisGraph_button,{
            output$graphsOutput <- renderUI({
            graph_names <- mixte_graph(model=mixte_models_list$models[[input$mixte_expliquee_model]],effets=input$mixte_effet_hypothesisGraph,output=output)
  
            plot_outputs <- lapply(graph_names, function(name) {
                tagList(
                    plotly::plotlyOutput(name),
                    br(),br()
                )
            
            })
  
            do.call(tagList, plot_outputs)
            })
        })


        Temoins_mixte <- reactiveVal(list())
        
        observe({
        temoins_mixte <- list()
        if (input$type_comp_mixte_emmeans == "trt.vs.ctrl") {
                for (col in input$mixte_emmeans_explicatives) {
                temoins_mixte[[col]] <- selectInput(
                inputId = paste0("temoin_", col),
                label = paste0("temoin : ", col),
                choices = unique(merged_data()[[col]]),
                selected = unique(merged_data()[[col]])[1]
                )
            }
            
        } else if (input$type_comp_mixte_emmeans == "personnalisé") {
            emm <- mixte_emmeans_function(mod=mixte_models_list$models[[input$mixte_emmeans]],
                                        var_explicatives=input$mixte_emmeans_explicatives)
            temoins_mixte$Groupe1 <- selectInput(
                inputId = "groupe1_mixte",
                label = "Groupe 1",
                choices = unique(contrast_list_function(emm)),
                multiple = TRUE
            )
            temoins_mixte$Groupe2 <- selectInput(
                inputId = "groupe2_mixte",
                label = "Groupe 2",
                choices = unique(contrast_list_function(emm)),
                multiple = TRUE
            )
            temoins_mixte$contrast_name_mixte <- textInput("contrast_name_mixte","Nom du contrast")
            temoins_mixte$contrast_list_button_mixte <- actionButton("contrast_list_button_mixte", "Ajouter contraste",class="btn-primary")
            
        }
        Temoins_mixte(temoins_mixte)
        })
        

        output$Temoins_mixte <- renderUI({
        temoins_mixte <- Temoins_mixte()
        if (!is.null(temoins_mixte) && length(temoins_mixte) > 0) {
            div(
            lapply(names(temoins_mixte), function(col) {
                temoins_mixte[[col]]
            })
            )
        }
        })

        ref_index_mixte <- eventReactive(input$mixte_emmeans_button,{
        emmeans_mixte <- mixte_emmeans_function(mixte_models_list$models[[input$mixte_emmeans]],
                                                input$mixte_emmeans_explicatives)
        ref_index_mixte <- ref_index_function(emm = emmeans_mixte,
                                        input=input,
                                        Temoins=Temoins_mixte())
        return(ref_index_mixte)
        
        })

        observeEvent(input$contrast_list_button_mixte,{
        emmeans_mixte <- mixte_emmeans_function(mixte_models_list$models[[input$mixte_emmeans]],
                                                input$mixte_emmeans_explicatives)
        contrast_list_mixte$ma_liste[[input$contrast_name_mixte]] <- mixte_contrast_function(emm=emmeans_mixte,
                                                                                        ref1=input$groupe1_mixte,
                                                                                        ref2=input$groupe2_mixte
                                                                                    )
        
        })
        
        emmeans_table_mixte <- eventReactive(input$mixte_emmeans_button,{
        emmeans_mixte <- mixte_emmeans_function(mixte_models_list$models[[input$mixte_emmeans]],
                                                input$mixte_emmeans_explicatives)
        emmeans_table_mixte <- mixte_emmeans_function_table(mod=emmeans_mixte, 
                                                            type_comp=input$type_comp_mixte_emmeans,
                                                            output=output,
                                                            input$mixte_emmeans_explicatives)
        return(emmeans_table_mixte)
        
        
        })
        
        contrasts_table_mixte <- eventReactive(input$mixte_emmeans_button,{
        emmeans_mixte <- mixte_emmeans_function(mixte_models_list$models[[input$mixte_emmeans]],
                                                input$mixte_emmeans_explicatives)
        contrasts_table_mixte <- mixte_contrasts_table_function(type_comp=input$type_comp_mixte_emmeans,
                                                    ref_index = ref_index_mixte(),
                                                    mod=emmeans_mixte,
                                                    contrast_list=contrast_list_mixte$ma_liste)
        
        return(contrasts_table_mixte)
  })
        output$mixte_emmeans_table <- renderDataTable(datatable(emmeans_table_mixte(),
                                                        options = list(
                                                            pageLength = 10,
                                                            autoWidth = TRUE,
                                                            lengthMenu = list(c(10,50,100, -1), c("10","50","100", "All"))
                                                        ),
                                                        caption = "Moyennes ajustées",
        )
        )
        
        
        output$mixte_emmeans_button_download <- downloadHandler(
        filename = function(){"emmeans_results.xlsx"}, 
        content = function(fname){
            tab <- emmeans_table()
            tab <- cbind(RowNames = rownames(tab), tab)
            writexl::write_xlsx(tab, fname,row.names = FALSE)
        }
        )
        
        output$mixte_contrast_table <- renderDataTable(datatable(contrasts_table_mixte(),
                                                        options = list(
                                                            pageLength = 10,
                                                            autoWidth = TRUE,
                                                            lengthMenu = list(c(10,50,100, -1), c("10","50","100", "All"))
                                                        ),
                                                        caption = "Contrasts",
                                                        )
                                                    )
        
        output$mixte_contrast_button_download <- downloadHandler(
        filename = function(){"contrast_results.xlsx"}, 
        content = function(fname){
            tab <- contrasts_table_mixte()
            tab <- cbind(RowNames = rownames(tab), tab)
            writexl::write_xlsx(tab, fname,row.names = FALSE)
        }
        )
    })
    }