<?


include 'connect.php';

if(!$u['id']){
header ("Location: aut.php");
exit;
}

$da = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_add` WHERE `user2` = '".$u['id']."'"), 0);

switch ($_GET['act']) {

//Вызов на дуэль ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'add':

//Если id получен 
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `users` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req) and $id != $u['id']) {
   $user = mysql_fetch_assoc($req);
   }
}

//Если кто то выбрался
if(isset($user['id'])){
include 'head.php';
echo '<div class="title"><img src= "img/duels.gif"> <b>Дуэли</b></div>';

//Заголовок раздела
echo '<div class="nav">';
   echo '<a href = "duels.php?act=view>Мои дуэли</a> | <a href = "duels.php?act=add_list">Вызовы ('.$da.')</a><br/><b>Вызов на дуэль</b>';
   echo '</div>';
echo '<div class="block_action">';
//Проверим не на дуэли ли тот кто пытается вызвать
$req = mysql_query("SELECT * FROM `duels_list` WHERE (`user1` = '".$u['id']."' or `user2` = '".$u['id']."') and `time_end` > '".time()."' LIMIT 1");
if(mysql_num_rows($req)){
echo 'Вы на дуэли!';
} else {
   //Проверяем не на дуэли ли
   $req = mysql_query("SELECT * FROM `duels_list` WHERE (`user1` = '".$user['id']."' or `user2` = '".$user['id']."') and `time_end` > '".time()."' LIMIT 1");
   if(mysql_num_rows($req)){
   echo 'Пользователь <a href = "page.php?id='.$user['id'].'">'.$user['login'].'</a> уже на дуэли!';
   } else {
      //Не встречная ли заявка
	  $req = mysql_query("SELECT * FROM `duels_add` WHERE `user1` = '".$user['id']."' and `user2` = '".$u['id']."' LIMIT 1");
      if(mysql_num_rows($req)){
	     //Если заявка встречная направляем сразу в принятие заявки
		 header ("Location: friends.php?act=add_list&add='".$user['id']."'");
	  } else {
	     //Не повторная ли заявка
	     $req = mysql_query("SELECT * FROM `duels_add` WHERE `user1` = '".$u['id']."' and `user2` = '".$user['id']."' LIMIT 1");
         if(mysql_num_rows($req)){
		 echo 'Вызов пользователю <a href = "page.php?id='.$user['id'].'">'.$user['login'].'</a> уже был отправлен ранее!';
		 } else {
		    if (isset($_POST['submit'])) {
			//удаляем заявки если есть
			mysql_query("DELETE FROM `duels_add` WHERE `user1` = '".$u['id']."'");
            mysql_query("INSERT INTO `duels_add` SET
            `user1` = '".$u['id']."',
	        `user2` = '".$user['id']."',
	        `time` = '".time()."'
            ");
			//Записываем в журнал
      if($u['sex'] == 'm'){
      $action[0] = 'Вызвал';
      } else {
      $action[0] = 'Вызвала';
      }
      $text = $action[0].' Вас на <a href = "duels.php?act=add_list">дуэль</a>.';
      mysql_query("INSERT INTO `jurnal` SET
      `user` = '".$user['id']."',
      `outuser` = '".$u['id']."',
      `text` = '$text',
      `time` = '".time()."',
      `new` = '1'
      ");
            echo 'Вызов пользователю <a href = "page.php?id='.$user['id'].'">'.$user['login'].'</a> отправлен!';
            } else {
	        echo 'Вызываем пользователя <a href = "page.php?id='.$user['id'].'">'.$user['login'].'</a> на дуэль?<br/>';
			//Нет ли заявки
	        $req = mysql_query("SELECT * FROM `duels_add` WHERE `user1` = '".$u['id']."' LIMIT 1");
            if(mysql_num_rows($req)){
		    echo '<div class = "action">Предыдущий Ваш вызов будет отменен!</div>';
		    }
			echo '<form action="duels.php?act=add&id='.$user['id'].'" method="post">';
            echo '<input type="submit" name="submit" class="btn" value="Да, вызываем" class="submit white"/>';
            echo '</form></div>';
            }
		 }
	  }
		 
	  }
}
echo '</div>';
include 'foot.php';
//Если никто не выбрался
} else {
header ("Location: index.php");
}
break;

//Вызовы, обработка ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'add_list':
include 'head.php';
//Подзаголовок
echo '<div class="title"><img src= "img/duels.gif"> <b>Дуэли</b></div>';

//Заголовок раздела
echo '<div class="nav">';
echo '<a href = "duels.php?act=view">Мои дуэли</a> | <a href = "duels.php?act=add_list">Вызовы ('.$da.')</a>'; if($fa){ echo ' | <a href = "friends.php?act=adding_list">Заявки ('.$fa.')</a>';}
echo '</div>';

//Принять
if($_GET['add']){
$add = num($_GET['add']);
   $req = mysql_query("SELECT * FROM `duels_add` WHERE `user1` = '$add' and `user2` = '".$u['id']."' LIMIT 1");
   if (mysql_num_rows($req)) {
   $user = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '$add' LIMIT 1"));
   mysql_query("INSERT INTO `duels_list` SET
   `user1` = '".$user['id']."',
   `user2` = '".$u['id']."',
   `time` = '".time()."',
   `time_end` = '".(time()+(60*60*24*3))."'
   ");
   
   //Записываем в журнал
   if($u['sex'] == 'm'){
   $action[0] = 'Принял';   
   } else {
   $action[0] = 'Приняла';
   }
   $text = $action[0].' Ваш вызов на <a href = "duels.php?act=view">дуэль</a>!';
   mysql_query("INSERT INTO `jurnal` SET
   `user` = '".$user['id']."',
   `outuser` = '".$u['id']."',
   `text` = '$text',
   `time` = '".time()."',
   `new` = '1'
   ");
   mysql_query("DELETE FROM `duels_add` WHERE `user1` = '$add' and `user2` = '".$u['id']."'");
   echo '<div class = "action">Вызов от пользователя <a href = "page.php?id='.$user['id'].'">'.$user['login'].'</a> принят!</div><hr>';
   } else {
   
   }
}

//Отклонить
if($_GET['notadd']){
$notadd = num($_GET['notadd']);
   $req = mysql_query("SELECT * FROM `friends_adding` WHERE `user` = '$notadd' and `friend` = '".$u['id']."' LIMIT 1");
   if (mysql_num_rows($req)) {
   $user = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '$notadd' LIMIT 1"));
   mysql_query("DELETE FROM friends_adding WHERE user = '".$user['id']. "' and `friend` = '".$u['id']."'");
   echo '<div class = "action">Заявка от пользователя <a href = "page.php?id='.$user['id'].'">'.$user['login'].'</a> отклонена!</div>';
   } else {
   
   }
}

$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_add` WHERE `user2` = '".$u['id']."'"), 0);
if($all > 0){
   $total = intval(($all - 1) / 10) + 1;
   $page = num($_GET['page']);
   if(empty($page) or $page < 0) $page = 1; 
   if($page > $total) $page = $total;
   $start = $page * 10 - 10;
   $result = mysql_query("SELECT * FROM `duels_add` WHERE `user2` = '".$u['id']."' ORDER BY `time` DESC LIMIT $start, 10");
      while($duel = mysql_fetch_assoc($result)){
	  $user = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '".$duel["user1"]."'"));
	  //Вывод
	  echo '<div class="block_list">';
	  echo '<table>
      <tr>
      <td>';
	  ava($user['id'],50);
	  echo '</td>
	  <td VALIGN=top>';
	  echo ''.ico($user['sex'],$user['admin']).' <a href = "page.php?id='.$user['id'].'">'.$user['login'].'</a> '.online($user['online']).'';
	  echo '<br/>';
	  echo '<a href = "duels.php?act=add_list&add='.$user['id'].'">Принять</a> | <a href = "duels.php?act=add_list&notadd='.$user['id'].'">Отклонить</a>';
	  echo '</td>
      </tr>
      </table>';

      echo '</div>';

	  }
	  navigation($page, $total,'duels.php?act=add_list&');
}else{
echo '<div class = "center">У Вас еще нет вызовов на дуэль!</div>';
}

include 'foot.php';
break;

//Дуэли пользователей ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'view':

//Если id получен 
$id=num($_GET['id']);
if(!$id) $id=$u['id'];
$req = mysql_query("SELECT * FROM `users` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)) {
   $user = mysql_fetch_assoc($req);
}
if(!$user['id']){
header ("Location: index.php");
exit;
}

if($id == $u['id']) $zag = 'Мои дуэли';
else $zag = 'Дуэли <a href = "page.php?id='.$user['id'].'">'.$user['login'].'</a>';

$title = $title.' | Дуэли';
include 'head.php';

echo '<div class="title"><img src= "img/duels.gif"> <b>'.$zag.'</b></div>';

if($u['id']){
//Подсчет
$d = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_list` WHERE `user1` = '".$u['id']."' OR `user2` = '".$u['id']."'"), 0);
$da = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_add` WHERE `user2` = '".$u['id']."'"), 0);
}

echo '<div class="nav">';
echo '<a href = "duels.php?act=view">Мои дуэли ('.$d.')</a> | <a href = "duels.php?act=add_list">Мои вызовы ('.$da.')</a>';
echo '</div>';

$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_list` WHERE `user1` = '".$user['id']."' OR `user2` = '".$user['id']."'"), 0);
$duels_victory = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_list` WHERE (`user1` = '".$user['id']."' OR `user2` = '".$user['id']."') AND `time_end` < '".time()."' AND `victory` = '".$user['id']."'"), 0);
$duels_victory2 = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_list` WHERE (`user1` = '".$user['id']."' OR `user2` = '".$user['id']."') AND (`time_end` < '".time()."' AND `victory` > 0 AND `victory` <> '".$user['id']."')"), 0);
$duels_victory3 = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_list` WHERE (`user1` = '".$user['id']."' OR `user2` = '".$user['id']."') AND `time_end` < '".time()."' AND `victory` = '0'"), 0);


echo '<div class="block_action">';
echo 'Побед: '.$duels_victory.'<br/>';
echo 'Поражений: '.$duels_victory2.'<br/>';
echo 'Ничьих: '.$duels_victory3.'<br/>';
echo '</div>';
echo '<div class="main_menu">';

//Голосование
//Если id получен и голос
if(isset($_GET['duel']) and isset($_GET['vote'])){
$duel=num($_GET['duel']);
$vote=num($_GET['vote']);
   if($vote ==1 or $vote = 2) {
$req = mysql_query("SELECT * FROM `duels_list` WHERE `id` = '$duel' AND `time_end` > '".time()."' LIMIT 1");
   if (mysql_num_rows($req)) {
   $duel = mysql_fetch_assoc($req);
      //Проверяем не голосовал ли
	  $req = mysql_query("SELECT * FROM `duels_votes` WHERE `user` = '".$u['id']."' AND `duel` = '".$duel['id']."' LIMIT 1");
      if(mysql_num_rows($req) == 0){
	  mysql_query("INSERT INTO `duels_votes` SET
      `user` = '".$u['id']."',
	  `vote` = '$vote',
      `time` = '".time()."',
      `duel` = '".$duel['id']."'
      ");
	  }
   }
   }
}


if($all > 0){
   $total = intval(($all - 1) / 10) + 1;
   $page = num($_GET['page']);
   if(empty($page) or $page < 0) $page = 1; 
   if($page > $total) $page = $total;
   $start = $page * 10 - 10;
   $result = mysql_query("SELECT * FROM `duels_list` WHERE `user1` = '".$user['id']."' OR `user2` = '".$user['id']."' ORDER BY `time` DESC LIMIT $start, 10");
      while($duel = mysql_fetch_assoc($result)){
	  echo '<div class="block_list">';
	  
	  //Если прошедший дуэль
	  if($duel['time_end'] < time()){
	  $user1 = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '".$duel["user1"]."'"));
	  $user2 = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '".$duel["user2"]."'"));
      echo '<img src = "img/time.png"> '.vremya($duel['time_end']).'<br/>';
	  echo '<table>
      <tr>
      <td VALIGN=top width = 100>';
	  ava($user1['id'],50);
	  $count = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_votes` WHERE `vote` = '1' AND `duel` = '".$duel['id']."'"), 0);
	  echo '<br/><a href = "page.php?id='.$user1['id'].'">'.$user1['login'].'</a> ('.$count.')<br/>';
	  echo '</td>
	  <td VALIGN=top>';
	  echo '<br/>vs.';
	  echo '</td>
	  <td VALIGN=top width = 100>';
	  ava($user2['id'],50);
	  $count = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_votes` WHERE `vote` = '2' AND `duel` = '".$duel['id']."'"), 0);
	  echo '<br/><a href = "page.php?id='.$user2['id'].'">'.$user2['login'].'</a> ('.$count.')<br/>';
	  echo '</td>
      </tr>
      </table>';
	  //Если еще идет
	  } else {
	  //Проверяем не голосовал ли
	  $req = mysql_query("SELECT * FROM `duels_votes` WHERE `user` = '".$u['id']."' AND `duel` = '".$duel['id']."' LIMIT 1");
      if(mysql_num_rows($req) == 0) $vote_acces = true; else $vote_acces = false;
	  $user1 = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '".$duel["user1"]."'"));
	  $user2 = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '".$duel["user2"]."'"));
	  $time = $duel['time_end']-time();
	  $chas=intval($time/3600);
      if($chas>0){ 
         $chas = $chas.' ч.';
	     $time=$time-($chas*3600);
      } else {
         $chas = '';
      }
      $min=intval($time/60);
      if($min>0){ 
         $min = $min.' м.';
	     $time=$time-($min*60);
      } else {
         $min = '';
      }
      $sek =  $time.' с.';
      echo '<img src = "img/time.png"> Осталось: '.$chas.' '.$min.'<br/>';
	  echo '<table>
      <tr>
      <td VALIGN=top width = 100>';
	  ava($user1['id'],50);
	  $count = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_votes` WHERE `vote` = '1' AND `duel` = '".$duel['id']."'"), 0);
	  echo '<br/><a href = "page.php?id='.$user1['id'].'">'.$user1['login'].'</a> ('.$count.')<br/>';
	  if($vote_acces == true) echo '<a href = "duels.php?act=view&id='.$id.'&duel='.$duel['id'].'&vote=1"><font color = "red">(+1)</font></a>';
	  echo '</td>
	  <td VALIGN=top>';
	  echo '<br/>vs.';
	  echo '</td>
	  <td VALIGN=top width = 100>';
	  ava($user2['id'],50);
	  $count = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_votes` WHERE `vote` = '2' AND `duel` = '".$duel['id']."'"), 0);
	  echo '<br/><a href = "page.php?id='.$user2['id'].'">'.$user2['login'].'</a> ('.$count.')<br/>';
	  if($vote_acces == true) echo '<a href = "duels.php?act=view&id='.$id.'&duel='.$duel['id'].'&vote=2"><font color = "red">(+1)</font></a>';
	  echo '</td>
      </tr>
      </table>';
	  }
	  echo '</div>';

	  }
	  navigation($page, $total,'duels.php?act=view&id='.$id.'&');
}else{
echo '<div class = "center">Дуэлей пока нет!</div>';
}

echo '</div>';
include 'foot.php';
break;

//Список всех дуэлей ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
default:
$title = $title.' | Дуэли';
include 'head.php';
//Подзаголовок
echo '<div class="title"><img src= "img/duels.gif"> <b>Дуэли</b></div>';

if($u['id']){
//Подсчет
$d = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_list` WHERE `user1` = '".$u['id']."' OR `user2` = '".$u['id']."'"), 0);
$da = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_add` WHERE `user2` = '".$u['id']."'"), 0);
echo '<div class="nav">';
echo '<a href = "duels.php?act=view">Мои дуэли ('.$d.')</a> | <a href = "duels.php?act=add_list">Мои вызовы ('.$da.')</a>';
echo '</div>';
}

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

//Голосование
//Если id получен и голос
if(isset($_GET['id']) and isset($_GET['vote'])){
$id=num($_GET['id']);
$vote=num($_GET['vote']);
   if($vote ==1 or $vote = 2) {
$req = mysql_query("SELECT * FROM `duels_list` WHERE `id` = '$id' AND `time_end` > '".time()."' LIMIT 1");
   if (mysql_num_rows($req)) {
   $duel = mysql_fetch_assoc($req);
      //Проверяем не голосовал ли
	  $req = mysql_query("SELECT * FROM `duels_votes` WHERE `user` = '".$u['id']."' AND `duel` = '".$duel['id']."' LIMIT 1");
      if(mysql_num_rows($req) == 0){
	  mysql_query("INSERT INTO `duels_votes` SET
      `user` = '".$u['id']."',
	  `vote` = '$vote',
      `time` = '".time()."',
      `duel` = '".$duel['id']."'
      ");
	  }
   }
   }
}


$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_list` WHERE `time_end` > '".time()."'"), 0);
if($all > 0){
   $total = intval(($all - 1) / 10) + 1;
   $page = num($_GET['page']);
   if(empty($page) or $page < 0) $page = 1; 
   if($page > $total) $page = $total;
   $start = $page * 10 - 10;
   $result = mysql_query("SELECT * FROM `duels_list` WHERE `time_end` > '".time()."' ORDER BY `time` DESC LIMIT $start, 10");
      while($duel = mysql_fetch_assoc($result)){
	  
	  //Проверяем не голосовал ли
	  $req = mysql_query("SELECT * FROM `duels_votes` WHERE `user` = '".$u['id']."' AND `duel` = '".$duel['id']."' LIMIT 1");
      if(mysql_num_rows($req) == 0) $vote_acces = true; else $vote_acces = false;
	  
	  $user1 = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '".$duel["user1"]."'"));
	  $user2 = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '".$duel["user2"]."'"));
	  echo $i % 2 ? '<div class="block2">' : '<div class="block1">';
	  $time = $duel['time_end']-time();
	  $chas=intval($time/3600);
      if($chas>0){ 
         $chas = $chas.' ч.';
	     $time=$time-($chas*3600);
      } else {
         $chas = '';
      }
      $min=intval($time/60);
      if($min>0){ 
         $min = $min.' м.';
	     $time=$time-($min*60);
      } else {
         $min = '';
      }
      $sek =  $time.' с.';
   
   echo '<img src = "img/time.png"> Осталось: '.$chas.' '.$min.'<br/>';
	  echo '<table>
      <tr>
      <td VALIGN=top width = 100>';
	  ava($user1['id'],50);
	  $count = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_votes` WHERE `vote` = '1' AND `duel` = '".$duel['id']."'"), 0);
	  echo '<br/><a href = "page.php?id='.$user1['id'].'">'.$user1['login'].'</a> ('.$count.')<br/>';
	  
	  if($vote_acces == true) echo '<a href = "duels.php?id='.$duel['id'].'&vote=1"><font color = "red">(+1)</font></a>';
	  
	  echo '</td>
	  <td VALIGN=top>';
	  echo '<br/>vs.';
	  echo '</td>
	  <td VALIGN=top width = 100>';
	  ava($user2['id'],50);
	  $count = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_votes` WHERE `vote` = '2' AND `duel` = '".$duel['id']."'"), 0);
	  echo '<br/><a href = "page.php?id='.$user2['id'].'">'.$user2['login'].'</a> ('.$count.')<br/>';
	  if($vote_acces == true) echo '<a href = "duels.php?id='.$duel['id'].'&vote=2"><font color = "red">(+1)</font></a>';
	  echo '</td>
      </tr>
      </table>';
      echo '<hr>';
      echo '</div>';
	  $i++;
	  }
	  navigation($page, $total,'duels.php?');
}else{
echo '<div class = "center">Дуэлей пока нет!</div>';
}

echo '</div>';
include 'foot.php';
break;
}
?>