<?php

use Battles\DressedItems;
use Battles\GameLogs;
use Battles\Nick;
use Battles\Template;

require_once "functions.php";

$q2 = mysql_fetch_array(mysql_query('SELECT * FROM `qst_user` WHERE `uid` = "' . $user['id'] . '" AND `cancel` = "0" AND `finish` = "0" LIMIT 1'));
if (isset($q2['id'])) {
    $q1 = mysql_fetch_array(mysql_query('SELECT * FROM `qst` WHERE `id` = "' . $q2['qid'] . '" LIMIT 1'));
}
$vipUsers = [
    'Father',
];
$errkom = '';
$varsitm = [[270, 1]];
$varsitm2 = [[87, 1], [88, 1], [48, 1], [49, 1], [29, 1], [66, 1], [97, 1], [67, 1], [98, 1], [115, 1]];

function labaItemAdd($id)
{
    global $user;
    $dress = mysql_fetch_array(mysql_query('SELECT * FROM `shop` WHERE `id` = "' . (int)$id . '" LIMIT 1'));

    if (isset($dress['id'])) {
        mysql_query("INSERT INTO `inventory` (`laba`, `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`,`koll`) VALUES ('$type', '{$dress['id']}','{$user['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['bron2']}','{$dress['bron3']}','{$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']}','{$dress[koll]}')");
    }
}

function money_add($sum)
{
    global $user;
    $user['money'] += $sum;
    mysql_query('UPDATE `users` SET `money` = "' . $user['money'] . '" WHERE `id` = "' . $user['id'] . '" LIMIT 1');
}


$lab = mysql_fetch_array(mysql_query('SELECT * FROM `laba_now` WHERE `id` = "' . $user['laba'] . '" LIMIT 1'));
$map = mysql_fetch_array(mysql_query('SELECT `id`,`data`,`update` FROM `laba_map` WHERE `id` = "' . $user['laba'] . '" LIMIT 1'));
$dies = mysql_fetch_array(mysql_query('SELECT COUNT(`id`) FROM `laba_act` WHERE `uid` = "' . $user['id'] . '" AND `lib` = "' . $user['laba'] . '" AND `vars` = "dielaba" LIMIT 1'));
$dies = $dies[0];
$map_d = json_decode($map['data']);
$usersDng = showProgressBar($user['hp'], $user['maxhp']);
$errors = '';
$effed = '';
$mapsee = '';
$varos = [];
$varos['trap1'] = mysql_fetch_array(mysql_query('SELECT `id`, `vals`, `time` FROM `laba_act` WHERE `uid` = "' . $user['id'] . '" AND `lib` = "' . $lab['id'] . '" AND `time` > "' . time() . '" ORDER BY `time` DESC LIMIT 1'));
$real_x = $user['x'];
$real_y = $user['y'];
if ($real_y < 6) {
    $real_y = 6;
}
if ($real_x < 6) {
    $real_x = 6;
}
if ($real_y > count($map_d) - 7) {
    $real_y = count($map_d) - 7;
}
if ($real_x > count($map_d) - 7) {
    $real_x = count($map_d) - 7;
}
$objs = [];
$sp = mysql_query('SELECT * FROM `laba_obj` WHERE `lib` = "' . $lab['id'] . '" AND `x` > ' . ($real_x - 7) . ' AND `x` < ' . ($real_x + 7) . ' AND `y` > ' . ($real_y - 12) . ' AND `y` < ' . ($real_y + 12) . ' LIMIT 144');
while ($pl = mysql_fetch_array($sp)) {
    $objs[$pl['x']][$pl['y']] = $pl;
}
$i = 1;
$goodgoo = [1 => 0, 2 => 0, 3 => 0, 4 => 0];
while ($i <= 4) {
    $goto = ['x' => $user['y'], 'y' => $user['x']];
    if ($i == 1) {
        $goto['x']--;
    } elseif ($i == 2) {
        $goto['y']--;
    } elseif ($i == 3) {
        $goto['x']++;
    } elseif ($i == 4) {
        $goto['y']++;
    }
    if ($map_d[$goto['y']][$goto['x']] == 0 && $goto['x'] > 0 && $goto['x'] < count($map_d) - 1 && $user['timeGo'] <= time()) {
        $goodgoo[$i] = 1;
    }
    $i++;
}
if (isset($_GET['goto'])) {
    $goto = ['x' => $user['y'], 'y' => $user['x']];
    if ($_GET['goto'] == 1) {
        $goto['x']--;
    } elseif ($_GET['goto'] == 2) {
        $goto['y']--;
    } elseif ($_GET['goto'] == 3) {
        $goto['x']++;
    } elseif ($_GET['goto'] == 4) {
        $goto['y']++;
    }

    if ($goodgoo[$_GET['goto']] == 1 && $user['timeGo'] <= time()) {
        $user['y'] = $goto['x'];
        $user['x'] = $goto['y'];
        $real_x = $user['x'];
        $real_y = $user['y'];
        $varos['timego'] = 0; #5
        if (isset($varos['trap1']['id'])) {
            $varos['timego'] += 3;
        }
        if ($user['align'] == 2.99) {
            $varos['timego'] = 0;
        }
        $user['timeGo'] = (time() + $varos['timego']);
        $user['timeGoL'] = time();
        if (!mysql_query('UPDATE `users` SET `x` = "' . $user['x'] . '", `y` = "' . $user['y'] . '", `timeGoL` = "' . $user['timeGoL'] . '", `timeGo` = "' . $user['timeGo'] . '" WHERE `id` = "' . $user['id'] . '" LIMIT 1')) {
            $errors = 'Ошибка перемещения!';
        }
    }
}

$tmdg = ($user['timeGo'] - time());
$tmdgl = ($user['timeGo'] - $user['timeGoL']);
$tmdgp = floor(100 - $tmdg / $tmdgl * 100);
if ($tmdgp < 1) {
    $tmdgp = 1;
} elseif ($tmdgp > 100) {
    $tmdgp = 100;
}
$tmdgm = 25 * $tmdgl;
$tmdg = floor(40 / 100 * $tmdgp);

if ($tmdg < 1) {
    $tmdg = 1;
} elseif ($tmdg > 40) {
    $tmdg = 40;
}

if (isset($_POST['exit'])) {
    if ($lab['users'] < 2) {
        mysql_query('DELETE FROM `laba_now` WHERE `id` = "' . $lab['id'] . '" LIMIT 1');
        mysql_query('DELETE FROM `laba_map` WHERE `id` = "' . $lab['id'] . '" LIMIT 1');
        mysql_query('DELETE FROM `laba_obj` WHERE `lib` = "' . $lab['id'] . '"');
        mysql_query('DELETE FROM `laba_act` WHERE `lib` = "' . $lab['id'] . '"');
        mysql_query('DELETE FROM `laba_itm` WHERE `lib` = "' . $lab['id'] . '"');
    } else {
        $lab['users']--;
        mysql_query('UPDATE `laba_now` SET `users` = "' . $lab['users'] . '" WHERE `id` = "' . $lab['id'] . '" LIMIT 1');
    }
    $dresed = mysql_query('SELECT `id`, `type` FROM `inventory` WHERE `dressed` = 1 AND `laba` = 2 AND `owner` = "' . $user['id'] . '"');
    while ($pl = mysql_fetch_array($dresed)) {
        $item = new DressedItems($user['id']);
        $item->undressItem($pl['type']);
    }
    mysql_query('DELETE FROM `inventory` WHERE `laba` > 0 AND `owner` = "' . $user['id'] . '"');
    mysql_query("UPDATE `users`, `online` SET `users`.`room` = '1051', `online`.`room` = '1051', `users`.`x` = '0', `users`.`y` = '0', `users`.`laba` = '0' WHERE `online`.`id` = `users`.`id` AND `online`.`id` = '" . $user['id'] . "'");
    mysql_query('UPDATE `qst_user` SET `val` = "0" WHERE `uid` = "' . $user['id'] . '" AND `cancel` = "0" AND `finish` = "0"');
    addActions(time(), 'go_labirint', (time() + 60 * 60 * 6), $user['id']);
    header('Location: lab_enter.php');
}

$itms = '';

if (isset($objs[$user['x']][$user['y']]['id'])) {
    $var = [];
    $mitm = $objs[$user['x']][$user['y']];
    if ($mitm['type'] == 2) {
        if ($mitm['use'] == 0) {
            $btl_pix = mysql_fetch_array(mysql_query('SELECT * FROM `users` WHERE `battle` > 0 AND `laba` = "' . $lab['id'] . '" AND `x` = "' . $user['x'] . '" AND `y` = "' . $user['y'] . '" LIMIT 1'));
            if (!isset($btl_pix['id'])) {
                $bots = [
                    0 => [10025, 10026, 10027, 10028, 10031, 10032, 10033, 10034],
                    1 => [10111, 10112, 10113, 10114, 10115, 10116],
                    2 => [10111, 10112, 10113],
                ];
                $bot_pix2 = $bots[$lab['type']];

                $teams = [];
                $where = '';
                $bot_ids = '';
                $i = 0;
                $j = (1 + rand(0, floor($user['level'] / rand(3, 4))));
                while ($i < $j) {
                    $bot_pix = $bot_pix2[rand(0, count($bot_pix2) - 1)];
                    $bot_pix = mysql_fetch_array(mysql_query('SELECT * FROM `users` WHERE `id` = "' . $bot_pix . '" LIMIT 1'));
                    mysql_query("INSERT INTO `bots` (`name`, `prototype`, `battle`, `hp`) VALUES ('" . $bot_pix['login'] . " (Бот #$i)', '" . $bot_pix['id'] . "', '', '" . $bot_pix['maxhp'] . "')");
                    $bot = mysql_insert_id();
                    $bot_ids .= $bot . ';';
                    $teams[$user['id']][$bot] = [0, 0, time()];
                    $teams[$bot][$user['id']] = [0, 0, time()];
                    $where = ' `id` = ' . $bot . ' OR';
                    $i++;
                }
                $bot_ids = rtrim($bot_ids, ';');
                $where = rtrim($where, ' OR');

                if (!mysql_query("INSERT INTO `battle` (`teams`, `timeout`, `type`, `status`, `t1`, `t2`, `to1`, `to2`, `x`, `y`) VALUES ('" . serialize($teams) . "', '3', '1', '0', '" . $user['id'] . "', '" . $bot_ids . "', '" . time() . "', '" . time() . "', '" . $user['x'] . "', '" . $user['y'] . "')")) {
                    exit('Error #2');
                }

                $id = mysql_insert_id();
                $bts = explode(';', $bot_ids);
                $is = 0;
                while ($is <= count($bts)) {
                    $nicks .= Nick::id($bts[$is])->full(1) . ', ';
                    $i_d .= $bts[$is] . ', ';
                    $is++;
                }
                $nicks = rtrim($nicks, ', ');
                $who = '`id` IN (' . rtrim($i_d, ', ') . ')';

                if ($user1['invis'] == 1) {
                    $rr = "<b>невидимка</b> и <b>" . $nicks . "</b>";
                } else {
                    $rr = "<b>" . Nick::id($user['id'])->full(1) . "</b> и <b>" . $nicks . "</b>";
                }

                if (!mysql_query("UPDATE `bots` SET `battle` = {$id} WHERE " . $who . "")) {
                    exit('Error #1' . $who);
                }
                mysql_query("UPDATE `users` SET `battle` = {$id}, `zayavka` = 0 WHERE `id`= {$user['id']} LIMIT 1");
                GameLogs::addBattleLog($id, "Часы показывали <span class=date>" . date("Y.m.d H.i") . "</span>, когда " . $rr . " бросили вызов друг другу.<BR>");
            } else {
                $bd = mysql_fetch_array(mysql_query('SELECT * FROM `battle` WHERE `id` = "' . $btl_pix['battle'] . '" LIMIT 1'));
                $botd = mysql_fetch_array(mysql_query('SELECT * FROM `bots` WHERE `battle` = "' . $bd['id'] . '" LIMIT 1'));
                $battle = unserialize($bd['teams']);
                $ak = array_keys($battle[$botd['id']]);
                $battle[$user['id']] = $battle[$ak[0]];
                foreach ($battle[$user['id']] as $k => $v) {
                    $battle[$user['id']][$k] = [0, 0, time()];
                    $battle[$k][$user['id']] = [0, 0, time()];
                }
                $t1 = explode(";", $bd['t1']);
                $ttt = 1;
                GameLogs::addBattleLog($jert['battle'], '<span class=date>' . date("H:i") . '</span> ' . Nick::id($user['id'])->short() . ' вмешался в поединок!<BR>');
                mysql_query('UPDATE `battle` SET `teams` = \'' . serialize($battle) . '\', `t' . $ttt . '` = CONCAT(`t' . $ttt . '`,\';' . $user['id'] . '\')  WHERE `id` = "' . $btl_pix['battle'] . '" LIMIT 1');
                mysql_query("UPDATE `users` SET `battle` = '" . $bd['id'] . "', `zayavka` = 0 WHERE `id` = '" . $user['id'] . "' LIMIT 1");
                header("Location: fbattle.php");
            }
            exit("<script>location.href='fbattle.php';</script>");
        }
    } elseif ($mitm['type'] == 1) {
        if ($mitm['use'] == 0) {
            $itms .= '<hr /><a title="Открыть" href="labirint.php?useobj=' . $mitm['id'] . '"><img src="/i/sh/use_sunduk_on.gif" width="60" height="60" /></a>';
        } else {
            $itms .= '<hr /><img title="Сундук был открыт" src="/i/sh/use_sunduk_off.gif" width="60" height="60" />';
        }
    } elseif ($mitm['type'] == 3) {
        if ($mitm['use'] == 0) {
            $itms .= '<hr /><a title="Выпить" href="labirint.php?useobj=' . $mitm['id'] . '"><img src="/i/sh/use_heal_on.gif" width="60" height="60" /></a>';
        } else {
            $itms .= '<hr /><img title="Эликсир был выпит" src="/i/sh/openHeal.gif" width="60" height="60" />';
        }
    } elseif ($mitm['type'] == 4) {
        if ($mitm['use'] == 0) {
            $var['trap1'] = mysql_fetch_array(mysql_query('SELECT `id`, `vals`, `time` FROM `laba_act` WHERE `uid` = "' . $user['id'] . '" AND `lib` = "' . $lab['id'] . '" AND `time` > "' . time() . '" ORDER BY `time` DESC LIMIT 1'));
            $var['time'] = rand(1, 60);
            if (isset($var['trap1']['id'])) {
                mysql_query('UPDATE `laba_act` SET `vals` = "' . ($var['trap1']['vals'] + $var['time']) . '", `time` = "' . ($var['trap1']['time'] + $var['time'] * 60) . '" WHERE `id` = "' . $var['trap1']['id'] . '" LIMIT 1');
            } else {
                mysql_query('INSERT INTO `laba_act` (`uid`, `time`, `lib`, `vars`, `vals`) VALUES ("' . $user['id'] . '", "' . (time() + $var['time'] * 60) . '", "' . $lab['id'] . '", "trap1", "' . $var['time'] . '")');
            }
            $mitm['use'] = $user['id'];
            mysql_query('UPDATE `laba_obj` SET `use` = "' . $mitm['use'] . '" WHERE `id` = "' . $mitm['id'] . '" LIMIT 1');
            $var['sex'] = '';
            if ($user['sex'] == 0) {
                $var['sex'] = 'а';
            }
            $var['text'] = '<img width=40 height=25 src=/i/sh/event_timer_trap.gif /> <b>' . $user['login'] . '</b> угодил' . $var['sex'] . ' в ловушку...';
            $varos['trap1'] = mysql_fetch_array(mysql_query('SELECT `vals`, `time` FROM `laba_act` WHERE `uid` = "' . $user['id'] . '" AND `lib` = "' . $lab['id'] . '" AND `time` > "' . time() . '" ORDER BY `time` DESC LIMIT 1'));
            $errors .= '<img width="40" height="25" src="/i/sh/event_timer_trap.gif" /> ' . $user['login'] . ' угодил' . $var['sex'] . ' в ловушку... Время перехода +3 секунды (Длительность: +' . $var['time'] . ' мин.)';
        }
    } elseif ($mitm['type'] == 5) {
        if ($mitm['use'] == 0) {
            $itms .= '<hr /><a title="Открыть" href="labirint.php?useobj=' . $mitm['id'] . '"><img src="/i/sh/panbox_on.gif" width="60" height="60" /></a>';
        } else {
            $itms .= '<hr /><img title="Сундук был открыт" src="/i/sh/panbox_off.gif" width="60" height="60" />';
        }
    } elseif ($mitm['type'] == 6) {
        if ($mitm['use'] == 0) {
            $itms .= '<hr /><a title="Использовать" href="labirint.php?useobj=' . $mitm['id'] . '"><img src="/i/sh/event_timer_trap_out.png" width="40" height="25" /></a>';
        } else {
            $itms .= '<hr /><img title="Недоступно" src="/i/sh/event_timer_trap_out.png" width="40" height="25" />';
        }
    }
    unset($var);
}

if ($user['y'] >= count($map_d) - 2) {
    if ($lab['users'] < 2) {
        mysql_query('DELETE FROM `laba_now` WHERE `id` = "' . $lab['id'] . '" LIMIT 1');
        mysql_query('DELETE FROM `laba_map` WHERE `id` = "' . $lab['id'] . '" LIMIT 1');
        mysql_query('DELETE FROM `laba_obj` WHERE `lib` = "' . $lab['id'] . '"');
        mysql_query('DELETE FROM `laba_act` WHERE `lib` = "' . $lab['id'] . '"');
        mysql_query('DELETE FROM `laba_itm` WHERE `lib` = "' . $lab['id'] . '"');
    } else {
        $lab['users']--;
        mysql_query('UPDATE `laba_now` SET `users` = "' . $lab['users'] . '" WHERE `id` = "' . $lab['id'] . '" LIMIT 1');
    }
    $dresed = mysql_query('SELECT `id`, `type` FROM `inventory` WHERE `dressed` = 1 AND `laba` = 2 AND `owner` = "' . $user['id'] . '"');
    while ($pl = mysql_fetch_array($dresed)) {
        $item = new DressedItems($user['id']);
        $item->undressItem($pl['type']);
    }
    mysql_query('UPDATE `inventory` SET `laba` = 0 WHERE `laba` = 1 AND `owner` = "' . $user['id'] . '"');
    mysql_query('DELETE FROM `inventory` WHERE `laba` = 2 AND `owner` = "' . $user['id'] . '"');
    mysql_query("UPDATE `users`, `online` SET `users`.`room` = '1051', `online`.`room` = '1051', `users`.`x` = '0', `users`.`y` = '0', `users`.`laba` = '0' WHERE `online`.`id` = `users`.`id` AND `online`.`id` = '" . $user['id'] . "'");
    addActions(time(), 'go_labirint', (time() + 60 * 60 * 6), $user['id']);
    header('Location: lab_enter.php');
}

if (isset($_GET['takeitm'])) {
    $errors = '<font color=red><b>Предмет не найден...</b></font>';
} elseif (isset($_GET['useobj'])) {
    $var = ['obj' => mysql_fetch_array(mysql_query('SELECT * FROM `laba_obj` WHERE `id` = "' . mysql_real_escape_string($_GET['useobj']) . '" AND `lib` = "' . $lab['id'] . '" AND `x` = "' . $user['x'] . '" AND `y` = "' . $user['y'] . '" LIMIT 1'))];
    if (isset($var['obj']['id'])) {
        if ($var['obj']['use'] == 0) {
            if ($var['obj']['type'] == 1) {
                $var['sex'] = '';
                if ($user['sex'] == 0) {
                    $var['sex'] = 'а';
                }
                $var['itm'] = $varsitm[rand(0, count($varsitm) - 1)];
                $var['itm'] = $var['itm'][0];
                $var['itm'] = mysql_fetch_array(mysql_query('SELECT `id`, `name` FROM `shop` WHERE `id` = "' . $var['itm'] . '" LIMIT 1'));
                if (isset($var['itm']['id'])) {
                    if ($var['itm']['id'] == 270) {
                        $arr = [0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2];
                        $kr = $arr[rand(0, count($arr) - 1)];
                        $var['itm']['name'] = $kr . ' кр';
                        money_add($kr);
                        unset($kr);
                    } else {
                        labaItemAdd($var['itm']['id']);
                    }
                } else {
                    $var['itm']['name'] = 'Предмет рассыпался на глазах...';
                }
                $errors .= '<img width="40" height="25" src="/i/sh/event_sunduk.gif" /> ' . $user['login'] . ' открыл' . $var['sex'] . ' сундук...и забрал &quot;' . $var['itm']['name'] . '&quot;';
                $var['obj']['use'] = $user['id'];
            } elseif ($var['obj']['type'] == 5) {
                $var['sex'] = '';
                if ($user['sex'] == 0) {
                    $var['sex'] = 'а';
                }

                $errors .= '<img width="40" height="25" src="/i/sh/event_pandbox.gif" /> ' . $user['login'] . ' открыл' . $var['sex'] . ' Ящик Пандоры...и забрал &quot;' . $var['itm']['name'] . '&quot;';
                $var['obj']['use'] = $user['id'];
            } elseif ($var['obj']['type'] == 3) {
                $var['sex'] = '';
                if ($user['sex'] == 0) {
                    $var['sex'] = 'а';
                }
                $var['hpp'] = rand(2, 5) * 10;
                $var['hp'] = round($user['maxhp'] / 100 * $var['hpp']);
                $user['hp'] += $var['hp'];
                if ($user['hp'] > $user['maxhp']) {
                    $user['hp'] = $user['maxhp'];
                }
                mysql_query('UPDATE `users` SET `hp` = "' . $user['hp'] . '" WHERE `id` = "' . $user['id'] . '" LIMIT 1');
                $errors .= '<img width="40" height="25" src="/i/sh/event_heal.gif" /> ' . $user['login'] . ' пополнил' . $var['sex'] . ' здоровье, Уровень Жизни +' . $var['hpp'] . '% (+' . $var['hp'] . 'HP)';
                $var['obj']['use'] = $user['id'];
            } elseif ($var['obj']['type'] == 6) {
                $var['trap1'] = mysql_fetch_array(mysql_query('SELECT `id`, `vals`, `time` FROM `laba_act` WHERE `uid` = "' . $user['id'] . '" AND `lib` = "' . $lab['id'] . '" AND `time` > "' . time() . '" ORDER BY `time` DESC LIMIT 1'));
                if (isset($var['trap1']['id'])) {
                    $var['time'] = rand(1, 50);
                    if ($var['trap1']['time'] <= (time() + 60 * $var['time'])) {
                        mysql_query('DELETE FROM `laba_act` WHERE `uid` = "' . $user['id'] . '" AND `lib` = "' . $lab['id'] . '" AND `time` > "' . time() . '" ORDER BY `time` DESC LIMIT 1');
                        $errors .= '<hr /><b style=\'color: Red;\'>Действие ловушки закончилось.</b>';
                        unset($var['trap1'], $var['time']);
                    } else {
                        $var['trap1']['time'] -= 60 * $var['time'];
                        mysql_query('UPDATE `laba_act` SET `time` = "' . $var['trap1']['time'] . '" WHERE `uid` = "' . $user['id'] . '" AND `lib` = "' . $lab['id'] . '" AND `time` > "' . time() . '" ORDER BY `time` DESC LIMIT 1');
                        $errors = '<hr /><b style=\'color: Red;\'>Действие ловушки снижено на ' . $var['time'] . ' мин...</b>';
                    }
                    $var['obj']['use'] = $user['id'];
                } else {
                    $errors .= '<hr /><b style=\'color: Red;\'>Вам нечего очищать ...</b>';
                }
            }
            if ($var['obj']['use'] > 0) {
                mysql_query('UPDATE `laba_obj` SET `use` = "' . $var['obj']['use'] . '" WHERE `id` = "' . $var['obj']['id'] . '" LIMIT 1');
                #$var['obj']['use'] = $var['obj']['use']; ?!?!?!?!?!
            }
        } else {
            $errors = '<font color=red><b>Кто-то уже использовал это до Вас...</b></font>';
        }
    } else {
        $errors = '<font color=red><b>Обьект не найден...</b></font>';
    }
    unset($var);
}

$sp = mysql_query('SELECT `x`, `y`, `level`, `login` FROM `users` WHERE `laba` = "' . $lab['id'] . '" AND `id` != "' . $user['id'] . '" LIMIT 3');
$pi = 1;
while ($pl = mysql_fetch_array($sp)) {
    $objs[$pl['x']][$pl['y']] = [2 => '<div title="Игрок : ' . $pl['login'] . '" class="ddp1ee' . $pi . '"></div>'];
    $pi++;
}

$objs[$user['x']][$user['y']] = [2 => '<div title="Я" class="ddp1me"></div>'];
$i = 0;
while ($i <= count($map_d)) {
    $j = 0;
    while ($j < count($map_d[$i])) {
        if ($i > $real_x - 6 && $i < $real_x + 6 && $j > $real_y - 6 && $j < $real_y + 6) {
            if ($map_d[$i][$j] == 1) {
                $mapsee .= '<div class="ddp1">' . $objs[$i][$j][2] . '</div>';
            } else {
                if (!isset($objs[$i][$j]['id'])) {
                    if ($j == 1) {
                        $objs[$i][$j][2] = '<div title="Вход в лабиринты" class="ddpStart"></div>';
                    } elseif ($j == count($map_d) - 2) {
                        $objs[$i][$j][2] = '<div title="Выход из лабиринов" class="ddpExit"></div>';
                    }
                } else {
                    if ($objs[$i][$j]['use'] == 0) {
                        $objs[$i][$j][2] = '<div class="' . $objs[$i][$j]['img'] . '"></div>';
                    } else {
                        $objs[$i][$j][2] = '';
                    }
                }
                $mapsee .= '<div class="ddp0">' . $objs[$i][$j][2] . '</div>';
            }
        }
        $j++;
    }
    if ($i > $real_x - 6 && $i < $real_x + 6) {
        $mapsee .= '<br />';
    }
    $i++;
}
$mapsee = '<div style="width: 165px; height: 165px; padding: 10px;">' . $mapsee . '</div>';

if ($user['align'] == 2.99) {
    unset($objs);
    $objs[$user['x']][$user['y']] = [2 => '<div title="Я" class="ddp1me"></div>'];
    $i = 0;
    while ($i <= count($map_d)) {
        $j = 0;
        while ($j < count($map_d[$i])) {
            if ($map_d[$i][$j] == 1) {
                $mapsee2 .= '<div class="ddp1">' . $objs[$i][$j][2] . '</div>';
            } else {
                if (!isset($objs[$i][$j]['id'])) {
                    if ($j == 1 && $i > 0 && $i < count($map_d) - 2) {
                        $objs[$i][$j][2] = '<div title="Вход в лабиринты" class="ddpStart"></div>';
                    } elseif ($j == count($map_d) - 2 && $i > 0 && $i < count($map_d) - 2) {
                        $objs[$i][$j][2] = '<div title="Выход из лабиринтов" class="ddpExit"></div>';
                    }
                } else {
                    if ($objs[$i][$j]['use'] == 0) {
                        $objs[$i][$j][2] = '<div class="' . $objs[$i][$j]['img'] . '"></div>';
                    } else {
                        $objs[$i][$j][2] = '';
                    }
                }
                $mapsee2 .= '<div class="ddp0">' . $objs[$i][$j][2] . '</div>';
            }
            $j++;
        }
        $mapsee2 .= '<br />';
        $i++;
    }
    $mapsee2 = '<div>' . $mapsee2 . '</div>';
}

if (isset($varos['trap1']['vals']) && $varos['trap1']['vals'] > 0) {
    $effed .= '<div><img width="40" height="25" src="/i/sh/event_timer_trap.gif" /> - Время перехода +3 секунды (Осталось : ' . timeOut($varos['trap1']['time'] - time()) . ')</div>';
}
unset($varos);
Template::header('labirint');
?>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
    $('body').keydown(function (event) {
        if (event.which == 38 || event.which == 87) {
            location.href = "labirint.php?goto=2";
        } else if (event.which == 37 || event.which == 65) {
            location.href = "labirint.php?goto=1";
        } else if (event.which == 39 || event.which == 68) {
            location.href = "labirint.php?goto=3";
        } else if (event.which == 40 || event.which == 83) {
            location.href = "labirint.php?goto=4";
        }
    });

    const update = true;
    $('body').keydown(function (event) {
        if (event.which == 37 || event.which == 65) {
            if (update == true) {
                GoAJAX('labirint.php?goto=1');
            }
        } else if (event.which == 38 || event.which == 87) {
            if (update == true) {
                GoAJAX('labirint.php?goto=2');
            }
        } else if (event.which == 39 || event.which == 68) {
            if (update == true) {
                GoAJAX('labirint.php?goto=3');
            }
        } else if (event.which == 40 || event.which == 83) {
            if (update == true) {
                GoAJAX('labirint.php?goto=4');
            }
        } else if (event.which == 13) {
            if ($('#useobjInp')) {
                GoAJAX('labirint.php?useobj=' + $('#useobjInp').val());
            }
        }
    });

    const delay = 30;
    let TimerOn = -1, tkHP, maxHP, speed = 750;
    const stLen = 185, redHP = 0.33, yellowHP = 0.66;

    function setHP(a, b, c) {
        tkHP = a;
        maxHP = b;
        TimerOn >= 0 && (clearTimeout(TimerOn), TimerOn = -1);
        speed = c;
        setHPlocal()
    }

    function setHPlocal() {
        tkHP > maxHP && (tkHP = maxHP);
        var a = Math.round(tkHP) + "/" + maxHP, a = stLen - (a.length + 2) * 7,
            b = Math.round((a - 1) / maxHP * tkHP);
        a -= b;
        HP = document.getElementById("hp_value");
        HP1 = document.getElementById("HP1");
        HP2 = document.getElementById("HP2");
        if (HP) HP1.width = b, HP2.width = a, HP1.src = tkHP / maxHP < redHP ? "i/1red.gif" : tkHP / maxHP < yellowHP ? "i/1yellow.gif" : "i/1green.gif",
            HP.innerHTML = Math.round(tkHP) + "/" + maxHP;
        tkHP += maxHP / 53 / 20 * (speed / 100);
        TimerOn = tkHP < maxHP ? setTimeout("setHPlocal()", delay * 100) : -1
    }

    function GoAJAX(goLink) {
        $.ajax({
            url: goLink + '&ajax=true',
            cache: false,
            type: "GET",
            dataType: "html",
            success: function (html) {
                $('#ViewLab').html(html);
            }
        });
    }

    function confirmSubmit(mes) {
        const agree = confirm(mes);
        return agree;
    }
</script>
<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#E2E0E0">
    <tbody>
    <tr>
        <td></td>
        <td width="307"></td>
        <td width="300"></td>
    </tr>
    <tr>
        <td height="409" valign="top">
            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                <tbody>
                <tr>
                    <td width="5">&nbsp;</td>
                    <td width="99%">
                        <script language="javascript" type="text/javascript">
                            function confirmSubmit(mes) {
                                const agree = confirm(mes);
                                return agree;
                            }
                        </script>
                        <script language=javascript>
                            <!--
                            const message = "Правая кнопка мыши отключена!";

                            function click(e) {
                                if (document.all) { // IE
                                    if (event.button === 2) { // Чтобы отключить левую кнопку поставьте цифру 1
                                        alert(message); // чтобы отключить среднюю кнопку поставьте цифру 1
                                        return false;
                                    }
                                }
                                if (document.layers) { // NC
                                    if (e.which == 3) {
                                        alert(message);
                                        return false;
                                    }
                                }
                            }

                            if (document.layers) {
                                document.captureEvents(Event.MOUSEDOWN);
                            }
                            document.onmousedown = click;
                            document.oncontextmenu = function (e) {
                                return false
                            };
                            //-->
                        </script>
                        <br/>
                        <form method="post">
                            <div>
                                <b><?= $user['login']; ?></b> <?= $usersDng ?>
                                <hr/>
                            </div>
                            <input type="submit" name="exit" value="Выйти и потерять все найденное!"
                                   onclick="return confirmSubmit('Действительно хотите Выйти и потерять все найденное?')"/>
                        </form>
                        <br/>
                        <? if ($effed != '') {
                            echo $effed;
                        } ?>
                        <br/>
                        <?
                        if ($dies > 0) {
                            echo '<b>Кол-во смертей : ' . $dies . '/3</b><br />';
                        }
                        ?>
                        Карта : #<?= $lab['id'] ?>. Координаты : {X = <?= $user['x'] ?> | Y = <?= $user['y'] ?>}
                        <br/></td>
                    <td width="5">&nbsp;</td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td>
                        <?
                        if (isset($q1['id'])) {
                            echo '<b>Задание:</b> ' . $q1['name'] . '<br />&bull; ';
                            if ($q1['type'] == 1) {
                                echo 'Собрать ресурсы: ';
                                $qobj = mysql_fetch_array(mysql_query('SELECT * FROM `shop` WHERE `id` = "' . $q1['obj_id'] . '" LIMIT 1'));

                                $qobj_f = mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM `inventory` WHERE `owner` = "' . $user['id'] . '" AND  "name" = "' . $qobj['obj_id'] . '" LIMIT 1'));
                                if ($q2['val'] != $qobj[0]) {
                                    mysql_query('UPDATE `qst_user` SET `val` = "' . $qobj[0] . '" WHERE `id` = "' . $q2['id'] . '" LIMIT 1');
                                    $q2['val'] = $qobj[0];
                                }
                                echo '<b>' . $qobj['name'] . '</b> &nbsp;';
                            } elseif ($q1['type'] == 2) {
                                echo 'Собрать трофеи: ';
                                $qobj = mysql_fetch_array(mysql_query('SELECT * FROM `shop` WHERE `id` = "' . $q1['obj_id'] . '" LIMIT 1'));
                                $qobj_f = mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM `inventory` WHERE `owner` = "' . $user['id'] . '" AND  "name" = "' . $qobj['obj_id'] . '" LIMIT 1'));

                                echo '<b>' . $qobj['name'] . '</b>';
                                $qobj = mysql_fetch_array(mysql_query('SELECT * FROM `users` WHERE `id` = "' . $q1['obj_id'] . '" LIMIT 1'));
                                if ($q2['val'] != $qobj[0]) {
                                    mysql_query('UPDATE `qst_user` SET `val` = "' . $qobj[0] . '" WHERE `id` = "' . $q2['id'] . '" LIMIT 1');
                                    $q2['val'] = $qobj[0];
                                }
                                echo ' c монстров <b>' . $qobj['name'] . '</b> &nbsp;';
                            } elseif ($q1['type'] == 3) {
                                echo 'Убить монстров: ';
                                $qobj = mysql_fetch_array(mysql_query('SELECT * FROM `users` WHERE `id` = "' . $q1['obj_id'] . '" LIMIT 1'));
                                echo '<b>' . $qobj['login'] . '</b> [' . $qobj['level'] . '] &nbsp;';
                            }
                            echo '[' . $q2['val'] . '/' . $q1['obj_val'] . ']<br />';
                            echo '<small>(Задание не засчитается, если Вы не найдёте выход.)</small>';
                        }
                        ?>
                    </td>
                    <td>&nbsp;</td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td><? if ($errors != '') {
                            echo $errors . '<br />';
                        } ?>
                        <?= $itms ?>
                        <?
                        if ($user['align'] == 2.99) {
                            echo '<hr />' . $mapsee2;
                        }
                        ?>
                    </td>
                    <td>&nbsp;</td>
                </tr>
                </tbody>
            </table>
        </td>
        <td style="background-repeat:repeat; width:300px; height:410px" align="right">&nbsp;</td>
        <td height="409" width="300" valign="top" align="center">
            <table width="100%" height="396" border="0" cellpadding="0" cellspacing="0"
                   style="background-position: top right; background-repeat: no-repeat; width: 300px; height: 410px; background: url('i/laba/navbg_big.gif'); ">
                <tbody>
                <tr>
                    <td height="34">
                        <table align="center" height="25" border="0"
                               style="background:url(i/laba/ramka_s2.gif); background-repeat:no-repeat; background-position:left;">
                            <tbody>
                            <tr valign="middle">
                                <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
                                <td>
                                    <div id="showbar"
                                         style="font-size: 2pt; padding: 2px; border: 0 solid black; visibility: visible;">
                                        <span id="progress1" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress2" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress3" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress4" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress5" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress6" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress7" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress8" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress9" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress10" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress11" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress12" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress13" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress14" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress15" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress16" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress17" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress18" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress19" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress20" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress21" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress22" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress23" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress24" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress25" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress26" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress27" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress28" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress29" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress30" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress31" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress32" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress33" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress34" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress35" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress36" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress37" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress38" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress39" style="background-color: green;">&nbsp;&nbsp;</span>
                                        <span id="progress40" style="background-color: green;">&nbsp;&nbsp;</span>
                                    </div>
                                </td>
                                <td>&nbsp;&nbsp;</td>
                            </tr>
                            </tbody>
                        </table>
                        <script language="javascript">
                            const progressEnd = 40; // set to number of progress <span>'s.
                            const progressColor = 'green'; // set to progress bar color
                            let progressInterval =;
                            let progressAt =;
                            let progressTimer;


                            function progress_set(too) {
                                for (let i = 1; i <= too; i++) document.getElementById('progress' + i).style.backgroundColor = progressColor;
                            }

                            function progress_none() {
                                for (let i = 1; i <= 40; i++) document.getElementById('progress' + i).style.backgroundColor = progressColor;
                            }

                            function progress_clear() {
                                for (let i = <?=$tmdg?>; i <= progressEnd; i++) document.getElementById('progress' + i).style.backgroundColor = 'transparent';
                                progressAt = <?=$tmdg?>;
                            }

                            function progress_update() {
                                document.getElementById('showbar').style.visibility = 'visible';
                                progressAt++;
                                if (progressAt > progressEnd) {
                                    clearTimeout(progressTimer);
                                    return;
                                } else document.getElementById('progress' + progressAt).style.backgroundColor = progressColor;
                                progressTimer = setTimeout('progress_update()', progressInterval);
                            }


                            progress_clear();
                            progress_set(<?=$tmdg?>);
                            progress_update();
                        </script>
                        <div align="right">&nbsp;</div>
                    </td>
                </tr>
                <tr>
                    <td height="17"></td>
                </tr>
                <tr>
                    <td height="102" valign="top" align="center">
                        <table width="100%" height="102" border="0" cellpadding="0" cellspacing="0">
                            <tbody>
                            <tr>
                                <td width="95" height="102"></td>
                                <td width="103"
                                    style="background:url(i/laba/in_nav_bg.gif); width:103px; height:102px; background-repeat: no-repeat;">
                                    <table width="103" height="102" border="0" cellspacing="0" cellpadding="0">
                                        <tbody>
                                        <tr>
                                            <td width="26" height="26"></td>
                                            <td width="12"></td>
                                            <td width="26" height="26"><a href="labirint.php?goto=2"><img
                                                            src="i/laba/arr1.gif" border="0" title="Вверх"
                                                            alt="Вверх"/></a></td>
                                            <td width="13"></td>
                                            <td width="26"></td>
                                        </tr>
                                        <tr>
                                            <td></td>
                                            <td></td>
                                            <td height="11"></td>
                                            <td></td>
                                            <td></td>
                                        </tr>
                                        <tr>
                                            <td width="26" height="26"><a href="labirint.php?goto=1"><img
                                                            src="i/laba/arr4.gif" border="0" title="Влево"
                                                            alt="Влево"/></a></td>
                                            <td></td>
                                            <td width="26" height="26"><a href="labirint.php?refresh"><img
                                                            src="i/laba/refresh.gif" border="0" title="Обновить"
                                                            alt="Обновить"/></a></td>
                                            <td></td>
                                            <td width="26" height="26"><a href="labirint.php?goto=3"><img
                                                            src="i/laba/arr2.gif" border="0" title="Вправо"
                                                            alt="Вправо"/></a></td>
                                        </tr>
                                        <tr>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                        </tr>
                                        <tr>
                                            <td height="13"></td>
                                            <td height="13"></td>
                                            <td height="13"></td>
                                            <td height="13"></td>
                                            <td height="13"></td>
                                        </tr>
                                        <tr>
                                            <td></td>
                                            <td></td>
                                            <td width="26" height="26"><a href="labirint.php?goto=4"><img
                                                            src="i/laba/arr3.gif" border="0" title="Вниз"
                                                            alt="Вниз"/></a></td>
                                            <td></td>
                                            <td></td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </td>
                                <td width="105" height="5"></td>
                            </tr>
                            </tbody>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td height="5"></td>
                </tr>
                <tr valign="top">
                    <td height="165">
                        <table width="303" height="165" border="0" cellpadding="0" cellspacing="0">
                            <tbody>
                            <tr>
                                <td width="67" height="74"></td>
                                <td width="165" height="165">
                                    <div>
                                        <?
                                        echo $mapsee;
                                        ?>
                                    </div>
                                </td>
                                <td width="64"></td>
                            </tr>
                            </tbody>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td height="25"></td>
                </tr>
                <tr>
                    <td height="25"></td>
                </tr>
                </tbody>
            </table>
        </td>
    </tr>
    </tbody>
</table>