if Config.framework == "newesx" then
	ESX = exports["es_extended"]:getSharedObject()
else
	TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
end

--██████╗ ██████╗ ██████╗ ███████╗
--██╔════╝██╔═══██╗██╔══██╗██╔════╝
--██║     ██║   ██║██║  ██║█████╗  
--██║     ██║   ██║██║  ██║██╔══╝  
--╚██████╗╚██████╔╝██████╔╝███████╗
-- ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝                    

AddEventHandler('onServerResourceStart', function (resource)
	if (GetCurrentResourceName() ~= resource) then
	  return
	end

	for _, playerId in ipairs(GetPlayers()) do
		Wait(500)
		TriggerClientEvent('mailbox:refresh', playerId)
	end
end)

RegisterNetEvent('mailbox:openmenu')
AddEventHandler('mailbox:openmenu', function()
	local xPlayer = GetPlayerFromId(source)
	local grade = getAdmin()

	for k,v in pairs(Config.staffgrade) do
		if grade == v then
			TriggerClientEvent('mailbox:openmenu', source)
		end
	end
end)

RegisterNetEvent('mailbox:create')
AddEventHandler('mailbox:create', function(label, position, heading, whitelist, enableProps, propsmodel)
	MySQL.Async.execute("INSERT INTO mailbox (label, position, heading, whitelist, enableProps, props) VALUES (@label, @position, @heading, @whitelist, @enableProps, @props)", 	
	{
		['@label'] = label,
		['@position'] = json.encode(position),
		['@heading'] = heading,
		['@whitelist'] = whitelist,
		['@enableProps'] = enableProps,
		['@props'] = propsmodel,
	}) 

	TriggerClientEvent('mailbox:notification', source, Locale["create_maillbox_notif"], "success")

	Wait(200)

	for _, playerId in ipairs(GetPlayers()) do
		TriggerClientEvent('mailbox:refresh', playerId)
	end
end)

RegisterServerCallback("mailbox:getidentifier", function(source, cb)
	local source = source
	local xPlayer = GetPlayerFromId(source)
	local identifier = getIdentifier(xPlayer, source)
	cb(identifier)
end)

RegisterServerCallback("mailbox:listing", function(source, cb)
    local mailbox =  {}
    MySQL.Async.fetchAll('SELECT * FROM mailbox', {
    }, function(data)
        for k, v in pairs(data) do
            table.insert(mailbox, {id = v.id, label = v.label, position = json.decode(v.position), whitelist = v.whitelist, enableProps = v.enableProps, props = v.props, heading = v.heading})
        end
    end)

	Wait(200)
	
	cb(mailbox)
end)

RegisterServerEvent("mailbox:sendlettre")
AddEventHandler("mailbox:sendlettre", function(id_mailbox, contenu, anonyme)
	local source = source
	local xPlayer = GetPlayerFromId(source)
	local identifier = getIdentifier(xPlayer, source)
	local date = os.date('*t')

	if date.day < 10 then date.day = '' .. tostring(date.day) end
	if date.month < 10 then date.month = '' .. tostring(date.month) end
	if date.hour < 10 then date.hour = '' .. tostring(date.hour) end
	if date.min < 10 then date.min = '' .. tostring(date.min) end
	if date.sec < 10 then date.sec = '' .. tostring(date.sec) end
	
	local datefortable = date.day.."/"..date.month.."/"..date.year.." | "..date.hour.."h "..date.min.."min"

	MySQL.Async.fetchAll('SELECT * FROM mailbox_letter where identifier = @identifier AND id_mailbox = @id_mailbox', {
		['@identifier'] = identifier,
		['@id_mailbox'] = id_mailbox,
    }, function(data)
		if #data < Config.limitePerPerson then
			MySQL.Async.execute("INSERT INTO mailbox_letter (identifier, id_mailbox, contenu, anonyme, date) VALUES (@identifier, @id_mailbox, @contenu, @anonyme, @date)", 	
			{
				['@identifier'] = identifier,
				['@id_mailbox'] = id_mailbox, 
				['@contenu'] = contenu,
				["@anonyme"] = anonyme,
				['@date'] = datefortable,
			}, function()
				TriggerClientEvent('mailbox:notification', source, Locale["post_letter"], "success")
			end)
		else
			TriggerClientEvent('mailbox:notification', source, Locale["already_post_in_mailbox"], "error")
		end
    end)
end)

RegisterServerCallback("mailbox:getlettre", function(source, cb, idletter)
	local tablelettre = {}
	MySQL.Async.fetchAll("SELECT * FROM mailbox_letter WHERE id_mailbox = @id_mailbox", {
		["@id_mailbox"] = idletter,
	}, function(data)
		for k,v in pairs(data) do
			MySQL.Async.fetchAll('SELECT * FROM '..usertable..' WHERE '..identifiertable..' = @identifier', {
				['@identifier'] = data[1].identifier,
			}, function(user)
				if v.anonyme == "no" then
					table.insert(tablelettre, {id = v.id, contenu = v.contenu, name = user[1].firstname.." "..user[1].lastname, identifier = v.identifier, date = v.date})
				else
					table.insert(tablelettre, {id = v.id, contenu = v.contenu, name = Locale["anonyme_letter"], identifier = v.identifier, date = v.date})

				end
			end)
		end

		Wait(500)

		cb(tablelettre)
	end)
end)

RegisterServerEvent("mailbox:suppressionlettre")
AddEventHandler("mailbox:suppressionlettre", function(idlettre)
	MySQL.Async.execute('DELETE from mailbox_letter WHERE id = @id', {
		['@id'] = idlettre,
	})  

	TriggerClientEvent('mailbox:notification', source, Locale["delete_letter_notif"], "success")
end)

RegisterServerEvent("mailbox:editpos")
AddEventHandler("mailbox:editpos", function(idlettre, position, heading, props, oldposition)
	MySQL.Async.execute("UPDATE mailbox SET `position` = @position, `heading` = @heading WHERE id = @id", {
		["@id"] = idlettre,
		['@position'] = json.encode(position),
		['@heading'] = heading,
	}, function()
    end)

	TriggerClientEvent('mailbox:notification', source, Locale["edit_mailbox_notification"], "success")

	for _, playerId in ipairs(GetPlayers()) do
		Wait(100)
		TriggerClientEvent('mailbox:refresh_edit', playerId, idlettre, position, props, oldposition)
	end
end)

RegisterServerEvent("mailbox:deletemailbox")
AddEventHandler("mailbox:deletemailbox", function(idlettre_delete, position, props_delete)
	MySQL.Async.execute('DELETE from mailbox WHERE id = @id', {
		['@id'] = idlettre_delete
	})

	TriggerClientEvent('mailbox:notification', source, Locale["delete_mailbox_notification"], "success")

	Wait(400)

	for _, playerId in ipairs(GetPlayers()) do
		TriggerClientEvent('mailbox:refresh_edit', playerId, idlettre_delete, position, props_delete)
	end
end)