-- Function that other scripts can call to change a player's stats

function PlayerStatManager:ChangeStat(player, statName, value)
	local playerUserId = "Player_" .. player.UserId
	sessionData[playerUserId][statName] = value
end

function PlayerStatManager:ChangeStatInTycoonPurchases(player, statName, value)
	local playerUserId = "Player_" .. player.UserId
	sessionData[playerUserId]["TycoonPurchases"][statName] = value
	print("Saving------------------> ",statName)
end

function PlayerStatManager:IncrementStat(player, statName, value)
	local playerUserId = "Player_" .. player.UserId
	if typeof(sessionData[playerUserId][statName]) == "number" then
		sessionData[playerUserId][statName] = sessionData[playerUserId][statName] + value
	end
end


local function setupPlayerData(player)	
	local playerMoney = serverStorage:WaitForChild("PlayerMoney")
	local playerStats = playerMoney:FindFirstChild(player.Name)
	--Sometimes people have duplicate tycoon add e.g in core handler script
	--adds PlayerMoney to storage and number value with player name that holds the 
	--money value 
	if playerStats == nil then
		playerStats = Instance.new("NumberValue",playerMoney)
		playerStats.Name = player.Name
		local isOwner = Instance.new("ObjectValue",playerStats)
		isOwner.Name = "OwnsTycoon"
	end
	local playerUserId = "Player_" .. player.UserId
 
	local success,data = pcall(function()
		return playerData:GetAsync(playerUserId)
	end)
	
	if success then
		if data then
			print("----------Money: ---------> "..data["Money"])
			print("Show tycoon purchases---------------------")
			sessionData[playerUserId] = data
			for key,value in pairs(sessionData[playerUserId]["TycoonPurchases"]) do
				print(key,value)
			end
			print("End printing tycoon purchases-------------")
			
			local playerMoneyChild = playerMoney:FindFirstChild(player.Name)
			if playerMoneyChild then
				playerMoneyChild.Value = playerMoneyChild.Value + data["Money"]
			else print("------------playerMoneyChild is nil") end
			
		else
			print("setupPlayerData no data found for player ",player.Name)	
			wait()
			local money = 0
			local success,err = pcall(function()
				if player:IsInGroup(SaveSettings.giveCashToPlayersInGroup.groupId) then
					local plrCash = playerMoney:FindFirstChild(player.Name)
					if plrCash then
						plrCash.Value = plrCash.Value + SaveSettings.giveCashToPlayersInGroup.cashAmount
						money = plrCash.Value	
					end
				end
			end)
			
			if success == false then
				print(err)
			end
			
			sessionData[playerUserId] = {}
			sessionData[playerUserId]["Money"] = money
			sessionData[playerUserId]["RebirthCount"] = 0
			sessionData[playerUserId]["TycoonPurchases"] = {}
		end	
		playerStats.Changed:Connect(function(newValue) 
			print("playerStats.Changed ",newValue)
			sessionData[playerUserId]["Money"] = newValue
		end)
	else
		warn("Couldn't get data")
		print(data)
	end		
end
 