<?php
require_once "functions.php";
$in_haos = mysql_fetch_array(mysql_query("SELECT * FROM `cit_haos_status` WHERE `id` = '{$user['id']}' LIMIT 1;"));
$wait_msg = "Ждем готовности всей группы...";
//rooms
$ch_rooms = [
    // 0 - empty
    "1" => "Ворота (1)",
    "2" => "Двор (2)",
    "3" => "Внешний корридор (3)",
    "4" => "Спуск в подвал (4)",
    "5" => "Подвал (5)",//босс Душа
    "6" => "Люк на Западную стену (6)",
    "7" => "Западная стена (7)",
    "8" => "Галерея Страха (8)",
    "9" => "Западная башня (9)",
    "10" => "Галерея Смерти (10)",//босс Зомби
    "11" => "Проход к Северной стене (11)",
    "12" => "Галерея Тьмы (12)",
    "13" => "Северная стена (13)",
    "14" => "Галерея Бликов (14)",
    "15" => "Внутренний корридор (15)",//босс Повелитель
    "16" => "Гостевая (16)",
    "17" => "Руины Северной башни (17)",
    "18" => "Поминальная комната (18)",
    "19" => "Галерея Порталов (19)",
    "20" => "Зал Посвященных (20)",//босс Хромой Билли
    "21" => "Старая лестница (21)",
    "22" => "Трофейная (22)",
    "23" => "Костяной зал (23)",
    "24" => "Склеп (24)",
    "25" => "Лабиринт (25)",//босс Мародер
    "26" => "Тронный зал (26)",
    "27" => "Тайный корридор (27)",
    "28" => "Комната прислуги (28)",
    "29" => "Королевские покои (29)",
    "30" => "Переход (30)"//босс Грохобот
];
//bots

$ch_bots = [];
//1 - упырь
//2 - падший
//3 - душа
$db = mysql_fetch_array(mysql_query("SELECT * FROM `cit_haos_var` WHERE `group`='" . $in_haos['group'] . "' limit 1; "));
if (!$db['bots']) {
    $bot_low = [
        // 0 - empty
        "1" => "Упырь",
        "2" => "Посланник смерти",
        "3" => "Падший",
        "4" => "Отморозок",
        "5" => "Проклятие глубин"
    ];
    for ($i = 1; $i <= 30; $i++) {
        $ch_get_bot = rand(1, 5);
        $ch_bots[$i] = ["0" => $bot_low[$ch_get_bot]];
    }
    $ch_bots[5] = ["0" => "Душа"];
    $ch_bots[10] = ["0" => "Зомби"];
    $ch_bots[15] = ["0" => "Повелитель"];
    $ch_bots[20] = ["0" => "Хромой Билли"];
    $ch_bots[25] = ["0" => "Мародер"];
    $ch_bots[30] = ["0" => "Грохобот"];
    $dbb = serialize($ch_bots);
    mysql_query("UPDATE `cit_haos_var` SET bots='" . $dbb . "'  WHERE `group`='" . $in_haos['group'] . "'; ");
} else {
    $ch_bots = unserialize($db['bots']);
}
// комната -  опыт == доблесть
$ch_priz = [
    "5" => [100, 1],
    "10" => [200, 2],
    "15" => [300, 3],
    "20" => [400, 4],
    "25" => [500, 5],
    "30" => [600, 10]
];
// комната - кирка == уник_7 == цветок == уник_8
$ch_drop = [
    "25" => [10, 60, 95, 100],
    "30" => [3, 6, 7, 8],
];
$priz_low =
    ["727"];
$priz_med =
    ["775", "776", "777", "778"];
$priz_flow =
    ["14"];
$priz_high =
    ["803", "804", "805", "806"];

/*$ch_bots[1]=array
(
"0"=>"Младший страж глубин",
"1"=>"Младший страж глубин",
"2"=>"Босс глубин"
);
$ch_bots[2]=array
(
"0"=>"Младший страж глубин",
"1"=>"Босс глубин"
);*/

if ($in_haos['status'] == 4) {
    mysql_query("UPDATE `users`,`online` SET `users`.`room` = '600',`online`.`room` = '600' WHERE `online`.`id` = `users`.`id` AND `online`.`id` = '{$_SESSION['uid']}' ;");
    mysql_query("UPDATE `cit_haos_status` SET room='0',bot='0',group='0' WHERE id = '{$user['id']}'; ");
    header('location: c_haos.php');
}
if (!$ch_rooms[$in_haos['room']]) {
    mysql_query("UPDATE `users`,`online` SET `users`.`room` = '600',`online`.`room` = '600' WHERE `online`.`id` = `users`.`id` AND `online`.`id` = '{$_SESSION['uid']}' ;");
    if ($in_haos['status'] == 2) {
        mysql_query("UPDATE `cit_haos_status` SET room='0',status='5',bot='0' WHERE id = '{$user['id']}'; ");
        addchp('Вы пробились до двери на 2 уровень подземелий Цитадели Хаоса. Только опытный воин и храбрый страж сможет пройти через нее (10 уровень, страж 2 уровня)', '{[]}' . Nick::id($user['id'])->short() . '{[]}');
    }
    mysql_query("UPDATE `cit_haos_var` SET bots='',players='' WHERE group='" . $in_haos['group'] . "'; ");
    header('location: c_haos.php');
}
\Battles\Template::header('c_haos_in');
?>
<script>
    function refreshPeriodic() {
        location.href = 'c_haos_in.php';//reload()
        timerID = setTimeout("refreshPeriodic()", 30000);
    }

    timerID = setTimeout("refreshPeriodic()", 30000);
</script>

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

    <tr>
        <td><h3>Цитадель Хаоса: <?= $ch_rooms[$in_haos['room']] ?><br/>
                <br/></td>
    </tr>

    <?php
    //attack
    if ($_POST['go_attack']) {
        if ($in_haos['status'] == 2) {
            $bot_name = $ch_bots[$in_haos['room']][$in_haos['bot']];
            switch ($bot_name) {
                case "Упырь":
                    $bot_id = 2897;
                    $bot_count = rand(10, 30);
                    break;
                case "Падший":
                    $bot_id = 2903;
                    $bot_count = rand(3, 9);
                    break;
                case "Посланник смерти":
                    $bot_id = 2896;
                    $bot_count = 2;
                    break;
                case "Отморозок":
                    $bot_id = 2893;
                    $bot_count = 3;
                    break;
                case "Проклятие глубин":
                    $bot_id = 2892;
                    $bot_count = rand(1, 5);
                    break;
                case "Душа":
                    $bot_id = 2895;
                    $bot_count = 1;
                    break;
                case "Зомби":
                    $bot_id = 2901;
                    $bot_count = 5;
                    break;
                case "Повелитель":
                    $bot_id = 2902;
                    $bot_count = 1;
                    break;
                case "Хромой Билли":
                    $bot_id = 2898;
                    $bot_count = 1;
                    break;
                case "Мародер":
                    $bot_id = 2899;
                    $bot_count = 1;
                    break;
                case "Грохобот":
                    $bot_id = 2900;
                    $bot_count = 1;
                    break;
            }
            $b_pers = mysql_fetch_array(mysql_query("SELECT * FROM users WHERE id='{$bot_id}' LIMIT 1;"));
            $bot_hp = $b_pers['maxhp'];
            $bots = [];
            $group_raw = mysql_query("SELECT * FROM `cit_haos_status` WHERE `group` = '{$in_haos['group']}' AND status='2';");
            while ($gr = mysql_fetch_array($group_raw)) {
                addchp('<font color=red>Внимание!</font> ' . $bot_name . ' напал на Вашу группу!', '{[]}' . Nick::id($gr['id'])->short() . '{[]}');
            }

            for ($bot_c = 0; $bot_c < $bot_count; $bot_c++) {
                $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 . "');");
                $bot = mysql_insert_id();
                $bots[] = $bot;
            }
            // командный вход
            $group_fight = [];
            $group_raw = mysql_query("SELECT * FROM `cit_haos_status` WHERE `group` = '{$in_haos['group']}' AND status='2';");
            while ($gr = mysql_fetch_array($group_raw)) {
                $group_fight[] = $gr['id'];
            }

            $teams = [];
            foreach ($bots as $b) {
                foreach ($group_fight as $gf) {
                    $teams[$gf][$b] = [0, 0, time()];
                    $teams[$b][$gf] = [0, 0, time()];
                    mysql_query("UPDATE `cit_haos_status` SET `status` = '3' WHERE `id` ='{$gf}'; ");
                }
            }

            mysql_query("INSERT INTO `battle`
        		(
        			`id`,`coment`,`teams`,`timeout`,`type`,`status`,`t1`,`t2`,`to1`,`to2`
        		)
        		VALUES
        		(
        			NULL,'','" . serialize($teams) . "','3','1','0','" . implode(";", $group_fight) . "','" . implode(";", $bots) . "','" . time() . "','" . time() . "'
        		)");

            $id = mysql_insert_id();

            // апдейтим бота
            foreach ($bots as $b) {
                mysql_query("UPDATE `bots` SET `battle` = {$id} WHERE `id` = {$b} LIMIT 1;");
            }

            foreach ($group_fight as $gf) {
                mysql_query("UPDATE users SET `battle` ={$id},`zayavka`=0 WHERE `id`= {$gf};");
            }
            exit("<script>location.href='fbattle.php';</script>");
        }
    }
    $group_num = mysql_num_rows(mysql_query("SELECT * FROM `cit_haos_status` WHERE `group` = '{$in_haos['group']}';"));
    $group_ready = mysql_num_rows(mysql_query("SELECT * FROM `cit_haos_status` WHERE (`room` = '{$in_haos['room']}' AND `group` = '{$in_haos['group']}');"));
    $cit_haos_t = mysql_fetch_array(mysql_query("SELECT * FROM `variables` WHERE `var` = 'cit_haos_time' LIMIT 1;"));
    $tm = time();
    if ($in_haos['status'] == 2) {
        if (($tm > ($cit_haos_t['value'] + 960)) || ($tm < ($cit_haos_t['value'] - 600)))//def 960
        {
            $flag_ref = 1;
            foreach ($ch_bots[$in_haos['room']] as $bot_id => $bot_name)
                if ($bot_id >= $in_haos['bot']) {
                    echo '<tr><td><FORM action="c_haos_in.php" method=POST>';
                    if ($bot_id == $in_haos['bot']) echo '<strong>' . $bot_name . '</strong>'; else echo($bot_name);
                    if ($bot_id == $in_haos['bot']) echo ' - <INPUT TYPE="submit" value="Напасть" name="go_attack">';
                    echo ' </FORM></td></tr>';
                    $flag_ref = 0;
                }
            if (!array_key_exists($in_haos['bot'], $ch_bots[$in_haos['room']])) {
                echo($wait_msg);
                //проверяем есть ли приз
                if (array_key_exists($in_haos['room'], $ch_priz)) {
                    $priz_exp = $ch_priz[$in_haos['room']][0];
                    $priz_dobl = $ch_priz[$in_haos['room']][1];
                } else {
                    $priz_exp = 0;
                    $priz_dobl = 0;
                }
                if (array_key_exists($in_haos['room'], $ch_drop)) {
                    $got_drop = rand(0, 400);//100 - norm, 400 - 25%
                } else {
                    $got_drop = -1;
                }
                //выбираем приз
                if ($in_haos['room'] < 30) {
                    if ($got_drop >= 0 && $got_drop < $ch_drop[$in_haos['room']][0]) {
                        $rand_k = array_rand($priz_low, 1);
                        $p_id = $priz_low[$rand_k];
                        $p_shop = "shop";
                    } elseif ($got_drop >= $ch_drop[$in_haos['room']][0] && $got_drop < $ch_drop[$in_haos['room']][1]) {
                        $rand_k = array_rand($priz_med, 1);
                        $p_id = $priz_med[$rand_k];
                        $p_shop = "shop";
                    } elseif ($got_drop >= $ch_drop[$in_haos['room']][1] && $got_drop < $ch_drop[$in_haos['room']][2]) {
                        $rand_k = array_rand($priz_flow, 1);
                        $p_id = $priz_flow[$rand_k];
                        $p_shop = "fshop";
                    } elseif ($got_drop >= $ch_drop[$in_haos['room']][2] && $got_drop <= $ch_drop[$in_haos['room']][3]) {
                        $rand_k = array_rand($priz_high, 1);
                        $p_id = $priz_high[$rand_k];
                        $p_shop = "shop";
                    }
                } elseif ($in_haos['room'] == 30) {
                    if ($got_drop <= 200)//400max/4=>50%
                    {
                        $priz_low =
                            ["808", "809"];

                        $rand_k = array_rand($priz_low, 1);
                        $p_id = $priz_low[$rand_k];
                        $p_shop = "shop";
                    }

                }

                //выбираем получателя
                $all_get = [];
                $gr_raw = mysql_query("SELECT * FROM `cit_haos_status` WHERE `group` = '{$in_haos['group']}';");
                while ($g_id = mysql_fetch_array($gr_raw)) {
                    $all_get[] = $g_id['id'];
                }
                $l_id = rand(0, count($all_get) - 1);
                //даем призы
                if ($p_id > 0) {
                    $dress = mysql_fetch_array(mysql_query("SELECT * FROM `{$p_shop}` WHERE `id` = '{$p_id}' LIMIT 1;"));
                    mysql_query("INSERT INTO `inventory`
				(`prototype`,`owner`,`name`,`type`,`massa`,`cost`,`img`,`maxdur`,`isrep`,
					`gsila`,`glovk`,`ginta`,`gintel`,`ghp`,`gnoj`,`gtopor`,`gdubina`,`gmech`,`gfire`,`gwater`,`gair`,`gearth`,`glight`,`ggray`,`gdark`,`needident`,`nsila`,`nlovk`,`ninta`,`nintel`,`nmudra`,`nvinos`,`nnoj`,`ntopor`,`ndubina`,`nmech`,`nfire`,`nwater`,`nair`,`nearth`,`nlight`,`ngray`,`ndark`,
					`mfkrit`,`mfakrit`,`mfuvorot`,`mfauvorot`,`bron1`,`bron2`,`bron3`,`bron4`,`maxu`,`minu`,`magic`,`nlevel`,`nalign`,`dategoden`,`goden`,`otdel`,`gmp`,`gmeshok`,`encicl`,`artefact`,`duration`,`present`
				)
				VALUES
				('{$dress['id']}','{$all_get[$l_id]}','{$dress['name']}','{$dress['type']}',{$dress['massa']},{$dress['cost']},'{$dress['img']}',{$dress['maxdur']},{$dress['isrep']},'{$dress['gsila']}','{$dress['glovk']}','{$dress['ginta']}','{$dress['gintel']}','{$dress['ghp']}','{$dress['gnoj']}','{$dress['gtopor']}','{$dress['gdubina']}','{$dress['gmech']}','{$dress['gfire']}','{$dress['gwater']}','{$dress['gair']}','{$dress['gearth']}','{$dress['glight']}','{$dress['ggray']}','{$dress['gdark']}','{$dress['needident']}','{$dress['nsila']}','{$dress['nlovk']}','{$dress['ninta']}','{$dress['nintel']}','{$dress['nmudra']}','{$dress['nvinos']}','{$dress['nnoj']}','{$dress['ntopor']}','{$dress['ndubina']}','{$dress['nmech']}','{$dress['nfire']}','{$dress['nwater']}','{$dress['nair']}','{$dress['nearth']}','{$dress['nlight']}','{$dress['ngray']}','{$dress['ndark']}',
				'{$dress['mfkrit']}','{$dress['mfakrit']}','{$dress['mfuvorot']}','{$dress['mfauvorot']}','{$dress['bron1']}','{$dress['bron3']}','{$dress['bron2']}','{$dress['bron4']}','{$dress['maxu']}','{$dress['minu']}','{$dress['magic']}','{$dress['nlevel']}','{$dress['nalign']}','" . (($dress['goden']) ? ($dress['goden'] * 24 * 60 * 60 + time()) : "") . "','{$dress['goden']}','{$dress['razdel']}','{$dress['gmp']}','{$dress['gmeshok']}','{$dress['encicl']}','{$dress['artefact']}','{$dur}','Мусорщик'
				) ;");
                    mysql_query("INSERT INTO `delo` (`id` , `author` ,`pers`, `text`, `type`, `date`) VALUES ('','0','$all_get[$l_id]','\"" . $user['login'] . "\" получил в ЦХ предмет: \"" . $dress['name'] . "\" " . $dresscount . "id:(" . $dressid . ") [0/" . $dress['maxdur'] . "]',1,'" . time() . "');");
                    addchp('За убийство босса Цитадели Хаоса вы получили ' . $dress['name'], '{[]}' . Nick::id($all_get[$l_id])->short() . '{[]}');
                }
                if ($priz_exp > 0) {
                    GiveExp($all_get[$l_id], $priz_exp);
                    addchp('За убийство босса Цитадели Хаоса вы получили ' . $priz_exp . ' опыта', '{[]}' . Nick::id($all_get[$l_id])->short() . '{[]}');
                    mysql_query("INSERT INTO `delo` (`id` , `author` ,`pers`, `text`, `type`, `date`) 
                        VALUES ('','0','{$cur_user['id']}','\"" . $all_get[$l_id] . "\" получил в ЦХ \"" . $priz_exp . "\" опыта',1,'" . time() . "');");
                }
                if ($priz_dobl > 0) {
                    mysql_query("UPDATE users SET `doblest`=`doblest`+'" . $priz_dobl . "' WHERE `id` = '" . $all_get[$l_id] . "';");
                    addchp('За убийство босса Цитадели Хаоса вы получили ' . $priz_dobl . ' доблести', '{[]}' . Nick::id($all_get[$l_id])->short() . '{[]}');
                    mysql_query("INSERT INTO `delo` (`id` , `author` ,`pers`, `text`, `type`, `date`) 
                        VALUES ('','0','{$cur_user['id']}','\"" . $all_get[$l_id] . "\" получил в ЦХ \"" . $priz_dobl . "\" доблести',1,'" . time() . "');");
                }
                mysql_query("UPDATE `cit_haos_status` SET `room` = `room`+1,`bot`=0 WHERE `group` = '{$in_haos['group']}'; ");
                if (!headers_sent()) {
                    header('location: c_haos_in.php');
                }
            }
            if ($flag_ref == 0 && !headers_sent()) {
                header('location: c_haos_in.php');
            }
        } else {
            echo "<TR><TD>Ждем готовности группы... Приготовьтесь!</TR></TD>";
            echo '<tr><td><FORM action="c_haos_in.php" method=POST><INPUT TYPE="submit" value="Обновить" name="refresh">';
            echo ' </FORM></td></tr>';
        }
    }
    ?>

</table>
<?php
echo '<div align=right><img width="260" src="i/zitadel/' . ($in_haos['room'] + 1) . '.jpg" /></div>';
?>