<?php
	header('Content-Type: text/html; charset=utf-8');

	include('../../../inc/start.php');
	include('../../../inc/protect.php');

	if(!isset($_POST['token']) || $_SESSION['token'] != clean($_POST['token'], null))
		exit(json_encode(array('status' => 'error', 'text' => 'Неверный токен')));

	function get_profile_by_id($id)
	{
		global $pdo;

		$user = $pdo->query('SELECT `id`, `login` FROM `users` WHERE `id`="'.$id.'" LIMIT 1');
				$user->setFetchMode(PDO::FETCH_OBJ);
		$user = $user->fetch();

		if(isset($user->id))
			return '<a target="_blank" href="../profile?id='.$user->id.'"><u>'.$user->login.'</u></a>';

		return 0;
	}

	function get_gamer_profile($nick, $steam_id, $type = 1)
	{
		global $pdo;

		$nick = str_replace(array('/', '\\'), '', check($nick, null));

		if($type == 1)
		{
			$admin = $pdo->query('SELECT `users`.`id`, `users`.`login`, `users`.`avatar` FROM `admins` LEFT JOIN `users` ON `user_id`=`users`.`id` WHERE `admins`.`name`="'.$nick.'" OR `admins`.`name`="'.$steam_id.'" LIMIT 1');
					 $admin->setFetchMode(PDO::FETCH_OBJ);
			$admin = $admin->fetch();
		}

		if(!$admin->id || $type == 2)
		{
			if(empty($steam_id))
			{
				$user = $pdo->query('SELECT `id`, `login` FROM `users` WHERE `nick`="'.$nick.'" LIMIT 1');
						$user->setFetchMode(PDO::FETCH_OBJ);
				$user = $user->fetch();
			}else{
				$user = $pdo->query('SELECT `id`, `login` FROM `users` WHERE `nick`="'.$nick.'" OR `steam_id`="'.$steam_id.'" LIMIT 1');
						$user->setFetchMode(PDO::FETCH_OBJ);
				$user = $user->fetch();
			}
		}

		if(isset($user->id))
			return '<a target="_blank" href="../profile?id='.$user->id.'" title="'.$user->login.'"><u>'.$nick.'</u></a>';

		return 0;
	}

	$tpl = new Template;
	$tpl->dir = '../tpl/ajax/elements/';

	$id = isset($_POST['server']) ? intval($_POST['server']) : 0;
	$start = isset($_POST['start']) ? intval($_POST['start']) : 0;
	$nick = isset($_POST['nick']) ? checkJs($_POST['nick'], null) : '';

	if($nick != '' && iconv_strlen($nick, 'UTF-8') < 2)
	{
		$tpl->load_template('content_none.tpl');
			$tpl->set('{text}', 'Слишком короткий идентификатор');
		$tpl->compile('content');

		exit($tpl->result['content']);
	}

	$limit = $pdo->query('SELECT `bans_lim2` FROM `config2` LIMIT 1');
			 $limit->setFetchMode(PDO::FETCH_OBJ);
	$limit = $limit->fetch();
	$limit = $limit->bans_lim2;

	$price = $pdo->query('SELECT `price2_1`, `price2_2`, `price2_3` FROM `config_prices` LIMIT 1');
			 $price->setFetchMode(PDO::FETCH_OBJ);
	$price = $price->fetch();

	$server = $pdo->query('SELECT `id`, `ip`, `port`, `db_host`, `db_user`, `db_pass`, `db_db`, `db_prefix`, `type`, `db_code`, `name` FROM `servers` WHERE `id`="'.$id.'" AND `type`!="0" LIMIT 1');
			   $server->setFetchMode(PDO::FETCH_OBJ);
	$server = $server->fetch();

	$address = $server->ip.':'.$server->port;

	if(!in_array($server->type, array('1', '2', '3', '4', '5')))
	{
		$tpl->load_template('content_none.tpl');
			$tpl->set('{text}', 'Недопустимое значения "`type`" в таблице `servers`');
		$tpl->compile('content');

		exit($tpl->result['content']);
	}

	if($server->type != '4')
	{
		if(!check_table('comms', $pdo))
		{
			$tpl->load_template('content_none.tpl');
				$tpl->set('{text}', 'Не найдена таблица "comms" в базе данных');
			$tpl->compile('content');

			exit($tpl->result['content']);
		}

		$query = $nick == '' 
			? 'ORDER BY `comms`.`bid` DESC LIMIT '.$start.', '.$limit
			: 'AND (`comms`.`authid` LIKE "%'.strip_data($nick).'%" OR `comms`.`name` LIKE "%'.strip_data($nick).'%") ORDER BY `comms`.`bid` DESC';

		$muts = $pdo->query('SELECT `comms`.`bid`, `comms`.`type`, `comms`.`expired` AS `unban_type`, `comms`.`modified_by` AS `ban_closed`, `comms`.`authid` AS `player_id`, `comms`.`name` AS `player_nick`, `comms`.`created` AS `ban_created`, `comms`.`length` AS `ban_length`, `comms`.`reason` AS `ban_reason`, `comms`.`admin_nick` AS `admin_nick`, `admins`.`name` AS `admin_nick2` FROM `comms` LEFT JOIN `admins` ON `comms`.`admin_id`=`admins`.`id`  WHERE `comms`.`server_id`="'.$id.'" '.$query);
	}else{
		if(!$pdo_remote = db_connect($server->db_host, $server->db_db, $server->db_user, $server->db_pass))
		{
			$tpl->load_template('content_none.tpl');
				$tpl->set('{text}', 'Не удалось подключиться к базе данных');
			$tpl->compile('content');

			exit($tpl->result['content']);
		}

		set_names($pdo_remote, $server->db_code);

		$table_comms = set_prefix($server->db_prefix, 'comms');

		if(!check_table($table_comms, $pdo_remote))
		{
			$tpl->load_template('content_none.tpl');
				$tpl->set('{text}', 'Не найдена таблица "comms" в базе данных (удаленной)');
			$tpl->compile('content');

			exit($tpl->result['content']);
		}

		$table_servers = set_prefix($server->db_prefix, 'servers');
		$server_remote = $pdo_remote->query('SELECT `sid` FROM `'.$table_servers.'` WHERE `ip`="'.$server->ip.'" AND `port`="'.$server->port.'" LIMIT 1');
						 $server_remote->setFetchMode(PDO::FETCH_OBJ); 
		$server_remote = $server_remote->fetch();

		$table_admins = set_prefix($server->db_prefix, 'admins');

		$query = $nick == '' 
			? 'ORDER BY `comms`.`bid` DESC LIMIT '.$start.', '.$limit
			: 'AND (`'.$table_comms.'`.`authid` LIKE "%'.strip_data($nick).'%" OR `'.$table_comms.'`.`name` LIKE "%'.strip_data($nick).'%") ORDER BY `'.$table_comms.'`.`bid` DESC';

		$muts = $pdo_remote->query('SELECT `'
				.$table_comms.'`.`bid`,`'
				.$table_comms.'`.`unban_type`,`'
				.$table_comms.'`.`ban_closed`,`'
				.$table_comms.'`.`type`,`'
				.$table_comms.'`.`RemoveType` AS `expired`,`'
				.$table_comms.'`.`authid` AS `player_id`,`'
				.$table_comms.'`.`name` AS `player_nick`,`'
				.$table_comms.'`.`created` AS `ban_created`,`'
				.$table_comms.'`.`length` AS `ban_length`,`'
				.$table_comms.'`.`reason` AS `ban_reason`,`'
				.$table_comms.'`.`adminip` AS `admin_ip`,`'
				.$table_admins.'`.`user` AS `admin_nick`,`'
				.$table_admins.'`.`nick` AS `admin_nick2`,`'
				.$table_admins.'`.`authid` AS `admin_id` FROM `'
				.$table_comms.'` LEFT JOIN `'
				.$table_admins.'` ON `'.$table_comms.'`.`aid`=`'.$table_admins.'`.`aid` WHERE (`'.$table_comms.'`.`sid`="'.$server_remote->sid.'" OR `'.$table_comms.'`.`sid`="0") '.$query);
	}

	$tpl->result['content'] = '';

	$aData = array(
		0 => array('status' => 'Срок истек', 'color' => 'success', 'display-unmut' => '', 'price' => ''),
		1 => array('status' => 'Размучен', 'color' => 'success', 'display-unmut' => 'disp-n', 'price' => ''),
		2 => array('status' => 'Куплен размут', 'color' => 'success', 'display-unmut' => 'disp-n', 'price' => ''),
		3 => array('status' => 'Никогда', 'color' => 'danger', 'display-unmut' => '', 'price' => $price->price2_3),
		4 => array('status' => '', 'color' => '', 'display-unmut' => '', 'price' => ''),
		5 => array('status' => 'На сессию', 'color' => 'success', 'display-unmut' => '', 'price' => ''),
	);

	$muts->setFetchMode(PDO::FETCH_OBJ);

	$now = $_SERVER['REQUEST_TIME'];

	while($mut = $muts->fetch())
	{
		$ban_length = $server->type != '4' ? $mut->ban_length*60 : $mut->ban_length;
		$ban_created = $mut->ban_created;

		if(expand_seconds2($ban_length))
			$aData = $aData[5];
		else{
			if($mut->unban_type == 1 || (isset($mut->expired) && $mut->expired == 'E'))
				$aData = $aData[0];
			elseif($row->unban_type == '-1' || ($row->unban_type == '-1' && (isset($row->expired) && $row->expired == 'U')))
				$aData = $aData[1];
			elseif($row->unban_type == '-2' || ($row->unban_type == '-2' && (isset($row->expired) && $row->expired == 'U')))
				$aData = $aData[2];
			else{
				if(!$ban_length)
					$aData = $aData[3];
				else{
					$aData = $aData[4];

					$time = date('Y-m-d H:i:s', $ban_created+$ban_length);

					$aData['status'] = expand_date($time, 1);

					if(($ban_created+$ban_length) < $now)
						$aData['color'] = 'success';
					else{
						$date = diff_date($time, date('Y-m-d H:i:s'));

						$aData['price'] = ($date['2'] < 7 && !$date['1'] && !$date['0']) ? $price->price2_1 : $price->price2_2;
					}
				}
			}
		}

		if(strripos($users_groups[$_SESSION['rights']]['rights'], "s") === false)
			$aData['display-unmut'] = 'disp-n';

		$aData['display'] = '';

		if(empty($_SESSION['id']) || (!$price && $aData['display-unmut'] == 'disp-n') || $aData['color'] == 'success')
			$aData['display'] = 'disp-n';

		if(!isset($mut->admin_nick2))
			$mut->admin_nick2 = null;

		$admin_nick = get_ban_admin_nick($mut->admin_nick, $mut->admin_nick2, $server->name, $server->type);

		if($admin_profile = get_gamer_profile($admin_nick, $mut->admin_id))
			$admin_nick = $admin_profile;

		$ban_closed = '';

		if(!empty($mut->ban_closed) && ($user_profile = get_profile_by_id($mut->ban_closed)))
			$ban_closed = $user_profile;

		if(!$ban_length)
			$aData['color'] = 'danger';

		if(!$aData['status'])
			$aData['status'] = 'Никогда';

		$nick = mb_convert_encoding($mut->player_nick, 'WINDOWS-1252', 'UTF-8');

		if(strpos($nick, '???') !== false)
			$nick = $mut->player_nick;

		$reason = mb_convert_encoding($mut->ban_reason, 'WINDOWS-1252', 'UTF-8');

		if(strpos($reason, '???') !== false)
			$reason = $mut->ban_reason;

		$admin_nick_temp = mb_convert_encoding($admin_nick, 'WINDOWS-1252', 'UTF-8');

		if(strpos($admin_nick_temp, '???') === false)
			$admin_nick = $admin_nick_temp;

		$tpl->load_template('mutlist.tpl');
			$tpl->set('{type}', $mut->type);
			$tpl->set('{bid}', $mut->bid);
			$tpl->set('{nick}', check($nick, null));
			$tpl->set('{steamid}', $mut->player_id);
			$tpl->set('{ban_reason}', check($reason, null));
			$tpl->set('{ban_length}', expand_seconds2($ban_length));
			$tpl->set('{ban_created}', expand_date(date('Y-m-d H:i:s', $ban_created), 7));

			$tpl->set('{server}', $id);
			$tpl->set('{server_name}', $server_name);
			$tpl->set('{server_address}', $address);
			$tpl->set('{admin_nick}', $admin_nick);
			$tpl->set('{ban_closed}', $ban_closed);

			$tpl->set('{color}', $aData['color']);
			$tpl->set('{status}', $aData['status']);
			$tpl->set('{price}', (int) $aData['price']);
			$tpl->set('{display}', $aData['display']);
			$tpl->set('{display-unmut}', $aData['display-unmut']);
		$tpl->compile('content');

	}

	if($tpl->result['content'] == '')
	{
		$tpl->load_template('content_none.tpl');
			$tpl->set('{text}', 'Мут лист пуст');
		$tpl->compile('content');
	}

	$tpl->show($tpl->result['content']);
?>