<?php

session_start();
require_once 'inc/functions.php';
check404();
securityCheck();
if (!isLoggedIn()) {
    header('Location: index.php');
    exit;
}

$user = getUserById($_SESSION['user_id']);
if (!$user) {
    session_destroy();
    header('Location: index.php');
    exit;
}

$setId = isset($_GET['set']) ? (int)$_GET['set'] : 0;
$vendorSet = getVendorSetById($setId);
if (!$vendorSet) {
    header('Location: equipment_shop.php');
    exit;
}

$items = getVendorItemsBySet($setId);

$message = '';
$error = '';

// Обработка покупки
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'buy_item') {
        $vendorItemId = (int)($_POST['vendor_item_id'] ?? 0);
        $bonus = (int)($_POST['bonus'] ?? 200);
        $result = purchaseVendorItem($user['id'], $vendorItemId, $bonus);
        if ($result['success']) {
            $message = $result['message'];
        } else {
            $error = $result['message'];
        }
    } elseif ($action === 'buy_all') {
        $bonus = (int)($_POST['bonus'] ?? 200);
        $result = purchaseAllVendorSet($user['id'], $setId, $bonus);
        if ($result['success']) {
            $message = $result['message'];
        } else {
            $error = $result['message'];
        }
    }
}

// Экипированные предметы пользователя
$equippedItems = getEquippedItems($user['id']);
$equippedBySlot = [];
foreach ($equippedItems as $eq) {
    $equippedBySlot[$eq['slot']] = $eq;
}

require_once 'inc/header.php';
?>

<span class="ttl"><b>Магазин <?= htmlspecialchars($vendorSet['name']) ?></b></span>
<div class="clb"></div>
<div class="hr"></div>

<div class="small cntr">
    <?= htmlspecialchars($vendorSet['description']) ?>
</div>
<div class="hr"></div>

<!-- Манекен (заглушка) -->
<table cellpadding="1" cellspacing="0" border="0"><tbody>
<tr>
<td valign="top">
    <img width="120" height="210" src="/images/maneken.png" alt="" border="0"/>
</td>
</tr>
</tbody></table>
<div class="hr"></div>

<!-- Бонусы -->
<div>
    <img class="internalIcon" alt="" border="0" src="/images/icons/dot.png"/>
    <span><em>Бонус вещи:</em></span> <span class="info">+200%</span> за
    <span><img src="images/icons/money_gold.png" width="12" height="12" alt="з"/>5</span><br/>
    <img class="internalIcon" alt="" border="0" src="/images/icons/dot.png"/>
    <span><em>Бонус вещи:</em></span> <span class="info">+250%</span> за
    <span><img src="images/icons/money_gold.png" width="12" height="12" alt="з"/>10</span><br/>
    <img class="internalIcon" alt="" border="0" src="/images/icons/dot.png"/>
    <span><em>Бонус вещи:</em></span> <span class="info">+275%</span> за
    <span><img src="images/icons/money_gold.png" width="12" height="12" alt="з"/>40</span><br/>
</div>
<div class="hr"></div>

<!-- Кнопка "Купить все" -->
<form method="post" style="display:inline;">
    <input type="hidden" name="action" value="buy_all">
    <input type="hidden" name="bonus" value="200">
    <img width="12" height="12" src="/images/icons/dot.png" alt="" border="0"/>
    <button type="submit" class="btn small" style="background:none; border:none; color:blue; text-decoration:underline; cursor:pointer;">
        Купить все вещи за <span><img src="images/icons/money_gold.png" width="12" height="12" alt="з"/>40</span> (10 по цене 8)
    </button>
</form>
<div class="hr"></div>

<?php if ($message): ?>
    <div class="ok"><?= htmlspecialchars($message) ?></div>
    <div class="hr"></div>
<?php endif; ?>
<?php if ($error): ?>
    <div class="error"><?= htmlspecialchars($error) ?></div>
    <div class="hr"></div>
<?php endif; ?>

<!-- Список предметов комплекта -->
<?php foreach ($items as $item): ?>
    <div>
        <table><tbody><tr>
            <td style="width:1%;vertical-align:top;">
                <img width="40" height="40" src="<?= htmlspecialchars($item['image']) ?>" alt="" border="0"/>
            </td>
            <td style="vertical-align:top;">
                <img width="12" height="12" src="/images/icons/bonusdarkiron.png" alt="" border="0"/>
                <a href="vendor_item.php?item=<?= $item['id'] ?>">
                    <span><?= htmlspecialchars($item['item_name']) ?></span>
                </a><br/>
                <span class="small">
                    <span><?= $item['level_required'] ?></span> ур, <span>новый</span>
                </span><br/>
                <!-- Кнопки покупки с разными бонусами -->
                <span class="small">
                    <form method="post" style="display:inline;">
                        <input type="hidden" name="action" value="buy_item">
                        <input type="hidden" name="vendor_item_id" value="<?= $item['id'] ?>">
                        <input type="hidden" name="bonus" value="200">
                        <button type="submit" class="btn small">+200% за 5з</button>
                    </form>
                    <form method="post" style="display:inline;">
                        <input type="hidden" name="action" value="buy_item">
                        <input type="hidden" name="vendor_item_id" value="<?= $item['id'] ?>">
                        <input type="hidden" name="bonus" value="250">
                        <button type="submit" class="btn small">+250% за 10з</button>
                    </form>
                    <form method="post" style="display:inline;">
                        <input type="hidden" name="action" value="buy_item">
                        <input type="hidden" name="vendor_item_id" value="<?= $item['id'] ?>">
                        <input type="hidden" name="bonus" value="275">
                        <button type="submit" class="btn small">+275% за 40з</button>
                    </form>
                </span>
                <!-- Характеристики предмета (предпросмотр с бонусом 200%) -->
                <?php
                $bonusPreview = 200;
                $multiplier = (100 + $bonusPreview) / 100;
                $stats = [
                    'attack'    => ['icon' => 'strength',        'name' => 'Атака'],
                    'health'    => ['icon' => 'life',            'name' => 'Здоровье'],
                    'defense'   => ['icon' => 'shield',          'name' => 'Защита'],
                    'stamina'   => ['icon' => 'energy',          'name' => 'Выносливость'],
                    'accuracy'  => ['icon' => 'accuracy',        'name' => 'Точность'],
                    'recovery'  => ['icon' => 'regeneration',    'name' => 'Восстановление'],
                ];
                foreach ($stats as $stat => $info):
                    $base = $item['base_' . $stat];
                    if ($base <= 0) continue;
                    $value = round($base * $multiplier);
                ?>
                    <br>
                    <img border="0" width="12" height="12" src="/images/icons/<?= $info['icon'] ?>.png" alt=""/>
                    <?= $info['name'] ?>: <strong><?= $value ?></strong>
                    <span class="minor">(+<?= $bonusPreview ?>%)</span>
                <?php endforeach; ?>
            </td>
        </tr></tbody></table>
        <div class="hr"></div>
    </div>
<?php endforeach; ?>

<!-- Блок "На мне надето" -->
<h2>На мне надето</h2>
<?php
$slotNames = [
    'head' => 'Голова',
    'neck' => 'Шея',
    'body' => 'Тело',
    'pants' => 'Штаны',
    'belt' => 'Пояс',
    'bracers' => 'Браслеты',
    'gloves' => 'Перчатки',
    'ring' => 'Кольцо',
    'weapon' => 'Оружие',
    'boots' => 'Обувь'
];

$anyEquipped = false;
foreach ($items as $vendorItem) {
    $slot = $vendorItem['slot'];
    if (isset($equippedBySlot[$slot])) {
        $anyEquipped = true;
        $eq = $equippedBySlot[$slot];
        $bonusValues = getItemBonusValues($eq);
        ?>
        <div>
            <table cellpadding="1" cellspacing="0" border="0"><tbody>
            <tr>
                <td valign="top">
                    <img width="40" height="40" src="<?= htmlspecialchars($eq['image']) ?>" alt="" border="0"/>
                </td>
                <td valign="top">
                    <div>
                        <img width="12" height="12" src="/images/icons/bonusdarkiron.png" alt="" border="0"/>
                        <span>элитный</span>, <span>личный</span>
                    </div>
                    <div>
                        <span><?= htmlspecialchars($eq['item_name']) ?></span>
                    </div>
                    <div>
                        <span><?= $slotNames[$slot] ?? $slot ?></span>, <strong><?= $eq['level_required'] ?></strong> уровень
                    </div>
                </td>
            </tr>
            </tbody></table>
        </div>
        <div>
            <?php
            $statsMap = [
                'attack'   => ['icon' => 'strength',     'name' => 'Атака'],
                'health'   => ['icon' => 'life',         'name' => 'Здоровье'],
                'defense'  => ['icon' => 'shield',       'name' => 'Защита'],
                'stamina'  => ['icon' => 'energy',       'name' => 'Выносливость'],
                'accuracy' => ['icon' => 'accuracy',     'name' => 'Точность'],
                'recovery' => ['icon' => 'regeneration', 'name' => 'Восстановление'],
            ];
            foreach ($bonusValues as $stat => $value):
                if ($value <= 0) continue;
                $info = $statsMap[$stat];
            ?>
                <img border="0" width="12" height="12" src="/images/icons/<?= $info['icon'] ?>.png" alt=""/>
                <?= $info['name'] ?>: <strong><?= $value ?></strong>
                <span class="minor">(+<?= $eq['bonus_percent'] ?>%)</span><br/>
            <?php endforeach; ?>
            <div class="hr"></div>
            Прочность: <strong>900</strong>/<strong>900</strong><br/>
        </div>
        <div class="hr"></div>
        <?php
    }
}
if (!$anyEquipped) {
    echo '<div class="cntr">У вас нет надетых предметов из этого комплекта.</div><div class="hr"></div>';
}
?>

<?php require_once 'inc/foot.php'; ?>