<?php
session_start();
if (!($_SESSION['uid'] > 0)) header("Location: index.php");
include "config.php";
include "functions.php";
$itemWeight = db::c()->query('SELECT sum(`massa`) AS `m` FROM `inventory` WHERE `owner` = ?i AND `dressed` = 0 AND `setsale` = 0', $user['id'])->fetch_assoc();
if ($user['room'] != 22) {
    header("Location: main.php");
    die();
}
if ($user['battle'] != 0) {
    header('location: fbattle.php');
    die();
}

if (($_GET['set'] OR $_POST['set'])) {
    if ($_GET['set']) {
        $set = $_GET['set'];
    }
    if ($_POST['set']) {
        $set = $_POST['set'];
    }
    if (!$_POST['count']) $_POST['count'] = 1;
    if (!is_numeric($_POST['count']) || $_POST['count'] != ((int)$_POST['count'])) {
        $_POST['count'] = 0;
        $count_ok = 0;
    } elseif ($_POST['count'] < 1) {
        $_POST['count'] = 0;
        $count_ok = 0;
    } else $count_ok = 1;
    $dress = db::c()->query('SELECT * FROM `ahero_shop` WHERE `id` = ?i', $set)->fetch_assoc();
    if ($count_ok == 0) {
        err('Неправильно введено количество');
        //$good = 0;
    } elseif (($dress['massa'] * $_POST['count'] + $itemWeight['m']) > (get_meshok())) {
        err('Недостаточно места в рюкзаке.');
        //$good = 0;
    } elseif ($count_ok == 1 && ($user['doblest'] >= ($dress['point'] * $_POST['count'])) && ($dress['count'] >= $_POST['count'])) {

        for ($k = 1; $k <= $_POST['count']; $k++) {
            if (isset($dress['goden'])) $goden = $dress['goden'] * 24 * 60 * 60 + time(); // Ну вот нахуя?
            db::c()->query(' 
                INSERT INTO `inventory`
                (
                  `opisan`, `prototype`,`owner`,`name`,`type`,`massa`,`point`,`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 
				(
				  "?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s",
				  "?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s",
				  "?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s","?s",
				  "?s","?s","?s","?s","?s"
				)', $dress['opisan'], $dress['id'], $user['id'], $dress['name'], $dress['type'], $dress['massa'], $dress['point'], $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'], $goden , $dress['goden'], $dress['razdel'], $dress['gmp'], $dress['gmeshok'], $dress['encicl'], $dress['artefact'], $dress['koll']);

            db::c()->query('UPDATE `shop` SET `count` = `count`- ?i WHERE `id` = ?i', $_POST['count'], $set);
            db::c()->query('UPDATE `users` set `doblest` = `doblest` - ?i * ?i WHERE id = ?i', $_POST['count'], $dress['point'], $user['id']);
            $user['money'] -= $_POST['count'] * $dress['point'];
            err('Вы купили {$_POST[\'count\']} шт. {$dress[\'name\']}');

            $limit = $_POST['count'];
            $invdb = db::c()->query('SELECT `id` FROM `inventory` WHERE `name` = "?s" ORDER by `id` DESC LIMIT ?i', $dress['name'], $limit);
            if ($limit == 1) {
                $dressinv = $invdb->fetch_assoc();
                $dressid = "cap" . $dressinv['id'];
                $dresscount = " ";
            } else {
                $dressid = "";
                while ($dressinv = $invdb->fetch_assoc()) {
                    $dressid .= "cap" . $dressinv['id'] . ",";
                }
                $dresscount = "(x" . $_POST['count'] . ") ";
            }

            $allcost = $_POST['count'] * $dress['point'];
            $deloText = $user['login'] . " купил товар: " . $dress['name'] . $dresscount . "id:(" . $dressid . ") [0/" . $dress['maxdur'] . "] за " . $allcost . " кр.";
            db::c()->query('INSERT INTO `delo` (`author` ,`pers`, `text`, `type`, `date`) VALUES (?i, ?i, "?s", ?i, "?s")', 0, $user['id'], $deloText, 1, time());
        }
    } else {
        err('Недостаточно репутации или нет вещей в наличии.');
    }
}

if ($_POST['sale']) {
    echo "Скупка";
} else
    switch ($_GET['otdel']) {
        case null:
            $otdel_name = "Оружие: кастеты,ножи";
            $_GET['otdel'] = 1;
            break;
        case 1:
            $otdel_name = "Оружие: кастеты,ножи";
            break;

        case 11:
            $otdel_name = "Оружие: топоры";
            break;

        case 12:
            $otdel_name = "Оружие: дубины,булавы";
            break;

        case 13:
            $otdel_name = "Оружие: мечи";
            break;

        case 14:
            $otdel_name = "Оружие: луки и арбалеты";
            break;

        case 2:
            $otdel_name = "Одежда: сапоги";
            break;

        case 21:
            $otdel_name = "Одежда: перчатки";
            break;

        case 22:
            $otdel_name = "&Одежда: легкая броня";
            break;

        case 23:
            $otdel_name = "Одежда: тяжелая броня";
            break;

        case 24:
            $otdel_name = "Одежда: шлемы";
            break;

        case 3:
            $otdel_name = "Щиты";
            break;

        case 4:
            $otdel_name = "Ювелирные товары: серьги";
            break;

        case 41:
            $otdel_name = "Ювелирные товары: ожерелья";
            break;

        case 42:
            $otdel_name = "Ювелирные товары: кольца";
            break;

        case 5:
            $otdel_name = "Заклинания: нейтральные";
            break;

        case 51:
            $otdel_name = "Заклинания: боевые и защитные";
            break;
        case 6:
            $otdel_name = "Амуниция";
            break;
        case 52:
            $otdel_name = "Руны";
            break;

    }
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link href="css/main.css" rel="stylesheet"/>
    <script LANGUAGE="JavaScript">
        function AddCount(name, txt) {
            document.all("hint3").innerHTML = '<form method=post style="margin:0; padding:0;"><table border=0 width=100% cellspacing=1 cellpadding=0 bgcolor="#CCC3AA"><tr><td align=center><B>Купить неск. штук</td><td width=20 align=right valign=top style="cursor: hand" onclick="closehint3();"><BIG><B>x</TD></tr><tr><td colspan=2>' +
                '<table border=0 width=100% cellspacing=0 cellpadding=0 bgcolor="#FFF6DD"><tr><INPUT TYPE="hidden" name="set" value="' + name + '"><td colspan=2 align=center><B><I>' + txt + '</td></tr><tr><td width=80% align=right>' +
                'Количество (шт.) <INPUT TYPE="text" NAME="count" size=4 ></td><td width=20%>&nbsp;<INPUT TYPE="submit" value=" »» ">' +
                '</TD></TR></TABLE></td></tr></table></form>';
            document.all("hint3").style.visibility = "visible";
            document.all("hint3").style.left = 100;
            document.all("hint3").style.top = 100;
            document.all("count").focus();
        }

        // Закрывает окно
        function closehint3() {
            document.all("hint3").style.visibility = "hidden";
        }
    </script>
</head>
<body marginwidth=5 marginheight=5 bgcolor=#d4d4d4>
<table border=0 width=100% cellspacing="0" cellpadding="0">
    <tr>
        <td><h3 style="color: blue">Магазин репутации</td>
        <td align=right>
            <FORM action="city.php" method=GET>
                <INPUT TYPE="button" value="Подсказка" style="background-color:#A9AFC0"
                       onclick="window.open('help/shop.html', 'help', 'height=300,width=500,location=no,menubar=no,status=no,toolbar=no,scrollbars=yes')">
                <INPUT TYPE="submit" value="Вернуться" name="cp">
            </FORM>
        </td>
    </tr>
</table>
<TABLE border=0 width=100% cellspacing="0" cellpadding="4">
    <TR>
        <FORM METHOD=POST ACTION="shop.php">
            <INPUT TYPE="hidden" name="sid" value="">
            <INPUT TYPE="hidden" name="id" value="1">
            <TD valign=top align=left>
                <!--Магазин-->
                <TABLE border=0 width=100% cellspacing="0" cellpadding="0" bgcolor="#A5A5A5">
                    <TR>
                        <TD align=center>
                            <B>Отдел "<?= $otdel_name ?>"</B>
                        </TD>
                    </TR>
                    <TR>
                        <TD><!--Рюкзак-->
                            <TABLE BORDER=0 WIDTH=100% CELLSPACING="1" CELLPADDING="2" BGCOLOR="#A5A5A5">
                                <?php
                                $data = db::c()->query('SELECT * FROM `ahero_shop` WHERE `count` > 0 AND `razdel` = ?i ORDER by `point` ASC', $_GET['otdel']);
                                while ($row = $data->fetch_assoc()) {
                                    if ($i == 0) {
                                        $i = 1;
                                        $color = '#C7C7C7';
                                    } else {
                                        $i = 0;
                                        $color = '#D5D5D5';
                                    }
                                    ?>
                                    <tr bgcolor="<?=$color?>">
                                        <td align="center" style="width: 150px;">
                                            <img src="i/sh/<?=$row['img']?>" border="0">
                                            <br><a href="ahero_shop.php?otdel=<?=$_GET['otdel']?>&set=<?=$row['id']?>&sid=">купить</a>
                                            <img src="i/up.gif" WIDTH=11 HEIGHT=11 BORDER=0 ALT="Купить несколько штук" style="cursor:hand" onclick="AddCount('<?=$row['id']?>', '<?=$row['name']?>')">
                                        </td>
                                        <td valign="top">
                                            <?php showitem($row, 11); ?>
                                        </td>
                                    </tr>
                                <?php
                                }
                                ?>
                            </TABLE>
                        </TD>
                    </TR>
                </TABLE>
            </TD>
            <TD valign=top width=280>
                <div style="MARGIN-LEFT:15px; MARGIN-TOP: 10px;">
                    <CENTER><B>Масса всех ваших вещей: <?= getItemsMassaInfo() ?><BR>
                            У вас в наличии: <span style="color: blue"><?=$user['doblest']?></span> реп.</B></CENTER>
                    <hr>
                    <a href=shop.php>ГОС. МАГАЗИН</a>
                    <hr>
                    <div style="background-color:#d2d0d0; padding:1px; text-align: center; font-weight: bold;">
                        Отделы магазина
                    </div>
                    <b>Оружие:</b> <BR>
                    <A HREF="ahero_shop.php?otdel=1&sid=&0.162486541405194">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;кастеты,ножи</A><BR>
                    <A HREF="ahero_shop.php?otdel=11&sid=&0.337606814894404">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;топоры</A><BR>
                    <A HREF="ahero_shop.php?otdel=12&sid=&0.286790872806733">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;дубины,булавы</A><BR>
                    <A HREF="ahero_shop.php?otdel=13&sid=&0.0943516060419363">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;мечи</A><BR>
                    <b>Одежда:</b> <BR>
                    <A HREF="ahero_shop.php?otdel=24&sid=&0.567932791291376">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;шлемы</A><BR>
                    <A HREF="ahero_shop.php?otdel=23&sid=&0.99133839275569">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;тяжелая
                        броня</A><BR>
                    <A HREF="ahero_shop.php?otdel=22&sid=&0.520447517792988">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;легкая
                        броня</A><BR>
                    <A HREF="ahero_shop.php?otdel=3&sid=&0.725667864710179">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;щиты</A><BR>
                    <A HREF="ahero_shop.php?otdel=21&sid=&0.648260824682342">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;перчатки</A><BR>
                    <A HREF="ahero_shop.php?otdel=2&sid=&0.76205958316951">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;сапоги</A><BR>
                    <b>Ювелирные товары:</b> <BR>
                    <A HREF="ahero_shop.php?otdel=4&sid=&0.321709306035984">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;серьги</A><BR>
                    <A HREF="ahero_shop.php?otdel=41&sid=&0.902093651333512">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ожерелья</A><BR>
                    <A HREF="ahero_shop.php?otdel=42&sid=&0.510210803380268">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;кольца</A><BR>
                    <b>Магия:</b> <BR>
                    <A HREF="ahero_shop.php?otdel=51&sid=&0.722009624500359">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;боевые</A><BR>
                    <A HREF="ahero_shop.php?otdel=5&sid=&0.648834385828923">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;разные</A><BR>
                    <b>Разное:</b> <BR>
                    <A HREF="ahero_shop.php?otdel=6&sid=&0.925798340638547">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;амуниция</A><BR>
                    <A HREF="ahero_shop.php?otdel=52&sid=&0.925798340638547">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;руны</A><BR>
                </div>
                <div id="hint3" class="ahint"></div>
            </TD>
        </FORM>
    </TR>
</TABLE>
</BODY>
</HTML>