
-- Функция отправки данных на API
function PLUGIN:SendBanToAPI(steamID, action, banData)
	local url = self.config.apiHost .. self.config.apiEndpoint
	
	local params = {
		api_key = self.config.apiKey,
		action = action,
		user_steam_id = steamID
	}
	
	if (action == "ban") then
		params.admin_steam_id = tostring(banData.adminSteamID or "")
		params.reason = tostring(banData.reason or "No reason provided")
		params.ban_type = tostring(self.config.banType or "server")
		params.duration = tostring(math.floor(banData.duration or 0))
		params.banned_at = tostring(math.floor(banData.bannedAt or os.time()))
		
		if (banData.unbanTime) then
			params.unbanned_at = tostring(math.floor(banData.unbanTime))
		end
	elseif (action == "unban") then
		params.unbanned_at = tostring(os.time())
	end
	
	http.Post(url, params, 
		function(body)
			local response = util.JSONToTable(body)
			if (response and response.success) then
				self:Log(string.format("%s успешно синхронизирован для %s", action == "ban" and "Бан" or "Разбан", steamID))
			else
				self:Log(string.format("Ошибка синхронизации: %s", response and response.error or "Unknown error"))
			end
		end,
		function(error)
			self:Log(string.format("HTTP ошибка: %s", error))
		end
	)
end

-- Хук на бан игрока (объект игрока)
hook.Add("SAM.BannedPlayer", "ixSAMBansSyncPlayer", function(ply, unbanDate, reason, adminSteamID)
	local steamID = ply:SteamID64()
	local duration = 0
	local unbanTime = nil
	
	-- Вычисляем длительность бана
	if (unbanDate and unbanDate > 0) then
		duration = unbanDate - os.time()
		unbanTime = unbanDate
	end
	
	-- Обрабатываем админа
	local adminID = nil
	if (adminSteamID and adminSteamID != "Console") then
		if (tostring(adminSteamID):sub(1, 7) == "7656119") then
			adminID = adminSteamID
		else
			adminID = util.SteamIDTo64(adminSteamID)
		end
	end
	
	local banData = {
		adminSteamID = adminID,
		reason = reason,
		duration = duration,
		bannedAt = os.time(),
		unbanTime = unbanTime
	}
	
	ix.plugin.list["sambans"]:SendBanToAPI(steamID, "ban", banData)
end)

-- Хук на бан по SteamID (оффлайн игрок)
hook.Add("SAM.BannedSteamID", "ixSAMBansSyncSteamID", function(steamID, unbanDate, reason, adminSteamID)
	local steamID64 = util.SteamIDTo64(steamID)
	local duration = 0
	local unbanTime = nil
	
	-- Вычисляем длительность бана
	if (unbanDate and unbanDate > 0) then
		duration = unbanDate - os.time()
		unbanTime = unbanDate
	end
	
	-- Обрабатываем админа
	local adminID = nil
	if (adminSteamID and adminSteamID != "Console") then
		if (tostring(adminSteamID):sub(1, 7) == "7656119") then
			adminID = adminSteamID
		else
			adminID = util.SteamIDTo64(adminSteamID)
		end
	end
	 
	local banData = {
		adminSteamID = adminID,
		reason = reason,
		duration = duration,
		bannedAt = os.time(),
		unbanTime = unbanTime
	}
	
	ix.plugin.list["sambans"]:SendBanToAPI(steamID64, "ban", banData)
end)

-- Хук на разбан
hook.Add("SAM.UnbannedSteamID", "ixSAMBansSyncUnban", function(steamID, admin)
	local steamID64 = util.SteamIDTo64(steamID)
	
	ix.plugin.list["sambans"]:SendBanToAPI(steamID64, "unban", {})
end)

-- Команда для теста API
concommand.Add("ix_sambans_test", function(ply)
	if (IsValid(ply) and not ply:IsSuperAdmin()) then return end
	
	local plugin = ix.plugin.list["sambans"]
	plugin:Log("Тестирование подключения к API...")
	
	local testData = {
		adminSteamID = "76561198000000000",
		reason = "Test ban from Helix plugin",
		duration = 3600,
		bannedAt = os.time()
	}
	
	plugin:SendBanToAPI("76561198000000001", "ban", testData)
end)

PLUGIN:Log("Плагин загружен. Синхронизация банов SAM активна.")
