local Data = game:GetService("DataStoreService"):GetDataStore("~~U@I")
local WinsOrderedData = game:GetService("DataStoreService"):GetOrderedDataStore("~~U@II")

function joined(player)
	local Stats = Instance.new("Folder")
	Stats.Name = player.Name
	local Wins = Instance.new("NumberValue")
	Wins.Name = "Wins"
	local Cash = Instance.new("NumberValue")
	Cash.Name = "Cash"
	Wins.Parent = Stats
	Cash.Parent = Stats
	Wins.Value = 0
	Cash.Value = 0
	Stats.Parent = game:GetService("ReplicatedStorage").Decal
	
	local pd = Data:GetAsync('~~~'..player.userId)
	if pd then
		Wins.Value = pd[1]
		Cash.Value = pd[2]
	end
	local Ls = Instance.new("Folder")
	Ls.Name = "leaderstats"
	local W = Instance.new("NumberValue")
	W.Name = 'Wins'
	W.Parent = Ls
	W.Value = Wins.Value
	local C = Instance.new("NumberValue")
	C.Name = "Cash"
	C.Value = Cash.Value
	C.Parent = Ls
	Ls.Parent = player
	Wins.Changed:Connect(function()
		W.Value = Wins.Value
	end)
	Cash.Changed:Connect(function()
		C.Value = Cash.Value
	end)
	W.Changed:Connect(function()
		W.Value = Wins.Value
	end)
	C.Changed:Connect(function()
		C.Value = Cash.Value
	end)
-- ORDERED DATA STORE HERE V
	local isAscending = false
    local pageSize = 10
    local pages = WinsOrderedData:GetSortedAsync(isAscending, pageSize)
    local topTen = pages:GetCurrentPage()
	for i,Data in ipairs(topTen) do
		print(Data.Key.." Is Number "..i.." With "..Data.Wins.." Wins!")
	end
end

function leave(player)
	local Stats = game:GetService("ReplicatedStorage").Decal:FindFirstChild(player.Name)
	local Wins = Stats.Wins
	local Cash = Stats.Cash
	local Table = {Wins.Value,Cash.Value}
	Data:SetAsync("~~~"..player.userId,Table)
	WinsOrderedData:SetAsync("Wins",{Key = player.userId,Win = Wins.Value})
	
end

game.Players.PlayerAdded:Connect(joined)
game.Players.PlayerRemoving:Connect(leave)