```{r setup, echo=FALSE, warning=FALSE, message=FALSE}
knitr::opts_chunk$set(
  echo = F,
  collapse = TRUE,
  message = FALSE,
  warning = FALSE,
  out.width = "70%",
  fig.align = 'center',
  fig.show = "hold"
)
library(tidyverse)
library(showtext)
font_add_google("Roboto", "roboto")
showtext_auto()
library(gt)
library(xts)
library(dygraphs) # https://rstudio.github.io/dygraphs/index.html
library(googleAuthR)
library(lubridate)

options(googleAuthR.scopes.selected = "https://www.googleapis.com/auth/analytics.readonly")
# Loading service account JSON from .Renviron
gar_auth_service(json_file=Sys.getenv("SERVICE_JSON"))
library(googleAnalyticsR)

account_id <- 62965925 # NtS GA Account
view_id <- 105540599 # NtS Main view
```

```{r, echo=F}

# Pull user and sessions data for line chart
ga_sessions <- google_analytics(viewId=view_id, date_range = c(Sys.Date()-30,Sys.Date()-1),
                                metrics=c("users","sessions"),dimensions=c("date"),max=-1)

# Break up the table data into 2 separate calls as we can only pull 10 metrics per query
ga_channels_1 <- google_analytics(viewId=view_id, date_range = c(Sys.Date()-30,Sys.Date()-1),
                                metrics=c("users","newUsers","pageviewsPerSession","avgSessionDuration","goal1Completions","goal1Value","bounces"),
                                dimensions=c("channelGrouping"),max=-1)

ga_channels_2 <- google_analytics(viewId=view_id, date_range = c(Sys.Date()-31,Sys.Date()-1),
                                metrics=c("sessions","pageviews", "sessionDuration"),
                                dimensions=c("channelGrouping"),max=-1)

# Merge the 2 channel queries back together
ga_channels <- ga_channels_1 %>% left_join(ga_channels_2,by=c("channelGrouping"))
```


```{r, fig.width=8, fig.height=1.5}
ga_sessions_xts <- xts(ga_sessions %>% select(users), order.by=ga_sessions$date)

dygraph(ga_sessions_xts) %>% 
  #dyRangeSelector() %>% # Optionally, we can include an interactive date range selector
  dyOptions(fillGraph = TRUE, fillAlpha = 0.15, gridLineColor = "#DDDDDD", axisLabelFontSize = 10) %>%
  dySeries("users", label = "Users",  drawPoints = T, pointSize = 2, 
           strokeWidth=2, color = "#058DC7") %>%
  dyAxis(name = "y", axisLineColor = "white") %>%
  dyAxis(name = "x", drawGrid = F) %>%
  dyLegend(show = "always", hideOnMouseOut =F)
```

```{r}
ga_channels %>% 
  # Generate summary row at the top first. channelGrouping is set to "" to hide any label for the summary row
  summarise(users = sum(users), newUsers=sum(newUsers),sessions=sum(sessions),bounceRate=sum(bounces)/sum(sessions), pageviewsPerSession = sum(pageviews)/sum(sessions), avgSessionDuration = sum(sessionDuration)/sum(sessions), goal1Completions = sum(goal1Completions),goal1ConversionRate=sum(goal1Completions)/sum(sessions), goal1Value=sum(goal1Value)) %>% mutate(channelGrouping = "") %>% 
  # Bind the remaining data rows for the detailed data
  bind_rows(ga_channels %>% mutate(bounceRate = bounces/sessions, goal1ConversionRate = goal1Completions/sessions) %>% select(-pageviews,-sessionDuration,-bounces) %>% arrange(desc(users))) %>%
  mutate(avgSessionDuration = seconds_to_period(round(avgSessionDuration))) %>%
  # Begin constructing gt table
  gt(rowname_col = "channelGrouping") %>%
  tab_spanner(label = "Acquisition", columns = vars(users, newUsers, sessions)) %>%
  tab_spanner(label = "Behavior", columns = vars(bounceRate, pageviewsPerSession, avgSessionDuration)) %>%
  tab_spanner(label = "Conversions", columns = vars(goal1ConversionRate, goal1Completions, goal1Value)) %>%
  tab_stubhead(label = "Channel Grouping") %>%
  cols_label(
    channelGrouping = "Default Channel Grouping",
    users = "Users",
    newUsers = "New Users",
    sessions = html("Sessions"),
    bounceRate = "Bounce Rate",
    pageviewsPerSession = "Pages / Session",
    avgSessionDuration = "Avg. Session Duration",
    goal1ConversionRate = ">1 Page per Session (Goal 1 Conversion Rate)",
    goal1Completions = ">1 Page per Session (Goal 1 Completions)",
    goal1Value = ">1 Page per Session (Goal 1 Value)"
  ) %>%
  fmt_percent(
    columns=vars(bounceRate,goal1ConversionRate)
  ) %>%
  fmt_number(
    columns = vars(pageviewsPerSession),
    decimals = 2
  ) %>%
  tab_style(
    style = list(cell_fill(color = "#E9E9E9"),
              cell_text(font = "Roboto", weight="bold",v_align="middle",size=px(10),align="center")),
    locations = list(cells_stubhead(),
                          cells_column_spanners(c("Acquisition","Behavior","Conversions")))
  ) %>%
  tab_style(
    style = list(cell_fill(color = "#E9E9E9"),
              cell_text(font = "Roboto", weight="bold",v_align="middle",size=px(10),align="center")),
    locations = cells_column_labels(vars(users,newUsers,sessions,bounceRate,pageviewsPerSession,avgSessionDuration,goal1ConversionRate,goal1Completions,goal1Value))
  )  %>%
  tab_style(
    style = list(cell_fill(color = "#FFFFFF"),
              cell_text(font = "Roboto",v_align="top",size=px(12),align="right")),
    locations = list(cells_body(columns = T, rows  = T),cells_stub(rows  = T))
  ) %>%
  tab_style(
    style = list(cell_fill(color = "#F8F8F8"),
              cell_text(font = "Roboto",v_align="top",size=px(18),align="right")),
    locations = cells_body(columns = T, rows  = 1)
  )

```

