<?php
require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/_helpers.php';
require_admin();

$valid_cats = ['weapon', 'armor', 'helmet', 'shield', 'gloves', 'boots', 'amulet', 'potion'];

// İşlem
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        flash_set('error', __('err_csrf'));
        redirect(APP_URL . '/admin/items.php');
    }

    $action = $_POST['action'] ?? '';

    if ($action === 'create' || $action === 'update') {
        $data = [
            ':category'        => in_array($_POST['category'] ?? '', $valid_cats, true) ? $_POST['category'] : 'weapon',
            ':name'            => trim((string)($_POST['name'] ?? '')),
            ':required_level'  => max(0, (int)($_POST['required_level'] ?? 0)),
            ':cost_gold'       => max(0, (int)($_POST['cost_gold'] ?? 0)),
            ':cost_hellstones' => max(0, (int)($_POST['cost_hellstones'] ?? 0)),
            ':bonus_pow'       => (int)($_POST['bonus_pow'] ?? 0),
            ':bonus_def'       => (int)($_POST['bonus_def'] ?? 0),
            ':bonus_agi'       => (int)($_POST['bonus_agi'] ?? 0),
            ':bonus_stam'      => (int)($_POST['bonus_stam'] ?? 0),
            ':bonus_chr'       => (int)($_POST['bonus_chr'] ?? 0),
            ':is_active'       => isset($_POST['is_active']) ? 1 : 0,
        ];

        if ($data[':name'] === '') {
            flash_set('error', __('error'));
            redirect(APP_URL . '/admin/items.php');
        }

        if ($action === 'create') {
            DB::execute(
                "INSERT INTO items (category, name, required_level, cost_gold, cost_hellstones,
                                    bonus_pow, bonus_def, bonus_agi, bonus_stam, bonus_chr, is_active)
                 VALUES (:category, :name, :required_level, :cost_gold, :cost_hellstones,
                         :bonus_pow, :bonus_def, :bonus_agi, :bonus_stam, :bonus_chr, :is_active)",
                $data
            );
            $newId = DB::lastInsertId();
            admin_log('item_create', $newId, "Created item: {$data[':name']}");
            flash_set('success', __('admin_action_done'));
        } else {
            $id = (int)($_POST['id'] ?? 0);
            $data[':id'] = $id;
            DB::execute(
                "UPDATE items SET category = :category, name = :name, required_level = :required_level,
                        cost_gold = :cost_gold, cost_hellstones = :cost_hellstones,
                        bonus_pow = :bonus_pow, bonus_def = :bonus_def, bonus_agi = :bonus_agi,
                        bonus_stam = :bonus_stam, bonus_chr = :bonus_chr, is_active = :is_active
                 WHERE id = :id",
                $data
            );
            admin_log('item_update', $id, "Updated item: {$data[':name']}");
            flash_set('success', __('admin_action_done'));
        }
    } elseif ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        DB::execute("DELETE FROM items WHERE id = :i", [':i' => $id]);
        admin_log('item_delete', $id, "Deleted item ID: {$id}");
        flash_set('success', __('admin_action_done'));
    }
    redirect(APP_URL . '/admin/items.php');
}

// Edit modu
$editItem = null;
if (isset($_GET['edit'])) {
    $editItem = DB::fetchOne("SELECT * FROM items WHERE id = :i", [':i' => (int)$_GET['edit']]);
}

// Liste
$cat = $_GET['cat'] ?? 'weapon';
$search = trim((string)($_GET['q'] ?? ''));
if (!in_array($cat, $valid_cats, true)) $cat = 'weapon';

$where = "category = :c";
$params = [':c' => $cat];
if ($search !== '') {
    $where .= " AND name LIKE :q";
    $params[':q'] = "%{$search}%";
}
$items = DB::fetchAll(
    "SELECT * FROM items WHERE {$where} ORDER BY required_level ASC LIMIT 100",
    $params
);

$page_title = __('admin_items');
require __DIR__ . '/_header.php';
?>

<h1>⚔ <?= e(__('admin_items')) ?></h1>

<!-- Yeni / Düzenle Form -->
<details class="card" <?= $editItem ? 'open' : '' ?>>
    <summary style="cursor:pointer; color: var(--accent); font-weight:bold;">
        <?= $editItem ? __('edit') . ': ' . e($editItem['name']) : '➕ ' . __('add') ?>
    </summary>
    <form method="post" style="margin-top:1rem;">
        <?= csrf_field() ?>
        <?php if ($editItem): ?>
            <input type="hidden" name="id" value="<?= (int)$editItem['id'] ?>">
        <?php endif; ?>

        <div style="display:grid; grid-template-columns: 1fr 1fr; gap:1rem;">
            <div class="form-row">
                <label><?= __('item_name') ?></label>
                <input type="text" name="name" value="<?= e($editItem['name'] ?? '') ?>" required>
            </div>
            <div class="form-row">
                <label><?= __('item_category') ?></label>
                <select name="category">
                    <?php foreach ($valid_cats as $c): ?>
                        <option value="<?= $c ?>" <?= ($editItem['category'] ?? 'weapon') === $c ? 'selected' : '' ?>>
                            <?= __('cat_' . $c) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-row">
                <label><?= __('item_level') ?></label>
                <input type="number" name="required_level" value="<?= (int)($editItem['required_level'] ?? 0) ?>" min="0">
            </div>
            <div class="form-row">
                <label><?= __('cost') ?? 'Cost' ?> 💰</label>
                <input type="number" name="cost_gold" value="<?= (int)($editItem['cost_gold'] ?? 0) ?>" min="0">
            </div>
            <div class="form-row">
                <label>🔥 <?= __('hellstones') ?></label>
                <input type="number" name="cost_hellstones" value="<?= (int)($editItem['cost_hellstones'] ?? 0) ?>" min="0">
            </div>
            <div class="form-row">
                <label>+<?= __('power') ?></label>
                <input type="number" name="bonus_pow" value="<?= (int)($editItem['bonus_pow'] ?? 0) ?>">
            </div>
            <div class="form-row">
                <label>+<?= __('defense') ?></label>
                <input type="number" name="bonus_def" value="<?= (int)($editItem['bonus_def'] ?? 0) ?>">
            </div>
            <div class="form-row">
                <label>+<?= __('agility') ?></label>
                <input type="number" name="bonus_agi" value="<?= (int)($editItem['bonus_agi'] ?? 0) ?>">
            </div>
            <div class="form-row">
                <label>+<?= __('stamina') ?></label>
                <input type="number" name="bonus_stam" value="<?= (int)($editItem['bonus_stam'] ?? 0) ?>">
            </div>
            <div class="form-row">
                <label>+<?= __('charisma') ?></label>
                <input type="number" name="bonus_chr" value="<?= (int)($editItem['bonus_chr'] ?? 0) ?>">
            </div>
        </div>
        <div class="form-row">
            <label style="text-transform:none;">
                <input type="checkbox" name="is_active" value="1" <?= !$editItem || (int)($editItem['is_active']) === 1 ? 'checked' : '' ?>>
                Aktif (dükkanın listesinde görünür)
            </label>
        </div>

        <button type="submit" name="action" value="<?= $editItem ? 'update' : 'create' ?>">
            <?= __('save') ?>
        </button>
        <?php if ($editItem): ?>
            <a href="<?= APP_URL ?>/admin/items.php" class="btn btn-secondary"><?= __('cancel') ?></a>
        <?php endif; ?>
    </form>
</details>

<!-- Liste -->
<div class="tabs" style="flex-wrap:wrap;">
    <?php foreach ($valid_cats as $c): ?>
        <a href="?cat=<?= $c ?>" class="<?= $c === $cat ? 'active' : '' ?>"><?= __('cat_' . $c) ?></a>
    <?php endforeach; ?>
</div>

<form method="get" style="margin-bottom:1rem;">
    <input type="hidden" name="cat" value="<?= e($cat) ?>">
    <input type="text" name="q" value="<?= e($search) ?>" placeholder="<?= __('search') ?>..." style="max-width:300px; display:inline-block;">
    <button type="submit" class="btn btn-sm"><?= __('search') ?></button>
</form>

<table class="tbl">
    <thead>
        <tr>
            <th>ID</th>
            <th><?= __('item_name') ?></th>
            <th><?= __('item_level') ?></th>
            <th><?= __('item_cost') ?></th>
            <th>+ Bonus</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($items as $it): ?>
        <tr <?= !$it['is_active'] ? 'style="opacity:0.5"' : '' ?>>
            <td><?= (int)$it['id'] ?></td>
            <td>
                <img src="<?= APP_URL ?>/assets/img/item/<?= (int)$it['id'] ?>.jpg"
                     alt="" style="width:32px; height:32px; vertical-align:middle; margin-right:0.5rem; border:1px solid var(--border); border-radius:3px;"
                     onerror="this.style.display='none'">
                <strong><?= e($it['name']) ?></strong>
            </td>
            <td><?= (int)$it['required_level'] ?></td>
            <td>
                <?php if ((int)$it['cost_gold'] > 0): ?>💰<?= format_number((int)$it['cost_gold']) ?><?php endif; ?>
                <?php if ((int)$it['cost_hellstones'] > 0): ?> 🔥<?= (int)$it['cost_hellstones'] ?><?php endif; ?>
            </td>
            <td class="text-muted">
                <?php
                $bonuses = [];
                if ((int)$it['bonus_pow']) $bonuses[] = '+' . $it['bonus_pow'] . ' P';
                if ((int)$it['bonus_def']) $bonuses[] = '+' . $it['bonus_def'] . ' D';
                if ((int)$it['bonus_agi']) $bonuses[] = '+' . $it['bonus_agi'] . ' A';
                if ((int)$it['bonus_stam']) $bonuses[] = '+' . $it['bonus_stam'] . ' S';
                if ((int)$it['bonus_chr']) $bonuses[] = '+' . $it['bonus_chr'] . ' C';
                echo e(implode(', ', $bonuses));
                ?>
            </td>
            <td>
                <a href="?cat=<?= e($cat) ?>&edit=<?= (int)$it['id'] ?>" class="btn btn-sm btn-secondary"><?= __('edit') ?></a>
                <form method="post" style="display:inline;" onsubmit="return confirm('<?= e(__('admin_confirm_delete')) ?>')">
                    <?= csrf_field() ?>
                    <input type="hidden" name="id" value="<?= (int)$it['id'] ?>">
                    <button type="submit" name="action" value="delete" class="btn btn-sm btn-danger"><?= __('delete') ?></button>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<?php require __DIR__ . '/_footer.php'; ?>
