#pragma semicolon 1
#define DEBUG
#define PLUGIN_AUTHOR "jenz"
#define PLUGIN_VERSION "1.00"
#define generic_length 256

#include <sourcemod>
#include <sdktools>
#include <PlayerManager>


int admin_editing[MAXPLAYERS + 1];
int server_port;
char admin_table_edit[generic_length];
char admin_table_coloumn_edit[generic_length];
char admin_table_info[generic_length];
Database database_connection;
Database database_hlstats_connection;

public Plugin myinfo = 
{
	name = "Unloze ingame polls",
	author = PLUGIN_AUTHOR,
	description = "ingame polls",
	version = PLUGIN_VERSION,
	url = "www.unloze.com"
};

public void OnPluginStart()
{
	//reg Cmds
	RegConsoleCmd("sm_poll", cmd_polls, "Poll menu for unloze");
	RegConsoleCmd("sm_polls", cmd_polls, "Poll menu for unloze");
	RegConsoleCmd("say", cmd_say);
	
	//adm cmds
	RegAdminCmd("sm_exec_pollcommands", cmd_poll_commands, ADMFLAG_GENERIC);
	//mysql con
	sql_start_connection();
	OnMapStart();
}

public void OnMapStart()
{
	server_port = GetConVarInt(FindConVar("hostport"));
	CreateTimer(1.0, poll_commands, INVALID_HANDLE);
}

public Action poll_commands(Handle timer)
{
	mysql_find_poll_commands();
}

public int MenuHandler1(Menu menu, MenuAction action, int client_, int selection)
{
	if (IsValidClient(client_))
	{
		switch(action)
		{
			case MenuAction_Select:
			{
				if (!selection)
					polladminmenu(client_);
				else
				{
					admin_editing[client_] = 5;
					mysql_get_polls("vote", client_, 0);
				}
			}
			case MenuAction_End:
			{
				if (menu != INVALID_HANDLE)
					delete menu;
			}
		}
	}
}

public int MenuHandler2(Menu menu, MenuAction action, int iclient2, int selection)
{
	if (IsValidClient(iclient2))
	{
		switch(action)
		{
			case MenuAction_Select:
			{
				admin_editing[iclient2] = selection;
				//PrintToChat(iclient2, "client: %N \nclient[admin_editing]: %i", iclient2, admin_editing[iclient2]);
				if (!selection)
				{
					mysql_find_poll_commands();
					PrintToChat(iclient2, "Executed Poll commands");
					polladminmenu(iclient2);
				}
				else if (selection == 1)
				{
					PrintToChat(iclient2, "Write poll question into the chat, type exit to abort");
				}
				else
				{
					char pollchoice[16];
					menu.GetItem(selection, pollchoice, sizeof(pollchoice));
					mysql_get_polls(pollchoice, iclient2, 1);
				}
			}
			case MenuAction_End:
			{
				admin_editing[iclient2] = 0;
				if (menu != INVALID_HANDLE)
					delete menu;
			}
		}
	}
}

public void editpoll(int client_edit, char []table_name_info)
{
	Menu menu2 = new Menu(editpollmenu);
	menu2.SetTitle("Poll editing: %s", table_name_info);
	menu2.AddItem(table_name_info, "Add option");
	menu2.AddItem(table_name_info, "Rewrite option");
	menu2.AddItem(table_name_info, "Remove option");
	menu2.AddItem(table_name_info, "Add command to options");
	menu2.AddItem(table_name_info, "playtime requirement");
	menu2.ExitButton = true;
	menu2.Display(client_edit, MENU_TIME_FOREVER);
}

public int menu_vote_poll_options(Menu menu, MenuAction action, int iclient, int selection)
{
	if (IsValidClient(iclient))
	{
		switch(action)
		{
			case MenuAction_Select:
			{
				char info[generic_length];
				menu.GetItem(selection, info, sizeof(info));
				int coloumn_index = StringToInt(info);
				mysql_insert_poll_vote(iclient, coloumn_index, admin_table_edit[iclient]);
			}
			case MenuAction_End:
			{
				admin_editing[iclient] = 0;
				if (menu != INVALID_HANDLE)
					delete menu;
			}
		}
	}
}

public int MenuHandler3(Menu menu, MenuAction action, int iclient3, int selection)
{
	if (IsValidClient(iclient3))
	{
		switch(action)
		{
			case MenuAction_Select:
			{
				char info[generic_length];
				menu.GetItem(selection, info, sizeof(info));
				//PrintToChat(iclient3, "admin_editing[iclient3]: %i \ninfo: %s", admin_editing[iclient3], info);
				switch(admin_editing[iclient3])
				{
					case 2:
					{
						//edit poll
						editpoll(iclient3, info);
					}
					case 3:
					{
						//enable or disable poll
						mysql_enable_disable_poll(iclient3, info);
					}
					case 4:
					{
						//delete poll
						mysql_delete_poll(iclient3, info);
					}
					case 5:
					{
						//vote poll
						mysql_vote_poll(iclient3, info);
					}
				}
			}
			case MenuAction_End:
			{
				admin_editing[iclient3] = 0;
				if (menu != INVALID_HANDLE)
					delete menu;
			}
		}
	}
}

public int menu_edit_poll_options(Menu menu, MenuAction action, int iclient4, int selection)
{
	if (IsValidClient(iclient4))
	{
		switch(action)
		{
			case MenuAction_Select:
			{
				char info[generic_length];
				menu.GetItem(selection, info, sizeof(info));
				int poll_id = StringToInt(info);
				DBResultSet rs2;
				char query_edit3[generic_length];
				Format(query_edit3, sizeof(query_edit3), "SELECT poll_option_text FROM unloze_css_polls.poll_text pt WHERE pt.poll_id = %i", poll_id);
				if ((rs2 = SQL_Query(database_connection, query_edit3)) != null && rs2.RowCount > 0)
				{
					rs2.FetchRow();
					rs2.FetchString(0, admin_table_info, sizeof(admin_table_info));
					if (StrContains(admin_table_coloumn_edit, "rewrite") != -1)
					{
						PrintToChat(iclient4, "Rewrite the option into chat. Type exit to abort");
						Format(admin_table_coloumn_edit, sizeof(admin_table_coloumn_edit), info);
						admin_editing[iclient4] = 8;
					}
					else if (StrContains(admin_table_coloumn_edit, "remove") != -1)
					{
						mysql_remove_poll_option(iclient4, poll_id, admin_table_edit, admin_table_info);
					}
					else if (StrContains(admin_table_coloumn_edit, "add command option to") != -1)
					{
						PrintToChat(iclient4, "Write the command related to option %s into the chat. Type exit to abort", info);
						Format(admin_table_coloumn_edit, sizeof(admin_table_coloumn_edit), info);
						admin_editing[iclient4] = 9;
					}
				}
				delete rs2;
			}
			case MenuAction_End:
			{
				if (menu != INVALID_HANDLE)
					delete menu;
			}
		}
	}
}


public int editpollmenu(Menu menu, MenuAction action, int iclient5, int selection)
{
	if (IsValidClient(iclient5))
	{
		switch(action)
		{
			case MenuAction_Select:
			{
				char info[generic_length];
				menu.GetItem(selection, info, sizeof(info));
				if (admin_editing[iclient5] == 7)
				{
					admin_editing[iclient5] = 0;
					mysql_playtime_update(iclient5, StringToInt(info), admin_table_edit);
				}
				else if (!selection)
				{
					Format(admin_table_edit, sizeof(admin_table_edit), info);
					admin_editing[iclient5] = 6;
					PrintToChat(iclient5, "type vote option into the chat. Type exit to abort");
				}
				else if (selection == 4)
				{
					Format(admin_table_edit, sizeof(admin_table_edit), info);
					mysql_playtime_requirement(iclient5, info);
				}
				else
					mysql_edit_poll(iclient5, info, selection);
			}
			case MenuAction_End:
			{
				admin_editing[iclient5] = 0;
				if (menu != INVALID_HANDLE)
					delete menu;
			}
		}
	}
}

public Action cmd_poll_commands(int i_client, int args)
{
	mysql_find_poll_commands();
	PrintToChat(i_client, "Executed poll commands");
	return Plugin_Handled;
}

public Action cmd_polls(int iclient, int args)
{
	if (IsValidClient(iclient))
	{
		if (CheckCommandAccess(iclient, "", ADMFLAG_SLAY))
		{
			Menu menu = new Menu(MenuHandler1);
			menu.SetTitle("Choose if you want to vote or use admin menu", "");
			menu.AddItem("", "Admin menu");
			menu.AddItem("", "Vote on Polls");
			menu.ExitButton = true;
			menu.Display(iclient, MENU_TIME_FOREVER);
		}
		else
		{
			admin_editing[iclient] = 5;
			mysql_get_polls("vote", iclient, 0);
		}
	}
	return Plugin_Handled;
}

public void polladminmenu(int client_admin)
{
	Menu menu = new Menu(MenuHandler2);
	menu.SetTitle("Poll admin menu", "", client_admin);
	menu.AddItem("", "Execute poll commands");
	menu.AddItem("", "Create new Poll");
	menu.AddItem("Edit", "Edit Poll");
	menu.AddItem("Enable/Disable", "Enable/Disable Poll");
	menu.AddItem("Delete", "Delete Poll");
	menu.ExitButton = true;
	menu.Display(client_admin, MENU_TIME_FOREVER);
}

public void OnClientDisconnect (int client_disc)
{
	admin_editing[client_disc] = 0;
}

public void OnClientPostAdminCheck(int client_pos)
{
	admin_editing[client_pos] = 0;
}

public Action cmd_say(int client_say, int args)
{
	if (!!admin_editing[client_say])
	{
		char info[generic_length];
		GetCmdArgString(info, sizeof(info));
		StripQuotes(info);
		if (StrEqual(info, "exit", false))
		{
			admin_editing[client_say] = 0;
			PrintToChat(client_say, "Aborted chat reading");
			return Plugin_Continue;
		}
		switch(admin_editing[client_say])
		{
			case 1:
			{
				sql_create_poll_table(client_say, info);
				PrintToChat(client_say, "Saved %s as poll Question", info);
				admin_editing[client_say] = 0;
				polladminmenu(client_say);
			}
			case 6:
			{
				mysql_add_poll_option(client_say, info);
				PrintToChat(client_say, "Saved %s as poll option", info);
				admin_editing[client_say] = 0;
			}
			case 8:
			{
				mysql_rewrite_poll_option(client_say, info);
				PrintToChat(client_say, "Rewrote %s into %s", admin_table_info, info);
				admin_editing[client_say] = 0;
			}
			case 9:
			{
				mysql_add_poll_option_command(client_say, info, admin_table_info);
				PrintToChat(client_say, "Added %s as command option", info);
				admin_editing[client_say] = 0;
			}
		}
	}
	return Plugin_Continue;
}

public void mysql_exec_prepared_statement(char []query_statement)
{
	char error[generic_length];
	DBStatement create_statement = SQL_PrepareQuery(database_connection, query_statement, error, sizeof(error));
	if (create_statement == INVALID_HANDLE)
	{
		CloseHandle(create_statement);
		return;
	}
	SQL_Execute(create_statement);
	CloseHandle(create_statement);
}

public void sql_start_connection()
{
	char error_connect[generic_length];
	if (SQL_CheckConfig("css_polls")) 
		database_connection = SQL_Connect("css_polls", true, error_connect, sizeof(error_connect));
	if (database_connection == null)
		PrintToChatAll("{green}[UNLOZE] {white}Error! Could not connect to maria-DB!");
	if (SQL_CheckConfig("hlstatsx"))
		database_hlstats_connection = SQL_Connect("hlstatsx", true, error_connect, sizeof(error_connect));
	if (database_hlstats_connection == null)
		PrintToChatAll("{green}[UNLOZE] {white}Error! Could not connect to maria-DB!");
	char query_start[generic_length];
	Format(query_start, sizeof(query_start), "CREATE TABLE IF NOT EXISTS unloze_css_polls.`poll_reff` (`polloption` VARCHAR(%i) NOT NULL, `command` text NOT NULL, `server_port` INT NOT NULL, PRIMARY KEY (`polloption`))", generic_length);
	mysql_exec_prepared_statement(query_start);
	Format(query_start, sizeof(query_start), "CREATE TABLE IF NOT EXISTS unloze_css_polls.`poll_status` (`poll_table` VARCHAR(%i) NOT NULL, PLAYTIME int(10) DEFAULT 0, `enabled` BOOL DEFAULT false, `server_port` INT default 0, PRIMARY KEY (`poll_table`))", generic_length);
	mysql_exec_prepared_statement(query_start);
	Format(query_start, sizeof(query_start), "CREATE TABLE IF NOT EXISTS unloze_css_polls.`poll_text` (`poll_id` INT NOT NULL AUTO_INCREMENT, `poll_option_text` text NOT NULL, PRIMARY KEY (`poll_id`))");
	mysql_exec_prepared_statement(query_start);
}

public void mysql_enable_disable_poll(int iclient6, char []table_name_enable)
{
	DBResultSet rs_disable;
	char query_enabled[generic_length];
	Format(query_enabled, sizeof(query_enabled), "UPDATE unloze_css_polls.poll_status SET enabled = !enabled where poll_table = '%s'", table_name_enable);
	mysql_exec_prepared_statement(query_enabled);
	Format(query_enabled, sizeof(query_enabled), "SELECT enabled from unloze_css_polls.poll_status WHERE poll_table = '%s'", table_name_enable);
	if ((rs_disable = SQL_Query(database_connection, query_enabled)) == null)
	{
		delete rs_disable;
		return;
	}
	if (rs_disable.RowCount > 0)
	{
		rs_disable.FetchRow();
		int status = rs_disable.FetchInt(0);
		delete rs_disable;
		if (status)
			PrintToChat(iclient6, "Enabled poll %s", table_name_enable);
		else
			PrintToChat(iclient6, "Disabled poll %s", table_name_enable);
	}
	editpoll(iclient6, table_name_enable);
}

public void mysql_delete_poll(int iclient7, char []table_name)
{
	char query_delete[generic_length];
	Format(query_delete, sizeof(query_delete), "DROP TABLE unloze_css_polls.`%s`", table_name);
	mysql_exec_prepared_statement(query_delete);
	Format(query_delete, sizeof(query_delete), "DELETE FROM unloze_css_polls.poll_status WHERE poll_table = '%s'", table_name);
	mysql_exec_prepared_statement(query_delete);
	PrintToChat(iclient7, "removed poll %s", table_name);
	polladminmenu(iclient7);
}

public void mysql_insert_poll_vote(int client, int coloumn_index, char []table_name)
{
	DBResultSet rs_vote;
	char sSID[64];
	GetClientAuthId(client, AuthId_Steam2, sSID, sizeof(sSID));
	Format(sSID, sizeof(sSID), "0%s", sSID[7]);
	char query_insert[generic_length];
	Format(query_insert, sizeof(query_insert), "DELETE FROM unloze_css_polls.`%s` WHERE steam_id = '%s'", table_name, sSID);
	//PrintToChat(client, "query_insert 0: %s", query_insert);
	mysql_exec_prepared_statement(query_insert);
	Format(query_insert, sizeof(query_insert), "INSERT INTO unloze_css_polls.`%s` (`steam_id`, `%i`) VALUES ('%s', 1)", table_name, coloumn_index, sSID);
	//PrintToChat(client, "query_insert 1: %s", query_insert);
	mysql_exec_prepared_statement(query_insert);
	Format(query_insert, sizeof(query_insert), "SELECT pt.poll_option_text FROM unloze_css_polls.`%s` ht INNER JOIN unloze_css_polls.poll_text pt WHERE pt.poll_id = %i AND ht.`%i` = 1", table_name, coloumn_index, coloumn_index);
	//PrintToChat(client, "query_insert 2: %s", query_insert);
	if ((rs_vote = SQL_Query(database_connection, query_insert)) != null)
	{
		char query_vote_result[generic_length];
		rs_vote.FetchRow();
		rs_vote.FetchString(0, query_vote_result, sizeof(query_vote_result));
		PrintToChat(client, "Voted on poll %s for option %s", table_name, query_vote_result);
	}
	delete rs_vote;
}

public void mysql_vote_poll(int client, char []table_name)
{
	DBResultSet rs_vote;
	char query_vote[generic_length];
	char sSID[24];
	GetClientAuthId(client, AuthId_Steam2, sSID, sizeof(sSID));
	Format(query_vote, sizeof(query_vote), "SELECT PLAYTIME FROM unloze_css_polls.poll_status WHERE poll_table = '%s'", table_name);
	if ((rs_vote = SQL_Query(database_connection, query_vote)) == null)
	{
		delete rs_vote;
		return;
	}
	rs_vote.FetchRow();
	int playtime = rs_vote.FetchInt(0);
	//PrintToChatAll("playtime: %i query_vote: %s", playtime, query_vote);
	GetClientAuthId(client, AuthId_Steam3, sSID, sizeof(sSID));
	if (playtime != 0)
	{
		char server[8];
		switch(server_port)
		{
			case 27015:
			{
				Format(server, sizeof(server), "css-ze");
			}
			case 27016:
			{
				Format(server, sizeof(server), "css-zr");
			}
			case 27017:
			{
				Format(server, sizeof(server), "css-mg");
			}
			case 27019:
			{
				Format(server, sizeof(server), "css-ze");
			}
			case 27035:
			{
				Format(server, sizeof(server), "css-ze");
			}
		}
		ReplaceString(sSID, sizeof(sSID), "[U:", "");
		ReplaceString(sSID, sizeof(sSID), "]", "");
		Format(sSID, sizeof(sSID), "0%s", sSID[1]);
		Format(query_vote, sizeof(query_vote), "SELECT connection_time from unloze_stats.hlstats_Players hp INNER JOIN unloze_stats.hlstats_PlayerUniqueIds pui on hp.playerId = pui.playerId AND pui.uniqueId = '%s' AND pui.game = '%s'", sSID, server);
		//PrintToChatAll("query_vote steam: %s", query_vote);
		if ((rs_vote = SQL_Query(database_hlstats_connection, query_vote)) == null)
		{
			delete rs_vote;
			return;
		}
		if (!rs_vote.RowCount)
		{
			Format(sSID, sizeof(sSID), "1%s", sSID[1]);
			Format(query_vote, sizeof(query_vote), "SELECT connection_time from unloze_stats.hlstats_Players hp INNER JOIN unloze_stats.hlstats_PlayerUniqueIds pui on hp.playerId = pui.playerId AND pui.uniqueId = '%s' AND pui.game = '%s'", sSID, server);
			if ((rs_vote = SQL_Query(database_hlstats_connection, query_vote)) == null)
			{
				delete rs_vote;
				return;
			}
			//PrintToChatAll("query_vote steam 1: %s", query_vote);
		}
		if (!rs_vote.RowCount)
		{
			GetClientAuthId(client, AuthId_Steam2, sSID, sizeof(sSID));
			Format(sSID, sizeof(sSID), "%s", sSID[8]);
			Format(sSID, sizeof(sSID), "0%s", sSID[1]);
			Format(query_vote, sizeof(query_vote), "SELECT connection_time from unloze_stats.hlstats_Players hp INNER JOIN unloze_stats.hlstats_PlayerUniqueIds pui on hp.playerId = pui.playerId AND pui.uniqueId = '%s' AND pui.game = '%s'", sSID, server);
			if ((rs_vote = SQL_Query(database_hlstats_connection, query_vote)) == null)
			{
				delete rs_vote;
				return;
			}
			//PrintToChatAll("query_vote steam 2: %s", query_vote);
		}
		if (!rs_vote.RowCount)
		{
			GetClientAuthId(client, AuthId_Steam2, sSID, sizeof(sSID));
			Format(sSID, sizeof(sSID), "%s", sSID[8]);
			Format(sSID, sizeof(sSID), "1%s", sSID[1]);
			Format(query_vote, sizeof(query_vote), "SELECT connection_time from unloze_stats.hlstats_Players hp INNER JOIN unloze_stats.hlstats_PlayerUniqueIds pui on hp.playerId = pui.playerId AND pui.uniqueId = '%s' AND pui.game = '%s'", sSID, server);
			if ((rs_vote = SQL_Query(database_hlstats_connection, query_vote)) == null)
			{
				delete rs_vote;
				return;
			}
			//PrintToChatAll("query_vote steam 3: %s", query_vote);
		}
		if (!rs_vote.RowCount)
		{
			PrintToChat(client, "you do not have enough time on this server to participate in this vote");
			delete rs_vote;
			return;
		}
		rs_vote.FetchRow();
		float connection_time_seconds = rs_vote.FetchFloat(0);
		float hours_pre = connection_time_seconds / 60;
		int hours = RoundToFloor(hours_pre / 60);
		if (hours < playtime)
		{
			PrintToChat(client, "you have %i hours but require %i to participate in this vote", hours, playtime);
			delete rs_vote;
			return;
		}
	}
	//check nosteam
	if (!PM_IsPlayerSteam(client))
	{
		PrintToChat(client, "You are not authenticated with steam and can therefore not vote");
		delete rs_vote;
		return;
	}
	Format(query_vote, sizeof(query_vote), "SELECT COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME = '%s'", table_name);
	if ((rs_vote = SQL_Query(database_connection, query_vote)) == null)
	{
		delete rs_vote;
		return;
	}
	if (rs_vote.RowCount > 0)
	{
		Format(admin_table_edit[client], sizeof(admin_table_edit), table_name);
		Menu menu2 = new Menu(menu_vote_poll_options);
		menu2.SetTitle("Select which option to vote on for poll: %s", table_name);
		for (int i = 0; i < 5; i++)
			menu2.AddItem("", "", ITEMDRAW_DISABLED);
		while (rs_vote.FetchRow())
		{
			DBResultSet rs_vote1;
			int poll_id = rs_vote.FetchInt(0);
			Format(query_vote, sizeof(query_vote), "SELECT COUNT(*), pt.poll_option_text FROM unloze_css_polls.`%s` ta INNER JOIN unloze_css_polls.poll_text pt WHERE pt.poll_id = %i AND ta.`%i` = 1", table_name, poll_id, poll_id);
			if ((rs_vote1 = SQL_Query(database_connection, query_vote)) != null)
			{
				if (rs_vote1.RowCount > 0)
				{
					rs_vote1.FetchRow();
					int poll_vote_count = rs_vote1.FetchInt(0);
					char poll_option[generic_length];
					char poll_option_vote[generic_length];
					rs_vote1.FetchString(1, poll_option, sizeof(poll_option));
					Format(poll_option_vote, sizeof(poll_option_vote), "%s Votes: %i", poll_option, poll_vote_count);
					char poll_char_id[24];
					IntToString(poll_id, poll_char_id, sizeof(poll_char_id));
					menu2.AddItem(poll_char_id, poll_option_vote);
				}
			}
			delete rs_vote1;
		}
		menu2.ExitButton = true;
		menu2.Display(client, MENU_TIME_FOREVER);
	}
	delete rs_vote;
}

public void mysql_remove_poll_option(int client, int poll_id, char []target_table, char []coloumn_text)
{
	DBResultSet rs_add;
	char query_remove[generic_length];
	Format(query_remove, sizeof(query_remove), "ALTER TABLE unloze_css_polls.`%s` DROP `%i`", target_table, poll_id);
	mysql_exec_prepared_statement(query_remove);
	Format(query_remove, sizeof(query_remove), "DELETE FROM unloze_css_polls.poll_text WHERE poll_id = %i", poll_id);
	mysql_exec_prepared_statement(query_remove);
	PrintToChat(client, "removed Option %s from poll %s", coloumn_text, target_table);
	delete rs_add;
	editpoll(client, target_table);
}

public void mysql_add_poll_option(int client, char []info)
{
	DBResultSet rs_add;
	char query_add[generic_length];
	Format(query_add, sizeof(query_add), "INSERT INTO unloze_css_polls.`poll_text` (poll_option_text) VALUES ('%s')", info);
	mysql_exec_prepared_statement(query_add);
	Format(query_add, sizeof(query_add), "SELECT LAST_INSERT_ID()");
	if ((rs_add = SQL_Query(database_connection, query_add)) == null)
	{
		delete rs_add;
		return;
	}
	int insert_id;
	rs_add.FetchRow();
	insert_id = rs_add.FetchInt(0);
	Format(query_add, sizeof(query_add), "ALTER TABLE unloze_css_polls.`%s` ADD COLUMN IF NOT EXISTS `%i` INT default 0", admin_table_edit, insert_id);
	mysql_exec_prepared_statement(query_add);
	delete rs_add;
	editpoll(client, admin_table_edit);
}

public void mysql_add_poll_option_command(int client, char []command, char []coloumn)
{
	char query_command[generic_length];
	Format(query_command, sizeof(query_command), "INSERT INTO unloze_css_polls.`poll_reff` (polloption, command, server_port) VALUES ('%s.%s', '%s', '%i') ON DUPLICATE KEY UPDATE command = '%s'", admin_table_edit, coloumn, command, server_port, command);
	mysql_exec_prepared_statement(query_command);
	editpoll(client, admin_table_edit);
}

public void mysql_rewrite_poll_option(int client, char []info)
{
	char query_rewrite[generic_length];
	int poll_id = StringToInt(admin_table_coloumn_edit);
	Format(query_rewrite, sizeof(query_rewrite), "UPDATE unloze_css_polls.`poll_text` SET poll_option_text = '%s' WHERE poll_id = %i", info, poll_id);
	//PrintToChat(client, "query_rewrite: %s", query_rewrite);
	mysql_exec_prepared_statement(query_rewrite);
}

public void mysql_playtime_update(int client, int info, char []admin_table_edit_local)
{
	char query_playtime[generic_length];
	Format(query_playtime, sizeof(query_playtime), "UPDATE unloze_css_polls.`poll_status` SET PLAYTIME = %i WHERE poll_table = '%s'", info, admin_table_edit_local);
	mysql_exec_prepared_statement(query_playtime);
	PrintToChat(client, "Edited playtime requirement %i to poll: %s", info, admin_table_edit_local);
	editpoll(client, admin_table_edit_local);
}

public void mysql_playtime_requirement(int client, char []info)
{	
	//selection = 4 : playtime requirement for poll
	DBResultSet rs;
	char query_playtimre_requir[generic_length];
	Format(query_playtimre_requir, sizeof(query_playtimre_requir), "SELECT PLAYTIME FROM unloze_css_polls.poll_status WHERE poll_table = '%s'", info);
	if ((rs = SQL_Query(database_connection, query_playtimre_requir)) == null)
	{
		delete rs;
		return;
	}
	if (rs.RowCount > 0)
	{
		int playtime;
		rs.FetchRow();
		playtime = rs.FetchInt(0);
		//PrintToChat(client, "playtime required: %i", playtime);
		admin_editing[client] = 7;
		Menu menu = new Menu(editpollmenu, MENU_ACTIONS_ALL);
		char menu_title[generic_length];
		Format(menu_title, sizeof(menu_title), "Poll %s has playtime requirement: %i", info, playtime);
		menu.SetTitle(menu_title);
		menu.AddItem("0", "0 hours playtime requirement");
		menu.AddItem("5", "5 hours playtime requirement");
		menu.AddItem("10", "10 hours playtime requirement");
		menu.AddItem("25", "25 hours playtime requirement");
		menu.AddItem("50", "50 hours playtime requirement");
		menu.AddItem("250", "250 hours playtime requirement");
		menu.AddItem("1000", "1000 hours playtime requirement");
		menu.ExitButton = true;
		menu.Display(client, MENU_TIME_FOREVER);
	}
	delete rs;
}

public void mysql_edit_poll(int client, char []info, int selection)
{
	//selection = 1 : rewrite option
	//selection = 2 : remove option
	//selection = 3 : add command to option
	DBResultSet rs;
	char query_edit2[generic_length];
	Format(query_edit2, sizeof(query_edit2), "SELECT COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME = '%s'", info);
	if ((rs = SQL_Query(database_connection, query_edit2)) == null)
	{
		delete rs;
		return;
	}
	if (rs.RowCount > 0)
	{
		//skip steam_auth row which is always first
		rs.FetchRow();
		char pollchoice[generic_length];
		switch(selection)
		{
			case 1:
			{
				Format(pollchoice, sizeof(pollchoice), "rewrite");
			}
			case 2:
			{
				Format(pollchoice, sizeof(pollchoice), "remove");
			}
			case 3:
			{
				Format(pollchoice, sizeof(pollchoice), "add command option to");
			}
		}
		Format(admin_table_coloumn_edit, sizeof(admin_table_coloumn_edit), pollchoice);
		Format(admin_table_edit, sizeof(admin_table_edit), info);
		
		Menu menu_poll_options = new Menu(menu_edit_poll_options);
		menu_poll_options.SetTitle("Select which option to %s in poll %s", pollchoice, info);
		while (rs.FetchRow())
		{
			DBResultSet rs1;
			char table_names[generic_length];
			char table_column_poll_ids[generic_length];
			int poll_id = rs.FetchInt(0);
			IntToString(poll_id, table_column_poll_ids, sizeof(table_column_poll_ids));
			Format(query_edit2, sizeof(query_edit2), "SELECT poll_option_text FROM unloze_css_polls.poll_text where poll_id = %i", poll_id);
			if ((rs1 = SQL_Query(database_connection, query_edit2)) == null)
				continue;
			rs1.FetchRow();
			rs1.FetchString(0, table_names, sizeof(table_names));
			menu_poll_options.AddItem(table_column_poll_ids, table_names);
			delete rs1;
		}
		menu_poll_options.ExitButton = true;
		menu_poll_options.Display(client, MENU_TIME_FOREVER);
	}
	delete rs;
}

public void mysql_get_polls(char []pollchoice, int client, int admin_enable)
{
	DBResultSet rs_polls;
	char query_get_polls[generic_length];
	Format(query_get_polls, sizeof(query_get_polls), "SELECT poll_table from unloze_css_polls.poll_status where server_port = %i", server_port);
	if ((rs_polls = SQL_Query(database_connection, query_get_polls)) == null)
	{
		delete rs_polls;
		return;
	}
	char table_names[generic_length];
	if (rs_polls.RowCount > 0)
	{
		Menu menu3 = new Menu(MenuHandler3);
		menu3.SetTitle("Select which poll to %s", pollchoice);
		while (rs_polls.FetchRow())
		{
			DBResultSet rs_vote;
			rs_polls.FetchString(0, table_names, sizeof(table_names));
			Format(query_get_polls, sizeof(query_get_polls), "SELECT enabled from unloze_css_polls.poll_status WHERE poll_table = '%s'", table_names);
			if ((rs_vote = SQL_Query(database_connection, query_get_polls)) != null)
			{
				rs_vote.FetchRow();
				int status = rs_vote.FetchInt(0);
				if (!status && !admin_enable)
					menu3.AddItem(table_names, table_names, ITEMDRAW_DISABLED);
				else
					menu3.AddItem(table_names, table_names);
			}
			delete rs_vote;
		}
		menu3.ExitButton = true;
		menu3.Display(client, MENU_TIME_FOREVER);
	}
	delete rs_polls;
}

public void mysql_find_poll_commands()
{
	DBResultSet rs;
	char query[generic_length];
	char query2[generic_length];
	Format(query, sizeof(query), "SELECT poll_table FROM unloze_css_polls.poll_status ps WHERE ps.server_port = %i", server_port);
	if ((rs = SQL_Query(database_connection, query)) == null)
	{
		delete rs;
		return;
	}
	if (rs.RowCount > 0)
	{
		while (rs.FetchRow())
		{
			char table[generic_length];
			DBResultSet rs1;
			rs.FetchString(0, table, sizeof(table));
			Format(query2, sizeof(query2), "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='unloze_css_polls' AND `TABLE_NAME`='%s'", table);
			if ((rs1 = SQL_Query(database_connection, query2)) != null)
			{
				if (rs1.RowCount > 0)
				{
					int highest_vote_option = 0;
					char highest_poll_option[generic_length];
					//skipping steam_ID
					rs1.FetchRow();
					while (rs1.FetchRow())
					{
						DBResultSet rs2;
						int poll_id = rs1.FetchInt(0);
						char column[generic_length];
						Format(query, sizeof(query), "SELECT COUNT(*), pt.poll_option_text FROM unloze_css_polls.`%s` ta INNER JOIN unloze_css_polls.poll_text pt WHERE pt.poll_id = %i AND ta.`%i` = 1", table, poll_id, poll_id);
						if ((rs2 = SQL_Query(database_connection, query)) != null)
						{
							rs2.FetchRow();
							int vote_count = rs2.FetchInt(0);
							rs2.FetchString(1, column, sizeof(column));
							if (vote_count > highest_vote_option)
							{
								highest_vote_option = vote_count;
								Format(highest_poll_option, sizeof(highest_poll_option), column);
							}
						}
						delete rs2;
					}
					if (highest_vote_option > 0)
					{
						DBResultSet rs2;
						Format(query2, sizeof(query2), "SELECT command FROM unloze_css_polls.poll_reff WHERE polloption = '%s.%s'", table, highest_poll_option);
						if ((rs2 = SQL_Query(database_connection, query2)) != null)
						{
							if (!!rs2.RowCount)
							{
								char command[generic_length];
								rs2.FetchRow();
								rs2.FetchString(0, command, sizeof(command));
								ServerCommand(command);
							}
						}
						delete rs2;
					}
				}
			}
			delete rs1;
		}
	}
	delete rs;
}

public void sql_create_poll_table(int client, char []info)
{
	if (database_connection == null)
		sql_start_connection();
	if (database_connection == null)
		return;
	char query[generic_length];
	Format(query, sizeof(query), "CREATE TABLE IF NOT EXISTS unloze_css_polls.`%s` (`steam_id` VARCHAR(24) NOT NULL, PRIMARY KEY (`steam_id`))", info);
	mysql_exec_prepared_statement(query);
	Format(query, sizeof(query), "INSERT IGNORE INTO unloze_css_polls.`poll_status` (PLAYTIME, enabled, poll_table, server_port) VALUES (0, 0, '%s', %i)", info, server_port);
	mysql_exec_prepared_statement(query);
}

stock bool IsValidClient(int client)
{
	if (client > 0 && client <= MaxClients && IsClientConnected(client) && IsClientInGame(client))
	{
		return true;
	}
	return false;
}