rank_menu = CreateMenu("Set rank")
function rank_menu:getcustombutton(b)
	local id = player(0,"table")[b]
	if id then return player(id, "name").."|"..SERVER_RANK[USER[id]["rank"]].prefix end
end

function rank_menu:click(id,b,p)
	local p = player(0,"table")[b]
	if p and player(p,"exists") then
		USERTEMP[id]["setrank"] = p
		rank_optionmenu:OpenPlayer(id, 1)
	end
end

rank_optionmenu = CreateMenu("Choose a rank", RankList())
function rank_optionmenu:getcustombutton(b,id,default)
	if default then
		if RankExists(default) then
			return SERVER_RANK[default].prefix.."|Lvl. "..SERVER_RANK[default].lvl
		end
		return ""
	end
end

function rank_optionmenu:click(id,b,page)
	local p = USERTEMP[id]["setrank"]
	if player(p, "exists") then
		local rank_name = RankList()[b]
		if rank_name then
			PlayerSetRank(id, p, rank_name)
		end
	else
		USERTEMP[id]["setrank"] = nil
	end
end

function PlayerSetRank(id,p,rank)
	if not RankExists(rank) then
		return ErrorMSG(id, "This rank does not exist")
	end

	local pr, idr = USER[p]["rank"], USER[id]["rank"]
	if SERVER_RANK[pr].lvl < SERVER_RANK[idr].lvl then
		if SERVER_RANK[rank].lvl < SERVER_RANK[idr].lvl then
			USER[p]["rank"] = rank
			SaveUSER(p)
			
			if SERVER_RANK[pr].lvl < SERVER_RANK[rank].lvl then
				msgc2(id, "You've promoted "..player(p,"name").." to "..SERVER_RANK[rank].prefix, 0, 100, 255)
				msgc2(p, "You've been promoted to "..SERVER_RANK[rank].prefix, 0, 100, 255)
			elseif SERVER_RANK[pr].lvl > SERVER_RANK[rank].lvl then
				msgc2(id, "You've demoted "..player(p,"name").." to "..SERVER_RANK[rank].prefix, 0, 100, 255)
				msgc2(p, "You've been demoted to "..SERVER_RANK[rank].prefix, 0, 100, 255)
			elseif SERVER_RANK[pr].lvl == SERVER_RANK[rank].lvl then
				msgc2(id, "You've set "..player(p,"name").."'s rank to "..SERVER_RANK[rank].prefix, 0, 100, 255)
				msgc2(p, "Your new rank has been set to "..SERVER_RANK[rank].prefix, 0, 100, 255)
			end
		else
			ErrorMSG(id, "You can't set a rank equal/higher than you")
		end
	else
		ErrorMSG(id, "You can't demote/promote this user")
	end
end

AddMenu(rank_menu, 30)