local DataStoreService = game:GetService("DataStoreService")
local DataStorage = DataStoreService:GetDataStore("FDSG#TY$HRFzz")
local DataKey = "@)(*IUROJFL"
local PlayerData = {}

game.Players.PlayerAdded:Connect(function(player)
	PlayerData[player.Name] = {}
	PlayerData[player.Name]["Stats"] = {}
	PlayerData[player.Name]["Stats"]["Level"] = 1
	PlayerData[player.Name]["Stats"]["Wins"] = 0
	PlayerData[player.Name]["Stats"]["XP"] = 0
	PlayerData[player.Name]["Stats"]["Money"] = 100
	
	-- Create Stats
	local Stats = Instance.new("Folder")
	Stats.Name = "Stats"
	Stats.Parent = player
	local Level = Instance.new("NumberValue")
	Level.Name = "Level"
	Level.Parent = Stats
	local Wins = Instance.new("NumberValue")
	Wins.Name = "Wins"
	Wins.Parent = Stats
	local XP = Instance.new("NumberValue")
	XP.Name = "XP"
	XP.Parent = Stats
	local Money = Instance.new("NumberValue")
	Money.Name = "Money"
	Money.Parent = Stats
	
	-- Check Data
	local Data = DataStorage:GetAsync(DataKey..player.userId)
	if Data then
		print("Loading Data")
		PlayerData[player.Name]["Stats"]["Level"] = Data[1]
		PlayerData[player.Name]["Stats"]["Wins"] = Data[2]
		PlayerData[player.Name]["Stats"]["XP"] = Data[3]
		PlayerData[player.Name]["Stats"]["Money"] = Data[4]
		Level.Value = Data[1]
		Wins.Value = Data[2]
		XP.Value = Data[3]
		Money.Value = Data[4]
	else
		print("Creating Data")
		Level.Value = PlayerData[player.Name]["Stats"]["Level"]
		Wins.Value = PlayerData[player.Name]["Stats"]["Wins"]
		XP.Value = PlayerData[player.Name]["Stats"]["XP"]
		Money.Value = PlayerData[player.Name]["Stats"]["Money"]
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
	local Stats = PlayerData[player.Name]["Stats"]
	local Lvl = Stats["Level"]
	local Wins = Stats["Wins"]
	local XP = Stats["XP"]
	local Money = Stats["Money"]
	local Tab = {Lvl,Wins,XP,Money}
	DataStorage:SetAsync(DataKey..player.userId,Tab)
end)