local PLUGIN = PLUGIN

-- Tracking when the last salary "tick" happened to avoid double triggers within the same minute
PLUGIN.lastTickMinute = PLUGIN.lastTickMinute or -1

function PLUGIN:Tick()
	local currentMinute = tonumber(os.date("%M"))
	
	-- Check for 00 or 30 minutes
	if (currentMinute == 0 or currentMinute == 30) then
		if (PLUGIN.lastTickMinute != currentMinute) then
			PLUGIN.lastTickMinute = currentMinute
			self:DistributeSalary()
		end
	else
		-- Reset the tick tracker when we are not in the target minute
		if (PLUGIN.lastTickMinute != -1) then
			PLUGIN.lastTickMinute = -1
		end
	end
end

function PLUGIN:OnCharacterLoaded(character)
	-- Store the time the character was loaded/joined if not already set
	-- This helps tracking playtime for the first salary
	if (!character:GetData("salary_start_time")) then
		character:SetData("salary_start_time", os.time())
	end
end

function PLUGIN:DistributeSalary(bIgnorePlaytime)
	local minPlaytime = ix.config.Get("salary_min_playtime", 30) * 60 -- convert to seconds
	local salaryTable = ix.config.Get("salary_amounts", {})
	local currentTime = os.time()

	for _, client in ipairs(player.GetAll()) do
		local character = client:GetCharacter()
		if (!character) then continue end

		local startTime = character:GetData("salary_start_time", currentTime)
		local playtime = currentTime - startTime

		if (bIgnorePlaytime or playtime >= minPlaytime) then
			local rank = tonumber(character:GetRank()) or 1
			
			-- Hardcoded fallback table in case config is empty or missing keys in database
			local defaultSalaries = {
				[1] = 500, [2] = 630, [3] = 760, [4] = 890, [5] = 1020, 
				[6] = 1150, [7] = 1280, [8] = 1410, [9] = 1540, [10] = 1670, 
				[11] = 1800, [12] = 1930, [13] = 2060, [14] = 2190, [15] = 2320, [16] = 2500
			}

			-- 1. Try to get value from config first
			local amount = 0
			for k, v in pairs(salaryTable) do
				if (tonumber(k) == rank) then
					amount = v
					break
				end
			end
			
			-- 2. If config has no data for this rank (or it's fallback 500 but not rank 1),
			-- use the hardcoded table in code.
			if (amount == 0 or (amount == 500 and rank != 1)) then
				amount = defaultSalaries[rank] or defaultSalaries[1] or 500
			end
			
			character:GiveMoney(amount)
			character:SetData("salary_start_time", currentTime) -- Reset timer for next salary

			client:Notify("Вы получили зарплату в размере " .. ix.currency.Get(amount) .. " за вашу службу!")
		else
			local remaining = math.ceil((minPlaytime - playtime) / 60)
			client:Notify("Вам не начислена зарплата, так как вы отыграли меньше " .. (minPlaytime / 60) .. " минут. Осталось: " .. remaining .. " мин.")
		end
	end
end

-- Force reset salary start time on join just in case
function PLUGIN:PlayerLoadedCharacter(client, character, oldCharacter)
	character:SetData("salary_start_time", os.time())
end
