<?
    ///Modul
require_once ('./system/func.php'); //тут подключаем шапку 
    


    $title = 'Выживание';    
require_once ('./system/header.php');

     


    if($user['level']>  0){
    /////////////////////////////////////////////////////////////SETTING /////////////////////////////////////////////////
    $LinkKey=md5(rand(1000,10000));
    //Level survival 
    
    if($user['rank_survival'] >=0){
        
    
    
    $rank_survival = "<span class='grey'>Обычное </span>";
    $bonus_exp = 1;
    }
    
    if($user['rank_survival'] >= 500){

    $rank_survival = "<span class='green'>Необычное </span>";
        $bonus_exp = 3;
    }

    if($user['rank_survival'] >=1500){
    
    $rank_survival = "<span class='blue'>Редкое</span>";
        $bonus_exp = 5;
}

    if($user['rank_survival'] >=3000){
    
    $rank_survival = "<span class='violet'>Эпическое  </span>";
            $bonus_exp = 7;
}

    if($user['rank_survival'] >=6000){
    
    $rank_survival = "<span class='orange'>Легендарное   </span>";
    
        $bonus_exp = 10;

    }
    
    
    
    
    
    
    
  $member = mysql_query('SELECT * FROM `survival_member` WHERE `user` = "'.$user['id'].'" ORDER BY `time` DESC LIMIT 1');
  $member = mysql_fetch_array($member);

  if($member) {

  $battle = mysql_query('SELECT * FROM `survival` WHERE `id` = "'.$member['battle'].'"');
  $battle = mysql_fetch_array($battle);

  }

  
  if($member['exit'] == 0 && $battle['start'] == 1 && $battle['end'] == 0) {

  if(mysql_result(mysql_query('SELECT COUNT(*) FROM `survival_member` WHERE `battle` = "'.$battle['id'].'" AND `dead` = "0"'),0) == 1) {
     
    mysql_query('UPDATE `survival` SET `end` = "1" WHERE `id` = "'.$battle['id'].'"');
  
      header('location: /survival/');
  
  exit;
  
  }
  
 
    if($member['dead'] == 1) {
    

echo "<div class='block_c'>
<br/><br/>
<font color='#999'>Вы были убиты во время сражения, ожидайте окончания боя</font>
</div>";


echo"
<div class='btn_grey='center'>
<a class='btn' href='/survival/?'><span class='btn_grey'>Обновить</a></div>";
    

    }
    else
    {
  
  if($_GET['exit'] == true) {

    $log = '<img src=\'/images/icon/race/'.$user['r'].'.png\' alt=\'\'/> <b>'.$user['login'].'</b> покидает бой';    
    mysql_query('INSERT INTO `survival_log` (`battle`,
                                               `user`,
                                             `object`,
                                               `text`) VALUES ("'.$battle['id'].'",
                                                                 "'.$user['id'].'",
                                                               "'.$object['id'].'",
                                                                        "'.$log.'")');

    mysql_query('UPDATE `survival_member` SET `dead` = "1" WHERE `battle` = "'.$battle['id'].'" AND `user` = "'.$user['id'].'"');
  
      header('location: /survival/');
  
  exit;
  
  }
  
  if($member['object'] == 0) {
  
    $rand_object = mysql_query('SELECT * FROM `survival_member` WHERE `battle` = "'.$battle['id'].'" AND `dead` = "0" AND `user` != "'.$user['id'].'" ORDER BY RAND() LIMIT 1');
    $rand_object = mysql_fetch_array($rand_object);


    mysql_query('UPDATE `survival_member` SET `object` = "'.$rand_object['id'].'" WHERE `battle` = "'.$battle['id'].'" AND `user` = "'.$user['id'].'"');

  }

if($member['object']) {

  if($_GET['last'] == true) {
  
    $rand_object = mysql_query('SELECT * FROM `survival_member` WHERE `battle` = "'.$battle['id'].'" AND `dead` = "0" AND `user` != "'.$user['id'].'" ORDER BY RAND() LIMIT 1');
    $rand_object = mysql_fetch_array($rand_object);


    mysql_query('UPDATE `survival_member` SET `object` = "'.$rand_object['id'].'" WHERE `battle` = "'.$battle['id'].'" AND `user` = "'.$user['id'].'"');

  header('location: /survival/');

  }


    $member_object = mysql_query('SELECT * FROM `survival_member` WHERE `battle` = "'.$battle['id'].'" AND `id` = "'.$member['object'].'"');
    $member_object = mysql_fetch_array($member_object);

    $object = mysql_query('SELECT * FROM `users` WHERE `id` = "'.$member_object['user'].'"');
    $object = mysql_fetch_array($object);

  
  if($_GET['attack'] == true && $member_object['dead'] == 0) {
  
    $dmg = 0;
    
    $object_dmg = 0;
  
 
      $dmg += ceil ( round(rand(($user['str']/6),($user['str']/4)))); 

      

$dmg -= ceil ( round(rand(($object['def']/12),($object['def']/7)))); 

    if($dmg < 0) { 
     
      $dmg = rand ( 10, 20); 
     
    } 
     

    if(mt_rand(50, 100) <= $crit) { 
    
      $dmg *= 2; 

    

  $log_crit = true; 
     
    } 

    $dodge = ( (rand(1,2) * ($opponent['agi'] / 100) ) - (rand(1,2) * ($user['agi'] / 100))); 

    if(mt_rand(50, 100) <= $dodge) { 
    
      $dmg = 0; 
       
    } 
     
     

     
    $dmg_time = time() - $member['time']; 
     
    if($dmg_time < 2) { 
     
      $dmg = 0; 
     
    } 
     
    if($dmg_time > 1 && $dmg_time < 4) { 
     
      $dmg -= round($dmg / 2); 
     
    } 
    
   
    
    if($dmg == 0) {
      $log = 'Слишком часто бьете ';
    }
    else
    {
      $log = '<font coloro=grey>Вы ударили  <b>'.$object['login'].'</b> на <b>'.$dmg.'</b> '.($log_crit == true ? '(крит)':'</font>');    
    }
    
    mysql_query('INSERT INTO `survival_log` (`battle`,
                                               `user`,
                                             `object`,
                                               `text`,
                                               `show`) VALUES ("'.$battle['id'].'",
                                                                 "'.$user['id'].'",
                                                               "'.($dmg > 0 ? $object['id']:0).'",
                                                                        "'.$log.'",
                                                                 "'.$user['id'].'")');
    
    if($dmg > 0) {
      $log = '<font color="white">'.$user['login'].'</font></b> ударил Вас на <b>'.$dmg.'</b> '.($log_crit == true ? '(крит)':'');    
    mysql_query('INSERT INTO `survival_log` (`battle`,
                                               `user`,
                                             `object`,
                                               `text`,
                                               `show`) VALUES ("'.$battle['id'].'",
                                                               "'.$object['id'].'",
                                                                 "'.$user['id'].'",
                                                                        "'.$log.'",
                                                               "'.$object['id'].'")');
    }

    if($dmg > 0) {
    $log = ' <b>'.$user['login'].'</b> ударил  <b> '.$object['login'].'</b> на<img src="/images/icons/str.png"> <b>'.$dmg.'</b> '.($log_crit == true ? '(крит)':'');    
    mysql_query('INSERT INTO `survival_log` (`battle`,
                                               `user`,
                                             `object`,
                                               `text`) VALUES ("'.$battle['id'].'",
                                                                 "'.$user['id'].'",
                                                               "'.$object['id'].'",
                                                                        "'.$log.'")');
    }



    mysql_query('UPDATE `users` SET `health` = "'.($object['health'] - $dmg).'" WHERE `id` = "'.$object['id'].'"');
    mysql_query('UPDATE `survival_member` SET `time` = "'.time().'" WHERE `battle` = "'.$battle['id'].'" AND `user` = "'.$user['id'].'"');






    if($dmg >= $object['health']) {

      $log = 'Вы убили  <b>'.$object['login'].'</b>';        
      mysql_query('INSERT INTO `survival_log` (`battle`,
                                                 `user`,
                                               `object`,
                                                 `text`,
                                                 `show`) VALUES ("'.$battle['id'].'",
                                                                   "'.$user['id'].'",
                                                                 "'.$object['id'].'",
                                                                          "'.$log.'",
                                                                   "'.$user['id'].'")');

      $log = ' <b>'.$user['login'].'</b> убил Вас';    
      mysql_query('INSERT INTO `survival_log` (`battle`,
                                                 `user`,
                                               `object`,
                                                 `text`,
                                                 `show`) VALUES ("'.$battle['id'].'",
                                                                 "'.$object['id'].'",
                                                                   "'.$user['id'].'",
                                                                          "'.$log.'",
                                                                 "'.$object['id'].'")');
    
    
      $log = ' <b>'.$user['login'].'</b> убил  <b>'.$object['login'].'</b>';    
      mysql_query('INSERT INTO `survival_log` (`battle`,
                                                 `user`,
                                               `object`,
                                                 `text`) VALUES ("'.$battle['id'].'", 
                                                                 "'.$user['id'].'",
                                                               "'.$object['id'].'",
                                                                        "'.$log.'")');


      mysql_query('UPDATE `survival_member` SET `dead` = "1" WHERE `battle` = "'.$battle['id'].'" AND `user` = "'.$object['id'].'"');
      mysql_query('UPDATE `survival_member` SET `kills` = `kills` + 1 WHERE `battle` = "'.$battle['id'].'" AND `user` = "'.$user['id'].'"');

      $rand_object = mysql_query('SELECT * FROM `survival_member` WHERE `battle` = "'.$battle['id'].'" AND `dead` = "0" AND `user` != "'.$user['id'].'" ORDER BY RAND() LIMIT 1');
      $rand_object = mysql_fetch_array($rand_object);

      mysql_query('UPDATE `survival_member` SET `object` = "'.$rand_object['id'].'" WHERE `battle` = "'.$battle['id'].'" AND `user` = "'.$user['id'].'"');

    }
    
        header("location: /survival/?LinkKey=$LinkKey");
    
    exit;
    

  }

echo"

<div class='block_l'>

<tr>
";

echo '<div class="title"><font color="red">'.($object['sex'] == 'w' ? '</center><img src="/images/icons/girl.png" width="5%">' : '<img src="/images/icons/boy.png">').' '.$object['login'].' </font></div><div class="btn_grey"> '.($object['sex'] == 'w' ? '</center><img src="/images/maneken/1.png" width="35%">' : '<img src="/images/maneken/0.png" width="35%"> 
 ').'';
  echo '</span><img src="/images/icons/str.png"> '.$object['str'].'     <img src="/images/icons/health.png"> '.$object['health'].'    <img src="/images/icons/def.png"> '.$object['def'].'</div> ';

 echo "</div>";



  }

echo "<table style='width:100%;'>";
 
echo "<td class='center' style='width:50%;'><div class='btn_grey'> <a href='?attack=true?refreshlink-->on-->true=LinkKey=$LinkKey'><font color='red'>Ударить </font></a></li></td>";

echo "</table></div>";



echo"

<div class='block_l'>

<tr>
";

echo '<div class="title"><font color="orange">'.($user['sex'] == 'w' ? '</center><img src="/images/icons/girl.png" width="5%">' : '<img src="/images/icons/boy.png">').' '.$user['login'].' </font></div><div class="btn_grey"> '.($user['sex'] == 'w' ? '</center><img src="/images/maneken/1.png" width="35%">' : '<img src="/images/maneken/0.png"width="35% ">
 ').'';
  echo '</span><img src="/images/icons/str.png"> '.$user['str'].'     <img src="/images/icons/health.png"> '.$user['health'].'    <img src="/images/icons/def.png"> '.$user['def'].' </div>';

 echo "</div>";

 
 $all_players= mysql_result(mysql_query('SELECT COUNT(*) FROM `survival_member` WHERE `battle` = "'.$battle['id'].'"'),0);
 
 echo "<div class='block_l'>Героев в бою:<span class='grey'> $all_players</span> </div>";
 
  }


  $count = mysql_result(mysql_query('SELECT COUNT(*) FROM `survival_log` WHERE `battle` = "'.$battle['id'].'"'),0);

if($count > 0) {


echo "<div class='main_link'>";
$q = mysql_query('SELECT * FROM `survival_log` WHERE `battle` = "'.$battle['id'].'" ORDER BY `id` DESC LIMIT 15');

  while($row = mysql_fetch_array($q)) {

    if($row['user'] == $user['id'] && $row['show'] == $user['id'] OR $row['object'] == $user['id'] && $row['show'] == $user['id']) {
  
      echo '<font color=\''.($row['object'] == 0 ? 'grey':'red').'\'>'.$row['text'].'</font><br/>';
  
    }
    elseif($row['show'] == 0)
    {
    
    if($row['user'] == $user['id']) {
        

    }
    else
    {

    if($row['object'] == $user['id']) {
    
    }
    else
    {
    
      echo $row['text'].'<br/>';
  
    }
  
    }
  
    }

  }
  


echo "</div>";

  
  }

  if($member['dead'] == 0) {

?>


<?

  }
  
  }
  else
  {

  if($member['exit'] == 0 && $battle['start'] == 1 && $battle['end'] == 1) {

$q = mysql_query('SELECT * FROM `survival_member` WHERE `battle` = "'.$battle['id'].'" ORDER BY `kills` DESC  LIMIT '.mysql_result(mysql_query('SELECT COUNT(*) FROM `survival_member` WHERE `battle` = "'.$battle['id'].'"'),0).'');

  while($row = mysql_fetch_array($q)) {
  
  $i++;
  
  if($i == 1) {
    
    $best = mysql_query('SELECT * FROM `users` WHERE `id` = "'.$row['user'].'"');
    $best = mysql_fetch_array($best);
  
  }
  
  if($row['user'] == $user['id']) {
  
      $place = $i;
  
  }

  }

    $reward_gold = round(rand(1,100) + (100 / $place) + (50* $member['kills']));

  $reward_exp = round($user['level]'] + (100 / $place) + (15 * $member['kills']));
    $rating_survival = round($user['level]'] + (100 / $place) + (5 * $member['kills']));
    

$reward_skull= ceil($place +2) * (2*$member['kills'] +1);
  mysql_query("UPDATE `users` SET `gold` =  '".($user[gold]+($reward_gold))."',
                                `exp` = '".($user[exp]+($reward_exp))."',
                                `skull` = '".($user[skull]+($reward_skulll))."',
                                `rank_survival` = '".($user[rank_survival]+($rating_survival))."' WHERE `id` = '".$myID."' ");
                                



if($user[id_clan] > 0){
mysql_query("UPDATE `users` SET `clan_exp` = '".($user[clan_exp]+ceil($reward_exp*$user[trust]/100))."' WHERE `id` = '".$myID."' LIMIT 1");
mysql_query("UPDATE `clans` SET `exp` = `exp` + '".ceil($reward_exp*$user[trust]/100)."' WHERE `id` = '".$user[id_clan]."' LIMIT 1");



$quest = mysql_fetch_assoc(mysql_query("SELECT * FROM `quest` WHERE `id` = '490'"));
$q = mysql_fetch_assoc(mysql_query("SELECT * FROM `quest_user` WHERE `id_quest` = '$quest[id]' AND `id_user` = '$myID'"));
if($q['last'] < time())mysql_query("update `quest_user` set `koll` = `koll`+'1' where (`id` = '".$q['id']."')");



}






  echo "<div class='block' align='center'><font color='gold'><b>Бой окончен!</b></font><br /><font color='#90b0c0#'>Награда за <b>$place</b> место:</font><br/><img src='/images/icons/gold.png'>$reward_gold золота  <img src='/images/icons/exp.png'>$reward_exp опыта</div>";
  
  




    mysql_query('UPDATE `survival_member` SET `exit` = "1" WHERE `battle` = "'.$battle['id'].'" AND `user` = "'.$user['id'].'"');
    
  }
  else
  {
  
  }


if(mysql_result(mysql_query('SELECT COUNT(*) FROM `survival` WHERE `start` = "0"'),0) == 0) {

  mysql_query('INSERT INTO `survival` (`start`,
                                         `end`,
                                        `time`) VALUES ("0",
                                                        "0",
                                        "'.(time() + 150).'")');

}

  $battle = mysql_query('SELECT * FROM `survival` WHERE `start` = "0"');
  $battle = mysql_fetch_array($battle);  

?>



<?

if(mysql_result(mysql_query('SELECT COUNT(*) FROM `survival_member` WHERE `battle` = "'.$battle['id'].'"'),0) < 5 && mysql_result(mysql_query('SELECT COUNT(*) FROM `survival_member` WHERE `battle` = "'.$battle['id'].'" AND `user` = "'.$user['id'].'"'),0) == 0) {

    if($user['health'] > (($user['max_health'] / 100) * 10) && $_GET['join'] == true && mysql_result(mysql_query('SELECT COUNT(*) FROM `survival_member` WHERE `battle` = "'.$battle['id'].'"'),0) < 5) {

      mysql_query('INSERT INTO `survival_member` (`battle`,
                                                    `user`,
                                                    `time`) VALUES ("'.$battle['id'].'",
                                                                      "'.$user['id'].'",
                                                                           "'.time().'")');
    
        header("location: /survival/?LinkKey=$LinkKey");
    
    exit;
    
   }
   
   switch (isset($_GET['action'])){
     
     
     case 'trade':
     
     echo  "<div class='block_c'> Черепы:<img src='/images/icons/skull.png'>".$user[skull]."</div> ";
     
					    echo "<table style='width:100%;'>";
					    echo "<td class='center'><li><div class='btn_grey'><a href='/survival/?$LinkKey'><font color='white'>Амулет </font></a></li></td>";

 
echo "<td class='center'><div class='btn_grey'><li><a href='?leave=true?$LinkKey'><font color='white'>Бонусы</a></li></td>";
echo "<td class='center'><li><div class='btn_grey'><a href='/survival/?$LinkKey'><font color='white'>Эффекты </font></a></li></td>";
echo "<td class='center'><li><div class='btn_grey'><a href='/survival/?$LinkKey'><font color='white'>Чары </font></a></li></td>";


echo "</table></div>";
					    
					    
          require_once ('./system/footer.php');

     exit;

     
 }



		if ( isset ($_GET ['fullhealth'])){
				    
				         mysql_query("update `users` set  `health` = '".num($user['max_health'])."' where (`id` = '".$myID."')");
$SESSION ['msg'] = " Здоровье восстановлено ";

        header("location: /survival/?LinkKey=$LinkKey");
    
    exit;
    
				}
				

	
			echo'<div class="block_c"><img src="/images/survival/logo.jpeg" alt=""><hr>';
				
		if($user['health'] >(($user['max_health'] / 100) * 10) ){
				
				
				echo"<div class='btn_grey'><a href='?join=true?LinkKey=$LinkKey'>Встать в очередь</a></div></div>";
				
				
								
			  }else{
			  
			      
			      echo "<center> <div class='btn_grey'><li>  <a href='?fullhealth'> Выпить настойку </a></center></div>";
			 
}

			
echo"<center><div class='main_link'><span class='white'>Сложность:</span> $rank_survival <br> + <span class='lime'>Бонус к </span>".ico ( 'icons' , 'exp.png')." $bonus_exp %</div>";

//<a href='?info'> Подробнее</a></div>
        
//echo"<div class='menu_link'><a href='/survival/trade_shop/?LinkKey=$LinkKey'><span class='white'>Торговая лавка </a></div></span>";


}
else
{

  if($_GET['leave'] == true && mysql_result(mysql_query('SELECT COUNT(*) FROM `survival_member` WHERE `battle` = "'.$battle['id'].'"'),0) < 3) {

    mysql_query('DELETE FROM `survival_member` WHERE `battle` = "'.$battle['id'].'" AND `user` = "'.$user['id'].'"');
   
        header('location: /survival/');
    
    exit;

  }
  
  if(mysql_result(mysql_query('SELECT COUNT(*) FROM `survival_member` WHERE `battle` = "'.$battle['id'].'"'),0) > 1) {
  
  if($battle['time'] > time()) {
  

echo" <div class='block_c'><span class='orange'>До начала боя:</span><span class='grey'>".($battle['time'] - time())." сек  </span></div>";


  
  }
  else
  {

    mysql_query('UPDATE `survival` SET `start` = "1" WHERE `id` = "'.$battle['id'].'"');
  
  header('location: /survival/');
  
  }
  
  }
  else
  {
  
  if($battle['time'] < time()) {
  
    mysql_query('UPDATE `survival` SET `time` = "'.(time() + 150).'" WHERE `id` = "'.$battle['id'].'"');
  
  }
  
  }




$players= mysql_result(mysql_query('SELECT COUNT(*) FROM `survival_member` WHERE `battle` = "'.$battle['id'].'"'),0);



					if (isset($_GET['confirm'])){
					    
					    
					    echo "<div class='block_c'>Вы хотите уйти с очереди ?</div>";
					    
					    
					    
					    echo "<table style='width:100%;'>";
 
echo "<td class='center' style='width:50%;'><div class='<span class='label''><li> <div class='btn_grey'><a href='?leave=true?$LinkKey'><font color='white'>Да,уйти</font></a></li></td>";
echo "<td class='center'><li><div class='<span class='label''><li> <div class='btn_grey'><a href='/survival/?$LinkKey'><font color='white'>Нет </font></a></li></td>";

echo "</table></div>";
					
  break;
  
	}
echo"<div class='block_c'>Участники:$players </div>";
 echo "<table style='width:100%;'>";
 
echo "<td class='center' style='width:50%;'><div class='<span class='label''><li> <div class='btn_grey'><a href='?refreshlink-->on-->true=LinkKey=$LinkKey'><font color='white'>Обновить</font></a></li></td>";
echo "<td class='center'><li><div class='link_center_h'><li> <div class='btn_grey'><a href='?confirm=yes?$LinkKey'><font color='white'> Покинуть </font></a></li></td>";

echo "</table></div>";

}
  }

 }
 else
 {
 
?>

<div class='content' align='center'>
Для участии в  Выживании требуется  10 уровень
</div>

<?
 
 }
  
require_once ('system/footer.php');
?>