<?php

if(empty($header)) $header = 'AVALOR';

echo '<html>
	<head>
		<meta name="description" content="AVALOR - мобильная браузерная MMORPG. Обманчиво простой сюжет захватит вас в свои объятия уже на первой минуте игры. Вам предстоит плечом к плечу с другими игроками сразить боссов и отыскать свою причину...">
		<meta name="keywords" content="avalor, авалор, авалор моби, avalor mobi, mmo, rpg, ммо, mmorpg, мморпг, рпг, игра, онлайн игра, онлайн игра авалор, мобильные игры, мобильная rpg игра авалор, мобильная онлайн игра avalor, скачать, играть, без регистрации">
		<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8"/>
		<meta http-equiv="Content-Style-Type" content="text/css" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link rel="stylesheet" type="text/css" href="/css/dark.css">
		<link rel="icon" type="image/png" href="/favicon.png" />
		<title>'.$header.'</title>
	</head>
	<body>';

//UTM Метки
if(isset($_GET['utm_source']) OR isset($_GET['utm_medium']) OR isset($_GET['utm_campaign'])){
	$base -> query('INSERT INTO `utm` SET
		`session` = "'.session_id().'",
		`user` = "",
		`date` = "'.time().'",
		`utm_source` = "'.$_GET['utm_source'].'",
		`utm_medium` = "'.$_GET['utm_medium'].'",
		`utm_campaign` = "'.$_GET['utm_campaign'].'",
		`utm_content` = "'.$_GET['utm_content'].'",
		`utm_term` = "'.$_GET['utm_term'].'"');
}

echo '<div class="page">';

if(!isset($u)){
	//echo '<div class="a"><center><b>'.$header.'</b></center></div>';
}else{

//UTM
$utm = $base -> query('SELECT * FROM `utm` WHERE `session`= "'.session_id().'" AND `user` != "'.$u['id'].'"') -> fetch_assoc();
if($utm > 0){
	$base -> query('UPDATE `utm` SET `user` = "'.$u['id'].'" WHERE `session` = "'.session_id().'"');
	$base -> query('UPDATE `users` SET `utm_source` = "'.$utm['utm_source'].'" WHERE `id` = "'.$u['id'].'"');
}

//Обучение
if($u['training_step'] > 0){
	if($u['training_step'] < 10
		AND $_SERVER['PHP_SELF'] != '/training.php'){
		header('Location: /training/'.$u['training_step'].'/');
		exit;
	}
	if($u['training_step'] == 10
		AND $_SERVER['PHP_SELF'] != '/location.php'
		AND $_SERVER['PHP_SELF'] != '/training.php'
		AND $_SERVER['PHP_SELF'] != '/inventory.php'){
		//$_SESSION['message'] = 'Для начала пройдите обучение.';
		header('Location: /location/');
		exit;
	}
	if($u['training_step'] == 11
		AND $_SERVER['PHP_SELF'] != '/location.php'
		AND $_SERVER['PHP_SELF'] != '/training.php'
		AND $_SERVER['PHP_SELF'] != '/user.php'
		AND $_SERVER['PHP_SELF'] != '/belt_slots.php'){
		//$_SESSION['message'] = 'Для начала пройдите обучение.';
		header('Location: /location/');
		exit;
	}
	if($u['training_step'] == 12
		AND $_SERVER['PHP_SELF'] != '/location.php'
		AND $_SERVER['PHP_SELF'] != '/training.php'
		AND $_SERVER['PHP_SELF'] != '/city.php'
		AND $_SERVER['PHP_SELF'] != '/tavern.php'){
		//$_SESSION['message'] = 'Для начала пройдите обучение.';
		header('Location: /location/');
		exit;
	}
		if($u['training_step'] == 13
		AND $_SERVER['PHP_SELF'] != '/location.php'
		AND $_SERVER['PHP_SELF'] != '/training.php'){
		//$_SESSION['message'] = 'Для начала пройдите обучение.';
		header('Location: /location/');
		exit;
	}
		if($u['training_step'] == 14
		AND $_SERVER['PHP_SELF'] != '/location.php'
		AND $_SERVER['PHP_SELF'] != '/training.php'
		AND $_SERVER['PHP_SELF'] != '/pve.php'){
		//$_SESSION['message'] = 'Для начала пройдите обучение.';
		header('Location: /location/');
		exit;
	}
		if($u['training_step'] == 15
		AND $_SERVER['PHP_SELF'] != '/location.php'
		AND $_SERVER['PHP_SELF'] != '/training.php'
		AND $_SERVER['PHP_SELF'] != '/save.php'){
		//$_SESSION['message'] = 'Для начала пройдите обучение.';
		header('Location: /location/');
		exit;
	}
		if($u['training_step'] == 16
		AND $_SERVER['PHP_SELF'] != '/location.php'
		AND $_SERVER['PHP_SELF'] != '/training.php'){
		//$_SESSION['message'] = 'Для начала пройдите обучение.';
		header('Location: /location/');
		exit;
	}
}

//Определяем скин
$skin='/images/skins/'.$u['skin'].''.$u['direction'].'.gif';
$avatar='/images/skins/'.$u['skin'].'_big.png';

//Завершаем баффы
$buffs_q = $base -> query('SELECT * FROM `buffs`');
$buffs_nr = $buffs_q -> num_rows;
if($buffs_nr > 0){
	while($buffs = $buffs_q -> fetch_assoc()){
		$buff = $base -> query('SELECT * FROM `skills` WHERE `id` = "'.$buffs['buff'].'" LIMIT 1') -> fetch_assoc();
		$buff_remain_time = ($buffs['time'] + $buff['duration']) - time();
		$buffed_user = $base -> query('SELECT * FROM `users` WHERE `id` = "'.$buffs['user'].'" LIMIT 1') -> fetch_assoc();
		//if($buffed_user['battle'] == 'no' AND $buff['ident_id'] != 10 AND $buff['ident_id'] != 11 AND $buff['ident_id'] != 12 AND $buff['ident_id'] != 13) $buff_remain_time = 0;
		if($buff_remain_time <= 0){
			$base -> query('UPDATE `users` SET
				`p_att` = `p_att` - "'.$buff['p_att'].'",
				`m_att` = `m_att` - "'.$buff['m_att'].'",
				`p_def` = `p_def` - "'.$buff['p_def'].'",
				`m_def` = `m_def` - "'.$buff['m_def'].'",
				`endurance` = `endurance` - "'.$buff['endurance'].'",
				`intellect` = `intellect` - "'.$buff['intellect'].'",
				`agility` = `agility` - "'.$buff['agility'].'",
				`skill` = `skill` - "'.$buff['skill'].'"
				WHERE `id` = "'.$buffed_user['id'].'"');
			$base -> query('DELETE FROM `buffs` WHERE `id` = "'.$buffs['id'].'"');
			if($buffed_user['id'] == $u['id']){
				header('Location: ?');
				exit;
			}
		}
	}
}

//Выравниваем характеристики
if($u['max_hp'] != ($u['endurance'] * 20)){
	$max_hp = $u['endurance'] * 20;
	$base -> query('UPDATE `users` SET `max_hp` = "'.$max_hp.'" WHERE `id` = "'.$u['id'].'" LIMIT 1');
	header('Location: ?');
	exit;
}
if($u['max_mp'] != ($u['intellect'] * 20)){
	$max_mp = $u['intellect'] * 20;
	$base -> query('UPDATE `users` SET `max_mp` = "'.$max_mp.'" WHERE `id` = "'.$u['id'].'" LIMIT 1');
	header('Location: ?');
	exit;
}
if($u['hp'] >  $u['max_hp']){
	$base -> query('UPDATE `users` SET `hp` = `max_hp` WHERE `id` = "'.$u['id'].'" LIMIT 1');
	header('Location: ?');
	exit;
}
if($u['mp'] >  $u['max_mp']){
	$base -> query('UPDATE `users` SET `mp` = `max_mp` WHERE `id` = "'.$u['id'].'" LIMIT 1');
	header('Location: ?');
	exit;
}
if($u['hp'] < 0){
	if($u['battle'] == 'no') $base -> query('UPDATE `users` SET `hp` = `max_hp` WHERE `id` = "'.$u['id'].'" LIMIT 1');
}

//Повышение уровня клана
if($uclan){
	$clexp = $base -> query("SELECT * FROM `clan_level` WHERE `id` = '".$uclan['level']."' LIMIT 1") -> fetch_assoc();
	if($uclan['level'] != 50 && $uclan['exp'] >= $clexp['exp']) {
		$cexp = $uclan['exp'] - $clexp['exp'];
		$base -> query("UPDATE `clans` SET
			`level` = `level` + '1',
			`exp` = '".$cexp."'
			WHERE `id` = '".$uclan['id']."'");
	}
}

//Обновляем онлайн
$base -> query("UPDATE `users` SET `date_online` = '".time()."' WHERE `id` = '".$u['id']."' LIMIT 1");

//Убиваем, если 0 здоровья
//if($u['hp'] <= 0) $base -> query("UPDATE `users` SET `battle` = '".time()."' WHERE `id` = '".$u['id']."'");

//Переадресация если в бою
if($u['battle'] != 'no'){
	if($u['battle'] == 'pve'){
		if($_SERVER['PHP_SELF'] != '/pve.php'){
			header('Location: /pve/');
			exit;
		}
	}
	if($u['battle'] == 'pvp'){
		if($_SERVER['PHP_SELF'] != '/pvp.php'){
			header('Location: /pvp/');
			exit;
		}
	}
	if($u['battle'] == 'pvb'){
		if($_SERVER['PHP_SELF'] != '/pvb.php'){
			header('Location: /pvb/');
			exit;
		}
	}
}


//Верхний бар, краткая информация
$lexp = $base -> query("SELECT * FROM `level` WHERE `id` = '".$u['level']."' LIMIT 1") -> fetch_assoc();
$now_hp = round($u['hp']/$u['max_hp']*100,1);
if($now_hp > 100)$now_hp = 100;
$now_mp = round($u['mp']/$u['max_mp']*100,1);
if($now_mp > 100)$now_mp = 100;
if($u['level'] != 50){
$progress = round($u['exp']/$lexp['exp']*100,1);
if($progress > 100)$progress = 100;
}

if($event['step'] == 1) $tokens = '<br/><img src="/images/icons/'.$event['image'].'_token.png" width="20px"> '.$u['token'].'';

//Если пришло сообщение
$mes = $base -> query("SELECT * FROM `message` WHERE `komy` = '".$u['id']."' and `readlen` = '0' LIMIT 1") -> num_rows;
if($mes > 0){
	$new_mes = '<a class="btn_smallest_green" href="/mail/"><img src="/images/icons/mail.png" width="20px"></a>';
}else{
	$new_mes = '<a class="btn_smallest" href="/mail/"><img src="/images/icons/mail.png" width="20px"></a>';
}

//Новости
if($u['fresh_news'] == 1) $green = '_green';
else $green = '';

if($u['training_step'] == 0 OR $u['training_step'] > 9){
echo '<div class="sticky_header">';
echo '<table width="100%" class="a_table a_table-common" style="border-collapse: collapse;"><tr>';
echo '<td width="45%">
<div class="exp" style="background-size: '.$progress.'% 12px; text-shadow: black 0 1px 0;"><font size="1">EXP: '.n_f($u['exp']).'/'.n_f($lexp['exp']).' ('.$progress.'%) <div style="float: right;">LV:'.$u['level'].'</div></font></div>
<div class="hp" style="background-size: '.$now_hp.'% 12px; text-shadow: black 0 1px 0;"><font size="1">HP: '.n_f($u['hp']).'/'.n_f($u['max_hp']).'</font></div>
<div class="mp" style="background-size: '.$now_mp.'% 12px; text-shadow: black 0 1px 0;"><font size="1">MP: '.n_f($u['mp']).'/'.n_f($u['max_mp']).'</font></div>
</td>';
echo '<td valign="top"><div style="text-shadow: black 0 1px 0;"><a href="/gold/"><img src="/images/icons/silver.png"  width="16px"> <font size="2">'.n_f($u['silver']).'</font></a><br/>
<a href="/gold/"><img src="/images/icons/gold.png" width="16px"> <font color="gold" size="2">'.n_f($u['gold']).'</font></a>
'.$tokens.'
</div></td>';
echo '<td align="right" valign="top">';
echo '<a class="btn_smallest" href="https://vk.com/avalormobi"><img src="/images/vk.png" width="20px"></a>';
echo '<a class="btn_smallest" href="https://t.me/joinchat/AAAAAFXi5EIjuCJfSiMxsg"><img src="/images/telegram.png" width="20px"></a>';
echo '<a class="btn_smallest'.$green.'" href="/fresh_news/"><img src="/images/icons/bell.png" width="20px"></a>';
echo ''.$new_mes.'';
echo '</td></tr></table>';
echo '</div>';
}

echo '<div class="body">';

//Бан
$ban = $base -> query("SELECT * FROM `ban` WHERE `id_user` = '".$u['id']."' AND `time_ban` > '".time()."' AND `blocked` = 'all' ORDER BY `id` DESC LIMIT 1") -> fetch_assoc();
if($ban['id']){
	if($ban['blocked'] == 'all') $bans = 'заблокированы';
	else $bans = 'заткнуты';
	echo '<div class="b">';
	echo '<div class="event">';
	echo '<center><font color="red"><b>Вы '.$bans.' за нарушение правил игры.</b></font></center>';
	echo '<font color="#B1B1B1">Окончание:</font> '.tm($ban['time_ban']).' <br/>';
	echo '<font color="#B1B1B1">Заблокировал(а):</font> '.name($ban['id_ban']).' <br/>';
	echo '<font color="#B1B1B1">Причина:</font> '.fl($ban['reason']).'';
	echo '</div>';
	die();
}

//Тех. Работы
if($u['id'] == 0){
	echo '<div class="b">';
	echo '<div class="title">Тех. Работы</div>';
	echo '<div class="event"><center>В скором времени, игра будет доступна.</center></div>';
	echo '</div>';
	include_once ('./core/foot.php');
	exit;
}

//Уведомления, если не в бою!!!!
if($u['battle'] == 'no'){

//Если не привязана электронная почта
if($u['email'] == '' AND $u['training_step'] == 0 AND $_SERVER['PHP_SELF'] != '/settings.php'){
	header('Location: /settings/email/');
	exit;
}

//Повышение уровня
if($u['level'] != 50 && $u['exp'] >= $lexp['exp'] && $_SERVER['PHP_SELF'] != '/location.php'){
	$exp = $u['exp'] - $lexp['exp'];
	$g = $u['level'] * 5;
	$base -> query("UPDATE `users` SET
		`level` = `level` + '1',
		`exp` = '".$exp."',
		`gold` = `gold` + '".$g."',
		`hp` = '".$u['max_hp']."',
		`mp` = '".$u['max_mp']."',
		`character_points` = `character_points` + '5',
		`skill_points` = `skill_points` + '1'
		WHERE `id` = '".$u['id']."' LIMIT 1");
	echo '<div class="b_inside">';
	echo '<div class="event"><center>
	<b>Уровень повышен!</b><br/>
	<img src="/images/icons/gold.png" width="16px"><font color="gold">'.$g.'</font> <img src="/images/icons/character_points.png" width="16px">5 <img src="/images/icons/skill_points.png" width="16px">1';
	echo '</center></div></div>';
}

//Приглашение в клан
$_GET['clan'] = fl($_GET['clan']);
$_GET['answer'] = fl($_GET['answer']);

if($_GET['clan'] != '' AND $_GET['answer'] != ''){
	$clan_invitation = $base -> query("SELECT * FROM `clan_invitation` WHERE `invitee_user` = '".$u['id']."' ORDER BY `id` DESC LIMIT 1") -> fetch_assoc();
	$clan = $base -> query("SELECT * FROM `clans` WHERE `leader` = '".$clan_invitation['user']."' LIMIT 1") -> fetch_assoc();
	if(!$uclan){
		if($_GET['answer'] == 'yes'){
		if($clan_invitation != 0 AND $clan != 0){
			$clan_members = $base -> query('SELECT * FROM `users` WHERE `clan` = "'.$clan['id'].'"') -> num_rows;
			if(($clan_members + 1) <= $clan['max_members']){
				$base -> query('DELETE FROM `clan_invitation` WHERE `invitee_user` = "'.$u['id'].'"');
				$base -> query('UPDATE `users` SET `clan` = "'.$clan['id'].'", `clan_rank` = "1" WHERE `id` = "'.$u['id'].'" LIMIT 1');
				$_SESSION['message'] = 'Добро пожаловать в клан '.$clan['name'].'.';
				header('Location: /clan/');
				exit;
			}else{
				$_SESSION['message'] = 'В клане нет мест.';
				header('Location: /');
				exit;
			}
		}else{
			$_SESSION['message'] = 'Ошибка.';
			header('Location: /');
			exit;
		}
		}elseif($_GET['answer'] == 'no'){
			$base -> query('DELETE FROM `clan_invitation` WHERE `id` = "'.$clan_invitation['id'].'"');
			header('Location: /location/');
			exit;
		}else{
			header('Location: /');
			exit;
		}
	}else{
		$_SESSION['message'] = 'Вы уже состоите в клане.';
		header('Location: /clan/');
		exit;
	}
}
$clan_invitations_q = $base -> query("SELECT * FROM `clan_invitation` WHERE `invitee_user` = '".$u['id']."' ORDER BY `id` DESC LIMIT 1");
$clan_invitations_nr = $clan_invitations_q -> num_rows;
if($clan_invitations_nr > 0 AND $_SERVER['PHP_SELF'] != '/location.php'){
	$clan_invitation = $clan_invitations_q -> fetch_assoc();
	$who = $base -> query('SELECT * FROM `users` WHERE `id` = "'.$clan_invitation['user'].'" LIMIT 1') -> fetch_assoc();
	$clan = $base -> query('SELECT * FROM `clans` WHERE `id` = "'.$who['clan'].'" LIMIT 1') -> fetch_assoc();
	echo '<div class="b_inside">';
	echo '<div class="event"><center>'.$who['login'].' приглашает вас в клан '.$clan['name'].'.<br/>
	<a class="btn_small" href="/clan/invite/'.$clan_invitation['id'].'/yes/">Принять</a> <a class="btn_small" href="/clan/invite/'.$clan_invitation['id'].'/no/">Отказать</a></center></div>';
	echo '</div>';
}

//Приглашение в команду
$_GET['party'] = fl($_GET['party']);
$_GET['answer'] = fl($_GET['answer']);

if($_GET['party'] != '' AND $_GET['answer'] != ''){
	$party_invitation = $base -> query("SELECT * FROM `party_invitation` WHERE `invitee_user` = '".$u['id']."' ORDER BY `id` DESC LIMIT 1") -> fetch_assoc();
	$party = $base -> query("SELECT * FROM `party` WHERE `first_user` = '".$party_invitation['user']."' LIMIT 1") -> fetch_assoc();
	if(!$uparty){
		if($party){
			if($_GET['answer'] == 'yes'){
			if($party_invitation != 0 AND $party != 0){
				if($party['third_user'] == 0){
					$party_leader = $base -> query('SELECT * FROM `users` WHERE `id` = "'.$party_invitation['user'].'" LIMIT 1') -> fetch_assoc();
					if($party_leader['world'] == $u['world'] AND $party_leader['x'] == $u['x'] AND $party_leader['y'] == $u['y']){
						if($party['second_user'] == 0) $s_or_t = 'second';
						else $s_or_t = 'third';
						$base -> query('DELETE FROM `party_invitation` WHERE `invitee_user` = "'.$u['id'].'"');
						$base -> query('UPDATE `party` SET `'.$s_or_t.'_user` = "'.$u['id'].'" WHERE `id` = "'.$party['id'].'" LIMIT 1');
						header('Location: /party/');
						exit;
					}else{
						$_SESSION['message'] = 'Приглашение недействительно, так как вы уже не стоите на одном месте, на одной локации.';
						$base -> query('DELETE FROM `party_invitation` WHERE `id` = "'.$party_invitation['id'].'" LIMIT 1');
						header('Location: /location/');
						exit;
					}
				}else{
					header('Location: /');
					exit;
				}
			}else{
				header('Location: /');
				exit;
			}
			}elseif($_GET['answer'] == 'no'){
				$base -> query('DELETE FROM `party_invitation` WHERE `id` = "'.$party_invitation['id'].'" LIMIT 1');
				header('Location: /location/');
				exit;
			}else{
				header('Location: /');
				exit;
			}
		}else{
			$_SESSION['message'] = 'Приглашение недействительно, такой команды не существует.';
			$base -> query('DELETE FROM `party_invitation` WHERE `id` = "'.$party_invitation['id'].'" LIMIT 1');
			header('Location: /location/');
			exit;
		}
	}else{
		header('Location: /location/');
		exit;
	}
}


$party_invitations_q = $base -> query("SELECT * FROM `party_invitation` WHERE `invitee_user` = '".$u['id']."' ORDER BY `id` DESC LIMIT 1");
$party_invitations_nr = $party_invitations_q -> num_rows;
if($party_invitations_nr > 0 AND $_SERVER['PHP_SELF'] != '/location.php'){
	$party = $party_invitations_q -> fetch_assoc();
	$who = $base -> query('SELECT * FROM `users` WHERE `id` = "'.$party['user'].'" LIMIT 1') -> fetch_assoc();
	echo '<div class="b_inside">';
	echo '<div class="event"><center>'.$who['login'].' приглашает вас в команду.<br/>
	<a class="btn_small" href="/party/'.$party['id'].'/yes/">Принять</a> <a class="btn_small" href="/party/'.$party['id'].'/no/">Отказать</a></center></div>';
	echo '</div>';
}

//print(''.time().'');

if($_SESSION['message']!='' AND $_SERVER['PHP_SELF'] != '/location.php'){
	echo '<div class="b_inside">';
	echo '<table class="event_info"><tr><td><img src="/images/icons/info.png"></td><td>'.$_SESSION['message'].'</td></tr></table>';
	unset($_SESSION['message']);
	echo '</div>';
}

}

}

?>