<?php

    session_start();
	if (!($_SESSION['uid'] >0)) header("Location: index.php");
    
	include "config.php";
    
    $user = mysql_fetch_array(mysql_query("SELECT * FROM `users` WHERE `id` = '{$_SESSION['uid']}' LIMIT 1;"));
    $owntravma = mysql_fetch_array(mysql_query("SELECT * FROM `effects` WHERE `owner` = ".$user['id']." AND (type=13 OR type=12 OR  type=14) limit 1;"));
	$klan = mysql_fetch_array(mysql_query("SELECT * FROM `clans` WHERE `id` = '{$user['klan']}' LIMIT 1;"));
    
	include "functions.php";
    if ($user['room'] != 45) { header("Location: main.php");  die(); }
	if ($user['battle'] != 0) { header('location: fbattle.php'); die(); }
    
    $cc_date=mysql_fetch_array(mysql_query("SELECT * FROM `variables` WHERE `var`='cc_time' LIMIT 1;"));
    $ccd=$cc_date['value'];
    
    if($_POST['admin_start'])
    {
        $tm=time();
        mysql_query("UPDATE `variables` SET `value`='{$tm}' WHERE `var`='cc_time';");
        die("<script>location.href='clan_castle.php';</script>");
    }
    if($_POST['admin_start1'])
    {
        $tm=time()-900;
        mysql_query("UPDATE `variables` SET `value`='{$tm}' WHERE `var`='cc_time';");
        die("<script>location.href='clan_castle.php';</script>");
    }
    
    if($_POST['add_zay'])
    {
        mysql_query("INSERT INTO `clan_castle` VALUES ('{$user['id']}','{$user['klan']}');");
        die("<script>location.href='clan_castle.php';</script>");
    }
    
    ?>
    <HTML><HEAD>
    <!-- JS -->
    <script>
			function refreshPeriodic()
			{
				location.href='clan_castle.php';
				timerID=setTimeout("refreshPeriodic()",30000);
			}
			timerID=setTimeout("refreshPeriodic()",30000);
		</script>
    
<link rel=stylesheet type="text/css" href="css/main.css">
<meta content="text/html; charset=utf-8" http-equiv=Content-type>
<META Http-Equiv=Cache-Control Content=no-cache>
<meta http-equiv=PRAGMA content=NO-CACHE>
<META Http-Equiv=Expires Content=0>

</HEAD>
<body leftmargin=5 topmargin=5 marginwidth=5 marginheight=5 bgcolor=#d4d4d4>

    <TABLE border=0 width=600 cellspacing="0" cellpadding="0" align=left>

<tr><td><h3>Замок Мэра</td></tr>
<tr><td><FORM action="city.php" method=GET><INPUT TYPE="submit" value="Вернуться в Город" name="bps"></FORM></td></tr>
<tr><td>Добро пожаловать в Замок доброго и справедливого Мэра!
Если Вы заинтерисованы в обладании правами на Замок, либо считаете что обладаете достаточными способностями для исполнения
обязанностей Мэра, приглашаем Вас и Ваших единомышлеников поселиться в Замке!  <br/> <br/>
Внимание! Администрация не несет ответственности за возможные конфликты на основе спора о правах обладания Замком, 
целость и сохранность Ваших личных вещей, здоровье и жизни посетителей!<br/>
<?php
$own=mysql_fetch_array(mysql_query("SELECT `value` FROM `variables` WHERE `var` = 'castle_owner' LIMIT 1;"));
if($own['value']>0) $tmp_k=mysql_fetch_array(mysql_query("SELECT `name` FROM `clans` WHERE `id` = '{$own['value']}' LIMIT 1;"));
echo('<br />Над Замком развевается флаг ');
if($tmp_k['name']) 
    echo('<strong>клана <img title="'.$tmp_k['name'].'" src="i/klan/'.$tmp_k['name'].'.gif">'.$tmp_k['name'].'</strong><br />');
else
    echo('<strong>сил Хаоса</strong><br />');

if($user['align']==2.99) echo('<FORM action="clan_castle.php" method=POST><INPUT TYPE="submit" value="Админ: запустить" name="admin_start"><br></FORM>');
if($user['align']==2.99) echo('<FORM action="clan_castle.php" method=POST><INPUT TYPE="submit" value="Админ: старт боя" name="admin_start1"><br></FORM>');
if($ccd>=time())
{
    echo("Следующая битва: ".(date("j.m",$ccd))." в ".(date("H:i",$ccd)));
    
}
elseif($ccd<time() && ($ccd+900)>=time())
{
    $zays=array();
   echo("Заявили права на Замок Мэра:");
   echo('<TABLE border=0 width=100% cellspacing="0" cellpadding="0" align=left>');
   $all_c=mysql_query("SELECT * FROM `clan_castle`;");
    while ($a_zay=mysql_fetch_array($all_c))
       {
            $zays[]=$a_zay['clan'];
            $tmp_k=mysql_fetch_array(mysql_query("SELECT `name` FROM `clans` WHERE `id` = '{$a_zay['clan']}' LIMIT 1;"));
            echo '<tr><td><strong>Клан <img title="'.$tmp_k['name'].'" src="i/klan/'.$tmp_k['name'].'.gif">'.$tmp_k['name'].'</strong></td></tr>';
       }
       if(empty($zays))
        echo '<tr><td><strong>Ждем смелых ...</strong></td></tr>';
    echo('</TABLE>');
     echo("<br/>Прием заявок до: <strong>".(date("H:i",$ccd+900))."</strong>");
    
    $own=mysql_fetch_array(mysql_query("SELECT `value` FROM `variables` WHERE `var` = 'castle_owner' LIMIT 1;"));
    
    if ($klan['glava']==$user['id'] && !in_array($user['klan'],$zays) && $user['klan']!=$own['value'])
    {
        echo("<br />Прием заявок от глав кланов:");    
        echo '<tr><td><FORM action="clan_castle.php" method=POST><INPUT TYPE="submit" value="Заявиться" name="add_zay"></FORM></td></tr>';
    }
        
}
elseif(($ccd+900)<time() && ($ccd+90+900)>=time())
{
        $zays=array();
        $all_zay=mysql_query("SELECT * FROM `clan_castle`;");
        while ($a_zay=mysql_fetch_array($all_zay))
        {
            $cur_c=mysql_num_rows(mysql_query("SELECT * FROM `users` WHERE `klan`='{$a_zay['clan']}' AND `room`='45';"));
            for($cc=0;$cc<$cur_c;$cc++)
                $zays[]=$a_zay['clan'];
        }
            $own=mysql_fetch_array(mysql_query("SELECT `value` FROM `variables` WHERE `var` = 'castle_owner' LIMIT 1;"));
            shuffle($zays);
            $lucky=$zays[array_rand($zays)];
            if($lucky>0 && $lucky!=$own['vlaue']);
            mysql_query("UPDATE `variables` SET `value`='{$lucky}' WHERE `var`='castle_att';");
            $tmp_k=mysql_fetch_array(mysql_query("SELECT `name` FROM `clans` WHERE `id` = '{$lucky}' LIMIT 1;"));
            
            if($own['value']>0)
                $tmp_o=mysql_fetch_array(mysql_query("SELECT `name` FROM `clans` WHERE `id` = '{$own['value']}' LIMIT 1;"));
       
   if($tmp_k) echo('Внимание!<img title="'.$tmp_k['name'].'" src="i/klan/'.$tmp_k['name'].'.gif"><strong>'.$tmp_k['name'].'</strong> собираются штурмовать замок');
   if($tmp_k && $own['value']>0) echo('<img title="'.$tmp_o['name'].'" src="i/klan/'.$tmp_o['name'].'.gif"><strong>'.$tmp_o['name'].'</strong>!');
   if($tmp_k && !$own['value']>0) echo('!');
}
elseif(($ccd+90+900)<=time())
{
    $att=mysql_fetch_array(mysql_query("SELECT `value` FROM `variables` WHERE `var` = 'castle_att' LIMIT 1;"));
    $own=mysql_fetch_array(mysql_query("SELECT `value` FROM `variables` WHERE `var` = 'castle_owner' LIMIT 1;"));
    
    $at_t=array();
    $ow_t=array();
    
    if($att['value']>0)
    {
        $att_r=mysql_query("SELECT `id` FROM `users` WHERE `klan`='{$att['value']}' AND `room`='45';");
        while($a=mysql_fetch_array($att_r))
        {
       	    $at_on = mysql_fetch_array(mysql_query("select `id` from `online` WHERE `date` >= ".(time()-60)." AND `id` = '{$a['id']}' LIMIT 1;"));
            if($at_on[0])
                $at_t[]=$a['id'];
        }
             
        
    }
            
    if($own['value']>0)
    {
        $def_r=mysql_query("SELECT `id` FROM `users` WHERE `klan`='{$own['value']}' AND `room`='45';");
        while($o=mysql_fetch_array($def_r))
        {
            $df_on = mysql_fetch_array(mysql_query("select `id` from `online` WHERE `date` >= ".(time()-60)." AND `id` = '{$o['id']}' LIMIT 1;"));
            if($df_on[0])
                $ow_t[]=$o['id']; 
        }
               
    }
    
    if(empty($at_t)) 
    {
        echo("Смелых так и не нашлось...<br/>");
    }
    elseif(empty($ow_t) && ($own['value']>0))
    {
        echo("Хозяева слили замок без боя...<br/>");
        $cc_own=mysql_fetch_array(mysql_query("SELECT `value` FROM variables WHERE var='castle_owner' LIMIT 1;"));
        $cc_k=mysql_fetch_array(mysql_query("SELECT `name` FROM `clans` WHERE `id` = '{$cc_own['value']}' LIMIT 1;"));
        $cc_att=mysql_fetch_array(mysql_query("SELECT `value` FROM variables WHERE var='castle_att' LIMIT 1;"));
        $cc_a=mysql_fetch_array(mysql_query("SELECT `name` FROM `clans` WHERE `id` = '{$cc_att['value']}' LIMIT 1;"));
        {AddChatSystem('<font color=red><strong>Клан <img title="'.$cc_a['name'].'" src="i/klan/'.$cc_a['name'].'.gif">'.$cc_a['name'].'</strong> без боя забрал у <strong>клана <img title="'.$cc_k['name'].'" src="i/klan/'.$cc_k['name'].'.gif">'.$cc_k['name'].'</strong> Замок Мэра</font>');}
         
         $c_prev=mysql_fetch_array(mysql_query("SELECT `glava`,`align` FROM `clans` WHERE `id`='{$own['value']}' LIMIT 1;"));
            mysql_query("UPDATE `users` SET `align`='{$c_prev['align']}',`abil`='' WHERE `id`='{$c_prev['glava']}';");
            
        mysql_query("UPDATE `variables` SET `value`='{$att['value']}' WHERE `var`='castle_owner';");
        mysql_query("UPDATE `variables` SET `value`='0' WHERE `var`='castle_att';");
        mysql_query("UPDATE `variables` SET `value`='{$tm}' WHERE `var`='cc_time';");
        
        $c_lead=mysql_fetch_array(mysql_query("SELECT `glava` FROM `clans` WHERE `id`='{$att['value']}' LIMIT 1;"));
	$abil=array();
	for($i=0;$i<10;$i++) $abil[$i]=9;
            mysql_query("UPDATE `users` SET `align`='7.97',`abil`='".serialize($abil)."' WHERE `id`='{$c_lead['glava']}';");
            
       
                        
        mysql_query("DELETE FROM `clan_castle`");
    }
    elseif($own['value']==0)
    {
        //побоище против ботов
        //ставим ботов
        $bots_raw=array
        ("2897","2897","2897","2897","2897","2897","2897","2897","2897","2897","4150","4150","4156","4156","4156","4156",
        "2895","2895","4158","4158","4158","4158","4158","2900");
        $bots=array();
        foreach($bots_raw as $bot_id)
            if($bot_id>0)
            {
                $b_pers=mysql_fetch_array(mysql_query("SELECT `login`,`maxhp` FROM users WHERE id='{$bot_id}' LIMIT 1;"));
                $bot_hp=$b_pers['maxhp'];
                $bot_name=$b_pers['login'];
                $nb = mysql_fetch_array(mysql_query("SELECT count(`id`) FROM `bots` WHERE `name` LIKE '".$bot_name."%';"));
            	mysql_query("INSERT INTO `bots` (`name`,`prototype`,`battle`,`hp`) values ('".$bot_name." ".($nb[0]+1)."','".$bot_id."','','".$bot_hp."');");
                $bots[]=mysql_insert_id();
            }
            
        //отаке!    
        
        $teams = array();
            foreach($at_t as $b)
                foreach($bots as $gf)
                {
                	$teams[$gf][$b] = array(0,0,time());
                	$teams[$b][$gf] = array(0,0,time());
                }
                
				mysql_query("INSERT INTO `battle`
						(
							`id`,`coment`,`teams`,`timeout`,`type`,`status`,`t1`,`t2`,`to1`,`to2`,`blood`
						)
						VALUES
						(
							NULL,'','".serialize($teams)."','3','1','0','".implode(";",$at_t)."','".implode(";",$bots)."','".time()."','".time()."','0'
						)");
                        
				$id = mysql_insert_id();
				// создаем лог
				$rr = "<b>";
                
				foreach( $at_t as $k=>$v ) {				    
					if ($k!=0) { $rr.=", "; $rrc.=", "; }
					$rr .= nick::id($v)->full(1);
					$rrc .= nick::id($v)->short();    
					addchp ('<font color=red>Внимание!</font> Ваш бой начался!<BR>\'; top.frames[\'main\'].location=\'fbattle.php\'; var z = \'   ','{[]}'.nick::id($v)->short().'{[]}');
                }
				$rr .= "</b> и <b>"; $rrc .= "</b> и <b>";
				foreach( $bots as $k=>$v ) {
					if ($k!=0) { $rr.=", "; $rrc.=", ";}
					$rr .= nick::id($v)->full(1);
					$rrc .= nick::id($v)->short();
                     }
				$rr .= "</b>";
                addch ("<a href=logs.php?log=".$id." target=_blank>Поединок</a> между <B>".$rrc."</B> начался.   ",$user['room']);
				mysql_query("INSERT INTO `logs` (`id`,`log`) VALUES('{$id}','Часы показывали <span class=date>".date("Y.m.d H.i")."</span>, когда ".$rr." бросили вызов друг другу. <BR>');");

				addlog($id,"Часы показывали <span class=date>".date("Y.m.d H.i")."</span>, когда ".$rr." бросили вызов друг другу. <BR>");
                $add_time=time();
				// всех в БОЙ!!!
				foreach($at_t as $k=>$v) {
					mysql_query("UPDATE users SET `battle` ={$id},`zayavka`=0 WHERE `id`= {$v}");
				}
				foreach($bots as $k=>$v) {
					mysql_query("UPDATE `bots` SET `battle` ={$id} WHERE `id`= {$v}");
				}
    mysql_query("DELETE FROM `clan_castle`");
    }
    elseif(!empty($at_t) && !empty($ow_t))
    {
        //побоище
        
        $teams = array();
            foreach($at_t as $b)
                foreach($ow_t as $gf)
                {
                	$teams[$gf][$b] = array(0,0,time());
                	$teams[$b][$gf] = array(0,0,time());
                }
                
				mysql_query("INSERT INTO `battle`
						(
							`id`,`coment`,`teams`,`timeout`,`type`,`status`,`t1`,`t2`,`to1`,`to2`,`blood`
						)
						VALUES
						(
							NULL,'','".serialize($teams)."','3','1','0','".implode(";",$at_t)."','".implode(";",$ow_t)."','".time()."','".time()."','0'
						)");
                        
				$id = mysql_insert_id();
				// создаем лог
				$rr = "<b>";
                
				foreach( $at_t as $k=>$v ) {				    
					if ($k!=0) { $rr.=", "; $rrc.=", "; }
					$rr .= nick::id($v)->full(1);
					$rrc .= nick::id($v)->short();    
					addchp ('<font color=red>Внимание!</font> Ваш бой начался!<BR>\'; top.frames[\'main\'].location=\'fbattle.php\'; var z = \'   ','{[]}'.nick::id($v)->short().'{[]}');
                }
				$rr .= "</b> и <b>"; $rrc .= "</b> и <b>";
				foreach( $ow_t as $k=>$v ) {
					if ($k!=0) { $rr.=", "; $rrc.=", ";}
					$rr .= nick::id($v)->full(1);
					$rrc .= nick::id($v)->short();
					addchp ('<font color=red>Внимание!</font> Ваш бой начался!<BR>\'; top.frames[\'main\'].location=\'fbattle.php\'; var z = \'   ','{[]}'.nick::id($v)->short().'{[]}');
                }
				$rr .= "</b>";
                addch ("<a href=logs.php?log=".$id." target=_blank>Поединок</a> между <B>".$rrc."</B> начался.   ",$user['room']);
				mysql_query("INSERT INTO `logs` (`id`,`log`) VALUES('{$id}','Часы показывали <span class=date>".date("Y.m.d H.i")."</span>, когда ".$rr." бросили вызов друг другу. <BR>');");

				addlog($id,"Часы показывали <span class=date>".date("Y.m.d H.i")."</span>, когда ".$rr." бросили вызов друг другу. <BR>");
                $add_time=time();
				// всех в БОЙ!!!
				foreach($at_t as $k=>$v) {
					mysql_query("UPDATE users SET `battle` ={$id},`zayavka`=0 WHERE `id`= {$v}");
				}
				foreach($ow_t as $k=>$v) {
					mysql_query("UPDATE users SET `battle` ={$id},`zayavka`=0 WHERE `id`= {$v}");
				}	
                mysql_query("DELETE FROM `clan_castle`");
    }
    $tm=time()+23*60*60;
    mysql_query("UPDATE `variables` SET `value`='0' WHERE `var`='castle_att';");
    mysql_query("UPDATE `variables` SET `value`='{$tm}' WHERE `var`='cc_time';");
    mysql_query("DELETE FROM `clan_castle`");
}
?>
</td></tr>
</table>
<div align=right><img width="260" src="i/zamok/4.jpg" /></div>

</BODY>
</HTML>