local PLUGIN = PLUGIN
print("[Warn System] Server Side Loaded")

-- Load warnings on startup
function PLUGIN:Initialize()
    self.warns = ix.data.Get("warns", {})
end

-- Save warnings to permanent storage
function PLUGIN:SaveWarns()
    ix.data.Set("warns", self.warns)
end

net.Receive("ixWarnAdd", function(length, client)
    if (!client:IsSuperAdmin()) then return end

    local targetSteamID = net.ReadString()
    local reason = net.ReadString() or "No reason provided"
    
    PLUGIN.warns = ix.data.Get("warns", {})
    PLUGIN.warns[targetSteamID] = PLUGIN.warns[targetSteamID] or {count = 0, history = {}}
    
    local targetData = PLUGIN.warns[targetSteamID]
    targetData.count = targetData.count + 1
    
    table.insert(targetData.history, {
        admin = client:Name(),
        adminSteamID = client:SteamID(),
        reason = reason,
        time = os.time(),
        type = "add"
    })

    local targetPlayer = player.GetBySteamID(targetSteamID)
    if (IsValid(targetPlayer)) then
        targetData.name = targetPlayer:Name()
        targetData.rank = targetPlayer:GetUserGroup()
        
        targetPlayer:Notify("Вы получили выговор (" .. targetData.count .. "/3). Причина: " .. reason)
    end

    -- Automatic demotion (3/3 warnings) - Now works for offline players too
    if (targetData.count >= 3) then
        if (sam) then
            -- Use SAM's Lua API for reliable rank setting (offline or online)
            sam.player.set_rank_id(targetSteamID, "user", 0)
            print("[Warn System] Initiated demotion for " .. targetSteamID .. " via SAM.")
        else
            -- Fallback for other systems
            if (IsValid(targetPlayer)) then
                targetPlayer:SetUserGroup("user")
            else
                -- If offline and not SAM, we attempt console command as last resort
                RunConsoleCommand("ulx", "adduser", targetSteamID, "user")
            end
        end

        PLUGIN.warns[targetSteamID] = nil -- Remove from system after demotion
        
        if (IsValid(targetPlayer)) then
            targetPlayer:Notify("Вы были автоматически сняты с админ-прав за достижение 3 выговоров.")
        end

        ix.util.Notify((targetData.name or targetSteamID) .. " был автоматически снят с админ-прав (3/3 выговоров).")
    end

    PLUGIN:SaveWarns()
    ix.util.Notify(client:Name() .. " выдал выговор " .. (targetData.name or targetSteamID) .. ". Причина: " .. reason)
end)

net.Receive("ixWarnRemove", function(length, client)
    if (!client:IsSuperAdmin()) then return end

    local targetSteamID = net.ReadString()
    local index = net.ReadInt(16)
    
    PLUGIN.warns = ix.data.Get("warns", {})
    local targetData = PLUGIN.warns[targetSteamID]
    
    if (targetData and targetData.history[index]) then
        targetData.count = math.max(0, targetData.count - 1)
        table.insert(targetData.history, {
            admin = client:Name(),
            adminSteamID = client:SteamID(),
            reason = "Снятие выговора #" .. index,
            time = os.time(),
            type = "remove"
        })
        
        PLUGIN:SaveWarns()
        ix.util.Notify(client:Name() .. " снял выговор у " .. (targetData.name or targetSteamID))
    end
end)
