
/*#######################################################################################################################################################
################################################# Подключаемся к базе данных		  ###################################################################
#########################################################################################################################################################*/

stock MySQLConnect ( )
{
	if ( mysql_ping () ) mysql_close ( ) ;
	dbHandle = mysql_connect ( MySQL_HOST, MySQL_USER, MySQL_DB, MySQL_PASS ) ;
	switch ( mysql_ping ( ) ) 
	{
		case 1: print ( "MySQL connection: OK." ) ;
		case -1: print ( "MySQL connection: ERROR." ) ;
	}
	mysql_debug ( MySQL_DEBUG ) ;
	mysql_function_query( dbHandle, "SET NAMES cp1251", false, "", "" ) ; 
	return 1;
}

/*#######################################################################################################################################################
################################################# Проверяем игрока на регистрацию	  ###################################################################
#########################################################################################################################################################*/

forward CheckPlayerRegistered ( playerid, registration );
public CheckPlayerRegistered ( playerid, registration ) 
{
	new rows, fields, query [ 512 ], temp [ 128 ] ;
	cache_get_data ( rows, fields ) ;

	switch ( registration )
	{
		case 0:
		{
			if ( rows ) 
			{
				new idx;
				cache_get_field_content ( 0, "id", temp ), idx = strval ( temp ) ;
				
				echo ( query, "SELECT `unban_date`, `reason` FROM `ban_log` WHERE `id_player` = '%d' AND `unban_date` > NOW( ) LIMIT 1", idx ) ;
				mysql_function_query ( dbHandle, query, true, "CheckPlayerBanned", "i", playerid ) ;
			}
			else
			{
				SetPVarInt ( playerid, "Page", 1 ) ;
				ShowDialog ( playerid, Show:Welcome, DIALOG_STYLE_MSGBOX, "{FFFFFF}Здравствуй дорогой друг!", "На нашем сервере установлен {FF0000}RolePlay режим!\n\n{A5C3E6}Это означает что ты должен отыгрывать роль своего персонажа, а не самого себя!\n\nВ выборе роли персонажа мы тебя не ограничиваем, всё зависит от твоего воображения!\n\nНО помни, выбрав роль персонажа, ты должен соответствовать этой роли!\n", "Далее", "" ) ;
			}
		}
		case 1:
		{
			if ( rows )
			{
				SendClientMessage ( playerid, COLOR_ADM, "Попытка зарегистрироватся под существующим ником!" ) ;
				AntiCheatLog ( playerid, "Попытка зарегистрироватся под существующим ником!" ) ;
				KickEx ( playerid );
			}
			else
			{
				new password [ 33 ], escape_pass [ 33 ] ;
				
				new email [ 64 ] ;
				GetPVarString ( playerid, "EMail", email, 64 ) ;
				
				GetPVarString ( playerid, "InputText", password, 33 ) ;
				mysql_real_escape_string ( password, escape_pass ) ;
				
				echo ( query, "INSERT INTO `players` ( `regdate`, `name`, `password`, `sex`, `skin`, `mail` ) VALUES ( CURDATE(), '%s', MD5('%s'), '%d', '%d', '%s' )", PlayerName [ playerid ], escape_pass, GetPVarInt ( playerid, "Sex" ), GetPVarInt ( playerid, "Skin" ), email ) ;
				
				mysql_function_query ( dbHandle, query, false, "", "" ) ;
				
				format ( query, sizeof ( query ), "SELECT * FROM `players` WHERE `name` = '%s' AND `password` = MD5('%s') LIMIT 1", PlayerName [ playerid ], escape_pass ) ;
				
				mysql_function_query ( dbHandle, query, true, "PlayerLogin", "i", playerid ) ;
				
				DeletePVar ( playerid, "InputText" ) ;
			}
		}
	}
	return 1;
}

/*#######################################################################################################################################################
################################################# Проверяем игрока на бан			 ###################################################################
#########################################################################################################################################################*/

forward CheckPlayerBanned ( playerid );
public CheckPlayerBanned ( playerid ) 
{
	new rows, fields, query [ 512 ], temp [ 128 ] ;
	cache_get_data ( rows, fields ) ;
	if ( rows )
	{
		new date [ 20 ], reason [ 64 ] ;
		cache_get_field_content ( 0, "unban_date", temp ), sscanf ( temp, "s[20]", date ) ;
		cache_get_field_content ( 0, "reason", temp ), sscanf ( temp, "s[64]", reason ) ;
		
		echo ( temp, "Акаунт %s забанен. Причина: %s. Дата разбана: %s", PlayerName [ playerid ], reason, date ) ;
		Send ( playerid, COLOR_ADM, temp ) ;
		KickEx ( playerid ) ;
	}
	else
	{
		echo   ( query, "{FFFFFF}---------------------------------------------------------------------\n\n" ) ;
		strcat ( query, "Добро пожаловать на {33AAFF}"NAME_SERVER"\n\n" ) ;
		echo   ( temp,	"{FFFFFF}Логин {33AAFF}%s {FFFFFF}зарегистрирован\n\n", PlayerName [ playerid ] ) ;
		strcat ( query, temp ) ;
		strcat ( query, "Введи пароль (мин. 6 симв.)\n\n" ) ;
		strcat ( query, "{FFFFFF}---------------------------------------------------------------------\n" ) ;
		
		ShowDialog ( playerid, Show:Login, DIALOG_STYLE_PASSWORD, "{FFFFFF}Авторизация", query, "Ввести", "" ) ;
	}
	return 1;
}

/*#######################################################################################################################################################
################################################# Проверяем E-Mail адрес		 	 ###################################################################
#########################################################################################################################################################*/

forward CheckEMailKey ( playerid );
public CheckEMailKey ( playerid ) 
{
	new rows, fields;
	cache_get_data ( rows, fields ) ;
	
	if ( rows )
	{
		new email [ 64 ] ;
		GetPVarString ( playerid, "EMail", email, 64 ) ;
	
		new query [ 128 ] ;
		echo ( query, "DELETE FROM `mails` WHERE `mail` = '%s' LIMIT 1", email ) ;
		mysql_function_query ( dbHandle, query, false, "", "" ) ;
		
		ShowDialog ( playerid, Show:Sex, DIALOG_STYLE_LIST, "{FFFFFF}Выбери пол", "Мужской\nЖенский", "Выбрать", "" ) ;
	}
	else
	{
		ShowDialog ( playerid, Show:MailAccept, DIALOG_STYLE_INPUT, "{FFFFFF}Введи код активации", "\n{FF0000}Неверный код активации!\n\n", "Ввести", "Назад" ) ;
	}
	return 1;
}

forward CheckEMail ( playerid, step );
public CheckEMail ( playerid, step ) 
{
	new rows, fields;
	cache_get_data ( rows, fields ) ;
	
	new email [ 64 ] ;
	GetPVarString ( playerid, "EMail", email, 64 ) ;

	switch ( step )
	{
		case 0:
		{
			if ( rows )
			{
				ShowDialog ( playerid, Show:Mail, DIALOG_STYLE_INPUT, "{FFFFFF}Введи E-Mail", "Введи свой действующий E-Mail адрес\n\nВНИМАНИЕ! На него придет регистрационый код.\n{FF0000}Данный E-Mail адрес зарегистрирован!", "Ввести", "" ) ;
			}
			else
			{
				new query [ 128 ] ;
				echo ( query, "SELECT * FROM `mails` WHERE `mail` = '%s' LIMIT 1", email ) ;
				mysql_function_query ( dbHandle, query, true, "CheckEMail", "ii", playerid, 1 ) ;
			}
		}
		case 1:
		{
			if ( rows )
			{
				ShowDialog ( playerid, Show:MailAccept, DIALOG_STYLE_INPUT, "{FFFFFF}Введи код активации", "Данный E-Mail адрес находится на активации, введи код активации!", "Ввести", "Назад" ) ;
			}
			else
			{
				SendMail ( playerid, email, 1 ) ;
			}
		}
	}
	return 1;
}

/*#######################################################################################################################################################
################################################# 		Авторизация игрока 			 ###################################################################
#########################################################################################################################################################*/

forward PlayerLogin ( playerid );
public PlayerLogin ( playerid ) 
{
	new rows, fields, temp [ 128 ], query [ 512 ] ;
	cache_get_data ( rows, fields ) ;
	if ( rows )
	{
		cache_get_field_content ( 0, "id", temp ) ,				PLAYER [ playerid ] [ ID ] = strval ( temp ) ;
		
		cache_get_field_content ( 0, "regdate", temp ) ,		sscanf ( temp, "s[11]", PLAYER [ playerid ] [ REGDATE ] ) ;
		
		cache_get_field_content ( 0, "settings", temp ) ,		sscanf ( temp, "p<|>dd", 
																PLAYER [ playerid ] [ SET ] [ 0 ], 
																PLAYER [ playerid ] [ SET ] [ 1 ] ) ;
		
		cache_get_field_content ( 0, "licenses", temp ) ,		sscanf ( temp, "p<|>ddddd", 
																PLAYER [ playerid ] [ LICENSES ] [ LIC_CAT_A ], 
																PLAYER [ playerid ] [ LICENSES ] [ LIC_CAT_B ], 
																PLAYER [ playerid ] [ LICENSES ] [ LIC_CAT_C ], 
																PLAYER [ playerid ] [ LICENSES ] [ LIC_CAT_D ], 
																PLAYER [ playerid ] [ LICENSES ] [ LIC_CAT_H ] ) ;
		
		cache_get_field_content ( 0, "hospital", temp ) ,		PLAYER [ playerid ] [ HOSPITAL ] = strval ( temp ) ;
		cache_get_field_content ( 0, "hospital_time", temp ) ,	PLAYER [ playerid ] [ HOSPITAL_TIME] = strval ( temp ) ;
		
		cache_get_field_content ( 0, "jail", temp ) ,			PLAYER [ playerid ] [ JAIL ] = strval ( temp ) ;
		cache_get_field_content ( 0, "jail_time", temp ) ,		PLAYER [ playerid ] [ JAIL_TIME ] = strval ( temp ) ;
		
		cache_get_field_content ( 0, "sex", temp ) ,			PLAYER [ playerid ] [ SEX ] = strval ( temp ) ;
		cache_get_field_content ( 0, "race", temp ) ,			PLAYER [ playerid ] [ RACE ] = strval ( temp ) ;
		cache_get_field_content ( 0, "skin", temp ) ,			PLAYER [ playerid ] [ SKIN ] = strval ( temp ) ;
		
		cache_get_field_content ( 0, "money", temp ) ,			PLAYER [ playerid ] [ MONEY ] = strval ( temp ) ;
		cache_get_field_content ( 0, "bank", temp ) ,			PLAYER [ playerid ] [ BANK ] = strval ( temp ) ;
		
		cache_get_field_content ( 0, "age", temp ) ,			PLAYER [ playerid ] [ AGE ] = strval ( temp ) ;
		cache_get_field_content ( 0, "hour", temp ) ,			PLAYER [ playerid ] [ HOUR ] = strval ( temp ) ;
		cache_get_field_content ( 0, "game_session", temp ) ,	PLAYER [ playerid ] [ GAME_SESSION ] = strval ( temp ) ;
		
		cache_get_field_content ( 0, "salary", temp ) ,			PLAYER [ playerid ] [ SALARY ] = strval ( temp ) ;
		cache_get_field_content ( 0, "job", temp ) ,			PLAYER [ playerid ] [ JOB ] = strval ( temp ) ;	

		cache_get_field_content ( 0, "admin", temp ) ,			PLAYER [ playerid ] [ ADMIN ] = strval ( temp );
		cache_get_field_content ( 0, "helper", temp ) ,			PLAYER [ playerid ] [ HELPER ] = strval ( temp ) ;
		
		new Float:_Position [ 4 ];
		cache_get_field_content ( 0, "pos_x", temp ) ,			_Position [ 0 ] = floatstr( temp ) ;
		cache_get_field_content ( 0, "pos_y", temp ) ,			_Position [ 1 ] = floatstr( temp ) ;
		cache_get_field_content ( 0, "pos_z", temp ) ,			_Position [ 2 ] = floatstr( temp ) ;
		cache_get_field_content ( 0, "face_angle", temp ) ,		_Position [ 3 ] = floatstr( temp ) ;
		
		new set [ 2 ] ;
		cache_get_field_content ( 0, "int", temp ) ,			set [ 0 ] = strval ( temp ) ;
		cache_get_field_content ( 0, "world", temp ) ,			set [ 1 ] = strval ( temp ) ;
		
		cache_get_field_content ( 0, "hp", temp ) ,				PLAYER [ playerid ] [ HEALTH ] = floatstr ( temp ) ;
		cache_get_field_content ( 0, "armour", temp ) ,			PLAYER [ playerid ] [ ARMOUR ] = floatstr ( temp ) ;
		cache_get_field_content ( 0, "satiety", temp ) ,		PLAYER [ playerid ] [ SATIETY ] = floatstr ( temp ) ;
		
		cache_get_field_content ( 0, "fraction", temp ) ,		PLAYER [ playerid ] [ FRAC ] = strval ( temp ) ;
		cache_get_field_content ( 0, "rank", temp ) ,			PLAYER [ playerid ] [ RANK ] = strval ( temp ) ;
		cache_get_field_content ( 0, "post", temp ) ,			PLAYER [ playerid ] [ POST ] = strval ( temp ) ;
		cache_get_field_content ( 0, "leader", temp ) ,			PLAYER [ playerid ] [ LEADER ] = strval ( temp ) ;
		
		SetAuthorizationLog ( playerid ) ;
		
		echo ( query, "SELECT `vehicles`.*, `plate_vehicles`.`plate` FROM `vehicles` LEFT JOIN `plate_vehicles` ON `plate_vehicles`.`vehicle_id` = `vehicles`.`id` WHERE `vehicles`.`type` = '0' AND `vehicles`.`owner` = '%d'", PLAYER [ playerid ] [ ID ] ) ;
		mysql_function_query ( dbHandle, query, true, "LoadPlayerVehicles", "i", playerid ) ;
		
		echo ( query, "UPDATE `players` SET `online` = '1', `lastdate` = NOW() WHERE `id` = '%d' LIMIT 1", PLAYER [ playerid ] [ ID ] ) ;
		mysql_function_query ( dbHandle, query, false, "", "" ) ;
		
		CreateTextDrawForHospital ( playerid ) ;
		CreateTextDrawForJail ( playerid ) ;
		CreateTextDrawForSpeedometr ( playerid ) ;
		//CreateZoneNames ( playerid ) ;
		
		PlayerTextDrawShow ( playerid, ZoneName [ playerid ] ) ;		
		
		ResetPlayerMoney ( playerid ) ;
		GivePlayerMoney ( playerid, PLAYER [ playerid ] [ MONEY ] ) ;
		
		PLAYER [ playerid ] [ TIMER ] [ 0 ] = SetTimerEx ( "PlayerControl", 200,  1, "i", playerid ) ;
		PLAYER [ playerid ] [ TIMER ] [ 1 ] = SetTimerEx ( "OneSecond", 	1000, 1, "i", playerid ) ;
		
		SetSpawnInfo ( playerid, 0, PLAYER [ playerid ] [ SKIN ], _Position [ 0 ], _Position [ 1 ], _Position [ 2 ], _Position [ 3 ], 0, 0, 0, 0, 0, 0 ) ;
		SetPlayerInterior ( playerid, set [ 0 ] ) ;
		SetPlayerVirtualWorld ( playerid, set [ 1 ] ) ;
		SpawnPlayer ( playerid ) ;
		
		MySetPlayerPos ( playerid, _Position [ 0 ], _Position [ 1 ], _Position [ 2 ], _Position [ 3 ], set [ 0 ], set [ 1 ] ) ;
		
		SendClientMessage ( playerid, COLOR_DGREEN, "========================================" ) ;
		echo ( temp, "Добро пожаловать в Штат, %s!", PlayerName [ playerid ] ) ;
		SendClientMessage ( playerid, -1, temp ) ;
		SendClientMessage ( playerid, COLOR_GOLD, "Используй /гид если заблудился." ) ;
		SendClientMessage ( playerid, COLOR_GOLD, "Всю информацию ты можешь найти в /помощь." ) ;
		SendClientMessage ( playerid, COLOR_DGREEN, "========================================" ) ;
		
		new bool:message = false;
		
		cache_get_field_content ( 0, "mail", temp ) ;
		if ( strlen ( temp ) == 0 )
			SendClientMessage ( playerid, COLOR_WARNS, "Внимание! У тебя не заполнен E-Mail адрес. В случае утраты пароля, мы не сможем восстановить тебе пароль!" ), message = true ;
		
		cache_get_field_content ( 0, "key", temp ) ;
		if ( strlen ( temp ) == 0 )
			SendClientMessage ( playerid, COLOR_WARNS, "Внимание! У тебя не заполнен Код протекции. В случае взлома акаунта, мы не сможем защитить твое имущество!" ), message = true ;
		
		if ( message == true )
			SendClientMessage ( playerid, COLOR_GRAY, "Что-бы заполнить данные воспользуйся /меню -> Безопасность" ) ;
		
		SetPVarInt ( playerid, "Session", gettime ( ) ) ;
		SetPVarInt ( playerid, "Logged", 1 ) ;
		DeletePVar ( playerid, "WrongPassword" ) ;

	}
	else
	{
		if ( GetPVarInt ( playerid, "WrongPassword" ) == 4 )
		{
			echo ( temp, "%s[%d] заблокирован AntiCheatSystem. Причина: Неправильный ввод пароля 5 раз", PlayerName [ playerid ], playerid ) ;
			SendToAdmins ( COLOR_ADM, temp  ) ;
			Send ( playerid, COLOR_ADM, temp ) ;
			KickEx ( playerid ) ;
			return 1;
		}
		
		SetPVarInt ( playerid, "WrongPassword", GetPVarInt ( playerid, "WrongPassword" ) + 1 ) ;
		
		strcat ( query, "{FFFFFF}---------------------------------------------------------------------\n\n" ) ;
		strcat ( query, "Добро пожаловать на {33AAFF}"NAME_SERVER"\n\n" ) ;
		echo   ( temp,	"{FFFFFF}Логин {33AAFF}%s {FFFFFF}зарегистрирован\n\n", PlayerName [ playerid ] ) ;
		strcat ( query, temp ) ;
		strcat ( query, "Введи пароль (мин. 6 симв.)\n" ) ;
		echo   ( temp, "{FF0000}Не верный пароль. Осталось попыток %d \n\n", 5 - GetPVarInt ( playerid, "WrongPassword" ) ) ;
		strcat ( query, temp ) ;
		strcat ( query, "{FFFFFF}---------------------------------------------------------------------\n" ) ;
		
		ShowDialog ( playerid, Show:Login, DIALOG_STYLE_PASSWORD, "{FFFFFF}Авторизация", query, "Ввести", "" ) ;
	}
	return 1;
}

/*#######################################################################################################################################################
#################################################	    	Смена Е-Мail адреса		  ###################################################################
#########################################################################################################################################################*/

forward ChangeMail ( playerid ) ;
public ChangeMail ( playerid )
{
	new rows, fields;
	cache_get_data ( rows, fields ) ;
	if ( rows )
	{
		new string [ 128 ], mail [ 65 ] ;
		cache_get_field_content ( 0, "mail", mail ) ;
		
		echo ( string, "E-Mail: %s\nВведи код активации:", mail ) ;
		
		ShowPlayerDialog ( playerid, DIALOG_CHANGE_MAIL, DIALOG_STYLE_INPUT, "{FFFFFF}Активация E-Mail", string, "Ввод", "Назад" ) ;
		SetPVarInt ( playerid, "ChangeMailStep", 1 ) ;
	}
	else ShowPlayerDialog ( playerid, DIALOG_CHANGE_MAIL, DIALOG_STYLE_INPUT, "{FFFFFF}E-Mail", "Введи свой E-Mail\n\n{FF0000}ВНИМАНИЕ! На указаный адрес придет код активации который нужно будет ввести.", "Ввод", "Назад" ) ;
	
	return 1;
}

/*#######################################################################################################################################################
#################################################		 	  Сохраняем акаунт		  ###################################################################
#########################################################################################################################################################*/

stock SaveAccount ( playerid ) 
{
	printf ( "SaveAccount ( %s )", PlayerName [ playerid ] ) ;
	
	new query [ 1024 ], to_query [ 512 ] ;
	
	echo ( query, "UPDATE `players` SET " ) ;
	
	echo ( to_query, 
	"`skin` = '%d', \
	`age` = '%d', \
	`game_session` = '%d', \
	`hour` = '%d', \
	`admin` = '%d', \
	`helper` = '%d', \
	`int` = '%d', \
	`world` = '%d', \
	`money` = '%d', \
	`bank` = '%d', \
	`hospital` = '%d', \
	`hospital_time` = '%d', \
	`jail` = '%d', \
	`jail_time` = '%d', \
	`leader` = '%d', \
	`fraction` = '%d', \
	`rank` = '%d', \
	`post` = '%d', \
	`job` = '%d', \
	`lastdate` = NOW(), ", 
	PLAYER [ playerid ] [ SKIN ], 
	PLAYER [ playerid ] [ AGE ], 
	PLAYER [ playerid ] [ GAME_SESSION ] + ( gettime () - GetPVarInt ( playerid, "Session" ) ), 
	PLAYER [ playerid ] [ HOUR ], 
	PLAYER [ playerid ] [ ADMIN ], 
	PLAYER [ playerid ] [ HELPER ], 
	PLAYER [ playerid ] [ PINTERIOR ], 
	PLAYER [ playerid ] [ PWORLD ], 
	PLAYER [ playerid ] [ MONEY ], 
	PLAYER [ playerid ] [ BANK ], 
	PLAYER [ playerid ] [ HOSPITAL ], 
	PLAYER [ playerid ] [ HOSPITAL_TIME ], 
	PLAYER [ playerid ] [ JAIL ], 
	PLAYER [ playerid ] [ JAIL_TIME ], 
	PLAYER [ playerid ] [ LEADER ], 
	PLAYER [ playerid ] [ FRAC ], 
	PLAYER [ playerid ] [ RANK ], 
	PLAYER [ playerid ] [ POST ], 
	PLAYER [ playerid ] [ JOB ] ) ;
	strcat ( query, to_query ) ;
	
	echo ( to_query, 
	"`pos_x` = '%f', \
	`pos_y` = '%f', \
	`pos_z` = '%f', \
	`face_angle` = '%f', \
	`hp` = '%f', \
	`armour` = '%f', \
	`satiety` = '%f' ",
	PLAYER [ playerid ] [ POSITION ] [ 0 ],
	PLAYER [ playerid ] [ POSITION ] [ 1 ],
	PLAYER [ playerid ] [ POSITION ] [ 2 ],
	PLAYER [ playerid ] [ POSITION ] [ 3 ],
	PLAYER [ playerid ] [ HEALTH ], 
	PLAYER [ playerid ] [ ARMOUR ],
	PLAYER [ playerid ] [ SATIETY ] ) ;
	strcat ( query, to_query ) ;
	
	echo ( to_query, "WHERE `id` = '%d' LIMIT 1", PLAYER [ playerid ] [ ID ] ) ;
	strcat ( query, to_query ) ;
	
	mysql_function_query ( dbHandle, query, false, "", "" ) ;
	return 1;
}

/*#######################################################################################################################################################
################################################# 		Список авторизаций	игрока	  ###################################################################
#########################################################################################################################################################*/


forward AuthorizationLog ( playerid, item, list );
public AuthorizationLog ( playerid, item, list ) 
{
	new rows, fields, date [ 11 ], time [ 9 ], ip [ 16 ];
	cache_get_data ( rows, fields ) ;
	
	if ( list == -1 )
	{
		if ( item == -1 )
		{
			new log [ 90 ], to_log [ 12 ] ;
			
			for ( new i = 0; i < rows; i++ )
			{
				cache_get_field_content ( i, "date", date ) ;
				echo	( to_log, "%s\n", date ) ;
				strcat	( log, to_log ) ;
			}
			ShowPlayerDialog ( playerid, DIALOG_AUTH_LOG, DIALOG_STYLE_LIST, "{FFFFFF}Лог авторизаций (за 7 дней)", log, "Выбрать", "Назад" ) ;
		}
		else
		{
			cache_get_field_content ( item, "date", date ) ;
			new query [ 128 ] ;
			echo ( query, "SELECT * FROM `authorization_log` WHERE `id_player` = '%d' AND `date` = '%s' ORDER BY `time` DESC LIMIT 20", PLAYER [ playerid ] [ ID ], date ) ;
			mysql_function_query ( dbHandle, query, true, "AuthorizationLog", "iii", playerid, -1, 1 ) ;
		}
	}
	else
	{
		new log [ 600 ], to_log [ 42 ] ;
		
		echo	( log, "{FF0000}Показаны последние 20 авторизаций.\nПодробней можно посмотреть на сайте\n\n" ) ;
		strcat	( log, "{33AAFF}Время \t\t\t\t IP \n{9CB6D6}" ) ;
		for ( new i = 0; i < rows; i++ )
		{
			cache_get_field_content ( i, "time", time ) ;
			cache_get_field_content ( i, "ip", ip ) ;
			echo	( to_log, "%s \t\t\t %s \n", time, ip ) ;
			strcat	( log, to_log ) ;
		}
		
		cache_get_field_content ( 0, "date", date ) ;
		echo ( to_log, "{FFFFFF}Лог авторизаций за %s", date ) ;
		
		ShowPlayerDialog ( playerid, DIALOG_AUTH_LOG, DIALOG_STYLE_MSGBOX, to_log, log, "Назад", "" ) ;
	}
	return 1;
}

/*#######################################################################################################################################################
################################################# 				Список лидеров		  ###################################################################
#########################################################################################################################################################*/


forward LeaderList ( playerid, listitem );
public LeaderList ( playerid, listitem ) 
{
	new rows, fields, temp [ 50 ], list [ 500 ], text [ 128 ], fid = GetPVarInt ( playerid, "Frac_ID" ), name [ MAX_PLAYER_NAME ] ;
	cache_get_data ( rows, fields ) ;
	if ( rows )
	{
		if ( listitem == -1 )
		{
			for ( new i = 0; i < rows; i++)
			{
				new to_list [ 56 ], status [ 14 ] ;
				
				cache_get_field_content ( i, "name", temp ), sscanf ( temp, "s[24]", name ) ;
				
				if ( ReturnPlayerId ( name ) != -1 )
					echo ( status, "{00FF00}(ON)" ) ;
				else
					echo ( status, "{FF0000}(OFF)" ) ;
				
				echo ( to_list, "%s %s\n", name, status ) ;
				strcat ( list, to_list ) ;
			}
			
			echo ( text, "{FFFFFF}%s - Лидеры", FRACTION [ fid ] [ Name ] ) ;
			ShowPlayerDialog ( playerid, DIALOG_UNMAKE_LEADER, DIALOG_STYLE_LIST, text, list, "Снять", "Назад" ) ;
		}
		else
		{
			new mid;
			
			cache_get_field_content ( listitem, "name", temp ), sscanf ( temp, "s[24]", name ) ;
			cache_get_field_content ( listitem, "id", temp ), mid = strval ( temp ) ;
			
			new id_player = ReturnPlayerId ( name ) ;
			
			if ( id_player != -1 )
			{
				echo ( text , "Ты снят с должности лидера, администратором %s", PlayerName [ playerid ] ) ;
				Send ( id_player, COLOR_ADM, text ) ;
				PLAYER [ id_player ] [ LEADER ] = 0 ;
				PLAYER [ id_player ] [ FRAC ] = 0 ;
				PLAYER [ id_player ] [ RANK ] = 0 ;
				PLAYER [ id_player ] [ POST ] = 0 ;
			}
			
			echo ( list, "UPDATE `players` SET `leader` = '0' WHERE `id` = '%d' LIMIT 1", mid ) ;
			mysql_function_query ( dbHandle, list, false, "", "" ) ;
			
			echo ( text, "Ты снял %s с должности лидера", name ) ;
			Send ( playerid, COLOR_ADM, text ) ;
			
			ShowPlayerDialog ( playerid, DIALOG_FRAC_EDIT, DIALOG_STYLE_LIST, FRACTION [ fid ] [ Name ], "Назначить лидера\nСписок лидеров\nИзменить название\nИзменить цвет\nИзменить положение сейфа\nИзменить ранги\nИзменить посты\nИзменить скины", "Выбрать", "Назад" ) ;
		}
	}
	else
	{
		Send ( playerid, COLOR_GRAY, "Лидеры не назначены!" ) ;
		ShowPlayerDialog ( playerid, DIALOG_FRAC_EDIT, DIALOG_STYLE_LIST, FRACTION [ fid ] [ Name ], "Назначить лидера\nСписок лидеров\nИзменить название\nИзменить цвет\nИзменить положение сейфа\nИзменить ранги\nИзменить посты", "Выбрать", "Назад" ) ;
	}
	return 1;
}

/*#######################################################################################################################################################
################################################# 		Список администрации		  ###################################################################
#########################################################################################################################################################*/

forward AdminList ( playerid, listitem );
public AdminList ( playerid, listitem ) 
{
	new rows, fields, temp [ 50 ], list [ 500 ] ;
	cache_get_data ( rows, fields ) ;
	if ( rows )
	{
		if ( listitem == -1 )
		{
			for ( new i = 0; i < rows; i++ )
			{
				new name [ MAX_PLAYER_NAME ], lvl, to_list [ 56 ], status [ 14 ] ;
				
				cache_get_field_content ( i, "name", temp ), sscanf ( temp, "s[24]", name ) ;
				cache_get_field_content ( i, "admin", temp ), lvl = strval ( temp ) ;
				
				if ( ReturnPlayerId ( name ) != -1 )
					echo ( status, "{00FF00}(ON)" ) ;
				else
					echo ( status, "{FF0000}(OFF)" ) ;
				
				echo ( to_list, "%s [%s] %s\n", name, AdminRanks [ lvl - 1 ], status ) ;
				strcat ( list, to_list ) ;
			}
		
			ShowPlayerDialog ( playerid, DIALOG_ADMIN_LIST, DIALOG_STYLE_LIST, "{FFFFFF}Список администраторов!", list, "Выбрать", "Назад" ) ;
		}
		else
		{
			new name [ MAX_PLAYER_NAME ], lvl, text [ 128 ], status [ 14 ] ;
			cache_get_field_content ( listitem, "name", temp ), sscanf ( temp, "s[24]", name ) ;
			cache_get_field_content ( listitem, "admin", temp ), lvl = strval ( temp ) ;

			cache_get_field_content ( listitem, "id", temp ), SetPVarInt ( playerid, "Admin_ID", strval ( temp ) ) ;
			SetPVarString ( playerid, "Admin_Name", name ) ;
			SetPVarInt ( playerid, "Admin_LVL", lvl ) ;
			
			if ( ReturnPlayerId ( name ) != -1 )
				echo ( status, "{00FF00}(ON)" ) ;
			else
				echo ( status, "{FF0000}(OFF)" ) ;
			
			echo ( text, "%s [%s] %s", name, AdminRanks [ lvl - 1 ], status ) ;
			
			ShowPlayerDialog ( playerid, DIALOG_ADMIN_OPTIONS, DIALOG_STYLE_LIST, text, "Повысить\nПонизить\nСнять", "Выбрать", "Назад" ) ;
		}
	}
	else Send ( playerid, COLOR_GRAY, "Администраторы не назначены" ) ;
	return 1;
}

/*#######################################################################################################################################################
################################################# 		Загружаем фракции			  ###################################################################
#########################################################################################################################################################*/

forward LoadFractions ( );
public LoadFractions ( ) 
{
	new rows, fields, temp [ 50 ], ranks [ 650 ], skins [ 128 ] ;
	cache_get_data ( rows, fields ) ;
	FractionCount = rows;
	if ( rows )
	{
		for ( new i = 0; i < rows; i++ )
		{
			cache_get_field_content ( i, "id", temp ), FRACTION [ i ] [ ID ] = strval ( temp ) ;
			cache_get_field_content ( i, "name", temp ), sscanf ( temp, "s[50]", FRACTION [ i ] [ Name ] ) ;
			cache_get_field_content ( i, "safe_money", temp ), FRACTION [ i ] [ Money ] = strval ( temp ) ;
			cache_get_field_content ( i, "safe_pos_x", temp ), FRACTION [ i ] [ SafePosition ] [ 0 ]  = floatstr ( temp ) ;
			cache_get_field_content ( i, "safe_pos_y", temp ), FRACTION [ i ] [ SafePosition ] [ 1 ] = floatstr ( temp ) ;
			cache_get_field_content ( i, "safe_pos_z", temp ), FRACTION [ i ] [ SafePosition ] [ 2 ] = floatstr ( temp ) ;
			cache_get_field_content ( i, "color", temp ), sscanf ( temp, "h", FRACTION [ i ] [ Color ] ) ;
			cache_get_field_content ( i, "type", temp ), FRACTION [ i ] [ Type ] = strval ( temp ) ;
			
			cache_get_field_content ( i, "ranks", ranks ), sscanf ( ranks,
			"p<|>s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]", 
			FRACRANG [ i ] [ 0 ], FRACRANG [ i ] [ 1 ], FRACRANG [ i ] [ 2 ], FRACRANG [ i ] [ 3 ], FRACRANG [ i ] [ 4 ],
			FRACRANG [ i ] [ 5 ], FRACRANG [ i ] [ 6 ], FRACRANG [ i ] [ 7 ], FRACRANG [ i ] [ 8 ], FRACRANG [ i ] [ 9 ],
			FRACRANG [ i ] [ 10 ], FRACRANG [ i ] [ 11 ], FRACRANG [ i ] [ 12 ], FRACRANG [ i ] [ 13 ], FRACRANG [ i ][ 14 ],
			FRACRANG [ i ] [ 15 ], FRACRANG [ i ] [ 16 ], FRACRANG [ i ] [ 17 ], FRACRANG [ i ] [ 18 ], FRACRANG [ i ] [ 19 ] ) ;

			cache_get_field_content ( i, "posts", ranks ), sscanf ( ranks,
			"p<|>s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]s[30]", 
			FRACPOST [ i ] [ 0 ], FRACPOST [ i ] [ 1 ], FRACPOST [ i ] [ 2 ], FRACPOST [ i ] [ 3 ], FRACPOST [ i ] [ 4 ],
			FRACPOST [ i ] [ 5 ], FRACPOST [ i ] [ 6 ], FRACPOST [ i ] [ 7 ], FRACPOST [ i ] [ 8 ], FRACPOST [ i ] [ 9 ],
			FRACPOST [ i ] [ 10 ], FRACPOST [ i ] [ 11 ], FRACPOST [ i ] [ 12 ], FRACPOST [ i ] [ 13 ], FRACPOST [ i ] [ 14 ],
			FRACPOST [ i ] [ 15 ], FRACPOST [ i ] [ 16 ], FRACPOST [ i ] [ 17 ], FRACPOST [ i ] [ 18 ], FRACPOST [ i ] [ 19 ] ) ;
			
			cache_get_field_content ( i, "skins", skins ), sscanf ( skins,
			"p<|>dddddddddddddddddddd", 
			FRACTION [ i ] [ Skins ] [ 0 ], FRACTION [ i ] [ Skins ] [ 1 ], FRACTION [ i ] [ Skins ] [ 2 ], FRACTION [ i ] [ Skins ] [ 3 ],
			FRACTION [ i ] [ Skins ] [ 4 ], FRACTION [ i ] [ Skins ] [ 5 ], FRACTION [ i ] [ Skins ] [ 6 ], FRACTION [ i ] [ Skins ] [ 7 ],
			FRACTION [ i ] [ Skins ] [ 8 ], FRACTION [ i ] [ Skins ] [ 9 ], FRACTION [ i ] [ Skins ] [ 10 ], FRACTION [ i ] [ Skins ] [ 11 ],
			FRACTION [ i ] [ Skins ] [ 12 ], FRACTION [ i ] [ Skins ] [ 13 ], FRACTION [ i ] [ Skins ] [ 14 ], FRACTION [ i ] [ Skins ] [ 15 ], 
			FRACTION [ i ] [ Skins ] [ 16 ], FRACTION [ i ] [ Skins ] [ 17 ], FRACTION [ i ] [ Skins ] [ 18 ], FRACTION [ i ] [ Skins ] [ 19 ] ) ;
			
			new safe [ 64 ] ;
			format ( safe, 64, "Сейф %s", FRACTION [ i ] [ Name ] ) ;
			FRACTION [ i ] [ Safe ] = CreateDynamic3DTextLabel ( safe, FRACTION [ i ] [ Color ], FRACTION [ i ] [ SafePosition ] [ 0 ], FRACTION [ i ] [ SafePosition ] [ 1 ], FRACTION [ i ] [ SafePosition ] [ 2 ], 10.0 ) ;
		}
		
		printf ( "Создано фракций: %d", FractionCount ) ;
	}
	else
	{
		print ( "Фракции не созданы" ) ;
	}
	return 1;
}

/*#######################################################################################################################################################
################################################# 			Сохраняем фракции	 	  ###################################################################
#########################################################################################################################################################*/

stock SaveFractions ( ) 
{
	for ( new fid = 0; fid < FractionCount ; fid++ )
	{
		if ( !FRACTION [ fid ] [ ID ] ) continue;
		
		new query [ 1024 ], escape_list [ 666 ], escape_name [ 50 ] ;
		
		mysql_real_escape_string ( FRACTION [ fid ] [ Name ], escape_name ) ;
		
		echo ( query,
		"UPDATE `fractions` SET \
		`safe_pos_x` = '%f', \
		`safe_pos_y` = '%f', \
		`safe_pos_z` = '%f', \
		`safe_money` = '%d', \
		`color` = '%h', \
		`name` = '%s' \
		WHERE `id` = '%d' LIMIT 1", 
		FRACTION [ fid ] [ SafePosition ] [ 0 ],
		FRACTION [ fid ] [ SafePosition ] [ 1 ],
		FRACTION [ fid ] [ SafePosition ] [ 2 ],
		FRACTION [ fid ] [ Money ],
		FRACTION [ fid ] [ Color ],
		escape_name,
		FRACTION [ fid ] [ ID ] ) ;
		mysql_function_query ( dbHandle, query, false, "", "" ) ;
		
		
		for ( new i = 0; i < 20; i++ )
		{
			new to_list [ 33 ] ;
			echo ( to_list, "%s%s", FRACRANG [ fid ] [ i ], ( i < 19 ) ? ( "|" ) : ( "" ) ) ;
			strcat ( escape_list, to_list ) ;
		}
		mysql_real_escape_string ( escape_list, escape_list ) ;
		echo ( query, "UPDATE `fractions` SET `ranks` = '%s' WHERE `id` = '%d' LIMIT 1", escape_list, FRACTION [ fid ] [ ID ] ) ;
		mysql_function_query ( dbHandle, query, false, "", "" ) ;
		
		echo ( escape_list, "" ) ;
		
		for ( new i = 0; i < 20; i++ )
		{
			new to_list [ 33 ] ;
			echo ( to_list, "%s%s", FRACPOST [ fid ] [ i ], ( i < 19 ) ? ( "|" ) : ( "" ) ) ;
			strcat ( escape_list, to_list ) ;
		}
		mysql_real_escape_string ( escape_list, escape_list ) ;
		format ( query, sizeof ( query ), "UPDATE `fractions` SET `posts` = '%s' WHERE `id` = '%d' LIMIT 1", escape_list, FRACTION [ fid ] [ ID ] ) ;
		mysql_function_query ( dbHandle, query, false, "", "" ) ;
		
		echo ( escape_list, "" ) ;
		
		for ( new i = 0; i < 20; i++ )
		{
			new to_list [ 33 ] ;
			echo ( to_list, "%d%s", FRACTION [ fid ] [ Skins ] [ i ], ( i < 19 ) ? ( "|" ) : ( "" ) ) ;
			strcat ( escape_list, to_list ) ;
		}
		mysql_real_escape_string ( escape_list, escape_list ) ;
		format ( query, sizeof ( query ), "UPDATE `fractions` SET `skins` = '%s' WHERE `id` = '%d' LIMIT 1", escape_list, FRACTION [ fid ] [ ID ] ) ;
		mysql_function_query ( dbHandle, query, false, "", "" ) ;
	}
	return 1;
}

forward NewSalonVehicle ( vehicleid ) ;
public NewSalonVehicle ( vehicleid )
{
	new rows, fields, temp [ 11 ] ;
	cache_get_data ( rows, fields ) ;
	if ( rows ) cache_get_field_content ( 0, "last_id", temp ), VEHICLE [ vehicleid ] [ MID ] = strval ( temp ) ;
	
	return 1;
}

/*#######################################################################################################################################################
#################################################			 Загружаем авто		   	  ###################################################################
#########################################################################################################################################################*/

forward LoadVehicles ( );
public LoadVehicles ( ) 
{
	new rows, fields, temp [ 50 ], vehicleid, model, type, time_resp, Float:_Position [ 4 ] ;
	cache_get_data ( rows, fields ) ;
	if ( rows )
	{
		for ( new i = 0; i < rows; i++)
		{
			cache_get_field_content ( i, "pos_x", temp ), _Position [ 0 ] = floatstr ( temp ) ;
			cache_get_field_content ( i, "pos_y", temp ), _Position [ 1 ] = floatstr ( temp ) ;
			cache_get_field_content ( i, "pos_z", temp ), _Position [ 2 ] = floatstr ( temp ) ;
			cache_get_field_content ( i, "angle", temp ), _Position [ 3 ] = floatstr ( temp ) ;
			cache_get_field_content ( i, "model", temp ), model = strval ( temp ) ;
			cache_get_field_content ( i, "type", temp ), type = strval ( temp ) ;

			switch ( type )
			{
				case VJOB: time_resp = 900;
				case VSALON: time_resp = 15;
				case VFRACTION, VRENT: time_resp = -1;
			}
			
			vehicleid = AddStaticVehicleEx ( model, _Position [ 0 ], _Position [ 1 ], _Position [ 2 ], _Position [ 3 ], -1, -1, time_resp ) ;
			
			cache_get_field_content ( i, "id", temp ), VEHICLE [ vehicleid ] [ MID ] = strval ( temp ) ;
			cache_get_field_content ( i, "owner", temp ), VEHICLE [ vehicleid ] [ OWNER ] = strval ( temp ) ;
			cache_get_field_content ( i, "fuel", temp ), VEHICLE [ vehicleid ] [ FUEL ] = floatstr ( temp ) ;
			cache_get_field_content ( i, "plate", temp ), sscanf ( temp, "s[10]", VEHICLE [ vehicleid ] [ PLATE ] ) ;
			cache_get_field_content ( i, "lock", temp ), VEHICLE [ vehicleid ] [ LOCK ] = strval ( temp ) ;
			cache_get_field_content ( i, "engine", temp ), VEHICLE [ vehicleid ] [ ENGINE ] = strval ( temp ) ;
			cache_get_field_content ( i, "health", temp ), VEHICLE [ vehicleid ] [ HEALTH ] = floatstr ( temp ) ;
			cache_get_field_content ( i, "tires", temp ), VEHICLE [ vehicleid ] [ TIRES ] = strval ( temp ) ;
			cache_get_field_content ( i, "panels", temp ), VEHICLE [ vehicleid ] [ PANELS ] = strval ( temp ) ;
			cache_get_field_content ( i, "doors", temp ), VEHICLE [ vehicleid ] [ DOORS ] = strval ( temp ) ;
			cache_get_field_content ( i, "lights", temp ), VEHICLE [ vehicleid ] [ LIGHTS ] = strval ( temp ) ;
			cache_get_field_content ( i, "color_one", temp ), VEHICLE [ vehicleid ] [ COLOR ] [ 0 ] = strval ( temp ) ;
			cache_get_field_content ( i, "color_two", temp ), VEHICLE [ vehicleid ] [ COLOR ] [ 1 ] = strval ( temp ) ;
			cache_get_field_content ( i, "price", temp ), VEHICLE [ vehicleid ] [ PRICE ] = strval ( temp ) ;
			
			switch ( type )
			{
				case VSALON:
				{
					echo ( temp, "Продается: %s | Цена: $%d", VehicleName [ model - 400 ], VEHICLE [ vehicleid ] [ PRICE ] ) ;
					
					VEHICLE [ vehicleid ] [ TEXTID3D ] = CreateDynamic3DTextLabel ( temp, 0x2186A5FF, 0.0, 0.0, 0.0, 15.0, INVALID_PLAYER_ID, vehicleid, 0, 0, 0, -1, 100.0 ) ;
				}
				case VJOB:
				{
					switch ( VEHICLE [ vehicleid ] [ OWNER ] )
					{
						case OIL_TRUCKER:
						{
							CreateTextDrawVehicleLoad ( vehicleid ) ;
							TextDrawSetString ( VEHICLE [ vehicleid ] [ TEXTID ], "OIL LOAD: 0 / 400" ) ;
						}
						case FUEL_TRUCKER:
						{
							CreateTextDrawVehicleLoad ( vehicleid ) ;
							TextDrawSetString ( VEHICLE [ vehicleid ] [ TEXTID ], "FUEL LOAD: 0 / 1000" ) ;						
						}
					}
				}
				case VFRACTION:
				{
					switch ( VEHICLE [ vehicleid ] [ OWNER ] )
					{
						case ID_LIC:
						{
							if ( model == 445 )
							{
								VEHICLE [ vehicleid ] [ OBJECT ] [ 0 ] = CreateDynamicObject ( 19309, _Position [ 0 ], _Position [ 1 ], _Position [ 2 ] + 0.9, 0 ,0 ,0 ) ;
								SetDynamicObjectMaterialText ( VEHICLE [ vehicleid ] [ OBJECT ] [ 0 ], 0, "Учебная", OBJECT_MATERIAL_SIZE_128x64, "Arial", 25, 1, 0xFFFFFFFF, -65536, OBJECT_MATERIAL_TEXT_ALIGN_CENTER ) ;
								AttachDynamicObjectToVehicle ( VEHICLE [ vehicleid ] [ OBJECT ] [ 0 ], vehicleid, 0.0, 0.0, 0.9, 0, 0, 90 ) ;
							}
						}
					}
				}
			}
			
			new lights, alarm, bonnet, boot, objective;
			SetVehicleParamsEx ( vehicleid, VEHICLE [ vehicleid ] [ ENGINE ], lights, alarm, VEHICLE [ vehicleid ] [ LOCK ], bonnet, boot, objective ) ;
			
			SetVehicleHealth ( vehicleid, VEHICLE [ vehicleid ] [ HEALTH ] ) ;
			
			UpdateVehicleDamageStatus ( vehicleid, VEHICLE [ vehicleid ] [ PANELS ], VEHICLE [ vehicleid ] [ DOORS ], VEHICLE [ vehicleid ] [ LIGHTS ], VEHICLE [ vehicleid ] [ TIRES ] ) ;
			
			ChangeVehicleColor ( vehicleid, VEHICLE [ vehicleid ] [ COLOR ] [ 0 ], VEHICLE [ vehicleid ] [ COLOR ] [ 1 ] ) ;
			
			if ( !strcmp ( VEHICLE [ vehicleid ] [ PLATE ], "NULL", true ) )
			{
				if ( type == VJOB )
					sscanf ( "Job Car", "s[8]", VEHICLE [ vehicleid ] [ PLATE ] ) ;
				else
					sscanf ( "Not Plate", "s[10]", VEHICLE [ vehicleid ] [ PLATE ] ) ;
			}
			
			VEHICLE [ vehicleid ] [ ID ] = vehicleid ;
			VEHICLE [ vehicleid ] [ MODEL ] = model ;
			VEHICLE [ vehicleid ] [ TYPE ] = type ;
			VEHICLE [ vehicleid ] [ POSITION ] [ 0 ] = _Position [ 0 ] ;
			VEHICLE [ vehicleid ] [ POSITION ] [ 1 ] = _Position [ 1 ] ;
			VEHICLE [ vehicleid ] [ POSITION ] [ 2 ] = _Position [ 2 ] ;
			VEHICLE [ vehicleid ] [ POSITION ] [ 3 ] = _Position [ 3 ] ;
			
			SetVehicleNumberPlate ( vehicleid, VEHICLE [ vehicleid ] [  PLATE ] ) ;
			
			cvector_push_back ( PVEHICLES, vehicleid ) ;
		}
		
		printf ( "Создано авто: %d", cvector_size ( PVEHICLES ) ) ;
	}
	else
	{
		print ( "Авто не созданы" ) ;
	}
	return 1;
}


/*#######################################################################################################################################################
################################################# 		Сохраняем авто 				  ###################################################################
#########################################################################################################################################################*/

stock SaveVehicles ( ) 
{
	new query [ 1024 ], to_query [ 512 ] ;
	
	for ( new i = cvector_size ( PVEHICLES ) - 1, vehicleid = 0; i != -1 ; --i  )
	{
		vehicleid = cvector_get ( PVEHICLES, i ) ;
		
		if ( vehicleid == -1 ) continue;
		if ( !VEHICLE [ vehicleid ] [ MID ] || VEHICLE [ vehicleid ] [ TYPE ] == VPLAYER ) continue;
		
		echo ( query , "UPDATE `vehicles` SET " ) ;
		
		switch ( VEHICLE [ vehicleid ] [ TYPE ] )
		{
			case VFRACTION, VSALON:
			{
				echo ( to_query , 
				"`pos_x` = '%f', \
				`pos_y` = '%f', \
				`pos_z` = '%f', \
				`angle` = '%f', \
				`fuel` = '%f', \
				`lock` = '%d', \
				`engine` = '%d', \
				`health` = '%f', \
				`tires` = '%d', \
				`panels` = '%d', \
				`doors` = '%d', \
				`lights` = '%d', ",
				VEHICLE [ vehicleid ] [ POSITION ] [ 0 ], 
				VEHICLE [ vehicleid ] [ POSITION ] [ 1 ],
				VEHICLE [ vehicleid ] [ POSITION ] [ 2 ],
				VEHICLE [ vehicleid ] [ POSITION ] [ 3 ],
				VEHICLE [ vehicleid ] [ FUEL ],
				VEHICLE [ vehicleid ] [ LOCK ], 
				VEHICLE [ vehicleid ] [ ENGINE ],
				VEHICLE [ vehicleid ] [ HEALTH ],
				VEHICLE [ vehicleid ] [ TIRES ],
				VEHICLE [ vehicleid ] [ PANELS ],
				VEHICLE [ vehicleid ] [ DOORS ],
				VEHICLE [ vehicleid ] [ LIGHTS ] ) ;
				
				strcat ( query, to_query ) ;
			}
		}
		
		echo ( to_query, 
		"`color_one` = '%d', \
		`color_two` = '%d', \
		`type` = '%d', \
		`price` = '%d', \
		`owner` = '%d' \
		WHERE `id` = '%d' LIMIT 1",
		VEHICLE [ vehicleid ] [ COLOR ] [ 0 ], 
		VEHICLE [ vehicleid ] [ COLOR ] [ 1 ],
		VEHICLE [ vehicleid ] [ TYPE ],
		VEHICLE [ vehicleid ] [ PRICE ],
		VEHICLE [ vehicleid ] [ OWNER ],
		VEHICLE [ vehicleid ] [ MID ] ) ;
		
		strcat ( query, to_query ) ;
		
		mysql_function_query ( dbHandle, query, false, "", "" ) ;
		
		new vehicleidx = cvector_find ( PVEHICLES, vehicleid ) ;
		if ( vehicleidx != -1 ) cvector_remove ( PVEHICLES, vehicleidx ) ;
	}
	return 1;
}


/*#######################################################################################################################################################
################################################# 		Загружаем авто игрока		  ###################################################################
#########################################################################################################################################################*/

forward LoadPlayerVehicles ( playerid );
public LoadPlayerVehicles ( playerid ) 
{
	new rows, fields, temp [ 128 ], vehicleid, model, Float:_Position [ 4 ] ;
	cache_get_data ( rows, fields ) ;
	if ( rows )
	{
		for ( new i = 0; i < rows; i++ )
		{
			cache_get_field_content ( i, "pos_x", temp ), _Position [ 0 ] = floatstr ( temp ) ;
			cache_get_field_content ( i, "pos_y", temp ), _Position [ 1 ] = floatstr ( temp ) ;
			cache_get_field_content ( i, "pos_z", temp ), _Position [ 2 ] = floatstr ( temp ) ;
			cache_get_field_content ( i, "angle", temp ), _Position [ 3 ] = floatstr ( temp ) ;
			cache_get_field_content ( i, "model", temp ), model = strval ( temp ) ;

			vehicleid = CreateVehicle ( model, _Position [ 0 ], _Position [ 1 ], _Position [ 2 ], _Position [ 3 ], -1, -1, -1 ) ;

			cache_get_field_content ( i, "id", temp ), VEHICLE [ vehicleid ] [ MID ] = strval ( temp ) ;
			cache_get_field_content ( i, "owner", temp ), VEHICLE [ vehicleid ] [ OWNER ] = strval ( temp ) ;
			cache_get_field_content ( i, "fuel", temp ), VEHICLE [ vehicleid ] [ FUEL ] = floatstr ( temp ) ;
			cache_get_field_content ( i, "plate", temp ), sscanf ( temp, "s[10]", VEHICLE [ vehicleid ] [ PLATE ] ) ;
			cache_get_field_content ( i, "lock", temp ), VEHICLE [ vehicleid ] [ LOCK ] = strval ( temp ) ;
			cache_get_field_content ( i, "engine", temp ), VEHICLE [ vehicleid ] [ ENGINE ] = strval ( temp ) ;
			cache_get_field_content ( i, "health", temp ), VEHICLE [ vehicleid ] [ HEALTH ] = floatstr ( temp ) ;
			cache_get_field_content ( i, "tires", temp ), VEHICLE [ vehicleid ] [ TIRES ] = strval ( temp ) ;
			cache_get_field_content ( i, "panels", temp ), VEHICLE [ vehicleid ] [ PANELS ] = strval ( temp ) ;
			cache_get_field_content ( i, "doors", temp ), VEHICLE [ vehicleid ] [ DOORS ] = strval ( temp ) ;
			cache_get_field_content ( i, "lights", temp ), VEHICLE [ vehicleid ] [ LIGHTS ] = strval ( temp ) ;
			cache_get_field_content ( i, "paintjob", temp ), VEHICLE [ vehicleid ] [ PAINTJOB ] = strval ( temp ) ;
			cache_get_field_content ( i, "color_one", temp ), VEHICLE [ vehicleid ] [ COLOR ] [ 0 ] = strval ( temp ) ;
			cache_get_field_content ( i, "color_two", temp ), VEHICLE [ vehicleid ] [ COLOR ] [ 1 ] = strval ( temp ) ;

			cache_get_field_content ( i, "tuning", temp ), sscanf ( temp, 
			"p<|>dddddddddddddd", 
			VEHICLE [ vehicleid ] [ TUNING ] [ 0 ] , VEHICLE [ vehicleid ] [ TUNING ] [ 1 ] , VEHICLE [ vehicleid ] [ TUNING ] [ 2 ], 
			VEHICLE [ vehicleid ] [ TUNING ] [ 3 ] , VEHICLE [ vehicleid ] [ TUNING ] [ 4 ] , VEHICLE [ vehicleid ] [ TUNING ] [ 5 ], 
			VEHICLE [ vehicleid ] [ TUNING ] [ 6 ] , VEHICLE [ vehicleid ] [ TUNING ] [ 7 ] , VEHICLE [ vehicleid ] [ TUNING ] [ 8 ], 
			VEHICLE [ vehicleid ] [ TUNING ] [ 9 ] , VEHICLE [ vehicleid ] [ TUNING ] [ 10 ] , VEHICLE [ vehicleid ] [ TUNING ] [ 11 ], 
			VEHICLE [ vehicleid ] [ TUNING ] [ 12 ] , VEHICLE [ vehicleid ] [ TUNING ] [ 13 ] ) ;
			
			
			new lights, alarm, bonnet, boot, objective;
			SetVehicleParamsEx ( vehicleid, VEHICLE [ vehicleid ] [ ENGINE ], lights, alarm, VEHICLE [ vehicleid ] [ LOCK ], bonnet, boot, objective ) ;
			
			SetVehicleHealth ( vehicleid, VEHICLE [ vehicleid ] [ HEALTH ] ) ;
			UpdateVehicleDamageStatus ( vehicleid, VEHICLE [ vehicleid ] [ PANELS ], VEHICLE [ vehicleid ] [ DOORS ], VEHICLE [ vehicleid ] [ LIGHTS ], VEHICLE [ vehicleid ] [ TIRES ] ) ;
			
			ChangeVehicleColor ( vehicleid, VEHICLE [ vehicleid ] [ COLOR ] [ 0 ], VEHICLE [ vehicleid ] [ COLOR ] [ 1 ] ) ;
			ChangeVehiclePaintjob ( vehicleid, VEHICLE [ vehicleid ] [ PAINTJOB ] ) ;
			
			for ( new t; t < 14; t++ ) if ( VEHICLE [ vehicleid ] [ TUNING ] [ t ] ) AddVehicleComponent ( vehicleid, VEHICLE [ vehicleid ] [ TUNING ] [ t ] ) ;
			
			if ( !strcmp ( VEHICLE [ vehicleid ] [  PLATE ], "NULL", true ) ) sscanf ( "Not Plate", "s[10]", VEHICLE [ vehicleid ] [ PLATE ] ) ;
			
			VEHICLE [ vehicleid ] [ ID ] = vehicleid ;
			VEHICLE [ vehicleid ] [ MODEL ] = model ;
			VEHICLE [ vehicleid ] [ TYPE ] = VPLAYER ;
			VEHICLE [ vehicleid ] [ POSITION ] [ 0 ] = _Position [ 0 ] ;
			VEHICLE [ vehicleid ] [ POSITION ] [ 1 ] = _Position [ 1 ] ;
			VEHICLE [ vehicleid ] [ POSITION ] [ 2 ] = _Position [ 2 ] ;
			VEHICLE [ vehicleid ] [ POSITION ] [ 3 ] = _Position [ 3 ] ;
			
			SetVehicleNumberPlate ( vehicleid, VEHICLE [ vehicleid ] [ PLATE ] ) ;
			
			cvector_push_back ( PVEHICLES, vehicleid ) ;
		}
	}
	return 1;
}

/*#######################################################################################################################################################
################################################# 		Сохраняем авто игрока		  ###################################################################
#########################################################################################################################################################*/

stock SavePlayerVehicles ( playerid ) 
{
	new query [ 1024 ] ;
	
	for ( new i = cvector_size ( PVEHICLES ) - 1, vehicleid = 0; i != -1 ; --i  )
	{
		vehicleid = cvector_get ( PVEHICLES, i ) ;
		
		if ( vehicleid == -1 ) continue;
		if ( !VEHICLE [ vehicleid ] [ MID ] ) continue;

		if ( VEHICLE [ vehicleid ] [ TYPE ] == VPLAYER && VEHICLE [ vehicleid ] [ OWNER ] == PLAYER [ playerid ] [ ID ] )
		{
			echo ( query, 
			"UPDATE `vehicles` SET \
			`pos_x` = '%f', \
			`pos_y` = '%f', \
			`pos_z` = '%f', \
			`angle` = '%f', \
			`fuel` = '%f', \
			`lock` = '%d', \
			`engine` = '%d', \
			`health` = '%f', \
			`tires` = '%d', \
			`panels` = '%d', \
			`doors` = '%d', \
			`lights` = '%d', \
			`color_one` = '%d', \
			`color_two` = '%d', \
			`tuning` = '%d|%d|%d|%d|%d|%d|%d|%d|%d|%d|%d|%d|%d|%d', \
			`paintjob` = '%d', \
			`type` = '%d', \
			`price` = '%d', \
			`owner` = '%d' \
			WHERE `id` = '%d' LIMIT 1", 
			VEHICLE [ vehicleid ] [ POSITION ] [ 0 ], 
			VEHICLE [ vehicleid ] [ POSITION ] [ 1 ], 
			VEHICLE [ vehicleid ] [ POSITION ] [ 2 ],
			VEHICLE [ vehicleid ] [ POSITION ] [ 3 ], 
			VEHICLE [ vehicleid ] [ FUEL ], 
			VEHICLE [ vehicleid ] [ LOCK ], 
			VEHICLE [ vehicleid ] [ ENGINE ], 
			VEHICLE [ vehicleid ] [ HEALTH ],
			VEHICLE [ vehicleid ] [ TIRES ],
			VEHICLE [ vehicleid ] [ PANELS ],
			VEHICLE [ vehicleid ] [ DOORS ],
			VEHICLE [ vehicleid ] [ LIGHTS ],
			VEHICLE [ vehicleid ] [ COLOR ] [ 0 ], 
			VEHICLE [ vehicleid ] [ COLOR ] [ 1 ],
			VEHICLE [ vehicleid ] [ TUNING ] [ 0 ], VEHICLE [ vehicleid ] [ TUNING ] [ 1 ],
			VEHICLE [ vehicleid ] [ TUNING ] [ 2 ], VEHICLE [ vehicleid ] [ TUNING ] [ 3 ], 
			VEHICLE [ vehicleid ] [ TUNING ] [ 4 ], VEHICLE [ vehicleid ] [ TUNING ] [ 5 ], 
			VEHICLE [ vehicleid ] [ TUNING ] [ 6 ], VEHICLE [ vehicleid ] [ TUNING ] [ 7 ], 
			VEHICLE [ vehicleid ] [ TUNING ] [ 8 ], VEHICLE [ vehicleid ] [ TUNING ] [ 9 ], 
			VEHICLE [ vehicleid ] [ TUNING ] [ 10 ], VEHICLE [ vehicleid ] [ TUNING ] [ 11 ], 
			VEHICLE [ vehicleid ] [ TUNING ] [ 12 ], VEHICLE [ vehicleid ] [ TUNING ] [ 13 ],
			VEHICLE [ vehicleid ] [ PAINTJOB ],
			VEHICLE [ vehicleid ] [ TYPE ],
			VEHICLE [ vehicleid ] [ PRICE ],
			VEHICLE [ vehicleid ] [ OWNER ],
			VEHICLE [ vehicleid ] [ MID ] ) ;

			mysql_function_query ( dbHandle, query, false, "", "" ) ;
			
			ClearVehicleInfo ( vehicleid ) ;
			DestroyVehicle ( vehicleid ) ;
			
			new vehicleidx = cvector_find ( PVEHICLES, vehicleid ) ;
			if ( vehicleidx != -1 ) cvector_remove ( PVEHICLES, vehicleidx ) ;
		}
	}
	return 1;
}

/*#######################################################################################################################################################
################################################# Загрузка серверной информации		  ###################################################################
#########################################################################################################################################################*/

forward LoadData ( ) ;
public LoadData ( )
{
	new rows, fields, temp[50], string[128];
	cache_get_data(rows, fields);
	if ( rows )
	{
		print ( "------------------------------------" );
		
		cache_get_field_content ( 0, "oil", temp ), DATA [ OIL ] = floatstr ( temp ) ;
		cache_get_field_content ( 0, "plant_oil", temp ), DATA [ PLANTOIL ] = floatstr ( temp ) ;
		cache_get_field_content ( 0, "plant_fuel", temp ), DATA [ PLANTFUEL ] = floatstr ( temp ) ;
		
		format ( string, sizeof ( string ), "Нефтяная вышка\nНефть: %.0f\nЗагруженость: %.1f%", DATA [ OIL ], ( DATA [ OIL ] / 2400 ) * 100 ) ;
		DATA [ OILTEXT ] = CreateDynamic3DTextLabel ( string, -1, 627.7416, 1357.9011, 13.1828, 25.0, INVALID_PLAYER_ID, INVALID_VEHICLE_ID, 0, 0, 0 ) ;
		CreateDynamicMapIcon ( 627.7416, 1357.9011, 13.1828, 11, 0, 0, 0, -1, 200.0 ) ;
		
		format ( string, sizeof ( string ), "Завод\nНефть: %.0f", DATA [ PLANTOIL ] ) ;
		DATA [ POTEXT ]  = CreateDynamic3DTextLabel ( string, -1, 245.0248, 1420.2291, 10.5574, 25.0, INVALID_PLAYER_ID, INVALID_VEHICLE_ID, 0, 0, 0 ) ;
		
		format ( string, sizeof ( string ), "Завод\nБензин: %.0f", DATA [ PLANTFUEL ] ) ;
		DATA [ PFTEXT ]  = CreateDynamic3DTextLabel ( string, -1, 245.2013, 1396.1296, 10.6802, 25.0, INVALID_PLAYER_ID, INVALID_VEHICLE_ID, 0, 0, 0 ) ;
		
		cp[0] = CreateDynamicCP ( 619.1220, 1357.8224, 11.8665, 3, 0, 0, -1, 5000.0 ) ;
		cp[1] = CreateDynamicCP ( 245.0248, 1420.2291, 10.5574, 3, 0, 0, -1, 5000.0 ) ;
		cp[2] = CreateDynamicCP ( 245.2013, 1396.1296, 10.6802, 3, 0, 0, -1, 5000.0 ) ;
		
		cache_get_field_content ( 0, "tax_auto", temp ), DATA [ TAX ] [ TAUTO ] = strval ( temp ) ;
		cache_get_field_content ( 0, "tax_house", temp ), DATA [ TAX ] [ THOUSE ] = strval ( temp ) ;
		cache_get_field_content ( 0, "tax_busines", temp ), DATA [ TAX ] [ TBUSINES ] = strval ( temp ) ;
		cache_get_field_content ( 0, "dole", temp ), DATA [ TAX ] [ TDOLE ] = strval ( temp ) ;
		cache_get_field_content ( 0, "fond_dole", temp ), DATA [ FOND ] [ FDOLE ] = strval ( temp ) ;
		cache_get_field_content ( 0, "fond_tax", temp ), DATA [ FOND ] [ FTAX ] = strval ( temp ) ;
		
		printf ( "Нефтяная вышка:            %0.2f (%.1f%)", DATA [ OIL ], ( DATA [ OIL ] / 2400 ) * 100 ) ;
		printf ( "Нефть на заводе:           %0.2f", DATA [ PLANTOIL ] ) ;
		printf ( "Бензин на заводе:          %0.2f", DATA [ PLANTFUEL ] ) ;
		printf ( "Налог на авто:             %d%s", DATA [ TAX ] [ TAUTO ], "%" ) ;
		printf ( "Налог на недвижимость:     %d%s", DATA [ TAX ] [ THOUSE ], "%" ) ;
		printf ( "Налог на бизнес:           %d%s", DATA [ TAX ] [ TBUSINES ], "%" ) ;
		printf ( "Пособие по безработице:    %d$", DATA [ TAX ] [ TDOLE ] ) ;
		printf ( "Фонд пособий:              %d$", DATA [ FOND ] [ FDOLE ] ) ;
		printf ( "Фонд налогов:              %d$", DATA [ FOND ] [ FTAX ] ) ;
		
		print ( "------------------------------------" ) ;
	}
	else
	{
		print ( "ERROR: Данные не загружены!" );
	}
	return 1;
}

/*#######################################################################################################################################################
################################################# Сохраняем серверную информацию	  ###################################################################
#########################################################################################################################################################*/

stock SaveData ( )
{
	new query [ 512 ] ;
	
	echo ( query, "UPDATE `data` SET \
	`oil` = '%f', \
	`plant_oil` = '%f', \
	`plant_fuel` = '%f', \
	`tax_auto` = '%d', \
	`tax_house` = '%d', \
	`tax_busines` = '%d', \
	`dole` = '%d', \
	`fond_dole` = '%d', \
	`fond_tax` = '%d' \
	LIMIT 1", 
	DATA [ OIL ], 
	DATA [ PLANTOIL ], 
	DATA [ PLANTFUEL ],
	DATA [ TAX ] [ TAUTO ],
	DATA [ TAX ] [ THOUSE ],
	DATA [ TAX ] [ TBUSINES ],
	DATA [ TAX ] [ TDOLE ],
	DATA [ FOND ] [ FDOLE ],
	DATA [ FOND ] [ FTAX ] ) ;
	
	mysql_function_query ( dbHandle, query, false, "", "" ) ;
	return 1;
}


/*#######################################################################################################################################################
################################################# 		Логируем действия читеров	  ###################################################################
#########################################################################################################################################################*/

stock AntiCheatLog ( playerid, reason[] ) 
{
	new query[256], escape_reason[128];
	mysql_real_escape_string ( reason, escape_reason ) ;
	
	format ( query, sizeof ( query ), "INSERT INTO `anticheat_log` ( `ip`, `id_player`, `reason`, `date`, `time` ) VALUES ( '%s', '%d', '%s', CURDATE(), CURTIME() )", PlayerIp [ playerid ], PLAYER [ playerid ] [ ID ], escape_reason ) ;
	mysql_function_query ( dbHandle, query, false, "", "" ) ;
	
	return 1;
}

/*#######################################################################################################################################################
################################################# Логируем действия администрации	  ###################################################################
#########################################################################################################################################################*/

stock AdminLog ( playerid, reason[], cmd[], amount, pid ) 
{
	new query[256], escape_reason[128];
	mysql_real_escape_string ( reason, escape_reason ) ;
	
	format ( query, sizeof ( query ), "INSERT INTO `admin_log` ( `ip_admin`, `ip_player`, `id_admin`, `id_player`, `reason`, `cmd`, `amount`, `date`, `time` ) VALUES ( '%s', '%s', '%d', '%d', '%s', '%s', '%d', CURDATE(), CURTIME() )", PlayerIp [ playerid ], PlayerIp [ pid ], PLAYER [ playerid ] [ ID ], PLAYER [ pid ] [ ID ], escape_reason, cmd, amount ) ;
	mysql_function_query ( dbHandle, query, false, "", "" ) ;
	
	return 1;
}

/*#######################################################################################################################################################
################################################# 			БАН ЛОГ					  ###################################################################
#########################################################################################################################################################*/

stock BanLog ( playerid, reason[], amount, pid ) 
{
	new query[256], escape_reason[128];
	mysql_real_escape_string ( reason, escape_reason ) ;
	
	format ( query, sizeof ( query ), "INSERT INTO `ban_log` ( `ip_admin`, `ip_player`, `id_admin`, `id_player`, `reason`, `amount`, `date`, `time`, `unban_date` ) VALUES ( '%s', '%s', '%d', '%d', '%s', '%d', CURDATE(), CURTIME(), NOW() + INTERVAL %d DAY )", PlayerIp [ playerid ], PlayerIp [ pid ], PLAYER [ playerid ] [ ID ], PLAYER [ pid ] [ ID ], escape_reason, amount, amount ) ;
	mysql_function_query ( dbHandle, query, false, "", "" ) ;
	
	return 1;
}

/*#######################################################################################################################################################
################################################# 			Логируем рекламы	  	  ###################################################################
#########################################################################################################################################################*/

stock AdvertLog ( playerid, text [ ] )
{
	new query [ 256 ] ;
	
	echo ( query, "INSERT INTO `advertisement_log` ( `ip`, `id_player`, `text`, `date`, `time` ) VALUES ( '%s', '%d', '%s', CURDATE(), CURTIME() )", PlayerIp [ playerid ], PLAYER [ playerid ] [ ID ], text ) ;
	mysql_function_query ( dbHandle, query, false, "", "" ) ;
	
	return 1;
}

/*#######################################################################################################################################################
################################################# 		Логируем авторизации игрока	  ###################################################################
#########################################################################################################################################################*/

stock SetAuthorizationLog ( playerid )
{
	new query [ 256 ] ;
	format ( query, sizeof ( query ), "INSERT INTO `authorization_log` ( `ip`, `id_player`, `date`, `time` ) VALUES ( '%s', '%d', CURDATE(), CURTIME() )", PlayerIp [ playerid ], PLAYER [ playerid ] [ ID ] ) ;
	mysql_function_query ( dbHandle, query, false, "", "" ) ;
	
	return 1;
}

