----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------



function AddGamepass(player, gamepassId)
	--- Variables
	local playerId = player.UserId
	local playerStats = _L.Storage.Stats["u" .. playerId]
	local playerCache = cache["u" .. playerId]

	--- Sanity check
	if playerStats == nil then  
		return  
	end
	
	--- Create cache
	if cache["u" .. playerId] == nil then
		cache["u" .. playerId] = {}
		playerCache = cache["u" .. playerId]
	end

	--- Check if gamepass is already written
	if not _L.Functions.SearchArray(playerStats.Gamepasses, gamepassId) then
		
		--- Write gamepass to save!
		table.insert(playerStats.Gamepasses, gamepassId)
		
		--- Analytics
		pcall(function()
			_L.Analytics.Purchase("Gamepass", player, gamepassId)
		end)
	end
	
	--- Update cache
	playerCache["g" .. gamepassId] = true
end


function CheckPlayer(player)
	--- Variables
	local playerId = player.UserId
	local playerStats = _L.Storage.Stats["u" .. playerId]
	local playerCache = cache["u" .. playerId]
	
	--- Sanity check
	if playerStats == nil then  
		return  
	end
	
	--- Create cache
	if cache["u" .. playerId] == nil then
		cache["u" .. playerId] = {}
		playerCache = cache["u" .. playerId]
	end
	
	--- Iterate through all gamepasses to check if player owns them or not (bought on website)
	for _, gamepassInfo in pairs(_L.Directory.Gamepasses) do
		local gamepassId = gamepassInfo.ID
		local gamepassOwned = playerCache["g" .. gamepassId] or false
		
		--- Gamepass not owned already?
		if gamepassOwned == false then
			--- Check if player owns gamepass (new API)
			local playerOwnsGamepass = false
			pcall(function()  playerOwnsGamepass = _L.Services.MarketplaceService:UserOwnsGamePassAsync(playerId, gamepassId)  end)
			
			--- Player bought this gamepass and it's not added! ADD IT!
			if playerOwnsGamepass == true then
				AddGamepass(player, gamepassId)
			end
		end
	end
end


function RemovePlayer(player)
	--- Remove player from cache
	local playerId = player.UserId
	cache["u" .. playerId] = nil
end

