<?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_lim` FROM `config2` LIMIT 1');
			 $limit->setFetchMode(PDO::FETCH_OBJ);
	$limit = $limit->fetch();
	$limit = $limit->bans_lim;

	$price = $pdo->query('SELECT `price1`, `price2`, `price3` 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.'" LIMIT 1');
			   $server->setFetchMode(PDO::FETCH_OBJ);
	$server = $server->fetch();

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

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

		exit($tpl->result['content']);
	}
	
	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);

	if($server->type != '4')
	{
		$query = $nick == '' 
			? 'ORDER BY `bid` DESC LIMIT '.$start.', '.$limit
			: 'AND (`player_ip` LIKE "%'.strip_data($nick).'%" OR `player_nick` LIKE "%'.strip_data($nick).'%" OR `player_id` LIKE "%'.strip_data($nick).'%" OR `bid`="'.$nick.'") ORDER BY `bid` DESC';

		$bans = $pdo_remote->query('SELECT * FROM `'.set_prefix($server->db_prefix, 'bans').'` WHERE `server_ip`="'.$address.'" '.$query);
	}else{
		$server_bans = $pdo_remote->query('SELECT `sid` FROM `'.set_prefix($server->db_prefix, 'servers').'` WHERE `ip`="'.$ip.'" AND `port`="'.$port.'" LIMIT 1');
						$server_bans->setFetchMode(PDO::FETCH_OBJ);
		$server_bans = $server_bans->fetch();

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

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

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

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

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

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

	$now = $_SERVER['REQUEST_TIME'];

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

		if($ban->unban_type == 1 || (isset($ban->expired) && $ban->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->price1 : $price->price2;
				}
			}
		}

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

		$aData['display'] = '';

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

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

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

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

		$ban_closed = '';

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

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

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

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

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

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

		if(strpos($reason, '???') !== false)
			$reason = $ban->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('banlist.tpl');
			$tpl->set('{bid}', $ban->bid);
			$tpl->set('{nick}', check($nick, null));
			$tpl->set('{ip}', $ban->player_ip);
			$tpl->set('{steamid}', $ban->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-unban}', $aData['display-unban']);
		$tpl->compile('content');

	}

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

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