<?php
session_start();
if (empty($_SESSION['uid'])) {
    header("Location: index.php");
    exit;
}
include "functions.php";
if ($user->room != 600) {
    header("Location: main.php");
    exit;
}
if ($user->battle) {
    header('location: fbattle.php');
    exit;
}

$in_haos = mysql_fetch_array(mysql_query("SELECT * FROM `cit_haos_status` WHERE `id` = '{$user['id']}';"));
$owntravma = mysql_fetch_array(mysql_query("SELECT * FROM `effects` WHERE `owner` = " . $user['id'] . " AND (type=13 OR type=12 OR type=14) limit 1;"));
$wait_msg = "Ждем подтверждения от всей группы...";

/** Генерация случайного пароля через хэш случайной строки.
 *
 * @return string
 */
function getPass():string
{
    return hash('crc32', mt_rand());
}

if (!$in_haos) {
    mysql_query("INSERT INTO cit_haos_status(id) values('{$user['id']}');");
    $in_haos = mysql_fetch_array(mysql_query("SELECT * FROM `cit_haos_status` WHERE `id` = '{$user['id']}' LIMIT 1;"));
}

$pass_s = getPass();

if ($_POST['pay']) {
    if (!$_POST['pay_gr']) $_POST['pay_gr'] = 1;
    $group_num = mysql_num_rows(mysql_query("SELECT * FROM `cit_haos_status` WHERE `group` = '{$_POST['pay_gr']}';"));
    $cit_haos_pl = mysql_fetch_array(mysql_query("SELECT * FROM `cit_haos_var` WHERE `group`='" . $_POST['pay_gr'] . "' LIMIT 1;"));
    $gps = $_POST['gr_pass_in' . $_POST['pay_gr']];
    if ($gps)
        $gps = str_replace(" ", "", $gps);

    if ($group_num < 4)
        if ($user['hp'] >= (int)($user['maxhp'] / 3) && !$owntravma[0])
            if ($user['money'] >= 20)
                if (
                    !preg_match('/[\/\:*?"<>|+%]/', $gps) &&
                    (
                        ($gps == $cit_haos_pl['password'] && strlen($cit_haos_pl['password']) > 1) ||
                        (strlen($cit_haos_pl['players']) < 3)
                    )
                ) {

                    mysql_query("UPDATE `cit_haos_status` SET `status` = '1',`group` = '{$_POST['pay_gr']}' WHERE `id` ='{$user['id']}'; ");
                    mysql_query("UPDATE `users` set `money` = `money`- '20' WHERE id = '{$user['id']}';");
                    $cit_haos_gr = mysql_num_rows(mysql_query("SELECT * FROM `cit_haos_var`;"));

                    if ($_POST['pay_gr'] > $cit_haos_gr)
                        mysql_query("INSERT INTO `cit_haos_var`(`group`,`password`) values('" . $_POST['pay_gr'] . "','" . $pass_s . "');");
                    $cit_haos_pl = mysql_fetch_array(mysql_query("SELECT * FROM `cit_haos_var` WHERE `group`='" . $_POST['pay_gr'] . "' LIMIT 1;"));
                    if (!in_array($user['id'], explode(";", $cit_haos_pl['players']))) {

                        if ($cit_haos_pl['players'] != '')
                            $ch_pl_t = $cit_haos_pl['players'] . ";" . $user['id'];
                        else
                            $ch_pl_t = $user['id'];
                        mysql_query("UPDATE `cit_haos_var` SET `players`='{$ch_pl_t}' WHERE `group`='" . $_POST['pay_gr'] . "';");
                    }
                } else ($pass_in_err = "Неверный пароль!");

            else ($pay_err = "Недостаточно денег для подачи стартового взноса!");
        else ($pay_err = "Вы слишком ослаблены либо травмированы! ");
    else ($pay_err = "Группа уже набрана!");
}
if ($_POST['adm_start_raid'] && $user['id'] == 1256) {
    mysql_query("DELETE FROM `cit_haos_status`;");
    mysql_query("DELETE FROM `cit_haos_var`;");
    AddChatSystem('<font color=red>Начинается прием заявок в рейд на Цитадель Хаоса! Начало рейда через 15 минут.</font>');
    $ch_time = time();
    mysql_query("UPDATE variables SET value='{$ch_time}' where var='cit_haos_time';");
}
if ($_POST['test_start_raid'] && $user['id'] == 1256) {
    mysql_query("DELETE FROM `cit_haos_status`;");
    mysql_query("DELETE FROM `cit_haos_var`;");
    // AddChatSystem('<font color=red>Начинается прием заявок в рейд на Цитадель Хаоса! Начало рейда через 15 минут.</font>');
    $ch_time = time();
    mysql_query("UPDATE variables SET value='{$ch_time}' where var='cit_haos_time';");
}
if ($in_haos['room'] != 0 && $in_haos['status'] == 2) {
    mysql_query("UPDATE `users`,`online` SET `users`.`room` = '601',`online`.`room` = '601' WHERE `online`.`id` = `users`.`id` AND `online`.`id` = '{$_SESSION['uid']}' ;");
    header('location: c_haos_in.php');

}
if ($in_haos['status'] == 2) {
    $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 (`status` = '2' AND `group` = '{$in_haos['group']}');"));
    if ($group_num == $group_ready && $group_ready > 0) {
        mysql_query("UPDATE `users`,`online` SET `users`.`room` = '601',`online`.`room` = '601' WHERE `online`.`id` = `users`.`id` AND `online`.`id` = '{$_SESSION['uid']}' ;");
        mysql_query("UPDATE `cit_haos_status` SET room='1' WHERE id = '{$user['id']}'; ");
        header('location: c_haos_in.php');
    }
}
$in_haos = mysql_fetch_array(mysql_query("SELECT * FROM `cit_haos_status` WHERE `id` = '{$user['id']}' LIMIT 1;"));
\Battles\Template::header('Цитадель Хаоса');
?>
<!-- JS -->
<script>
    function refreshPeriodic() {
        location.href = 'c_haos.php';//reload()
        timerID = setTimeout("refreshPeriodic()", 30000);
    }

    timerID = setTimeout("refreshPeriodic()", 30000);
</script>
<TABLE border=0 width=600 cellspacing="0" cellpadding="0" align=left>

    <tr>
        <td><h3>Цитадель Хаоса</td>
    </tr>
    <?php
    $tm = time();
    $cit_haos_t = mysql_fetch_array(mysql_query("SELECT * FROM `variables` WHERE `var` = 'cit_haos_time' LIMIT 1;"));
    if ($tm < $cit_haos_t['value'] || $tm > ($cit_haos_t['value'] + 900))//def 900
    {
        $tob_all = [];
        mysql_query("DELETE FROM `cit_haos_var` WHERE CHAR_LENGTH(players)<3;");

        if ($in_haos['status'] == 1) {
            $dbb = mysql_query("SELECT * FROM `cit_haos_var`;");
            while ($ch_tob = mysql_fetch_array($dbb)) {
                if (!in_array($ch_tob['players'], $tob_all)) {
                    $tob_all = $tob_all . ";" . $ch_tob['players'];
                }
            }
            foreach (explode(";", $tob_all) as $tob) {
                mysql_query("UPDATE `cit_haos_status` SET status='2' WHERE id = '{$tob}'; ");
            }
        }
        $tm = time();
        $test_tm = time() + 900;
        $show_tm = $cit_haos_t['value'] + 0.5 * 24 * 60 * 60;
        switch (date("N", $show_tm)) {
            default:
            case 1:
                $d_o = "в понедельник";
                break;
            case 2:
                $d_o = "во вторник";
                break;
            case 3:
                $d_o = "в среду";
                break;
            case 4:
                $d_o = "в четверг";
                break;
            case 5:
                $d_o = "в пятницу";
                break;
            case 6:
                $d_o = "в субботу";
                break;
            case 7:
                $d_o = "в воскресение";
                break;
        }
        if ($tm < $cit_haos_t['value']) {
            echo '<tr><td>Следующий рейд начнется <b>' . date("j.m </b> в <b> H:i</b>", $cit_haos_t['value']) . '</td></tr>';
        } else {
            echo '<tr><td>Готовьтесь! Следующий рейд будет <b>' . $d_o . '</td></tr>';
        }
        echo '<tr><td><FORM action="city.php" method=GET><INPUT TYPE="submit" value="Вернуться в Город" name="bps"></FORM></td></tr>';
        if ($user['id'] == 1256) {
            echo '<tr><td><FORM method=POST><INPUT TYPE="submit" value="Тест (Начать рейд)" name="test_start_raid"><br></FORM></td></tr>
<tr><td><FORM method=POST><INPUT TYPE="submit" value="Админ - Начать рейд" name="adm_start_raid"><br></FORM></td></tr>';
        }
    } elseif ($in_haos['status'] == 0) {
        $cit_haos_gr = mysql_num_rows(mysql_query("SELECT * FROM `cit_haos_var`;"));
        if ($cit_haos_gr == 0) {
            $pass_s = getPass();
            mysql_query("INSERT INTO `cit_haos_var`(`group`,`password`) values('1','{$pass_s}');");
            $cit_haos_gr = mysql_num_rows(mysql_query("SELECT * FROM `cit_haos_var`;"));
        }
        echo '<tr><td>Рейд начинается <b>' . date("j.m </b> в <b> H:i</b>", $cit_haos_t['value'] + 900) . '</td></tr>';
        echo '<tr><td><FORM action="c_haos.php" method=POST>Взнос за участие в рейде <strong>20 кр</strong><br>';
        echo '<tr><td><FORM action="c_haos.php" method=POST>Максимальный размер группы - <strong>4</strong> участника<br>';
        echo '<tr><td>' . $pass_in_err . '<br />';
        $check_em = mysql_num_rows(mysql_query("SELECT * FROM `cit_haos_status` WHERE `group`=1 ;"));

        if ($check_em < 1) {
            $i = 1;
            echo '<INPUT TYPE="radio" value="' . $i . '" name="pay_gr">Группа ' . $i . ":";
            $cit_haos_pl = mysql_fetch_array(mysql_query("SELECT * FROM `cit_haos_var` WHERE `group`='" . $i . "' LIMIT 1;"));
            if ($cit_haos_pl['players'] != '') {
                foreach (explode(";", $cit_haos_pl['players']) as $ch_p) {
                    echo Nick::id($ch_p)->full(1) . ",";
                }
                echo 'Пароль:<input type="text" size="10" NAME="gr_pass_in' . $i . '">';
            } else {
                echo '  <em>(Создать новую группу)</em>';
            }
            echo '<BR>';
        } else {
            for ($i = 1; $i <= $cit_haos_gr + 1; $i++) {
                echo '<INPUT TYPE="radio" value="' . $i . '" name="pay_gr">Группа ' . $i . ":";
                $cit_haos_pl = mysql_fetch_array(mysql_query("SELECT * FROM `cit_haos_var` WHERE `group`='" . $i . "' LIMIT 1;"));
                if (strlen($cit_haos_pl['players']) > 1) {
                    foreach (explode(";", $cit_haos_pl['players']) as $ch_p) {
                        echo Nick::id($ch_p)->full(1) . ",";
                    }
                    echo 'Пароль:<input type="text" size="10" NAME="gr_pass_in' . $i . '">';
                } else {
                    echo '  <em>(Создать новую группу)</em>';
                }
                echo '<BR />';
            }
        }
        echo '<INPUT TYPE="submit" value="Вступить" name="pay"></FORM>';
        if ($pay_err) {
            echo $pay_err;
        }
        echo '<tr><td><FORM action="city.php" method=GET><INPUT TYPE="submit" value="Вернуться в Город" name="bps"></FORM></td></tr>';
    } elseif ($in_haos['status'] == 1) {
        echo '<tr><td><FORM action="c_haos.php" method=POST>Начать первый рейд: <INPUT TYPE="submit" value="Готов!" name="join_raid"></FORM></td></tr>';
        $cit_haos_pl = mysql_fetch_array(mysql_query("SELECT * FROM `cit_haos_var` WHERE `group`='" . $in_haos['group'] . "' LIMIT 1;"));
        echo '<tr><td>Рейд начинается <b>' . date("j.m </b> в <b> H:i</b>", $cit_haos_t['value'] + 900) . '</td></tr>';
        echo "<tr><td>Ждем начала рейда...<br /></td></tr>";
        echo "<tr><td>Ваша группа ";
        if (!empty($cit_haos_pl['password'])) {
            echo ":: <strong>Пароль - [" . $cit_haos_pl['password'] . "]</strong> <br />";
        }
        if ($pass_err) {
            echo $pass_err . "<br />";
        }
        $num = mysql_num_rows(mysql_query("SELECT * FROM `cit_haos_status` WHERE `group`='" . $in_haos['group'] . "';"));
        echo "<br /><b>" . $num . "</b> из <b>4</b>";
        if ($num == 4) {
            echo " - <strong>Группа заполнена</strong>";
        }
        echo "<br />";
        $cit_haos_pl = mysql_fetch_array(mysql_query("SELECT * FROM `cit_haos_var` WHERE `group`='" . $in_haos['group'] . "' LIMIT 1;"));
        foreach (explode(";", $cit_haos_pl['players']) as $ch_p) {
            echo Nick::id($ch_p)->full(1) . "<br />";
        }
        echo "</td></tr>";
    } elseif ($in_haos['status'] == 2) {
        echo '<tr><td>';
        if ($wait_msg) {
            echo $wait_msg;
        }
        echo '</td></tr>';
        header('location: c_haos_in.php');
    } elseif ($in_haos['status'] == 4) {
        mysql_query("DELETE FROM `cit_haos_status` WHERE `id` ='{$user['id']}'; ");
        echo '<tr><td><FORM action="city.php" method=GET><INPUT TYPE="submit" value="Вернуться в Город" name="bps"></FORM></td></tr>';
    } elseif ($in_haos['status'] == 5) {
        mysql_query("UPDATE users SET `doblest`=`doblest`+'1' WHERE `id` = '" . $user['id'] . "';");
        addchp('За убийство босса ЦХ вы получили 1 доблести', '{[]}' . Nick::id($user['id'])->short() . '{[]}');
        mysql_query("INSERT INTO `delo` (`id` , `author` ,`pers`, `text`, `type`, `date`) 
                        VALUES ('','0','{$cur_user['id']}','\"" . $user['login'] . "\" получил в ЦХ 1 доблести',1,'" . time() . "');");
        mysql_query("DELETE FROM `cit_haos_status` WHERE `id` ='{$user['id']}'; ");
        header('location: c_haos.php');
    }
    ?>

</table>
<div align=right><img width="260" src="i/zitadel/1.jpg"/></div>