<?php
session_start();
require_once '../inc/admin_auth.php';
requireAdmin();
require_once '../inc/functions.php';

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

$stat_names = [
    'attack'   => 'Атака',
    'health'   => 'Здоровье',
    'defense'  => 'Защита',
    'stamina'  => 'Выносливость',
    'accuracy' => 'Точность',
    'recovery' => 'Восстановление'
];

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

$set = getVendorSetById($setId);
if (!$set) {
    header('Location: vendor_sets.php');
    exit;
}

// Обработка POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Добавление предмета
        if (isset($_POST['add_item'])) {
            $slot = $_POST['slot'];
            $item_name = trim($_POST['item_name']);
            $description = trim($_POST['description']);
            $level = (int)$_POST['level_required'];
            $price = (int)$_POST['price_gold'];
            $image = trim($_POST['image']);
            $sort = (int)$_POST['sort_order'];

            $base_attack = (int)$_POST['base_attack'];
            $base_health = (int)$_POST['base_health'];
            $base_defense = (int)$_POST['base_defense'];
            $base_stamina = (int)$_POST['base_stamina'];
            $base_accuracy = (int)$_POST['base_accuracy'];
            $base_recovery = (int)$_POST['base_recovery'];

            $stmt = $pdo->prepare("INSERT INTO vendor_items 
                (set_id, slot, item_name, description, level_required, price_gold, image, sort_order,
                 base_attack, base_health, base_defense, base_stamina, base_accuracy, base_recovery)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$setId, $slot, $item_name, $description, $level, $price, $image, $sort,
                $base_attack, $base_health, $base_defense, $base_stamina, $base_accuracy, $base_recovery]);

            $_SESSION['admin_message'] = '✅ Предмет добавлен.';
            header("Location: admin_vendor_items.php?set_id=$setId");
            exit;
        }

        // Редактирование предмета
        if (isset($_POST['edit_item'])) {
            $itemId = (int)$_POST['item_id'];
            $slot = $_POST['slot'];
            $item_name = trim($_POST['item_name']);
            $description = trim($_POST['description']);
            $level = (int)$_POST['level_required'];
            $price = (int)$_POST['price_gold'];
            $image = trim($_POST['image']);
            $sort = (int)$_POST['sort_order'];

            $base_attack = (int)$_POST['base_attack'];
            $base_health = (int)$_POST['base_health'];
            $base_defense = (int)$_POST['base_defense'];
            $base_stamina = (int)$_POST['base_stamina'];
            $base_accuracy = (int)$_POST['base_accuracy'];
            $base_recovery = (int)$_POST['base_recovery'];

            $stmt = $pdo->prepare("UPDATE vendor_items SET 
                slot=?, item_name=?, description=?, level_required=?, price_gold=?, image=?, sort_order=?,
                base_attack=?, base_health=?, base_defense=?, base_stamina=?, base_accuracy=?, base_recovery=?
                WHERE id=?");
            $stmt->execute([$slot, $item_name, $description, $level, $price, $image, $sort,
                $base_attack, $base_health, $base_defense, $base_stamina, $base_accuracy, $base_recovery, $itemId]);

            $_SESSION['admin_message'] = '✅ Предмет обновлён.';
            header("Location: admin_vendor_items.php?set_id=$setId");
            exit;
        }

        // Удаление предмета
        if (isset($_POST['delete_item'])) {
            $itemId = (int)$_POST['item_id'];
            $stmt = $pdo->prepare("DELETE FROM vendor_items WHERE id=?");
            $stmt->execute([$itemId]);

            $_SESSION['admin_message'] = '✅ Предмет удалён.';
            header("Location: admin_vendor_items.php?set_id=$setId");
            exit;
        }
    } catch (Exception $e) {
        $_SESSION['admin_message'] = '❌ Ошибка: ' . $e->getMessage();
        header("Location: admin_vendor_items.php?set_id=$setId");
        exit;
    }
}

$items = getVendorItemsBySet($setId);

require_once '../inc/header.php';
if (isset($_SESSION['admin_message'])) {
    echo '<div style="border:1px solid green; background:#e0ffe0; padding:10px; margin-bottom:10px;">' . htmlspecialchars($_SESSION['admin_message']) . '</div>';
    unset($_SESSION['admin_message']);
}
?>

<span class="ttl"><b>📦 Предметы комплекта: <?= htmlspecialchars($set['name']) ?></b></span>
<div class="clb"></div>
<div class="hr"></div>

<div class="menu">
    <a class="btn full" href="vendor_sets.php?set_id=<?= $setId ?>">
        <span class="nwr"><img src="/images/icons/arrow.png" width="12" height="12"/> ← Вернуться к комплекту</span>
    </a>
</div>
<div class="hr"></div>

<!-- Форма добавления -->
<details>
    <summary style="cursor:pointer; background:#eee; padding:5px; border-radius:3px;">➕ Добавить предмет в комплект</summary>
    <form method="post" style="margin-top:10px; padding:10px; background:#f9f9f9;">
        <table style="width:100%;">
            <tr><td>Слот:</td><td>
                <select name="slot">
                    <?php foreach ($slots_ru as $val => $ru): ?>
                        <option value="<?= $val ?>"><?= $ru ?></option>
                    <?php endforeach; ?>
                </select>
            </td></tr>
            <tr><td>Название предмета:</td><td><input type="text" name="item_name" required size="50"></td></tr>
            <tr><td>Описание:</td><td><textarea name="description" rows="2" cols="50"></textarea></td></tr>
            <tr><td>Требуемый уровень:</td><td><input type="number" name="level_required" value="25" min="1"></td></tr>
            <tr><td>Цена (золото):</td><td><input type="number" name="price_gold" value="5" min="0"></td></tr>
            <tr><td>Изображение:</td><td><input type="text" name="image" value="/images/items/newset/default.png" size="50"></td></tr>
            <tr><td>Порядок сортировки:</td><td><input type="number" name="sort_order" value="0"></td></tr>
            <tr><th colspan="2">Базовые характеристики</th></tr>
            <tr><td>⚔️ Атака:</td><td><input type="number" name="base_attack" value="0" min="0"></td></tr>
            <tr><td>❤️ Здоровье:</td><td><input type="number" name="base_health" value="0" min="0"></td></tr>
            <tr><td>🛡️ Защита:</td><td><input type="number" name="base_defense" value="0" min="0"></td></tr>
            <tr><td>⚡ Выносливость:</td><td><input type="number" name="base_stamina" value="0" min="0"></td></tr>
            <tr><td>🎯 Точность:</td><td><input type="number" name="base_accuracy" value="0" min="0"></td></tr>
            <tr><td>🔄 Восстановление:</td><td><input type="number" name="base_recovery" value="0" min="0"></td></tr>
        </table>
        <div class="menu" style="margin-top:10px;">
            <button type="submit" name="add_item" class="btn full">➕ Добавить предмет</button>
        </div>
    </form>
</details>

<div class="hr"></div>

<!-- Таблица предметов -->
<table class="tables" border="1" cellpadding="5" style="width:100%;">
    <tr>
        <th>ID</th><th>Слот</th><th>Название</th><th>Ур.</th><th>Цена</th><th>Сорт.</th>
        <th>⚔️</th><th>❤️</th><th>🛡️</th><th>⚡</th><th>🎯</th><th>🔄</th><th>Действия</th>
    </tr>
    <?php foreach ($items as $item): ?>
    <tr>
        <form method="post">
            <input type="hidden" name="item_id" value="<?= $item['id'] ?>">
            <td><?= $item['id'] ?></td>
            <td>
                <select name="slot" style="width:100px;">
                    <?php foreach ($slots_ru as $val => $ru): ?>
                        <option value="<?= $val ?>" <?= ($val == $item['slot']) ? 'selected' : '' ?>><?= $ru ?></option>
                    <?php endforeach; ?>
                </select>
            </td>
            <td><input type="text" name="item_name" value="<?= htmlspecialchars($item['item_name']) ?>" style="width:150px;"></td>
            <td><input type="number" name="level_required" value="<?= $item['level_required'] ?>" style="width:50px;"></td>
            <td><input type="number" name="price_gold" value="<?= $item['price_gold'] ?>" style="width:60px;"></td>
            <td><input type="number" name="sort_order" value="<?= $item['sort_order'] ?>" style="width:50px;"></td>
            <td><input type="number" name="base_attack" value="<?= $item['base_attack'] ?>" style="width:50px;"></td>
            <td><input type="number" name="base_health" value="<?= $item['base_health'] ?>" style="width:50px;"></td>
            <td><input type="number" name="base_defense" value="<?= $item['base_defense'] ?>" style="width:50px;"></td>
            <td><input type="number" name="base_stamina" value="<?= $item['base_stamina'] ?>" style="width:50px;"></td>
            <td><input type="number" name="base_accuracy" value="<?= $item['base_accuracy'] ?>" style="width:50px;"></td>
            <td><input type="number" name="base_recovery" value="<?= $item['base_recovery'] ?>" style="width:50px;"></td>
            <td>
                <input type="text" name="image" placeholder="изобр." value="<?= htmlspecialchars($item['image']) ?>" style="width:100px;">
                <textarea name="description" placeholder="описание" style="width:150px;"><?= htmlspecialchars($item['description'] ?? '') ?></textarea><br>
                <button type="submit" name="edit_item" class="btn-mini" title="Сохранить">💾</button>
                <button type="submit" name="delete_item" class="btn-mini" title="Удалить" onclick="return confirm('Удалить предмет?');">❌</button>
            </td>
        </form>
    </tr>
    <?php endforeach; ?>
</table>

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