options(dplyr.summarise.inform = FALSE)

crime_type_details <- crime_data %>%
  filter(!is.na(Longitude), !is.na(Latitude), !is.na(ANZSOC.Division)) %>%
  group_by(Area.Unit, Latitude, Longitude, ANZSOC.Division) %>%
  summarise(type_count = sum(Victimisations), .groups = "drop")

crime_data_aggregated <- crime_data %>%
  group_by(Area.Unit, Latitude, Longitude) %>%
  summarise(Victimisations = sum(Victimisations),.groups = "drop") %>%
  filter(!is.na(Longitude), !is.na(Latitude))

crime_data_aggregated <- crime_data_aggregated %>%
  group_by(Area.Unit, Latitude, Longitude) %>%
  do({types <- filter(crime_type_details, 
                   Area.Unit == .$Area.Unit,
                   Latitude == .$Latitude,
                   Longitude == .$Longitude)
    type_text <- if(nrow(types) > 0) {
      paste("<strong>Crime Types:</strong><br>",paste("-", types$ANZSOC.Division, ": ", types$type_count, collapse = "<br>"),sep = "")} else {
      "<strong>Crime Types:</strong><br>No detailed data available"}
  
    data.frame(Victimisations = .$Victimisations,type_details = type_text)}) %>%ungroup()

leaflet(crime_data_aggregated) %>%
  addTiles() %>%
  addHeatmap(
    lng = ~Longitude,lat = ~Latitude,
    intensity = ~Victimisations,
    radius = 12) %>%
  addCircleMarkers(
    lng = ~Longitude,
    lat = ~Latitude,
    radius = 5,
    fillColor = "blue",
    fillOpacity = 0.1,
    stroke = FALSE,
    label = ~paste("Number of crimes: ", Victimisations),
    labelOptions = labelOptions(
      style = list(
        "font-size" = "12px","font-weight" = "bold",
        "color" = "red","background-color" = "rgba(255,255,255,0.8)",
        "padding" = "3px 6px","border-radius" = "4px"),
      direction = "auto"),
    popup = ~paste(
      "<strong>Location: </strong>", Area.Unit, "<br><br>",
      "<strong>Total crimes: </strong>", Victimisations, "<br><br>",
      type_details),
    popupOptions = popupOptions(
      maxWidth = 350,
      style = list("font-size" = "12px","font-weight" = "bold",
        "color" = "red","background-color" = "rgba(255,255,255,0.9)",
        "padding" = "5px 10px","border-radius" = "4px")))
ggplot(hourly_crimes, aes(x = factor(Occurrence.Hour.Of.Day), 
                          y = crime_count, fill = crime_count)) +
  geom_bar(stat = "identity", show.legend = FALSE) +
  coord_polar(start = -0.15) +  
  scale_fill_gradient(low = "white", high = "red") +
  labs(
    title = "Crime Heatmap by Hour of Day in Auckland",
    x = "Hour of Day",
    y = "Crime Count") +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 12, angle = 0, hjust = 0.5, face = "bold"),  
    axis.text.y = element_blank(),
    axis.ticks = element_blank(),
    plot.title = element_text(size = 14, hjust = 0.5))