<?php 

define('H', $_SERVER['DOCUMENT_ROOT'].'/');
include_once H.'sys/inc/start.php';
include_once H.'sys/inc/compress.php';
include_once H.'sys/inc/sess.php';
include_once H.'sys/inc/settings.php';
include_once H.'sys/inc/db_connect.php';
include_once H.'sys/inc/ipua.php';
include_once H.'sys/inc/fnc.php';
include_once H.'sys/inc/user.php';

if (isset($user)) {
  $ifuser = true;
} else {
  $ifuser = false;
}

$sex = 0;

require 'config.php';

if (isset($_GET['id'])) {
  $ID = (int) $_GET['id'];
  $sexwars = mysql_fetch_assoc(mysql_query("SELECT * FROM `sexwars` WHERE `id` = '$ID' LIMIT 1"));
}

if (!isset($sexwars['id'])) {
  $sexwars = mysql_fetch_assoc(mysql_query("SELECT * FROM `sexwars` WHERE `active` = '1' LIMIT 1"));
}

$count = mysql_fetch_assoc(mysql_query("SELECT SUM(IF (sex = 'female', 1, 0)) AS female, SUM(IF (sex = 'male', 1, 0)) AS male FROM `sexwars_users` WHERE `id_tournament` = '$sexwars[id]' LIMIT 1"));

if (mysql_result(mysql_query("SELECT COUNT(*) FROM `sexwars` WHERE `active` = '1'"), 0) == 0) {
  mysql_query("INSERT INTO `sexwars`(`time`, `active`) VALUES ('$time', '1')");
}

if ($ifuser) 
{
  $sex = ($user['pol'] == '0' ? 'female' : 'male');
  
  // Игровая анкета
  $ank = mysql_fetch_assoc(mysql_query("SELECT * FROM `sexwars_users` WHERE `id_user` = '$user[id]' LIMIT 1"));
  
  if (isset($_POST['msg']) && isset($ank['id']) && $sexwars['active'] == 1) 
  {
  	$msg = $_POST['msg'];
    
  	$mat = antimat($msg);
    
  	if ($mat) { 
      $err[] = 'В тексте сообщения обнаружен мат: ' . $mat;
    } 
    
  	if (strlen2($msg) > 512){ $err[] = 'Сообщение слишком длинное'; }
  	elseif (strlen2($msg) < 2){ $err[] = 'Короткое сообщение'; }
  	elseif (mysql_result(mysql_query("SELECT COUNT(*) FROM `sexwars_chat` WHERE `id_user` = '$user[id]' AND `id_tournament` = '$sexwars[id]' AND `msg` = '" . my_esc($msg) . "' LIMIT 1"),0) != 0)
  	{
  		$err[] = 'Ваше сообщение повторяет предыдущее';
  	}
  	
    if (!isset($err))
  	{
  		// Начисление баллов за активность
  		include_once H.'sys/add/user.active.php';
      
  		if (isset($ank_reply['id']))
  		{
  			$ank_reply = get_user($ank_reply['id']);
  			
  			if ($ank_reply['id'] != $user['id'] && $ank_reply['url'] != $_SERVER['PHP_SELF']) {
          mysql_query("INSERT INTO `notification` (`avtor`, `id_user`, `type`, `time`) VALUES ('$user[id]', '$ank_reply[id]', 'sexwars', '$time')");
        }
  		}

  		mysql_query("INSERT INTO `sexwars_chat` (id_user, time, msg, id_tournament, sex) values('$user[id]', '$time', '" . my_esc($msg) . "', '$sexwars[id]', '$sex')");
  		$_SESSION['message'] = 'Сообщение успешно добавлено';
  		header ('Location: ?id=' . $sexwars['id']);
  		exit;
  	}
  }
  
  /**
  * Регистрация в игре
  */
  
  if (isset($_GET['start']) && !isset($ank['id']) && $sexwars['active'] == 1) {
    mysql_query("INSERT INTO `sexwars_users`(`time`, `sex`, `id_tournament`, `id_user`) VALUES ('$time', '$sex', '$sexwars[id]', '$user[id]')");
    header('Location: ?id=' . $sexwars['id']);
    exit;
  } 
  
  if ($ank['id_tournament'] != $sexwars['id'] && $sexwars['active'] == 1) {
    mysql_query("UPDATE `sexwars_users` SET `id_tournament` = '$sexwars[id]', `count_weapon` = '0' WHERE `id_user` = '$user[id]' LIMIT 1");
  }
  
  if ($sexwars['active'] == 1 && ($sexwars['female'] == 100 || $sexwars['male'] == 100)) {
    $win = ($sexwars['female'] == 100 ? 'female' : 'male');
    mysql_query("UPDATE `sexwars` SET `active` = '0', `win` = '$win', `time_end` = '$time' WHERE `id` = '$sexwars[id]' LIMIT 1");
    
    $q = mysql_query("SELECT * FROM `sexwars_users` WHERE `id_tournament` = '$sexwars[id]' AND `sex` = '$win' ORDER BY `count_weapon` DESC LIMIT 5");
    
    while($wars = mysql_fetch_assoc($q)) {
        $msg = 'Поздравляем!!! Ваша команда победила в игре [url=/plugins/sexwar/]Война Полов[/url], вам начислено ' . 
        ($config['balls'] > 0 ? des2num(ceil($config['balls'] * $wars['count_weapon']), $config['balls_name']) . ', ' : '') . 
        ($config['money'] > 0 ? des2num(ceil($config['money'] * $wars['count_weapon']), $config['coins_name']) . ', ' : '') . 
        ($config['rating'] > 0 ? des2num(ceil($config['rating'] * $wars['count_weapon']), $config['rating_name']) . ', ' : '') . 
        ' удачи в следующей битве! :)';
        
        mysql_query("UPDATE `user` SET 
        `balls` = `balls` + '" . ceil($config['balls'] * $wars['count_weapon']) . "', 
        `money` = `money` + '" . ceil($config['money'] * $wars['count_weapon']) . "', 
        `rating` = `rating` + '" . ceil($config['rating'] * $wars['count_weapon']) . "' WHERE `id` = '$wars[id_user]' LIMIT 1");
        
        mysql_query("INSERT INTO `mail` (`id_user`, `id_kont`, `msg`, `time`) values('0', '$wars[id_user]', '" . my_esc($msg) . "', '$time')");
    }
  } 
  
  /**
  * Действие 
  */
  
  if (isset($_GET['act']) && $sexwars['active'] == 1) 
  {
    $glums_id = $_GET['act'];
    
    if (!isset($glums[$glums_id])) {
      $err[] = 'Такого ляпа не существует';
    }
    
    if ($ank['time_reboot'] > $time) {
      $err[] = 'Идет перезарядка..';
    }
    
    if (!isset($err)) {
      $glum['type'] = $glums_id;
      $glum['id'] = mt_rand(1, $glums[$glums_id]);
      $glum['style'] = array('top' => mt_rand(-10, 90), 'left' => mt_rand(-10, 90), 'rotate' => mt_rand(0, 360));
      
      mysql_query("INSERT INTO `sexwars_weapons` (`time`, `sex`, `id_tournament`, `id_user`, `style`, `type`, `id_weapon`) VALUES ('$time', '$sex', '$sexwars[id]', '$user[id]', '" . serialize($glum['style']) . "', '" . $glum['type'] . "', '" . $glum['id'] . "')");
      
      mysql_query("UPDATE `sexwars_users` SET `time_reboot` = '" . ($time + $config['reboot']) . "', `count_weapon` = `count_weapon` + '1', `rating` = `rating` + '1' WHERE `id_user` = '$user[id]' LIMIT 1");
      
      mysql_query("UPDATE `sexwars` SET `" . $sex . "` = `" . $sex . "` + '1' WHERE `id` = '$sexwars[id]' LIMIT 1");
      header('Location: ?id=' . $sexwars['id']);
      exit;
    }
  }
}

if (isset($_GET['delete']) && user_access('guest_delete')) {
    $delete = (int) $_GET['delete'];
  	mysql_query("DELETE FROM `sexwars_chat` WHERE `id` = '$delete' LIMIT 1");
  	$_SESSION['message'] = 'Сообщение успешно удалено';
  	header('Location: ?id=' . $sexwars['id']);
  	exit;
}

$set['title'] = 'Война полов';
include_once H.'sys/inc/thead.php';
title();
aut();
err();
?>
<link rel="stylesheet" href="css/main.css" type="text/css" />

<table class="sexwar">
  <tr>
    <td>
      <div class="title-female"><a href="users.php?id=<?= $sexwars['id']?>&amp;sex=female">Девушки</a> (<?= $count['female']?>)</div>
    </td>
    
    <td>
      <div class="title-male"><a href="users.php?id=<?= $sexwars['id']?>&amp;sex=male">Парни</a> (<?= $count['male']?>)</div>
    </td>
  </tr>
  
  <tr>
    <td>
      <div class="wars-progress">
        <div class="female" style="width: <?= (100 - $sexwars['male'])?>%;"></div>
        <span><?= (100 - $sexwars['male'])?>%</span>
      </div> 
    </td>
    
    <td>
      <div class="wars-progress">
        <div class="male" style="width: <?= (100 - $sexwars['female'])?>%;"></div>
        <span><?= (100 - $sexwars['female'])?>%</span>
      </div>
    </td>
  </tr>
  
  <tr>
    <td class="display female">
     <?= weapon_avatars($sexwars['id'], 'female')?>
     
     <div>
       <?= weapon_view($sexwars['id'], 'male')?>
       <?= ($sexwars['active'] == 0 && $sexwars['win'] == 'male' ? '<div class="potracheno"><img src="images/potracheno.png" /></div>' : '')?>
     </div>
    </td>
    
    <td class="display male">
     <?= weapon_avatars($sexwars['id'], 'male')?>
     
     <div>
       <?= weapon_view($sexwars['id'], 'female')?>
       <?= ($sexwars['active'] == 0 && $sexwars['win'] == 'female' ? '<div class="potracheno"><img src="images/potracheno.png" /></div>' : '')?>
     </div>
    </td>
  </tr>
  
  <? if ($sexwars['active'] == 1) { ?>
  <tr>
    <td class="weapon">
    <? if (isset($ank['id']) && $sex == 'male') { ?>
      <? if ($ank['time_reboot'] < $time) { ?>
        <?= weapon_panel()?>
      <? } else { ?>
        <img src="images/clock-history.png" /> <?= weapon_time($ank['time_reboot'])?>
      <? } ?>
    <? } elseif (isset($ank['id'])) { ?>
      Я: <?= des2num($ank['count_weapon'], array('выстрел', 'выстрела', 'выстрелов'))?>
    <? } else { ?>
      Участников (<?= mysql_result(mysql_query("SELECT COUNT(id) FROM `sexwars_users` WHERE `id_tournament` = '$sexwars[id]' AND `sex` = 'female' AND `count_weapon` > '0'"), 0)?>)
    <? } ?>
    </td>
    
    <td class="weapon">
    <? if (isset($ank['id']) && $sex == 'female') { ?>
      <? if ($ank['time_reboot'] < $time) { ?>
        <?= weapon_panel()?>
      <? } else { ?>
        <img src="images/clock-history.png" /> <?= weapon_time($ank['time_reboot'])?>
      <? } ?>
    <? } elseif (isset($ank['id'])) { ?>
      Я: <?= des2num($ank['count_weapon'], array('выстрел', 'выстрела', 'выстрелов'))?>
    <? } else { ?>
      Участников (<?= mysql_result(mysql_query("SELECT COUNT(id) FROM `sexwars_users` WHERE `id_tournament` = '$sexwars[id]' AND `sex` = 'male' AND `count_weapon` > '0'"), 0)?>)
    <? } ?>
    </td>
  </tr>
  <? } ?>
</table>

<? if ($sexwars['active'] == 0) { ?>
  <div class="wars-over">
    <img src="images/trophy.png" /> Победители команда <b>&laquo;<?= ($sexwars['win'] == 'male' ? 'Парней' : 'Девочек')?>&raquo;</b><br />
    <img src="images/alarm-clock.png" /> Время завершения <?= vremja($sexwars['time_end'])?><br />
  </div>
  
  <div class="sex_chat">
    Победители битвы №<?= $sexwars['id']?>
  </div>
  
  <? 
  $q = mysql_query("SELECT id_user, count(id) AS count
    FROM sexwars_weapons
    WHERE `id_tournament` = '$sexwars[id]' AND `sex` = '$sexwars[win]'
    GROUP BY id_user
    ORDER BY `count` DESC LIMIT 5");
  $num = 0;
  
  while($wars = mysql_fetch_assoc($q)) 
  {
    $num++;
    ?>
    <div class="sex_menu">
      <?= $num?>) <img src="images/medal-<?= $num?>.png" /> <?= user::nick($wars['id_user'], 1, 1, 1)?> <?= des2num($wars['count'], array('очко', 'очка', 'очков'))?>
    </div>
    <?
  }
  ?>
<? } ?>

<?
if ($ifuser && !isset($ank['id']) && $sexwars['active'] == 1) {
  ?>
  <div class="sex_menu">
    <img src="images/fire-plus.png" /> <a href="?id=<?= $sexwars['id']?>&amp;start">Вступить в битву</a>
  </div>
  <?
}

/**
* Чат битвы полов
*/

?>
<div class="sex_chat">
  Чат &laquo;Война Полов&raquo;
</div>
<?

$k_post = mysql_result(mysql_query("SELECT COUNT(id) FROM `sexwars_chat` WHERE `id_tournament` = '$sexwars[id]'"), 0);
$k_page = k_page($k_post, $set['p_str']);
$page = page($k_page);
$start = $set['p_str'] * $page - $set['p_str'];

if ($ifuser && isset($ank['id']) && $sexwars['active'] == 1)
{
	?><form class="weapon_form" method="post" name="message" action="?id=<?= $sexwars['id']?>page=<?= $page . REPLY?>"><?
	if (is_file(H.'style/themes/' . $set['set_them'] . '/altername_post_form.php')) {
    include_once H.'style/themes/' . $set['set_them'] . '/altername_post_form.php';
  } else {
    echo $tPanel . '<textarea name="msg">' . $insert . '</textarea><br />';
  }
	?>
  <input value="Отправить" type="submit" /> <a class="btn btn-link" href="?id=<?= $sexwars['id']?>">Обновить</a>
	</form>
  <?
}

?><table class="post"><?

if ($k_post == 0)
{
	?>
  <div class="mess" id="no_object">
	Нет сообщений
	</div>
  <?
}

$q = mysql_query("SELECT * FROM `sexwars_chat` WHERE `id_tournament` = '$sexwars[id]' ORDER BY id DESC LIMIT $start, $set[p_str]");

$num = 0;

while ($post = mysql_fetch_assoc($q))
{
	// Лесенка
	?><div class="post-<?= $post['sex']?>"><?
	$num++;
    
	echo user::avatar($post['id_user'], 2) . user::nick($post['id_user'], 1, 1, 1);
  
	if (isset($user) && $user['id'] != $post['id_user']) {
    echo ' <a href="?id=' . $sexwars['id'] . '&amp;=' . $page . '&amp;response=' . $post['id_user'] . '">[*]</a> ';
  } 

	echo ' (' . vremja($post['time']) . ') <br />'; 
  echo output_text($post['msg']);

	?>
  <span class="pull-right">
  <?
	if (user_access('guest_delete')) {
		?><a href="?id=<?= $sexwars['id']?>&amp;delete=<?= $post['id']?>"><img src="/style/icons/delete.gif" alt="*" title="Удалить сообщение"></a><?
	}
	?>
  </span>
	</div>
  <?
}

?></table><?

if ($k_page > 1) {
  str('?id=' . $sexwars['id'] . '&amp;', $k_page, $page);
}
?>
<div class="foot">
  &laquo; <a href="index.php">Главная игры</a>
</div>
<?
include_once H.'sys/inc/tfoot.php';