<?php

use Battles\GameLogs;
use Battles\Nick;
use Battles\User;

class Tournament
{
    public $MaxUserLevel = 9;
    private $awards = [1 => [1 => 10, 20, 30, 40, 50, 60, 70, 80],
        2 => [1 => 8, 15, 20, 30, 35, 45, 50, 60],
        3 => [1 => 5, 10, 15, 20, 25, 30, 35, 40]];

    function AddUserInTournament(int $id)
    {
        global $user;
        $chek = mysql_fetch_row(mysql_query("select id from turnament where id=" . $id . " and old=0"));
        if ($chek[0] == '') {
            exit("Жаль, очень жаль....");
        }

        if (mysql_query("insert into turnamuser (idturnam,iduser,level) values(" . $id . "," . $user['id'] . "," . $user['level'] . ")")) {
            mysql_query("update turnament set kolvo=kolvo+1 where id=" . $id);
            echo "Регистрация пройдена!";
        } else {
            exit("Вы уже зарегистрированы.");
        }
    }

    function DellUserInTournament(int $id)
    {
        global $user;
        mysql_query("delete from turnamuser where idturnam=" . $id . " and iduser=" . $user['id']);
        mysql_query("update turnament set kolvo=kolvo-1 where id=" . $id);
        echo "Заявка отозвана<br>";
    }

    function fract($num = 0)
    {
        if (!is_float($num)) {
            return false;
        }
        $out = explode('.', $num);
        return $out[1];
    }

    function PrepearTournir()
    {//запускается за час до начала турнира

        for ($i = 1; $i < $this->MaxUserLevel; $i++) {
            $uch = mysql_query("select id,iduser from turnamuser where loose=0 and idturnam=(select id from turnament where old=0 and level=" . $i . ") order by id desc");
            $kol = mysql_num_rows($uch);
            $cop = $kol;
            if ($kol > 7) {
                while (true) {
                    $stepen = log($cop) / log(2);
                    if (!$this->fract($stepen)) { //==false - дробная часть отсутствует
                        for ($j = 1; $j <= ($kol - $cop); $j++) {
                            $res = mysql_fetch_row($uch);
                            mysql_query("delete from turnamuser where id=" . $res[0]);
                            addchp('<font color=red>Внимание!</font> На этой неделе Вам не нашлелся противник в турнире.<BR>', '{[]}' . Nick::id($res[1])->short() . '{[]}');
                        }
                        mysql_query("update turnament set kolvo=kolvo-" . ($kol - $cop) . " where old=0 and level=" . $i);
                        break;
                    }
                    $cop--;
                }
                $CountUser = [];
                while ($res = mysql_fetch_row($uch)) {
                    $CountUser[] = $res[1];
                }
                shuffle($CountUser);

                for ($ii = 0; $ii < count($CountUser); $ii++) {
                    $user1 = $CountUser[$ii];
                    $user2 = $CountUser[++$ii];
                    mysql_query("insert into turnirbattle(userid,userid1,level,idtur) values(" . $user1 . "," . $user2 . "," . $i . ",(select id from turnament where old=0 and level=" . $i . "))");
                    addchp('<font color=red>Внимание!</font> Подготовтесь к турниру.<BR>', '{[]}' . Nick::id($user1)->short() . '{[]}');
                    addchp('<font color=red>Внимание!</font> Подготовтесь к турниру.<BR>', '{[]}' . Nick::id($user2)->short() . '{[]}');
                }
            } else {
                //Если команда не набралась удалить из таблицы и поставить турниру статус 2
                while ($res = mysql_fetch_row($uch)) {
                    mysql_query("delete from turnamuser where id=" . $res['0']);
                    addchp('<font color=red>Внимание!</font>На этой неделе команда для турнира не набралась.<BR>', '{[]}' . Nick::id($res[1])->short() . '{[]}');
                }
                mysql_query("delete from turnament where old=0 and level=" . $i);
            }
        }
    }

    // созает поединок между 2 юзерами
    function MakeBattle($user1, $user2)
    {
        $res = mysql_fetch_array(mysql_query("select * from turnirbattle where userid=" . $user1 . " or userid1=" . $user1 . " limit 1"));
        if ($res['userid1'] == $user1 && $res['badmaxweap1'] != 0) {
            if ((time() - $res['badmaxweap1']) > 120) {
                mysql_query("update turnamuser set loose=2, place=" . time() . " where iduser=" . $user1 . " and idturnam=" . $res['idtur']);
                mysql_query("delete from turnirbattle where userid1=" . $user1);
                addchp('<font color=red>Внимание!</font>Вы выбыли из турнира<BR>', '{[]}' . Nick::id($user1)->short() . '{[]}');
                addchp('<font color=red>Внимание!</font>Ваш противник отказался от боя. Техническая победа.<BR>', '{[]}' . Nick::id($user2)->short() . '{[]}');
            }
        } elseif ($res['userid'] == $user2 && $res['badmaxweap'] != 0) {
            if ((time() - $res['badmaxweap']) > 120) {
                mysql_query("update turnamuser set loose=2, place=" . time() . " where iduser=" . $user2 . " and idturnam=" . $res['idtur']);
                mysql_query("delete from turnirbattle where userid=" . $user2);
                addchp('<font color=red>Внимание!</font>Вы выбыли из турнира<BR>', '{[]}' . Nick::id($user2)->short() . '{[]}');
                addchp('<font color=red>Внимание!</font>Ваш противник отказался от боя. Техническая победа.<BR>', '{[]}' . Nick::id($user1)->short() . '{[]}');
            }
        } elseif ($res['userid'] == $user1 && $res['badmaxweap'] != 0) {
            if ((time() - $res['badmaxweap']) > 120) {
                mysql_query("update turnamuser set loose=2, place=" . time() . " where iduser=" . $user1 . " and idturnam=" . $res['idtur']);
                mysql_query("delete from turnirbattle where userid=" . $user1);
                addchp('<font color=red>Внимание!</font>Вы выбыли из турнира<BR>', '{[]}' . Nick::id($user1)->short() . '{[]}');
                addchp('<font color=red>Внимание!</font>Ваш противник отказался от боя. Техническая победа.<BR>', '{[]}' . Nick::id($user2)->short() . '{[]}');
            }
        } elseif ($res['userid1'] == $user2 && $res['badmaxweap1'] != 0) {
            if ((time() - $res['badmaxweap1']) > 120) {
                mysql_query("update turnamuser set loose=2, place=" . time() . " where iduser=" . $user2 . " and idturnam=" . $res['idtur']);
                mysql_query("delete from turnirbattle where userid1=" . $user2);
                addchp('<font color=red>Внимание!</font>Вы выбыли из турнира<BR>', '{[]}' . Nick::id($user2)->short() . '{[]}');
                addchp('<font color=red>Внимание!</font>Ваш противник отказался от боя. Техническая победа.<BR>', '{[]}' . Nick::id($user1)->short() . '{[]}');
            }
        } else {
            //Если на человеке лишняя одежда написать чтобы снял поставить время ожидания 2 минуты
            $Shmotuser = mysql_fetch_array(mysql_query("select * from users where id=" . $user1));
            $Shmotuser1 = mysql_fetch_array(mysql_query("select * from users where id=" . $user2));
            $PriceWeap = mysql_fetch_row(mysql_query("select cost from inventory where id=" . $Shmotuser['weap'] . " limit 1")) ?? [];
            $PriceWeap1 = mysql_fetch_row(mysql_query("select cost from inventory where id=" . $Shmotuser1['weap'] . " limit 1")) ?? [];

            if ($PriceWeap[0] > 16 || $Shmotuser['sergi'] != 0 || $Shmotuser['kulon'] != 0 || $Shmotuser['perchi'] != 0 || $Shmotuser['bron'] != 0 || $Shmotuser['r1'] != 0 || $Shmotuser['r2'] != 0 || $Shmotuser['r3'] != 0 || $Shmotuser['helm'] != 0 || $Shmotuser['shit'] != 0 || $Shmotuser['boots'] != 0 || $Shmotuser['stats'] != 0 || $Shmotuser['m1'] != 0 || $Shmotuser['m2'] != 0 || $Shmotuser['m3'] != 0 || $Shmotuser['m4'] != 0 || $Shmotuser['m5'] != 0 || $Shmotuser['m6'] != 0 || $Shmotuser['m7'] != 0 || $Shmotuser['m8'] != 0 || $Shmotuser['m9'] != 0 || $Shmotuser['m10'] != 0) {
                if ($res['userid'] == $user1) {
                    mysql_query("update turnirbattle set badmaxweap=" . time() . " , checkuser=0 where userid=" . $user1);
                }
                if ($res['userid1'] == $user1) {
                    mysql_query("update turnirbattle set badmaxweap1=" . time() . " , checkuser2=0 where userid1=" . $user1);
                }
                addchp('<font color=red>Внимание!</font>Оставьте оружие только до 16экр или оставьте только оружие.<BR>', '{[]}' . Nick::id($user1)->short() . '{[]}');
            } elseif ($PriceWeap1[0] > 16 || $Shmotuser1['sergi'] != 0 || $Shmotuser1['kulon'] != 0 || $Shmotuser1['perchi'] != 0 || $Shmotuser1['bron'] != 0 || $Shmotuser1['r1'] != 0 || $Shmotuser1['r2'] != 0 || $Shmotuser1['r3'] != 0 || $Shmotuser1['helm'] != 0 || $Shmotuser1['shit'] != 0 || $Shmotuser1['boots'] != 0 || $Shmotuser1['stats'] != 0 || $Shmotuser1['m1'] != 0 || $Shmotuser1['m2'] != 0 || $Shmotuser1['m3'] != 0 || $Shmotuser1['m4'] != 0 || $Shmotuser1['m5'] != 0 || $Shmotuser1['m6'] != 0 || $Shmotuser1['m7'] != 0 || $Shmotuser1['m8'] != 0 || $Shmotuser1['m9'] != 0 || $Shmotuser1['m10'] != 0) {
                if ($res['userid'] == $user2) {
                    mysql_query("update turnirbattle set badmaxweap=" . time() . " , checkuser=0 where userid=" . $user2);
                }
                if ($res['userid1'] == $user2) {
                    mysql_query("update turnirbattle set badmaxweap1=" . time() . " , checkuser2=0 where userid1=" . $user2);
                }
                addchp('<font color=red>Внимание!</font>Оставьте оружие только до 16экр или оставьте только оружие.<BR>', '{[]}' . Nick::id($user2)->short() . '{[]}');
            } else {
                // генерим массив с командами
                $teams = [];
                $teams[$user1][$user2] = [0, 0, time()];
                $teams[$user2][$user1] = [0, 0, time()];
                //Востанавливаем HP
                mysql_query("update users set hp=maxhp where id=" . $user1 . " or id=" . $user2);
                // создаем битву
                mysql_query("INSERT INTO `battle`(
				`id`,`coment`,`teams`,`timeout`,`type`,`status`,`t1`,`t2`,`to1`,`to2`,`blood`)
				VALUES(
				NULL,'','" . serialize($teams) . "','3','1','0','" . $user1 . "','" . $user2 . "','" . time() . "','" . time() . "','0')");
                // айди боя
                $id = mysql_insert_id();
                // кидаем в бой
                mysql_query("UPDATE `users` SET `battle` = {$id} WHERE `id` = " . $user1 . " OR `id` = " . $user2);
                // создаем лог
                $rr = "<b>" . Nick::id(User::getInstance()->getId())->full(1) . "</b> и <b>" . Nick::id($jert['id'])->full(1) . "</b>";
                addch("<a href=logs.php?log=" . $id . " target=_blank>Бой</a> между <B><b>" . Nick::id(User::getInstance()->getId())->short() . "</b> и <b>" . Nick::id($jert['id'])->short() . "</b> начался.   ", User::getInstance()->getRoom());
                GameLogs::addBattleLog($id, "Часы показывали <span class=date>" . date("Y.m.d H.i") . "</span>, когда " . $rr . " решили выяснить кто из них сильнее. <i>(турнир)</i><BR>");
                return $id;
            }
        }
    }

    // функция проверки статуса боя
    function CheckBattle($id)
    {
        // если по айдишнику возвращается
        // 1 - победил USER1
        // 2 - победил USER2
        // 3 - бои идет
        $res = mysql_fetch_array(mysql_query("SELECT `win` FROM `battle` WHERE `id` = " . (int)$id . " LIMIT 1;"));
        return $res['win'];
    }

    function UpdateTournir()
    {
        for ($i = 1; $i < $this->MaxUserLevel; $i++) {
            $sql = mysql_query("select * from  turnirbattle where level=" . $i);

            if (mysql_numrows($sql) == 0) {
                $this->NextTournir($i);
                $this->StartTournir($i);
            } else {
                echo "Для " . $i . " уровня игроков следующий этап турнира начнется после завершения следующих боёв: <br>";
            }

            while ($res = mysql_fetch_array($sql)) {
                $win = $this->CheckBattle($res['battleid']);
                if ($win == 1) {
                    mysql_query("update turnamuser set place=" . time() . ", loose=loose+1 where iduser=" . $res['userid1']);
                    mysql_query("update turnamuser set place=0 where iduser=" . $res['userid']);
                    mysql_query("delete from turnirbattle where id=" . $res['id']);
                }
                if ($win == 2) {
                    mysql_query("update turnamuser set place=" . time() . ", loose=loose+1 where iduser=" . $res['userid']);
                    mysql_query("update turnamuser set place=0 where iduser=" . $res['userid1']);
                    mysql_query("delete from turnirbattle where id=" . $res['id']);
                }
                if ($win == 3) {
                    echo Nick::id($res['userid'])->full(1) . " против " . Nick::id($res['useridl'])->full(1);
                }
            }
        }
    }

    function NextTournir($level)
    {
        $CheckFinal = [];
        for ($i = 0; $i <= 1; $i++) {
            $sql = mysql_query("select iduser from turnamuser where level=" . $level . " and loose=" . $i . " and idturnam=(select id from turnament where old=0 and level=" . $level . ")");

            $ArrayUsers = [];
            while ($res = mysql_fetch_row($sql)) {
                $ArrayUsers[] = $res[0];
            }
            shuffle($CountUser);

            if (count($ArrayUsers) == 1) {
                $CheckFinal[] = $ArrayUsers[0];
            }
            if (count($ArrayUsers) == 1 && $i == 0) {
                addchp('<font color=red>Внимание!</font> Вы вышли в финал. Дождитесь второго финалиста.<BR>', '{[]}' . Nick::id($ArrayUsers[0])->short() . '{[]}');
            }

            if ($this->fract(count($ArrayUsers) / 2)) {
                $countUs = count($ArrayUsers) - 1;
            } else {
                $countUs = count($ArrayUsers);
            }

            for ($ii = 0; $ii < $countUs; $ii++) {
                $user1 = $ArrayUsers[$ii];
                $user2 = $ArrayUsers[++$ii];
                //Востанавливаем HP
                mysql_query("update users set hp=maxhp where id=" . $user1 . " or id=" . $user2);
                mysql_query("insert into turnirbattle(userid,userid1,level,idtur) values(" . $user1 . "," . $user2 . "," . $level . ",(select id from turnament where old=0 and level=" . $level . "))");
                addchp('<font color=red>Внимание!</font> Подготовтесь к следующему туру.<BR>', '{[]}' . Nick::id($user1)->short() . '{[]}');
                addchp('<font color=red>Внимание!</font> Подготовтесь к следующему туру.<BR>', '{[]}' . Nick::id($user2)->short() . '{[]}');
            }
        }
        if (count($CheckFinal) == 2) {
            $this->TournirFinal($level, $CheckFinal);
        }
        if (count($CheckFinal) == 1) {
            $this->CreateHTML($level);
            //поставить турниру статус 2. создать HTML для подгрузки результатов
            //Если команда не набралась - удалить турнир. - эо при старте в 4 часа.
            $this->ShowTournirFinaliats($level);
        }
    }

    function CreateHTML($level)
    {
        $dir = "logtur/" . $level;
        if (!file_exists($dir)) {
            mkdir($dir);
        }
        $tur = mysql_fetch_array(mysql_query("select * from turnament where old=0 and level=" . $level . " limit 1"));
        $f = fopen($dir . "/" . $tur['datetime'] . ".html", 'w+');
        fwrite($f, '<html><head><TITLE></TITLE><META content="text/html; charset=utf-8" http-equiv=Content-type></head>');
        fwrite($f, '<bpdy><table><tr><td>Игрок</td><td>Место</td></tr>');
        mysql_query("update turnamuser set place=" . (time() + 1000) . " where place=0 and idturnam=" . $tur['id'] . " and level=" . $level);
        $sql = mysql_query("select tur.*, us.login from turnamuser as tur left join users as us on us.id=tur.iduser where tur.idturnam=" . $tur['id'] . " order by tur.place desc");
        $i = 1;

        while ($res = mysql_fetch_array($sql)) {
            if ($i == 1 || $i == 2 || $i == 3) {
                mysql_query("INSERT INTO `delo`(`id` , `author` ,`pers`, `text`, `type`, `date`) VALUES ('','0','" . $res['iduser'] . "','Выиграл в турнире " . $this->awards[$i][$level] . " кр.','1','" . time() . "');");
                addchp('<font color=red>Внимание!</font> За ' . $i . ' место в турнире, Вы получили ' . $this->awards[$i][$level] . ' кр.<BR>', '{[]}' . Nick::id($res['iduser'])->short() . '{[]}');
            }
            fwrite($f, '<tr><td>' . $res['login'] . '</td><td>' . $i++ . '</td></tr>');

        }
        fwrite($f, '</table></body></html>');
        fclose($f);
        mysql_query("update turnament set old=2, path='/" . $dir . "/" . $tur['datetime'] . ".html' where old=0 and level=" . $level);

        if (mysql_numrows(mysql_query("select id from turnament where old=0")) == 0) {
            $this->CreateTournament("Еженедельные турниры");
        }
    }

    function ShowTournirFinaliats()
    {
        $sql = mysql_query("select datetime,level,path from turnament where old=2 group by level order by datetime");
        $level = 0;

        echo "Результаты прошедших турниров.<br><table border='0' style='background-color:#E0E0E0;'><tr><td>Уровень</td><td>Дата</td></tr>";
        while ($res = mysql_fetch_array($sql)) {
            if ($level != $res['level']) {
                echo "<tr><td>" . $res['level'] . "</td>";
            }
            echo "<td><a href='http://capitalcity.oldbk.com" . $res['path'] . "'>" . date("d.m.Y H:i", $res['datetime']) . "</a></td>";
            if ($level != $res['level']) {
                echo "</tr>";
                $level = $res['level'];
            }
        }
        echo "</table>";
    }

    function TournirFinal($level, $masFinals)
    {
        mysql_query("update turnamuser set place=0 where (iduser=" . $masFinals[0] . " or iduser=" . $masFinals[1] . ") and idturnam=(select id from turnament where old=0 and level=" . $level . ")");
        mysql_query("insert into turnirbattle(userid,userid1,level,idtur) values(" . $masFinals[0] . "," . $masFinals[1] . "," . $level . ",(select id from turnament where old=0 and level=" . $level . "))");
        addchp('<font color=red>Внимание!</font> Подготовтесь к финалу.<BR>', '{[]}' . Nick::id($masFinals[0])->short() . '{[]}');
        addchp('<font color=red>Внимание!</font> Подготовтесь к финалу.<BR>', '{[]}' . Nick::id($masFinals[1])->short() . '{[]}');
    }

    function expectationenemy()
    {
        global $user;
        $res = mysql_fetch_array(mysql_query("select * from turnirbattle where userid=" . $user['id'] . " or userid1=" . $user['id'] . " limit 1"));
        if ($res['id'] != '') {
            if ($res['userid'] == $user['id'] && $res['checkuser'] == 0 && $res['badmaxweap'] == 0) {
                mysql_query("update turnirbattle set checkuser=1 where userid=" . $user['id']);
                if ($res['checkuser2'] == 1) {
                    $battle = $this->MakeBattle($res['userid'], $res['userid1']);
                    mysql_query("update turnirbattle set battleid=" . $battle . " where id=" . $res['id']);
                }
            } elseif ($res['badmaxweap'] != 0) {
                if ((time() - $res['badmaxweap']) > 120) {
                    mysql_query("update turnamuser set loose=2, place=" . time() . " where iduser=" . $res['userid'] . " and idturnam=" . $res['idtur']);
                    mysql_query("delete from turnirbattle where userid=" . $res['userid']);
                    addchp('<font color=red>Внимание!</font>Вы выбыли из турнира<BR>', '{[]}' . Nick::id($res['userid'])->short() . '{[]}');
                    addchp('<font color=red>Внимание!</font>Ваш противник отказался от боя. Техническая победа.<BR>', '{[]}' . Nick::id($res['userid1'])->short() . '{[]}');
                }
            }
            if ($res['userid1'] == $user['id'] && $res['checkuser2'] == 0 && $res['badmaxweap1'] == 0) {
                mysql_query("update turnirbattle set checkuser2=1 where userid1=" . $user['id']);
                if ($res['checkuser'] == 1) {
                    $battle = $this->MakeBattle($res['userid'], $res['userid1']);
                    mysql_query("update turnirbattle set battleid=" . $battle . " where id=" . $res['id']);
                }
            } elseif ($res['badmaxweap1'] != 0) {
                if ((time() - $res['badmaxweap1']) > 120) {
                    mysql_query("update turnamuser set loose=2, place=" . time() . " where iduser=" . $res['userid'] . " and idturnam=" . $res['idtur1']);
                    mysql_query("delete from turnirbattle where userid1=" . $res['userid1']);
                    addchp('<font color=red>Внимание!</font>Вы выбыли из турнира<BR>', '{[]}' . Nick::id($res['userid1'])->short() . '{[]}');
                    addchp('<font color=red>Внимание!</font>Ваш противник отказался от боя. Техническая победа.<BR>', '{[]}' . Nick::id($res['userid'])->short() . '{[]}');
                }
            }
        }
    }

    function StartTournir($level = null)
    {//Запускается в 17-00-10 каждую пятницу
        //Разослать всем кнопочки на вход в турнир
        global $user;
        $res = mysql_fetch_array(mysql_query("select * from turnirbattle where userid=" . $user['id'] . " or userid1=" . $user['id'] . " limit 1"));
        $PriceWeap = mysql_fetch_row(mysql_query("select cost from inventory where id=" . $user['weap'] . " limit 1")) ?? [];

        if ($PriceWeap[0] > 16 || $user['sergi'] != 0 || $user['kulon'] != 0 || $user['perchi'] != 0 || $user['bron'] != 0 || $user['r1'] != 0 || $user['r2'] != 0 || $user['r3'] != 0 || $user['helm'] != 0 || $user['shit'] != 0 || $user['boots'] != 0 || $user['stats'] != 0 || $user['m1'] != 0 || $user['m2'] != 0 || $user['m3'] != 0 || $user['m4'] != 0 || $user['m5'] != 0 || $user['m6'] != 0 || $user['m7'] != 0 || $user['m8'] != 0 || $user['m9'] != 0 || $user['m10'] != 0) {
            if ($res['userid'] == $user['id'] && $res['badmaxweap'] == 0) {
                mysql_query("update turnirbattle set badmaxweap=" . time() . " , checkuser=0 where userid=" . $user['id']);
            }
            if ($res['userid1'] == $user['id'] && $res['badmaxweap1'] == 0) {
                mysql_query("update turnirbattle set badmaxweap1=" . time() . " , checkuser2=0 where userid1=" . $user['id']);
            }
            addchp('<font color=red>Внимание!</font>Оставьте оружие только до 16экр или оставьте только оружие.<BR>', '{[]}' . Nick::id($user['id'])->short() . '{[]}');
        } else {
            if ($res['userid'] == $user['id']) {
                mysql_query("update turnirbattle set badmaxweap=0 where userid=" . $user['id']);
            }
            if ($res['userid1'] == $user['id']) {
                mysql_query("update turnirbattle set badmaxweap1=0 where userid1=" . $user['id']);
            }
        }

        $sql = mysql_query("select * from turnirbattle where badmaxweap1<>0 or badmaxweap<>0");
        while ($res = mysql_fetch_array($sql)) {
            if ($res['badmaxweap1'] != 0 && (time() - $res['badmaxweap1']) > 120) {
                mysql_query("update turnamuser set loose=2, place=" . time() . " where iduser=" . $res['userid1'] . " and idturnam=" . $res['idtur']);
                mysql_query("delete from turnirbattle where userid1=" . $res['userid1']);
                addchp('<font color=red>Внимание!</font>Вы выбыли из турнира<BR>', '{[]}' . Nick::id($res['userid1'])->short() . '{[]}');
                addchp('<font color=red>Внимание!</font>Ваш противник отказался от боя. Техническая победа.<BR>', '{[]}' . Nick::id($res['userid'])->short() . '{[]}');
            }
            if ($res['badmaxweap'] != 0 && (time() - $res['badmaxweap']) > 120) {
                mysql_query("update turnamuser set loose=2, place=" . time() . " where iduser=" . $res['userid'] . " and idturnam=" . $res['idtur']);
                mysql_query("delete from turnirbattle where userid=" . $res['userid']);
                addchp('<font color=red>Внимание!</font>Вы выбыли из турнира<BR>', '{[]}' . Nick::id($res['userid'])->short() . '{[]}');
                addchp('<font color=red>Внимание!</font>Ваш противник отказался от боя. Техническая победа.<BR>', '{[]}' . Nick::id($res['userid1'])->short() . '{[]}');
            }
        }

        if ($level != '') {
            $level = ' and level=' . $level;
        }
        $sql = mysql_query("SELECT * FROM turnirbattle WHERE (userid=" . $user['id'] . " or userid1=" . $user['id'] . ") " . $level);
        while ($res = mysql_fetch_array($sql)) {
            $looseL1 = mysql_fetch_row(mysql_query("select loose from turnamuser where iduser=" . $res['userid1'] . " and idturnam=" . $res['idtur']));
            $looseL = mysql_fetch_row(mysql_query("select loose from turnamuser where iduser=" . $res['userid'] . " and idturnam=" . $res['idtur']));
            if ($res['userid'] == $user['id']) {
                if ($res['checkuser'] == 0) {
                    if ($res['badmaxweap'] != 0) {
                        if ((time() - $res['badmaxweap']) > 120) {
                            mysql_query("update turnamuser set loose=2, place=" . time() . " where iduser=" . $res['userid'] . " and idturnam=" . $res['idtur']);
                            mysql_query("delete from turnirbattle where userid=" . $res['userid']);
                            addchp('<font color=red>Внимание!</font>Вы выбыли из турнира<BR>', '{[]}' . Nick::id($res['userid'])->short() . '{[]}');
                            addchp('<font color=red>Внимание!</font>Ваш противник отказался от боя. Техническая победа.<BR>', '{[]}' . Nick::id($res['userid1'])->short() . '{[]}');
                        } else {
                            echo "<form method='post'><input type='submit' name='expenemy' value='Я готов'> противник " . Nick::id($res['useridl'])->full(1) . "(поражений-" . $looseL1[0] . ")</form>";
                        }
                    } else {
                        echo "<form method='post'><input type='submit' name='expenemy' value='Я готов'> противник " . Nick::id($res['useridl'])->full(1) . "(поражений-" . $looseL1[0] . ")</form>";
                    }
                } else {
                    echo "Ожидаем противника";
                }
            }

            if ($res['userid1'] == $user['id']) {
                if ($res['checkuser2'] == 0) {
                    if ($res['badmaxweap1'] != 0) {
                        if ((time() - $res['badmaxweap1']) > 120) {
                            mysql_query("update turnamuser set loose=2, place=" . time() . " where iduser=" . $res['userid1'] . " and idturnam=" . $res['idtur']);
                            mysql_query("delete from turnirbattle where userid1=" . $res['userid1']);
                            addchp('<font color=red>Внимание!</font>Вы выбыли из турнира<BR>', '{[]}' . Nick::id($res['userid1'])->short() . '{[]}');
                            addchp('<font color=red>Внимание!</font>Ваш противник отказался от боя. Техническая победа.<BR>', '{[]}' . Nick::id($res['userid'])->short() . '{[]}');
                        } else {
                            echo "<form method='post'><input type='submit' name='expenemy' value='Я готов'>противник " . Nick::id($res['userid'])->full(1) . "(поражений-" . $looseL[0] . ")</form>";
                        }
                    } else {
                        echo "<form method='post'><input type='submit' name='expenemy' value='Я готов'>противник " . Nick::id($res['userid'])->full(1) . "(поражений-" . $looseL[0] . ")</form>";
                    }
                } else {
                    echo "Ожидаем противника";
                }
            }
        }
    }

    function CreateTournament($title)
    {
        //Вычисляем следующую пятницу
        $dateTime = '';
        if (date("w", mktime(0, 0, 0, date('n'), date('j'), date('Y'))) == 5 && date("H") > 17) {
            $nextDay = date('j') + 1;
            $DayofMonth = date('j');
            if ($nextDay > date('t')) {
                $nextDay = 1;
                $DayofMonth = date("t", mktime(0, 0, 0, date('n') + 1, 1, date('Y')));//даже если date('n')+1 = 13 mktime переведет на 01.01.следующий год
            }
        } else {
            $nextDay = date('j');
            $DayofMonth = date('t');
        }

        for ($j = $nextDay; $j <= $DayofMonth; $j++) {
            //узнаем день недели
            $DayofWeek = date("w", mktime(0, 0, 0, date('n'), $j, date('Y')));
            if ($DayofWeek == 5) {
                $dateTime = mktime(17, 0, 0, date('n'), $j, date('Y'));
                break;
            }
        }
        //если пятниц в этом месяце не осталось
        if ($dateTime == '') {
            if (date("n") + 1 == 13) {
                $Month = 1;
                $Year = date("Y") + 1;
            } else {
                $Month = date('n') + 1;
                $Year = date("Y");
            }

            for ($j = 1; $j <= date('t', mktime(0, 0, 0, $Month, 1, $Year)); $j++) {
                //узнаем день недели
                $DayofWeek = date("w", mktime(0, 0, 0, $Month, $j, $Year));
                if ($DayofWeek == 5) {
                    $dateTime = mktime(17, 0, 0, $Month, $j, $Year);
                    break;
                }
            }
        }

        //Создаем турниры.
        for ($i = 1; $i < $this->MaxUserLevel; $i++)
            if (!mysql_query("insert into turnament(title,level,datetime) values ('" . $title . "'," . $i . ",'" . $dateTime . "')")) {
                $f = fopen('/tmp/memcache/logtur/error.log', 'w');
                fwrite($f, "insert into turnament(title,level,datetime) values ('" . $title . "'," . $i . ",'" . $dateTime . "')\n");
                fclose($f);
            }
    }

    function showAllTurnament()
    {
        global $user;
        $sql = mysql_query("select * from turnament where old=0");
        $dateD = mysql_fetch_row(mysql_query("select datetime from turnament where old=0 limit 1"));
        if (mysql_num_rows($sql) < 1) {
            echo "На данный момент новых чемпионатов нет";
        }
        if ($user['level'] > 0 && mktime() < $dateD[0]) {
            echo "<form method='post'>";
        }
        echo "<table border=1 style='font-weight:bold;'>
				<tr>
					<td>Название турнира</td>
					<td>Время проведения</td>
					<td>Кол-во учасников</td>
					<td>Уровень</td>";
        if ($user['level'] > 0 && mktime() < $dateD[0]) {
            echo "<td>Регистрация</td>";
        }
        echo "</tr>";
        while ($res = mysql_fetch_array($sql)) {
            if ($user['level'] == $res['level']) {
                $dellzay = mysql_fetch_row(mysql_query("select id from turnamuser where iduser=" . $user['id'] . " and idturnam=" . $res['id']));
            }
            echo "<tr>
					<td>
						" . $res['title'] . "
					</td>
					<td>
						" . date("d.m.Y H:i", $res['datetime']) . "
					</td>
					<td>
						" . $res['kolvo'] . "
					</td>
					<td>
						" . $res['level'] . "
					</td>";
            if ($user['level'] == $res['level'] && mktime() < $dateD[0]) {
                if ($dellzay[0] == '') {
                    echo "<td>
							<input type='submit' name='addzayvka' value='Зарегистрироваться'>
							<input type='hidden' name='idtur' value='" . $res['id'] . "'>
						</td>";
                }
                else {
                    echo "<td>
							<input type='submit' name='dellzayvka' value='Отказаться'>
							<input type='hidden' name='idtur' value='" . $res['id'] . "'>
						</td>";
                }
            }
            echo "</tr>";
        }
        echo "</table>";
        if ($user['level'] > 0 && mktime() < $dateD[0]) {
            echo "</form>";
        }
    }
}
