local PLUGIN = PLUGIN

PLUGIN.name = "Inventory Group Limits"
PLUGIN.author = "Scripty"
PLUGIN.description = "Adjusts character inventory size based on player user group via types."

-- Регистрируем типы инвентарей (Shared)
ix.inventory.Register("player_user", 8, 4)      -- 32 слота
ix.inventory.Register("player_prem", 8, 6)      -- 48 слотов
ix.inventory.Register("player_sponsor", 8, 8)   -- 64 слота
ix.inventory.Register("player_admin", 8, 8)     -- 64 слота

local groupToType = {
	["user"] = "player_user",
	["prem"] = "player_prem",
	["premium"] = "player_prem",
	["sponsor"] = "player_sponsor",
	["superadmin"] = "player_admin",
	["admin"] = "player_admin"
}

function PLUGIN:GetTargetType(client)
	if (!IsValid(client)) then return "player_user" end
	local group = client:GetUserGroup()
	local t = groupToType[group] or "player_user"
	return t
end

if (SERVER) then
	function PLUGIN:UpdatePlayerInventorySize(client)
		if (!IsValid(client)) then return end
		local character = client:GetCharacter()
		if (!character) then return end
		
		local inventory = character:GetInventory()
		
		if (!inventory or isnumber(inventory)) then
			-- Пытаемся еще раз через небольшой промежуток времени
			timer.Simple(2, function()
				if (IsValid(client)) then
					self:UpdatePlayerInventorySize(client)
				end
			end)
			return
		end

		local targetType = self:GetTargetType(client)
		local typeData = ix.item.inventoryTypes[targetType]
		if (!typeData) then return end

		-- Если тип уже совпадает, ничего не делаем
		if (inventory.vars and inventory.vars.isBag == targetType) then
			inventory:SetSize(typeData.w, typeData.h) -- На всякий случай обновляем размер в памяти
			return
		end

		-- Обновляем в БД
		local updateQuery = mysql:Update("ix_inventories")
			updateQuery:Update("inventory_type", targetType)
			updateQuery:Where("inventory_id", inventory:GetID())
		updateQuery:Execute()

		-- Обновляем в памяти
		inventory.vars.isBag = targetType
		inventory:SetSize(typeData.w, typeData.h)
		inventory:Sync(client)
		
		print(string.format("[Inventory] Обновлен размер для %s: %dx%d (%s)", 
			client:Name(), typeData.w, typeData.h, targetType))
	end

	function PLUGIN:PlayerLoadedCharacter(client, character)
		timer.Simple(2, function()
			if (IsValid(client)) then
				self:UpdatePlayerInventorySize(client)
			end
		end)
	end

	hook.Add("SAM.ChangedRank", "ixInventoryUpdateOnRank", function(client, old, new)
		timer.Simple(1, function()
			if (IsValid(client)) then
				PLUGIN:UpdatePlayerInventorySize(client)
			end
		end)
	end)

	ix.command.Add("InvUpdate", {
		description = "Обновить размер инвентаря согласно группе.",
		OnRun = function(self, client)
			PLUGIN:UpdatePlayerInventorySize(client)
			return "Попытка обновления инвентаря..."
		end
	})
end
