<?php

define('_CONSTANT_', 1);

require_once '../../../core/start.php';

checkAuth();


switch ($do) 
{
    default:
    # User items;
    head('Снаряжение', 'Снаряжение');

    echo '<div style="margin: 5px;">';

    # Helmet
    $helmet = DB::$dbs->query("SELECT * FROM " . USERITEM . " WHERE `status` = ? and `type` = ? and `user_id` = ?", [1, 'helmet', $user['id']]);
    $helmetS = DB::$dbs->querySingle("SELECT * FROM " . USERITEM . " WHERE `status` = ? and `type` = ? and `user_id` = ?", [1, 'helmet', $user['id']]);

    if ($helmetS == null) 
    {
        echo '<img src="/img/item/empty.png" alt="*"> Шлем<br/>';
    } 
    else 
    { 
        while ($hel = $helmet -> fetch()) 
        {
            echo '<img src="/img/item/helmet/' . $hel['img'] . '.png" alt="*" width="25px"><a href="' . HOME . '/modules/user/items/index.php?infoItem=' . $hel['id'] . '"> ' . $Filter->output($hel['name']) . '</a><br/><a href="' . HOME . '/modules/user/items/index.php?unwearItem=' . $hel['id'] . '">Снять</a><hr>';
        }
    }

    # Weapon 
    $weapon = DB::$dbs->query("SELECT * FROM " . USERITEM . " WHERE `status` = ? and `type` = ? and `user_id` = ?", [1, 'weapon', $user['id']]);
    $weaponS = DB::$dbs->querySingle("SELECT * FROM " . USERITEM . " WHERE `status` = ? and `type` = ? and `user_id` = ?", [1, 'weapon', $user['id']]);

    if ($weaponS == null) 
    {
        echo '<img src="/img/item/empty.png" alt="*"> Оружие<br/>';
    } 
    else 
    { 
        while ($wea = $weapon -> fetch()) 
        {
            echo '<img src="/img/item/weapon/' . $wea['img'] . '.png" alt="*" width="25px"><a href="' . HOME . '/modules/user/items/index.php?infoItem=' . $wea['id'] . '"> ' . $Filter->output($wea['name']) . '</a><br/><a href="' . HOME . '/modules/user/items/index.php?unwearItem=' . $wea['id'] . '">Снять</a><hr>';
        }
    }

    # Defend(защита); 
    $defend = DB::$dbs->query("SELECT * FROM " . USERITEM . " WHERE `status` = ? and `type` = ? and `user_id` = ?", [1, 'defend', $user['id']]);
    $defendS = DB::$dbs->querySingle("SELECT * FROM " . USERITEM . " WHERE `status` = ? and `type` = ? and `user_id` = ?", [1, 'defend', $user['id']]);

    if ($defendS == null) 
    {
        echo '<img src="/img/item/empty.png" alt="*"> Защита<br/>';
    } 
    else 
    { 
        while ($def = $defend -> fetch()) 
        {
            echo '<img src="/img/item/defend/' . $wea['img'] . '.png" alt="*" width="25px"><a href="' . HOME . '/modules/user/items/index.php?infoItem=' . $def['id'] . '"> ' . $Filter->output($def['name']) . '</a><br/><a href="' . HOME . '/modules/user/items/index.php?unwearItem=' . $def['id'] . '">Снять</a><hr>';
        }
    }

    # Armor(броня);
    $armor = DB::$dbs->query("SELECT * FROM " . USERITEM . " WHERE `status` = ? and `type` = ? and `user_id` = ?", [1, 'armor', $user['id']]);
    $armorS = DB::$dbs->querySingle("SELECT * FROM " . USERITEM . " WHERE `status` = ? and `type` = ? and `user_id` = ?", [1, 'armor', $user['id']]);

    if ($armorS == null) 
    {
        echo '<img src="/img/item/empty.png" alt="*"> Тело<br/>';
    } 
    else 
    { 
        while ($arm = $armor -> fetch()) 
        {
            echo '<img src="/img/item/armor/' . $arm['img'] . '.png" alt="*" width="25px"><a href="' . HOME . '/modules/user/items/index.php?infoItem=' . $arm['id'] . '"> ' . $Filter->output($arm['name']) . '</a><br/><a href="' . HOME . '/modules/user/items/index.php?unwearItem=' . $arm['id'] . '">Снять</a><hr>';
        }
    }

    # Soulder(плечи);
    $shoulder = DB::$dbs->query("SELECT * FROM " . USERITEM . " WHERE `status` = ? and `type` = ? and `user_id` = ?", [1, 'shoulder', $user['id']]);
    $shoulderS = DB::$dbs->querySingle("SELECT * FROM " . USERITEM . " WHERE `status` = ? and `type` = ? and `user_id` = ?", [1, 'shoulder', $user['id']]);

    if ($shoulderS == null) 
    {
        echo '<img src="/img/item/empty.png" alt="*"> Плечи<br/>';
    } 
    else 
    { 
        while ($sho = $shoulder -> fetch()) 
        {
            echo '<img src="/img/item/shoulder/' . $sho['img'] . '.png" alt="*" width="25px"><a href="' . HOME . '/modules/user/items/index.php?infoItem=' . $sho['id'] . '"> ' . $Filter->output($sho['name']) . '</a><br/><a href="' . HOME . '/modules/user/items/index.php?unwearItem=' . $sho['id'] . '">Снять</a><hr>';
        }
    }

    # Ring(кольцо);
    $ring = DB::$dbs->query("SELECT * FROM " . USERITEM . " WHERE `status` = ? and `type` = ? and `user_id` = ?", [1, 'ring', $user['id']]);
    $ringS = DB::$dbs->querySingle("SELECT * FROM " . USERITEM . " WHERE `status` = ? and `type` = ? and `user_id` = ?", [1, 'ring', $user['id']]);

    if ($ringS == null) 
    {
        echo '<img src="/img/item/empty.png" alt="*"> Кольцо<br/>';
    } 
    else 
    { 
        while ($rin = $ring -> fetch()) 
        {
            echo '<img src="/img/item/ring/' . $rin['img'] . '.png" alt="*" width="25px"><a href="' . HOME . '/modules/user/items/index.php?infoItem=' . $rin['id'] . '"> ' . $Filter->output($rin['name']) . '</a><br/><a href="' . HOME . '/modules/user/items/index.php?unwearItem=' . $rin['id'] . '">Снять</a><hr>';
        }
    }

    echo '</div>';

    # Unwear item;
    if (isset($_GET['unwearItem'])) 
    {
        $itemId = $Filter->clearInt($_GET['unwearItem']);

        $unwearItem = DB::$dbs->queryFetch("SELECT * FROM " . USERITEM . " WHERE `id` = ? and `user_id` = ?", [$itemId, $user['id']]);

        if (empty($unwearItem)) 
        {
            errorNoExit('Ошибка!');
        } 
        else if ($unwearItem['status'] == 0) 
        {
            errorNoExit('Вещь не должна ноходиться в рюкзаке.');
        } 
        else if ($user['inv'] == $user['max_inv']) 
        {
            errorNoExit('Рюкзак переполнен.');
        }
        else 
        {
            DB::$dbs->query("UPDATE " . USERITEM . " SET `status` = ? WHERE `id` = ?", [0, $itemId]);
            DB::$dbs->query("UPDATE " . USERS . " SET `inv` = ?, `strike` = ?, `defend` = ?, `max_health` = ? WHERE `id` = ?", [($user['inv'] + 1), ($user['strike'] - $unwearItem['strike']), ($user['defend'] - $unwearItem['defend']), ($user['max_health'] - $unwearItem['health']), $user['id']]);
            success('Вы сняли вещь', '/modules/user/items/index.php?do=rack', 'Рюкзак');
        }
    }

    # Item info;
    if (isset($_GET['infoItem'])) 
    {
        $itemId = $Filter->clearInt($_GET['infoItem']);

        $infoItem = DB::$dbs->queryFetch("SELECT * FROM " . USERITEM . " WHERE `id` = ?", [$itemId]);

        if (empty($infoItem)) 
        {
            errorNoExit('Вещи не существует.');
        } 
        else 
        {
            ?> 
            <div class="title"><h1><?=$Filter->output($infoItem['name'])?></h1></div>
            <div style="text-align: center;"><img src="/img/item/<?=$Filter->output($infoItem['type'])?>/<?=$Filter->output($infoItem['img'])?>.png" width="35px"></div>
            <?=ico('strike.png')?> Сила: <?=$Filter->clearInt($infoItem['strike'])?><br/> 
            <?=ico('defend.png')?> Защита: <?=$Filter->clearInt($infoItem['defend'])?><br/> 
            <?=ico('health.png')?> Здоровье: <?=$Filter->clearInt($infoItem['health'])?><br/>
            Владелец: <?=userLink($infoItem['user_id'])?><br/> 
            <?php
        }
    }
    # Foot 
    echo '<a href="' . HOME . '/modules/user/items/index.php?do=rack" class="link-touch">'. ico('rack.png') .' Рюкзак</a>';
    break;

    case 'rack': 
    # User rack;
    head('Рюкзак', 'Рюкзак');

    $all = DB::$dbs->querySingle("SELECT COUNT(`id`) FROM " . USERITEM . " WHERE `status` = ? and `user_id` = ? ORDER BY `id` DESC", [0, $user['id']]);
    $n = new Navigator($all,10,'do=rack');
    $sql = DB::$dbs->query("SELECT * FROM " . USERITEM . " WHERE `status` = ? and `user_id` = ? ORDER BY `id` DESC LIMIT {$n->start()}, 10", [0, $user['id']]);

    if (empty($all)) 
    {
        echo '<div style="text-align: center;">Рюкзак пуст...</div>';
    } 
    else 
    {
        while ($item = $sql -> fetch()) 
        {
            ?>
            <div class="content">
            <img src="/img/item/<?=$item['type']?>/<?=$item['img']?>.png" alt="*" width="35px"> <a href="<?=HOME?>/modules/user/items/index.php?infoItem=<?=$Filter->clearInt($item['id'])?>"> <?=$Filter->output($item['name'])?></a><br/>
            <a href="<?=HOME?>/modules/user/items/index.php?do=rack&amp;dropItem=<?=$item['id']?>" style="color: #808080;"> Выкинуть</a><?=($item['type'] != 'chest' ? '<a href="' . HOME . '/modules/user/items/index.php?do=rack&amp;wearItem=' . $item['id'] . '" style="color: #fff000;"> Надеть</a>' : '<a href="' . HOME . '/modules/user/items/index.php?do=rack&amp;openItem=' . $item['id'] . '" style="color: #fff000;"> Открыть</a>')?><a href="<?=HOME?>/modules/user/items/index.php?do=rack&amp;kickItem=<?=$item['id']?>" style="color: #808080;"> Разобрать на <?=ico('skull.png') . $item['res_kick']?></a><br/>
            </div>
            <?php
        } 
        echo $n->navi();
    }

    # Drop item;
    if (isset($_GET['dropItem'])) 
    {
        $itemId = $Filter->clearInt($_GET['dropItem']);

        $dropedItem = DB::$dbs->queryFetch("SELECT * FROM " . USERITEM . " WHERE `id` = ? and `user_id` = ?", [$itemId, $user['id']]);

        if (empty($dropedItem)) 
        {
            errorNoExit('Ошибка!');
        } 
        else if ($dropedItem['status'] == 1) 
        {
            errorNoExit('Вещь должна ноходиться в рюкзаке.');
        } 
        else 
        {
            DB::$dbs->query("DELETE FROM " . USERITEM . " WHERE `id` = ?", [$itemId]);
            DB::$dbs->query("UPDATE " . USERS . " SET `inv` = ? WHERE `id` = ?", [($user['inv'] - 1), $user['id']]);
            success('Вы выбросили вещь', '/modules/user/items/index.php?do=rack', 'Рюкзак');
        }
    }

    # Kick item;
    if (isset($_GET['kickItem'])) 
    {
        $itemId = $Filter->clearInt($_GET['kickItem']);

        $kickedItem = DB::$dbs->queryFetch("SELECT * FROM " . USERITEM . " WHERE `id` = ? and `user_id` = ?", [$itemId, $user['id']]);

        if (empty($kickedItem)) 
        {
            errorNoExit('Ошибка!');
        } 
        else if ($kickedItem['status'] == 1) 
        {
            errorNoExit('Вещь должна ноходиться в рюкзаке.');
        } 
        else if ($kickedItem['res_kick'] == 0) 
        {
            errorNoExit('Эту вещь разобрать не получится.');
        }
        else 
        {
            DB::$dbs->query("DELETE FROM " . USERITEM . " WHERE `id` = ?", [$itemId]);
            DB::$dbs->query("UPDATE " . USERS . " SET `inv` = ?, `skull` = ? WHERE `id` = ?", [($user['inv'] - 1), ($user['skull'] + $kickedItem['res_kick']), $user['id']]);
            success('Вы разобрали вещь', '/modules/user/items/index.php?do=rack', 'Рюкзак');
        }
    } 

    # Wear item;
    if (isset($_GET['wearItem'])) 
    {
        $itemId = $Filter->clearInt($_GET['wearItem']);

        $wearItem = DB::$dbs->queryFetch("SELECT * FROM " . USERITEM . " WHERE `id` = ? and `user_id` = ?", [$itemId, $user['id']]);

        $userItem = DB::$dbs->queryFetch("SELECT * FROM " . USERITEM . " WHERE `status` = ? and `type` = ? and `user_id` = ?", [1, $wearItem['type'], $user['id']]);
        
        if (empty($wearItem)) 
        {
            errorNoExit('Ошибка!');
        } 
        else if ($wearItem['status'] == 1) 
        {
            errorNoExit('Вещь должна ноходиться в рюкзаке.');
        } 
        else if (!empty($userItem)) 
        {
            errorNoExit('На вас уже одета вещь данного типа.');
        } 
        else 
        {
            DB::$dbs->query("UPDATE " . USERITEM . " SET `status` = ? WHERE `id` = ?", [1, $itemId]);
            DB::$dbs->query("UPDATE " . USERS . " SET `inv` = ?, `strike` = ?, `defend` = ?, `max_health` = ? WHERE `id` = ?", [($user['inv'] - 1), ($user['strike'] + $wearItem['strike']), ($user['defend'] + $wearItem['defend']), ($user['max_health'] + $wearItem['health']), $user['id']]);
            success('Вы одели вещь', '/modules/user/items/index.php?do=rack', 'Рюкзак');
        }
    }

    # Open item; 
    if (isset($_GET['openItem'])) 
    {
        $itemId = $Filter->clearInt($_GET['openItem']);

        $openItem = DB::$dbs->queryFetch("SELECT * FROM " . USERITEM . " WHERE `id` = ? and `user_id` = ?", [$itemId, $user['id']]);

        if (empty($openItem)) 
        {
            errorNoExit('Ошибка!');
        } 
        else if ($openItem['type'] != 'chest') 
        {
            errorNoExit('Ошибка!.');
        } 
        else 
        {
            $goldReward = rand(1, $openItem['gold_reward']); // Drop gold;
            $expReward = rand(1, $openItem['exp_reward']);   // Exp drop;
            $itemReward = rand(1, 100);                  // Item drop chanse;

            # Item drop;
            if (!empty($openItem['item_reward']) && $itemReward > 50) 
            {
                $dropedItem = DB::$dbs->queryFetch("SELECT * FROM " . ALL_ITEMS . " WHERE `id` = ?", [$openItem['item_reward']]);

                if ($user['inv'] != $user['max_inv']) 
                {
                    DB::$dbs->query("INSERT INTO " . USERITEM . "(`user_id`, `status`, `type`, `name`, `img`, `res_kick`, `strike`, `defend`, `health`) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)", [$user['id'], 0, $dropedItem['type'], $Filter->clearString($dropedItem['name']), $dropedItem['img'], $dropedItem['res_kick'], $dropedItem['strike'], $dropedItem['defend'], $dropedItem['health']]); 
                    // DB::$dbs->query("UPDATE " . USERS . " SET `inv` = ? WHERE `id` = ? LIMIT 1", [($user['inv'] + 1), $user['id']]);                   
                }
            }
            
            # Drop res;
            DB::$dbs->query("UPDATE " . USERS . " SET `money` = ?, `exp` = ? ". (!empty($openItem['item_reward']) && $itemReward > 50 ? NULL : ', `inv` = ?') ." WHERE `id` = ? LIMIT 1", (!empty($openItem['item_reward']) && $itemReward > 50 ? [($user['money'] + $goldReward), ($user['exp'] + $expReward), $user['id']] : [($user['money'] + $goldReward), ($user['exp'] + $expReward), ($user['inv'] - 1), $user['id']]));
            DB::$dbs->query("DELETE FROM " . USERITEM . " WHERE `id` = ?", [$openItem['id']]);

            # Output reward;
            $journal = 'Вы нашли в сундуке: <br/>' . (!empty($openItem['gold_reward']) ? ico('gold.png') . $goldReward . '<br/>' : NULL) . (!empty($openItem['exp_reward']) ? ico('exp.png') . $expReward . '<br/>' : NULL) . (!empty($openItem['item_reward'] && $itemReward > 50 && $user['inv'] != $user['max_inv']) ? ico('1.png') . $Filter->output($dropedItem['name']) . '<br/>' : NULL);
            $User->addUserJournal($journal, $user['id']);
            success('Вы открыли сундук', '/modules/user/items/index.php?do=rack', 'Рюкзак');
        }
    }

    echo moneyIcon() . $user['money'] . ',' . ico('skull.png') . $user['skull'] . ','. ico('ruby.png') . $user['ruby'] .'<a href="' . HOME . '/modules/user/items/index.php" class="link-touch">'. ico('items.png') .' Снаряжение</a><a href="' . HOME . '/modules/user/belt/index.php" class="link-touch">'. ico('items.png') .' Пояс</a>';
    break;
} 

require_once '../../../core/foot.php';