-- init

game.ReplicatedStorage.RE.marketPlace.OnServerEvent:Connect(function(player, name)
	spawn(function()
		local product, class = getAsset(name)
		if not product then
			print("Not product //"..name)
			return
		end
		
		local data = Datastore:GetData(player)
		
		local t = MarketplaceService:UserOwnsGamePassAsync(player.UserId,product.Id)

		if data and table.find(data.Gamepasses or {}, product.Id) then
			return onProductPurchased(player, product.Id) -- already owned
		end
		
		if t then
			return onProductPurchased(player, product.Id) 
		end
		game.ReplicatedStorage.RE.GamepassNotification:FireClient(player)
		if class == "Passes" then
			MarketplaceService:PromptGamePassPurchase(player, product.Id)
		elseif class == "Products" then
			MarketplaceService:PromptProductPurchase(player, product.Id)
		end
	end)
end)



game.Players.PlayerAdded:Connect(function(player)
	local data

	while not Datastore do
		Datastore = shared.Datastore
		wait()
	end

	while not data do
		if not player.Parent then 
			return
		end

		data = Datastore:GetData(player)
		wait(1)
	end

	local gamepasses = data.Gamepasses or {}
	for i, module in pairs(script.Passes:GetChildren()) do
		local pass = getAsset(module.Name)
		local id = pass.Id

		local found = table.find(gamepasses, id)
		if found or MarketplaceService:UserOwnsGamePassAsync(player.UserId, id) then
			if not found then
				table.insert(data.Gamepasses, id)
			end
			if pass.onJoined then
				pass.onJoined(player)
			end

			game.ReplicatedStorage.RE.gamepassUpdate:FireClient(player, getNameFromID(id))
		end
	end
end)
