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

$user = User::current();

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

    $userItemId = (int)($_POST['user_item_id'] ?? 0);
    $action = $_POST['action'] ?? '';

    // Bu user_item gerçekten bu kullanıcıya mı ait?
    $ui = DB::fetchOne(
        "SELECT ui.*, i.name AS item_name, i.category, i.cost_gold
         FROM user_items ui
         JOIN items i ON ui.item_id = i.id
         WHERE ui.id = :id AND ui.user_id = :u",
        [':id' => $userItemId, ':u' => $user['id']]
    );

    if (!$ui) {
        flash_set('error', __('err_item_not_yours'));
    } elseif ($action === 'equip') {
        // Aynı kategorideki diğerlerini çıkar, bunu kuşan
        try {
            DB::beginTransaction();
            DB::execute(
                "UPDATE user_items ui
                 JOIN items i ON ui.item_id = i.id
                 SET ui.equipped = 0
                 WHERE ui.user_id = :u AND i.category = :c AND ui.equipped = 1",
                [':u' => $user['id'], ':c' => $ui['category']]
            );
            DB::execute(
                "UPDATE user_items SET equipped = 1 WHERE id = :id",
                [':id' => $userItemId]
            );
            DB::commit();
            flash_set('success', __('msg_item_equipped', ['item' => $ui['item_name']]));
        } catch (Throwable $e) {
            DB::rollback();
            flash_set('error', __('error'));
        }
    } elseif ($action === 'unequip') {
        DB::execute("UPDATE user_items SET equipped = 0 WHERE id = :id", [':id' => $userItemId]);
        flash_set('success', __('msg_item_unequipped', ['item' => $ui['item_name']]));
    } elseif ($action === 'sell') {
        // Satış fiyatı: orijinal altın fiyatının %50'si
        $sellPrice = (int) floor((int)$ui['cost_gold'] * 0.5);
        try {
            DB::beginTransaction();
            DB::execute("DELETE FROM user_items WHERE id = :id", [':id' => $userItemId]);
            DB::execute(
                "UPDATE users SET gold = gold + :p WHERE id = :u",
                [':p' => $sellPrice, ':u' => $user['id']]
            );
            DB::commit();
            flash_set('success', __('msg_item_sold', ['item' => $ui['item_name'], 'gold' => format_number($sellPrice)]));
        } catch (Throwable $e) {
            DB::rollback();
            flash_set('error', __('error'));
        }
    }

    redirect(APP_URL . '/hideout.php');
}

$items = User::items((int)$user['id']);

// Kategoriye göre grupla
$grouped = ['equipped' => [], 'inventory' => []];
foreach ($items as $it) {
    if ((int)$it['equipped'] === 1) {
        $grouped['equipped'][] = $it;
    } else {
        $grouped['inventory'][] = $it;
    }
}

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

<h1>🏚 <?= e(__('menu_hideout')) ?></h1>

<h2><?= __('equipment') ?> (<?= count($grouped['equipped']) ?>)</h2>
<?php if (empty($grouped['equipped'])): ?>
    <p class="text-muted">—</p>
<?php else: ?>
<div class="items-grid">
    <?php foreach ($grouped['equipped'] as $it):
        $img_path = APP_URL . '/assets/img/item/' . (int)$it['id'] . '.jpg';
    ?>
        <div class="item-card equipped">
            <img src="<?= $img_path ?>" alt="<?= e($it['name']) ?>" class="item-img"
                 onerror="this.style.display='none'">
            <div class="item-name"><?= e($it['name']) ?></div>
            <div class="item-stats text-muted"><?= e(__('cat_' . $it['category'])) ?></div>
            <div class="item-stats">
                <?php
                if ((int)$it['bonus_pow'])  echo '<div class="item-bonus">+' . (int)$it['bonus_pow'] . ' ' . __('power') . '</div>';
                if ((int)$it['bonus_def'])  echo '<div class="item-bonus">+' . (int)$it['bonus_def'] . ' ' . __('defense') . '</div>';
                if ((int)$it['bonus_agi'])  echo '<div class="item-bonus">+' . (int)$it['bonus_agi'] . ' ' . __('agility') . '</div>';
                if ((int)$it['bonus_stam']) echo '<div class="item-bonus">+' . (int)$it['bonus_stam'] . ' ' . __('stamina') . '</div>';
                if ((int)$it['bonus_chr'])  echo '<div class="item-bonus">+' . (int)$it['bonus_chr'] . ' ' . __('charisma') . '</div>';
                ?>
            </div>
            <form method="post" style="margin-top:0.5rem;">
                <?= csrf_field() ?>
                <input type="hidden" name="user_item_id" value="<?= (int)$it['user_item_id'] ?>">
                <button type="submit" name="action" value="unequip" class="btn btn-sm btn-secondary" style="width:100%;">
                    <?= __('item_unequip') ?>
                </button>
            </form>
        </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<hr class="divider">

<h2><?= __('inventory') ?> (<?= count($grouped['inventory']) ?>)</h2>
<?php if (empty($grouped['inventory'])): ?>
    <p class="text-muted">—</p>
<?php else: ?>
<div class="items-grid">
    <?php foreach ($grouped['inventory'] as $it):
        $sellPrice = (int) floor((int)$it['cost_gold'] * 0.5);
        $img_path = APP_URL . '/assets/img/item/' . (int)$it['id'] . '.jpg';
    ?>
        <div class="item-card">
            <img src="<?= $img_path ?>" alt="<?= e($it['name']) ?>" class="item-img"
                 onerror="this.style.display='none'">
            <div class="item-name"><?= e($it['name']) ?></div>
            <div class="item-stats text-muted"><?= e(__('cat_' . $it['category'])) ?></div>
            <div class="item-stats">
                <?php
                if ((int)$it['bonus_pow'])  echo '<div class="item-bonus">+' . (int)$it['bonus_pow'] . ' ' . __('power') . '</div>';
                if ((int)$it['bonus_def'])  echo '<div class="item-bonus">+' . (int)$it['bonus_def'] . ' ' . __('defense') . '</div>';
                if ((int)$it['bonus_agi'])  echo '<div class="item-bonus">+' . (int)$it['bonus_agi'] . ' ' . __('agility') . '</div>';
                if ((int)$it['bonus_stam']) echo '<div class="item-bonus">+' . (int)$it['bonus_stam'] . ' ' . __('stamina') . '</div>';
                if ((int)$it['bonus_chr'])  echo '<div class="item-bonus">+' . (int)$it['bonus_chr'] . ' ' . __('charisma') . '</div>';
                ?>
            </div>
            <form method="post" style="margin-top:0.5rem; display:flex; gap:0.3rem;">
                <?= csrf_field() ?>
                <input type="hidden" name="user_item_id" value="<?= (int)$it['user_item_id'] ?>">
                <button type="submit" name="action" value="equip" class="btn btn-sm" style="flex:1;">
                    <?= __('item_equip') ?>
                </button>
                <button type="submit" name="action" value="sell" class="btn btn-sm btn-secondary"
                        onclick="return confirm('<?= e(__('item_sell')) ?>: <?= format_number($sellPrice) ?> 💰?')">
                    <?= __('item_sell') ?> (<?= format_number($sellPrice) ?>)
                </button>
            </form>
        </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

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