<?php

use Battles\Template;

require_once "functions.php";
$in_park = mysql_fetch_array(mysql_query("SELECT * FROM `cit_park` WHERE `id` = '{$user['id']}' LIMIT 1;"));
$owntravma = mysql_fetch_array(mysql_query("SELECT * FROM `effects` WHERE `owner` = " . $user['id'] . " AND (type=13 OR type=12 OR  type=14) limit 1;"));

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

//комнаты парка
$ch_rooms = [
    // 0 - empty
    "1" => "Площадь (1)",
    "2" => "Аллея Геры (2)",
    "3" => "Фонтан Снов (3)",
    "4" => "Лабиринт Фавна (4)",
    "5" => "Поляна Сказок (5)",//босс Душа
    "6" => "Переулок Зеленый (6)",
    "7" => "Дубрава (7)",
    "8" => "Старая Роща (8)",
    "9" => "Лукоморье (9)",
    "10" => "Золотая Роща (10)",//босс Зомби
    "11" => "Вечная Осень (11)",
    "12" => "Заливные Луга (12)",
    "13" => "Терра Нова (13)",
    "14" => "Гора Райдинг (14)",
    "15" => "Пасифик-Риф (15)"//босс Повелитель
];

// выдаем ботов

$ch_bots = [];
$bot_low = ["4150", "4152", "4153", "4154", "4155", "4156"];
$bot_high = ["4157", "4158", "4159"];
if ($in_park['bots'] == '') {
    for ($i = 1; $i <= 15; $i++) {
        $rand_num = rand(3, 7);
        $rand_bot = '';
        for ($j = 1; $j <= $rand_num; $j++) {
            $rand_bot .= $bot_low[array_rand($bot_low, 1)];
            $rand_bot .= ';';
        }
        if ($i % 5 == 0) {
            $rand_bot .= $bot_high[array_rand($bot_high, 1)];
        }
        $rand_bot .= ';';

        $ch_bots[$i] = $rand_bot;
    }
    $dbb = serialize($ch_bots);
    mysql_query("UPDATE `cit_park` SET bots='{$dbb}' WHERE `id`='{$user['id']}'; ");
} else {
    $ch_bots = unserialize($in_park['bots']);
}

// начинаем расчет действий

if ($_POST['start_raid']) {
    mysql_query("UPDATE `cit_park` SET `counter`=`counter`+1, `room`=`room`+1 WHERE `id`='{$user['id']}';");
    $in_park = mysql_fetch_array(mysql_query("SELECT * FROM `cit_park` WHERE `id` = '{$user['id']}' LIMIT 1;"));
}

//старт боя - началоа

if ($_POST['attack']) {
    $bots_raw = explode(";", $ch_bots[$in_park['room']]);
    $bots = [];
    foreach ($bots_raw as $bot_id) {
        if ($bot_id > 0) {
            $b_pers = mysql_fetch_array(mysql_query("SELECT `login`,`maxhp` FROM users WHERE id='{$bot_id}' LIMIT 1;"));
            $bot_hp = $b_pers['maxhp'];
            $bot_name = $b_pers['login'];
            $nb = mysql_fetch_array(mysql_query("SELECT count(`id`) FROM `bots` WHERE `name` LIKE '" . $bot_name . "%';"));
            mysql_query("INSERT INTO `bots` (`name`,`prototype`,`battle`,`hp`) values ('" . $bot_name . " " . ($nb[0] + 1) . "','" . $bot_id . "','','" . $bot_hp . "');");
            $bots[] = mysql_insert_id();
        }
    }

    $teams = [];
    foreach ($bots as $b) {
        $teams[$user['id']][$b] = [0, 0, time()];
        $teams[$b][$user['id']] = [0, 0, time()];
    }

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

    $id = mysql_insert_id();
    foreach ($bots as $b) {
        mysql_query("UPDATE `bots` SET `battle` = {$id} WHERE `id` = {$b} LIMIT 1;");
    }
    mysql_query("UPDATE users SET `battle` ={$id},`zayavka`=0 WHERE `id`= {$user['id']};");

    addchp('<font color=red>Внимание!</font> Вы вступили в бой c бандитами!', '{[]}' . Nick::id($user['id'])->short() . '{[]}');

    exit("<script>location.href='fbattle.php';</script>");
}


//старт боя - конец
Template::header('Городской Парк');
?>
    <script>
        function refreshPeriodic() {
            location.href = 'c_park.php';//reload()
            timerID = setTimeout("refreshPeriodic()", 30000);
        }

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

    <tr>
        <td><h3>Городской Парк</td>
    </tr>
    <?php
    if ($in_park['room'] == 0 || $in_park['room'] >= 15) {
        echo '<tr><td>Вы стоите на парковой площади</strong></td></tr>';
        echo "<tr><td>За сегодня Вы посетили парк <b>" . $in_park['counter'] . "/3</b> раз.</td></tr>";
        if ($in_park['room'] == 15) {
            echo "<tr><td>Вы вышли из парка с чувством глубокого удовлетворения...</td></tr>";
            //раздача гаек
            $dress = mysql_fetch_array(mysql_query("SELECT * FROM `shop` WHERE `id` = '856' LIMIT 1;"));
            $gadget_num = mt_rand(1, 8);
            for ($i = 0; $i < $gadget_num; $i++) {
                mysql_query("INSERT INTO `inventory`
				(`prototype`,`owner`,`name`,`type`,`massa`,`cost`,`img`,`maxdur`,`isrep`,
					`gsila`,`glovk`,`ginta`,`gintel`,`ghp`,`gnoj`,`gtopor`,`gdubina`,`gmech`,`gfire`,`gwater`,`gair`,`gearth`,`glight`,`ggray`,`gdark`,`needident`,`nsila`,`nlovk`,`ninta`,`nintel`,`nmudra`,`nvinos`,`nnoj`,`ntopor`,`ndubina`,`nmech`,`nfire`,`nwater`,`nair`,`nearth`,`nlight`,`ngray`,`ndark`,
					`mfkrit`,`mfakrit`,`mfuvorot`,`mfauvorot`,`bron1`,`bron2`,`bron3`,`bron4`,`maxu`,`minu`,`magic`,`nlevel`,`nalign`,`dategoden`,`goden`,`otdel`,`gmp`,`gmeshok`,`encicl`,`artefact`,`duration`
				)
				VALUES
				('{$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['bron3']}','{$dress['bron2']}','{$dress['bron4']}','{$dress['maxu']}','{$dress['minu']}','{$dress['magic']}','{$dress['nlevel']}','{$dress['nalign']}','" . (($dress['goden']) ? ($dress['goden'] * 24 * 60 * 60 + time()) : "") . "','{$dress['goden']}','{$dress['razdel']}','{$dress['gmp']}','{$dress['gmeshok']}','{$dress['encicl']}','{$dress['artefact']}','0'
				) ;");
            }
            //раздача страничек
            $dress = mysql_fetch_array(mysql_query("SELECT * FROM `shop` WHERE `id` = '867' LIMIT 1;"));
            $gadget_num = mt_rand(1, 5);
            for ($i = 0; $i < $gadget_num; $i++) {
                mysql_query("INSERT INTO `inventory`
				(`prototype`,`owner`,`name`,`type`,`massa`,`cost`,`img`,`maxdur`,`isrep`,
					`gsila`,`glovk`,`ginta`,`gintel`,`ghp`,`gnoj`,`gtopor`,`gdubina`,`gmech`,`gfire`,`gwater`,`gair`,`gearth`,`glight`,`ggray`,`gdark`,`needident`,`nsila`,`nlovk`,`ninta`,`nintel`,`nmudra`,`nvinos`,`nnoj`,`ntopor`,`ndubina`,`nmech`,`nfire`,`nwater`,`nair`,`nearth`,`nlight`,`ngray`,`ndark`,
					`mfkrit`,`mfakrit`,`mfuvorot`,`mfauvorot`,`bron1`,`bron2`,`bron3`,`bron4`,`maxu`,`minu`,`magic`,`nlevel`,`nalign`,`dategoden`,`goden`,`otdel`,`gmp`,`gmeshok`,`encicl`,`artefact`,`duration`
				)
				VALUES
				('{$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['bron3']}','{$dress['bron2']}','{$dress['bron4']}','{$dress['maxu']}','{$dress['minu']}','{$dress['magic']}','{$dress['nlevel']}','{$dress['nalign']}','" . (($dress['goden']) ? ($dress['goden'] * 24 * 60 * 60 + time()) : "") . "','{$dress['goden']}','{$dress['razdel']}','{$dress['gmp']}','{$dress['gmeshok']}','{$dress['encicl']}','{$dress['artefact']}','0'
				) ;");
            }
            //раздача ингридиентов
            $ing_list = ["859", "860", "861", "862", "863", "864", "865"];
            $ing_id = $ing_list[array_rand($ing_list)];
            $dress = mysql_fetch_array(mysql_query("SELECT * FROM `shop` WHERE `id` = '{$ing_id}' LIMIT 1;"));
            $gadget_num = mt_rand(1, 3);
            for ($i = 0; $i < $gadget_num; $i++) {
                mysql_query("INSERT INTO `inventory`
				(`prototype`,`owner`,`name`,`type`,`massa`,`cost`,`img`,`maxdur`,`isrep`,
					`gsila`,`glovk`,`ginta`,`gintel`,`ghp`,`gnoj`,`gtopor`,`gdubina`,`gmech`,`gfire`,`gwater`,`gair`,`gearth`,`glight`,`ggray`,`gdark`,`needident`,`nsila`,`nlovk`,`ninta`,`nintel`,`nmudra`,`nvinos`,`nnoj`,`ntopor`,`ndubina`,`nmech`,`nfire`,`nwater`,`nair`,`nearth`,`nlight`,`ngray`,`ndark`,
					`mfkrit`,`mfakrit`,`mfuvorot`,`mfauvorot`,`bron1`,`bron2`,`bron3`,`bron4`,`maxu`,`minu`,`magic`,`nlevel`,`nalign`,`dategoden`,`goden`,`otdel`,`gmp`,`gmeshok`,`encicl`,`artefact`,`duration`
				)
				VALUES
				('{$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['bron3']}','{$dress['bron2']}','{$dress['bron4']}','{$dress['maxu']}','{$dress['minu']}','{$dress['magic']}','{$dress['nlevel']}','{$dress['nalign']}','" . (($dress['goden']) ? ($dress['goden'] * 24 * 60 * 60 + time()) : "") . "','{$dress['goden']}','{$dress['razdel']}','{$dress['gmp']}','{$dress['gmeshok']}','{$dress['encicl']}','{$dress['artefact']}','0'
				) ;");
            }

            mysql_query("INSERT INTO `delo` (`id` , `author` ,`pers`, `text`, `type`, `date`) VALUES ('','0','{$user['id']}','\"" . $user['login'] . "\" Подобрал в Парке гайки ( \"" . $gadget_num . "\" " . $dresscount . "id:(" . $dressid . ") [0/" . $dress['maxdur'] . "]',1,'" . time() . "');");
            addchp('В Парке Вы подобрали гайки (' . $gadget_num . ' шт.)', '{[]}' . Nick::id($user['id'])->short() . '{[]}');
            //денежный приз
            $priz = mt_rand(1, 10);
            mysql_query("UPDATE users set money=money+{$priz} where id='{$user['id']}';");
            addchp('После посещения Парка Вы обогатились на ' . $priz . ' кр. ', '{[]}' . Nick::id($user['id'])->short() . '{[]}');
            mysql_query("INSERT INTO `delo` (`id` , `author` ,`pers`, `text`, `type`, `date`) 
            VALUES ('','0','{$user['id']}','\"" . $user['login'] . "\" нашел в Парке " . $priz . " кр. ',1,'" . time() . "');");
            //переход
            mysql_query("UPDATE `cit_park` SET `room`=0,`bots`='',`time`='" . time() . "' WHERE `id` ='{$user['id']}'; ");
        }
        if ($in_park['counter'] >= 3) {
            echo '<tr><td>По какому-то странному совпадению Вам не хочется идти в парк. Может, подождать до завтра? </td></tr>';
        }
        elseif (($in_park['time'] + 3600) > time()) {
            $tm = time();
            $t_wait = round(((3600 - $tm + $in_park['time']) / 60), 1);
            echo '<tr><td>Вы совсем недавно вернулись из парка, бесполезно идти туда снова. <br/>(Осталось ждать: <strong>' . $t_wait . '</strong> мин.)</td></tr>';
        } else {
            echo '<tr><td><FORM action="c_park.php" method=POST><INPUT TYPE="submit" value="Прогуляться" name="start_raid"><br></FORM></td></tr>';
        }
        echo '<tr><td><FORM action="city.php" method=GET><INPUT TYPE="submit" value="Вернуться в Город" name="ps"></FORM></td></tr>';
    } else {
        echo '<tr><td>Вы видите табличку с названием улицы: <strong>' . $ch_rooms[$in_park['room']] . '</strong></td></tr>';
        echo '<tr><td>В парке пустынно и темно, только какие-то подозрительные личности шныряют по своим делам.</td></tr>';
        echo '<tr><td>Вы видите несколько бандитов. Они замышляют зловещие преступления в городе!</td></tr>';
        echo '<tr><td><FORM action="c_park.php" method=POST><INPUT TYPE="submit" value="Напасть" name="attack"><br></FORM></td></tr>';
    }
    ?>
</table>
<div align=right><img width="260" src="i/park/<?php echo($in_park['room'] + 1); ?>.jpg"/></div>