TicketSystem_TicketsGUI = {}
TicketSystem_TicketsCreationGUI = {}
TicketSystem_TicketsShowGUI = {}
TicketSystem_AdminTicketsGUI = {}
TicketSystem_AdminShowGUI = {}
TicketSystem_AdminStatsGUI = {}

local TicketsGUI = TicketSystem_TicketsGUI
local TicketsCreationGUI = TicketSystem_TicketsCreationGUI
local TicketsShowGUI = TicketSystem_TicketsShowGUI
local AdminTicketsGUI = TicketSystem_AdminTicketsGUI
local AdminShowGUI = TicketSystem_AdminShowGUI
local AdminStatsGUI = TicketSystem_AdminStatsGUI

function TicketsGUI:Init()
	self.Frame = false
	self.PanelWidth = TicketSystem_Config.MyTicketsWindowSize[1]
	self.PanelHeight = TicketSystem_Config.MyTicketsWindowSize[2]
end

function TicketsGUI:Create()
	self.Frame = vgui.Create("DFrame")
	self.Frame:SetSize(self.PanelWidth, self.PanelHeight) 
	self.Frame:Center()
	self.Frame:SetTitle(TicketSystem_Language:GetPhrase("MY_TICKETS_TITLE"))
	self.Frame:SetDraggable(true)
	self.Frame.Paint = MG_Theme.Theme.Frame.Paint
	self.Frame.PaintOver = MG_Theme.Theme.Frame.PaintOver
	self.Frame.OnRemove = function()
		net.Start("TicketSystem_CloseMenu")
		net.SendToServer()
	end
	local TicketList = vgui.Create("DListView", self.Frame)
	self.TicketList = TicketList
	TicketList:AddColumn("ID"):SetFixedWidth(50)
	TicketList:AddColumn(TicketSystem_Language:GetPhrase("TICKET_TITLE")):SetFixedWidth(131)
	TicketList:AddColumn(TicketSystem_Language:GetPhrase("TICKET_STATE")):SetFixedWidth(80)
	TicketList:AddColumn(TicketSystem_Language:GetPhrase("TICKET_CATEGORY")):SetFixedWidth(90)
	TicketList:AddColumn(TicketSystem_Language:GetPhrase("TICKET_ADMIN")):SetFixedWidth(160)
	TicketList:AddColumn(TicketSystem_Language:GetPhrase("TICKET_DATE")):SetFixedWidth(120)
	TicketList:SetSize(0, self.PanelHeight - 75)	
	TicketList:Dock(TOP)
	TicketList:SetMultiSelect(false)
	self.TicketData = {}

	function TicketList:OnRowRightClick(id, panel)
		local id = tonumber(panel:GetColumnText(1))
		local tdata = TicketsGUI.TicketData[id]
		local menu = DermaMenu(self)
		TicketsGUI.DermaMenu = menu
		TicketsGUI.DermaID = id
		MG_Theme.Theme.DMenu.AddOption(menu, TicketSystem_Language:GetPhrase("OPEN"), function()
			TicketsShowGUI:Open(tdata)
			net.Start("TicketSystem_UpdateMessages")
				net.WriteUInt(id, 32)
			net.SendToServer()
		end)
		menu.Paint = MG_Theme.Theme.DMenu.Paint
		menu:Open()
	end

	function TicketList:DoDoubleClick(id, panel)
		local id = tonumber(panel:GetColumnText(1))
		local tdata = TicketsGUI.TicketData[id]	
		TicketsShowGUI:Open(tdata)
		net.Start("TicketSystem_UpdateMessages")
			net.WriteUInt(id, 32)
		net.SendToServer()
	end

	local Create = vgui.Create("DButton", self.Frame)
	Create:SetSize(self.PanelWidth - 10, 35)
	Create:SetPos(5, self.PanelHeight - 40)
	Create:SetText(TicketSystem_Language:GetPhrase("CREATE_NEW_TICKET"))
	Create.DoClick = function()
		TicketsCreationGUI:Open()
	end
	MG_Theme.Theme.Button.SetupTheme(Create)
	MG_Theme.Theme.ListView.SetupTheme(TicketList)
end

function TicketsGUI:Close()
	if IsValid(self.Frame) then
		self.Frame:Close()
		if IsValid(self.DermaMenu) then
			self.DermaMenu:Remove()
		end
	end
end

function TicketsGUI:Open()
	if IsValid(self.Frame) then
		self.Frame:Close()
		if IsValid(self.DermaMenu) then
			self.DermaMenu:Remove()
		end
	end
	self:Create()
	self.Frame:MakePopup()
end

function TicketsGUI:UpdateTickets(tickets)
	if !IsValid(self.TicketList) then return end
	self.TicketData = {}
	self.TicketList:Clear()
	for _, ticket in pairs(tickets) do
		local id = ticket.id
		local state = tonumber(ticket.status)
		local color = MG_Theme.Theme:GetStatusColor(state)
		local title = ticket.title
		local line = self.TicketList:AddLine(id, title, TicketSystem_Config.TicketStatus[state] or TicketSystem_Language:GetPhrase("UNKNOWN"), ticket.category, ticket.admin, os.date("%H:%M, %d.%m.%Y", tonumber(ticket.date)))
		line:SetColumnColor(3, color)
		line:SetTooltip(title)
		self.TicketData[tonumber(id)] = ticket
	end
	MG_Theme.Theme.ListView.SetupTheme(self.TicketList)
end

TicketsGUI:Init()

function TicketsCreationGUI:Init()
	self.Frame = self.Frame or false
	self.PanelWidth = TicketSystem_Config.NewTicketWindowSize[1]
	self.PanelHeight = TicketSystem_Config.NewTicketWindowSize[2]
end

function TicketsCreationGUI:Create()
	self:Init()
	self.Frame = vgui.Create("DFrame")
	self.Frame:SetSize(self.PanelWidth, self.PanelHeight)
	self.Frame:Center()
	self.Frame:SetTitle(TicketSystem_Language:GetPhrase("NEW_TICKET_TITLE"))
	self.Frame:SetDraggable(true)
	self.Frame.Paint = MG_Theme.Theme.Frame.Paint
	self.Frame.PaintOver = MG_Theme.Theme.Frame.PaintOver
	local TitleLabel = vgui.Create("DLabel", self.Frame)
	TitleLabel:SetText(TicketSystem_Language:GetPhrase("TICKET_TITLE")..":")
	TitleLabel:SetPos(15, 30)
	local Title = vgui.Create("DTextEntry", self.Frame)
	Title:SetPos(15, 50)
	Title:SetSize(self.PanelWidth - 30, 30)
	Title:SetAllowNonAsciiCharacters(true)
	MG_Theme.Theme.TextEntry.Setup(Title)
	local Category = vgui.Create("DComboBox", self.Frame)
	Category:SetSize(self.PanelWidth - 30, 30)
	Category:SetPos(15, 90)
	Category:SetValue(TicketSystem_Language:GetPhrase("TICKET_CATEGORY"))
	Category:SetTextColor(Color(180, 180, 180))
	for _, cat in ipairs(TicketSystem_Config.TicketCategories) do
		Category:AddChoice(cat)
	end
	MG_Theme.Theme.ComboBox.Setup(Category)
	local TitleLabel = vgui.Create("DLabel", self.Frame)
	TitleLabel:SetText(TicketSystem_Language:GetPhrase("REPORT")..":")
	TitleLabel:SetPos(15, 140)
	local Text = vgui.Create("DTextEntry", self.Frame)
	Text:SetPos(15, 160)
	Text:SetSize(self.PanelWidth - 30, 140)
	Text:SetAllowNonAsciiCharacters(true)
	Text:SetMultiline(true)
	Text:SetText(TicketSystem_Language:GetPhrase("TICKET_TEXT"))
	Text.OldMousePressed = Text.OnMousePressed
	function Text:OnMousePressed(...)
		self:OldMousePressed(...)
		if (self:GetValue() == (TicketSystem_Language:GetPhrase("TICKET_TEXT"))) then
			self:SetValue("")
		end
	end
	MG_Theme.Theme.TextEntry.Setup(Text)
	local Create = vgui.Create("DButton", self.Frame)
	Create:SetSize(self.PanelWidth - 30, 35)
	Create:SetPos(15, 310)
	Create:SetText(TicketSystem_Language:GetPhrase("CREATE_TICKET"))
	MG_Theme.Theme.Button.SetupTheme(Create)
	Create:SetTextColor(MG_Theme.Theme:GetSuccessColor())
	Create.DoClick = function()
		local title = Title:GetValue()
		local category = Category:GetSelected()
		local text = Text:GetValue()
		local len_title = #title
		local len_text = #text
		if len_title < TicketSystem_Config.MinTitleChars or string.Trim(title) == "" then
			return TicketSystem_Notify:Add(TicketSystem_Language:GetPhrase("INVALID_TITLE"), 3000, "DANGER")
		end
		if len_title > TicketSystem_Config.MaxTitleChars then
			return TicketSystem_Notify:Add(TicketSystem_Language:GetPhrase("TITLE_MAX_CHARS").." "..TicketSystem_Config.MaxTitleChars, 3000, "DANGER")
		end
		if len_text < TicketSystem_Config.MinReportChars or text == TicketSystem_Language:GetPhrase("TICKET_TEXT") or string.Trim(text) == "" then
			return TicketSystem_Notify:Add(TicketSystem_Language:GetPhrase("INVALID_REPORT"), 3000, "DANGER")
		end
		if len_text > TicketSystem_Config.MaxReportChars then
			return TicketSystem_Notify:Add(TicketSystem_Language:GetPhrase("REPORT_MAX_CHARS").." "..TicketSystem_Config.MaxMessageChars, 3000, "DANGER")
		end
		local found
		for _, cat in ipairs(TicketSystem_Config.TicketCategories) do
			if (cat == category) then
				found = true
			end
		end
		if !found then
			return TicketSystem_Notify:Add(TicketSystem_Language:GetPhrase("INVALID_CATEGORY"), 3000, "DANGER")
		end
		net.Start("TicketSystem_CreateTicket")
			net.WriteString(title)
			net.WriteString(category)
			net.WriteString(text)
		net.SendToServer()
		self:Close()
		if IsValid(TicketsGUI.Frame) then
			TicketsGUI.Frame:Close()
		end
	end
end

function TicketsCreationGUI:Close()
	if IsValid(self.Frame) then
		self.Frame:Close()
	end
end

function TicketsCreationGUI:Open()
	if IsValid(self.Frame) then
		self.Frame:Close()
	end
	self:Create()
	self.Frame:MakePopup()
end

function TicketsShowGUI:Init()
	self.Frame = self.Frame or false
	self.PanelWidth = TicketSystem_Config.MyTicketWindowSize[1]
	self.PanelHeight = TicketSystem_Config.MyTicketWindowSize[2]
end

local function AddTicketContent(self)
	local txt = self.Ticket.text
	local Form = self.Scroll:Add("DForm")
	self.Form = Form
	Form:Dock(TOP)
	Form:DockMargin(0, 0, 0, 10)
	Form:DockPadding(0, 0, 10, 10)
	Form:SetName(TicketSystem_Language:GetPhrase("TICKET_BY").." "..self.Ticket.user)
	local Date = vgui.Create("DLabel")
	Date:SetAutoStretchVertical(true)
	Date:SetText(os.date("%H:%M, %d.%m.%Y", tonumber(self.Ticket.date)))
	Date:SetWrap(true)
	Date:SetTextColor(Color(150, 150, 150))
	local Label = vgui.Create("DLabel")
	Label:SetAutoStretchVertical(true)
	Label:SetText(txt)
	Label:SetWrap(true)
	Label:SetTooltip(TicketSystem_Language:GetPhrase("CLICK_TO_COPY"))
	Label.DoClick = function()
		SetClipboardText(txt)
		surface.PlaySound("ui/buttonclick.wav")
	end
	Form.Header:SetTextColor(MG_Theme.Theme:GetUserColor())
	Form:AddItem(Date)
	Form:AddItem(Label)
	Form.Items[1]:DockPadding(10, 0, 10, 0)
	Form.Items[2]:DockPadding(10, 5, 10, 0)
	Form.Paint = function(s, w, h)
		draw.RoundedBox(0, 0, 0, w, h, Color(0, 0, 0, 200))
	end
end

function TicketsShowGUI:Create(ticket)
	self:Init()
	self.Ticket = ticket
	self.ID = tonumber(ticket.id)
	self.Frame = vgui.Create("DFrame")
	self.Frame:SetSize(self.PanelWidth, self.PanelHeight)
	if self.LastPositions then
		self.Frame:SetPos(self.LastPositions[1], self.LastPositions[2])
	else
		self.Frame:Center()
	end
	self.Frame:SetTitle(TicketSystem_Language:GetPhrase("MY_TICKET_TITLE"))
	self.Frame:SetDraggable(true)
	self.Frame.Paint = MG_Theme.Theme.Frame.Paint
	self.Frame.PaintOver = MG_Theme.Theme.Frame.PaintOver
	self.Frame.OnRemove = function()
		net.Start("TicketSystem_CloseInfo")
			net.WriteUInt(self.ID, 32)
		net.SendToServer()
	end
	local TitleLabel = vgui.Create("DLabel", self.Frame)
	TitleLabel:SetText(TicketSystem_Language:GetPhrase("TICKET_TITLE")..":")
	TitleLabel:SetPos(15, 30)
	TitleLabel:SetTextColor(Color(170, 170, 170))
	TitleLabel:SetSize(self.PanelWidth - 40, 20)
	local Title = vgui.Create("DLabel", self.Frame)
	Title:SetText(ticket.title)
	Title:SetPos(15, 45)
	Title:SetTextColor(Color(200, 200, 200))
	Title:SetSize(self.PanelWidth / 2 - 30, 20)
	local CategoryLabel = vgui.Create("DLabel", self.Frame)
	CategoryLabel:SetText(TicketSystem_Language:GetPhrase("TICKET_CATEGORY")..":")
	CategoryLabel:SetPos(15, 65)
	CategoryLabel:SetTextColor(Color(170, 170, 170))
	CategoryLabel:SetSize(self.PanelWidth - 40, 20)
	local Category = vgui.Create("DLabel", self.Frame)
	Category:SetText(ticket.category)
	Category:SetPos(15, 80)
	Category:SetTextColor(Color(200, 200, 200))
	Category:SetSize(self.PanelWidth / 2 - 30, 20)
	local StateLabel = vgui.Create("DLabel", self.Frame)
	StateLabel:SetText(TicketSystem_Language:GetPhrase("TICKET_STATE")..":")
	StateLabel:SetPos(200, 30)
	StateLabel:SetTextColor(Color(170, 170, 170))
	StateLabel:SetSize(self.PanelWidth - 40, 20)
	local State = vgui.Create("DLabel", self.Frame)
	self.StateLabel = State
	State:SetText(TicketSystem_Config.TicketStatus[tonumber(ticket.status)] or TicketSystem_Language:GetPhrase("UNKNOWN"))
	State:SetPos(200, 45)
	State:SetTextColor(MG_Theme.Theme:GetStatusColor(tonumber(ticket.status)))
	State:SetSize(self.PanelWidth / 2 - 30, 20)
	local AdminLabel = vgui.Create("DLabel", self.Frame)
	AdminLabel:SetText(TicketSystem_Language:GetPhrase("TICKET_ADMIN")..":")
	AdminLabel:SetPos(200, 65)
	AdminLabel:SetTextColor(Color(170, 170, 170))
	AdminLabel:SetSize(self.PanelWidth - 40, 20)
	local Admin = vgui.Create("DLabel", self.Frame)
	self.AdminLabel = Admin
	Admin:SetText(ticket.admin)
	Admin:SetPos(200, 80)
	Admin:SetTextColor(Color(170, 170, 170))
	Admin:SetSize(self.PanelWidth / 2 - 30, 20)
	local Answers = vgui.Create("DLabel", self.Frame)
	Answers:SetText(TicketSystem_Language:GetPhrase("TICKET_CONTENTS")..":")
	Answers:SetPos(15, 100)
	Answers:SetTextColor(Color(170, 170, 170))
	Answers:SetSize(self.PanelWidth - 40, 20)
	local Scroll = vgui.Create("DScrollPanel", self.Frame)
	self.Scroll = Scroll
	Scroll:SetPos(15, 120)
	Scroll:SetSize(self.PanelWidth - 30, 200)
	MG_Theme.Theme.ScrollBar.Setup(Scroll.VBar)
	AddTicketContent(self)
	local Text = vgui.Create("DTextEntry", self.Frame)
	Text:SetPos(15, 330)
	Text:SetSize(self.PanelWidth - 30, 80)
	Text:SetAllowNonAsciiCharacters(true)
	Text:SetMultiline(true)
	Text:SetText(TicketSystem_Language:GetPhrase("MESSAGE").."..")
	Text.OldMousePressed = Text.OnMousePressed
	function Text:OnMousePressed(...)
		self:OldMousePressed(...)
		if (self:GetValue() == (TicketSystem_Language:GetPhrase("MESSAGE").."..")) then
			self:SetValue("")
		end
	end
	MG_Theme.Theme.TextEntry.Setup(Text)
	local Create = vgui.Create("DButton", self.Frame)
	Create:SetSize(self.PanelWidth - 30, 35)
	Create:SetPos(15, 415)
	Create:SetText(TicketSystem_Language:GetPhrase("MESSAGE_ON_TICKET"))
	MG_Theme.Theme.Button.SetupTheme(Create)
	Create:SetTextColor(MG_Theme.Theme:GetSuccessColor())
	Create:SetTextColor(MG_Theme.Theme:GetSuccessColor())
	Create.DoClick = function()
		local text = Text:GetValue()
		if #text < TicketSystem_Config.MinMessageChars or text == TicketSystem_Language:GetPhrase("MESSAGE")..".." or string.Trim(text) == "" then
			return TicketSystem_Notify:Add(TicketSystem_Language:GetPhrase("INVALID_MESSAGE"), 3000, "DANGER")
		end
		if #text > TicketSystem_Config.MaxMessageChars then
			return TicketSystem_Notify:Add(TicketSystem_Language:GetPhrase("MESSAGE_MAX_CHARS").." "..TicketSystem_Config.MaxMessageChars, 3000, "DANGER")
		end
		Text:SetText(TicketSystem_Language:GetPhrase("MESSAGE").."..")
		local x, y = self.Frame:GetPos()
		self.LastPositions = {x, y}
		net.Start("TicketSystem_CreateTicketAnswer")
			net.WriteString(text)
			net.WriteUInt(self.ID, 32)
		net.SendToServer()
	end
end

function TicketsShowGUI:Close()
	if IsValid(self.Frame) then
		self.Frame:Close()
		if IsValid(self.DermaMenu) then
			self.DermaMenu:Remove()
		end
	end
end

function TicketsShowGUI:Open(ticket)
	if IsValid(self.Frame) then
		self.Frame:Close()
		if IsValid(self.DermaMenu) then
			self.DermaMenu:Remove()
		end
	end
	self:Create(ticket)
	self.Frame:MakePopup()
end

function TicketsShowGUI:AddMessages(messages)
	if IsValid(self.Form) then
		self.Form:Remove()
	end
	for k, v in pairs(self.Forms or {}) do
		v:Remove()
		self.Forms[k] = nil
	end
	local msg_count = #messages
	for i, message in ipairs(messages) do
		local text = message.text
		local steamid = message.steamid
		local Form = self.Scroll:Add("DForm")
		self.Forms = self.Forms or {}
		self.Forms[i] = Form
		Form:Dock(TOP)
		Form:DockMargin(0, 0, 0, 5)
		Form:DockPadding(0, 0, 10, 10)
		Form:SetName(text != "" and TicketSystem_Language:GetPhrase("MESSAGE_BY").." "..message.user.." [#"..msg_count.."]" or TicketSystem_Language:GetPhrase("STATUS_UPDATE").." [#"..msg_count.."]")
		local Date = vgui.Create("DLabel")
		Date:SetAutoStretchVertical(true)
		Date:SetText(os.date("%H:%M, %d.%m.%Y", tonumber(message.date)))
		Date:SetWrap(true)
		Date:SetTextColor(Color(150, 150, 150))
		local Label = vgui.Create("DLabel")
		Label:SetAutoStretchVertical(true)
		local txt = text != "" and text or (steamid == "1" and string.format(TicketSystem_Language:GetPhrase("ACCEPTED_BY"), message.user) or steamid == "2" and string.format(TicketSystem_Language:GetPhrase("CLOSED_BY"), message.user) or string.format(TicketSystem_Language:GetPhrase("REOPENED_BY"), message.user))
		Label:SetText(txt)
		Label:SetWrap(true)
		Label:SetTooltip(TicketSystem_Language:GetPhrase("CLICK_TO_COPY"))
		Label.DoClick = function()
			SetClipboardText(txt)
			surface.PlaySound("ui/buttonclick.wav")
		end
		if text == "" then
			Form.Header:SetTextColor(MG_Theme.Theme:GetPrimaryColor())
		elseif steamid != self.Ticket.steamid then
			Form.Header:SetTextColor(MG_Theme.Theme:GetAdminColor())
		else
			Form.Header:SetTextColor(MG_Theme.Theme:GetUserColor())
		end
		Form:AddItem(Date)
		Form:AddItem(Label)
		Form.Items[1]:DockPadding(10, 0, 10, 0)
		Form.Items[2]:DockPadding(10, 5, 10, 0)
		Form.Paint = function(s, w, h)
			draw.RoundedBox(0, 0, 0, w, h, Color(0, 0, 0, 200))
		end
		msg_count = msg_count - 1
	end
	AddTicketContent(self)
end

TicketsShowGUI:Init()

function AdminTicketsGUI:Init()
	self.Frame = false
	self.PanelWidth = TicketSystem_Config.AdminWindowSize[1]
	self.PanelHeight = TicketSystem_Config.AdminWindowSize[2]
end

local showclosedtickets = CreateClientConVar("cl_showclosedtickets", 0)
function AdminTicketsGUI:Create()
	local ply = LocalPlayer()
	self.Frame = vgui.Create("DFrame")
	self.Frame:SetSize(self.PanelWidth, self.PanelHeight)
	self.Frame:Center()
	self.Frame:SetTitle(TicketSystem_Language:GetPhrase("ADMIN_TICKETS_TITLE"))
	self.Frame:SetDraggable(true)
	self.Frame.Paint = MG_Theme.Theme.Frame.Paint
	self.Frame.PaintOver = MG_Theme.Theme.Frame.PaintOver
	self.Frame.OnRemove = function()
		net.Start("TicketSystem_CloseMenu")
		net.SendToServer()
	end
	local MenuBar = vgui.Create("DMenuBar", self.Frame)
	MenuBar:DockMargin(-6, -4, -6, 5)
	MG_Theme.Theme.MenuBar.Setup(MenuBar)
	local ListMenu = MenuBar:AddMenu(TicketSystem_Language:GetPhrase("LIST"))
	MG_Theme.Theme.DMenu.Setup(ListMenu)
	local submenu, parent = ListMenu:AddSubMenu(TicketSystem_Language:GetPhrase("SELECT_PAGE"))
	submenu:SetDeleteSelf(false)
	MG_Theme.Theme.DMenu.Setup(submenu)
	parent:SetIcon("icon16/page_copy.png")
	local Frame
	submenu:AddOption(TicketSystem_Language:GetPhrase("SELECT_PAGE").."...", function()
		if IsValid(Frame) then Frame:Close() end
		Frame = vgui.Create("DFrame")
		Frame:SetSize(200, 120)
		Frame:Center()
		Frame:SetTitle(TicketSystem_Language:GetPhrase("SELECT_PAGE"))
		Frame:SetDraggable(true)
		Frame.Paint = MG_Theme.Theme.Frame.Paint
		Frame.PaintOver = MG_Theme.Theme.Frame.PaintOver
		Frame.Think = function()
			if !IsValid(AdminTicketsGUI.Frame) then
				Frame:Close()
			end
		end
		Frame:MakePopup()
		local Page = vgui.Create("DTextEntry", Frame)
		Page:SetPos(15, 35)
		Page:SetSize(170, 30)
		Page:SetNumeric(true)
		MG_Theme.Theme.TextEntry.Setup(Page)
		local Load = vgui.Create("DButton", Frame)
		Load:SetSize(170, 30)
		Load:SetPos(15, 70)
		Load:SetText(TicketSystem_Language:GetPhrase("LOAD_PAGE"))
		Load.DoClick = function()
			Frame:Close()
			self.TicketData = {}
			self.TicketList:Clear()
			TicketSystem.UpdateTickets(tonumber(Page:GetValue()))
			Frame:Close()
		end
		MG_Theme.Theme.Button.SetupTheme(Load)
	end):SetIcon("icon16/folder.png")
	submenu:AddSpacer()
	for i=1, 10 do
		submenu:AddOption(TicketSystem_Language:GetPhrase("PAGE").." "..i, function()
			self.TicketData = {}
			self.TicketList:Clear()
			TicketSystem.UpdateTickets(i)
		end):SetIcon("icon16/page.png")
	end
	ListMenu:AddOption(TicketSystem_Language:GetPhrase("REFRESH"), function()
		self.TicketData = {}
		self.TicketList:Clear()
		TicketSystem.UpdateTickets(self.Page)
	end):SetIcon("icon16/database_refresh.png")
	local closed = showclosedtickets:GetBool()
	ListMenu:AddOption(closed and TicketSystem_Language:GetPhrase("HIDE_CLOSED_TICKETS") or TicketSystem_Language:GetPhrase("SHOW_CLOSED_TICKETS"), function(s)
		self.TicketData = {}
		self.TicketList:Clear()
		closed = showclosedtickets:GetBool()
		TicketSystem.UpdateTickets(self.Page, !closed)
		s:SetText(!closed and TicketSystem_Language:GetPhrase("HIDE_CLOSED_TICKETS") or TicketSystem_Language:GetPhrase("SHOW_CLOSED_TICKETS"))
		RunConsoleCommand("cl_showclosedtickets", closed == true and 0 or 1)
	end):SetIcon("icon16/eye.png")
	if TicketSystem:IsManager(ply) then
		local Manage = MenuBar:AddMenu(TicketSystem_Language:GetPhrase("MANAGE"))
		MG_Theme.Theme.DMenu.Setup(Manage)
		Manage:AddOption(TicketSystem_Language:GetPhrase("CLOSE_ALL_TICKETS"), function()
			net.Start("TicketSystem_Admin_CloseTickets")
			net.SendToServer()
		end):SetIcon("icon16/lock.png")
		local Frame
		Manage:AddOption(TicketSystem_Language:GetPhrase("DELETE_ALL_TICKETS"), function()
			if IsValid(Frame) then Frame:Close() end
			Frame = vgui.Create("DFrame")
			Frame:SetSize(200, 120)
			Frame:Center()
			Frame:SetTitle(TicketSystem_Language:GetPhrase("TICKETS_RESET"))
			Frame:SetDraggable(true)
			Frame.Paint = MG_Theme.Theme.Frame.Paint
			Frame.PaintOver = MG_Theme.Theme.Frame.PaintOver
			Frame.Think = function()
				if !IsValid(AdminTicketsGUI.Frame) then
					Frame:Close()
				end
			end
			Frame:MakePopup()
			local Tickets = vgui.Create("DLabel", Frame)
			Tickets:SetText(TicketSystem_Language:GetPhrase("TICKETS_CONFIRM_RESET"))
			Tickets:SetTextColor(Color(170, 170, 170))
			Tickets:SetPos(20, 35)
			Tickets:SetSize(180, 30)
			local Reset = vgui.Create("DButton", Frame)
			Reset:SetSize(170, 30)
			Reset:SetPos(15, 70)
			Reset:SetText(TicketSystem_Language:GetPhrase("RESET"))
			Reset.DoClick = function()
				Frame:Close()
				self.TicketData = {}
				self.TicketList:Clear()
				net.Start("TicketSystem_Admin_DeleteTickets")
				net.SendToServer()
			end
			MG_Theme.Theme.Button.SetupTheme(Reset)
		end):SetIcon("icon16/delete.png")
	end
	if TicketSystem:IsSuperAdmin(ply) then
		local Stats = MenuBar:AddMenu(TicketSystem_Language:GetPhrase("STATS"))
		MG_Theme.Theme.DMenu.Setup(Stats)
		Stats:AddOption(TicketSystem_Language:GetPhrase("SHOW"), function()
			AdminStatsGUI:Open()
		end):SetIcon("icon16/chart_bar.png")
	end
	local x, y = (self.PanelWidth - 10) * 0.8 + 15, 50
	local PanelWidth = (self.PanelWidth - 10) * 0.4
	local TitleLabel = vgui.Create("DLabel", self.Frame)
	TitleLabel:SetText(TicketSystem_Language:GetPhrase("TICKET_TITLE")..":")
	TitleLabel:SetPos(x, y)
	local Title = vgui.Create("DLabel", self.Frame)
	Title:SetText("")
	Title:SetPos(x, y + 15)
	Title:SetSize(PanelWidth, 20)
	Title:SetTextColor(Color(230, 230, 230))
	local CategoryLabel = vgui.Create("DLabel", self.Frame)
	CategoryLabel:SetText(TicketSystem_Language:GetPhrase("TICKET_CATEGORY")..":")
	CategoryLabel:SetPos(x, y + 35)
	local Category = vgui.Create("DLabel", self.Frame)
	Category:SetText("")
	Category:SetPos(x, y + 50)
	Category:SetSize(PanelWidth, 20)
	Category:SetTextColor(Color(230, 230, 230))
	local UserLabel = vgui.Create("DLabel", self.Frame)
	UserLabel:SetText(TicketSystem_Language:GetPhrase("TICKET_USER")..":")
	UserLabel:SetPos(x, y + 70)
	local User = vgui.Create("DLabel", self.Frame)
	User:SetText("")
	User:SetPos(x, y + 85)
	User:SetSize(PanelWidth, 20)
	User:SetTextColor(Color(230, 230, 230))
	local DateLabel = vgui.Create("DLabel", self.Frame)
	DateLabel:SetText(TicketSystem_Language:GetPhrase("TICKET_DATE")..":")
	DateLabel:SetPos(x, y + 105)
	local Date = vgui.Create("DLabel", self.Frame)
	Date:SetText("")
	Date:SetPos(x, y + 120)
	Date:SetSize(PanelWidth, 20)
	Date:SetTextColor(Color(230, 230, 230))
	local StateLabel = vgui.Create("DLabel", self.Frame)
	StateLabel:SetText(TicketSystem_Language:GetPhrase("TICKET_STATE")..":")
	StateLabel:SetPos(x, y + 140)
	local State = vgui.Create("DLabel", self.Frame)
	State:SetText("")
	State:SetPos(x, y + 155)
	State:SetSize(PanelWidth, 20)
	State:SetTextColor(Color(230, 230, 230))
	local AdminLabel = vgui.Create("DLabel", self.Frame)
	AdminLabel:SetText(TicketSystem_Language:GetPhrase("TICKET_ADMIN")..":")
	AdminLabel:SetPos(x, y + 175)
	local Admin = vgui.Create("DLabel", self.Frame)
	Admin:SetText("")
	Admin:SetPos(x, y + 190)
	Admin:SetSize(PanelWidth, 20)
	Admin:SetTextColor(Color(230, 230, 230))
	local Tickets = vgui.Create("DLabel", self.Frame)
	self.TicketsLabel = Tickets
	Tickets:SetText(TicketSystem_Language:GetPhrase("TICKETS")..": ?")
	Tickets:SetPos(x, self.PanelHeight - 40)
	Tickets:SetSize(PanelWidth, 20)
	Tickets:SetTextColor(Color(230, 230, 230))
	local Page = vgui.Create("DLabel", self.Frame)
	self.PageLabel = Page
	Page:SetText(TicketSystem_Language:GetPhrase("PAGE")..": ?")
	Page:SetPos(x, self.PanelHeight - 25)
	Page:SetSize(PanelWidth, 20)
	Page:SetTextColor(Color(230, 230, 230))
	PanelWidth = PanelWidth - 15
	local TicketList = vgui.Create("DListView", self.Frame)
	self.TicketList = TicketList
	TicketList:AddColumn("ID"):SetFixedWidth(50)
	TicketList:AddColumn(TicketSystem_Language:GetPhrase("TICKET_TITLE")):SetFixedWidth(131)
	TicketList:AddColumn(TicketSystem_Language:GetPhrase("TICKET_STATE")):SetFixedWidth(80)
	TicketList:AddColumn(TicketSystem_Language:GetPhrase("TICKET_CATEGORY")):SetFixedWidth(90)
	TicketList:AddColumn(TicketSystem_Language:GetPhrase("TICKET_USER")):SetFixedWidth(160)
	TicketList:AddColumn(TicketSystem_Language:GetPhrase("TICKET_DATE")):SetFixedWidth(120)
	TicketList:SetSize((self.PanelWidth - 10) * 0.8, self.PanelHeight - 75)
	TicketList:Dock(LEFT)
	TicketList:SetMultiSelect(false)
	self.TicketData = {}

	function TicketList:OnRowRightClick(id, panel)
		local id = tonumber(panel:GetColumnText(1))
		local tdata = AdminTicketsGUI.TicketData[id]
		local status = tonumber(tdata.status)
		local new = status == 1
		local menu = DermaMenu(self)
		AdminTicketsGUI.DermaMenu = menu
		AdminTicketsGUI.DermaID = id
		MG_Theme.Theme.DMenu.Setup(menu)
		menu:AddOption(new and TicketSystem_Language:GetPhrase("ACCEPT_TICKET") or TicketSystem_Language:GetPhrase("OPEN_TICKET"), function()
			if new then
				net.Start("TicketSystem_Admin_AcceptTicket")
					net.WriteUInt(id, 32)
				net.SendToServer()
			end
			AdminShowGUI:Open(tdata)
			net.Start("TicketSystem_UpdateMessages")
				net.WriteUInt(id, 32)
			net.SendToServer()
		end):SetIcon(new and "icon16/accept.png" or "icon16/information.png")
		if new then
			menu:AddOption(TicketSystem_Language:GetPhrase("OPEN_TICKET"), function()
				AdminShowGUI:Open(tdata)
				net.Start("TicketSystem_UpdateMessages")
					net.WriteUInt(id, 32)
				net.SendToServer()
			end):SetIcon("icon16/information.png")
		end
		if status == 2 or status == 3 then
			menu:AddOption(TicketSystem_Language:GetPhrase("REOPEN_TICKET"), function()
				net.Start("TicketSystem_Admin_ReopenTicket")
					net.WriteUInt(id, 32)
				net.SendToServer()
			end):SetIcon("icon16/lock_open.png")
		end
		if status == 1 or status == 2 then
			menu:AddOption(TicketSystem_Language:GetPhrase("CLOSE_TICKET"), function()
				net.Start("TicketSystem_Admin_CloseTicket")
					net.WriteUInt(id, 32)
				net.SendToServer()
			end):SetIcon("icon16/lock.png")
		end
		if TicketSystem:IsSuperAdmin(ply) then
			local submenu, parent = menu:AddSubMenu(TicketSystem_Language:GetPhrase("MANAGE"))
			MG_Theme.Theme.DMenu.Setup(submenu)
			parent:SetIcon("icon16/cog.png")
			submenu:AddOption(TicketSystem_Language:GetPhrase("DELETE"), function()
				net.Start("TicketSystem_Admin_DeleteTicket")
					net.WriteUInt(id, 32)
				net.SendToServer()
			end):SetIcon("icon16/delete.png")
			submenu:AddSpacer()
			local steamid = tdata.steamid
			if status == 1 or status == 2 then
				local Frame
				submenu:AddOption(TicketSystem_Language:GetPhrase("CLOSE_TICKETS_USER"), function()
					if IsValid(Frame) then Frame:Close() end
					Frame = vgui.Create("DFrame")
					Frame:SetSize(225, 120)
					Frame:Center()
					Frame:SetTitle(TicketSystem_Language:GetPhrase("TICKETS_CLOSE"))
					Frame:SetDraggable(true)
					Frame.Paint = MG_Theme.Theme.Frame.Paint
					Frame.PaintOver = MG_Theme.Theme.Frame.PaintOver
					Frame.Think = function()
						if !IsValid(AdminTicketsGUI.Frame) then
							Frame:Close()
						end
					end
					Frame:MakePopup()
					local Tickets = vgui.Create("DLabel", Frame)
					Tickets:SetText(TicketSystem_Language:GetPhrase("TICKETS_CONFIRM_CLOSE"))
					Tickets:SetTextColor(Color(170, 170, 170))
					Tickets:SetPos(24, 35)
					Tickets:SetSize(195, 30)
					local Close = vgui.Create("DButton", Frame)
					Close:SetSize(195, 30)
					Close:SetPos(15, 70)
					Close:SetText(TicketSystem_Language:GetPhrase("DELETE"))
					Close.DoClick = function()
						Frame:Close()
						net.Start("TicketSystem_Admin_CloseTickets_User")
							net.WriteString(steamid)
						net.SendToServer()
					end
					MG_Theme.Theme.Button.SetupTheme(Close)
				end):SetIcon("icon16/lock_delete.png")
			end
			local Frame
			submenu:AddOption(TicketSystem_Language:GetPhrase("DELETE_TICKETS_USER"), function()
				if IsValid(Frame) then Frame:Close() end
				Frame = vgui.Create("DFrame")
				Frame:SetSize(215, 120)
				Frame:Center()
				Frame:SetTitle(TicketSystem_Language:GetPhrase("TICKETS_DELETE"))
				Frame:SetDraggable(true)
				Frame.Paint = MG_Theme.Theme.Frame.Paint
				Frame.PaintOver = MG_Theme.Theme.Frame.PaintOver
				Frame.Think = function()
					if !IsValid(AdminTicketsGUI.Frame) then
						Frame:Close()
					end
				end
				Frame:MakePopup()
				local Tickets = vgui.Create("DLabel", Frame)
				Tickets:SetText(TicketSystem_Language:GetPhrase("TICKETS_CONFIRM_DELETE"))
				Tickets:SetTextColor(Color(170, 170, 170))
				Tickets:SetPos(22, 35)
				Tickets:SetSize(195, 30)
				local Delete = vgui.Create("DButton", Frame)
				Delete:SetSize(185, 30)
				Delete:SetPos(15, 70)
				Delete:SetText(TicketSystem_Language:GetPhrase("DELETE"))
				Delete.DoClick = function()
					Frame:Close()
					net.Start("TicketSystem_Admin_DeleteTickets_User")
						net.WriteString(steamid)
					net.SendToServer()
				end
				MG_Theme.Theme.Button.SetupTheme(Delete)
			end):SetIcon("icon16/exclamation.png")
		end
		local submenu, parent = menu:AddSubMenu(TicketSystem_Language:GetPhrase("ACTION"))
		MG_Theme.Theme.DMenu.Setup(submenu)
		parent:SetIcon("icon16/attach.png")
		submenu:AddOption(TicketSystem_Language:GetPhrase("COPY_STEAMID"), function()
			SetClipboardText(tdata.steamid)
			ply:ChatPrint(TicketSystem_Language:GetPhrase("COPIED_STEAMID"))
		end):SetIcon("icon16/cut_red.png")
		submenu:AddSpacer()
		if TicketSystem_Config.FSpectate then
			submenu:AddOption(TicketSystem_Language:GetPhrase("FADMIN_SPECTATE"), function()
				local ply2 = TicketSystem:GetUserBySteamID(tdata.steamid)
				if IsValid(ply2) then
					RunConsoleCommand("ulx", "fspectate", ply2:Name())
				else
					ply:ChatPrint(TicketSystem_Language:GetPhrase("NOT_AVAILABLE"))
				end
			end):SetIcon("icon16/eye.png")
		end
		if TicketSystem_Config.ULX_Commands then
			submenu:AddOption(TicketSystem_Language:GetPhrase("ULX_BRING"), function()
				local ply2 = TicketSystem:GetUserBySteamID(tdata.steamid)
				if IsValid(ply2) then
					RunConsoleCommand("ulx", "bring", ply2:Name())
				else
					ply:ChatPrint(TicketSystem_Language:GetPhrase("NOT_AVAILABLE"))
				end
			end):SetIcon("icon16/arrow_in.png")
			submenu:AddOption(TicketSystem_Language:GetPhrase("ULX_GOTO"), function()
				local ply2 = TicketSystem:GetUserBySteamID(tdata.steamid)
				if IsValid(ply2) then
					RunConsoleCommand("ulx", "goto", ply2:Name())
				else
					ply:ChatPrint(TicketSystem_Language:GetPhrase("NOT_AVAILABLE"))
				end
			end):SetIcon("icon16/arrow_out.png")
			submenu:AddOption(TicketSystem_Language:GetPhrase("ULX_RETURN"), function()
				local ply2 = TicketSystem:GetUserBySteamID(tdata.steamid)
				if IsValid(ply2) then
					RunConsoleCommand("ulx", "return", ply2:Name())
				else
					ply:ChatPrint(TicketSystem_Language:GetPhrase("NOT_AVAILABLE"))
				end
			end):SetIcon("icon16/arrow_undo.png")
			submenu:AddOption(TicketSystem_Language:GetPhrase("ULX_FREEZE"), function()
				local ply2 = TicketSystem:GetUserBySteamID(tdata.steamid)
				if IsValid(ply2) then
					if ply2:IsFlagSet(FL_FROZEN) then
						RunConsoleCommand("ulx", "unfreeze", ply2:Name())
					else
						RunConsoleCommand("ulx", "freeze", ply2:Name())
					end
				else
					ply:ChatPrint(TicketSystem_Language:GetPhrase("NOT_AVAILABLE"))
				end
			end):SetIcon("icon16/clock.png")
		end
		menu.Paint = MG_Theme.Theme.DMenu.Paint
		menu:Open()
	end

	function TicketList:DoDoubleClick(id, panel)
		local id = tonumber(panel:GetColumnText(1))
		local tdata = AdminTicketsGUI.TicketData[id]
		AdminShowGUI:Open(tdata)
		net.Start("TicketSystem_UpdateMessages")
			net.WriteUInt(id, 32)
		net.SendToServer()
	end

	function TicketList:OnRowSelected(id, panel)
		local tdata = panel and AdminTicketsGUI.TicketData[tonumber(panel:GetColumnText(1))]
		AdminTicketsGUI.Selected = tdata and tdata.id
		Title:SetText(tdata and tdata.title or "")
		Category:SetText(tdata and tdata.category or "")
		Date:SetText(tdata and os.date("%H:%M, %d.%m.%Y", tonumber(tdata.date)) or "")
		Admin:SetText(tdata and tdata.admin or "")
		User:SetText(tdata and tdata.user or "")
		local state = tdata and tonumber(tdata.status)
		local color = state and MG_Theme.Theme:GetStatusColor(state)
		State:SetText(state and (TicketSystem_Config.TicketStatus[state] or TicketSystem_Language:GetPhrase("UNKNOWN")) or "")
		if color then
			State:SetTextColor(color)
		end
	end

	MG_Theme.Theme.ListView.SetupTheme(TicketList)
end

function AdminTicketsGUI:Close()
	if IsValid(self.Frame) then
		self.Frame:Close()
		if IsValid(self.DermaMenu) then
			self.DermaMenu:Remove()
		end
	end
end

function AdminTicketsGUI:Open()
	if IsValid(self.Frame) then
		self.Frame:Close()
		if IsValid(self.DermaMenu) then
			self.DermaMenu:Remove()
		end
	end
	self:Create()
	self.Frame:MakePopup()
end

function AdminTicketsGUI:UpdateTickets(tickets, page)
	if !IsValid(self.TicketList) then return end
	self.TicketData = {}
	self.TicketList:Clear()
	local ply = LocalPlayer()
	for _, ticket in pairs(tickets) do
		local id = ticket.id
		local state = tonumber(ticket.status)
		local color = MG_Theme.Theme:GetStatusColor(state)
		local title = ticket.title
		local line = self.TicketList:AddLine(id, title, TicketSystem_Config.TicketStatus[state] or TicketSystem_Language:GetPhrase("UNKNOWN"), ticket.category, ticket.user, os.date("%H:%M, %d.%m.%Y", tonumber(ticket.date)))
		line:SetColumnColor(3, color)
		line:SetTooltip(title)
		if ticket.admin_steamid == ply:SteamID() then
			line.BackgroundColor = MG_Theme.Theme:GetPrimaryColor(30)
		end
		self.TicketData[tonumber(id)] = ticket
	end
	self.PageLabel:SetText(TicketSystem_Language:GetPhrase("PAGE")..": "..string.Comma(page))
	self.TicketsLabel:SetText(TicketSystem_Language:GetPhrase("TICKETS")..": "..string.Comma(table.Count(tickets)))
	MG_Theme.Theme.ListView.SetupTheme(self.TicketList)
end

function AdminTicketsGUI:UpdateMenu(typ, data)
	if !IsValid(self.Frame) then return end
	if typ == 1 and self.TicketData then
		local id = data.id
		local state = tonumber(data.status)
		local color = MG_Theme.Theme:GetStatusColor(state)
		local line = self.TicketList:AddLine(id, data.title, TicketSystem_Config.TicketStatus[state] or TicketSystem_Language:GetPhrase("UNKNOWN"), data.category, data.user, os.date("%H:%M, %d.%m.%Y", tonumber(data.date)))
		line:SetColumnColor(3, color)
		self.TicketData[tonumber(id)] = data
		MG_Theme.Theme.ListView.SetupTheme(self.TicketList)
	elseif typ == 4 then
		local id = tonumber(data.id)
		if self.TicketData and self.TicketData[id] then
			self.TicketData[id]["status"] = 0
		end
	end
end

AdminTicketsGUI:Init()

function AdminShowGUI:Init()
	self.Frame = self.Frame or false
	self.PanelWidth = TicketSystem_Config.AdminTicketWindowSize[1]
	self.PanelHeight = TicketSystem_Config.AdminTicketWindowSize[2]
end

local function AddTicketContent(self)
	local txt = self.Ticket.text
	local Form = self.Scroll:Add("DForm")
	self.Form = Form
	Form:Dock(TOP)
	Form:DockMargin(0, 0, 0, 10)
	Form:DockPadding(0, 0, 10, 10)
	Form:SetName(TicketSystem_Language:GetPhrase("TICKET_BY").." "..self.Ticket.user)
	local Date = vgui.Create("DLabel")
	Date:SetAutoStretchVertical(true)
	Date:SetText(os.date("%H:%M, %d.%m.%Y", tonumber(self.Ticket.date)))
	Date:SetWrap(true)
	Date:SetTextColor(Color(150, 150, 150))
	local Label = vgui.Create("DLabel")
	Label:SetAutoStretchVertical(true)
	Label:SetText(txt)
	Label:SetWrap(true)
	Label:SetTooltip(TicketSystem_Language:GetPhrase("CLICK_TO_COPY"))
	Label.DoClick = function()
		SetClipboardText(txt)
		surface.PlaySound("ui/buttonclick.wav")
	end
	Form.Header:SetTextColor(MG_Theme.Theme:GetUserColor())
	Form:AddItem(Date)
	Form:AddItem(Label)
	Form.Items[1]:DockPadding(10, 0, 10, 0)
	Form.Items[2]:DockPadding(10, 5, 10, 0)
	Form.Paint = function(s, w, h)
		draw.RoundedBox(0, 0, 0, w, h, Color(0, 0, 0, 200))
	end
end

function AdminShowGUI:AddMenuBar(ticket)
	if IsValid(self.MenuBar) then
		self.MenuBar:Remove()
	end
	local MenuBar = vgui.Create("DMenuBar", self.Frame)
	self.MenuBar = MenuBar
	MenuBar:DockMargin(-6, -4, -6, 10)
	MG_Theme.Theme.MenuBar.Setup(MenuBar)
	local TicketMenu = MenuBar:AddMenu(TicketSystem_Language:GetPhrase("TICKET"))
	MG_Theme.Theme.DMenu.Setup(TicketMenu)
	local status = tonumber(ticket.status)
	local new = status == 1
	if new then
		TicketMenu:AddOption(TicketSystem_Language:GetPhrase("ACCEPT_TICKET"), function()
			net.Start("TicketSystem_Admin_AcceptTicket")
				net.WriteUInt(self.ID, 32)
			net.SendToServer()
		end):SetIcon("icon16/accept.png")
	end
	if status == 2 or status == 3 then
		TicketMenu:AddOption(TicketSystem_Language:GetPhrase("REOPEN_TICKET"), function()
			net.Start("TicketSystem_Admin_ReopenTicket")
				net.WriteUInt(self.ID, 32)
			net.SendToServer()
		end):SetIcon("icon16/lock_open.png")
	end
	if status == 1 or status == 2 then
		TicketMenu:AddOption(TicketSystem_Language:GetPhrase("CLOSE_TICKET"), function()
			net.Start("TicketSystem_Admin_CloseTicket")
				net.WriteUInt(self.ID, 32)
			net.SendToServer()
		end):SetIcon("icon16/lock.png")
	end
	local actions = MenuBar:AddMenu(TicketSystem_Language:GetPhrase("ACTION"))
	MG_Theme.Theme.DMenu.Setup(actions)
	actions:AddOption(TicketSystem_Language:GetPhrase("COPY_STEAMID"), function()
		SetClipboardText(ticket.steamid)
		LocalPlayer():ChatPrint(TicketSystem_Language:GetPhrase("COPIED_STEAMID"))
	end):SetIcon("icon16/cut_red.png")
	actions:AddSpacer()
	if TicketSystem_Config.FSpectate then
		actions:AddOption(TicketSystem_Language:GetPhrase("FADMIN_SPECTATE"), function()
			local ply2 = TicketSystem:GetUserBySteamID(ticket.steamid)
			if IsValid(ply2) then
				RunConsoleCommand("ulx", "fspectate", ply2:Name())
			else
				LocalPlayer():ChatPrint(TicketSystem_Language:GetPhrase("NOT_AVAILABLE"))
			end
		end):SetIcon("icon16/eye.png")
	end
	if TicketSystem_Config.ULX_Commands then
		actions:AddOption(TicketSystem_Language:GetPhrase("ULX_BRING"), function()
			local ply = TicketSystem:GetUserBySteamID(ticket.steamid)
			if IsValid(ply) then
				RunConsoleCommand("ulx", "bring", ply:Name())
			else
				LocalPlayer():ChatPrint(TicketSystem_Language:GetPhrase("NOT_AVAILABLE"))
			end
		end):SetIcon("icon16/arrow_in.png")
		actions:AddOption(TicketSystem_Language:GetPhrase("ULX_GOTO"), function()
			local ply = TicketSystem:GetUserBySteamID(ticket.steamid)
			if IsValid(ply) then
				RunConsoleCommand("ulx", "goto", ply:Name())
			else
				LocalPlayer():ChatPrint(TicketSystem_Language:GetPhrase("NOT_AVAILABLE"))
			end
		end):SetIcon("icon16/arrow_out.png")
		actions:AddOption(TicketSystem_Language:GetPhrase("ULX_RETURN"), function()
			local ply = TicketSystem:GetUserBySteamID(ticket.steamid)
			if IsValid(ply) then
				RunConsoleCommand("ulx", "return", ply:Name())
			else
				LocalPlayer():ChatPrint(TicketSystem_Language:GetPhrase("NOT_AVAILABLE"))
			end
		end):SetIcon("icon16/arrow_undo.png")
		actions:AddOption(TicketSystem_Language:GetPhrase("ULX_FREEZE"), function()
			local ply = TicketSystem:GetUserBySteamID(ticket.steamid)
			if IsValid(ply) then
				if ply:IsFlagSet(FL_FROZEN) then
					RunConsoleCommand("ulx", "unfreeze", ply:Name())
				else
					RunConsoleCommand("ulx", "freeze", ply:Name())
				end
			else
				LocalPlayer():ChatPrint(TicketSystem_Language:GetPhrase("NOT_AVAILABLE"))
			end
		end):SetIcon("icon16/clock.png")
	end
end

function AdminShowGUI:Create(ticket)
	self:Init()
	self.Ticket = ticket
	self.ID = tonumber(ticket.id)
	self.Frame = vgui.Create("DFrame")
	self.Frame:SetSize(self.PanelWidth, self.PanelHeight)
	if self.LastPositions then
		self.Frame:SetPos(self.LastPositions[1], self.LastPositions[2])
	else
		self.Frame:Center()
	end
	self.Frame:SetTitle(string.format(TicketSystem_Language:GetPhrase("ADMIN_TICKET_TITLE"), ticket.user))
	self.Frame:SetDraggable(true)
	self.Frame.Paint = MG_Theme.Theme.Frame.Paint
	self.Frame.PaintOver = MG_Theme.Theme.Frame.PaintOver
	self.Frame.OnRemove = function()
		net.Start("TicketSystem_CloseInfo")
			net.WriteUInt(self.ID, 32)
		net.SendToServer()
	end
	self:AddMenuBar(ticket)
	local y = 20
	local TitleLabel = vgui.Create("DLabel", self.Frame)
	TitleLabel:SetText(TicketSystem_Language:GetPhrase("TICKET_TITLE")..":")
	TitleLabel:SetPos(15, 30 + y)
	TitleLabel:SetTextColor(Color(170, 170, 170))
	local Title = vgui.Create("DLabel", self.Frame)
	Title:SetText(ticket.title)
	Title:SetPos(15, 45 + y)
	Title:SetTextColor(Color(200, 200, 200))
	Title:SetSize(self.PanelWidth / 2 - 30, 20)
	local CategoryLabel = vgui.Create("DLabel", self.Frame)
	CategoryLabel:SetText(TicketSystem_Language:GetPhrase("TICKET_CATEGORY")..":")
	CategoryLabel:SetPos(15, 65 + y)
	CategoryLabel:SetTextColor(Color(170, 170, 170))
	CategoryLabel:SetSize(self.PanelWidth-40, 20)
	local Category = vgui.Create("DLabel", self.Frame)
	Category:SetText(ticket.category)
	Category:SetPos(15, 80 + y)
	Category:SetTextColor(Color(200, 200, 200))
	Category:SetSize(self.PanelWidth / 2 - 30, 20)
	local StateLabel = vgui.Create("DLabel", self.Frame)
	StateLabel:SetText(TicketSystem_Language:GetPhrase("TICKET_STATE")..":")
	StateLabel:SetPos(220, 30 + y)
	StateLabel:SetTextColor(Color(170, 170, 170))
	StateLabel:SetSize(self.PanelWidth - 40, 20)
	local State = vgui.Create("DLabel", self.Frame)
	self.StateLabel = State
	State:SetText(TicketSystem_Config.TicketStatus[tonumber(ticket.status)] or TicketSystem_Language:GetPhrase("UNKNOWN"))
	State:SetPos(220, 45 + y)
	State:SetTextColor(MG_Theme.Theme:GetStatusColor(tonumber(ticket.status)))
	State:SetSize(self.PanelWidth / 2 - 30, 20)
	local AdminLabel = vgui.Create("DLabel", self.Frame)
	AdminLabel:SetText(TicketSystem_Language:GetPhrase("TICKET_ADMIN")..":")
	AdminLabel:SetPos(220, 65 + y)
	AdminLabel:SetTextColor(Color(170, 170, 170))
	AdminLabel:SetSize(self.PanelWidth - 40, 20)
	local Admin = vgui.Create("DLabel", self.Frame)
	self.AdminLabel = Admin
	Admin:SetText(ticket.admin)
	Admin:SetPos(220, 80 + y)
	Admin:SetTextColor(Color(170, 170, 170))
	Admin:SetSize(self.PanelWidth / 2 - 30, 20)
	local Answers = vgui.Create("DLabel", self.Frame)
	Answers:SetText(TicketSystem_Language:GetPhrase("TICKET_CONTENTS")..":")
	Answers:SetPos(15, 100 + y)
	Answers:SetTextColor(Color(170, 170, 170))
	Answers:SetSize(self.PanelWidth - 40, 20)
	local Scroll = vgui.Create("DScrollPanel", self.Frame)
	self.Scroll = Scroll
	Scroll:SetPos(15, 120 + y)
	Scroll:SetSize(self.PanelWidth - 30, 200)
	MG_Theme.Theme.ScrollBar.Setup(Scroll.VBar)
	AddTicketContent(self)
	local Text = vgui.Create("DTextEntry", self.Frame)
	Text:SetPos(15, 330 + y)
	Text:SetSize(self.PanelWidth - 30, 80)
	Text:SetAllowNonAsciiCharacters(true)
	Text:SetMultiline(true)
	Text:SetText(TicketSystem_Language:GetPhrase("MESSAGE").."..")	
	Text.OldMousePressed = Text.OnMousePressed
	function Text:OnMousePressed(...)
		self:OldMousePressed(...)
		if (self:GetValue() == (TicketSystem_Language:GetPhrase("MESSAGE").."..")) then
			self:SetValue("")
		end
	end
	MG_Theme.Theme.TextEntry.Setup(Text)
	local Create = vgui.Create("DButton", self.Frame)
	Create:SetSize(self.PanelWidth - 30, 35)
	Create:SetPos(15, 415 + y)
	Create:SetText(TicketSystem_Language:GetPhrase("MESSAGE_ON_TICKET"))
	MG_Theme.Theme.Button.SetupTheme(Create)
	Create:SetTextColor(MG_Theme.Theme:GetSuccessColor())
	local Frame = self.Frame
	Create.DoClick = function()
		local text = Text:GetValue()
		if #text < TicketSystem_Config.MinMessageChars or text == TicketSystem_Language:GetPhrase("MESSAGE")..".." or string.Trim(text) == "" then
			return TicketSystem_Notify:Add(TicketSystem_Language:GetPhrase("INVALID_MESSAGE"), 3000, "DANGER")
		end
		if #text > TicketSystem_Config.MaxMessageChars then
			return TicketSystem_Notify:Add(TicketSystem_Language:GetPhrase("MESSAGE_MAX_CHARS").." "..TicketSystem_Config.MaxMessageChars, 3000, "DANGER")
		end
		Text:SetText(TicketSystem_Language:GetPhrase("MESSAGE").."..")
		local x, y = Frame:GetPos()
		self.LastPositions = {x, y}
		net.Start("TicketSystem_Admin_CreateAnswer")
			net.WriteString(text)
			net.WriteUInt(self.ID, 32)
		net.SendToServer()
	end
	local Close = vgui.Create("DButton", self.Frame)
	Close:SetSize(self.PanelWidth - 30, 35)
	Close:SetPos(15, 455 + y)
	Close:SetText(TicketSystem_Language:GetPhrase("CLOSE_TICKET"))
	MG_Theme.Theme.Button.SetupTheme(Close)
	Close:SetTextColor(MG_Theme.Theme:GetDangerColor())
	local Frame = self.Frame
	Close.DoClick = function()
		self:Close()
		net.Start("TicketSystem_Admin_CloseTicket")
			net.WriteUInt(self.ID, 32)
		net.SendToServer()
	end
end

function AdminShowGUI:Close()
	if IsValid(self.Frame) then
		self.Frame:Close()
	end
end

function AdminShowGUI:Open(ticket)
	if IsValid(self.Frame) then
		self.Frame:Close()
	end
	self:Create(ticket)
	self.Frame:MakePopup()
end

function AdminShowGUI:AddMessages(messages)
	if IsValid(self.Form) then
		self.Form:Remove()
	end
	for k, v in pairs(self.Forms or {}) do
		v:Remove()
		self.Forms[k] = nil
	end
	local msg_count = #messages
	for i, message in ipairs(messages) do
		local text = message.text
		local steamid = message.steamid
		local Form = self.Scroll:Add("DForm")
		self.Forms = self.Forms or {}
		self.Forms[i] = Form
		Form:Dock(TOP)
		Form:DockMargin(0, 0, 0, 5)
		Form:DockPadding(0, 0, 10, 10)
		Form:SetName(text != "" and TicketSystem_Language:GetPhrase("MESSAGE_BY").." "..message.user.." [#"..msg_count.."]" or TicketSystem_Language:GetPhrase("STATUS_UPDATE").." [#"..msg_count.."]")
		local Date = vgui.Create("DLabel")
		Date:SetAutoStretchVertical(true)
		Date:SetText(os.date("%H:%M, %d.%m.%Y", tonumber(message.date)))
		Date:SetWrap(true)
		Date:SetTextColor(Color(150, 150, 150))
		local Label = vgui.Create("DLabel")
		Label:SetAutoStretchVertical(true)
		local txt = text != "" and text or (steamid == "1" and string.format(TicketSystem_Language:GetPhrase("ACCEPTED_BY"), message.user) or steamid == "2" and string.format(TicketSystem_Language:GetPhrase("CLOSED_BY"), message.user) or string.format(TicketSystem_Language:GetPhrase("REOPENED_BY"), message.user))
		Label:SetText(txt)
		Label:SetWrap(true)
		Label:SetTooltip(TicketSystem_Language:GetPhrase("CLICK_TO_COPY"))
		Label.DoClick = function()
			SetClipboardText(txt)
			surface.PlaySound("ui/buttonclick.wav")
		end
		if text == "" then
			Form.Header:SetTextColor(MG_Theme.Theme:GetPrimaryColor())
		elseif steamid != self.Ticket.steamid then
			Form.Header:SetTextColor(MG_Theme.Theme:GetAdminColor())
		else
			Form.Header:SetTextColor(MG_Theme.Theme:GetUserColor())
		end
		Form:AddItem(Date)
		Form:AddItem(Label)
		Form.Items[1]:DockPadding(10, 0, 10, 0)
		Form.Items[2]:DockPadding(10, 5, 10, 0)
		Form.Paint = function(s, w, h)
			draw.RoundedBox(0, 0, 0, w, h, Color(0, 0, 0, 200))
		end
		msg_count = msg_count - 1
	end
	AddTicketContent(self)
end

AdminShowGUI:Init()

function AdminStatsGUI:Init()
	self.Frame = self.Frame or false
	self.PanelWidth = TicketSystem_Config.StatsWindowSize[1]
	self.PanelHeight = TicketSystem_Config.StatsWindowSize[2]
end

function AdminStatsGUI:Create()
	self.Frame = vgui.Create("DFrame")
	self.Frame:SetSize(self.PanelWidth, self.PanelHeight)
	self.Frame:Center()
	self.Frame:SetTitle(TicketSystem_Language:GetPhrase("STATS_TITLE"))
	self.Frame:SetDraggable(true)
	self.Frame.Paint = MG_Theme.Theme.Frame.Paint
	self.Frame.PaintOver = MG_Theme.Theme.Frame.PaintOver
	local UserList = vgui.Create("DListView", self.Frame)
	self.UserList = UserList
	UserList:AddColumn(TicketSystem_Language:GetPhrase("STATS_PICTURE")):SetFixedWidth(45)
	UserList:AddColumn("ID"):SetFixedWidth(50)
	UserList:AddColumn(TicketSystem_Language:GetPhrase("STATS_USER"))
	UserList:AddColumn(TicketSystem_Language:GetPhrase("STATS_ACCEPTED")):SetFixedWidth(100)
	UserList:AddColumn(TicketSystem_Language:GetPhrase("STATS_LAST_ACTION")):SetFixedWidth(100)
	UserList:Dock(FILL)
	UserList:SetMultiSelect(false)

	function UserList:DoDoubleClick(id, panel)
		local steamid = AdminStatsGUI.Lines[panel]
		gui.OpenURL("https://steamcommunity.com/profiles/"..util.SteamIDTo64(steamid))
	end

	function UserList:OnRowRightClick(id, panel)
		local menu = DermaMenu(self)
		MG_Theme.Theme.DMenu.Setup(menu)
		local steamid = AdminStatsGUI.Lines[panel]
		menu:AddOption(TicketSystem_Language:GetPhrase("STATS_OPEN_PROFILE"), function()
			gui.OpenURL("https://steamcommunity.com/profiles/"..util.SteamIDTo64(steamid))
		end)
		if TicketSystem:IsManager(LocalPlayer()) then
			menu:AddSpacer()
			local Frame
			menu:AddOption(TicketSystem_Language:GetPhrase("STATS_SET"), function()
				if IsValid(Frame) then Frame:Close() end
				Frame = vgui.Create("DFrame")
				Frame:SetSize(200, 120)
				Frame:Center()
				Frame:SetTitle(TicketSystem_Language:GetPhrase("STATS_SET"))
				Frame:SetDraggable(true)
				Frame.Paint = MG_Theme.Theme.Frame.Paint
				Frame.PaintOver = MG_Theme.Theme.Frame.PaintOver
				Frame.Think = function()
					if !IsValid(AdminStatsGUI.Frame) then
						Frame:Close()
					end
				end
				Frame:MakePopup()
				local Stats = vgui.Create("DTextEntry", Frame)
				Stats:SetPos(15, 35)
				Stats:SetSize(170, 30)
				Stats:SetNumeric(true)
				MG_Theme.Theme.TextEntry.Setup(Stats)
				local Set = vgui.Create("DButton", Frame)
				Set:SetSize(170, 30)
				Set:SetPos(15, 70)
				Set:SetText(TicketSystem_Language:GetPhrase("SET"))
				Set.DoClick = function()
					local value = tonumber(Stats:GetValue())
					local gui = AdminStatsGUI
					if IsValid(gui) then
						for k, v in ipairs(gui.Stats or {}) do
							if v.steamid == steamid then
								gui.Stats[k]["tickets_accepted"] = value
							end
						end
						gui:UpdateStats(gui.Stats)
					end
					net.Start("TicketSystem_Admin_SetStat")
						net.WriteString(steamid)
						net.WriteUInt(value, 32)
					net.SendToServer()
					Frame:Close()
				end
				MG_Theme.Theme.Button.SetupTheme(Set)
			end)
			local Frame
			menu:AddOption(TicketSystem_Language:GetPhrase("STATS_DELETE"), function()
				if IsValid(Frame) then Frame:Close() end
				Frame = vgui.Create("DFrame")
				Frame:SetSize(200, 120)
				Frame:Center()
				Frame:SetTitle(TicketSystem_Language:GetPhrase("STATS_DELETE"))
				Frame:SetDraggable(true)
				Frame.Paint = MG_Theme.Theme.Frame.Paint
				Frame.PaintOver = MG_Theme.Theme.Frame.PaintOver
				Frame.Think = function()
					if !IsValid(AdminStatsGUI.Frame) then
						Frame:Close()
					end
				end
				Frame:MakePopup()
				local Stats = vgui.Create("DLabel", Frame)
				Stats:SetText(TicketSystem_Language:GetPhrase("STATS_CONFIRM_DELETE"))
				Stats:SetTextColor(Color(170, 170, 170))
				Stats:SetPos(25, 35)
				Stats:SetSize(170, 30)
				local Delete = vgui.Create("DButton", Frame)
				Delete:SetSize(170, 30)
				Delete:SetPos(15, 70)
				Delete:SetText(TicketSystem_Language:GetPhrase("DELETE"))
				Delete.DoClick = function()
					local gui = AdminStatsGUI
					if IsValid(gui) then
						for k, v in ipairs(gui.Stats or {}) do
							if v.steamid == steamid then
								table.remove(gui.Stats, k)
								break
							end
						end
						gui:UpdateStats(gui.Stats)
					end
					net.Start("TicketSystem_Admin_DeleteStat")
						net.WriteString(steamid)
					net.SendToServer()
					Frame:Close()
				end
				MG_Theme.Theme.Button.SetupTheme(Delete)
			end)
			menu:AddSpacer()
			local Frame
			menu:AddOption(TicketSystem_Language:GetPhrase("STATS_RESET_ALL"), function()
				if IsValid(Frame) then Frame:Close() end
				Frame = vgui.Create("DFrame")
				Frame:SetSize(230, 120)
				Frame:Center()
				Frame:SetTitle(TicketSystem_Language:GetPhrase("STATS_RESET"))
				Frame:SetDraggable(true)
				Frame.Paint = MG_Theme.Theme.Frame.Paint
				Frame.PaintOver = MG_Theme.Theme.Frame.PaintOver
				Frame.Think = function()
					if !IsValid(AdminStatsGUI.Frame) then
						Frame:Close()
					end
				end
				Frame:MakePopup()
				local Stats = vgui.Create("DLabel", Frame)
				Stats:SetText(TicketSystem_Language:GetPhrase("STATS_CONFIRM_RESET"))
				Stats:SetTextColor(Color(170, 170, 170))
				Stats:SetPos(25, 35)
				Stats:SetSize(210, 30)
				local Reset = vgui.Create("DButton", Frame)
				Reset:SetSize(200, 30)
				Reset:SetPos(15, 70)
				Reset:SetText(TicketSystem_Language:GetPhrase("RESET"))
				Reset.DoClick = function()
					if IsValid(AdminStatsGUI) then
						AdminStatsGUI:UpdateStats({})
					end
					net.Start("TicketSystem_Admin_DeleteStats")
					net.SendToServer()
					Frame:Close()
				end
				MG_Theme.Theme.Button.SetupTheme(Reset)
			end)
		end
		menu:Open()
	end
	MG_Theme.Theme.ListView.SetupTheme(UserList)
	UserList:SetDataHeight(40)
end

function AdminStatsGUI:UpdateStats(stats)
	self.UserList:Clear()

	table.sort(stats, function(a, b)
		return tonumber(a.date) > tonumber(b.date)
	end)

	self.Lines = {}
	for _, user in ipairs(stats) do
		local sid = user.steamid
		local line = self.UserList:AddLine("", user.id, user.user, string.Comma(user.tickets_accepted), os.date("%H:%M, %d.%m.%Y", tonumber(user.date)))
		local Avatar = vgui.Create("AvatarImage", line.Columns[1])
		Avatar:SetSize(32, 32)
		Avatar:SetPos(4, 4)
		Avatar:SetSteamID(util.SteamIDTo64(sid), 64)
		self.Lines[line] = sid
		self.Stats = stats
	end
	MG_Theme.Theme.ListView.SetupTheme(self.UserList)
	self.UserList:SetDataHeight(40)
end

function AdminStatsGUI:Close()
	if IsValid(self.Frame) then
		self.Frame:Close()
		if IsValid(self.DermaMenu) then
			self.DermaMenu:Remove()
		end
	end
end

function AdminStatsGUI:Open()
	net.Start("TicketSystem_Admin_SendStats")
	net.SendToServer()
	if IsValid(self.Frame) then
		self.Frame:Close()
		if IsValid(self.DermaMenu) then
			self.DermaMenu:Remove()
		end
	end
	self:Create()
	self.Frame:MakePopup()
end

AdminStatsGUI:Init()