<? 
include './system/common.php';  
include './system/functions.php';
include './system/user.php';


if(!$user) {
header('location: /');
exit;}

$title = 'Набег';    
include './system/h.php';
echo'<div class="title">'.$title.'</div>';
  $travel = mysql_query('SELECT * FROM `travel` WHERE `user` = "'.$user['id'].'"');  
  $travel = mysql_fetch_array($travel);
  
    $travel_boss = mysql_query('SELECT * FROM `travel_boss` WHERE `id` = "'.$travel['boss'].'"');  
  $travel_boss = mysql_fetch_array($travel_boss);
  
	 if(mysql_result(mysql_query('SELECT * FROM `travel` WHERE `user` = "'.$user[id].'"'),0) == 0) {//Добавляем в бд, если зашел в первый раз
mysql_query('INSERT INTO `travel` (`user`) VALUES ("'.$user[id].'")');
header('location: /travel.php');  
exit;
}
  
  if($travel['h'] == '0' && $travel['time'] == '0' && $travel['step'] == '0') {//0-й этап
  $h = _string(_num($_GET['id'])); //Оприделяем какой набег
  
  if($h == '1'){
	  $h=1;
      $h2=1;
	  $boss=mt_rand(1,3);
	  $boss_stat=mt_rand(35,110);
	  }
  if($h == '2'){
	  $h=2;
      $h2=2;
	  $boss=mt_rand(4,8);
	  $boss_stat=mt_rand(110,400);
  }
  if($h == '3'){
	  $h=3;
      $h2=4;
	  $boss=mt_rand(9,12);
	  $boss_stat=mt_rand(400,1500);
  }
  if($h == '4'){
	  $h=4;
      $h2=8;
	  $boss=mt_rand(13,15);
	  $boss_stat=mt_rand(1500,4500);
  }
  if($h == '5'){
	  $h=5;
      $h2=12;
	  $boss=mt_rand(16,18);
	  $boss_stat=mt_rand(4500,9000);
  } 
	  
	  
  if($h) {
$hs = ($h2 * (60 * 60));         
mysql_query('UPDATE `travel` SET `h` = "'.$h.'", `step` = "1", `boss` = "'.$boss.'", `user_hp` = "'.$user['vit'].'", `boss_hp` = "'.$boss_stat.'", `boss_attack` = "'.$boss_stat.'", `boss_def` = "'.$boss_stat.'", `time` = "'.(time() + $hs).'" WHERE `user` = "'.$user['id'].'"');


// Задания
$task_id=6;// Сходи в набег 2 раза
$req = mysql_query('select * from `task_user` WHERE (`user`="'.$user['id'].'") AND (`task`="'.$task_id.'") AND (`complete`="0")');
    if (mysql_num_rows ($req) != 0) {
while ($t = mysql_fetch_array ($req)) {
$task = mysql_fetch_array(mysql_query ('SELECT * FROM `task` WHERE (`id`="'.$task_id.'")'));
if ($t['how'] < $task['how']){                            
mysql_query ('UPDATE `task_user` SET `how`=`how`+1 WHERE (`user`="'.$user['id'].'") AND (`task`="'.$task_id.'")');
}}}
/////////////////////////////////////////////////


header('location: /travel.php');   
}



echo'  <div class="empty_block">
<table> <tbody><tr>
<td width="23%">
<img src="/images/ico/travel/location_1.png">
</td><td> 
Долина ветров <br>
1 час
</td></tr>
</tbody></table>
<form action="/travel.php?id=1" method="post">
<center><input class="button" type="submit" value="В долину"/></center>
</form>
</div><div class="line"></div>';

echo'  <div class="empty_block">
<table> <tbody><tr>
<td width="23%">
<img src="/images/ico/travel/location_2.png">
</td><td> 
Ущелье грома <br>
'.($user['str'] >= 110 ? '2 часа':'Требуется 110 силы').'
</td></tr>
</tbody></table>
<form action="/travel.php?id=2" method="post">
<center> '.($user['str'] >= 110 ? '<input class="button" type="submit" value="В ущелье"/>':'<div class="button2">В ущелье</div>').'</center>
</form>
</div><div class="line"></div>';

echo'  <div class="empty_block">
<table> <tbody><tr>
<td width="23%">
<img src="/images/ico/travel/location_3.png">
</td><td> 
Алая пустыня <br>
'.($user['str'] >= 400 ? '4 часа':'Требуется 400 силы').'
</td></tr>
</tbody></table>
<form action="/travel.php?id=3" method="post">
<center> '.($user['str'] >= 400 ? '<input class="button" type="submit" value="В пустыню"/>':'<div class="button2">В пустыню</div>').'</center>
</form>
</div><div class="line"></div>';

echo'  <div class="empty_block">
<table> <tbody><tr>
<td width="23%">
<img src="/images/ico/travel/location_4.png">
</td><td> 
Мглистые горы <br>
'.($user['str'] >= 1500 ? '8 часов':'Требуется 1500 силы').'
</td></tr>
</tbody></table>
<form action="/travel.php?id=4" method="post">
<center> '.($user['str'] >= 1500 ? '<input class="button" type="submit" value="В горы"/>':'<div class="button2">В горы</div>').'</center>
</form>
</div><div class="line"></div>';

echo'  <div class="empty_block">
<table> <tbody><tr>
<td width="23%">
<img src="/images/ico/travel/location_5.png">
</td><td> 
Древний лес <br>
'.($user['str'] >= 4500 ? '12 часов':'Требуется 4500 силы').'
</td></tr>
</tbody></table>
<form action="/travel.php?id=5" method="post">
<center> '.($user['str'] >= 4500 ? '<input class="button" type="submit" value="В лес"/>':'<div class="button2">В лес</div>').'</center>
</form>
</div><div class="line"></div>';


echo' <div class="empty_block item_center">
В набегах можно зарабатывать опыт и серебро. Чем продолжительнее набег, тем больше награда!</div>
<div class="line"></div>';

}




    if($travel['step'] == '1'){//1-й этап
if($travel['time'] > time()) {

echo'
<div class="empty_block item_center">
<img src="/images/ico/travel/travel_progress.png"> <br>
Ваш герой участвует в набеге. <br>
До конца осталось '._time($travel['time'] - time()).'<br/>

<a href="/"><div class="button">На главную</div></a>
</div><div class="line"></div>';

}else{

  if($_GET['enter'] == true) {
    mysql_query('UPDATE `travel` SET `step` = "2" WHERE `user` = "'.$user['id'].'"');
    header('location: /travel.php');
	exit;
  }
  
echo'
<div class="empty_block item_center">
Вы встретили '.$travel_boss['name2'].' <br/>
<img src="/images/ico/travel/'.$travel['boss'].'.png"> <br>

<a href="/travel.php?enter=true"><div class="button">Напасть</div></a>
</div><div class="line"></div>';



  }
}  
  
  
      if($travel['step'] == '2'){//2-й этап

  if($travel[boss_hp] <= '0' OR $travel['user_hp'] <= '0') {
mysql_query("UPDATE `travel` SET `step` = '3' WHERE `user` = '".$user['id']."' LIMIT 1");
header("Location:/travel.php");
exit;
  }


  if (isset($_GET['attack'])){
$my_attack = _string(mt_rand($user[str] / 3.5,$user[str] / 3) - mt_rand($travel[boss_def] / 12,$travel[boss_def] / 9));
if($my_attack <= '0'){ $my_attack = 2;}
$boss_atk = _string(mt_rand($travel[boss_attack] / 3.5,$travel[boss_attack] / 3) - mt_rand($user[def] / 12,$user[def] / 9));
if($boss_atk <= '0'){ $boss_atk = 2;}      
      
      

 
$my = "<b>Вы</b> нанесли "._string($my_attack)." урона";
$boss = "<b>".$travel_boss[name]."</b> нанес "._string($boss_atk)." урона";
$msg = "$my <br/> $boss";
mysql_query("update `travel` set    `boss_hp` = `boss_hp` - '".$my_attack."', `user_hp` = `user_hp` - '".$boss_atk."' where (`user` = '".$user[id]."')");
mysql_query("INSERT INTO `travel_log` SET
            `id_user`='".$user[id]."',
            `text`='".$msg."'");
    header("Location:/travel.php");
    exit;
   }

   
   
   
   
  echo' <div class="empty_block">
    <table align="center"> <tbody><tr>
 <td style="width:33%;">
 <span style="float:right;"> <b>Вы</b> </span> <br>
 <span style="float:right;"> <img src="/images/ico/png/hp.png" alt="hp" width="15"> '._string($travel[user_hp]).' </span>               
    </td><td> <img src="/images/user/'.($user['sex'] = man ? 'man':'woman').'.png" alt="*" width="48"><td>
  <td> <img src="'.$HOME.'/images/ico/travel/'.$travel['boss'].'.png" alt="demon" width="48"> </td>
  <td style="width:33%;">
    <span style="float:left;"> <b>'.$travel_boss[name].'</b> </span> <br>
    <span style="float:left;"> <img src="/images/ico/png/hp.png" alt="hp" width="15"> '._string($travel[boss_hp]).'  </span> 
  </td></tr>
 </tbody></table>
</div> ';

echo' <div class="block_link"><a href="/travel.php?attack"> <img src="/images/ico/png/attack.png" alt="attack"> Атаковать </a></div>';

   $ca=mysql_result(mysql_query("SELECT COUNT(*) FROM `travel_log`"),0);
$req = mysql_query("SELECT * FROM `travel_log` where `id_user` = '".$user[id]."' ORDER by `id` DESC LIMIT 3  ");
$avto=mysql_num_rows($req);
if($avto==0){
     echo'<div class="block"> Нет истории боя </div> ';
}else{
     echo' <div class="empty_block item_center"> История боя </div> <div class="block">';
while($log = mysql_fetch_array($req))
{
     echo' '.$log[text].' <br/>';
}
echo' </div>';
}
	  }

	        
			
if($travel['step'] == '3'){//3-й этап

if($travel[boss_hp] <= '0'){ //Награда при победе
$_gold=$travel['h'];
$_silver=rand(1,10) + ($user['vit']/2) + ($user['vit']/3);
$_exp=rand(1,10) + ($user['vit']/2) + ($user['vit']/3);}
if($travel[user_hp] <= '0'){ //Награда при поражении
$_gold=0;
$_silver=rand(1,10) + ($user['vit']/3.5) + ($user['vit']/4);
$_exp=rand(1,10) + ($user['vit']/3.5) + ($user['vit']/4);}



    if($clan_memb && $clan_memb['v'] > 0) {  //Верность клану
$_exp += round($_exp/100) * $clan_memb['v'];
}
  if($premium) {$_exp+= round($_exp/ 100) * 25;} //Если премик


	 
          
        
          
    mysql_query('UPDATE `travel` SET `h` = "0", 
								`step` = "0",
								`boss` = "0",
								`user_hp` = "0",
								`boss_hp` = "0",
								`boss_attack` = "0",
								`boss_def` = "0",
                                `time` = "0" WHERE `user` = "'.$user['id'].'"');
    
	if($travel[user_hp] <= '0'){ //Награда при поражении
mysql_query('UPDATE `users` SET `s` = `s` + "'.$_silver.'", `exp` = `exp` + "'.$_exp.'" WHERE `id` = "'.$user['id'].'"');
     if($clan) {//Если в клане 
mysql_query('UPDATE `clans`     SET `exp` = `exp` + '.$_exp.' WHERE `id` = "'.$clan['id'].'"'); //Плюсуем в клан
mysql_query('UPDATE `clan_memb` SET `exp` = `exp` + '.$_exp.' WHERE `clan` = "'.$clan['id'].'" AND `user` = "'.$user['id'].'"'); //Плюсуем учаснику клана
  } 
}
	if($travel[boss_hp] <= '0'){ //Награда при победе
mysql_query('UPDATE `users` SET  `g` = `g` + "'.$_gold.'", `s` = `s` + "'.$_silver.'", `exp` = `exp` + "'.$_exp.'" WHERE `id` = "'.$user['id'].'"');	
     if($clan) {//Если в клане 
mysql_query('UPDATE `clans`     SET `exp` = `exp` + '.$_exp.' WHERE `id` = "'.$clan['id'].'"'); //Плюсуем в клан
mysql_query('UPDATE `clan_memb` SET `exp` = `exp` + '.$_exp.' WHERE `clan` = "'.$clan['id'].'" AND `user` = "'.$user['id'].'"'); //Плюсуем учаснику клана
} }
  
  //
    $proc = rand(1,100);
	if($travel[user_hp] <= '0'){ //Награда при поражении
	$shans=20;
	}elseif($travel[boss_hp] <= '0'){ //Награда при победе
	$shans=30;
	}
  if($proc < $shans) { //Шанс выпадания шмоток 
$w = mysql_fetch_array(mysql_query('SELECT * FROM `shop` WHERE `quality` <= "3" ORDER BY RAND() LIMIT 1'));
if(mysql_num_rows(mysql_query('SELECT * FROM `inv` WHERE `place` = \'0\' AND `user` = \''.$user['id'].'\'')) + 1 < 200) { //Если в рюкзакуменьше 20-ти вещей
mysql_query('INSERT INTO `inv` (`user`,
                                    `item`,
                                    `quality`,
                                    `_str`,
                                    `_vit`,
                                    `_def`) VALUES (\''.$user['id'].'\',
                                                    \''.$w['id'].'\',
                                                    \''.$w['quality'].'\',
                                                    \''.$w['_str'].'\',
                                                    \''.$w['_vit'].'\',
                                                    \''.$w['_def'].'\')');
$w_id = mysql_insert_id();
$w = mysql_fetch_array(mysql_query('SELECT * FROM `inv` WHERE `id` = \''.$w_id.'\''));
$item = mysql_fetch_array(mysql_query('SELECT * FROM `items` WHERE `id` = \''.$w['item'].'\''));
  


  switch($w['quality']) {
case 1:
$quality = 'Обычный';
$quality_color = '#999999';
break;
case 2:
$quality = 'Необычный';
$quality_color = '#B1D689';
break;
case 3:
$quality = 'Редкий';
$quality_color = '#6BA0E7';
break;
case 4:
$quality = 'Эпический';
$quality_color = '#C780DB';
break;
case 5:
$quality = 'Легендарный';
$quality_color = '#FF8E94';
break;
case 6:
$quality = 'Мифический';
$quality_color = '#FE7E01';
break;
}
  

$equip_item = mysql_query('SELECT * FROM `inv` WHERE `id` = "'.$user['w_'.$item['w']].'"');
$equip_item = mysql_fetch_array($equip_item);
    $diff = 0;
  if($w['_str'] > $equip_item['_str']) { 
$diff += $w['_str'] - $equip_item['_str'];
}
    if($w['_vit'] > $equip_item['_vit']) {
$diff += $w['_vit'] - $equip_item['_vit'];
}
    if($w['_def'] > $equip_item['_def']) {
      $diff += $w['_def'] - $equip_item['_def'];
}


  if(($w['_str'] + $w['_vit'] + $w['_def']) - ($equip_item['_str'] + $equip_item['_vit'] + $equip_item['_def']) > 0) {
$ddd='<font color="#3c3">+'.$diff.'</font> </small>';
  }
$_SESSION['mes_item'] = '
<table cellpadding="0" cellspacing="0">
<tr>
<td width="15%"><img src="/images/items/'.$w['item'].'.png" alt="*"/></td>
<td>
<img src="/images/ico/quality/'.$w['quality'].'.png" alt="*"/> <a href="/item/'.$w['id'].'/"> '.$item['name'].' </a>
<br/><small>
<font color="#'.(($user['level'] < $item['level']) ? 'c06060':'ffffff').'"><img src="/images/ico/png/up.png" alt="*" width="12"/>'.$item['level'].' ур, </font>
<font color="'.$quality_color.'"> '.$quality.' </font>
'.$ddd.'
</td></tr></table>';
  }
  
  }
//  
mysql_query("DELETE FROM `travel_log` WHERE `id_user` = '".$user['id']."'");
  
  
  
  
  
  
  
  
  
if($travel[boss_hp] <= '0'){	
	echo' <div class="empty_block"><center>
    <font color="lime">Вы победили </font> </br>
	<font color="lime">Награда: </font> 
	<img src="/images/ico/png/gold.png"> '.n_f($_gold).'  
	<img src="/images/ico/png/silver.png"> '.n_f($_silver).'
	<img src="/images/ico/png/exp.png"> '.n_f($_exp).'</center>
	'.$_SESSION['mes_item'].'';
	$_SESSION['mes_item']=NULL; //Удаляем сесию
echo'<center>
<img src="/images/ico/travel/travel_win.png"> </center>	
<a href="/travel.php?end=true"><div class="button">Забрать награду</div></a>
</div><div class="line"></div>';
}

if($travel[user_hp] <= '0'){
	echo' <div class="empty_block"><center>
    Вы отступили. </br>
	Возвращайтесь когда станете сильнее </br>
	<font color="lime">Награда: </font>
	<img src="/images/ico/png/silver.png"> '.n_f($_silver).'
	<img src="/images/ico/png/exp.png"> '.n_f($_exp).'</center>
	'.$_SESSION['mes_item'].'';
	$_SESSION['mes_item']=NULL; //Удаляем сесию
echo'<center>	
<img src="/images/ico/travel/travel_lose.png"> </center>
<a href="/travel.php?end=true"><div class="button">Забрать награду</div></a>
</div><div class="line"></div>';
}

	


	
}
			
			
			
			
include './system/f.php';
?>