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



_L.Services.MarketplaceService.ProcessReceipt = function(receiptInfo)
	--- Reciept info
	local playerId = receiptInfo.PlayerId
	local productId, purchaseId = receiptInfo.ProductId, receiptInfo.PurchaseId
	local currencySpent, currencyType = receiptInfo.CurrencySpent, receiptInfo.CurrencyType
	local placeId = receiptInfo.PlaceIdWherePurchased
	
	--- Find the player instance from playerId (scans several times just in case)
	local function FindPlayer()
		local player = game.Players:GetPlayerByUserId(playerId)
		local attempts = 0
		while (not player) and attempts < 20 do
			wait(.2)
			player = game.Players:GetPlayerByUserId(playerId)
			attempts = attempts + 1
		end
		return player
	end
	
	--- Process product reciept
	local player = FindPlayer()
	if player then
		local productDir = Products.GetDir(productId)
		local playerStats = _L.Saving.Get(player)
		if productDir and playerStats then
			--- Reward the player for purchasing this product based on the callback!
			local pass = false
			local pass2 = pcall(function()
				pass = productDir.Callback(player, receiptInfo)
			end)
			
			--- Success!
			if pass and pass2 then
				pcall(function()
					_L.Network.Fire("Product Bought", player, receiptInfo)
					_L.Signal.Fire("Product Bought", player, receiptInfo)
					_L.Analytics.Purchase("product", player.Name, productId)
				end)
				return Enum.ProductPurchaseDecision.PurchaseGranted
			end
		end
	end
	
	--- Failed, for some reason. Attempt to let the player know (if they are in the server)
	pcall(function()
		if player then
			_L.Network.Fire("Product Failed", player, receiptInfo)
			_L.Print("[bold]HUGE ISSUE: Failed to process product purchase! (plr: " .. player.Name .. " | id: " .. productId .. ") [/bold]", true)
		else
			_L.Print("[bold]HUGE ISSUE: Failed to process product purchase, could not find player! (plr: " .. playerId .. " | id: " .. productId .. ") [/bold]", true)
		end
	end)
	
	--
	return Enum.ProductPurchaseDecision.NotProcessedYet
end

