-----------------------------------------------------------------------------------------------------------------------------------------
-- VRP
-----------------------------------------------------------------------------------------------------------------------------------------
local Tunnel = module("vrp","lib/Tunnel")
local Proxy = module("vrp","lib/Proxy")
local Tools = module("vrp","lib/Tools")
vRP = Proxy.getInterface("vRP")
vRPclient = Tunnel.getInterface("vRP")
local inventory = module("vrp","cfg/inventory")

cRP = {}
local idgens = Tools.newIDGenerator()
Tunnel.bindInterface("et_inv",cRP)
vCLIENT = Tunnel.getInterface("et_inv")
-----------------------------------------------------------------------------------------------------------------------------------------
-- CONEXÃO
-----------------------------------------------------------------------------------------------------------------------------------------
local vthirst = 0
local vhunger = 0


vGARAGE = Tunnel.getInterface(tunnel_garagem)
vHOMES = Tunnel.getInterface(tunnel_homes)
vTASKBAR = Tunnel.getInterface(tunnel_taskbar)
vPLAYER = Tunnel.getInterface(tunnel_player)
-----------------------------------------------------------------------------------------------------------------------------------------
-- VARIABLES
-----------------------------------------------------------------------------------------------------------------------------------------

local active = {}
local actived = {}
local bandagem = {}
local amountUse = {}
local uchests = {}
local vchests = {}
local syringeTime = {}

vRP._prepare("homes/get_homepermissions","SELECT * FROM vrp_homes_permissions WHERE home = @home")
vRP._prepare("homes/buy_permissions","INSERT INTO vrp_homes_permissions (owner, user_id, garage, home, tax) VALUES (1, @user_id, 1, @home, @tax)")
vRP._prepare("homes/pay_iptu","UPDATE vrp_homes_permissions SET tax = @tax WHERE user_id = @user_id AND home = @home")
vRP._prepare("identity/get_number","SELECT * FROM vrp_user_identities WHERE phone = @phone")
vRP._prepare("identity/new_number","UPDATE vrp_user_identities SET phone = @phone WHERE user_id = @user_id")

function SendWebhookMessage(webhookUrl, message)
    PerformHttpRequest(webhookUrl, function(err, text, headers) end, 'POST', json.encode({content = message}), { ['Content-Type'] = 'application/json' })
end

local logenviaritem = "SEU LINK WEBHOOK LOG ENVIAR"

-----------------------------------------------------------------------------------------------------------------------------------------
-- REGISTERTIMERS
-----------------------------------------------------------------------------------------------------------------------------------------
local registerBlips = {}
local registerTimers = {}
Citizen.CreateThread(function()
	while true do
		for k,v in pairs(registerTimers) do
			if v[4] > 0 then
				v[4] = v[4] - 1
				if v[4] <= 0 then
					table.remove(registerTimers,k)
					vCLIENT.updateRegister(-1,registerTimers)
				end
			end
		end
		Citizen.Wait(1000)
	end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- BANDAGE
-----------------------------------------------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
	while true do
		for k,v in pairs(bandagem) do
			if v > 0 then
				bandagem[k] = v - 1
			end
		end
		Citizen.Wait(1000)
	end
end)



-----------------------------------------------------------------------------------------------------------------------------------------
-- SYRINGETIME
-----------------------------------------------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
	while true do
		for k,v in pairs(syringeTime) do
			if v > 0 then
				syringeTime[k] = v - 1
			end
		end
		Citizen.Wait(60000)
	end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- ACTIVE
-----------------------------------------------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
	while true do
		for k,v in pairs(active) do
			if v > 0 then
				active[k] = v - 1
			end
		end
		Citizen.Wait(1000)
	end
end)

uchests = {}
inventariosAbertos = {}
-----------------------------------------------------------------------------------------------------------------------------------------
-- MOCHILA
-----------------------------------------------------------------------------------------------------------------------------------------
function cRP.Mochila()
	local source = source
	local user_id = vRP.getUserId(source)
	if user_id then
		local inventory = {}
		local inv = vRP.getInventory(user_id)
		if inv then
			for k,v in pairs(inv) do
				if vRP.itemBodyList(k) then
					table.insert(inventory, { 
						amount = parseInt(v.amount), 
						name = vRP.itemNameList(k), 
						index = vRP.itemIndexList(k),  
						key = k,type = vRP.itemTypeList(k), 
						peso = vRP.getItemWeight(k), 
						desc = vRP.itemDescList(k),
						keybind = v.keybind or nil,
					})
				end
			end

			return inventory,vRP.getInventoryWeight(user_id),vRP.getInventoryMaxWeight(user_id)
		end
	end
end

function cRP.closeInvSync()
	local source = source
	local user_id = vRP.getUserId(source)
	if uchests[user_id] then 
		inventariosAbertos[uchests[user_id].chest] = nil
		if uchests[user_id].type == "car" then 
			vGARAGE.vehicleClientTrunk(-1,uchests[(user_id)].netid,true)
		end
		uchests[user_id] = nil
	end
end

function cRP.setKeybind(idname, key)
    local source = source
    local user_id = vRP.getUserId(source)
	local data = vRP.getUserDataTable(user_id)
	if data then
		if data.inventory[idname] then
			if cRP.removeKeybind(idname, false, nil) then
				data.inventory[idname].keybind = key

				vRP.setUserData(user_id, data)
				vRP.setUData(user_id, "vRP:datatable", json.encode(data))

				TriggerClientEvent("vrp_inventory:Update",source,"updateMochila")
			end
		end
	end
end

function cRP.removeKeybind(idname, up, slot)
    local source = source
    local user_id = vRP.getUserId(source)
    
	local data = vRP.getUserDataTable(user_id)
	if data then
		if data.inventory[idname] then
			data.inventory[idname] = { amount = data.inventory[idname].amount, slot = slot or data.inventory[idname].slot }

			vRP.setUserData(user_id, data)
            vRP.setUData(user_id, "vRP:datatable", json.encode(data))

			if up then
				TriggerClientEvent("vrp_inventory:Update",source,"updateMochila")
			end

			return true
		end
	end

	return true
end

function cRP.handleKeybind(key)
    local source = source
    local user_id = vRP.getUserId(source)
    
	local inve = cRP.Mochila()

	if inve then
		for i, v in ipairs(inve) do
            if v.keybind == key then
                cRP.useItem(v.key, v.type, 1)
            end
        end
	end
end

function cRP.portaMalas()
	local source = source
	local user_id = vRP.getUserId(source)
	if user_id then
		local vehicle,vnetid,placa,vname,lock,banned,trunk = vRPclient.vehList(source,3.0)
		-- print(vehicle,vnetid,placa,vname,lock,banned,trunk,vRP.getUserByRegistration(placa))
		if vehicle then	
			placa = placa:gsub("%s","")
			local vehicleName = vRP.vehicleName(vname)
			local placa_user_id = vRP.getUserByRegistration(placa)
			if placa_user_id then
				if lock == 1 then 
					local myvehicle = {}
					local mala = "chest:u"..parseInt(placa_user_id).."veh_"..vname
					if (not inventariosAbertos[mala] or inventariosAbertos[mala] == nil) or (uchests[user_id] and uchests[user_id].chest == mala) then 
						local data = vRP.getSData(mala)
						local sdata = json.decode(data) or {}
						if sdata then
							for k,v in pairs(sdata) do
								if vRP.itemBodyList(k) then
									table.insert(myvehicle,{ amount = parseInt(v.amount), name = vRP.itemNameList(k), key = k,index = vRP.itemIndexList(k), peso = vRP.getItemWeight(k), desc = vRP.itemDescList(k) })
								end
							end
						end
						vGARAGE.vehicleClientTrunk(-1,vnetid,false)
						inventariosAbertos[mala] = true

						uchests[(user_id)] = {chest = mala,type = "car",chestName = "CARRO "..vname,chest_max = parseInt(inventory.chestweight[vname]),netid = vnetid}
						return myvehicle,parseInt(vRP.computeItemsWeight(sdata)),uchests[user_id].chest_max, uchests[(user_id)].chestName
					end
				end
			end
		end
		
		local success,chestName = vCLIENT.getNearChest(source)
		if success then 
			if vRP.hasPermission(user_id,CHESTS[chestName].permissao) then 

				local chest = {}
				local mala = "chest:"..chestName
				if (not inventariosAbertos[mala] or inventariosAbertos[mala] == nil) or (uchests[user_id] and uchests[user_id].chest == mala) then 
					local data = vRP.getSData(mala)
					local sdata = json.decode(data) or {}

					if sdata then
						for k,v in pairs(sdata) do
							if vRP.itemBodyList(k) then
								table.insert(chest,{ amount = parseInt(v.amount), name = vRP.itemNameList(k), key = k,index = vRP.itemIndexList(k), peso = vRP.getItemWeight(k), desc = vRP.itemDescList(k) })
							end
						end
					end
					inventariosAbertos[mala] = true

					uchests[(user_id)] = {chest = mala,type = "chest",chestName = chestName,chest_max = CHESTS[chestName].weight}
					return chest,parseInt(vRP.computeItemsWeight(sdata)),CHESTS[chestName].weight, uchests[(user_id)].chestName
				end
			end
		end

		local sucesso,homeName,homeWeight = vHOMES.getNearHome(source)

		if sucesso then 
			local chest = {}
				local mala = "chest:"..homeName
				if (not inventariosAbertos[mala] or inventariosAbertos[mala] == nil) or (uchests[user_id] and uchests[user_id].chest == mala) then 
					local data = vRP.getSData(mala)
					local sdata = json.decode(data) or {}
					if sdata then
						for k,v in pairs(sdata) do
							if vRP.itemBodyList(k) then
								table.insert(chest,{ amount = parseInt(v.amount), name = vRP.itemNameList(k), key = k,index = vRP.itemIndexList(k), peso = vRP.getItemWeight(k), desc = vRP.itemDescList(k) })
							end
						end
					end
					inventariosAbertos[mala] = true

						--print(mala,"chest",homeName,homeWeight)
					uchests[(user_id)] = {chest = mala,type = "homes",chestName = homeName,chest_max = homeWeight}
					--print(chest,parseInt(vRP.computeItemsWeight(sdata)),homeWeight, uchests[(user_id)].homeName)
					return chest,parseInt(vRP.computeItemsWeight(sdata)),homeWeight, uchests[(user_id)].chestName
				end
		end

	end
	return false
end

function cRP.Identidade()
	local source = source
	local user_id = vRP.getUserId(source)
	if user_id then
		local cash = vRP.getMoney(user_id)
		local banco = vRP.getBankMoney(user_id)
		local identity = vRP.getUserIdentity(user_id)
		local multas = vRP.getUData(user_id,"vRP:multas")
		local mymultas = json.decode(multas) or 0
		local coins = vRP.getUData(user_id,"vRP:coins") 
		local paypal = vRP.getUData(user_id,"vRP:paypal")
		local mypaypal = json.decode(paypal) or 0
		if identity then
			return vRP.format(parseInt(cash)),vRP.format(parseInt(banco)),identity.name,identity.firstname,identity.user_id,identity.registration,identity.age,identity.phone,vRP.format(parseInt(mymultas)),vRP.format(parseInt(mypaypal)),vRP.format(parseInt(coins)),identity.foto
		end
	end
end


function cRP.checkJobs()
	local source = source
	local user_id = vRP.getUserId(source)
    local groupv = vRP.getUserGroupByType(user_id,TypeJob) or "Desempregado"
	local groupname = vRP.getGroupTitle(groupv)

	local groupvip = vRP.getUserGroupByType(user_id,TypeVip) or "FREE"
	local groupnamevip = vRP.getGroupTitle(groupvip)
	if groupname then
		return groupname,groupnamevip
	end
end

delayBau = {}
Citizen.CreateThread(function()
	while true do
		Citizen.Wait(1000)

		for k,v in pairs(active) do
			if type(v) == "number" and v > 0 then
				active[k] = v - 1
			end
		end
		for k,v in pairs(delayBau) do 
			if v> 0 then 
				delayBau[k] = v - 1 
			end 
		end
	end
end)

function cRP.storeItem(itemName,amount,vehname,webhook_bau)
	
	local source = source
	if itemName then
		local user_id = vRP.getUserId(source)
		local identity = vRP.getUserIdentity(user_id)
		if user_id and not delayBau[user_id] or delayBau[user_id] <= 0 then

			if string.match(itemName,"dinheirosujo") then
				if uchests[user_id].type == "car" and ALLOW_DIRTYMONEY_INCAR == false then 
					TriggerClientEvent("Notify",source,"importante","Não pode guardar este item em veículos.",8000)
					return
				end
			end

			local data = vRP.getSData(uchests[user_id].chest)
			local items = json.decode(data) or {}
			if items then
				local max_veh = uchests[user_id].chest_max or 50
				if parseInt(amount) > 0 then
					local new_weight = vRP.computeItemsWeight(items)+vRP.getItemWeight(itemName)*parseInt(amount)
					if new_weight <= parseInt(max_veh) then
						if user_id and not delayBau[user_id] or delayBau[user_id] <= 0 then
							delayBau[user_id] = 2
							if vRP.tryGetInventoryItem(user_id,itemName,parseInt(amount)) then
								if items[itemName] ~= nil then
									items[itemName].amount = items[itemName].amount + parseInt(amount)
								else
									items[itemName] = { amount = parseInt(amount) }
								end

								PerformHttpRequest(webhook_bau, function(err, text, headers) end, 'POST', json.encode({
									embeds = {
										{     ------------------------------------------------------------
											title = "GUARDOU NO BAU		\n⠀",
											thumbnail = {
												url = imagem
											}, 
											fields = {
												{ 
													name = "``Player``",
													value = "Nome: "..identity.name.." "..identity.firstname.."\nID: "..user_id.."\n"
												},
												{ 
													name = "``Item``",
													value = ""..vRP.format(parseInt(items[itemName].amount)).." "..vRP.itemNameList(itemName)..""
												},
												{ 
													name = "``Bau``",
													value = ""..uchests[user_id].chest..""
												}
											}, 
											footer = { 
												text = "Data e hora: " ..os.date("%d/%m/%Y | %H:%M:%S"),
												icon_url = "https://www.autoriafacil.com/wp-content/uploads/2019/01/icone-data-hora.png"
											},
											color = 3066993
										}
									}
								}), { ['Content-Type'] = 'application/json' })

								
							end
						end
					else
						TriggerClientEvent("Notify",source,"negado","<b>Porta-Malas</b> cheio.",8000)
					end
				else
					local inv = vRP.getInventory(user_id)
					for k,v in pairs(inv) do
						if itemName == k then
							local new_weight = vRP.computeItemsWeight(items)+vRP.getItemWeight(itemName)*parseInt(v.amount)
							if new_weight <= parseInt(max_veh) then
								if user_id and not delayBau[user_id] or delayBau[user_id] <= 0 then
									delayBau[user_id] = 2
									if vRP.tryGetInventoryItem(user_id,itemName,parseInt(v.amount)) then
										if items[itemName] ~= nil then
											items[itemName].amount = items[itemName].amount + parseInt(v.amount)
										else
											items[itemName] = { amount = parseInt(v.amount) }
										end
										PerformHttpRequest(webhook_bau, function(err, text, headers) end, 'POST', json.encode({
											embeds = {
												{     ------------------------------------------------------------
													title = "GUARDOU NO BAU		\n⠀",
													thumbnail = {
														url = imagem
													}, 
													fields = {
														{ 
															name = "``Player``",
															value = "Nome: "..identity.name.." "..identity.firstname.."\nID: "..user_id.."\n"
														},
														{ 
															name = "``Item``",
															value = ""..vRP.format(parseInt(items[itemName].amount)).." "..vRP.itemNameList(itemName)..""
														},
														{ 
															name = "``Bau``",
															value = ""..uchests[user_id].chest..""
														}
													}, 
													footer = { 
														text = "Data e hora: " ..os.date("%d/%m/%Y | %H:%M:%S"),
														icon_url = "https://www.autoriafacil.com/wp-content/uploads/2019/01/icone-data-hora.png"
													},
													color = 3066993
												}
											}
										}), { ['Content-Type'] = 'application/json' })
									
									end
								end

							else
								TriggerClientEvent("Notify",source,"negado","<b>Porta-Malas</b> cheio.",8000)
							end
						end
					end
				end
				vRP.setSData(uchests[user_id].chest,json.encode(items))
				TriggerClientEvent('Creative:UpdateTrunk',source,'updateMochila2')
			end
		end
	end
	return false
end
-----------------------------------------------------------------------------------------------------------------------------------------
-- TAKEITEM
-----------------------------------------------------------------------------------------------------------------------------------------
function cRP.takeItem(itemName,amount,webhook_bau)
	
	local source = source
	if itemName then
		local user_id = vRP.getUserId(source)
		local identity = vRP.getUserIdentity(user_id)
		if user_id and not delayBau[user_id] or delayBau[user_id] <= 0 then
			local data = vRP.getSData(uchests[user_id].chest)
			if uchests[user_id].type == "chest" and not vRP.hasPermission(user_id, CHESTS[uchests[user_id].chestName].permissao) then 
				TriggerClientEvent("Notify", source, "negado","Você não tem permissão para retirar itens.")
				TriggerClientEvent('Creative:UpdateTrunk',source,'updateMochila2')
				return 
			end
			local items = json.decode(data) or {}
			if items then
				if parseInt(amount) > 0 then
					if items[itemName] ~= nil and items[itemName].amount >= parseInt(amount) then
						if user_id and not delayBau[user_id] or delayBau[user_id] <= 0 then
							delayBau[user_id] = 2
							if vRP.getInventoryWeight(user_id)+vRP.getItemWeight(itemName)*parseInt(amount) <= vRP.getInventoryMaxWeight(user_id) then
							
								PerformHttpRequest(webhook_bau, function(err, text, headers) end, 'POST', json.encode({
									embeds = {
										{     ------------------------------------------------------------
											title = "PEGOU NO BAU		\n⠀",
											thumbnail = {
												url = imagem
											}, 
											fields = {
												{ 
													name = "``Player``",
													value = "Nome: "..identity.name.." "..identity.firstname.."\nID: "..user_id.."\n"
												},
												{ 
													name = "``Item``",
													value = ""..vRP.format(parseInt(items[itemName].amount)).." "..vRP.itemNameList(itemName)..""
												},
												{ 
													name = "``Bau``",
													value = ""..uchests[user_id].chest..""
												}
											}, 
											footer = { 
												text = "Data e hora: " ..os.date("%d/%m/%Y | %H:%M:%S"),
												icon_url = "https://www.autoriafacil.com/wp-content/uploads/2019/01/icone-data-hora.png"
											},
											color = 15158332
										}
									}
								}), { ['Content-Type'] = 'application/json' })
								vRP.giveInventoryItem(user_id,itemName,parseInt(amount))
								items[itemName].amount = items[itemName].amount - parseInt(amount)
								if items[itemName].amount <= 0 then
									items[itemName] = nil
								end
							else
								TriggerClientEvent("Notify",source,"negado","<b>Mochila</b> cheia.",8000)
							end
						end
					end
				else
					if items[itemName] ~= nil and items[itemName].amount >= parseInt(amount) then
						if user_id and not delayBau[user_id] or delayBau[user_id] <= 0 then
							delayBau[user_id] = 2
							if vRP.getInventoryWeight(user_id)+vRP.getItemWeight(itemName)*parseInt(items[itemName].amount) <= vRP.getInventoryMaxWeight(user_id) then
								vRP.giveInventoryItem(user_id,itemName,parseInt(items[itemName].amount))
								PerformHttpRequest(webhook_bau, function(err, text, headers) end, 'POST', json.encode({
									embeds = {
										{     ------------------------------------------------------------
											title = "PEGOU NO BAU		\n⠀",
											thumbnail = {
												url = imagem
											}, 
											fields = {
												{ 
													name = "``Player``",
													value = "Nome: "..identity.name.." "..identity.firstname.."\nID: "..user_id.."\n"
												},
												{ 
													name = "``Item``",
													value = ""..vRP.format(parseInt(items[itemName].amount)).." "..vRP.itemNameList(itemName)..""
												},
												{ 
													name = "``Bau``",
													value = ""..uchests[user_id].chest..""
												}
											}, 
											footer = { 
												text = "Data e hora: " ..os.date("%d/%m/%Y | %H:%M:%S"),
												icon_url = "https://www.autoriafacil.com/wp-content/uploads/2019/01/icone-data-hora.png"
											},
											color = 15158332
										}
									}
								}), { ['Content-Type'] = 'application/json' })
								items[itemName] = nil
							else
								TriggerClientEvent("Notify",source,"negado","<b>Mochila</b> cheia.",8000)
							end
						end
					end
				end
				TriggerClientEvent('Creative:UpdateTrunk',source,'updateMochila2')
				vRP.setSData(uchests[user_id].chest,json.encode(items))
			end
		end
	end
	return false
end
-----------------------------------------------------------------------------------------------------------------------------------------
-- SENDITEM
-----------------------------------------------------------------------------------------------------------------------------------------
function cRP.sendItem(itemName,amount)
	local source = source
	if itemName then
		local user_id = vRP.getUserId(source)
		local nplayer = vRPclient.getNearestPlayer(source,2)
		local nuser_id = vRP.getUserId(nplayer)
		local identity = vRP.getUserIdentity(user_id)
		local identityy = vRP.getUserIdentity(nuser_id)
		if nuser_id and vRP.itemIndexList(itemName) and itemName ~= "identidade" and itemName ~= "distintivo"  and parseInt(amount) <= vRP.getInventoryItemAmount(user_id,itemName) then
			if parseInt(amount) > 0 then
				if user_id and active[user_id] == 0 or not active[user_id] then
					active[user_id] = 2
					if vRP.getInventoryWeight(nuser_id) + vRP.getItemWeight(itemName) * amount <= vRP.getInventoryMaxWeight(nuser_id) then
						if vRP.tryGetInventoryItem(user_id,itemName,amount) then
							vRP.giveInventoryItem(nuser_id,itemName,amount)
							vRPclient._playAnim(source,true,{"mp_common","givetake1_a"},false)
							TriggerClientEvent("Notify",source,"sucesso","Enviou <b>"..vRP.format(parseInt(amount)).."x "..vRP.itemNameList(itemName).."</b>.",8000)
							TriggerClientEvent("Notify",nplayer,"sucesso","Recebeu <b>"..vRP.format(parseInt(amount)).."x "..vRP.itemNameList(itemName).."</b>.",8000)
			
							TriggerClientEvent("vrp_inventory:Update",source,"updateMochila")
							TriggerClientEvent("vrp_inventory:Update",nplayer,"updateMochila")

							PerformHttpRequest(log_enviar_item, function(err, text, headers) end, 'POST', json.encode({
								embeds = {
									{ 
										title = "REGISTRO DE ENVIO",
										thumbnail = {
											url = imagem
										}, 
										fields = {
											{ 
												name = "**QUEM ENVIOU:**", 
												value = " "..identity.name.." "..identity.firstname.." ["..user_id.."] "
											},
											{ 
												name = "**ENVIOU:**", 
												value = " "..amount.."x "..vRP.itemNameList(itemName).." "
											},
											{ 
												name = "**RECEBEU:**", 
												value = " "..identityy.name.." "..identityy.firstname.." ["..nuser_id.."] "
											}
										}, 
										footer = { 
											text = "Data e hora: " ..os.date("%d/%m/%Y | %H:%M:%S"),
											icon_url = "https://www.autoriafacil.com/wp-content/uploads/2019/01/icone-data-hora.png"
										},
										color = 15914080 
									}
								}
							}), { ['Content-Type'] = 'application/json' })
							return true
						end
					end
				end

			else
				local inv = vRP.getInventory(user_id)
				for k,v in pairs(inv) do
					if itemName == k then
						if user_id and active[user_id] == 0 or not active[user_id] then
							active[user_id] = 2
							if vRP.getInventoryWeight(nuser_id) + vRP.getItemWeight(itemName) * parseInt(v.amount) <= vRP.getInventoryMaxWeight(nuser_id) then
								if vRP.tryGetInventoryItem(user_id,itemName,parseInt(v.amount)) then
									vRP.giveInventoryItem(nuser_id,itemName,parseInt(v.amount))
									vRPclient._playAnim(source,true,{"mp_common","givetake1_a"},false)
									TriggerClientEvent("Notify",source,"sucesso","Enviou <b>"..vRP.format(parseInt(v.amount)).."x "..vRP.itemNameList(itemName).."</b>.",8000)
									TriggerClientEvent("Notify",nplayer,"sucesso","Recebeu <b>"..vRP.format(parseInt(v.amount)).."x "..vRP.itemNameList(itemName).."</b>.",8000)
									SendWebhookMessage(logenviaritem,"```prolog\n[ID]: "..user_id.." "..identity.name.." "..identity.firstname.." \n[ENVIOU]: "..amount.."x "..itemName.." "..os.date("\n[Data]: %d/%m/%Y [Hora]: %H:%M:%S").." \r```")
									TriggerClientEvent("vrp_inventory:Update",source,"updateMochila")
									TriggerClientEvent("vrp_inventory:Update",nplayer,"updateMochila")
									return true
								end
							end
						end
					end
				end
			end
		end
	end
	return false
end

-----------------------------------------------------------------------------------------------------------------------------------------
-- DROPITEM
-----------------------------------------------------------------------------------------------------------------------------------------
function cRP.dropItem(itemName,amount)
	local source = source
	if itemName ~= "identidade" and itemName ~= "distintivo" then
		local user_id = vRP.getUserId(source)
		local x,y,z = vRPclient.getPosition(source)
		local identity = vRP.getUserIdentity(user_id)
		if parseInt(amount) > 0 and vRP.tryGetInventoryItem(user_id,itemName,amount) then
			TriggerEvent("DropSystem:create",itemName,amount,x,y,z,3600)
			vRPclient._playAnim(source,true,{"pickup_object","pickup_low"},false)
			TriggerClientEvent("vrp_inventory:Update",source,"updateMochila")
			return true
		else
			local inv = vRP.getInventory(user_id)
			for k,v in pairs(inv) do
				if itemName == k then
					if vRP.tryGetInventoryItem(user_id,itemName,parseInt(v.amount)) then
						TriggerEvent("DropSystem:create",itemName,parseInt(v.amount),x,y,z,3600)
				
						vRPclient._playAnim(source,true,{"pickup_object","pickup_low"},false)
						
						TriggerClientEvent("vrp_inventory:Update",source,"updateMochila")
						PerformHttpRequest(log_drop_item, function(err, text, headers) end, 'POST', json.encode({
							embeds = {
								{ 
									title = "REGISTRO DE DROP",
									thumbnail = {
										url = imagem
									}, 
									fields = {
										{ 
											name = "**QUEM EQUIPOU:**", 
											value = " "..identity.name.." "..identity.firstname.." ["..user_id.."] "
										},
										{ 
											name = "**DROPOU:**", 
											value = " "..v.amount.."x "..vRP.itemNameList(itemName).." "
										}
									}, 
									footer = { 
										text = "Data e hora: " ..os.date("%d/%m/%Y | %H:%M:%S"),
										icon_url = "https://www.autoriafacil.com/wp-content/uploads/2019/01/icone-data-hora.png"
									},
									color = 15914080 
								}
							}
						}), { ['Content-Type'] = 'application/json' })
						return true
					end
				end
			end
		end
	end
	return false
end

local pick = {}
local blips = {}

-----------------------------------------------------------------------------------------------------------------------------------------
-- USEITEM
-----------------------------------------------------------------------------------------------------------------------------------------
function cRP.useItem(itemName,type,ramount)
	local source = source
	local user_id = vRP.getUserId(source)
	local source = source
	local data = vRP.getUserAptitudes(user_id)
	UseItemInventory(itemName,type,ramount,user_id,vGARAGE,vHOMES,vTASKBAR,vPLAYER,cRP)
end
-----------------------------------------------------------------------------------------------------------------------------------------
-- PLAYERLEAVE
-----------------------------------------------------------------------------------------------------------------------------------------
AddEventHandler("vRP:playerLeave",function(user_id,source)
	local source = source
	active[user_id] = nil
	bandagem[user_id] = nil
	amountUse[user_id] = nil
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- vrp_inventory:CANCEL
-----------------------------------------------------------------------------------------------------------------------------------------
RegisterServerEvent("vrp_inventory:Cancel")
AddEventHandler("vrp_inventory:Cancel",function()
	local source = source
	local user_id = vRP.getUserId(source)
	if user_id then
		if active[user_id] == nil then
			active[user_id] = 0
		end

		if active[user_id] > 0 then
			active[user_id] = -1
			TriggerClientEvent("progress",source,1500)

			SetTimeout(1000,function()
				vRPclient._removeObjects(source)
				vCLIENT.blockButtons(source,false)
				vGARAGE.updateHotwired(source,false)
			end)
		else
			vRPclient._removeObjects(source)
		end
	end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- CHECKRADIO
-----------------------------------------------------------------------------------------------------------------------------------------
function cRP.checkRadio()
	local source = source
	local user_id = vRP.getUserId(source)
	if user_id then
		if vRP.getInventoryItemAmount(user_id,"radio") < 1 then
			return true
		end
		return false
	end
end
-----------------------------------------------------------------------------------------------------------------------------------------
-- CHECKINVENTORY
-----------------------------------------------------------------------------------------------------------------------------------------
function cRP.checkInventory()
	local source = source
	local user_id = vRP.getUserId(source)
	if user_id then
		if active[user_id] == nil then
			active[user_id] = 0
		end

		if active[user_id] > 0 then
			return false
		end
		return true
	end
end

cRP.CheckPerm_bau = function(permissa)
	local source = source
	local user_id = vRP.getUserId(source)
	if vRP.hasPermission(user_id,permissa) then
		return true
	else
		return false
	end
end

function cRP.chestOpen()
	local source = source
	local user_id = vRP.getUserId(source)
	if user_id then
		local vehicle,vnetid,placa,vname,lock,banned,trunk = vRPclient.vehList(source,7)
		if vehicle then
			if lock == 1 then
				if banned then
					return
				end
				local placa_user_id = vRP.getUserByRegistration(placa)
				if placa_user_id then
					vCLIENT.vehicleClientTrunk(-1,vnetid,false)
					TriggerClientEvent("trunkchest:Open",source)
				end
			end
		end
	end
end


-- Data Bases -- 
vRP._prepare("etstore/insert", "INSERT INTO inventario(user_id, bolsos, bolsosocupados, img, banner) VALUES(@user_id, @bolsos, @bolsosocupados, @img, @banner)")
vRP._prepare("etstore/pegarinfos", "SELECT * FROM inventario WHERE user_id = @user_id")

vRP._prepare("etstore/colocarbolsos", "UPDATE inventario SET bolsos = bolsos + @bolsos WHERE user_id = @user_id")
vRP._prepare("etstore/updateperfil", "UPDATE inventario SET img = @img, banner = banner WHERE user_id = @user_id")
vRP._prepare("etstore/updateperfil2", "UPDATE inventario SET banner = @banner WHERE user_id = @user_id")

vRP._prepare("etstore/inventario", [[
    CREATE TABLE IF NOT EXISTS inventario (
        user_id INTEGER PRIMARY KEY,
        bolsos INTEGER,
        bolsosocupados INTEGER,
        img TEXT,
        banner TEXT
    )
]])


Citizen.CreateThread(function()
    vRP.execute("etstore/inventario")
end)

AddEventHandler("vRP:playerSpawn", function(user_id, source, first_spawn)
    local user_id = vRP.getUserId(source) -- Não precisa redeclarar 'source', já está disponível
    if user_id then
        local infos = vRP.query("etstore/pegarinfos", {user_id = parseInt(user_id)})

        if infos[1] == nil then
            vRP.query("etstore/insert", {
                user_id = parseInt(user_id),
                bolsos = 5, -- Valor exemplo, ajuste conforme necessário
                bolsosocupados = 0, -- Valor exemplo, ajuste conforme necessário
                img = "https://cdn.fivemetstore.com/etstore/logo-fundo.png",
                banner = "https://cdn.fivemetstore.com/etstore/logo-fundo.png" -- 
            })
        end
    end
end)

RegisterCommand('tabinv', function(source)
	local user_id = vRP.getUserId(source)
	print(user_id)
    if user_id then
		print('sim')
        local infos = vRP.query("etstore/pegarinfos", {user_id = parseInt(user_id)})

        if infos[1] == nil then
            vRP.query("etstore/insert", {
                user_id = parseInt(user_id),
                bolsos = 5, -- Valor exemplo, ajuste conforme necessário
                bolsosocupados = 0, -- Valor exemplo, ajuste conforme necessário
                img = "https://cdn.fivemetstore.com/etstore/logo-fundo.png",
                banner = "https://cdn.fivemetstore.com/etstore/logo-fundo.png" --
            })
        end
    end
	TriggerClientEvent('Notify', source, 'sucesso', 'Tabelas Criadas')
end)


-- Sistema de Imagens --

cRP.RetornarImagens = function()
    local source = source
    local user_id = vRP.getUserId(source)

    local infos = vRP.query("etstore/pegarinfos", {user_id = parseInt(user_id)})
    -- print(json.encode(infos))
    if infos and #infos > 0 then 
        -- Acessa o primeiro registro e então a propriedade img desse registro
        return infos[1].img
    else
        return nil
    end
end


cRP.updateperfil = function(imglink, bannerlink)
    local source = source
    local user_id = vRP.getUserId(source)

    -- Atualiza a imagem do perfil
    vRP.query("etstore/updateperfil", {
        user_id = parseInt(user_id),
        img = imglink,
    })

    -- Atualiza o banner do perfil
    vRP.query("etstore/updateperfil2", {
        user_id = parseInt(user_id),
        banner = bannerlink,
    })

    TriggerClientEvent("Notify", source, "sucesso", "Você atualizou as imagens na Identidade.")
    return true
end


RegisterCommand('item',function(source,args,rawCommand)
	local user_id = vRP.getUserId(source)
	if args[2] == nil then
		vRP.giveInventoryItem(user_id, args[1], 1)
	elseif args[1] and args[2] then
		vRP.giveInventoryItem(user_id, args[1], parseInt(args[2]))
	end
end)