<?php

use Battles\Template;
use Battles\User;

require_once "functions.php";

function secs2hrs($s, $short = 0)
{
    if ($s < 60) {
        return "$s сек.";
    }
    $retstr = '';
    if ($s < 3600) {
        $min = floor($s / 60);
        if ($min || !$short) {
            $retstr .= "$min мин. ";
        }
        $sec = $s % 60;
        if ($sec || !$short) {
            $retstr .= "$sec сек.";
        }
        return $retstr;
    }
    $ret = floor($s / 3600);
    $s = $s % 3600;

    $d = floor($ret / 24);
    $h = $ret % 24;
    if ($d && ($d > 1 || $h || $s)) {
        $retstr .= "$d д. ";
        if ($h || !$short) {
            $retstr .= "$h ч. ";
        }
        $min = floor($s / 60);
        if ($min || !$short) {
            $retstr .= "$min мин.";
        }
        return $retstr;
    } elseif ($d) {
        $h += $d * 24;
    }
    if ($h) {
        $retstr = "$h ч. ";
        $min = floor($s / 60);
        if ($min || !$short) {
            $retstr .= "$min мин.";
        }
        return $retstr;
    }
    return floor($s / 60) . " мин. " . ($s % 60) . " сек.";
}

if ($_GET['ext'] == 1) {
    $yas = mysql_fetch_array(mysql_query("SELECT `id` FROM `vxodd` WHERE `login` = '$user[login]' LIMIT 1"));
    $yad = mysql_fetch_array(mysql_query("SELECT `id` FROM `vxod` WHERE `login` = '$user[login]' LIMIT 1"));
    if (isset($yas['id']) || isset($yad['id'])) {
        echo "<b><font color=red>Подали заявку и убегаем? Не хорошо...</font></b>";
    } else {
        mysql_query("UPDATE `users`,`online` SET `users`.`room` = '2111', `online`.`room` = '2111' WHERE `online`.`id` = `users`.`id` AND `online`.`id` = '{$_SESSION['uid']}' ;");
        header('location: main.php');
    }
}


if (in_array(User::getInstance()->getRoom(), CANAL_ENTERS)) {
    $podzemroom = User::getInstance()->getRoom() + 1;
    $cavedata = [620 => ['x1' => 3, 'y1' => 2, 'dir1' => 2]];
    $podzemdata = [621 => ['name1' => 'Проклятый Рудник', 'name2' => 'Проклятого Рудника']];
    $warning = $_GET["warning"] ?? '';
    Template::header('enter_cave');
    if ($warning) {
        echo sprintf('<b style="color: #f80000">%s</b>', $warning);
    }
    ?>
    <div id=hint4 class=ahint></div>

    <TABLE width=100%>
        <TR>
            <TD valign=top width=100%>
                <center><h3><?= $rooms[$user["room"]] ?></h3></center>
                <?php
                $select = mysql_query("SELECT `time` FROM `visit_podzem` WHERE `room` = '$podzemroom' AND `login` = '" . $user['login'] . "' AND `time` > 0 LIMIT 1");
                if ($el = mysql_fetch_array($select)) {
                    $wait_sec = $el['time'];
                    $new_t = time();
                    $left_time = $wait_sec - $new_t;
                    $left_min = floor($left_time / 60);
                    $left_sec = $left_time - $left_min * 60;

                    if (($user['align'] == '2.99') && $wait_sec > $new_t) {
                        $wait_sec = 1;
                        mysql_query("UPDATE `visit_podzem` SET `time` = 1 WHERE `login` = '$user[login]' AND `time` > 0 AND `room` = 'User::getInstance()->getRoom()' LIMIT 1");
                    }

                    if ($wait_sec > $new_t && $_GET['donate']) {
                        if ($user['money'] >= $podzemdata[$podzemroom]['passprice']) {
                            mysql_query("UPDATE `users` SET `money` = (`money`-" . $podzemdata[$podzemroom]['passprice'] . ") WHERE `id` = '$user[id]' LIMIT 1");
                            mysql_query("INSERT INTO `delo` (`id`, `author`, `pers`, `text`, `type`, `date`) VALUES ('', '0', '{$_SESSION['uid']}', '\"" . $user['login'] . "\" пожертвовал на благоустройство пещеры \"" . $podzemdata[$podzemroom]['passprice'] . "\" кр. ($user[money]/$user[ekr]). ', 7, '" . time() . "')");
                            $wait_sec = 0;
                        } else {
                            echo "<b><font color=red>У вас недостаточно денег</font></b>";
                        }
                    }

                    if ($wait_sec > $new_t) {
                        echo " <font style='font-size: 12px;'>Вы можете посетить " . $podzemdata[$podzemroom]['name1'] . " через <font style='font-size: 11px; color: #000;'> " . secs2hrs($left_time) . "</font><br />";
                        if ($podzemdata[$podzemroom]['passprice']) {
                            echo "Пожертвовав " . $podzemdata[$podzemroom]['passprice'] . " кр. на благоустройство " . $podzemdata[$podzemroom]['name2'] . ", это можно сделать прямо сейчас. <a onclick=\"return confirm('Пожертвовать " . $podzemdata[$podzemroom]['passprice'] . " кр. на благоустройство " . $podzemdata[$podzemroom]['name2'] . "?');\" href=\"enter_cave.php?donate=1\">Пожертвовать</a>.";
                        }
                    } else {
                        mysql_query("DELETE FROM `visit_podzem` WHERE `login` = '" . $user['login'] . "' AND `room` = '$podzemroom' LIMIT 1");
                        echo "<script>location.href='main.php?act=none'</script>";
                        exit();
                    }
                } else {
                $login = $user['login'];
                $ya = mysql_query("SELECT `login` FROM `vxodd` WHERE `login` = '$login' LIMIT 1");
                $wawe = "0";
                if ($daw = mysql_fetch_array($ya)) {
                    $wawe = "1";
                }
                $naw = mysql_query("SELECT `login` FROM `vxod` WHERE `login` = '$login' LIMIT 1");
                $nawe = "0";
                if ($ser = mysql_fetch_array($naw)) {
                    $nawe = "1";
                }
                $rt = mysql_query("SELECT `id`, `level` FROM `users` WHERE `login` = '$login' LIMIT 1");
                $est = mysql_fetch_array($rt);
                $user_id = $est['id'];
                $user_lvl = $est['level'];

                if ($wawe == 0) {
                    echo "<FORM id='REQUEST'>
        <FIELDSET style='padding-left: 5px; width=50%; color:#000000;'><LEGEND><B> Группа </B> </LEGEND>
        <table>
          <tr>
            <td>Комментарий</td>
            <td><INPUT style=\"font-size:12px;\" TYPE=text NAME=cmt maxlength=40 size=40></td>
          </tr>
          <tr>
            <td>Пароль</td>
            <td><INPUT style=\"font-size:12px;\" TYPE=password NAME=pass maxlength=6 size=40></td>
          </tr>
          <tr>
            <td></td>
            <td><INPUT style='font-size:12px;' TYPE=submit name=open value='Создать группу'></td>
          </tr>
        </table>
        </FIELDSET>
        </FORM>";
                } else {
                    echo "<FORM id='REQUEST'>
        <FIELDSET style='padding-left: 5px; width=50%'>
        <LEGEND><B> Группа </B> </LEGEND>";
                    if ($nawe == 1) {
                        echo "<INPUT style=\"font-size:12px;\" type='submit' name='start' value='Начать' /> &nbsp;";
                    }
                    echo "<INPUT style=\"font-size:12px;\" type='submit' name='del' value='Покинуть группу' /></FIELDSET></FORM>";
                }

                if ($_GET['warning'] == 1) {
                    echo "<font style='color:#CC0000'>&nbsp;Вы покинули группу</font>";
                }
                if ($_GET['warning'] == 2) {
                    echo "<font style='color:#CC0000'>&nbsp;Увы! Не угадали пароль!</font>";
                }
                if ($_GET['warning'] == 3) {
                    echo "<font style='color:#CC0000'>&nbsp;Вы подали заявку, сначала отзовите её!</font>";
                }
                if ($_GET['warning'] == 4) {
                    echo "<font style='color:#CC0000'>&nbsp;Вы уже в группе!</font>";
                }
                if ($_GET['warning'] == 5) {
                    echo "<font style='color:#CC0000'>&nbsp;Группа уже собрана!</font>";
                }
                if ($_GET['warning'] == 6) {
                    echo "<font style='color:#CC0000'>&nbsp;Максимальная плата для вашего уровня: ";
                    if ($user['level'] < 5) {
                        echo "1500 кр";
                    } elseif ($user['level'] < 7) {
                        echo "3500 кр";
                    } else {
                        echo "6500 кр";
                    }
                    echo "!</font>";
                }
                if ($_GET['warning'] == 7) {
                    echo "<font style='color:#CC0000'>&nbsp;Недостаточно денег для оплаты.</font>";
                }
                if ($_GET['warning'] == 8) {
                    echo "<font style='color:#CC0000'>&nbsp;Со склонностью хаос оплата походов запрещена.</font>";
                }
                echo "<TABLE cellpadding=1 cellspacing=0>";

                $i = 0;
                function isonlinelogin($l)
                {
                    $i = mysql_fetch_assoc(mysql_query("SELECT DISTINCT(`users`.`id`) FROM `online` LEFT JOIN `users` ON (`users`.`id` = `online`.`id`) WHERE login_time >= " . (time() - 60) . " AND `users`.`login` = '$l'"));
                    return $i;
                }

                $Q = mysql_query("SELECT * FROM `vxod` WHERE `room` = 'User::getInstance()->getRoom()'");
                while ($DATA = mysql_fetch_array($Q)) {
                    $cr = $DATA['glav_id'];
                    $z_login[$i] = $DATA['login'];
                    $date[$i] = $DATA['date'];
                    $comment[$i] = $DATA['comment'];
                    $password[$i] = $DATA['pass'];
                    $mine_z[$i] = 0;

                    $Q2 = mysql_query("SELECT `glav_id` FROM `vxodd` WHERE `glav_id` = '$cr'");
                    $t1_all[$i] = 0;
                    while ($DATAS = mysql_fetch_array($Q2)) {
                        $t1_all[$i]++;
                    }
                    $creator[$i] = $DATA['glav_id'];
                    $i++;
                }

                for ($n = 0; $n < $i; $n++) {
                    echo "<form id='REQUEST'><TR><TD><font class=date>$date[$n]</font><font style='font-size: 12px; color: #000000;'> ";

                    $QUER = mysql_query("SELECT `login`, `lvl`, `fee` FROM `vxodd` WHERE `glav_id` = '$creator[$n]' ORDER BY `id` ASC");
                    while ($DATAS = mysql_fetch_array($QUER)) {
                        if ($user['id'] == 10022) {
                            $ol = isonlinelogin($DATAS['login']);
                            if (!$ol) {
                                mysql_query("DELETE FROM `vxod` WHERE `login` = '$DATAS[login]'");
                                mysql_query("DELETE FROM `vxodd` WHERE `glav_id` = '" . mysql_fetch_assoc(mysql_query("SELECT `id` FROM `users` WHERE `login` = '$DATAS[login]'")) . "'");
                                mysql_query("DELETE FROM `vxodd` WHERE `login` = '$DATAS[login]'");
                            }
                        }

                        $p1 = $DATAS['login'];
                        $p_login = $DATAS['login'];
                        $p_lvl = $DATAS['lvl'];
                        if ($p1 != '') {
                            $p1 = "<b>$p1</b> [$p_lvl] <a href='inf.php?login=$p1' target='_blank'><img src='i/inf.gif' border=0></a> ";
                            if ($t1_all[$n] == 1) {
                                echo "$p1";
                            } else {
                                echo "$p1,";
                            }
                        }
                    }

                    if (!empty($comment[$n])) {
                        echo "| $comment[$n] </font>";
                    }

                    if ($wawe == 0) {
                        if (!empty($password[$n])) {
                            echo "<INPUT style=\"font-size: 12px;\" type='password' name='pass' size='5' /> ";
                        }
                        echo "<input style=\"font-size: 12px;\" name='naw_id' type='hidden' value='$creator[$n]' /><INPUT style='font-size: 12px;' TYPE='submit' name='add' value='Присоед.' />";
                    }
                    echo "</TD></TR></FORM>";
                }
                ?>

        <TR>
            <TD></TD>
        </TR>
        <TR>
            <TD colspan=2></TD>
        </TR>
    </TABLE>
    <?php

    ///////////////Подача заявки////////////////////
    if ($_GET['open']) {
        $der = mysql_query("SELECT `glav_id` FROM `vxodd` WHERE `login` = '" . $user['login'] . "' LIMIT 1");
        if ($deras = mysql_fetch_array($der)) {
            echo "<script>location.href='?warning=4'</script>";
            exit();
        }
        $time = date("H:i");
        $SQL2 = mysql_query("INSERT INTO `vxod` (`date`, `login`, `glav_id`, `comment`, `pass`, `room`) VALUES('$time', '$login', '$user_id', '" . mysql_real_escape_string($_GET['cmt']) . "', '" . mysql_real_escape_string($_GET['pass']) . "', 'User::getInstance()->getRoom()')");
        $SQL2 = mysql_query("INSERT INTO `vxodd` (`login`, `glav_id`, `lvl`) VALUES('$login', '$user_id', '$user_lvl')");
        if ($SQL2) {
            echo "<script>location.href='main.php?act=none'</script>";
            exit();
        } else {
            echo "Ошибка!!! Сообщите администратору!";
        }
    }
    //////////////Удаление заявки//////////////////////
    if ($_GET['del']) {
        $e = mysql_query("DELETE FROM `vxod` WHERE `login` = '$login'");
        $es = mysql_query("DELETE FROM `vxodd` WHERE `glav_id` = '$user_id'");
        $ed = mysql_query("DELETE FROM `vxodd` WHERE `login` = '$login'");
        if ($e) {
            echo "<script>location.href='?warning=1'</script>";
            exit();
        } else {
            echo "Ошибка!!! Сообщите администратору!";
        }
    }

    if ($_GET['add']) {
        $der = mysql_query("SELECT `glav_id`, `id` FROM `vxodd` WHERE `login` = '" . $user['login'] . "' LIMIT 1");
        if ($deras = mysql_fetch_array($der)) {
            echo "<script>location.href='?warning=4'</script>";
            exit();
        }

        $den = mysql_query("SELECT `id` FROM `vxodd` WHERE `glav_id` = '" . $_GET['naw_id'] . "'");
        if (mysql_num_rows($den) >= (in_array(User::getInstance()->getRoom() + 1, CAVE_ROOMS) ? 5 : 4)) {
            echo "<script>location.href='?warning=5'</script>";
            exit();
        }

        if ($_GET['naw_id']) {
            $fee = (int)$_GET['fee'];
            if ($fee < 0) {
                $fee = 0;
            }
            $badfee = 0;
            if ($fee > 1500 && $user['level'] < 5) {
                $badfee = 1;
            } elseif ($fee > 3500 && $user['level'] < 7) {
                $badfee = 1;
            } elseif ($fee > 6500) {
                $badfee = 1;
            } elseif ($fee > $user['money']) {
                $badfee = 2;
            }
            if ($user['align'] == 4 && $fee > 0) {
                $badfee = 3;
            }
            $p = mysql_fetch_assoc(mysql_query("SELECT `pass` FROM `vxod` WHERE `glav_id` = '$_GET[naw_id]' LIMIT 1"));
            if ($badfee) {
                echo "<script>location.href='?warning=" . (5 + $badfee) . "'</script>";
                exit();
            } elseif ($p['pass'] == $_GET['pass']) {
                $rt = mysql_query("SELECT `level` FROM `users` WHERE `login` = '$login' LIMIT 1");
                $est = mysql_fetch_array($rt);
                $s = mysql_query("INSERT INTO `vxodd` (`login`, `glav_id`, `lvl`, `fee`) VALUES('$login', '" . $_GET['naw_id'] . "', '" . $est['level'] . "', '$fee')");
                if ($s) {
                    echo "<script>location.href='?act=none'</script>";
                    exit();
                } else {
                    echo "Ошибка!!! Сообщите администратору!";
                }
            } else {
                echo "<script>location.href='?warning=2'</script>";
                exit();
            }
        } else {
            echo "<script>location.href='?warning=2'</script>";
            exit();
        }
    }

    if ($_GET['start']) {
        if (in_array(User::getInstance()->getRoom() + 1, CAVE_ROOMS)) {
            $nc = 1;
            $locs = [];
        }
        $zax = mysql_query("SELECT `login`, `fee` FROM `vxodd` WHERE `glav_id` = '" . $user['id'] . "'");
        $level = 0;
        while ($nana = mysql_fetch_array($zax)) {
            $n_login = $nana['login'];
            $rty = mysql_query("SELECT `id`, `level`, `login`, `shadow`, `money`, `hp` FROM `users` WHERE `login` = '$n_login' LIMIT 1");
            $esth = mysql_fetch_array($rty);
            if ($esth['hp'] <= 0) {
                $esth['hp'] = 1;
                mysql_query('UPDATE `users` SET `hp` = "' . $esth['hp'] . '" WHERE `id` = "' . $esth['id'] . '" LIMIT 1');
            }
            if ($nana['fee']) {
                if ($nana['fee'] > $esth['money']) {
                    continue;
                }
                mysql_query("UPDATE `users` SET `money` = (`money+$nana[fee]) WHERE `id` = '$user[id]' LIMIT 1");
                mysql_query("update `users` SET `money` = (`money-$nana[fee]) WHERE `id` = '$esth[id]' LIMIT 1");
                $user['money'] += $nana['fee'];
                $esth['money'] -= $nana['fee'];
                adddelo($user['id'], "Персонаж $user[login] получил $nana[fee] кр. за поход по локации \"" . $rooms[User::getInstance()->getRoom() + 1] . "\" от персонажа $esth[login] ($user[money]).", 1);
                adddelo($esth['id'], "Персонаж $esth[login] заплатил $nana[fee] кр. за поход по локации \"" . $rooms[User::getInstance()->getRoom() + 1] . "\" персонажу $user[login] ($esth[money]).", 1);
            }
            if ($esth['level'] > $level) {
                $level = $esth['level'];
            }
            $est_id = $esth['id'];
            $est_login = $esth['login'];
            $vremya = 60 * 60 * 6 + time();

            mysql_query('INSERT INTO `visit_podzem` (`login`, `time`, `room`) VALUES ("' . $n_login . '", "' . $vremya . '", \'' . $podzemroom . '\')');
            $vrem = 30 * 60 + time();

            $cavedata = CAVE_DATA ?? [];
            mysql_query("INSERT INTO `caveparties` SET `user` = '$esth[id]', `leader` = '$user[id]', `login` = '$esth[login]', `shadow` = '0.png', `x` = '" . $cavedata[User::getInstance()->getRoom() + 1]['x1'] . "', `y` = '" . $cavedata[User::getInstance()->getRoom() + 1]['y1'] . "', `dir` = '" . $cavedata[User::getInstance()->getRoom() + 1]['dir1'] . "', `floor` = 1");
            mysql_query("UPDATE `users`, `online` SET " . ($nc ? "`users`.`caveleader` = '$user[id]', " : "") . " `users`.`room` = '" . (User::getInstance()->getRoom() + 1) . "', `online`.`room` = '" . (User::getInstance()->getRoom() + 1) . "' WHERE `online`.`id` = `users`.`id` AND `online`.`id` = '" . $esth['id'] . "'");
        }

        if ($nc) {
            $r = mysql_query("SELECT * FROM `cavemaps` WHERE `room` = 'User::getInstance()->getRoom()'");
            while ($rec = mysql_fetch_assoc($r)) {
                $map = unserialize($rec['map']);
                foreach ($map as $k => $v) {
                    foreach ($v as $k2 => $v2) {
                        $obj = substr($v2, 0, 1);
                        if ($obj == "b" || $obj == "a" || $obj == "w") {
                            $tmp = explode("/", $v2);
                            $i = 1;
                            if ($obj == "b") {
                                $t = 0;
                            } elseif ($obj == "w") {
                                $t = 1;
                            } else {
                                $t = 2;
                            }
                            while ($tmp[$i]) {
                                mysql_query("INSERT INTO `cavebots` SET `leader` = '$user[id]', `x` = '$k2', `y` = '$k', `startx` = '$k2', `starty` = '$k', `bot` = '$tmp[$i]', `cnt` = '" . ($tmp[$i + 1]) . "', `floor` = '$rec[floor]', `type` = '$t'");
                                $i += 2;
                            }
                            $map[$k][$k2] = 2;
                        }
                    }
                }
                include('cave_add_objects.php');
                mysql_query("INSERT INTO `caves` SET `leader` = '$user[id]', `map` = '" . serialize($map) . "', `level` = '$level', `floor` = '$rec[floor]'");
                savecavedata([], $user['id'], $rec['floor']);
            }
        }
        ?>
        <script>top.frames['online'].location = 'ch.php?online=' + Math.round(Math.random() * 100000);</script>
        <?php
        mysql_query("DELETE FROM `vxod` WHERE `login` = '$login'");
        mysql_query("DELETE FROM `vxodd` WHERE `glav_id` = " . $user['id'] . "");
        mysql_query("DELETE FROM `vxodd` WHERE `login` = '$login'");
        print "<script>location.href='cave.php'</script>";
        exit();
    }
}
    ?>

    <TD nowrap valign=top>
        <BR>
        <DIV align=right>
            <INPUT style="font-size:12px;" onClick="document.location.href='enter_cave.php?<?= time(); ?>'"
                   value=Обновить type=button>
            <input style="font-size: 12px;" type="button" value="Вернуться"
                   onclick="document.location.href='enter_cave.php?ext=1';"/>
        </DIV>
        </TABLE>
        </TABLE>
        <div id="goto" style="text-align:right;white-space:nowrap">&nbsp;</div>
        <br><br>
    <?php
} else {
    header("location: main.php");
}