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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALfZHJgAAAEAdFJOU////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////wBT9wclAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAGHRFWHRTb2Z0d2FyZQBwYWludC5uZXQgNC4xLjb9TgnoAAAGdUlEQVRoQ7WZ93sURRiAFZO76O1eklt215OgBwqJgmgCRhAhRrAAiogBK4gBJEFEgWAEYiGIYEGp1kjXQECkiF0OWyjJ/k34zcy3db7Zu8fHe3/KTXnzPbPT56orRTEYAhMLUFgNKkeiGH8BNaV1KWSPVXveU9s3LW9pvhdoblm+afspTHZi5Wo1BnzpaOfcnFmWSBv29YBtpBNlZm5u59FLPDsmdJUaxQeXNugZw5IwMnrD0oO8iFKuUHNx/+bGZLWNMgm7Otm4uZ/LsVIEUs3F+Y5a3USNAlOv7cgr5ZSamQffyOnKgH1sPdfFi2PVILKaReEcmKwVIWbY2uQDvApW95HULIb+Ng0rFoXWxppcCjyqZuZjk4oNWWBrk44R7oiamXdkC3w9GTO7Q3aH1cy8OkWFnHtitstM4j/bqdWSO6Rm5nYdS4e5FbKQwxlMC6G3Q1bIHVQz8+IKLBphJLdydlRjWpiKxZAXdAfUPOak4gOO4FZOdxWmhbGTkbh9NTOvoVsDuGmAaxkdlZgWRV8Dub7bV0PyzhQWkqk5z7WMdjpqILUTslEXUEPQJ7Lq7pz9WXiBZ4iZUGBnTwTCdtVgvjgxpj+b3vTvTEteq5KbEy/6blcNVZapR3cmdc9Z4QV6Pnxzdr1GF9aWQQFUohqCPqQc3ZV17X3C6tP31kyL+Jy2dsgLW6jBPDgVc6OkR3XxCV/i9IqRRFedylxc6qk30L3DNF7ikz1Jft0oLOaT2hBSg/l8jmwOo24/amimYzkfOwfdlLtdNT1YjIaf0EFzgGhuNnB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7N8XNtH0VP6mXfvV+z4iEsLFrbqqkXXho2Z8dynwgo8NdZK0SXpqxbmjrsgquhCsXrhgOYgL4h4k8Rca5VvFV7gTkySUVxrsbBjLuOGfMy1jCZFa6gv47hbeYU4ZA/XMmbRy13MFaJwqy4+Ez1cy3iSVsddfGLcdJvo33Ato5VcSeOva4WbvmQ2v+daxkrqfqXQJbNwk1fj9kOPuNwlZxdxNS7c5IW+MdRFMhd3oS/cpXmG4EOnRI8nAAt8sKsETz4AK1yahyqAy0vxvAaU7lEQcJ8yj9BPmUf+81MmR8iB//kBllOyZ2NOqR67XUAVABNjuXLlX2rCcoFjOcGoAAAAAElFTkSuQmCC'

RegisterNetEvent('esx:setJob')
AddEventHandler('esx:setJob', function(job)
	ESX.PlayerData.job = job
	RefreshBussHUD()
end)

RegisterNetEvent('esx:playerLoaded')
AddEventHandler('esx:playerLoaded', function(xPlayer)
	ESX.PlayerData = xPlayer
	ESX.PlayerLoaded = true
	RefreshBussHUD()
end)

function RefreshBussHUD()
	DisableSocietyMoneyHUDElement()

	if ESX.PlayerData.job.grade_name == 'boss' then
		EnableSocietyMoneyHUDElement()

		ESX.TriggerServerCallback('esx_society:getSocietyMoney', function(money)
			UpdateSocietyMoneyHUDElement(money)
		end, ESX.PlayerData.job.name)
	end
end

RegisterNetEvent('esx_addonaccount:setMoney')
AddEventHandler('esx_addonaccount:setMoney', function(society, money)
	if ESX.PlayerData.job and ESX.PlayerData.job.grade_name == 'boss' and 'society_' .. ESX.PlayerData.job.name == society then
		UpdateSocietyMoneyHUDElement(money)
	end
end)

function EnableSocietyMoneyHUDElement()
	local societyMoneyHUDElementTpl = '<div><img src="' .. base64MoneyIcon .. '" style="width:20px; height:20px; vertical-align:middle;">&nbsp;{{money}}</div>'

	if ESX.GetConfig().EnableHud then
		ESX.UI.HUD.RegisterElement('society_money', 3, 0, societyMoneyHUDElementTpl, {
			money = 0
		})
	end

	TriggerEvent('esx_society:toggleSocietyHud', true)
end

function DisableSocietyMoneyHUDElement()
	if ESX.GetConfig().EnableHud then
		ESX.UI.HUD.RemoveElement('society_money')
	end

	TriggerEvent('esx_society:toggleSocietyHud', false)
end

function UpdateSocietyMoneyHUDElement(money)
	if ESX.GetConfig().EnableHud then
		ESX.UI.HUD.UpdateElement('society_money', {
			money = ESX.Math.GroupDigits(money)
		})
	end

	TriggerEvent('esx_society:setSocietyMoney', money)
end

function OpenBossMenu(society, close, options)
	options = options or {}
	local elements = {
		{unselectable = true, icon = "fas fa-user", title = TranslateCap('boss_menu')}
	}

	ESX.TriggerServerCallback('esx_society:isBoss', function(isBoss)
		if isBoss then
			local defaultOptions = {
				checkBal = true,
				withdraw = true,
				deposit = true,
				wash = true,
				employees = true,
				salary = true,
				grades = true
			}

			for k,v in pairs(defaultOptions) do
				if options[k] == nil then
					options[k] = v
				end
			end

			if options.checkBal then
				elements[#elements+1] = {icon = "fas fa-wallet", title = TranslateCap('check_society_balance'), value = "check_society_balance"}
			end
			if options.withdraw then
				elements[#elements+1] = {icon = "fas fa-wallet", title = TranslateCap('withdraw_society_money'), value = "withdraw_society_money"}
			end
			if options.deposit then
				elements[#elements+1] = {icon = "fas fa-wallet", title = TranslateCap('deposit_society_money'), value = "deposit_money"}
			end
			if options.wash then
				elements[#elements+1] = {icon = "fas fa-wallet", title = TranslateCap('wash_money'), value = "wash_money"}
			end
			if options.employees then
				elements[#elements+1] = {icon = "fas fa-users", title = TranslateCap('employee_management'), value = "manage_employees"}
			end
			if options.salary then
				elements[#elements+1] = {icon = "fas fa-wallet", title = TranslateCap('salary_management'), value = "manage_salary"}
			end
			if options.grades then
				elements[#elements+1] = {icon = "fas fa-scroll", title = TranslateCap('grade_management'), value = "manage_grades"}
			end

			ESX.OpenContext("right", elements, function(menu,element)
				if element.value == "check_society_balance" then
					TriggerServerEvent('esx_society:checkSocietyBalance', society)
				elseif element.value == "withdraw_society_money" then
					local elements = {
						{unselectable = true, icon = "fas fa-wallet", title = TranslateCap('withdraw_amount'), description = "Withdraw money from the society account"},
						{icon = "fas fa-wallet", title = "Amount", input = true, inputType = "number", inputPlaceholder = "Amount to withdraw..", inputMin = 1, inputMax = 250000, name = "withdraw"},
						{icon = "fas fa-check", title = "Confirm", value = "confirm"}
					}
					ESX.RefreshContext(elements)
				elseif element.value == "confirm" then
					local amount = tonumber(menu.eles[2].inputValue)
					if amount == nil then
						ESX.ShowNotification(TranslateCap('invalid_amount'))
					else
						TriggerServerEvent('esx_society:withdrawMoney', society, amount)
						ESX.CloseContext()
					end
				elseif element.value == "deposit_money" then
					local elements = {
						{unselectable = true, icon = "fas fa-wallet", title = TranslateCap('deposit_amount'), description = "Deposit some money into the society account"},
						{icon = "fas fa-wallet", title = "Amount", input = true, inputType = "number", inputPlaceholder = "Amount to deposit..", inputMin = 1, inputMax = 250000, name = "deposit"},
						{icon = "fas fa-check", title = "Confirm", value = "confirm2"}
					}
					ESX.RefreshContext(elements)
				elseif element.value == "confirm2" then
					local amount = tonumber(menu.eles[2].inputValue)
					if amount == nil then
						ESX.ShowNotification(TranslateCap('invalid_amount'))
					else
						TriggerServerEvent('esx_society:depositMoney', society, amount)
						ESX.CloseContext()
					end
				elseif element.value == "wash_money" then
					local elements = {
						{unselectable = true, icon = "fas fa-wallet", title = TranslateCap('wash_money_amount'), description = "Deposit some money into the money wash"},
						{icon = "fas fa-wallet", title = "Amount", input = true, inputType = "number", inputPlaceholder = "Amount to wash..", inputMin = 1, inputMax = 250000, name = "wash"},
						{icon = "fas fa-check", title = "Confirm", value = "confirm3"}
					}
					ESX.RefreshContext(elements)
				elseif element.value == "confirm3" then
					local amount = tonumber(menu.eles[2].inputValue)
					if amount == nil then
						ESX.ShowNotification(TranslateCap('invalid_amount'))
					else
						TriggerServerEvent('esx_society:washMoney', society, amount)
						ESX.CloseContext()
					end
				elseif element.value == "manage_employees" then
					OpenManageEmployeesMenu(society)
				elseif element.value == "manage_salary" then
					OpenManageSalaryMenu(society)
				elseif element.value == "manage_grades" then
					OpenManageGradesMenu(society)
				end
			end)
		end
	end, society)
end

function OpenManageEmployeesMenu(society)
	local elements = {
		{unselectable = true, icon = "fas fa-users", title = TranslateCap('employee_management')},
		{icon = "fas fa-users", title = TranslateCap('employee_list'), value = "employee_list"},
		{icon = "fas fa-users", title = TranslateCap('recruit'), value = "recruit"}
	}
	ESX.OpenContext("right", elements, function(menu,element)
		if element.value == "employee_list" then
			OpenEmployeeList(society)
		elseif element.value == "recruit" then
			OpenRecruitMenu(society)	
		end
	end)
end

function OpenEmployeeList(society)
	ESX.TriggerServerCallback('esx_society:getEmployees', function(employees)
		local elements = {
			{unselectable = true, icon = "fas fa-user", title = "Employees"}
		}

		for i=1, #employees, 1 do
			local gradeLabel = (employees[i].job.grade_label == '' and employees[i].job.label or employees[i].job.grade_label)

			elements[#elements+1] = {icon = "fas fa-user", title = employees[i].name .. " | " ..gradeLabel, gradeLabel = gradeLabel, data = employees[i]}
		end

		elements[#elements+1] = {icon = "fas fa-arrow-left", title = "Return", value = "return"}

		ESX.OpenContext("right", elements, function(menu,element) 
			if element.value == "return" then
				OpenManageEmployeesMenu(society)
			else
				local elements2 = {
					{unselectable = true, icon = "fas fa-user", title = element.title},
					{icon = "fas fa-user", title = "Promote", value = "promote"},
					{icon = "fas fa-user", title = "Fire", value = "fire"},
					{icon = "fas fa-arrow-left", title = "Return", value = "return"}
				}
				ESX.OpenContext("right", elements2, function(menu2,element2)
					local employee = element.data
					if element2.value == "promote" then
						ESX.CloseContext()
						OpenPromoteMenu(society, employee)
					elseif element2.value == "fire" then
						ESX.ShowNotification(TranslateCap('you_have_fired', employee.name))

						ESX.TriggerServerCallback('esx_society:setJob', function()
							OpenEmployeeList(society)
						end, employee.identifier, 'unemployed', 0, 'fire')
					elseif element2.value == "return" then
						OpenEmployeeList(society)
					end
				end)
			end
		end)
	end, society)
end

function OpenRecruitMenu(society)
	ESX.TriggerServerCallback('esx_society:getOnlinePlayers', function(players)
		local elements = {
			{unselectable = true, icon = "fas fa-user", title = TranslateCap('recruiting')}
		}

		for i=1, #players, 1 do
			if players[i].job.name ~= society then
				elements[#elements+1] = {icon = "fas fa-user", title = players[i].name, value = players[i].source, name = players[i].name, identifier = players[i].identifier}
			end
		end

		elements[#elements+1] = {icon = "fas fa-arrow-left", title = "Return", value = "return"}

		ESX.OpenContext("right", elements, function(menu,element)
			if element.value == "return" then
				OpenManageEmployeesMenu(society)
			else
				local elements2 = {
					{unselectable = true, icon = "fas fa-user", title = "Confirm"},
					{icon = "fas fa-times", title = TranslateCap('no'), value = "no"},
					{icon = "fas fa-check", title = TranslateCap('yes'), value = "yes"},
				}
				ESX.OpenContext("right", elements2, function(menu2,element2)
					if element2.value == "yes" then
						ESX.ShowNotification(TranslateCap('you_have_hired', element.name))

						ESX.TriggerServerCallback('esx_society:setJob', function()
							OpenRecruitMenu(society)
						end, element.identifier, society, 0, 'hire')
					end
				end)
			end
		end)
	end)
end

function OpenPromoteMenu(society, employee)
	ESX.TriggerServerCallback('esx_society:getJob', function(job)
		local elements = {
			{unselectable = true, icon = "fas fa-user", title = TranslateCap('promote_employee', employee.name)}
		}

		for i=1, #job.grades, 1 do
			local gradeLabel = (job.grades[i].label == '' and job.label or job.grades[i].label)

			elements[#elements+1] = {icon = "fas fa-user", title = gradeLabel, value = job.grades[i].grade, selected = (employee.job.grade == job.grades[i].grade)}
		end

		elements[#elements+1] = {icon = "fas fa-arrow-left", title = "Return", value = "return"}

		ESX.OpenContext("right", elements, function(menu,element)
			if element.value == "return" then
				OpenEmployeeList(society)
			else
				ESX.ShowNotification(TranslateCap('you_have_promoted', employee.name, element.title))

				ESX.TriggerServerCallback('esx_society:setJob', function()
					OpenEmployeeList(society)
				end, employee.identifier, society, element.value, 'promote')
			end
		end, function(menu)
			OpenEmployeeList(society)
		end)
	end, society)
end

function OpenManageSalaryMenu(society)
	ESX.TriggerServerCallback('esx_society:getJob', function(job)
		local elements = {
			{unselectable = true, icon = "fas fa-wallet", title = TranslateCap('salary_management')}
		}

		for i=1, #job.grades, 1 do
			local gradeLabel = (job.grades[i].label == '' and job.label or job.grades[i].label)

			elements[#elements+1] = {
				icon = "fas fa-wallet",
				title = ('%s - <span style="color:green;">%s</span>'):format(gradeLabel, TranslateCap('money_generic', ESX.Math.GroupDigits(job.grades[i].salary))),
				value = job.grades[i].grade
			}
		end

		ESX.OpenContext("right", elements, function(menu,element)
			local elements = {
				{unselectable = true, icon = "fas fa-wallet", title = element.title, description = "Change a grade salary amount", value = element.value},
				{icon = "fas fa-wallet", title = "Amount", input = true, inputType = "number", inputPlaceholder = "Amount to change grade salary..", inputMin = 1, inputMax = Config.MaxSalary, name = "gradesalary"},
				{icon = "fas fa-check", title = "Confirm", value = "confirm"}
			}

			ESX.RefreshContext(elements)
			if element.value == "confirm" then
				local amount = tonumber(menu.eles[2].inputValue)

				if amount == nil then
					ESX.ShowNotification(TranslateCap('invalid_amount'))
				elseif amount > Config.MaxSalary then
					ESX.ShowNotification(TranslateCap('invalid_amount_max'))
				else
					ESX.CloseContext()
					ESX.TriggerServerCallback('esx_society:setJobSalary', function()
						OpenManageSalaryMenu(society)
					end, society, menu.eles[1].value, amount)
				end
			end
		end)
	end, society)
end

function OpenManageGradesMenu(society)
	ESX.TriggerServerCallback('esx_society:getJob', function(job)
		local elements = {
			{unselectable = true, icon = "fas fa-wallet", title = TranslateCap('grade_management')}
		}

		for i=1, #job.grades, 1 do
			local gradeLabel = (job.grades[i].label == '' and job.label or job.grades[i].label)

			elements[#elements+1] = {icon = "fas fa-wallet", title = ('%s'):format(gradeLabel), value = job.grades[i].grade}
		end

		ESX.OpenContext("right", elements, function(menu,element)
			local elements = {
				{unselectable = true, icon = "fas fa-wallet", title = element.title, description = "Change a grade label", value = element.value},
				{icon = "fas fa-wallet", title = "Label", input = true, inputType = "text", inputPlaceholder = "Label to change job grade label..", name = "gradelabel"},
				{icon = "fas fa-check", title = "Confirm", value = "confirm"}
			}

			ESX.RefreshContext(elements)
			if element.value == "confirm" then
				local label = tostring(menu.eles[2].inputValue)

				ESX.TriggerServerCallback('esx_society:setJobLabel', function()
					OpenManageGradesMenu(society)
				end, society, menu.eles[1].value, label)
			end
		end)
	end, society)
end

AddEventHandler('esx_society:openBossMenu', function(society, close, options)
	OpenBossMenu(society, close, options)
end)

if ESX.PlayerLoaded then RefreshBussHUD() end
