<?php
session_start();
if ($_SESSION['uid'] == null) header("Location: index.php");
require_once 'functions.php';

if ($user['room'] != 50) {
    header("Location: main.php");
    die();
}

if ($user['battle'] != 0) {
    header('location: fbattle.php');
    die();
}

$bank = db::c()->query('SELECT `ekr` FROM `bank` WHERE `id`=?i', $_SESSION['uid'])->fetch_assoc();

$shopItems = db::c()->query('SELECT `ashop`.*,
       `magic`.`name` AS `magic_name`,
       `magic`.`chanse` AS `magic_chanse`,
       `magic`.`time` AS `magic_time`,
       `magic`.`file` AS `magic_file`,
       `magic`.`targeted` AS `magic_targeted`,
       `magic`.`needcharge` AS `magic_needcharge`,
       `magic`.`img` AS `magic_img`

FROM `ashop` LEFT JOIN `magic` ON `magic` = `magic`.`id` WHERE `count` > 0 AND `ecost` > 0 AND `razdel` = ?i ORDER by `nlevel` ASC, `id` ASC', $_GET['otdel']);

$iteminfo = [];
while ($row = $shopItems->fetch_assoc()) {
    $iteminfo[] = new ShopItem($row);
}

if (!empty($_GET['buy'])) {
    $dress = db::c()->query('SELECT * FROM `ashop` WHERE `id`=?i', $_GET['buy'])->fetch_assoc();
    $itemWeight = db::c()->query('SELECT sum(`massa`) AS `m` FROM `inventory` WHERE `owner` = ?i AND `setsale` = 0', $user['id'])->fetch_assoc();
    if (($dress['massa'] + $itemWeight['m']) > (get_meshok())) $status = 'Недостаточно места в рюкзаке.';
    elseif ($bank['ekr'] >= $dress['ecost'] AND ($dress['count'] > 0 OR $dress['count'] == -1)) {

        $goden = '';
        if (isset($dress['goden'])) $goden = $dress['goden'] * 24 * 60 * 60 + time(); // Ну вот нахуя?
        db::c()->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`,
                `artefact`, `koll`
              )
              VALUES (?i,?i,"?s",?i,?i,"?s","?s",?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i)
            ', $dress['id'], $_SESSION['uid'], $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'], $goden, $dress['goden'], $dress['razdel'], $dress['artefact'], $dress['koll']);

        $inventoryItemId = db::c()->getLastInsertId();
        if ($dress['count'] != -1) db::c()->query('UPDATE `ashop` SET `count` = `count`- 1 WHERE `id` = ?i', $_GET['buy']);

        $deloText = "{$user['login']} купил товар «{$dress['name']}» id:({$inventoryItemId}) в магазине «Берёзка» за {$dress['ecost']} екр.";
        addToDelo($deloText);

        $status = "Вы купили «{$dress['name']}» за {$dress['ecost']} екр.";
        db::c()->query('UPDATE `bank` SET `ekr` = `ekr` - ?i WHERE `id` = ?i', $dress['ecost'], $_SESSION['uid']);
        //    Для обновления данных о деньгах на странице
        $bank['ekr'] -= $dress['ecost'];

    } else {
        $status = "Недостаточно денег или нет вещей в наличии.";
    }
}
$shopCategory = '';
$shopCategoryTypeNumber = empty($_GET['otdel']) ?: $_GET['otdel'];
switch ($shopCategoryTypeNumber) {
    default:
        $shopCategory = "Прихожая";
        break;
    case 1:
        $shopCategory = "Кастеты и ножи";
        break;
    case 11:
        $shopCategory = "Топоры";
        break;
    case 12:
        $shopCategory = "Дубины и булавы";
        break;
    case 13:
        $shopCategory = "Мечи";
        break;
    case 14:
        $shopCategory = "Луки и арбалеты";
        break;
    case 2:
        $shopCategory = "Сапоги";
        break;
    case 21:
        $shopCategory = "Перчатки";
        break;
    case 22:
        $shopCategory = "Легкая броня";
        break;
    case 23:
        $shopCategory = "Тяжелая броня";
        break;
    case 24:
        $shopCategory = "Шлемы";
        break;
    case 3:
        $shopCategory = "Щиты";
        break;
    case 4:
        $shopCategory = "Серьги";
        break;
    case 41:
        $shopCategory = "Ожерелья";
        break;
    case 42:
        $shopCategory = "Кольца";
        break;
    case 5:
        $shopCategory = "Заклинания: нейтральные";
        break;
    case 51:
        $shopCategory = "Заклинания: боевые и защитные";
        break;
    case 6:
        $shopCategory = "Амуниция";
        break;
    case 7:
        $shopCategory = "Букеты";
        break;
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link href="css/main.css" rel="stylesheet"/>
    <script src="js/main.js"></script>
</head>
<body>
<h1>Магазин Берёзка</h1>
<a href=# onclick=hrefToFrame('city.php?cp')> ← выйти на Центральную площадь</a>
<div><?php if (!empty($status)) err($status); ?></div>
<table border=0 width=100% cellspacing="0" cellpadding="4">
    <tr>
        <td valign=top align=left>
            <h3><?= $shopCategory ?></h3>
            <!--Магазин-->
            <table class="zebra" width=100% cellspacing="1" cellpadding="2">
                <?php foreach ($iteminfo as $ii): ?>
                    <tr>
                        <td style='width: 150px; text-align: center;'>
                            <?php $ii->printImage();
                            $ii->printControls('ashop'); ?>
                        </td>
                        <td style='vertical-align: top;'>
                            <?php $ii->printInfo(); ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </table>
        </td>
        <td valign=top width=280>
            <b>Масса всех ваших вещей: <?= getItemsMassaInfo() ?>
                <br>У вас в наличии: <span style="color: #339900;"><?= $bank['ekr'] ?></span> екр.</b>
            <hr>

            <div style="text-align: center; font-weight: bold;">Отделы магазина</div>
            <dl>
                <dt><b>Оружие:</b></dt>
                <dd><a href="?otdel=1&rnd=<?= mt_rand() ?>">кинжалы</a></dd>
                <dd><a href="?otdel=11&rnd=<?= mt_rand() ?>">топоры</a></dd>
                <dd><a href="?otdel=12&rnd=<?= mt_rand() ?>">дубины</a></dd>
                <dd><a href="?otdel=13&rnd=<?= mt_rand() ?>">мечи</a></dd>
                <dt><b>Одежда:</b></dt>
                <dd><a href="?otdel=24&rnd=<?= mt_rand() ?>">шлемы</a></dd>
                <dd><a href="?otdel=23&rnd=<?= mt_rand() ?>">тяжелая броня</a></dd>
                <dd><a href="?otdel=22&rnd=<?= mt_rand() ?>">легкая броня</a></dd>
                <dd><a href="?otdel=3&rnd=<?= mt_rand() ?>">щиты</a></dd>
                <dd><a href="?otdel=21&rnd=<?= mt_rand() ?>">перчатки</a></dd>
                <dd><a href="?otdel=2&rnd=<?= mt_rand() ?>">сапоги</a></dd>
                <dt><b>Ювелирные товары:</b></dt>
                <dd><a href="?otdel=4&rnd=<?= mt_rand() ?>">серьги</a></dd>
                <dd><a href="?otdel=41&rnd=<?= mt_rand() ?>">ожерелья</a></dd>
                <dd><a href="?otdel=42&rnd=<?= mt_rand() ?>">кольца</a></dd>
                <dt><b>Магия:</b></dt>
                <dd><a href="?otdel=51&rnd=<?= mt_rand() ?>">боевые</a></dd>
                <dd><a href="?otdel=5&rnd=<?= mt_rand() ?>">разные</a></dd>
                <dt><b>Разное:</b></dt>
                <dd><a href="?otdel=6&rnd=<?= mt_rand() ?>">амуниция</a></dd>
                <dd><a href="?otdel=7&rnd=<?= mt_rand() ?>">букеты</a></dd>
            </dl>
        </td>
    </tr>
</table>
</body>
</html>