##Tried to install packages when they failed to load while coding

library(dplyr)  # Load the dplyr package
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggplot2)
library(RColorBrewer)

library(ggplot2)
library(dplyr)
library(completejourney)
## Welcome to the completejourney package! Learn more about these data
## sets at http://bit.ly/completejourney.
library(scales)
library(reshape2)
library(ggcorrplot)
library(gganimate)
library(gifski)

# Loading the datasets from the completejourney package
data("transactions_sample")
data("demographics")
data("products")
data("campaigns")
data("coupon_redemptions")


##Identifying Customer Segmentation by Age and Coupon Redemption Impact
# Join the datasets and calculate average sales by age group and coupon usage
coupon_analysis <- transactions_sample %>%
  inner_join(demographics, by = "household_id") %>%
  left_join(coupon_redemptions, by = "household_id", relationship = "many-to-many") %>%
  mutate(coupon_used = !is.na(coupon_upc)) %>%
  group_by(age, coupon_used) %>%
  summarise(total_sales = sum(sales_value, na.rm = TRUE),
            household_count = n()) %>%
  mutate(avg_sales = total_sales / household_count)
## `summarise()` has grouped output by 'age'. You can override using the `.groups`
## argument.
# Basic plot for Coupon Usage Impact on Sales by Age Group
ggplot(coupon_analysis, aes(x = age, y = avg_sales, fill = coupon_used)) +
  geom_bar(stat = "identity", position = "dodge") +
  scale_fill_manual(values = c("#FF9999", "#66B2FF")) +
  labs(title = "Coupon Usage Impact by Age", x = "Age Group", y = "Avg Sales") +
  theme_minimal() +
  scale_y_continuous(labels = scales::dollar_format()) +
  theme(axis.text.x = element_text(angle = 0), plot.title = element_text(hjust = 0.5))

# 2nd Plot

# Summarizing the sales data by product category and filter top 10 categories
category_sales <- transactions_sample %>%
  inner_join(products, by = "product_id") %>%
  group_by(department) %>%
  summarise(total_sales = sum(sales_value, na.rm = TRUE)) %>%
  top_n(10, total_sales)  # Select top 10 categories by sales

# Creating a clearer pie chart with larger labels and better sorting
ggplot(category_sales, aes(x = "", y = total_sales, fill = reorder(department, total_sales))) +
  geom_bar(stat = "identity", width = 1, color = "white") +
  coord_polar(theta = "y") +
  labs(title = "Top 10 Sales Distribution by Product Category") +
  theme_void() +  # Removes unnecessary elements for clarity
  scale_fill_brewer(palette = "Set3") +  # Use a color palette for better contrast
  theme(legend.position = "right", legend.title = element_blank())  # Position and simplify the legend

####PLOT 3

# Aggregating total spending by income and marital status
bar_chart_data <- transactions_sample %>%
  inner_join(demographics, by = "household_id") %>%
  group_by(income, marital_status) %>%
  summarise(total_spent = sum(sales_value, na.rm = TRUE), .groups = "drop")  # Aggregating total spending



# This is used to define colors || Using retro palette
retro_metro_palette <- c("#ea5545", "#f46a9b", "#ef9b20", "#edbf33", "#ede15b", 
                         "#bdcf32", "#87bc45", "#27aef7", "#b33dc6")

# Create the stacked bar chart with the new color palette
ggplot(bar_chart_data, aes(x = income, y = total_spent, fill = marital_status)) +
  geom_bar(stat = "identity", position = "stack") +
  labs(title = "Total Spending by Income and Marital Status",
       x = "Household Income", y = "Total Spending (USD)") +
  theme_minimal() +
  scale_fill_manual(values = retro_metro_palette[1:length(unique(bar_chart_data$marital_status))]) +  # Apply the Retro Metro palette
  theme(plot.title = element_text(face = "bold", size = 14, hjust = 0.5),
        axis.text = element_text(size = 12),
        axis.text.x = element_text(angle = 45, hjust = 1),  # Rotate the x-axis labels
        plot.margin = margin(10, 10, 10, 10))  # Adjust the margin for better spacing