local frame
local function OpenLawyerMenu(target)
	if IsValid(frame) then frame:Close() end
	frame = vgui.Create("DFrame")
	frame:SetSize(450, 150)
	frame:MakePopup()
	frame:ShowCloseButton(false)
	frame:SetTitle("Befreie Jemanden gegen Kaution aus dem Gefängnis")
	frame:Center()
	frame.Paint = MG_Theme.Theme.Frame.Paint
	frame.PaintOver = MG_Theme.Theme.Frame.PaintOver
	frame.MenuOpened = CurTime() + 60
	local ply = LocalPlayer()
	frame.Think = function()
		if frame.MenuOpened <= CurTime() or (ply:isArrested() or !ply:Alive() or !IsValid(target) or !target:isArrested() or ply:GetPos():DistToSqr(target:GetPos()) > 65536) then
			frame:Close()
		end
	end
	local Close = vgui.Create("DButton", frame)
	Close:SetSize(50, 20)
	Close:SetPos(frame:GetWide() - 52, 2)
	Close:SetText("X")
	Close:SetFont("MG_Theme_Close")
	Close:SetTextColor(color_white)
	Close.Paint = function(self, w, h)
		local col
		if self:IsHovered() then
			col = Color(255, 100, 100)
		else
			col = Color(200, 50, 50)
		end
		draw.RoundedBox(0, 0, 0, w, h, col)
	end
	Close.DoClick = function()
		surface.PlaySound("ui/buttonclick.wav")
		frame:Remove()
	end
	local p = vgui.Create("DPanel", frame)
	p:Dock(LEFT)
	p:SetContentAlignment(5)
	p:SetWide(110)
	function p:Paint()
	end
	local img = vgui.Create("DImage", p)
	img:SetImage("gui/attorney-legal.png")
	img:SetSize(110, 110)
	local right = vgui.Create("DPanel", frame)
	right:DockMargin(5, 5, 5, 5)
	right:Dock(FILL)
	function right:Paint()
	end
	local title = vgui.Create("DLabel", right)
	title:SetText("Kaution für "..target:Name().. " vorschlagen.")
	title:Dock(TOP)
	title:SizeToContents()
	local number = vgui.Create("DNumSlider", right)
	number:DockMargin(5, 5, 5, 5)
	number:SetText("Kaution: ")
	number:Dock(TOP)
	number:SetDecimals(0)
	number:SetMin(BAIL.MinimumAmount)
	number:SetMax(BAIL.MaximumAmount)
	number:SetValue(BAIL.MinimumAmount)
	local button = vgui.Create("DButton", right)
	button:DockMargin(5, 5, 5, 5)
	button:SetText("Angebot machen")
	MG_Theme.Theme.Button.SetupTheme(button)
	button:Dock(TOP)
	function button:DoClick()
		frame:Close()
		if IsValid(target) then
			surface.PlaySound("ui/buttonclick.wav")
			net.Start("Bail_LawyerOfferBail")
				net.WriteEntity(target)
				net.WriteUInt(number:GetValue(), 32)
			net.SendToServer()
			Derma_Message(target:Name().." hat dein Angebot erhalten. Wenn er es akzeptiert wirst du mit $"..string.Comma(math.floor(number:GetValue())).." für deine Arbeit entlohnt.", "Dein Angebot wurde versendet!")
		end
	end
end

net.Receive("Bail_LawyerOpenBailMenu", function()
	local ply = net.ReadEntity()
	if !IsValid(ply) then return end
	OpenLawyerMenu(ply)
end)

local frame
local function OpenBailMenu(lawyer, amount)
	if IsValid(frame) then frame:Close() end
	frame = vgui.Create("DFrame")
	frame:SetSize(500, 190)
	frame:MakePopup()
	frame:ParentToHUD()
	frame:ShowCloseButton(false)
	frame:SetTitle("Kaution bezahlen")
	frame:Center()
	local ply = LocalPlayer()
	frame.Think = function()
		if !ply:isArrested() or !IsValid(lawyer) or lawyer:isArrested() then
			frame:Close()
		end
	end
	frame.Paint = MG_Theme.Theme.Frame.Paint
	frame.PaintOver = MG_Theme.Theme.Frame.PaintOver
	local Close = vgui.Create("DButton", frame)
	Close:SetSize(50, 20)
	Close:SetPos(frame:GetWide() - 52, 2)
	Close:SetText("X")
	Close:SetFont("MG_Theme_Close")
	Close:SetTextColor(color_white)
	Close.Paint = function(self, w, h)
		local col
		if self:IsHovered() then
			col = Color(255, 100, 100)
		else
			col = Color(200, 50, 50)
		end
		draw.RoundedBox(0, 0, 0, w, h, col)
	end
	Close.DoClick = function()
		surface.PlaySound("ui/buttonclick.wav")
		frame:Remove()
	end
	local p = vgui.Create("DPanel", frame)
	p:Dock(LEFT)
	p:SetContentAlignment(5)
	p:SetWide(110)
	function p:Paint()
	end 
	local img = vgui.Create("DImage", p)
	img:SetImage("gui/attorney-legal.png")
	img:SetSize(110, 110)
	local right = vgui.Create("DPanel", frame)
	right:DockMargin(5, 5, 5, 5)
	right:Dock(FILL)
	function right:Paint()
	end
	local title = vgui.Create("DLabel", right)
	title:SetText("Du hast ein Kautionsangebot von "..lawyer:Name().." erhalten.")
	title:DockMargin(5, 5, 5, 5)
	title:Dock(TOP)
	title:SizeToContents()
	local number = vgui.Create("DLabel", right)
	number:SetText("Kaution: $"..string.Comma(amount).."\nMit Karte: $"..string.Comma(math.Round(amount + (amount * (BAIL.CardFee / 100)))))
	number:DockMargin(5, 0, 5, 5)
	number:Dock(TOP)
	number:SizeToContents()
	local pay = vgui.Create("DButton", right)
	pay:DockMargin(5, 10, 5, 5)
	pay:SetText("Kaution bezahlen")
	MG_Theme.Theme.Button.SetupTheme(pay)
	pay:Dock(TOP)
	function pay:DoClick()
		if ply:canAfford(amount) and IsValid(lawyer) then
			surface.PlaySound("ui/buttonclick.wav")
			frame:Close()
			net.Start("Bail_AcceptBailOffer")
				net.WriteEntity(lawyer)
				net.WriteBool(false)
			net.SendToServer()
		else
			Derma_Message("Du hast nicht genug Geld um die Kaution bezahlen zu können!", "Nicht genug Geld!")
		end
	end
	if !ply:canAfford(amount) then
		pay:SetColor(Color(200, 0, 0, 255))
	end
	if BAIL.CardPay then
		local fee = BAIL.CardFee and BAIL.CardFee != 0 and "(+"..BAIL.CardFee.."%)" 
		local cardpay = vgui.Create("DButton", right)
		cardpay:SetText("Mit Karte zahlen "..fee)
		MG_Theme.Theme.Button.SetupTheme(cardpay)
		cardpay:DockMargin(5, 0, 5, 5)
		cardpay:Dock(TOP)
		function cardpay:DoClick()
			surface.PlaySound("ui/buttonclick.wav")
			frame:Close()
			net.Start("Bail_AcceptBailOffer")
				net.WriteEntity(lawyer)
				net.WriteBool(true)
			net.SendToServer()
		end
	end
	local decline = vgui.Create("DButton", right)
	decline:SetText("Angebot ablehnen")
	MG_Theme.Theme.Button.SetupTheme(decline)
	decline:DockMargin(5, 5, 5, 5)
	decline:Dock(TOP)
	function decline:DoClick()
		frame:Close()
	end
end

net.Receive("Bail_PlayerBailOffer", function()
	local lawyer = net.ReadEntity()
	local amount = net.ReadUInt(32)
	if !IsValid(lawyer) then return end
	OpenBailMenu(lawyer, amount)
end)

local local_ply

local baildistance = BAIL.BailDistance * BAIL.BailDistance
local function DrawArrestedPlayers()
	local_ply = local_ply or LocalPlayer()
	if local_ply:isArrested() then return end
	if (!BAIL.AllowedTeams or BAIL.AllowedTeams[local_ply:Team()] != true) then return end
	local ent = local_ply:GetEyeTrace().Entity
	if IsValid(ent) and ent:IsPlayer() and ent:isArrested() and local_ply:GetPos():DistToSqr(ent:GetPos()) < baildistance then
		local x, y = ScrW() / 2, ScrH() / 2 + 30
		draw.DrawNonParsedText("Drücke E um eine Kaution vorzuschlagen!", "Roboto20", x + 1, y + 1, color_black, 1)
		draw.DrawNonParsedText("Drücke E um eine Kaution vorzuschlagen!", "Roboto20", x, y, Color(0, 153, 0, 255), 1)
	end
end
hook.Add("HUDPaint", "Bail_DrawArrestedPlayers", DrawArrestedPlayers)

local lastKeyPress = 0
hook.Add("KeyPress", "Bail_OpenBailMenu", function(ply, key)
	if key != IN_USE or lastKeyPress > CurTime() - 0.2 then return end
	local_ply = local_ply or LocalPlayer()
	if local_ply:isArrested() then return end
	if (!BAIL.AllowedTeams or BAIL.AllowedTeams[local_ply:Team()] != true) then return end
	lastKeyPress = CurTime()
	local ent = local_ply:GetEyeTrace().Entity
	if !IsValid(ent) or !ent:IsPlayer() or !ent:isArrested() or local_ply:GetPos():DistToSqr(ent:GetPos()) > baildistance then return end
	RunConsoleCommand("darkrp", "kaution")
end)