---
title: "Main Document"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

library(tidyverse)
library(blastula)
```

# An R Markdown Document (Main Report)

This is an **R Markdown** document. *Markdown* is a simple formatting syntax for writing on the web. **R Markdown** takes this a step further by combining *Markdown* prose and **R** code into reproducible documents that can be output as HTML, PDF, Word, and many more output formats. For more details on using **R Markdown**, have a look through [its documentation site](https://rmarkdown.rstudio.com/docs/).

Here is some **R** code, which is contained within a code chunk:

```{r diamonds_plot}

diamonds %>%
  group_by(carat, cut) %>%
  summarize(mean_price = mean(price)) %>%
  filter(cut != "Fair", carat < 3) %>%
  ggplot() +
  geom_point(aes(x = carat, y = mean_price)) +
  stat_smooth(
    aes(x = carat, y = mean_price),
    method = "gam"
  ) +
  facet_wrap(facets = vars(cut)) +
  labs(
    title = "Diamond Prices",
    subtitle = "Faceted by Diamond Cut",
    caption = "Source: The [diamonds] dataset in {ggplot2}.",
    x = "Carats", y = "Mean Price, US Dollars"
  ) +
  scale_y_continuous(labels = scales::dollar)
```

Let's get some summarized data about yearly home sales in Dallas, TX and also write that data to a CSV file:

```{r dallas_home_sales}

dallas_home_sales <- 
  txhousing %>%
  filter(city == "Dallas") %>%
  group_by(year) %>%
  summarize(total_sales = sum(sales, na.rm = TRUE))

dallas_home_sales
```

It looks like the year `r dallas_home_sales %>% filter(total_sales == max(total_sales)) %>% pull(year)` had the greatest number of sales. Let's create a CSV for distribution (this code chunk that generates the CSV is ultimately not shown because we used `echo=FALSE` as a chunk option).

```{r write_csv, echo=FALSE}
dallas_home_sales %>% write_csv("dallas_home_sales.csv")
```

We can create an email on **Posit Connect** that aligns with the content from this report. We do this with the `render_connect_email()` and `attach_connect_email()` functions from the **blastula** package. The email subdocument (`"connect-example-email.Rmd"`) is used to craft the contents of the email, drawing upon results available in this document. Attachments for the email can added by using the arguments:

- `attachments` (for any output files or included files)
- `attach_output` (which attaches the rendered report)

```{r connect_email_setup, echo=FALSE}
render_connect_email(input = "connect-example-email.Rmd") %>%
  attach_connect_email(
    subject = "Posit Connect HTML Email",
    attach_output = TRUE,
    attachments = c("dallas_home_sales.csv", "austin_home_sales.csv")
  )
```

