local LOYALTY_REWARD = 1
local REQUIRED_SECONDS = 3600 -- 60 minut
local STORAGE_ONLINE_SECONDS = 99993
local STORAGE_LAST_LOGIN_TIME = 99992

function onThink(interval)
    for _, player in ipairs(Game.getPlayers()) do
        local lastLogin = player:getStorageValue(STORAGE_LAST_LOGIN_TIME)
        local storedTime = player:getStorageValue(STORAGE_ONLINE_SECONDS)

        if lastLogin < 0 then lastLogin = os.time() end
        if storedTime < 0 then storedTime = 0 end

        local onlineNow = os.time() - lastLogin
        local totalOnline = storedTime + onlineNow

        if totalOnline >= REQUIRED_SECONDS then
            local extra = totalOnline - REQUIRED_SECONDS
            player:setStorageValue(STORAGE_ONLINE_SECONDS, extra)
            player:setStorageValue(STORAGE_LAST_LOGIN_TIME, os.time())
            db.query("UPDATE `players` SET `loyalty_points` = `loyalty_points` + " .. LOYALTY_REWARD .. " WHERE `id` = " .. player:getGuid())
            player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "You received " .. LOYALTY_REWARD .. " loyalty point for 1 hour online.")
        end
    end
    return true
end
