<?php

use Battles\Bank;
use Battles\Database\Db;
use Battles\GameLogs;
use Battles\InventoryItem;
use Battles\Template;
use Battles\User;

require_once("functions.php");
const GRAV_LIMIT = 32;
const GRAV_COST = 30;
const REPAIR_STATUS = [
    'OK_GRAV_ADDED' => 'Гравировка добавлена!',
    'OK_GRAV_REMOVED' => 'Гравировка удалена!',
    'OK_REPAIRED' => 'Предмет отремонтирован!',
    'ERROR_SIZE_LIMIT' => 'Превышен лимит в ' . GRAV_LIMIT . ' символа!',
    'ERROR_NO_MONEY' => 'Недостаточно денег!',
];
$gravirovkaText = $_POST['gravirovka_text'] ?? null;
$itemId = $_POST['itemId'] ?? null;
$gravirovkaRemove = $_POST['gravirovka_remove'] ?? null;
$action = $_POST['action'] ?? null;
$goto = $_POST['goto'] ?? null;
$remont_query = null;
$gravirovka_query = null;

// Гравировка 30 кред. Максимум 32 символа.
if ($gravirovkaText && $itemId) {
    if (User::getInstance()->getMoney() >= GRAV_COST) {
        if (iconv_strlen($gravirovkaText) <= GRAV_LIMIT) {
            Db::getInstance()->execute('UPDATE inventory SET text = ? WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [$gravirovkaText, User::getInstance()->getId(), $itemId]);
            User::getInstance()->setMoney(User::getInstance()->getMoney() - GRAV_COST);
            Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId());
            $status = REPAIR_STATUS['OK_GRAV_ADDED'];
        } else {
            $status = REPAIR_STATUS['ERROR_SIZE_LIMIT'];
        }
    } else {
        $status = REPAIR_STATUS['ERROR_NO_MONEY'];
    }
}
// Снять гравировку.
if ($gravirovkaRemove) {
    if (User::getInstance()->getMoney() >= GRAV_COST) {
        Db::getInstance()->execute('UPDATE inventory SET text = null WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [User::getInstance()->getId(), $itemId]);
        User::getInstance()->setMoney(User::getInstance()->getMoney() - GRAV_COST);
        Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId());
        $status = REPAIR_STATUS['OK_GRAV_REMOVED'];
    } else {
        $status = REPAIR_STATUS['ERROR_NO_MONEY'];
    }
}
// Ремонт 0,5 кред за единицу.
// Пока что лимит ремонта поставлен на 25. Дальше можно обыграть.
if ($action == 'repair' && $itemId) {
    $q = Db::getInstance()->ofetch('SELECT name, durability FROM inventory WHERE item_id = ?', $itemId);
    if (User::getInstance()->getMoney() > ceil($q->duration / 2)) {
        Db::getInstance()->execute('UPDATE inventory SET duration = 25 WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [User::getInstance()->getId(), $itemId]);
        User::getInstance()->setMoney(User::getInstance()->getMoney() - ceil($q->duration / 2));
        Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId());
        GameLogs::addUserLog(User::getInstance()->getId(), 'Отремонтирован предмет «' . $q->name . '» id:(' . $itemId . ') за ' . ceil($q->duration / 2) . ' кр.');
        $status = REPAIR_STATUS['OK_REPAIRED'];
    } else {
        $status = REPAIR_STATUS['ERROR_NO_MONEY'];
    }
}
if ($goto == 'remont') {
    $remont_query = Db::getInstance()->ofetchAll('SELECT item_id, name, image, durability FROM inventory WHERE item_type < 12 AND dressed_slot = 0 AND on_sale = 0 AND durability < 25 AND owner_id = ? ORDER BY name', User::getInstance()->getId());
}
if ($goto == 'gravirovka') {
    $gravirovka_query = Db::getInstance()->ofetchAll('SELECT item_id, name, image, text FROM inventory WHERE owner_id = ? AND dressed_slot = 0 AND item_type = 3 AND name NOT LIKE "%Букет%" AND on_sale = 0 OR text IS NOT NULL AND owner_id = ? AND dressed_slot = 0 AND on_sale = 0 ORDER BY name', [User::getInstance()->getId(), User::getInstance()->getId()]);
}
Template::header('Кузня');
?>
<link href="css/secondary.css" rel="stylesheet"/>
<script src="js/main.js"></script>
<h1>Ремонтная мастерская</h1>
<a href=# onclick=hrefToFrame('city.php?cp')> ← выйти из мастерской</a><br>
<div class="appblock appblock-main">
    <span class="legend">Информация</span>
    <span class="wrap">Кредиты<span class="num"><?= $user['money'] ?></span></span>
    <span class="wrap">Масса вещей<span class="num"><?= InventoryItem::getWeightData() ?></span></span>
</div>
<div class="appblock">
    <span class="legend">Зал ремонта</span>
    <form method="post">
        <input type="hidden" name="goto" value="remont">
        <input type="submit" value="Войти">
    </form>
    <span class="wrap">Починка поврежденных предметов. В процессе ремонта состояние предмета
        уменьшится на единицу!</span>
</div>
<div class="appblock">
    <span class="legend">Зал гравировки</span>
    <form method="post">
        <input type="hidden" name="goto" value="gravirovka">
        <input type="submit" value="Войти" disabled>
    </form>
    <span class="wrap">Нанесение надписей на оружие и удаление надписей из любого обмундирования.
        Максимум 32 символа!</span>
</div>
<div style="clear: both;">
    <?php if (isset($status)): ?>
        <span class="wrap"><?= $status ?></span>
    <?php endif; ?>
</div>
<?php if ($goto == 'remont'):
    $i = 0;
    while ($i < count($remont_query)): ?>
        <div class="appblock">
            <span class="legend"><?= $remont_query[$i]->name ?></span>
            <span class="wrap">Состояние предмета<span class="num"><?= $remont_query[$i]->duration ?>/25</span></span>
            <span class="wrap">Стоимость услуги<span class="num"><?= ceil($remont_query[$i]->duration / 2) ?></span></span>
            <div style="text-align: center">
                <img src="i/sh/<?= $remont_query[$i]->img ?>" alt="item">
                <form method="post">
                    <input type="hidden" name="itemId" value="<?= $remont_query[$i]->id ?>">
                    <input type="hidden" name="action" value="repair">
                    <input type="submit" value="Ремонт">
                </form>
            </div>
        </div>
        <?php $i++; endwhile;
    unset($i); endif; ?>

<?php if ($goto == 'gravirovka'):
    $i = 0;
    while ($i < count($gravirovka_query)): ?>
        <div class="appblock">
            <span class="legend"><?= $gravirovka_query[$i]->name ?></span>
            <span class="wrap">Стоимость услуги<span class="num">30</span></span>
            <div style="text-align: center">
                <?php if (empty($gravirovka_query[$i]->text)): ?>
                    <form method="post" id="gravirovka">
                        <label>
                            <input maxlength="32" placeholder="Текст гравировки" name="gravirovka_text">
                        </label>
                        <br><img src="i/sh/<?= $gravirovka_query[$i]->img ?>" alt="item"><br>
                        <input type="hidden" name="itemId" value="<?= $gravirovka_query[$i]->id ?>">
                        <input type="submit" value="Добавить надпись">
                    </form>
                <?php else: ?>
                    <form method="post" id="gravirovka">
                        <input value="<?= $gravirovka_query[$i]->text ?>" readonly title>
                        <br><img src="i/sh/<?= $gravirovka_query[$i]->img ?>" alt="item"><br>
                        <input type="hidden" name="gravirovka_remove" value="<?= $gravirovka_query[$i]->id ?>">
                        <input type="submit" value="Удалить надпись">
                    </form>
                <?php endif; ?>
            </div>
        </div>
        <?php $i++; endwhile;
    unset($i); endif; ?>