local civilmenu = {
	opened = false,
	title = "Menu Personnel",
	currentmenu = "main",
	lastmenu = nil,
	currentpos = nil,
	selectedbutton = 0,
	marker = { r = 0, g = 155, b = 255, a = 200, type = 1 },
	menu = {
		x = 0.1,
		y = 0.32,
		width = 0.2,
		height = 0.04,
		buttons = 10,
		from = 1,
		to = 10,
		scale = 0.4,
		font = 0,
		["main"] = { 
			title = "CATEGORIES", 
			name = "main",
			buttons = { 
				{name = "Animations", description = ""},
				{name = "Telephone", description = ""},
				{name = "Carte d'identité", description = ""},
				{name = "Donner de l'argent", description = ""},
				{name = "Sauvegarder ma position", description = ""},
			}
		},
		["mainanimation"] = { 
			title = "Animations",
			name = "mainanimation",
			buttons = { 
				{name = "Applaudire", description = ''},
				{name = "Regarder sa carte", description = ''},
				{name = "Faire du Yoga", description = ''},
				{name = "Faire des pompes", description = ''},
				{name = "Jouer de la musique", description = ''},
				{name = "Filmer", description = ''},
			}
		},
		["maingivemoney"] = { 
			title = "Argent",
			name = "maingivemoney",
			buttons = { 
				{name = "Donner de l'argent", description = ''},
				{name = "Donner de l'argent sale", description = ''},
			}
		},
		["maintelephone"] = { 
			title = "Telephone", 
			name = "maintelephone",
			buttons = { 
				{name = "Répertoire", description = ''},
				{name = "Police", description = ''},
				{name = "Médecin", description = ''},
				-- {name = "Pompier", description = ''},
				{name = "Taxi", description = ''},
				{name = "Dépanneur", description = ''},
				{name = "Journaliste", description = ''},
			}
		},
		["mainrepertoire"] = { 
			title = "Repertoire", 
			name = "mainrepertoire",
			buttons = { 
				
			}
		},
		["mainrepertoire2"] = { 
			title = "Repertoire", 
			name = "mainrepertoire2",
			buttons = { 
				{name = "Envoyer un message", description = ''},
				{name = "Appeler (SOON)", description = ''},
				{name = "Supprimer le contact (SOON)", description = ''},
			}
		},			
	}
}

RegisterNetEvent('MyRepertoire')
AddEventHandler('MyRepertoire', function(tablerep)
	
    local a = tablerep
	
	civilmenu.menu["mainrepertoire"].buttons = {}
	
	table.insert(civilmenu.menu["mainrepertoire"].buttons, {name = "Ajouter un numéro", description = ''})
	table.insert(civilmenu.menu["mainrepertoire"].buttons, {name = "911", description = ''})
	table.insert(civilmenu.menu["mainrepertoire"].buttons, {name = "CNN", description = ''})

	local i = 1
	while a[i] do
		
	namerepclient = a[i]['player_name']
	numrepclient = a[i]['phone_number']

    table.insert(civilmenu.menu["mainrepertoire"].buttons, {name = namerepclient, description = "", numero = numrepclient})

	i = i + 1
	end

end)


RegisterNetEvent('MyRepertoire2')
AddEventHandler('MyRepertoire2', function()

	civilmenu.currentmenu = "mainrepertoire"
	civilmenu.opened = true
	civilmenu.selectedbutton = 0
	
end)


local function LocalPed()
return GetPlayerPed(-1)
end

	inmenucivil = 0
	inmenuinv = 0
	inmenujob = 0

--Creator Weapon
function OpenCreatorcivilmenu()		
	civilmenu.currentmenu = "main"
	civilmenu.opened = true
	civilmenu.selectedbutton = 0
end
function CloseCreatorcivilmenu()
	Citizen.CreateThread(function()
		civilmenu.opened = false
		civilmenu.menu.from = 1
		civilmenu.menu.to = 10
		inmenucivil = 0
		inmenuinv = 0
		inmenujob = 0
	end)
	Citizen.CreateThread(function()
	end)
end

--Menu pomenu

function drawMenuButton(button,x,y,selected)
	local menu = civilmenu.menu
	SetTextFont(menu.font)
	SetTextProportional(0)
	SetTextScale(menu.scale, menu.scale)
	if selected then
		SetTextColour(0, 0, 0, 255)
	else
		SetTextColour(255, 255, 255, 255)
	end
	SetTextCentre(0)
	SetTextEntry("STRING")
	AddTextComponentString(button.name)
	if selected then
		DrawRect(x,y,menu.width,menu.height,255,255,255,255)
	else
		DrawRect(x,y,menu.width,menu.height,0,0,0,150)
	end
	DrawText(x - menu.width/2 + 0.005, y - menu.height/2 + 0.0028)	
end

function drawMenuInfo(text)
	local menu = civilmenu.menu
	SetTextFont(menu.font)
	SetTextProportional(0)
	SetTextScale(0.45, 0.45)
	SetTextColour(255, 255, 255, 255)
	SetTextCentre(0)
	SetTextEntry("STRING")
	AddTextComponentString(text)
	DrawRect(0.675, 0.95,0.65,0.050,0,0,0,150)
	DrawText(0.365, 0.934)	
end

function drawMenuRight(txt,x,y,selected)
	local menu = civilmenu.menu
	SetTextFont(menu.font)
	SetTextProportional(0)
	SetTextScale(menu.scale, menu.scale)
	SetTextRightJustify(1)
	if selected then
		SetTextColour(0, 0, 0, 255)
	else
		SetTextColour(255, 255, 255, 255)
	end
	SetTextCentre(0)
	SetTextEntry("STRING")
	AddTextComponentString(txt)
	DrawText(x + menu.width/2 - 0.03, y - menu.height/2 + 0.0028)	
end

function drawMenuTitleCivmen(txt,x,y)
local menu = civilmenu.menu
	SetTextFont(2)
	SetTextProportional(0)
	SetTextScale(0.5, 0.5)
	SetTextColour(255, 255, 255, 255)
	SetTextEntry("STRING")
	AddTextComponentString(txt)
	DrawRect(x,y,menu.width,menu.height,93,166,202,150)
	DrawText(x - menu.width/2 + 0.005, y - menu.height/2 + 0.0028)
end

function tablelength(T)
  local count = 0
  for _ in pairs(T) do count = count + 1 end
  return count
end
function NotifyCivilMenu(text)
SetNotificationTextEntry('STRING')
AddTextComponentString(text)
DrawNotification(false, false)
end

function ShowNotificationMenuCivil2(text)
	SetNotificationTextEntry("STRING")
	AddTextComponentString(text)
	DrawNotification(false, false)
end

local backlock = false
Citizen.CreateThread(function()
	while true do
		Citizen.Wait(0)
		if IsControlJustPressed(1,288) then
		  if IsPedInAnyVehicle(LocalPed(), true) == false then
		  if (inmenuinv == 0) and (inmenujob == 0) then
			if civilmenu.opened then
				CloseCreatorcivilmenu()
				inmenucivil = 0
				inmenuinv = 0
				inmenujob = 0
			else
				OpenCreatorcivilmenu()
				freezetargetCiv = totarget
				inmenucivil = 1
				inmenuinv = 0
				inmenujob = 0
			end
		  end
		  else
		    ShowNotificationMenuCivil2("~r~Vous ne pouvez pas ouvrir le menu dans un véhicule !")
	      end
		end
		if civilmenu.opened then
			local ped = LocalPed()
			local menu = civilmenu.menu[civilmenu.currentmenu]
			drawTxt(civilmenu.title,1,1,civilmenu.menu.x,civilmenu.menu.y,1.0, 255,255,255,255)
			drawMenuTitleCivmen(menu.title, civilmenu.menu.x,civilmenu.menu.y + 0.08)
			drawTxt(civilmenu.selectedbutton.."/"..tablelength(menu.buttons),0,0,civilmenu.menu.x + civilmenu.menu.width/2 - 0.0385,civilmenu.menu.y + 0.067,0.4, 255,255,255,255)
			local y = civilmenu.menu.y + 0.12
			buttoncount = tablelength(menu.buttons)
			local selected = false
			
			for i,button in pairs(menu.buttons) do
				if i >= civilmenu.menu.from and i <= civilmenu.menu.to then
					
					if i == civilmenu.selectedbutton then
						selected = true
					else
						selected = false
					end
					drawMenuButton(button,civilmenu.menu.x,y,selected)
					y = y + 0.04
					if selected and IsControlJustPressed(1,201) then
						ButtonSelectedCivilMenu(button)
					end
				end
			end	
		end
		if civilmenu.opened then
			if IsControlJustPressed(1,202) then
				BackCivilMenu()
			end
			if IsControlJustReleased(1,202) then
				backlock = false
			end
			if IsControlJustPressed(1,188) then
				if civilmenu.selectedbutton > 1 then
					civilmenu.selectedbutton = civilmenu.selectedbutton -1
					if buttoncount > 10 and civilmenu.selectedbutton < civilmenu.menu.from then
						civilmenu.menu.from = civilmenu.menu.from -1
						civilmenu.menu.to = civilmenu.menu.to - 1
					end
				end
			end
			if IsControlJustPressed(1,187)then
				if civilmenu.selectedbutton < buttoncount then
					civilmenu.selectedbutton = civilmenu.selectedbutton +1
					if buttoncount > 10 and civilmenu.selectedbutton > civilmenu.menu.to then
						civilmenu.menu.to = civilmenu.menu.to + 1
						civilmenu.menu.from = civilmenu.menu.from + 1
					end
				end	
			end
		end
	end
end)

inputrep = 0
inputrep911 = 0
inputrep2 = 0
inputmoney = 0
inputmoneysale = 0
havePhone = 0
inputmotifpolice = 0
motifx = 0
motify = 0
motifz = 0
				
function ButtonSelectedCivilMenu(button)
	local ped = GetPlayerPed(-1)
	local this = civilmenu.currentmenu
	local btn = button.name
	callx, cally, callz = table.unpack(GetEntityCoords(GetPlayerPed(-1) , true))
	if this == "main" then
		if btn == "Animations" then
			OpenMenuCivilmenu('mainanimation')
		elseif btn == "Telephone" then
			TriggerServerEvent('playerPhone')
		elseif btn == "Carte d'identité" then
			TriggerServerEvent('MyIdent')
		elseif btn == "Donner de l'argent" then
			OpenMenuCivilmenu('maingivemoney')
		elseif btn == "Sauvegarder ma position" then
			TriggerServerEvent('SavePosServer', {table.unpack(GetEntityCoords(ped)) })
			ShowNotificationMenuCivil2("~h~~b~Position sauvegardée.")
			CloseCreatorcivilmenu()
			inmenucivil = 0
			inmenuinv = 0
			inmenujob = 0	
		end
	elseif this == "mainanimation" then
		if btn == "Applaudire" then
		    Citizen.CreateThread(function()
                    TaskStartScenarioInPlace(GetPlayerPed(-1), "WORLD_HUMAN_CHEERING", 0, 1)
					PlayAmbientSpeech1(GetPlayerPed(-1), "GENERIC_CURSE_MED", "SPEECH_PARAMS_FORCE")
					Citizen.Wait(5000)
					ClearPedTasksImmediately(GetPlayerPed(-1))
			end)
			
		elseif btn == "Filmer" then
		    Citizen.CreateThread(function()
                    TaskStartScenarioInPlace(GetPlayerPed(-1), "WORLD_HUMAN_MOBILE_FILM_SHOCKING", 0, 1)
					PlayAmbientSpeech1(GetPlayerPed(-1), "GENERIC_CURSE_MED", "SPEECH_PARAMS_FORCE")
					Citizen.Wait(5000)
					ClearPedTasksImmediately(GetPlayerPed(-1))
			end)
		elseif btn == "Jouer de la musique" then
		    Citizen.CreateThread(function()
                    TaskStartScenarioInPlace(GetPlayerPed(-1), "WORLD_HUMAN_MUSICIAN", 0, 1)
					PlayAmbientSpeech1(GetPlayerPed(-1), "GENERIC_CURSE_MED", "SPEECH_PARAMS_FORCE")
					Citizen.Wait(20000)
					ClearPedTasksImmediately(GetPlayerPed(-1))
			end)			
		elseif btn == "Regarder sa carte" then
		    Citizen.CreateThread(function()
                    TaskStartScenarioInPlace(GetPlayerPed(-1), "WORLD_HUMAN_TOURIST_MAP", 0, 1)
					PlayAmbientSpeech1(GetPlayerPed(-1), "GENERIC_CURSE_MED", "SPEECH_PARAMS_FORCE")
					Citizen.Wait(10000)
					ClearPedTasksImmediately(GetPlayerPed(-1))
			end)			
		elseif btn == "Faire du Yoga" then
		    Citizen.CreateThread(function()
                    TaskStartScenarioInPlace(GetPlayerPed(-1), "WORLD_HUMAN_YOGA", 0, 1)
					PlayAmbientSpeech1(GetPlayerPed(-1), "GENERIC_CURSE_MED", "SPEECH_PARAMS_FORCE")
					Citizen.Wait(20000)
					ClearPedTasksImmediately(GetPlayerPed(-1))
			end)		
		elseif btn == "Faire des pompes" then
		    Citizen.CreateThread(function()
                    TaskStartScenarioInPlace(GetPlayerPed(-1), "WORLD_HUMAN_PUSH_UPS", 0, 1)
					PlayAmbientSpeech1(GetPlayerPed(-1), "GENERIC_CURSE_MED", "SPEECH_PARAMS_FORCE")
					Citizen.Wait(20000)
					ClearPedTasksImmediately(GetPlayerPed(-1))
			end)			
		
		end
	elseif this == "maintelephone" then
		if btn == "Police" then
		    DisplayOnscreenKeyboard(true, "FMMC_KEY_TIP8", "", "", "", "", "", 120)
			ShowNotificationCall911("~b~ENTREZ UNE RAISON DE L'APPEL...")
			inputmotifpolice = 1
			motifx = callx
			motify = cally
			motifz = callz
			CloseCreatorcivilmenu()
			
		elseif btn == "Taxi" then
		    TriggerServerEvent('CallTaxi', callx, cally, callz)
			
		elseif btn == "Dépanneur" then
		    TriggerServerEvent('CallDep', callx, cally, callz)
			
		elseif btn == "Pompier" then
		    TriggerServerEvent('CallPomp', callx, cally, callz)
			
		elseif btn == "Médecin" then
		    TriggerServerEvent('CallDoc', callx, cally, callz)
				
		elseif btn == "Journaliste" then
		    TriggerServerEvent('CallCnn', callx, cally, callz)
			
		elseif btn == "Répertoire" then
		   TriggerServerEvent('MyRep')
			
		end
	elseif this == "mainrepertoire" then
		if btn == "Ajouter un numéro" then
			DisplayOnscreenKeyboard(true, "FMMC_KEY_TIP8", "", "", "", "", "", 120)
			inputrep = 1
			CloseCreatorcivilmenu()
			inmenucivil = 0
			inmenuinv = 0
			inmenujob = 0
		elseif btn == "911" then
			DisplayOnscreenKeyboard(true, "FMMC_KEY_TIP8", "", "", "", "", "", 120)
			inputrep911 = 1
			CloseCreatorcivilmenu()
			inmenucivil = 0
			inmenuinv = 0
			inmenujob = 0
		elseif btn == "CNN" then
			DisplayOnscreenKeyboard(true, "FMMC_KEY_TIP8", "", "", "", "", "", 120)
			inputrepCNN = 1
			CloseCreatorcivilmenu()
			inmenucivil = 0
			inmenuinv = 0
			inmenujob = 0
		else
		    OpenMenuCivilmenu('mainrepertoire2')
		    nameSMStarget = button.name
			numeroSMStarget = button.numero
		end
	elseif this == "mainrepertoire2" then
		if btn == "Envoyer un message" then
			DisplayOnscreenKeyboard(true, "FMMC_KEY_TIP8", "", "", "", "", "", 120)
			inputrep2 = 1
			CloseCreatorcivilmenu()
			inmenucivil = 0
			inmenuinv = 0
			inmenujob = 0
		elseif btn == "Supprimer le contact" then
		
		end
	elseif this == "maingivemoney" then
		if btn == "Donner de l'argent" then
			DisplayOnscreenKeyboard(true, "FMMC_KEY_TIP8", "", "", "", "", "", 120)
			inputmoney = 1
			CloseCreatorcivilmenu()
			inmenucivil = 0
			inmenuinv = 0
			inmenujob = 0
		elseif btn == "Donner de l'argent sale" then
		    DisplayOnscreenKeyboard(true, "FMMC_KEY_TIP8", "", "", "", "", "", 120)
			inputmoneysale = 1
		    CloseCreatorcivilmenu()
			inmenucivil = 0
			inmenuinv = 0
			inmenujob = 0
		end
	end
end

--MOTIF CALL POLICE
Citizen.CreateThread(function()
	while true do
		Wait(0)
		if inputmotifpolice == 1 then
			if UpdateOnscreenKeyboard() == 3 then
				inputmotifpolice = 0
			elseif UpdateOnscreenKeyboard() == 1 then
				inputmotifclient = GetOnscreenKeyboardResult()
					if string.len(inputmotifclient) > 0 then
						ResultMotifAdd = inputmotifclient
						inputmotifpolice = 2
					else
						inputmotifpolice = 0
					end

			elseif UpdateOnscreenKeyboard() == 2 then
				inputmotifpolice = 0
			end
		end
		if inputmotifpolice == 2 then
		    TriggerServerEvent('Call911', motifx, motify, motifz, ResultMotifAdd)
			inputmotifpolice = 0
		end
	end
end)
--REPERTOIRE
Citizen.CreateThread(function()
	while true do
		Wait(0)
		if inputrep == 1 then
			if UpdateOnscreenKeyboard() == 3 then
				inputrep = 0
			elseif UpdateOnscreenKeyboard() == 1 then
				inputrepclient = GetOnscreenKeyboardResult()
					if string.len(inputrepclient) > 0 then
						ResultRepAdd = inputrepclient
						inputrep = 2
					else
						inputrep = 0
					end

			elseif UpdateOnscreenKeyboard() == 2 then
				inputrep = 0
			end
		end
		if inputrep == 2 then
		    TriggerServerEvent('AddNameInRep', ResultRepAdd)
			inputrep = 0
		end
		if inputmoney == 1 then
			if UpdateOnscreenKeyboard() == 3 then
				inputmoney = 0
			elseif UpdateOnscreenKeyboard() == 1 then
				inputemoneyclient = GetOnscreenKeyboardResult()
					if string.len(inputemoneyclient) > 0 then
						Resultmoney = inputemoneyclient
						inputmoney = 2
					else
						inputmoney = 0
					end

			elseif UpdateOnscreenKeyboard() == 2 then
				inputmoney = 0
			end
		end
		if inputmoney == 2 then
		    TriggerServerEvent('GivemoneyCiv', freezetargetCiv, Resultmoney)
			inputmoney = 0
		end
		if inputmoneysale == 1 then
			if UpdateOnscreenKeyboard() == 3 then
				inputmoneysale = 0
			elseif UpdateOnscreenKeyboard() == 1 then
				inputemoneyclient2 = GetOnscreenKeyboardResult()
					if string.len(inputemoneyclient2) > 0 then
						Resultmoneysale = inputemoneyclient2
						inputmoneysale = 2
					else
						inputmoneysale = 0
					end

			elseif UpdateOnscreenKeyboard() == 2 then
				inputmoneysale = 0
			end
		end
		if inputmoneysale == 2 then
		    TriggerServerEvent('GivemoneyCivSale', freezetargetCiv, Resultmoneysale)
			inputmoneysale = 0
		end
		if inputrep2 == 1 then
			if UpdateOnscreenKeyboard() == 3 then
				inputrep2 = 0
			elseif UpdateOnscreenKeyboard() == 1 then
				inputsmsclient = GetOnscreenKeyboardResult()
					if string.len(inputsmsclient) > 0 then
						ResultSmsAdd = inputsmsclient
						inputrep2 = 2
					else
						inputrep2 = 0
					end

			elseif UpdateOnscreenKeyboard() == 2 then
				inputrep2 = 0
			end
		end
		if inputrep2 == 2 then
		    TriggerServerEvent('ReceiveSMS', nameSMStarget, numeroSMStarget, ResultSmsAdd)
			inputrep2 = 0
		end
		if inputrep911 == 1 then
			if UpdateOnscreenKeyboard() == 3 then
				inputrep911 = 0
			elseif UpdateOnscreenKeyboard() == 1 then
				inputsmsclient911 = GetOnscreenKeyboardResult()
					if string.len(inputsmsclient911) > 0 then
						ResultSmsAdd911 = inputsmsclient911
						inputrep911 = 2
					else
						inputrep911 = 0
					end

			elseif UpdateOnscreenKeyboard() == 2 then
				inputrep911 = 0
			end
		end
		if inputrep911 == 2 then
		    TriggerServerEvent('SMS911', ResultSmsAdd911)
			inputrep911 = 0
		end
		if inputrepCNN == 1 then
			if UpdateOnscreenKeyboard() == 3 then
				inputrepCNN = 0
			elseif UpdateOnscreenKeyboard() == 1 then
				inputsmsclientCNN = GetOnscreenKeyboardResult()
					if string.len(inputsmsclientCNN) > 0 then
						ResultSmsAddCNN = inputsmsclientCNN
						inputrepCNN = 2
					else
						inputrepCNN = 0
					end

			elseif UpdateOnscreenKeyboard() == 2 then
				inputrepCNN = 0
			end
		end
		if inputrepCNN == 2 then
		    TriggerServerEvent('SMSCNN', ResultSmsAddCNN)
			inputrepCNN = 0
		end
	end
end)

RegisterNetEvent('CheckAddinRep')
AddEventHandler('CheckAddinRep', function(name)
    ShowNotificationMenuCivil2("~h~Vous avez ajouté ~b~"..name.."~w~ à votre répertoire.")
end)

RegisterNetEvent('CheckAddinRepFalse')
AddEventHandler('CheckAddinRepFalse', function(num)
    ShowNotificationMenuCivil2("~h~Aucun citoyen n'a le numéro ~r~"..num)
end)


RegisterNetEvent('CheckDejaNum')
AddEventHandler('CheckDejaNum', function()
    ShowNotificationMenuCivil2("~h~~r~Vous avez déjà ce numéro.")
end)

---MESSAGE RECU
affichesms = false
smsattente = 0
-- sonnerie = 0

RegisterNetEvent('OpenSMS')
AddEventHandler('OpenSMS', function(author, msg)
	
	
	if affichesms == false then
		affichesms = true
	
		authorForSMS = author
		messageForSMS = msg
		
	elseif affichesms == true then
	
	    smsattente = 1
	    authorForSMS2 = author
		messageForSMS2 = msg
		
	end
	
end)

Citizen.CreateThread(function()
	while true do
	Citizen.Wait(0)
        if smsattente == 1 then
		Citizen.Wait(20000)
		affichesms = true
		authorForSMS = authorForSMS2
		messageForSMS = messageForSMS2
		smsattente = 0
		end
	end
end)

Citizen.CreateThread(function()
	while true do
	Citizen.Wait(0)
        if affichesms == true then
		-- sonnerie = 1
		Citizen.Wait(20000)
		affichesms = false
		end
	end
end)

-- Citizen.CreateThread(function()
	-- while true do
	-- Citizen.Wait(0)
        -- if sonnerie == 1 then
		-- PlaySoundFrontend(GetPlayerPed(-1), "Hack_Success", "DLC_HEIST_BIOLAB_PREP_HACKING_SOUNDS", 0)
		-- sonnerie = 0
		-- end
	-- end
-- end)



RegisterNetEvent('OpenSMSForAuthor')
AddEventHandler('OpenSMSForAuthor', function(name)
	
    ShowNotificationMenuCivil2("~h~Vous avez envoyé un message à  ~b~"..name.."~w~.")
end)


Citizen.CreateThread(function()
	while true do
        Citizen.Wait(0)	
		    			
			if (affichesms == true) then
			
		    DrawRect(0.912000000000001, 0.292, 0.185, 0.205, 0, 0, 0, 150)
			DrawAdvancedText(0.966000000000001, 0.220, 0.005, 0.0028, 0.7, "~h~MESSAGE", 255, 255, 255, 255, 1, 1)
			DrawAdvancedText(0.924000000000001, 0.278, 0.005, 0.0028, 0.4, "de ~h~~b~"..authorForSMS, 255, 255, 255, 255, 6, 1)
			DrawAdvancedText(0.924000000000001, 0.322, 0.005, 0.0028, 0.4, messageForSMS, 255, 255, 255, 255, 6, 1)		
			
			end
	end
end)


RegisterNetEvent('FinishMenuCivil')
AddEventHandler('FinishMenuCivil', function()
	civilmenu.opened = false
	civilmenu.menu.from = 1
	civilmenu.menu.to = 10
	inmenucivil = 0
	inmenuinv = 0
	inmenujob = 0
end)

function ShowInfoCarteIdentite(text, state)
	SetTextComponentFormat("STRING")
	AddTextComponentString(text)
	DisplayHelpTextFromStringLabel(0, state, 0, -1)
end

function OpenMenuCivilmenu(menu)
	civilmenu.lastmenu = civilmenu.currentmenu
	if menu == "mainanimation" then
		civilmenu.lastmenu = "main"
	elseif menu == "maintelephone"  then
		civilmenu.lastmenu = "main"
	elseif menu == 'mainrepertoire' then
		civilmenu.lastmenu = "maintelephone"
	elseif menu == "race_create_objects_spawn" then
		civilmenu.lastmenu = "race_create_objects"
	end
	civilmenu.menu.from = 1
	civilmenu.menu.to = 10
	civilmenu.selectedbutton = 0
	civilmenu.currentmenu = menu	
end


function BackCivilMenu()
	if backlock then
		return
	end
	backlock = true
	if civilmenu.currentmenu == "main" then
		CloseCreatorcivilmenu()
		inmenucivil = 0
		inmenuinv = 0
		inmenujob = 0
	else
		OpenMenuCivilmenu(civilmenu.lastmenu)
	end
end

function stringstartsCivilMenu(String,Start)
   return string.sub(String,1,string.len(Start))==Start
end

RegisterNetEvent('PhoneOK')
AddEventHandler('PhoneOK', function(havetel)
    if havetel ~= null then
        OpenMenuCivilmenu('maintelephone')
    else
        ShowNotificationMenuCivil2("~h~~r~Vous n'avez de téléphone !")
    end
end)


function DrawMissionText3(m_text, showtime)
		ClearPrints()
		SetTextEntry_2("STRING")
		AddTextComponentString(m_text)
		DrawSubtitleTimed(showtime, 1)
		end
		
Citizen.CreateThread(function()
	while true do
		Citizen.Wait(0)
		if IsControlPressed(1, 323) and IsPedInAnyVehicle(GetPlayerPed(-1), true) == false then --Start holding X
			TaskHandsUp(GetPlayerPed(-1), 1000, GetPlayerPed(-1), -1, true) -- Perform animation.
		end
	end
end)



Citizen.CreateThread(function()

	while true do
		Citizen.Wait(1)
		
		entitytarget = Citizen.InvokeNative(0x2975C866E6713290, PlayerId(), Citizen.PointerValueInt(), Citizen.ResultAsInteger(entitytarget))
			
		
			local pos = GetEntityCoords(GetPlayerPed(-1))
            local t = 0
			for i = 0,2000 do
				if(GetPlayerServerId(i))then
					if GetDistanceBetweenCoords(GetEntityCoords(GetPlayerPed(-1)), GetEntityCoords(GetPlayerPed(i))) > 3.0001 then
					    -- totarget = 0
					else
						
					    if(NetworkIsPlayerTalking(i)) then
						--if(NetworkIsPlayerActive(i))then
						t = t + 1

						    if(t == 1)then
							
								--DrawMissionText3("[DEBUG] Civil Proche "..GetPlayerServerId(i), 1000)
								totarget = GetPlayerServerId(i)
								
						    end
					    end
					end
				end
			end
	end
end)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
local invmenu = {
	opened = false,
	title = "Inventaire",
	currentmenu = "main",
	lastmenu = nil,
	currentpos = nil,
	selectedbutton = 0,
	marker = { r = 0, g = 155, b = 255, a = 200, type = 1 },
	menu = {
		x = 0.1,
		y = 0.32,
		width = 0.2,
		height = 0.04,
		buttons = 9,
		from = 1,
		to = 9,
		scale = 0.4,
		font = 0,
		["main"] = { 
			title = "", 
			name = "main",
			buttons = {
				
			}
		},
		["itemmenu"] = { 
			title = "", 
			name = "itemmenu",
			buttons = { 
				{name = "Utiliser", description = ''},
				{name = "Donner", description = ''},
				{name = "Supprimer", description = ''},
			}
		},
	}
}


RegisterNetEvent('MyInvClient')
AddEventHandler('MyInvClient', function(playerinventory,iteminfo,playername)
	-- inmenucivil = 0
	-- inmenuinv = 1
	-- inmenujob = 0
	iteminuse = 0
	local insrt = table.insert
	invmenu.menu["main"].title = playername
	invmenu.menu["main"].buttons = {}
	counttable = tablelength(playerinventory)
	countbutton = 0
	i = 1

	while countbutton ~= counttable do
		item = playerinventory[iteminfo[i]['item_price_name']]
		if item ~= null then
			if item > 1 then
				nametext = iteminfo[i]['name_pluriel']
			else
				nametext = iteminfo[i]['name_singulier']
			end
			finaltext = item.." "..nametext
			refname = iteminfo[i]['item_price_name']
			fct = iteminfo[i]['function_use_item']
			reftext = iteminfo[i]['name_singulier']
			insrt(invmenu.menu["main"].buttons, {name = finaltext, description = "", ref = refname, itemnumber = item,textsing = reftext, use = fct})
			countbutton = countbutton + 1
		end
		i = i + 1
	end

	invmenu.currentmenu = "main"
	invmenu.opened = true
	invmenu.selectedbutton = 0
end)

--NOTIFICATION 
RegisterNetEvent('GiveTarget')
AddEventHandler('GiveTarget', function(item, name)
    if (item == "GPS") then
		gpsacitve = 1
	end
	ShowNotificationMain("~h~Vous avez refusé ~g~un "..item.."~w~ de la part de ~b~"..name.."~w~.")
end)

RegisterNetEvent('GiveSource')
AddEventHandler('GiveSource', function(item, name)
	ShowNotificationMain("~h~Vous avez donné ~g~un "..item.."~w~ à  ~b~"..name.."~w~.")
end)

RegisterNetEvent('Deletesource')
AddEventHandler('Deletesource', function(item)
	ShowNotificationMain("~h~Vous avez supprimé ~r~un "..item.."~w~.")
end)

local function LocalPed()
return GetPlayerPed(-1)
end

function CloseCreatorinvmenu()
	Citizen.CreateThread(function()
		invmenu.opened = false
		invmenu.menu.from = 1
		invmenu.menu.to = 10
		inmenucivil = 0
		inmenuinv = 0
		inmenujob = 0
	end)
end

--Menu pomenu

function drawMenuButton(button,x,y,selected)
	local menu = invmenu.menu
	SetTextFont(menu.font)
	SetTextProportional(0)
	SetTextScale(menu.scale, menu.scale)
	if selected then
		SetTextColour(0, 0, 0, 255)
	else
		SetTextColour(255, 255, 255, 255)
	end
	SetTextCentre(0)
	SetTextEntry("STRING")
	AddTextComponentString(button.name)
	if selected then
		DrawRect(x,y,menu.width,menu.height,255,255,255,255)
	else
		DrawRect(x,y,menu.width,menu.height,0,0,0,150)
	end
	DrawText(x - menu.width/2 + 0.005, y - menu.height/2 + 0.0028)	
end

function drawMenuTitleInv(txt,x,y)
local menu = invmenu.menu
	SetTextFont(2)
	SetTextProportional(0)
	SetTextScale(0.5, 0.5)
	SetTextColour(255, 255, 255, 255)
	SetTextEntry("STRING")
	AddTextComponentString(txt)
	DrawRect(x,y,menu.width,menu.height,93,166,202,150)
	DrawText(x - menu.width/2 + 0.005, y - menu.height/2 + 0.0028)
end

function tablelength(T)
  local count = 0
  for _ in pairs(T) do count = count + 1 end
  return count
end
function Notifyinvmenu(text)
SetNotificationTextEntry('STRING')
AddTextComponentString(text)
DrawNotification(false, false)
end

local backlock = false
Citizen.CreateThread(function()
	while true do
		Citizen.Wait(0)
		if IsControlJustPressed(1,289) then
		if IsPedInAnyVehicle(LocalPed(), true) == false then
		if (inmenucivil == 0) and (inmenujob == 0) then
			if invmenu.opened then
				CloseCreatorinvmenu()
			else
				TriggerServerEvent('MyInv')		
				inmenucivil = 0
				inmenuinv = 1
				inmenujob = 0
			end
		end
		else
		    ShowNotificationMenuCivil2("~r~Vous ne pouvez pas ouvrir le menu dans un véhicule !")
	    end
		end
		if invmenu.opened then
			local ped = LocalPed()
			local menu = invmenu.menu[invmenu.currentmenu]
			drawTxt(invmenu.title,1,1,invmenu.menu.x,invmenu.menu.y,1.0, 255,255,255,255)
			drawMenuTitleInv(menu.title, invmenu.menu.x,invmenu.menu.y + 0.08)
			drawTxt(invmenu.selectedbutton.."/"..tablelength(menu.buttons),0,0,invmenu.menu.x + invmenu.menu.width/2 - 0.0385,invmenu.menu.y + 0.067,0.4, 255,255,255,255)
			local y = invmenu.menu.y + 0.12
			buttoncount = tablelength(menu.buttons)
			local selected = false
			
			for i,button in pairs(menu.buttons) do
				if i >= invmenu.menu.from and i <= invmenu.menu.to then
					
					if i == invmenu.selectedbutton then
						selected = true
					else
						selected = false
					end
					drawMenuButton(button,invmenu.menu.x,y,selected)
					y = y + 0.04
					if selected and IsControlJustPressed(1,201) then
						ButtonSelectedinvmenu(button)
					end
				end
			end	
		end
		if invmenu.opened then
			if IsControlJustPressed(1,202) then
				Backinvmenu()
			end
			if IsControlJustReleased(1,202) then
				backlock = false
			end
			if IsControlJustPressed(1,188) then
				if invmenu.selectedbutton > 1 then
					invmenu.selectedbutton = invmenu.selectedbutton -1
					if buttoncount > 10 and invmenu.selectedbutton < invmenu.menu.from then
						invmenu.menu.from = invmenu.menu.from -1
						invmenu.menu.to = invmenu.menu.to - 1
					end
				end
			end
			if IsControlJustPressed(1,187)then
				if invmenu.selectedbutton < buttoncount then
					invmenu.selectedbutton = invmenu.selectedbutton +1
					if buttoncount > 10 and invmenu.selectedbutton > invmenu.menu.to then
						invmenu.menu.to = invmenu.menu.to + 1
						invmenu.menu.from = invmenu.menu.from + 1
					end
				end	
			end
		end
	end
end)


				
function ButtonSelectedinvmenu(button)
	local ped = GetPlayerPed(-1)
	local this = invmenu.currentmenu
	local btn = button.name
	callx, cally, callz = table.unpack(GetEntityCoords(GetPlayerPed(-1) , true))
	if this == "main" then
			useitem = button.use
			itemref = button.ref
			nameofitem = button.textsing
			actualnumber = button.itemnumber
			invmenu.menu["itemmenu"].title = nameofitem
			OpenMenuinvmenu('itemmenu')
	elseif this == "itemmenu" then
		if btn == "Utiliser" then
			if useitem == "" then
				ShowNotificationMain("~h~Cet objet n'est pas utilisable.")
			else	
				if iteminuse == 1 then
					ShowNotificationMain("~h~Hum..le mélange n'est jamais bon !'")
				else
					fctuse = load(useitem.."()")
					iteminuse = 1
					CloseCreatorinvmenu()
				end
			end
		elseif btn =="Donner" then
		    if (itemref == "gps") and (actualnumber == 1) then
			    gpsacitve = 0
			end
			targetid = totarget
			TriggerServerEvent('InvGive',targetid,itemref,nameofitem)
			actualnumber = actualnumber -1
			if actualnumber <= 0 then
				CloseCreatorinvmenu()
			end

		elseif btn =="Supprimer" then
		    if (itemref == "gps") and (actualnumber == 1) then
			    gpsacitve = 0
			end
			TriggerServerEvent('InvDelete',itemref,nameofitem)
			actualnumber = actualnumber -1
			if actualnumber <= 0 then
				CloseCreatorinvmenu()
			end
			
		end
	end
end

function OpenMenuinvmenu(menu)
	invmenu.lastmenu = invmenu.currentmenu
	if menu == "itemmenu" then
		invmenu.lastmenu = "main"
	end
	invmenu.menu.from = 1
	invmenu.menu.to = 10
	invmenu.selectedbutton = 0
	invmenu.currentmenu = menu	
end


function Backinvmenu()
	if backlock then
		return
	end
	backlock = true
	if invmenu.currentmenu == "main" then
		CloseCreatorinvmenu()
	end
	if invmenu.currentmenu == "itemmenu" then
		invmenu.opened = false
		invmenu.menu.from = 1
		invmenu.menu.to = 10
		TriggerServerEvent('MyInv')	
	else
		OpenMenuinvmenu(invmenu.lastmenu)
	end
end

function stringstartsinvmenu(String,Start)
   return string.sub(String,1,string.len(Start))==Start
end

function tablelength(T)
  local count = 0
  for _ in pairs(T) do count = count + 1 end
  return count
end