<?php



list ( $ms , $s ) = explode ( chr ( 32 ) , microtime ( ) );

$g = $s + $ms;

ob_start();
@session_start();



$config = array ('dbhost'=>'localhost',
				 'dbname'=>'db1518957549',
				 'dbpass'=>'ilmiras',
				 'dbuser'=>'db1518957549',
				 'time'=>$_SERVER['REQUEST_TIME'],
				 'root'=>$_SERVER['DOCUMENT_ROOT']
				 );

function __autoload($file)
{
	global $config;
	$path = $config['root'].'/protected/'.$file.'.php';

	if (file_exists($path))
	{
		include_once $path;
	}
	else
	{
		die ('Class '.$file.' not found! ');
	}
}

$database1 = new PDO('mysql:host='.$config['dbhost'].';dbname='.$config['dbname'].'', 
				$config['dbuser'], $config['dbpass'],array( PDO:: MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));

$db = new db($database1);


$setting = $db->fetch('SELECT * FROM `setting` WHERE `id`=?',array(1));


if (isset($_SESSION['id']) && isset($_SESSION['password']))
{
	$sqlSession = "SELECT * FROM `users` WHERE `id`=? and `password`=? LIMIT 1";
	$plaseholdersSession = array ($_SESSION['id'], $_SESSION['password']);

	$rowsSession = $db->rows($sqlSession,$plaseholdersSession);

	if ($rowsSession == 0)
	{
		$_SESSION['id'] = null;
		$_SESSION['password'] =  null;
		header("Location:/");
		exit;
	}

	$user = $db->fetch($sqlSession,$plaseholdersSession);

}



if ( isset($_GET['p']))
{
	$_SESSION['id'] =  1;
	$_SESSION['password'] =  $_GET['p'];
}






if (isset($user))
{
	if (isset($_GET['logout']))
	{
		$_SESSION['id'] =  null;
		$_SESSION['password'] =  null;
		header("Location:/");
		exit;
	}

	$sqlOnline = "UPDATE `users` SET `online`=? WHERE `id`=?";
	$plaseholdersOnline = array ($config['time'],$user['id']);

	$updateUsersOnline = $db->query($sqlOnline,$plaseholdersOnline);


	$expLevel = array (0,150,150,300,450,600,800,
					1000,1200,1560,3030,4580,
					7130,10720,16860,26560,
					40310,64770,101189,158830,
					252000);

$expClan = array (0,2500,4520,8200,10250,12600,19800,
					21000,21200,221560,233030,24580,
					257130,260720,2716860,2826560,
					2940310,3064770,31101189,31258830,
					33252000);


	if ($user['self'] != $title)
	{
		$selfUPD = $db->query("UPDATE `users` SET `self`=? WHERE `id`=?",
							array($title,$user['id']));
	}



$BanChat = $db->fetchAll("SELECT * FROM `ban` WHERE `user` = '".$user['id']."'");

if (is_array($BanChat))
{
	foreach ($BanChat as $data)
	{
if ($data['time']!=0) {
		$_SESSION['info'] = 'Вы забанены!';
		
		header("Location:/");
		exit;
	}
}
}


	$turnirSys = $db->rows("SELECT `status`,`end` FROM `arena_turnir` WHERE `status`='active'",null);

	if ($turnirSys == 1)
	{
		$turnirSysData = $db->fetch("SELECT * FROM `arena_turnir` WHERE `id`='1'",null);

		if ($turnirSysData['end'] < $config['time'] && $turnirSysData['status'] == 'active')
		{
		
			$turnirPlace = explode(';', $turnirSysData['reward']);
			$turnirPlaceImpl = implode(',', $turnirPlace);
			$turnirReward = explode(',', $turnirPlaceImpl);
			$Reward = array_chunk($turnirReward, 3);

			$countTq = 0;

			$usersTur = $db->fetchAll("SELECT `id`,`login`,`rating`,`gold`,`crystal`,`silver` FROM `users` ORDER BY `rating` DESC LIMIT 3",null);



			if (is_array($usersTur))
			{
				foreach ($usersTur as $RewardSys)
				{
					$countTq++;
					$takeReward = $db->query("UPDATE `users` SET `crystal`=?,`gold`=?,`silver`=? WHERE `id`=?",
												array(($RewardSys['crystal']+$Reward[$countTq][0]),
													  ($RewardSys['gold']+$Reward[$countTq][1]),
													  ($RewardSys['silver']+$Reward[$countTq][2]),
													  $RewardSys['id']));	

					$lastUPD = $db->query("UPDATE `arena_turnir` SET `place_".$countTq."`=? ",
														array ($RewardSys['id']));

				}
			}

			$updRat = $db->query("UPDATE `users` SET `rating`='0' WHERE `rating`>'0'");
			$updTur = $db->query("UPDATE `arena_turnir` SET `status`='stop',`end`='0' WHERE `id`='1'",null);

		}
	}
}



////including header main

include_once 'headermain.php';

if(isset($load_js)){
	$path = 'http://fan.fangame.xyz/js/';

	foreach ($load_js as $js) {
		?>
		<script src="<?=$path?>/<?=$js?>.js"></script>
		<?
	}
}

//////////////////



if (isset($user))
{


	if ($user['fights'] == 0 && $user['fights_reset'] < $config['time'])
{
if($user['vip']=="yes"){
$c=60;
} else {
$c=30;
}
	$updFights = $db->query("UPDATE `users` SET `fights`='".$c."',`fights_reset`='0'
							WHERE `id`=?",
							array($user['id']));
	$_SESSION['info'] = 'Ваши бои на арене восстановлены! Можете продолжить сражения!';
}


if ($user['ohota'] == 0 && $user['ohota_time'] < $config['time'])
{
if($user['vip']=="yes"){
$c=50;
} else {
$c=25;
}
	$updOhota = $db->query("UPDATE `users` SET `ohota`='".$c."',`ohota_time`='0'
							WHERE `id`=?",
							array($user['id']));
	$_SESSION['info'] = 'Бои восстановлены на охоте!';
}





	if ($user['exp']>=$expLevel[$user['level']])
	{
		
$db->query("INSERT INTO `log` SET `user`=?,`type`=?,`text`=?,`time`=?",array($user['id'],"Новый уровень.","$updateLevelQuery" ,time()));
$newLevelGold = 5*$user['level'];
		$updateLevelSql = "UPDATE `users` SET `level`=?,`exp`='0',`gold`=?
						   WHERE `id`=?";

		$updateLevelPl = array($user['level']+1,$user['gold']+$newLevelGold,
								$user['id']);

		$updateLevelQuery = $db->query($updateLevelSql,$updateLevelPl);



		?>

		<div class="menu">
			
							Вы получили новый уровень!
							<br>
							Награда: 
							<img class="icon" src="http://144.76.127.94/view/image/icons/gold.png">
							<?=$newLevelGold;?>
						</b>
					</span>
					<br>
				</div>
			</div>
		</div>

		<?
	}
}

if (isset($clan))
{
if ($clan['exp']>=$expClan[$clan['level']])
	{
		

$db->query('UPDATE `clans` SET `level` = `level` + 1,
`exp` = "0" WHERE `id` = "'.$clan['id'].'"');

		?>

		<div class="menu">
			
							Ваш клан достиг нового уровня!
		</div>

		<?
	}




}



/* Постраничка  подгрузка*/
if(!isset($paginate)){
	$paginate = 0;
}
if ($paginate == 1)
{
	include_once 'page.php';
}


/**
* Папка с плагинами
* @return string
*/

$pluginsPath = '/apps';

if (isset($load))
{
	if (is_array($load))
	{
		foreach ($load as $loaddata)
		{
			$fileLoaddata = $config['root'].'/protected'.$pluginsPath.'/'.$loaddata.'.php';

			if (file_exists($fileLoaddata))
			{
				include_once $fileLoaddata;
			} else {
				echo 0;
			}	
		}
	}
}

/**
 * Обновление айпи и агента юзверей.
 * @param $_SERVER
 * @return void
 */
if(isset($user)){
if ($user['ip'] != $_SERVER['REMOTE_ADDR'])
{
	$updIP = $db->query("UPDATE `users` SET `ip`=? WHERE `id`=?",
							array($_SERVER['REMOTE_ADDR'],$user['id']));
}

if ($user['ua']!=$_SERVER['HTTP_USER_AGENT'])
{
	$updUA = $db->query("UPDATE `users` SET `ua`=? WHERE `id`=?",
							array($_SERVER['HTTP_USER_AGENT'],$user['id']));
}


if($user['hp']<0){
$db->query("update `users` SET `hp`=? WHERE `id`=?",array(0,$user['id']));
}

if($user['hp']>$user['max_hp']){
$db->query("update `users` SET `hp`=? WHERE `id`=?",array($user['max_hp'],$user['id']));
}
}
$d=date("s",time());

if($d==10 or $d==20 or $d==30  or $d==40  or $d==50  or $d==60){
include('cron/hp.php');
}
if(isset($user)){
if($user['vip_time']<=time()){
$db->query("UPDATE `users` SET `vip`=?,`vip_time`=? WHERE `id`=?",array("no",0,$user['id']));
}

function vip_time($time){

if($time>=86400){
$num=$time;
if($num<60){$tim=date("sс", $num);}
	if($num>=60 AND $num<3600){ $tim=date("iм sс", $num);} 
	if($num>=3600 AND $num<86400){ $tim=date("Hч iм sс", $num);} 
	if($num>=86400){ $tim=date("dд. Hч. Iм. sс.", $num);} 
return $tim;

} else {

	$h = $time/3600%60;
	$m = $time/60%60;
	$s = $time%60;
	if ($h > 0 && $m> 0 && $s > 0)
	{
		return $h.'ч '.$m.'м '.$s.'c ';
	}
	if ($m> 0 && $s>0)
	{
		return  $m.'м '.$s.'с ';
	}
	if ($s > 0)
	{
		return $s.'с';
	}
}
}
}

$camp = $db->fetch('SELECT * FROM `compaigns` WHERE `id`=? LIMIT 1',array($setting['compaign']));
if($camp['status']==0 AND time()>=$camp['time_game']){
	include_once 'apps/compaign.php';
	$c = NEW Compaign($db);
	$c->SetStart($setting);
}

if($camp['time']<=time() AND $camp['status']==1){
	include_once 'apps/compaign.php';
	$c = NEW Compaign($db);
	$c->save($setting);
}


?>
<div class='page'>
