<?php
$us = mysql_fetch_array(mysql_query("SELECT *, (SELECT `id` FROM `online` WHERE `real_time` >= ".(time()-60)." AND `id` = `users`.`id`) AS `online` FROM `users` WHERE `login` = '".mysql_real_escape_string($_POST['target'])."' LIMIT 1"));

$owntravma = mysql_fetch_array(mysql_query("SELECT `id` FROM `effects` WHERE `owner` = ".$us['id']." AND (`type` = 13 OR `type` = 12 OR `type` = 14) LIMIT 1"));
$us_b = mysql_fetch_array(mysql_query("SELECT `type`, `open` FROM `battle` WHERE `id` = '{$us['battle']}' LIMIT 1"));
$vip = mysql_fetch_array(mysql_query('SELECT `id`, `uid`, `pers_attack` FROM `abils_vip` WHERE `uid` = "'.$user['id'].'" LIMIT 1'));
if($user['invis'] == 1) { $lo = '<i><b>невидимка</b></i>'; } else { $lo = $user['login']; }
$los = Nick::id($user['id'])->short();

if($vip['pers_attack'] <= 0) {
  echo "Магия исчерпала себя ...";
} elseif($user['battle'] > 0) {
  echo "Не в бою...";
} elseif($us_b['type'] == 3 || $us_b['type'] == 5) {
  echo "Запрещено входить в хаотический бой!";
} elseif($us['battle'] > 0 && $us_b['open'] == 0) {
  echo "Бой закрыт для вмешательства!";
} elseif(!$us['online']) {
  echo "Персонаж не в игре!";
} elseif($us['align'] == 2.99) {
  echo "Не атакуйте Администратора!";
} elseif($user['zayavka'] > 0) {
  echo "Вы ожидаете поединка...";
} elseif($owntravma['id'] && !$us['battle']) {
  echo "Персонаж тяжело травмирован...";
} elseif($user['klan'] != '' && ($user['klan'] == $us['klan'])) {
  echo "Чтите честь ваших сокланов.";
} elseif($user->getRoom() != $us['room']) {
  echo "Персонаж в другой комнате!";
} elseif ($us['room'] == 31 || $us['room'] == 46 || $us['room'] == 47 || $us['room'] == 48 || $us['room'] == 49 ||$us['room'] == 600 || $us['room'] == 601 || $us['room'] == 45 || $us['room'] == 602 || $us['room'] == 43 || $us['room'] == 45) {
  echo "Нападения в этой локации запрещены!";
} elseif($us['align'] == 2.9) {
	echo "Нападение на Представителя Высшего Совета строго запрещено!";
} elseif($us['align'] > 1 && $us['align'] < 2) {
  echo "Нападение на Законников запрещено!";
} elseif($us['align'] == 4.99) {
  echo "Нападение на Комментатора запрещено!";
} elseif($us['level'] < 1) {
  echo "Новички находятся под защитой Мироздателя!";
} elseif($us['hp'] < $us['maxhp']*0.33  && !$us['battle']) {
  echo "Жертва слишком слаба!";
} elseif($user['hp'] < $user['maxhp']*0.33) {
  echo "Вы слишком ослаблены для нападения!";
} elseif($us['hp'] < 1  && $us['battle']) {
  echo "Вы не можете напасть на погибшего!";
} else {
  if($user['sex'] == 1) { $action = "напал"; } else { $action = "напала"; }
  if($user['align'] > '2' && $user['align'] < '3') { $angel = "Служитель закона"; } elseif ($user['align'] > '1' && $user['align'] < '2') { $angel = "Персонаж"; }

  $jert = mysql_fetch_array(mysql_query("SELECT * FROM `users` WHERE `login` = '".mysql_real_escape_string($_POST['target'])."' LIMIT 1"));
  if($jert['id'] != $user['id']) {
	addch("<img src=i/magic/attackb.gif> <B>{$lo}</B>, применив магию кровавого нападения, внезапно ".$action." на &quot;{$_POST['target']}&quot;");
    addchp('<font color=red>Внимание!</font> На вас '.$action.' <b>'.$lo.'</b>.<br />\'; top.frames[\'main\'].location=\'fbattle.php\'; var z = \'   ', '{[]}'.Nick::id($jert['id'])->short().'{[]}');

	if($jert['id'] > _BOTSEPARATOR_) {
	  $arha = mysql_fetch_array(mysql_query('SELECT * FROM `bots` WHERE `prototype` = '.$jert['id'].' LIMIT 1'));
	  $jert['battle'] = $arha['battle'];
	  $jert['id'] = $arha['id'];
	  $bot = 1;
	}

    if($jert['battle'] > 0) {
	  $bd = mysql_fetch_array(mysql_query('SELECT * FROM `battle` WHERE `id` = '.$jert['battle'].' LIMIT 1'));
	  $battle = unserialize($bd['teams']);
	  $ak = array_keys($battle[$jert['id']]);
	  $battle[$user['id']] = $battle[$ak[0]];
	  foreach($battle[$user['id']] as $k => $v) {
		$battle[$user['id']][$k] = array(0, 0, time());
		$battle[$k][$user['id']] = array(0, 0, time());
	  }

      $t1 = explode(";", $bd['t1']);
	  if(in_array($jert['id'], $t1)) {
		$ttt = 2;
	  } else {
		$ttt = 1;
	  }

      addch("<b>".$los."</b> вмешался в <a href=logs.php?log=".$id." target=_blank>поединок »»</a>.", $user->getRoom());
      if($user['invis'] == 1) { $lod = '<i><b>невидимка</b></i>'; } else { $lod = Nick::id($user['id'])->short(); }
      addlog($jert['battle'], '<span class=date>'.date("H:i").'</span> '.$lod.' вмешался в поединок!<BR>');
      mysql_query('UPDATE `battle` SET `teams` = \''.serialize($battle).'\', `t'.$ttt.'` = CONCAT(`t'.$ttt.'`,\';'.$user['id'].'\'), `blood` = 1 WHERE `id` = "'.$jert['battle'].'" LIMIT 1');
	  mysql_query("UPDATE `users` SET `battle` = ".$jert['battle'].", `zayavka` = 0 WHERE `id` = '".$user['id']."' LIMIT 1");
      header("Location:fbattle.php");
	} else {
	  if($jert['zayavka']) {
		$fict1 = mysql_fetch_array(mysql_query("SELECT * FROM `zayavka` WHERE `team1` LIKE '{$jert['id']};%' OR `team1` LIKE '%;{$jert['id']};%' LIMIT 1"));
		$fict2 = mysql_fetch_array(mysql_query("SELECT * FROM `zayavka` WHERE `team2` LIKE '{$jert['id']};%' OR `team2` LIKE '%;{$jert['id']};%' LIMIT 1"));
		if($fict1) { $team = 1; } elseif($fict2) { $team = 2; }
		mysql_query("UPDATE `users` SET `zayavka` = '' WHERE `id` = {$jert['id']} LIMIT 1");
		$z = mysql_fetch_array(mysql_query("SELECT `team{$team}` FROM `zayavka` WHERE `id` = '".$jert['zayavka']."' LIMIT 1"));
        $teams = str_replace($jert['id'].";", "", $z[0]);
		mysql_query("UPDATE  `zayavka` SET `team{$team}` = '{$teams}' WHERE	`id` = {$jert['zayavka']} LIMIT 1");
	  }

	  if($bot) {
		mysql_query("INSERT INTO `bots` (`name`, `prototype`, `battle`, `hp`) values ('Архивариус', '83', '', '".$jert['hp']."')");
		$jert['id'] = mysql_insert_id();
	  }

	  $teams = array();
	  $teams[$user['id']][$jert['id']] = array(0, 0, time());
	  $teams[$jert['id']][$user['id']] = array(0, 0, time());
	  $sv = array(3, 4, 5);

	  mysql_query("INSERT INTO `battle` (`teams`, `timeout`, `type`, `status`, `t1`, `t2`, `to1`, `to2`, `blood`) VALUES ('".serialize($teams)."', '".$sv[rand(0, 2)]."', '1', '0', '".$user['id']."', '".$jert['id']."', '".time()."', '".time()."', '1')");
	  $id = mysql_insert_id();

	  if($bot) {
		mysql_query("UPDATE `bots` SET `battle` = {$id} WHERE `id` = {$jert['id']} LIMIT 1");
	  } else {
		mysql_query("UPDATE `users` SET `battle` = {$id} WHERE `id` = {$jert['id']} LIMIT 1");
	  }

      $ld = Nick::id($user['id'])->full(1);
      $lds = Nick::id($user['id'])->short();
      $rr = "<b>".$ld."</b> и <b>".Nick::id($jert['id'])->full(1)."</b>";
	  addch("<a href=logs.php?log=".$id." target=_blank>Бой</a> между <b>".$lds."</b> и <b>".Nick::id($jert['id'])->short()."</b> начался.", $user->getRoom());
      addlog($id, "Часы показывали <span class=date>".date("Y.m.d H.i")."</span>, когда ".$rr." бросили вызов друг другу. <BR>");
      mysql_query("UPDATE users SET `battle` ={$id},`zayavka`=0 WHERE `id`= {$user['id']} OR `id` = {$jert['id']}");
	  header("Location: fbattle.php");
	}
    $vip['pers_attack'] -= 1;
    mysql_query('UPDATE `abils_vip` SET `pers_attack` = "'.$vip['pers_attack'].'" WHERE `id` = "'.$vip['id'].'" LIMIT 1');

  } else {
	echo '<font color=red>Мазохист?...</font>';
  }

}