<?
include './system/common.php';   
include './system/functions.php';     
include './system/user.php';
    
if(!$user) {
header('location: /');   
exit;}
    
$title = 'Арена';
include './system/h.php';  


if(mysql_result(mysql_query('SELECT * FROM `arena` WHERE `user` = "'.$user['id'].'"'),0) == 0) {
mysql_query('INSERT INTO `arena` (`user`) VALUES ("'.$user['id'].'")');
}

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


if($arena[attack] <= '0'){
echo'<div class="title">'.$title.' </div>';
}else{
echo'<div class="title">'.$title.' ('.$arena['attack'].' боев) </div>';
}


 echo' '.$_SESSION['mes1'].' '.$_SESSION['mes2'].' '.$_SESSION['mes3'].'  </div>
 <div class="line"></div>';

    $_SESSION['mes1']=NULL; //Удаляем сесию
    $_SESSION['mes2']=NULL; //Удаляем сесию
	$_SESSION['mes3']=NULL; //Удаляем сесию


if($arena[attack] <= '0'){

echo'<div class="empty_block item_center">
<img src="/images/ico/png/arena_grey.png" alt="*"> 15 боев закончились, возвращайтесь через <br/>
'._time($arena['time']-time()).' чтобы продолжить сражения
<div class="link_center"> <a href="/"> На главную </a> </div>
</div><div class="line"></div>';

include './system/f.php';
exit;
}

























   if(!$arena['opponent']) {
$opponent = mysql_query('SELECT * FROM `users` WHERE `str` + `vit` + `def` >= "'.(($user['str'] + $user['vit'] + $user['def']) / 2).'" AND `str` + `vit` + `def` <= "'.($user['str'] + $user['vit'] + $user['def']).'" AND `id` != "'.$user['id'].'" ORDER BY RAND() LIMIT 1');
$opponent = mysql_fetch_array($opponent);
      
  if(!$opponent) {
$opponent = mysql_query('SELECT * FROM `users` WHERE `str` + `vit` + `def` >= "'.(($user['str'] + $user['vit'] + $user['def']) / 2).'" AND `id` != "'.$user['id'].'" OR `str` + `vit` + `def` <= "'.($user['str'] + $user['vit'] + $user['def']).'" AND `id` != "'.$user['id'].'" ORDER BY RAND() LIMIT 1');
$opponent = mysql_fetch_array($opponent);
}
    
mysql_query('UPDATE `arena` SET `opponent` = "'.$opponent['id'].'" WHERE `user` = "'.$user['id'].'"');
        
}else{
$opponent = mysql_query('SELECT * FROM `users` WHERE `id` = "'.$arena['opponent'].'"');
$opponent = mysql_fetch_array($opponent);
}

  

      
		 
   if($_GET['attack'] == true && $arena[attack] > '0') { 

$dmg = _string(mt_rand($user[str] / 3.5,$user[str] / 3) - mt_rand($opponent[def] / 12,$opponent[def] / 9));
if($dmg <= '0'){ $dmg = 2;}
$opponent_dmg = _string(mt_rand($opponent[str] / 3.5,$opponent[str] / 3) - mt_rand($user[def] / 12,$user[def] / 9));
if($opponent_dmg <= '0'){ $opponent_dmg = 2;}   
     
    if($dmg > $opponent_dmg) { //При победе
$_s = $user['amulet_silver'] + rand(1,10) + (5 * $user['level']);           
$_exp = $user['amulet_exp'] + rand(1,10) + (5 * $user['level']);            
$_SESSION['mes1'] = mes('Победа');
}else{//При поражении
$_s = $user['amulet_silver'] + rand(1,10) + (3 * $user['level']);
$_exp = $user['amulet_exp'] + rand(1,10) + (3 * $user['level']);           
$_SESSION['mes1'] = mes('Поражение');
}

  if($user['trophies_silver']) {$_s+= round($_s/ 100) * $user['trophies_silver'];} //Бонус трофеев
  if($user['trophies_exp']) {$_exp+= round($_exp/ 100) * $user['trophies_exp'];}   //Бонус трофеев

if($_s < 1) {$_s = 1;}
if($_exp < 1) {$_exp = 1;}
   
   
       if($clan_memb && $clan_memb['v'] > 0) {  //Верность клану
$_exp += round($_exp/100) * $clan_memb['v'];
}

  if($premium) {$_s+= round($_s/ 100) * 100;} //Если премик
  if($premium) {$_exp+= round($_exp/ 100) * 100;} //Если премик
  

  
  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'].'"'); //Плюсуем учаснику клана
}


      mysql_query('UPDATE `arena` SET `end` = "0" WHERE `user` = "'.$user['id'].'"');
     
      $opponent = mysql_query('SELECT * FROM `users` WHERE `str` + `vit` + `def` >= "'.(($user['str'] + $user['vit'] + $user['def']) / 2).'" AND `str` + `vit` + `def` <= "'.($user['str'] + $user['vit'] + $user['def']).'" AND `id` != "'.$user['id'].'" ORDER BY RAND() LIMIT 1');
      $opponent = mysql_fetch_array($opponent);
      
      if(!$opponent) {

      $opponent = mysql_query('SELECT * FROM `users` WHERE `str` + `vit` + `def` <= "'.($user['str'] + $user['vit'] + $user['def']).'" AND `id` != "'.$user['id'].'" ORDER BY RAND() LIMIT 1');
      $opponent = mysql_fetch_array($opponent);
      
      }
    mysql_query('UPDATE `arena` SET `opponent` = "'.$opponent['id'].'",
                                          `time` = "'.(time() + 1).'", 
                                          `attack` = `attack` - "1" WHERE `user` = "'.$user['id'].'"');







$_SESSION['mes2'] = '<div class="empty_block">
<center><img src="/images/ico/png/silver.png" alt="*"/> '.n_f($_s).' серебра <img src="/images/ico/png/exp.png" alt="*"/> '.n_f($_exp).' опыта </center>';



if($user['level'] >= '1') { $quality='1';  }
if($user['level'] >= '10'){ $quality='2';  }
if($user['level'] >= '24'){ $quality='3';  }
if($user['level'] >= '36'){ $quality='4';  }
if($user['level'] >= '48'){ $quality='5';  }
if($user['level'] == '60'){ $quality='1';  }



 
  $proc = rand(1,100);
  if($proc < '15' && $dmg > $opponent_dmg) { //Шанс выпадания шмоток 15% только при победе
$w = mysql_fetch_array(mysql_query('SELECT * FROM `shop` WHERE `quality` <= "'.$quality.'" ORDER BY RAND() LIMIT 1'));

if(mysql_num_rows(mysql_query('SELECT * FROM `inv` WHERE `place` = \'0\' AND `user` = "'.$user['id'].'" ')) + 1 < 20) { //Если в рюкзакуменьше 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'].'\''));
  
$task_id_25=25;// Найди на арене 6 вещей необычного качества и лучше
$req2 = mysql_query ('select * from `task_user` WHERE (`user`="'.$user['id'].'") AND (`task`="'.$task_id_25.'") AND (`complete`="0")');
$task2 = mysql_fetch_array(mysql_query ('SELECT * FROM `task` WHERE (`id`="'.$task_id_25.'")'));
   if (mysql_num_rows ($req2) != 0) {
while ($t2 = mysql_fetch_array ($req2)) {
   if ($t2['how'] < $task2['how']){                               
mysql_query ('UPDATE `task_user` SET `how`=`how`+1 WHERE (`user`="'.$user['id'].'") AND (`task`="'.$task_id_25.'")');
}}}
//////////////////////////

  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;
}
  
  if($user['w_'.$item['w']] != 0) {   
$equip_item = mysql_query('SELECT * FROM `inv` WHERE `id` = "'.$user['w_'.$item['w']].'"');
$equip_item = mysql_fetch_array($equip_item);

  if(($w['_str'] + $w['_vit'] + $w['_def']) - ($equip_item['_str'] + $equip_item['_vit'] + $equip_item['_def']) > 0) {
$aaaa='<font color="#30c030">+'.($w['_str'] + $w['_vit'] + $w['_def']) - ($equip_item['_str'] + $equip_item['_vit'] + $equip_item['_def']).'</font> ';
}
  
}else{
$aaaa='<font color="#30c030">+'.($w['_str'] + $w['_vit'] + $w['_def']).'</font>';
}


  
  
$_SESSION['mes3'] = '
<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>
'.$aaaa.' </small>
</td></tr></table>';
  }

}//Конец выпадания шмоток


  
  
  
  
  
// Задания
$task_id=2;// Победи 30 противников на Арене
$req = mysql_query ('SELECT SQL_CACHE * FROM `task_user` WHERE (`user`="'.$user['id'].'") AND (`task`="'.$task_id.'") AND (`complete`="0")');
$task = mysql_fetch_array(mysql_query ('SELECT * FROM `task` WHERE (`id`="'.$task_id.'")'));
   if (mysql_num_rows ($req) != 0) {
while ($t = mysql_fetch_array ($req)) {
   if ($t['how'] < $task['how']){                      
if($dmg > $opponent_dmg) {          
mysql_query ('UPDATE `task_user` SET `how`=`how`+1 WHERE (`user`="'.$user['id'].'") AND (`task`="'.$task_id.'")');
}}}} 
// Задания
$task_id_2=11;// Победи 25 противников на Арене
$req2 = mysql_query ('select * from `task_user` WHERE (`user`="'.$user['id'].'") AND (`task`="'.$task_id_2.'") AND (`complete`="0")');
$task2 = mysql_fetch_array(mysql_query ('SELECT * FROM `task` WHERE (`id`="'.$task_id_2.'")'));
   if (mysql_num_rows ($req2) != 0) {
while ($t2 = mysql_fetch_array ($req2)) {
   if ($t2['how'] < $task2['how']){                      
if($dmg > $opponent_dmg) {          
mysql_query ('UPDATE `task_user` SET `how`=`how`+1 WHERE (`user`="'.$user['id'].'") AND (`task`="'.$task_id_2.'")');
}}}} 
//////////////////////////
$task_id_22=22;// Победи 60 противников на Арене
$req2 = mysql_query ('select * from `task_user` WHERE (`user`="'.$user['id'].'") AND (`task`="'.$task_id_22.'") AND (`complete`="0")');
$task2 = mysql_fetch_array(mysql_query ('SELECT * FROM `task` WHERE (`id`="'.$task_id_22.'")'));
   if (mysql_num_rows ($req2) != 0) {
while ($t2 = mysql_fetch_array ($req2)) {
   if ($t2['how'] < $task2['how']){                      
if($dmg > $opponent_dmg) {          
mysql_query ('UPDATE `task_user` SET `how`=`how`+1 WHERE (`user`="'.$user['id'].'") AND (`task`="'.$task_id_22.'")');
}}}} 
//////////////////////////
$task_id_47=47;// Победи 200 противников на Арене
$req2 = mysql_query ('select * from `task_user` WHERE (`user`="'.$user['id'].'") AND (`task`="'.$task_id_47.'") AND (`complete`="0")');
$task2 = mysql_fetch_array(mysql_query ('SELECT * FROM `task` WHERE (`id`="'.$task_id_47.'")'));
   if (mysql_num_rows ($req2) != 0) {
while ($t2 = mysql_fetch_array ($req2)) {
   if ($t2['how'] < $task2['how']){                      
if($dmg > $opponent_dmg) {          
mysql_query ('UPDATE `task_user` SET `how`=`how`+1 WHERE (`user`="'.$user['id'].'") AND (`task`="'.$task_id_47.'")');
}}}} 
//////////////////////////

mysql_query('UPDATE `users` SET `exp` = `exp` + '.$_exp.', `s` = `s` + '.$_s.' WHERE `id` = "'.$user['id'].'"'); 
header("Location: /arena/"); 
exit; 
}




  
  
  
  $opponent = mysql_query('SELECT * FROM `users` WHERE `id` = "'.$arena['opponent'].'"');
  $opponent = mysql_fetch_array($opponent);

echo'<div class="empty_block">
<table cellpadding="0" cellspacing="0">
<tr>
<td><a href="/arena/?attack=true">';
 

if($opponent['sex'] == '0'){
echo'<img src="/images/user/man.png" alt="*">';}
if($opponent['sex'] == '1'){
echo'<img src="/images/user/woman.png" alt="*">';}

echo'</a></td>
<td>  <img src="/images/ico/png/hero.png" alt="*"/>'.$opponent['login'].'<br/>
    <img src="/images/ico/png/attack.png" alt="*"/> Сила:   '.$opponent['str'].'     <br/>
    <img src="/images/ico/png/hp.png" alt="*"/> Жизнь:  '.$opponent['vit'].' <br/>
    <img src="/images/ico/png/def.png" alt="*"/> Защита: '.$opponent['def'].'     <br/>   
</td>
</tr></table>
<div class="link_center"><a href="/arena/?attack=true">Атаковать</a></div>
</div><div class="line"></div>';






  
echo'<div class="empty_block">
Ваши параметры:<br/>
	<img src="/images/ico/png/attack.png" alt="*"/> '.$user['str'].'
	<img src="/images/ico/png/hp.png" alt="*"/> '.$user['vit'].'
	<img src="/images/ico/png/def.png" alt="*"/> '.$user['def'].'
</div><div class="line"></div>';

echo'<div class="empty_block item_center">
Чем выше уровень амулета, тем больше опыта и серебра получишь за победу!
</div><div class="line"></div>
<div class="block_link"><a href="/shop/amulet"><img src="/images/ico/png/amulet.png" alt="*"/> Амулет арены (+) </a>
</div><div class="line"></div>';
include './system/f.php';

?>