# clear environment
rm(list = ls())

# load library
library(knitr)
library(car)
## Loading required package: carData
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ✖ dplyr::recode() masks car::recode()
## ✖ purrr::some()   masks car::some()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(jtools)
library(readr)
library(readxl)
library(flexdashboard)
library(plotly)
## 
## Attaching package: 'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following object is masked from 'package:graphics':
## 
##     layout
library(shiny)

# turn this off if you want scientific notation
options(scipen = 999)

# change wd
current_wd <- dirname(rstudioapi::getSourceEditorContext()$path)
setwd(current_wd)
# Function to create the plot
plot_results <- function(srn) {
  SD %>%
    filter(SRN == srn) %>%
    ggplot(aes(x = ResultDate_Local, y = Result, color = ResultName)) +
    geom_line() +
    geom_point() +
    facet_wrap(~ResultName, scales = "free_y", ncol = 2) +
    theme_minimal() +
    labs(title = paste("Results for Patient", srn),
         x = "Date",
         y = "Result Value") +
    theme(legend.position = "none")
}
# Create the dashboard
ui <- fluidPage(
  titlePanel("Patient Results Dashboard"),
  
  sidebarLayout(
    sidebarPanel(
      selectInput("patient_srn", "Select Patient SRN:", 
                  choices = unique(SD$SRN),
                  selected = unique(SD$SRN)[1])
    ),
    
    mainPanel(
      plotlyOutput("results_plot"),
      tableOutput("latest_results")
    )
  )
)

server <- function(input, output) {
  output$results_plot <- renderPlotly({
    p <- plot_results(input$patient_srn)
    ggplotly(p)
  })
  
  output$latest_results <- renderTable({
    SD %>%
      filter(SRN == input$patient_srn) %>%
      group_by(ResultName) %>%
      select(ResultName, Result, Units, ResultDate_Local)
  })
}

# Run the application
shinyApp(ui = ui, server = server)
## PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.
Shiny applications not supported in static R Markdown documents