library(readxl)
library(tidyverse)
library(dplyr)
library(sysfonts)
library(ggplot2)
library(ggimage)
library(ggtext)
library(maps)
library(geosphere)
library(BBmisc)
library(randomNames)
library(networkD3)

font_paths("/Users/theotimebourgeois/Library/Fonts/AvertaPE-Black.otf")
font_add(family = "AvertaPE-Black.otf",
         regular = "AvertaPE-Black.otf")
font_paths("/Users/theotimebourgeois/Library/Fonts/AvertaPE-Regular.otf")
font_add(family = "AvertaPE-Regular.otf",
         regular = "AvertaPE-Regular.otf")

font <- "AvertaPE-Regular"

purple <- c("#2C2C54")
pink <- c("#A40E4C")
blue <- c("#2E86AB")
yellow <- c("#FF9C00")
lila <- c("#E3DFFF")
brown <- c("#C3979F")
grey <- c("#F2F2F2")
white <- c("#FFFFFF")

colfunc <- colorRampPalette(c(pink, blue, purple, yellow))
colfunc2 <- colorRampPalette(c(pink,yellow,lila,purple))

FormDB <- read_excel("/Users/theotimebourgeois/Downloads/Mobile payment methods, use according to your network? (réponses).xlsx", sheet = "Réponses au formulaire 1")

SourceText <- "Source: ‟Mobile payment methods, use according to your network?”\nForm performed by Théotime Bourgeois"
People <- nrow(FormDB)

FormDB[,6:29][ FormDB[,6:29] == "5 (Strongly agree)" ] <- "5"
FormDB[,6:29][ FormDB[,6:29] == "1 (Strongly disagree)" ] <- "1"
FormDB[,6:29] <- FormDB[,6:29] %>% mutate_if(is.character,as.numeric)

FormDB$LastName <-
  FormDB$`Your last name (Your family name will be anonymized: it is only useful to identify your family group):` %>% toupper

FormDB <- FormDB %>% select(-`Your last name (Your family name will be anonymized: it is only useful to identify your family group):`)

FormDB$`Name of your company:` <- FormDB$`Name of your company:` %>% toupper

FormDB$`Approximate start date of your studies:` <- FormDB$`Approximate start date of your studies:` %>% format("%Y")
FormDB$`Approximate end date of your studies:` <- FormDB$`Approximate end date of your studies:` %>% format("%Y")

FormDB <- FormDB %>% 
  mutate(ID=1,
         ID=cumsum(ID),
         ID=paste("Person",ID))

FormDB$Link[FormDB$ID=="Person 1"] <- "Person 2"

FormDB$Name <- randomNames(nrow(FormDB), which.names="first")

UTAUT_List <- FormDB[6:29] %>% colnames() %>% as.data.frame()

UTAUT_List <- strsplit(UTAUT_List$.,"\\[") %>% as.data.frame() %>% t()
rownames(UTAUT_List) <- 1:nrow(UTAUT_List)
PurposeOT <- FormDB$`I make online transactions to : (check all that apply to you)` %>%
  strsplit(", ") %>%
  unlist() %>%
  table() %>%
  as.data.frame() %>% 
  `colnames<-`(c("Purpose","Freq")) %>%
  arrange(desc(Freq)) %>%
  mutate(
    Purpose = sapply(Purpose %>% str_split("\\("), `[`, 1),
    Purpose = factor(Purpose, levels=rev(Purpose)))

PurposeOT <- PurposeOT %>% mutate(
    ID = 1:nrow(PurposeOT),
    label = paste0(Purpose,": ",Freq))

ggplot(PurposeOT, aes(x = ID, y = Freq, fill = Purpose)) +
  geom_segment(aes(x = 1:nrow(PurposeOT), xend = 1:nrow(PurposeOT), y = People, yend = 0),col = grey)+
  geom_bar(width = 0.9, stat="identity")+
  geom_segment(aes(x = 0, xend = nrow(PurposeOT)+1, y = 0, yend = 0))+
  coord_polar(theta = "y")+
  scale_fill_manual(values=colfunc(nrow(PurposeOT)))+
  xlim(c(-5,1+nrow(PurposeOT))) +
  ylim(c(0,People)) +
  geom_text(hjust = 1.05, size = 3, family = font,
          aes(x = ID, y = 0, label = label)) +
  geom_richtext(size = 4.5, col = purple,family = "AvertaPE-Black", fill = NA, label.color = NA,
   aes(x = -5, y = 0,
       label=paste0("On a sample of <br><span style='font-size:25pt; color:",
                    pink,"'> **",People," people**</span>")))+
  labs(title="Main reasons for using these applications",
    y=NULL,x=NULL, fill="Skills",
    caption=SourceText)+
  theme_minimal() +
  theme(legend.position = "none",
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        plot.title = element_text(size = 15, family = "AvertaPE-Black", color = purple),
        plot.caption = element_text(size = 8, color = blue),
        axis.line = element_blank(),
        axis.text.y = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks = element_blank())

HowOT <- FormDB$`What is the reason for this?` %>%
  strsplit(", ") %>%
  unlist() %>%
  table() %>%
  as.data.frame() %>% 
  `colnames<-`(c("How","Freq")) %>%
  arrange(desc(Freq)) %>%
  mutate(
    How = sapply(How %>% str_split("\\("), `[`, 1),
    How = factor(How, levels=rev(How)))

HowOT$How <- HowOT$How %>% droplevels() %>% as.character()

HowOT$How[HowOT$How %>% str_detect("institution")] <- "Existing user institution"
HowOT$How[HowOT$How %>% str_detect("knew")] <- "Option already known"
HowOT$How[HowOT$How %>% str_detect("payment")] <- "Time of payment"
HowOT$How[HowOT$How %>% str_detect("friend")] <- "Conversion by a friend"

HowOT <- HowOT %>% mutate(
    ID = 1:nrow(HowOT),
    label = paste0(How,": ",Freq))

ggplot(HowOT, aes(x = ID, y = Freq, fill = How)) +
  geom_segment(aes(x = 1:nrow(HowOT), xend = 1:nrow(HowOT), y = max(Freq)+1, yend = 0),col = grey)+
  geom_bar(width = 0.9, stat="identity")+
  geom_segment(aes(x = 0, xend = nrow(HowOT)+1, y = 0, yend = 0))+
  coord_polar(theta = "y")+
  scale_fill_manual(values=colfunc(nrow(HowOT)))+
  xlim(c(-5,1+nrow(HowOT))) +
  ylim(c(0,max(HowOT$Freq)+1)) +
  geom_text(hjust = 1.05, size = 3, family = font,
          aes(x = ID, y = 0, label = label)) +
  geom_richtext(size = 4.5, col = purple,family = "AvertaPE-Black", fill = NA, label.color = NA,
   aes(x = -5, y = 0,
       label =paste0("On a sample of <br><span style='font-size:25pt; color:",
                    pink,"'> **",People," people**</span>")))+
  labs(title="Conversion mostly done thanks to users",
       subtitle = "Institutions as majority converters",
    y=NULL,x=NULL, fill="Skills",
    caption=SourceText)+
  theme_minimal() +
  theme(legend.position = "none",
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        plot.title = element_text(size = 15, family = "AvertaPE-Black", color = purple),
        plot.caption = element_text(size = 8, color = blue),
        axis.line = element_blank(),
        axis.text.y = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks = element_blank())

Market <- FormDB$`What mobile applications/payment methods do you use to transfer money to a friend?` %>%
  strsplit(", ") %>%
  unlist() %>%
  table() %>%
  as.data.frame() %>% 
  `colnames<-`(c("Market","Freq"))

size <- 10

Market$Image[Market$Market %>% str_detect("Lydia")] <- "Lydia.png"
Market$Image[Market$Market %>% str_detect("RIB")] <- "RIB.png"
Market$Image[Market$Market %>% str_detect("Check")] <- "Check.png"
Market$Image[Market$Market %>% str_detect("Lyf Pay")] <- "Lyfpay.png"
Market$Image[Market$Market %>% str_detect("Pumpkin")] <- "Pumpkin.png"
Market$Image[Market$Market %>% str_detect("Pumpkin")] <- "PayLib.png"
Market$Image[Market$Market %>% str_detect("PayPal")] <- "PayPal.png"


Market <- Market %>% arrange(desc(Freq)) %>% mutate(Market = factor(Market, levels=rev(Market)))

ggplot(Market, aes(y = Market))+
  geom_segment(aes(x = 0, xend = Freq-0.3, yend = Market), size = size, col = purple)+
  geom_point(aes(x = Freq-0.3), size = size*0.95, col = yellow)+
  geom_image(aes(x = Freq, image=Image,),
             asp = 1.8,
             size=.07)+
  geom_text(aes(x=Freq-0.3, label = Freq), col = white, family = "AvertaPE-Black")+
  labs(title="New payment methods: a complement to traditional methods",
       subtitle="Use of payment methods in respondents' daily lives",
       y=NULL, x="Count",
       col = "Movies")+
  scale_y_discrete(labels = function(y) str_wrap(y, width = 12))+
  theme(text=element_text(size=12, family="AvertaPE-Regular"),
        panel.background = element_blank(),
        legend.position = "right",
        legend.background = element_blank(),
        axis.line = element_line(colour = purple),
        plot.title = element_text(size = 15, family = "AvertaPE-Black", color = purple),
        plot.caption = element_text(size = 10, color = blue))

ZIPCodeDB <- read_csv("/Users/theotimebourgeois/Documents/Cours/BSB/MASTER2/Thesis/R Thesis/cities.csv")

ZIPDB <- FormDB %>%
  select(`Postal code of your company:`,`Postal code of your recently attended school:`,`Your postal code:`) %>% 
  as.data.frame() %>% 
  `colnames<-`(c("Pro","School","Perso"))

ZIPCode <- ZIPCodeDB %>%
  select(zip_code, gps_lat, gps_lng,name) %>%
  mutate(ID=1, ID=ave(ID, zip_code, FUN=cumsum)) %>%
  filter(ID==1) %>%
  select(-ID)

ZIPCode <- rbind(ZIPCode,
c("LU-2182",49.58317971148099,6.122436170578234, "Luxembourg")) %>% unique()

ZIPPoints <- rbind(ZIPDB[1] %>% `colnames<-`(c("Zip")),
      ZIPDB[2] %>% `colnames<-`(c("Zip")),
      ZIPDB[3] %>% `colnames<-`(c("Zip"))) %>%
  table() %>% 
  as.data.frame() %>%
  `colnames<-`(c("zip_code","Freq")) %>% merge(y = ZIPCode, by = "zip_code")

ZIPToAdd <- ZIPPoints[!ZIPPoints$zip_code %in% ZIPCode$zip_code,]

ZIPToAdd

ZIPCode <- ZIPCode %>% select(zip_code, gps_lat, gps_lng)

PersoPro <- ZIPDB %>%
  select("Pro","Perso") %>%
  `colnames<-`(c("zip_code","Perso")) %>%
  merge(y = ZIPCode, by = "zip_code") %>%
  `colnames<-`(c("Pro","zip_code","Pro_lat","Pro_lng")) %>% 
  merge(y = ZIPCode, by = "zip_code") %>% 
  `colnames<-`(c("Perso","Pro","Pro_lat","Pro_lng","Perso_lat","Perso_lng")) %>% 
  table() %>%
  as.data.frame() %>% 
  filter(Freq>0)

SchoolPerso <- ZIPDB %>% select("Perso","School") %>% `colnames<-`(c("zip_code","School")) %>%
  merge(y = ZIPCode, by = "zip_code") %>%
  `colnames<-`(c("Perso","zip_code","Perso_lat","Perso_lng")) %>% 
  merge(y = ZIPCode, by = "zip_code") %>% 
  `colnames<-`(c("School","Perso","Perso_lat","Perso_lng","School_lat","School_lng")) %>%
  table() %>% 
  as.data.frame() %>% 
  filter(Freq>0)


SchoolPerso$School_lng <- SchoolPerso$School_lng %>% droplevels() %>% as.character() %>% as.numeric()
SchoolPerso$School_lat <- SchoolPerso$School_lat %>% droplevels() %>% as.character() %>% as.numeric()
SchoolPerso$Perso_lat <- SchoolPerso$Perso_lat %>% droplevels() %>% as.character() %>% as.numeric()
SchoolPerso$Perso_lng <- SchoolPerso$Perso_lng %>% droplevels() %>% as.character() %>% as.numeric()

PersoPro$Pro_lng <- PersoPro$Pro_lng %>% droplevels() %>% as.character() %>% as.numeric()
PersoPro$Pro_lat <- PersoPro$Pro_lat %>% droplevels() %>% as.character() %>% as.numeric()
PersoPro$Perso_lat <- PersoPro$Perso_lat %>% droplevels() %>% as.character() %>% as.numeric()
PersoPro$Perso_lng <- PersoPro$Perso_lng %>% droplevels() %>% as.character() %>% as.numeric()

PersoPro$Width <- PersoPro$Freq %>% normalize(method = "range",range = c(1, 5))
SchoolPerso$Width <- SchoolPerso$Freq %>% normalize(method = "range",range = c(1, 5))
ZIPPoints$Width <- ZIPPoints$Freq %>% normalize(method = "range",range = c(0.5, 1.5))
map('world',
    col="#f2f2f2", fill=TRUE, bg="white", lwd=0.05,
    mar=rep(0,4),border=0, ylim=c(40,55), xlim=c(-15,21)
)
for (i in 1:nrow(SchoolPerso)){
  inter <- gcIntermediate(c(SchoolPerso$School_lng[i],SchoolPerso$School_lat[i]),
                        c(SchoolPerso$Perso_lng[i],SchoolPerso$Perso_lat[i]),
                        n=50, addStartEnd=TRUE, breakAtDateLine=F)
  lines(inter, col=yellow, lwd=SchoolPerso$Width[i])
}
for (i in 1:nrow(PersoPro)){
  inter <- gcIntermediate(c(PersoPro$Pro_lng[i],PersoPro$Pro_lat[i]),
                        c(PersoPro$Perso_lng[i],PersoPro$Perso_lat[i]),
                        n=50, addStartEnd=TRUE, breakAtDateLine=F)
  lines(inter, col=pink, lwd=PersoPro$Width[i])
}
points(x=ZIPPoints$gps_lng, y=ZIPPoints$gps_lat, col=purple, cex=ZIPPoints$Width, pch=20)

rm(ZIPCode,ZIPDB,ZIPPoints,ZIPToAdd,ZIPCodeDB,SchoolPerso,PersoPro)
BirthYear <- FormDB$`Your year of birth:` %>% table() %>% as.data.frame()


ggplot(BirthYear, aes(x = ., y = Freq))+
  geom_bar(stat = "summary", fun = "mean", fill=pink)+
  geom_text(aes(label = Freq),
            size=3,
            hjust=0.5,
            vjust=-1,
            check_overlap = T)+
  labs(title="Distribution of respondents' years of birth",
       subtitle=paste0("1998 corresponds to the year of birth of the majority of the students of my promotion"),
       y="Frequency", x="Year")+
  theme(text=element_text(size=12, family="AvertaPE-Regular"),
        panel.background = element_blank(),
        legend.position = "right",
        legend.background = element_blank(),
        axis.line = element_line(colour = purple),
        plot.title = element_text(size = 15, family = "AvertaPE-Black", color = purple),
        plot.caption = element_text(size = 8, color = blue))

MatrixName <- matrix(data=NA, nrow = nrow(FormDB), ncol = nrow(FormDB)) %>%
  as.data.frame() %>% 
  `colnames<-`(FormDB$ID) %>% 
  `rownames<-`(FormDB$ID)

for (col in 1:ncol(MatrixName)){
  for (row in 1:nrow(MatrixName)){
    MatrixName[row,col] <-
      FormDB$LastName[FormDB$ID==rownames(MatrixName[row,])]==FormDB$LastName[FormDB$ID==colnames(MatrixName)[col]]
  }
}

MatrixLastName <- MatrixName %>% mutate(from=rownames(MatrixName))
MatrixLastName <- MatrixLastName[,c(ncol(MatrixLastName),1:(ncol(MatrixLastName)-1))] %>%
  as.data.frame() %>%
  gather(key="to", value="value", -1) %>%
  mutate(to = gsub("\\.", " ",to)) %>%
  na.omit() %>% 
  filter(value==TRUE)

for (col in 1:ncol(MatrixName)){
  for (row in 1:nrow(MatrixName)){
    MatrixName[row,col] <-
      FormDB$`Name of your company:`[FormDB$ID==rownames(MatrixName[row,])]==FormDB$`Name of your company:`[FormDB$ID==colnames(MatrixName)[col]]
  }
}

MatrixPro <- MatrixName %>% mutate(from=rownames(MatrixName))
MatrixPro <- MatrixPro[,c(ncol(MatrixPro),1:(ncol(MatrixPro)-1))] %>%
  as.data.frame() %>%
  gather(key="to", value="value", -1) %>%
  mutate(to = gsub("\\.", " ",to)) %>%
  na.omit() %>% 
  filter(value==TRUE)

for (col in 1:ncol(MatrixName)){
  for (row in 1:nrow(MatrixName)){
    MatrixName[row,col] <-
      FormDB$`Name of your recently attended school:`[FormDB$ID==rownames(MatrixName[row,])]==FormDB$`Name of your recently attended school:`[FormDB$ID==colnames(MatrixName)[col]]
  }
}

MatrixSchool <- MatrixName %>% mutate(from=rownames(MatrixName))
MatrixSchool <- MatrixSchool[,c(ncol(MatrixSchool),1:(ncol(MatrixSchool)-1))] %>%
  as.data.frame() %>%
  gather(key="to", value="value", -1) %>%
  mutate(to = gsub("\\.", " ",to)) %>%
  na.omit() %>% 
  filter(value==TRUE, from!=to)

MatrixLastName$value <- "Family"
MatrixSchool$value <- "School"
MatrixPro$value <- "Pro"

MatrixPerso <- FormDB %>%
  select(ID, Link) %>%
  filter(!is.na(Link)) %>%
  `colnames<-`(c("from","to")) %>% 
  mutate(value = "Perso")

Top_Network <- rbind(MatrixLastName,MatrixSchool,MatrixPro,MatrixPerso)

p <- simpleNetwork(Top_Network %>% select(from,to), height="100px", width="100px",        
        Source = 1,             # column number of source
        Target = 2,             # column number of target
        linkDistance = 10,      # distance between node. Increase this value to have more space between nodes
        charge = -900,          # numeric value indicating either the strength of the node repulsion (negative value) or attraction (positive value)
        fontSize = 14,          # size of the node names
        fontFamily = font,   # font og node names
        linkColour = purple,    # colour of edges, MUST be a common colour for the whole graph
        nodeColour = pink,     # colour of nodes, MUST be a common colour for the whole graph
        opacity = 1,        # opacity of nodes. 0=transparent. 1=no transparency
        zoom = T              # Can you zoom on the figure?
        )

p
UTAUTAnalysis <- FormDB[6:29] %>% t() %>% as.data.frame()
rownames(UTAUTAnalysis) <- 1:nrow(UTAUTAnalysis)

UTAUT_List <- UTAUT_List %>% as.data.frame() %>% mutate(`1`=1, `2`=2, `3`=3, `4`=4, `5`=5)

for (i in 1:nrow(UTAUT_List)){
  UTAUT_List$Mean[i] <- UTAUTAnalysis[i,] %>% unlist() %>% mean()
  for (j in 1:5){
    UTAUT_List[i,j+2] <- (UTAUTAnalysis[i,] %>%
                            unlist() %>%
                            table() %>%
                            as.data.frame() %>%
                            `colnames<-`(c("Value","Freq")) %>%
                            filter(Value==j))[2] %>% as.numeric()
  }
}

colnames(UTAUT_List)[1:2] <- c("Category","Question")

UTAUT_Group <- UTAUT_List %>% 
  group_by(Category) %>% 
  summarise(Mean = mean(Mean),
            `1`=sum(`1`,na.rm=T),
            `2`=sum(`2`,na.rm=T),
            `3`=sum(`3`,na.rm=T),
            `4`=sum(`4`,na.rm=T),
            `5`=sum(`5`,na.rm=T))

UTAUT_Radar <- UTAUT_Group %>% select(1,2) %>% t()
UTAUT_Radar[1,] <- c("Behavior","Effort","Facilitating","Enjoyment","Performance","Social","Trust")
colnames(UTAUT_Radar) <- UTAUT_Radar[1,] %>% str_replace(" / ","/")  %>% str_replace(" ","\n")
UTAUT_Radar <- UTAUT_Radar[2,] %>% t() %>% as.data.frame()
UTAUT_Radar[1,] <- ((UTAUT_Radar[1,] %>% as.numeric())/5) %>% round(2)
UTAUT_Radar[2,] <- (c(3.224,2.535,3.348,3.264,3.1,3.325,3.163)/5) %>% round(2)
UTAUT_Radar[,1:7] <- sapply(UTAUT_Radar[,1:7], as.numeric)
UTAUT_Radar <- cbind(c("Thesis Results","Triasesiarta Nur Results"),UTAUT_Radar[1:7])
colnames(UTAUT_Radar)[1] <- "Name"



library(ggradar)

Skill_radar_graph <- UTAUT_Radar %>%
  ggradar(font.radar = font,
          grid.label.size = 4,  # Affects the grid annotations (0%, 50%, etc.)
          axis.label.size = 4,
          group.point.size = 5,   # Simply the size of the point 
          group.colours = c(yellow, pink))+
  labs(title = paste("Comparison of the results obtained by the UTAUT Model"),
       subtitle = "between my study and the literature review",
       caption = SourceText)+
  theme(text=element_text(size=12, family="AvertaPE-Regular"),
        legend.position = c(-0.1,-0.025),
        legend.justification = "left",
        legend.text = element_text(size = 10, family = font),
        legend.key = element_rect(fill = NA, color = NA),
        panel.background = element_blank(),
        legend.background = element_blank(),
        plot.title = element_text(size = 15, family = "AvertaPE-Black", color = purple),
        plot.caption = element_text(size = 8, color = blue))

Skill_radar_graph

UTAUT_Group2 <- rbind(UTAUT_Group %>% select(1,3) %>% `colnames<-`(c("Category","Freq")) %>% mutate(Rate = 1),
                      UTAUT_Group %>% select(1,4) %>% `colnames<-`(c("Category","Freq")) %>% mutate(Rate = 2),
                      UTAUT_Group %>% select(1,5) %>% `colnames<-`(c("Category","Freq")) %>% mutate(Rate = 3),
                      UTAUT_Group %>% select(1,6) %>% `colnames<-`(c("Category","Freq")) %>% mutate(Rate = 4),
                      UTAUT_Group %>% select(1,7) %>% `colnames<-`(c("Category","Freq")) %>% mutate(Rate = 5)) %>% 
  mutate(Rate = as.character(Rate))

library(ggridges)

ggplot(UTAUT_Group2, aes(x = Category, y = Freq, fill = Rate, group = Rate)) +
  geom_col(position = "dodge")+
  coord_flip()+
  scale_fill_manual(values=colfunc2(5))+
  labs(title="Model UTAUT analysis on a scale of 1 to 5",
       subtitle=paste0("1998 corresponds to the year of birth of the majority of the students of my promotion"),
       y="Rate Frequency", x=element_blank())+
  theme(text=element_text(size=12, family="AvertaPE-Regular"),
        panel.background = element_blank(),
        legend.position = "right",
        legend.background = element_blank(),
        axis.line = element_line(colour = purple),
        plot.title = element_text(size = 15, family = "AvertaPE-Black", color = purple),
        plot.caption = element_text(size = 8, color = blue))