﻿     1→-- Player data of the ornament game (economy phase 1), saved in a DataStore. The server is the only writer.
     2→-- Mirrored for the UI as player attributes:
     3→--   Shards, Level, XP, XPNeed, Booster_<id>, Pity_<rarity>, Upg_<id> (upgrade levels), ShardCap,
     4→--   ShardRegenAt (unix time of the next free shard, 0 = stock full), DataLoaded
     5→-- Owned ornaments: player.OrnamentInventory/<uid> (Configuration; attributes Toy, Rarity, Variant, Order, Created,
     6→-- OnTree = slot number while the toy hangs on the player's Christmas tree; such toys are locked for the
     7→-- shredder / fusion / trading / market until they are taken off)
     8→-- If loading fails the player gets defaults for this session and NOTHING is saved (an outage can never wipe data).
     9→-- Session lock: the save holds Lock = { Job = JobId, Time }. A server only loads a profile whose lock is free or
    10→-- stale (no heartbeat for LOCK_STALE s) and only writes while it owns the lock -> no duplication across servers
    11→-- (required for trading). Autosave refreshes the lock, leaving releases it.
    12→local DataStoreService = game:GetService("DataStoreService")
    13→local HttpService = game:GetService("HttpService")
    14→local ReplicatedStorage = game:GetService("ReplicatedStorage")
    15→
    16→local Config = require(ReplicatedStorage:WaitForChild("OrnamentMachine"):WaitForChild("Config"))
    17→
    18→local PlayerData = {}
    19→local STORE_NAME = "OrnamentPlayerData_v1"
    20→local VERSION = 3          -- 3: 250 new toys in 5 tiers -> old toys / listings / collection / pity are wiped
    21→local JOB = (game.JobId ~= "" and game.JobId) or ("studio-" .. HttpService:GenerateGUID(false))
    22→local LOCK_STALE = 300
    23→local store
    24→pcall(function() store = DataStoreService:GetDataStore(STORE_NAME) end)
    25→
    26→local profiles = {}   -- [Player] = { data = table, canSave = bool, dirty = bool, released = bool }
    27→local inflight = 0    -- saves running right now (BindToClose waits for them)
    28→
    29→local function keyOf(player) return "u_" .. player.UserId end
    30→
    31→local function defaults()
    32→	return {
    33→		Version = VERSION,
    34→		Shards = Config.STARTER.Shards,
    35→		Level = 1, XP = 0,
    36→		Boosters = table.clone(Config.STARTER.Boosters),
    37→		Ornaments = {}, NextId = 1,
    38→		Pity = {}, Discovered = {}, Upgrades = {},
    39→		Listings = {},      -- [listingId] = { Item = {...}, Price, Expires }  (toys in market escrow)
    40→		Decor = {},         -- [shopId] = true (bought, in the inventory) | { X, Z, R } (placed on the plot)
    41→		Crafts = {},        -- [craftId] = number of EXTRA crafted items in the inventory (the first one lives in Decor)
    42→		Receipts = {},      -- [purchaseId] = os.time()  (Robux purchases already granted, newest ~100)
    43→		RegenAt = os.time(),
    44→		Stats = { Generated = 0, Recycled = 0 },
    45→		TutorialDone = false,   -- the first-time tutorial (TutorialGuide) was finished or skipped
    46→		Promos = {},        -- [CODE] = os.time() of redeeming (each promo code once per player)
    47→		VipGift = false,    -- VIP given by a promo code (permanent, like the game pass)
    48→		-- player settings (Settings window): volumes 0..1, background music on/off, interface language
    49→		-- ("auto" = Roblox auto-translation to the device language, "en", "ru")
    50→		Settings = { Master = 1, Music = 1, Effects = 1, UI = 1, MusicOn = true, Lang = "auto" },
    51→	}
    52→end
    53→
    54→local SETTING_VOLUMES = { "Master", "Music", "Effects", "UI" }
    55→local SETTING_LANGS = { auto = true, en = true, ru = true }
    56→-- settings attributes: Set_Master / Set_Music / Set_Effects / Set_UI (0..1), Set_MusicOn, Set_Lang.
    57→-- Published only on load and on change (not on every touch), so they never jump while the player drags a slider.
    58→local function publishSettings(player, st)
    59→	for _, k in SETTING_VOLUMES do player:SetAttribute("Set_" .. k, st[k]) end
    60→	player:SetAttribute("Set_MusicOn", st.MusicOn)
    61→	player:SetAttribute("Set_Lang", st.Lang)
    62→end
    63→local function cleanSettings(raw)
    64→	local def = { Master = 1, Music = 1, Effects = 1, UI = 1, MusicOn = true, Lang = "auto" }
    65→	if type(raw) ~= "table" then return def end
    66→	for _, k in SETTING_VOLUMES do
    67→		local v = tonumber(raw[k])
    68→		if v and v == v then def[k] = math.clamp(math.floor(v * 100 + 0.5) / 100, 0, 1) end
    69→	end
    70→	if type(raw.MusicOn) == "boolean" then def.MusicOn = raw.MusicOn end
    71→	if type(raw.Lang) == "string" and SETTING_LANGS[raw.Lang] then def.Lang = raw.Lang end
    72→	return def
    73→end
    74→
    75→-- fills missing fields of older saves (version 1 had only Shards / Boosters / Ornaments)
    76→local function migrate(d)
    77→	if (tonumber(d.Version) or 1) < 3 then
    78→		d.Ornaments, d.Listings, d.Discovered, d.Pity = {}, {}, {}, {}
    79→	end
    80→	-- saves from before the tutorial existed: players who already generated something do not get it
    81→	if d.TutorialDone == nil then
    82→		d.TutorialDone = type(d.Stats) == "table" and (tonumber(d.Stats.Generated) or 0) > 0
    83→	end
    84→	local def = defaults()
    85→	for k, v in def do
    86→		if d[k] == nil then d[k] = v end
    87→	end
    88→	for old, new in Config.BOOSTER_MIGRATE do
    89→		if d.Boosters[old] then
    90→			d.Boosters[new] = (d.Boosters[new] or 0) + d.Boosters[old]
    91→			d.Boosters[old] = nil
    92→		end
    93→	end
    94→	d.Shards = math.max(0, math.floor(tonumber(d.Shards) or 0))
    95→	if type(d.Crafts) ~= "table" then d.Crafts = {} end
    96→	-- TEST top-up: ONCE per profile (it used to run on every load, so any balance below the minimum came back
    97→	-- as the minimum after rejoining and looked like "shards are not saved")
    98→	if Config.TEST_MIN_SHARDS and not d.TestTopUp then
    99→		d.Shards = math.max(d.Shards, Config.TEST_MIN_SHARDS)
   100→		d.TestTopUp = true
   101→	end
   102→	d.Coins, d.Sparks = nil, nil     -- removed: shards are the only resource
   103→	d.Level = math.clamp(math.floor(tonumber(d.Level) or 1), 1, Config.MAX_LEVEL)
   104→	d.XP = math.max(0, math.floor(tonumber(d.XP) or 0))
   105→	d.NextId = math.max(1, math.floor(tonumber(d.NextId) or 1))
   106→	d.Settings = cleanSettings(d.Settings)
   107→	d.Version = VERSION
   108→	return d
   109→end
   110→
   111→local function retry(fn)
   112→	for attempt = 1, 4 do
   113→		local ok, result = pcall(fn)
   114→		if ok then return true, result end
   115→		warn("[OrnamentData] attempt " .. attempt .. " failed: " .. tostring(result))
   116→		task.wait(attempt)
   117→	end
   118→	return false
   119→end
   120→
   121→local function inventoryFolder(player)
   122→	local f = player:FindFirstChild("OrnamentInventory")
   123→	if not f then
   124→		f = Instance.new("Folder")
   125→		f.Name = "OrnamentInventory"
   126→		f.Parent = player
   127→	end
   128→	return f
   129→end
   130→
   131→local function mirrorOrnament(player, uid, item)
   132→	local c = Instance.new("Configuration")
   133→	c.Name = uid
   134→	c:SetAttribute("Toy", item.Toy)
   135→	c:SetAttribute("Rarity", item.Rarity)
   136→	c:SetAttribute("Variant", item.Variant)
   137→	c:SetAttribute("Order", tonumber(uid) or 0)
   138→	c:SetAttribute("Created", item.T or 0)
   139→	c:SetAttribute("OnTree", item.OnTree)
   140→	c:SetAttribute("Cost", item.Cost)
   141→	c.Parent = inventoryFolder(player)
   142→end
   143→
   144→-- tier attributes: MaxTier (highest tier the generator may use), TierFound_<n> (different toys of tier n found),
   145→-- TierToys_<n> (one char per toy of tier n in Config.ToysByTier order: char(48 + mask), mask bit (k-1) = rarity
   146→-- Config.RARITIES[k] found; "0" = never dropped). Recomputed only when the level or the collection changed.
   147→local function publishTiers(player, p)
   148→	local d = p.data
   149→	if not p.tierStale and p.tierLevel == d.Level then return end
   150→	p.tierStale, p.tierLevel = false, d.Level
   151→	for i in Config.TIERS do player:SetAttribute("TierFound_" .. i, Config.TierFound(d.Discovered, i)) end
   152→	for i in Config.TIERS do
   153→		local chars = {}
   154→		for k, toy in Config.ToysByTier[i] or {} do
   155→			local mask = 0
   156→			for ri, r in Config.RARITIES do
   157→				if d.Discovered[toy.Id .. "|" .. r.Id] then mask += 2 ^ (ri - 1) end
   158→			end
   159→			chars[k] = string.char(48 + mask)
   160→		end
   161→		player:SetAttribute("TierToys_" .. i, table.concat(chars))
   162→	end
   163→	player:SetAttribute("MaxTier", Config.MaxTier(d.Level, d.Discovered))
   164→end
   165→
   166→local function publish(player, p)
   167→	local d = p.data
   168→	player:SetAttribute("Shards", d.Shards)
   169→	player:SetAttribute("Level", d.Level)
   170→	player:SetAttribute("XP", d.XP)
   171→	player:SetAttribute("XPNeed", d.Level >= Config.MAX_LEVEL and 0 or Config.XpToNext(d.Level))
   172→	for id in Config.BOOSTERS do player:SetAttribute("Booster_" .. id, d.Boosters[id] or 0) end
   173→	for _, pity in Config.PITY do player:SetAttribute("Pity_" .. pity.Rarity, d.Pity[pity.Rarity] or 0) end
   174→	for _, u in Config.UPGRADES do player:SetAttribute("Upg_" .. u.Id, d.Upgrades[u.Id] or 0) end
   175→	for _, s in Config.SHOP do
   176→		local v = d.Decor[s.Id]
   177→		player:SetAttribute("Decor_" .. s.Id, v ~= nil and v ~= false)       -- owned
   178→		player:SetAttribute("Placed_" .. s.Id, type(v) == "table")           -- standing on the plot
   179→	end
   180→	-- Craft_<id> = crafted items NOT on the plot (can be placed or sold)
   181→	for _, c in Config.CRAFTS do
   182→		player:SetAttribute("Craft_" .. c.Id, (d.Crafts[c.Id] or 0) + (d.Decor[c.Id] == true and 1 or 0))
   183→	end
   184→	local cap, every = Config.RegenCap(d.Upgrades.Regen), Config.RegenSeconds(d.Upgrades.Regen)
   185→	player:SetAttribute("TutorialDone", d.TutorialDone == true)
   186→	player:SetAttribute("ShardCap", cap)
   187→	player:SetAttribute("ShardRegenAt", d.Shards >= cap and 0 or math.ceil(d.RegenAt + every))
   188→	publishTiers(player, p)
   189→end
   190→
   191→local function touch(player, p)
   192→	p.dirty = true
   193→	publish(player, p)
   194→end
   195→
   196→---------------------------------------------------------------- lifecycle
   197→function PlayerData.Load(player)
   198→	local p = { canSave = false, dirty = false, tierStale = true }
   199→	local ok, saved, locked = false, nil, false
   200→	if store then
   201→		for attempt = 1, 6 do
   202→			local callOk, result = pcall(function()
   203→				local outcome
   204→				store:UpdateAsync(keyOf(player), function(old)
   205→					old = type(old) == "table" and old or nil
   206→					if old and type(old.Lock) == "table" and old.Lock.Job ~= JOB and os.time() - (tonumber(old.Lock.Time) or 0) < LOCK_STALE then
   207→						outcome = "locked"
   208→						return nil                      -- cancel: another server still owns this profile
   209→					end
   210→					local d = old or defaults()
   211→					d.Lock = { Job = JOB, Time = os.time() }
   212→					outcome = d
   213→					return d
   214→				end)
   215→				return outcome
   216→			end)
   217→			if callOk and result ~= "locked" then
   218→				ok, saved, locked = true, result, false
   219→				break
   220→			end
   221→			locked = callOk and result == "locked"
   222→			if not callOk then warn("[OrnamentData] load attempt " .. attempt .. " failed: " .. tostring(result)) end
   223→			task.wait(locked and 5 or attempt)
   224→			if not player.Parent then return end
   225→		end
   226→	end
   227→	if locked then
   228→		player:Kick("Your data is still being saved on another server. Please rejoin in a minute.")
   229→		return
   230→	end
   231→	if ok then
   232→		p.data = migrate(type(saved) == "table" and saved or defaults())
   233→		p.canSave = true
   234→	else
   235→		p.data = defaults()
   236→		warn("[OrnamentData] could not load data for " .. player.Name .. "; this session will NOT be saved")
   237→	end
   238→	if not player.Parent then return end
   239→	profiles[player] = p
   240→	inventoryFolder(player)
   241→	for uid, item in p.data.Ornaments do
   242→		if type(item) == "table" and Config.ToyById[item.Toy] and Config.RarityById[item.Rarity] then
   243→			mirrorOrnament(player, uid, item)
   244→		else
   245→			p.data.Ornaments[uid] = nil
   246→		end
   247→	end
   248→	PlayerData.TickRegen(player)   -- shards regenerated while offline
   249→	publish(player, p)
   250→	publishSettings(player, p.data.Settings)
   251→	player:SetAttribute("DataLoaded", true)
   252→end
   253→
   254→function PlayerData.Get(player)
   255→	local p = profiles[player]
   256→	return p and p.data
   257→end
   258→
   259→---------------------------------------------------------------- currencies
   260→local function addField(player, field, amount)
   261→	local p = profiles[player]
   262→	if not p then return false end
   263→	p.data[field] = math.max(0, p.data[field] + amount)
   264→	touch(player, p)
   265→	return true
   266→end
   267→function PlayerData.AddShards(player, amount)
   268→	local p = profiles[player]
   269→	local cap = p and Config.RegenCap(p.data.Upgrades.Regen)
   270→	if p and amount < 0 and p.data.Shards >= cap and p.data.Shards + amount < cap then
   271→		p.data.RegenAt = os.time()          -- regeneration restarts when the stock drops below the cap
   272→	end
   273→	return addField(player, "Shards", amount)
   274→end
   275→
   276→function PlayerData.AddBooster(player, id, amount)
   277→	local p = profiles[player]
   278→	if not p or not Config.BOOSTERS[id] then return false end
   279→	p.data.Boosters[id] = math.max(0, (p.data.Boosters[id] or 0) + amount)
   280→	touch(player, p)
   281→	return true
   282→end
   283→
   284→-- free shard regeneration (call periodically): +1 per REGEN_SECONDS while below REGEN_CAP
   285→function PlayerData.TickRegen(player)
   286→	local p = profiles[player]
   287→	if not p then return end
   288→	local d = p.data
   289→	local now = os.time()
   290→	local cap, every = Config.RegenCap(d.Upgrades.Regen), Config.RegenSeconds(d.Upgrades.Regen)
   291→	if d.Shards >= cap then
   292→		d.RegenAt = now
   293→		return
   294→	end
   295→	local ticks = math.floor((now - d.RegenAt) / every)
   296→	if ticks > 0 then
   297→		local add = math.min(ticks, cap - d.Shards)
   298→		d.Shards += add
   299→		d.RegenAt += ticks * every
   300→		touch(player, p)
   301→	end
   302→end
   303→
   304→---------------------------------------------------------------- upgrades
   305→function PlayerData.UpgradeLevel(player, id)
   306→	local p = profiles[player]
   307→	return p and (p.data.Upgrades[id] or 0) or 0
   308→end
   309→
   310→-- pays the next level of an upgrade; returns new level or nil, message
   311→function PlayerData.BuyUpgrade(player, id)
   312→	local p = profiles[player]
   313→	if not p or not Config.UpgradeById[id] then return nil, "Unknown upgrade" end
   314→	local d = p.data
   315→	local level = d.Upgrades[id] or 0
   316→	local cost = Config.UpgradeCost(id, level)
   317→	if not cost then return nil, "Already at max level" end
   318→	if d.Shards < cost then return nil, "Not enough shards: you need " .. cost end
   319→	PlayerData.AddShards(player, -cost)
   320→	d.Upgrades[id] = level + 1
   321→	touch(player, p)
   322→	return level + 1
   323→end
   324→
   325→---------------------------------------------------------------- level / xp
   326→-- adds XP; returns the list of levels reached (the caller hands out the rewards)
   327→function PlayerData.AddXP(player, amount)
   328→	local p = profiles[player]
   329→	if not p then return {} end
   330→	local d = p.data
   331→	local reached = {}
   332→	if d.Level >= Config.MAX_LEVEL then return reached end
   333→	if amount > 0 and player:GetAttribute("VIP") == true then amount = math.floor(amount * Config.VIP.XP + 0.5) end   -- VIP pass
   334→	d.XP += amount
   335→	while d.Level < Config.MAX_LEVEL and d.XP >= Config.XpToNext(d.Level) do
   336→		d.XP -= Config.XpToNext(d.Level)
   337→		d.Level += 1
   338→		table.insert(reached, d.Level)
   339→	end
   340→	if d.Level >= Config.MAX_LEVEL then d.XP = 0 end
   341→	touch(player, p)
   342→	return reached
   343→end
   344→
   345→---------------------------------------------------------------- pity / collection
   346→function PlayerData.SetPity(player, rarityId, value)
   347→	local p = profiles[player]
   348→	if not p then return end
   349→	p.data.Pity[rarityId] = value
   350→	touch(player, p)
   351→end
   352→
   353→-- marks "Toy|Rarity" as collected; true the first time
   354→function PlayerData.Discover(player, toyId, rarityId)
   355→	local p = profiles[player]
   356→	if not p then return false end
   357→	local key = toyId .. "|" .. rarityId
   358→	if p.data.Discovered[key] then return false end
   359→	p.data.Discovered[key] = true
   360→	p.tierStale = true
   361→	touch(player, p)
   362→	return true
   363→end
   364→
   365→function PlayerData.CountStat(player, stat, amount)
   366→	local p = profiles[player]
   367→	if not p then return end
   368→	p.data.Stats[stat] = (p.data.Stats[stat] or 0) + amount
   369→	p.dirty = true
   370→end
   371→
   372→---------------------------------------------------------------- ornaments
   373→function PlayerData.OrnamentCount(player)
   374→	local p = profiles[player]
   375→	if not p then return 0 end
   376→	local n = 0
   377→	for _ in p.data.Ornaments do n += 1 end
   378→	return n
   379→end
   380→
   381→-- cost = shards spent on the toy (generation price; for Fused toys: inputs + fee) -> market quick-sell
   382→function PlayerData.AddOrnament(player, toyId, rarityId, variantId, cost)
   383→	local p = profiles[player]
   384→	if not p then return nil end
   385→	local uid = tostring(p.data.NextId)
   386→	p.data.NextId += 1
   387→	local item = { Toy = toyId, Rarity = rarityId, Variant = variantId, T = os.time(), Cost = tonumber(cost) and math.max(0, math.floor(cost)) or 0 }
   388→	p.data.Ornaments[uid] = item
   389→	p.dirty = true
   390→	mirrorOrnament(player, uid, item)
   391→	return uid
   392→end
   393→
   394→-- uids of `count` plain (no variant) toys of one kind + rarity, oldest first; nil if there are fewer
   395→function PlayerData.FindFusable(player, toyId, rarityId, count)
   396→	local p = profiles[player]
   397→	if not p then return nil end
   398→	local list = {}
   399→	for uid, item in p.data.Ornaments do
   400→		if item.Toy == toyId and item.Rarity == rarityId and not item.Variant and not item.OnTree then table.insert(list, uid) end
   401→	end
   402→	if #list < count then return nil end
   403→	table.sort(list, function(a, b) return (tonumber(a) or 0) < (tonumber(b) or 0) end)
   404→	return table.move(list, 1, count, 1, {})
   405→end
   406→
   407→-- removes the given uids (only ones the player owns); returns the removed items
   408→function PlayerData.TakeOrnaments(player, uids)
   409→	local p = profiles[player]
   410→	if not p then return {} end
   411→	local removed = {}
   412→	local folder = inventoryFolder(player)
   413→	for _, uid in uids do
   414→		local item = p.data.Ornaments[uid]
   415→		if item and not item.OnTree then
   416→			p.data.Ornaments[uid] = nil
   417→			table.insert(removed, item)
   418→			local c = folder:FindFirstChild(uid)
   419→			if c then c:Destroy() end
   420→		end
   421→	end
   422→	if #removed > 0 then p.dirty = true end
   423→	return removed
   424→end
   425→
   426→---------------------------------------------------------------- trading (phase 3)
   427→local function count(t) local n = 0 for _ in t do n += 1 end return n end
   428→
   429→-- true if the player owns the toy and it is old enough to be traded
   430→function PlayerData.CanTradeItem(player, uid, minAge)
   431→	local p = profiles[player]
   432→	local it = p and p.data.Ornaments[uid]
   433→	return it ~= nil and not it.OnTree and os.time() - (it.T or 0) >= minAge
   434→end
   435→
   436→function PlayerData.ItemInfo(player, uid)
   437→	local p = profiles[player]
   438→	local it = p and p.data.Ornaments[uid]
   439→	return it and { Toy = it.Toy, Rarity = it.Rarity, Variant = it.Variant, T = it.T, OnTree = it.OnTree, Cost = it.Cost } or nil
   440→end
   441→
   442→-- Swaps two offers in one step after re-validating everything. offer = { uids = { ... }, shards = n }.
   443→-- The receiver of shards gets them minus tax. Returns true, { gotA = items for A, gotB = items for B } or false, msg.
   444→function PlayerData.ExecuteTrade(pa, pb, offerA, offerB, taxRate, minAge)
   445→	local A, B = profiles[pa], profiles[pb]
   446→	if not A or not B then return false, "Player data not loaded" end
   447→	offerA.shards, offerB.shards = 0, 0     -- only ornaments can be traded
   448→	local now = os.time()
   449→	local function valid(P, offer)
   450→		if P.data.Shards < offer.shards then return false end
   451→		local seen = {}
   452→		for _, uid in offer.uids do
   453→			local it = P.data.Ornaments[uid]
   454→			if seen[uid] or not it or it.OnTree or now - (it.T or 0) < minAge then return false end
   455→			seen[uid] = true
   456→		end
   457→		return true
   458→	end
   459→	if not valid(A, offerA) or not valid(B, offerB) then return false, "The offer is no longer valid" end
   460→	local capA = Config.StorageCap(A.data.Upgrades.Storage)
   461→	local capB = Config.StorageCap(B.data.Upgrades.Storage)
   462→	if count(A.data.Ornaments) - #offerA.uids + #offerB.uids > capA then return false, pa.DisplayName .. ": storage would overflow" end
   463→	if count(B.data.Ornaments) - #offerB.uids + #offerA.uids > capB then return false, pb.DisplayName .. ": storage would overflow" end
   464→
   465→	local itemsA = PlayerData.TakeOrnaments(pa, offerA.uids)
   466→	local itemsB = PlayerData.TakeOrnaments(pb, offerB.uids)
   467→	local function give(player, P, items)
   468→		for _, it in items do
   469→			local uid = tostring(P.data.NextId)
   470→			P.data.NextId += 1
   471→			local copy = { Toy = it.Toy, Rarity = it.Rarity, Variant = it.Variant, T = it.T, Cost = it.Cost }
   472→			P.data.Ornaments[uid] = copy
   473→			mirrorOrnament(player, uid, copy)
   474→			P.data.Discovered[it.Toy .. "|" .. it.Rarity] = true
   475→			P.tierStale = true
   476→		end
   477→	end
   478→	give(pb, B, itemsA)
   479→	give(pa, A, itemsB)
   480→	A.data.Shards = A.data.Shards - offerA.shards + math.floor(offerB.shards * (1 - taxRate))
   481→	B.data.Shards = B.data.Shards - offerB.shards + math.floor(offerA.shards * (1 - taxRate))
   482→	A.data.Stats.Trades = (A.data.Stats.Trades or 0) + 1
   483→	B.data.Stats.Trades = (B.data.Stats.Trades or 0) + 1
   484→	touch(pa, A)
   485→	touch(pb, B)
   486→	return true, { gotA = itemsB, gotB = itemsA }
   487→end
   488→
   489→---------------------------------------------------------------- market (phase 5)
   490→function PlayerData.Listings(player)
   491→	local p = profiles[player]
   492→	return p and p.data.Listings or {}
   493→end
   494→
   495→-- moves a toy from the inventory into the market escrow record (the toy stays saved with the seller until
   496→-- the listing is sold, cancelled or expired)
   497→function PlayerData.EscrowForListing(player, uid, listingId, price, expires)
   498→	local p = profiles[player]
   499→	if not p or not p.data.Ornaments[uid] then return nil end
   500→	local item = PlayerData.TakeOrnaments(player, { uid })[1]
   501→	if not item then return nil end
   502→	p.data.Listings[listingId] = { Item = item, Price = price, Expires = expires }
   503→	touch(player, p)
   504→	return item
   505→end
   506→
   507→-- same for a crafted item (one that is not on the plot)
   508→function PlayerData.EscrowCraft(player, id, listingId, price, expires)
   509→	local p = profiles[player]
   510→	if not p or not PlayerData.TakeCraft(player, id) then return nil end
   511→	local item = { Craft = id }
   512→	p.data.Listings[listingId] = { Item = item, Price = price, Expires = expires }
   513→	touch(player, p)
   514→	return item
   515→end
   516→
   517→function PlayerData.DropListing(player, listingId)
   518→	local p = profiles[player]
   519→	if not p then return nil end
   520→	local rec = p.data.Listings[listingId]
   521→	p.data.Listings[listingId] = nil
   522→	if rec then touch(player, p) end
   523→	return rec
   524→end
   525→
   526→---------------------------------------------------------------- Craft House (crafted plot items)
   527→-- one crafted item lives in Decor[id] (true = in the inventory, table = on the plot), the rest are counted in
   528→-- Crafts[id]. Adding fills Decor first, taking uses the extras first, so a placed item always stays put.
   529→local function addCraft(p, id)
   530→	if p.data.Decor[id] == nil or p.data.Decor[id] == false then
   531→		p.data.Decor[id] = true
   532→	else
   533→		p.data.Crafts[id] = (p.data.Crafts[id] or 0) + 1
   534→	end
   535→end
   536→function PlayerData.AddCraft(player, id)
   537→	local p = profiles[player]
   538→	if not p or not Config.CraftById[id] then return false end
   539→	addCraft(p, id)
   540→	touch(player, p)
   541→	return true
   542→end
   543→-- crafted items of `id` that are not on the plot
   544→function PlayerData.CraftSpare(player, id)
   545→	local p = profiles[player]
   546→	if not p then return 0 end
   547→	return (p.data.Crafts[id] or 0) + (p.data.Decor[id] == true and 1 or 0)
   548→end
   549→-- takes one crafted item that is NOT on the plot (market listing); false if there is none
   550→function PlayerData.TakeCraft(player, id)
   551→	local p = profiles[player]
   552→	if not p or not Config.CraftById[id] then return false end
   553→	local d = p.data
   554→	if (d.Crafts[id] or 0) > 0 then
   555→		d.Crafts[id] -= 1
   556→		if d.Crafts[id] <= 0 then d.Crafts[id] = nil end
   557→	elseif d.Decor[id] == true then
   558→		d.Decor[id] = nil
   559→	else
   560→		return false
   561→	end
   562→	touch(player, p)
   563→	return true
   564→end
   565→-- crafts one item: takes the recipe toys (Config.CraftPick) and adds the item. Returns true, takenItems or false, msg
   566→function PlayerData.CraftItem(player, id)
   567→	local p = profiles[player]
   568→	local c = Config.CraftById[id]
   569→	if not p or not c then return false, "Unknown item" end
   570→	local items = {}
   571→	for uid, it in p.data.Ornaments do
   572→		table.insert(items, { uid = uid, Toy = it.Toy, Rarity = it.Rarity, Variant = it.Variant, OnTree = it.OnTree })
   573→	end
   574→	local picks, complete = Config.CraftPick(id, items)
   575→	if not complete then return false, "Not enough ornaments for this recipe" end
   576→	local uids = {}
   577→	for _, line in picks do for _, it in line do table.insert(uids, it.uid) end end
   578→	local taken = PlayerData.TakeOrnaments(player, uids)
   579→	if #taken ~= #uids then
   580→		-- can not happen (all checked above); give back whatever was taken
   581→		for _, it in taken do PlayerData.GiveItem(player, it, false) end
   582→		return false, "Not enough ornaments for this recipe"
   583→	end
   584→	addCraft(p, id)
   585→	p.data.Stats.Crafted = (p.data.Stats.Crafted or 0) + 1
   586→	touch(player, p)
   587→	return true, taken
   588→end
   589→
   590→-- gives a toy (bought or returned) back into the inventory, keeping its variant. A crafted item ({ Craft = id })
   591→-- goes to the crafted items instead.
   592→function PlayerData.GiveItem(player, item, fresh)
   593→	local p = profiles[player]
   594→	if not p then return nil end
   595→	if item.Craft then
   596→		if not Config.CraftById[item.Craft] then return nil end
   597→		addCraft(p, item.Craft)
   598→		touch(player, p)
   599→		return "craft"
   600→	end
   601→	local uid = tostring(p.data.NextId)
   602→	p.data.NextId += 1
   603→	local copy = { Toy = item.Toy, Rarity = item.Rarity, Variant = item.Variant, T = fresh and os.time() or item.T, Cost = item.Cost }
   604→	p.data.Ornaments[uid] = copy
   605→	p.data.Discovered[item.Toy .. "|" .. item.Rarity] = true
   606→	p.tierStale = true
   607→	mirrorOrnament(player, uid, copy)
   608→	touch(player, p)
   609→	return uid
   610→end
   611→
   612→---------------------------------------------------------------- shop (plot decorations)
   613→function PlayerData.OwnsDecor(player, id)
   614→	local p = profiles[player]
   615→	local v = p and p.data.Decor[id]
   616→	return v ~= nil and v ~= false
   617→end
   618→
   619→-- all placements of the player: { [id] = { X, Z, R } }
   620→function PlayerData.DecorPlacements(player)
   621→	local p = profiles[player]
   622→	local out = {}
   623→	if not p then return out end
   624→	for id, v in p.data.Decor do
   625→		if type(v) == "table" then out[id] = v end
   626→	end
   627→	return out
   628→end
   629→
   630→-- placement = { X, Z, R } to put it on the plot, or nil to put it back into the inventory
   631→function PlayerData.SetDecorPlacement(player, id, placement)
   632→	local p = profiles[player]
   633→	if not p or not PlayerData.OwnsDecor(player, id) then return false end
   634→	p.data.Decor[id] = placement and { X = placement.X, Z = placement.Z, R = placement.R, Points = placement.Points } or true
   635→	touch(player, p)
   636→	return true
   637→end
   638→
   639→-- pays for a decoration; returns true or false, message
   640→function PlayerData.BuyDecor(player, id)
   641→	local p = profiles[player]
   642→	local item = Config.ShopById[id]
   643→	if not p or not item then return false, "No such item" end
   644→	if item.Craft then return false, "This item is made in the Craft House" end
   645→	if PlayerData.OwnsDecor(player, id) then return false, "Already bought" end
   646→	if p.data.Shards < item.Price then return false, "Not enough shards: you need " .. item.Price end
   647→	PlayerData.AddShards(player, -item.Price)
   648→	p.data.Decor[id] = true
   649→	touch(player, p)
   650→	return true
   651→end
   652→
   653→---------------------------------------------------------------- Robux purchases
   654→-- Grants a purchase exactly once: grant(player) runs only if purchaseId is new, then the profile is saved
   655→-- right away. Returns true when the purchase is safely recorded (-> PurchaseGranted), false to retry later.
   656→function PlayerData.GrantPurchase(player, purchaseId, grant)
   657→	local p = profiles[player]
   658→	if not p then return false end
   659→	local d = p.data
   660→	if d.Receipts[purchaseId] then return true end
   661→	grant(player)
   662→	d.Receipts[purchaseId] = os.time()
   663→	-- keep the receipt list small: drop the oldest beyond 100
   664→	local list = {}
   665→	for id, t in d.Receipts do table.insert(list, { id = id, t = t }) end
   666→	if #list > 100 then
   667→		table.sort(list, function(a, b) return a.t < b.t end)
   668→		for k = 1, #list - 100 do d.Receipts[list[k].id] = nil end
   669→	end
   670→	touch(player, p)
   671→	if not p.canSave or not store then return true end   -- Studio without API access: nothing to save
   672→	return PlayerData.Save(player) == true
   673→end
   674→
   675→---------------------------------------------------------------- Christmas tree toys
   676→-- { [slot] = uid } of the toys hanging on the player's tree
   677→function PlayerData.TreeToys(player)
   678→	local p = profiles[player]
   679→	local out = {}
   680→	if not p then return out end
   681→	for uid, it in p.data.Ornaments do
   682→		if it.OnTree then out[it.OnTree] = uid end
   683→	end
   684→	return out
   685→end
   686→
   687→-- slot = number to hang it, nil to take it off; returns true or false, message
   688→function PlayerData.SetToySlot(player, uid, slot)
   689→	local p = profiles[player]
   690→	local it = p and p.data.Ornaments[uid]
   691→	if not it then return false, "Ornament not found" end
   692→	if slot ~= nil then
   693→		for otherUid, other in p.data.Ornaments do
   694→			if otherUid ~= uid and other.OnTree == slot then return false, "This spot is already taken" end
   695→		end
   696→	end
   697→	it.OnTree = slot
   698→	local c = player:FindFirstChild("OrnamentInventory") and player.OrnamentInventory:FindFirstChild(uid)
   699→	if c then c:SetAttribute("OnTree", slot) end
   700→	p.dirty = true
   701→	return true
   702→end
   703→
   704→---------------------------------------------------------------- tutorial
   705→function PlayerData.SetTutorialDone(player)
   706→	local p = profiles[player]
   707→	if not p or p.data.TutorialDone then return end
   708→	p.data.TutorialDone = true
   709→	touch(player, p)
   710→end
   711→
   712→---------------------------------------------------------------- admin (OrnamentAdminServer)
   713→-- sets the level directly (XP of the new level starts at 0); no level-up rewards
   714→function PlayerData.SetLevel(player, level)
   715→	local p = profiles[player]
   716→	if not p then return false end
   717→	p.tierStale = true
   718→	p.data.Level = math.clamp(math.floor(level), 1, Config.MAX_LEVEL)
   719→	p.data.XP = 0
   720→	touch(player, p)
   721→	return true
   722→end
   723→
   724→function PlayerData.ResetTutorial(player)
   725→	local p = profiles[player]
   726→	if not p then return false end
   727→	p.data.TutorialDone = false
   728→	touch(player, p)
   729→	return true
   730→end
   731→
   732→-- "tutorial reset for everyone": a global counter; a profile with an older one gets TutorialDone = false once
   733→function PlayerData.ApplyTutorialEpoch(player, epoch)
   734→	local p = profiles[player]
   735→	if not p or type(epoch) ~= "number" or epoch <= 0 then return end
   736→	local d = p.data
   737→	if (d.TutorialEpoch or 0) >= epoch then return end
   738→	d.TutorialEpoch = epoch
   739→	d.TutorialDone = false
   740→	touch(player, p)
   741→end
   742→
   743→-- the profile becomes a new player's; Robux receipts stay (a purchase is never granted twice).
   744→-- Returns the ids of the old market listings (the caller takes them off the market), nil if not loaded.
   745→function PlayerData.ResetProfile(player)
   746→	local p = profiles[player]
   747→	if not p then return nil end
   748→	local old = p.data
   749→	local d = defaults()
   750→	d.Receipts = old.Receipts or {}
   751→	d.TestTopUp = old.TestTopUp
   752→	d.TutorialEpoch = old.TutorialEpoch
   753→	d.Promos = old.Promos or {}                  -- redeemed codes stay redeemed (no second reward after a reset)
   754→	d.VipGift = old.VipGift == true
   755→	d.Settings = old.Settings or d.Settings      -- the player's sound / language settings are not progress
   756→	p.data = d
   757→	p.tierStale = true
   758→	local inv = player:FindFirstChild("OrnamentInventory")
   759→	if inv then inv:ClearAllChildren() end
   760→	touch(player, p)
   761→	local lots = {}
   762→	for id in old.Listings or {} do table.insert(lots, id) end
   763→	return lots
   764→end
   765→
   766→---------------------------------------------------------------- promo codes (OrnamentPromo)
   767→function PlayerData.HasPromo(player, code)
   768→	local p = profiles[player]
   769→	return p ~= nil and type(p.data.Promos) == "table" and p.data.Promos[code] ~= nil
   770→end
   771→function PlayerData.MarkPromo(player, code)
   772→	local p = profiles[player]
   773→	if not p then return false end
   774→	p.data.Promos = type(p.data.Promos) == "table" and p.data.Promos or {}
   775→	p.data.Promos[code] = os.time()
   776→	touch(player, p)
   777→	return true
   778→end
   779→function PlayerData.SetVipGift(player)
   780→	local p = profiles[player]
   781→	if not p then return false end
   782→	p.data.VipGift = true
   783→	touch(player, p)
   784→	return true
   785→end
   786→function PlayerData.HasVipGift(player)
   787→	local p = profiles[player]
   788→	return p ~= nil and p.data.VipGift == true
   789→end
   790→
   791→---------------------------------------------------------------- settings
   792→-- partial update from the Settings window; unknown keys / bad values are ignored. Returns true if anything changed.
   793→function PlayerData.SetSettings(player, patch)
   794→	local p = profiles[player]
   795→	if not p or type(patch) ~= "table" then return false end
   796→	local merged = table.clone(p.data.Settings or {})
   797→	for k, v in patch do if type(k) == "string" then merged[k] = v end end
   798→	local clean = cleanSettings(merged)
   799→	local changed = false
   800→	for k, v in clean do if p.data.Settings[k] ~= v then changed = true end end
   801→	if not changed then return false end
   802→	p.data.Settings = clean
   803→	p.dirty = true
   804→	publishSettings(player, clean)
   805→	return true
   806→end
   807→
   808→---------------------------------------------------------------- saving
   809→local function deepCopy(t)
   810→	local c = {}
   811→	for k, v in t do c[k] = type(v) == "table" and deepCopy(v) or v end
   812→	return c
   813→end
   814→
   815→-- writes the profile (also refreshes the session lock); release = drop the lock (player left)
   816→function PlayerData.Save(player, release)
   817→	local p = profiles[player]
   818→	if not p or not p.canSave or not store then return end
   819→	if p.released and not release then return end   -- leaving: only the final (lock-releasing) save may write
   820→	local snapshot = deepCopy(p.data)
   821→	snapshot.Lock = (not release) and { Job = JOB, Time = os.time() } or nil
   822→	local lost = false
   823→	inflight += 1
   824→	local ok = retry(function()
   825→		store:UpdateAsync(keyOf(player), function(old)
   826→			if type(old) == "table" and type(old.Lock) == "table" and old.Lock.Job ~= JOB then
   827→				lost = true
   828→				return nil                              -- someone else owns the profile now: never overwrite
   829→			end
   830→			-- an autosave that finishes after the final save must not put the lock back
   831→			if not release and p.released then return nil end
   832→			return snapshot
   833→		end)
   834→	end)
   835→	inflight -= 1
   836→	if lost then
   837→		warn("[OrnamentData] lost the session lock for " .. player.Name .. "; changes are not saved")
   838→		p.canSave = false
   839→	elseif ok then
   840→		p.dirty = false
   841→	end
   842→	return ok and not lost
   843→end
   844→
   845→function PlayerData.Release(player)
   846→	local p = profiles[player]
   847→	if not p or p.released then return end
   848→	p.released = true
   849→	PlayerData.Save(player, true)
   850→	profiles[player] = nil
   851→end
   852→
   853→function PlayerData.ForEach(fn)
   854→	for player in profiles do fn(player) end
   855→end
   856→
   857→function PlayerData.SaveAll()
   858→	local pending = 0
   859→	for player in profiles do
   860→		pending += 1
   861→		task.spawn(function()
   862→			PlayerData.Release(player)
   863→			pending -= 1
   864→		end)
   865→	end
   866→	-- also wait for the saves PlayerRemoving already started (on shutdown the players leave first, so their
   867→	-- profiles may be gone from `profiles` while the save is still on its way)
   868→	task.wait(0.5)
   869→	local deadline = os.clock() + 25
   870→	while (pending > 0 or inflight > 0) and os.clock() < deadline do task.wait(0.2) end
   871→end
   872→
   873→return PlayerData
   874→
