transactions <- get_transactions()
brand_sales <- products %>% 
  inner_join(transactions, by = "product_id") %>%
  group_by(product_category, product_type, brand) %>%
  summarise(total_quantity = sum(quantity, na.rm = TRUE))

## Investigate product categories with greatest opportunity for Private Brand Growth,
## using quantity as indicator of consumer choice.
top_diff <- brand_sales %>%
  ## Include NA so that only products with confirmed alternative are compared.
  pivot_wider(names_from = brand, values_from = total_quantity) %>% 
  mutate(difference = National - Private) %>%
  arrange(desc(difference)) %>%
  head(25) 

## Use difference to scope brand_sales for plotting
top_comp <- brand_sales %>%
  semi_join(top_diff, by = c('product_category', 'product_type')) 

# Create the plot
ggplot(top_comp, aes(x = reorder(product_type, -total_quantity), y = total_quantity, fill = brand)) +
  geom_bar(stat = "identity", position = "stack") +
  coord_flip() +
  labs(title = "Consumer Choices by Brand",
       subtitle = "Top 20 Private Label Opportunities",
       x = "Product Type",
       y = "Total Quantity Sold",
       fill = "Brand") 

## Drill Down into yogurt sales
yogurt_transactions <- transactions %>% 
  inner_join(products, 'product_id') %>%
  filter(product_type == 'YOGURT NOT MULTI-PACKS')

yogurt_sales <- yogurt_transactions %>%
  mutate( transaction_month = month(transaction_timestamp)) %>%
  group_by(transaction_month, brand) %>%
  summarise(total_quantity = sum(quantity, na.rm = TRUE), total_sales = sum(sales_value)) 

ggplot(yogurt_sales, aes(x = transaction_month, y = total_quantity, fill = brand)) +
  geom_bar(stat = "identity", position = "dodge") +  # Side-by-side bars for each brand
  labs(title = "Yogurt Quantity Sold Over Time (Non-Multi-Packs)",
       x = "Month",
       y = "Total Quantity Sold",
       fill = "Brand") +  # Legend title for brand
  theme_minimal() +
  scale_color_brewer()

## Note I am reusing the filter and join shown in previous step
yogurt_transactions <- yogurt_transactions %>% 
  mutate(
    Loyalty_Price = (sales_value - (retail_disc + coupon_match_disc)) / quantity, 
    Non_Loyalty_Price = (sales_value - (coupon_match_disc)) / quantity)

ggplot(yogurt_transactions, aes(y = Loyalty_Price, fill = brand)) +
  geom_boxplot() +  # Violin plot for price density
  labs(title = "Price Density of Yogurt (Non-Multi-Packs) by Brand",
       x = "Brand",
       y = "Loyalty Price") +
  facet_wrap(~brand)