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

$user = User::current();
$category = $_GET['cat'] ?? 'weapon';
$valid_cats = ['weapon', 'helmet', 'armor', 'shield', 'gloves', 'boots', 'amulet', 'potion'];
if (!in_array($category, $valid_cats, true)) {
    $category = 'weapon';
}

// Satın alma işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['buy'])) {
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        flash_set('error', __('err_csrf'));
        redirect(APP_URL . '/shop.php?cat=' . $category);
    }

    $itemId = (int)($_POST['item_id'] ?? 0);
    $item = DB::fetchOne("SELECT * FROM items WHERE id = :i AND is_active = 1", [':i' => $itemId]);

    if (!$item) {
        flash_set('error', __('err_item_not_found'));
    } elseif ((int)$user['level'] < (int)$item['required_level']) {
        flash_set('error', __('err_level_too_low', ['level' => $item['required_level']]));
    } elseif ((int)$user['gold'] < (int)$item['cost_gold']) {
        flash_set('error', __('err_not_enough_gold'));
    } elseif ((int)$user['hellstones'] < (int)$item['cost_hellstones']) {
        flash_set('error', __('err_not_enough_stones'));
    } else {
        // Transaction ile güvenli satın alma
        try {
            DB::beginTransaction();
            DB::execute(
                "UPDATE users SET gold = gold - :g, hellstones = hellstones - :h WHERE id = :u",
                [':g' => $item['cost_gold'], ':h' => $item['cost_hellstones'], ':u' => $user['id']]
            );
            DB::execute(
                "INSERT INTO user_items (user_id, item_id, equipped, durability, acquired_at)
                 VALUES (:u, :i, 0, 100, :t)",
                [':u' => $user['id'], ':i' => $itemId, ':t' => time()]
            );
            DB::commit();
            flash_set('success', __('msg_item_bought', ['item' => $item['name']]));
        } catch (Throwable $e) {
            DB::rollback();
            flash_set('error', APP_DEBUG ? $e->getMessage() : __('error'));
        }
    }
    redirect(APP_URL . '/shop.php?cat=' . $category);
}

// Item listesi
$items = DB::fetchAll(
    "SELECT * FROM items
     WHERE category = :c AND is_active = 1
     ORDER BY required_level ASC, cost_gold ASC",
    [':c' => $category]
);

$page_title = __('shop_title');
require __DIR__ . '/includes/header.php';
?>

<h1>🏪 <?= e(__('shop_title')) ?></h1>

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

<p class="text-muted mb-1">
    💰 <?= format_number((int)$user['gold']) ?> &middot;
    🔥 <?= format_number((int)$user['hellstones']) ?> &middot;
    <?= __('level') ?>: <?= (int)$user['level'] ?>
</p>

<?php if (empty($items)): ?>
    <p class="text-muted text-center" style="padding: 2rem;"><?= __('item_not_found') ?? '—' ?></p>
<?php else: ?>
<div class="items-grid">
    <?php foreach ($items as $item):
        $afford_gold = (int)$user['gold'] >= (int)$item['cost_gold'];
        $afford_stones = (int)$user['hellstones'] >= (int)$item['cost_hellstones'];
        $level_ok = (int)$user['level'] >= (int)$item['required_level'];
        $can_buy = $afford_gold && $afford_stones && $level_ok;
        $img_path = APP_URL . '/assets/img/item/' . (int)$item['id'] . '.jpg';
    ?>
        <div class="item-card">
            <img src="<?= $img_path ?>" alt="<?= e($item['name']) ?>" class="item-img"
                 onerror="this.style.display='none'">
            <div class="item-name"><?= e($item['name']) ?></div>
            <div class="item-stats">
                <?= __('item_level') ?>: <strong><?= (int)$item['required_level'] ?></strong>
            </div>
            <div class="item-stats">
                <?php
                $bonuses = [];
                if ((int)$item['bonus_pow'])  $bonuses[] = '+' . $item['bonus_pow'] . ' ' . __('power');
                if ((int)$item['bonus_def'])  $bonuses[] = '+' . $item['bonus_def'] . ' ' . __('defense');
                if ((int)$item['bonus_agi'])  $bonuses[] = '+' . $item['bonus_agi'] . ' ' . __('agility');
                if ((int)$item['bonus_stam']) $bonuses[] = '+' . $item['bonus_stam'] . ' ' . __('stamina');
                if ((int)$item['bonus_chr'])  $bonuses[] = '+' . $item['bonus_chr'] . ' ' . __('charisma');
                ?>
                <?php foreach ($bonuses as $b): ?>
                    <div class="item-bonus"><?= e($b) ?></div>
                <?php endforeach; ?>
            </div>
            <div class="item-cost">
                <?php if ((int)$item['cost_gold'] > 0): ?>
                    💰 <?= format_number((int)$item['cost_gold']) ?>
                <?php endif; ?>
                <?php if ((int)$item['cost_hellstones'] > 0): ?>
                    🔥 <?= (int)$item['cost_hellstones'] ?>
                <?php endif; ?>
            </div>
            <form method="post" style="margin-top:0.5rem;">
                <?= csrf_field() ?>
                <input type="hidden" name="item_id" value="<?= (int)$item['id'] ?>">
                <button type="submit" name="buy" value="1"
                        class="btn btn-sm" style="width:100%;"
                        <?= $can_buy ? '' : 'disabled' ?>>
                    <?= __('item_buy') ?>
                </button>
            </form>
        </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<?php require __DIR__ . '/includes/footer.php'; ?>
