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

// Обработка загрузки изображения
function uploadItemImage($file) {
    $targetDir = '../images/items/upload/';
    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0755, true);
    }
    $check = getimagesize($file['tmp_name']);
    if ($check === false) {
        return ['success' => false, 'message' => 'Файл не является изображением'];
    }
    if ($file['size'] > 2 * 1024 * 1024) { // 2 МБ
        return ['success' => false, 'message' => 'Файл слишком большой (макс. 2 МБ)'];
    }
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    if (!in_array($ext, $allowed)) {
        return ['success' => false, 'message' => 'Допустимые форматы: ' . implode(', ', $allowed)];
    }
    $newName = 'item_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
    $targetFile = $targetDir . $newName;
    if (move_uploaded_file($file['tmp_name'], $targetFile)) {
        return ['success' => true, 'path' => '/images/items/upload/' . $newName];
    } else {
        return ['success' => false, 'message' => 'Ошибка сохранения файла'];
    }
}

// Обработка POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Добавление предмета
        if (isset($_POST['add_item'])) {
            $name = trim($_POST['name']);
            $slot = $_POST['slot'];
            $level = (int)$_POST['level_required'];
            $image = trim($_POST['image']); // если вручную ввели путь

            // Если загружен файл
            if (!empty($_FILES['image_file']['name'])) {
                $upload = uploadItemImage($_FILES['image_file']);
                if ($upload['success']) {
                    $image = $upload['path'];
                } else {
                    throw new Exception($upload['message']);
                }
            }

            $baseAttack = (int)$_POST['base_attack'];
            $baseHealth = (int)$_POST['base_health'];
            $baseDefense = (int)$_POST['base_defense'];
            $baseStamina = (int)$_POST['base_stamina'];
            $baseAccuracy = (int)$_POST['base_accuracy'];
            $baseRecovery = (int)$_POST['base_recovery'];

            $stmt = $pdo->prepare("INSERT INTO items 
                (name, slot, level_required, image, base_attack, base_health, base_defense, base_stamina, base_accuracy, base_recovery) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $slot, $level, $image, $baseAttack, $baseHealth, $baseDefense, $baseStamina, $baseAccuracy, $baseRecovery]);

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

        // Редактирование предмета
        if (isset($_POST['edit_item'])) {
            $id = (int)$_POST['id'];
            $name = trim($_POST['name']);
            $slot = $_POST['slot'];
            $level = (int)$_POST['level_required'];
            $image = trim($_POST['image']);

            if (!empty($_FILES['image_file']['name'])) {
                $upload = uploadItemImage($_FILES['image_file']);
                if ($upload['success']) {
                    $image = $upload['path'];
                } else {
                    throw new Exception($upload['message']);
                }
            }

            $baseAttack = (int)$_POST['base_attack'];
            $baseHealth = (int)$_POST['base_health'];
            $baseDefense = (int)$_POST['base_defense'];
            $baseStamina = (int)$_POST['base_stamina'];
            $baseAccuracy = (int)$_POST['base_accuracy'];
            $baseRecovery = (int)$_POST['base_recovery'];

            $stmt = $pdo->prepare("UPDATE items SET 
                name=?, slot=?, level_required=?, image=?, base_attack=?, base_health=?, base_defense=?, base_stamina=?, base_accuracy=?, base_recovery=?
                WHERE id=?");
            $stmt->execute([$name, $slot, $level, $image, $baseAttack, $baseHealth, $baseDefense, $baseStamina, $baseAccuracy, $baseRecovery, $id]);

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

        // Удаление предмета
        if (isset($_POST['delete_item'])) {
            $id = (int)$_POST['id'];
            $stmt = $pdo->prepare("DELETE FROM items WHERE id=?");
            $stmt->execute([$id]);
            $_SESSION['admin_message'] = '✅ Предмет удалён.';
            header('Location: items.php');
            exit;
        }
    } catch (Exception $e) {
        $_SESSION['admin_message'] = '❌ Ошибка: ' . $e->getMessage();
        header('Location: items.php');
        exit;
    }
}

// Поиск и пагинация
$search = $_GET['search'] ?? '';
$slotFilter = $_GET['slot'] ?? '';
$page = (int)($_GET['page'] ?? 1);
if ($page < 1) $page = 1;
$limit = 20;
$offset = ($page - 1) * $limit;

$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM items WHERE 1";
$params = [];
if ($search) {
    $sql .= " AND (name LIKE ? OR id = ?)";
    $params[] = "%$search%";
    $params[] = is_numeric($search) ? $search : 0;
}
if ($slotFilter) {
    $sql .= " AND slot = ?";
    $params[] = $slotFilter;
}
$sql .= " ORDER BY id DESC LIMIT ? OFFSET ?";

$stmt = $pdo->prepare($sql);
$i = 1;
foreach ($params as $param) {
    $stmt->bindValue($i++, $param, is_int($param) ? PDO::PARAM_INT : PDO::PARAM_STR);
}
$stmt->bindValue($i++, $limit, PDO::PARAM_INT);
$stmt->bindValue($i++, $offset, PDO::PARAM_INT);
$stmt->execute();
$items = $stmt->fetchAll();
$total = $pdo->query("SELECT FOUND_ROWS()")->fetchColumn();

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

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>🛡️ Редактор предметов</b></span>
<div class="clb"></div>
<div class="hr"></div>

<div class="menu">
    <a class="btn full" href="index.php">← В админ-панель</a>
</div>
<div class="hr"></div>

<!-- Поиск и фильтр -->
<div class="menu">
    <form method="get" style="display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
        <span class="nwr"><img src="/images/icons/search.png" width="12" height="12"> Поиск:</span>
        <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="ID или название" style="flex:1;">
        <span class="nwr">Слот:</span>
        <select name="slot" style="width:150px;">
            <option value="">Все слоты</option>
            <?php foreach ($slots_ru as $val => $ru): ?>
                <option value="<?= $val ?>" <?= ($slotFilter == $val) ? 'selected' : '' ?>><?= $ru ?></option>
            <?php endforeach; ?>
        </select>
        <button type="submit" class="btn">Применить</button>
    </form>
</div>

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

<!-- Форма добавления нового предмета -->
<details>
    <summary style="cursor:pointer; background:#eee; padding:5px; border-radius:3px;">➕ Добавить новый предмет</summary>
    <form method="post" enctype="multipart/form-data" style="margin-top:10px; padding:10px; background:#f9f9f9;">
        <table style="width:100%;">
            <tr><td>Название:</td><td><input type="text" name="name" required size="50"></td></tr>
            <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="number" name="level_required" value="1" min="1"></td></tr>
            <tr>
                <td>Изображение (URL или загрузить):</td>
                <td>
                    <input type="text" name="image" placeholder="http://... или оставьте пустым для загрузки" style="width:70%;">
                    <input type="file" name="image_file" accept="image/*">
                </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>
    </tr>
    <?php foreach ($items as $item): ?>
    <tr>
        <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="id" value="<?= $item['id'] ?>">
            <td><?= $item['id'] ?></td>
            <td>
                <?php if ($item['image']): ?>
                    <img src="<?= htmlspecialchars($item['image']) ?>" style="max-width:50px; max-height:50px;">
                <?php endif; ?>
            </td>
            <td><input type="text" name="name" value="<?= htmlspecialchars($item['name']) ?>" style="width:150px;"></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="number" name="level_required" value="<?= $item['level_required'] ?>" 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 style="white-space:nowrap;">
                <input type="text" name="image" placeholder="URL" value="<?= htmlspecialchars($item['image']) ?>" style="width:100px;">
                <input type="file" name="image_file" accept="image/*" style="width:90px;">
                <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 if ($total > $limit): ?>
<div style="margin-top:15px;">
    Страницы: 
    <?php for ($i = 1; $i <= ceil($total / $limit); $i++): ?>
        <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&slot=<?= urlencode($slotFilter) ?>" <?= ($i == $page) ? 'style="font-weight:bold;"' : '' ?>>
            [<?= $i ?>]
        </a>
    <?php endfor; ?>
</div>
<?php endif; ?>

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