local meta = FindMetaTable("Player")

function meta:PS_GetItems()
	return PS.LocalData
end

function meta:PS_HasItem(item_id)
	local items = PS.LocalData
	if !items then return false end
	return items[item_id] and true or false
end

function meta:PS_HasItemEquipped(item_id)
	if !self:PS_HasItem(item_id) then return false end
	return PS.LocalData[item_id].Equipped or false
end

function meta:PS_BuyItem(item_id)
	if self:PS_HasItem(item_id) then return false end
	if !self:PS_HasPoints(PS.Config.CalculateBuyPrice(self, PS.Items[item_id])) then return false end
	net.Start("PS_BuyItem")
		net.WriteEntity(PS.CurrentNPC)
		net.WriteString(item_id)
	net.SendToServer()
	return true
end

function meta:PS_SellItem(item_id)
	if !self:PS_HasItem(item_id) then return false end
	net.Start("PS_SellItem")
		net.WriteEntity(PS.CurrentNPC)
		net.WriteString(item_id)
	net.SendToServer()
	return true
end

function meta:PS_EquipItem(item_id)
	if !self:PS_HasItem(item_id) then return false end
	net.Start("PS_EquipItem")
		net.WriteEntity(PS.CurrentNPC)
		net.WriteString(item_id)
	net.SendToServer()
	return true
end

function meta:PS_HolsterItem(item_id)
	if !self:PS_HasItem(item_id) then return false end
	net.Start("PS_HolsterItem")
		net.WriteEntity(PS.CurrentNPC)
		net.WriteString(item_id)
	net.SendToServer()
	return true
end

function meta:PS_GetPoints()
	return self:getDarkRPVar("money") or 0
end

function meta:PS_HasPoints(points)
	return self:canAfford(points)
end

local function CleanupOldModels()
	for ply, items in pairs(PS.ClientsideModels) do
		if !IsValid(ply) then
			for item_id, model in pairs(items or {}) do
				if IsValid(model) then
					model:Remove()
				end
			end
			PS.ClientsideModels[ply] = nil
			continue
		end
	end
end

function meta:PS_AddClientsideModel(item_id)
	if !PS.Items[item_id] then return false end
	CleanupOldModels()
	PS.ClientsideModels[self] = PS.ClientsideModels[self] or {}
	local old_model = PS.ClientsideModels[self][item_id]
	if IsValid(old_model) then
		old_model:Remove()
	end
	local ITEM = PS.Items[item_id]
	local mdl = ClientsideModel(ITEM.Model, ITEM.RenderGroup or RENDERGROUP_OPAQUE)
	if !IsValid(mdl) then return false end
	mdl:SetNoDraw(true)
	PS.ClientsideModels[self][item_id] = mdl
	return true
end

function meta:PS_RemoveClientsideModel(item_id)
	if !PS.Items[item_id] then return false end
	local cl_models = PS.ClientsideModels[self]
	if !cl_models then return false end
	local old_model = cl_models[item_id]
	if !old_model then return false end
	if IsValid(old_model) then
		old_model:Remove()
	end
	PS.ClientsideModels[self][item_id] = nil
	return true
end

function meta:PS_RemoveAllClientsideModels()
	local cl_models = PS.ClientsideModels[self]
	if !cl_models then return false end
	for _, model in pairs(cl_models) do
		if IsValid(model) then
			model:Remove()
		end
	end
	PS.ClientsideModels[self] = nil
	return true
end