<?php
require_once "../includes/db.php";
require_once "../includes/functions.php";

$todaysChampion = getTodaysChampion($pdo);
$todaysChampionId = $todaysChampion['id'];

$category = $_GET['cat'] ?? 'all';
$search   = $_GET['q']   ?? '';
$sort     = $_GET['sort'] ?? 'newest';

$sql = "
    SELECT i.*, c.name AS champion_name
    FROM items i
    LEFT JOIN champions c ON c.id = i.champion_id
    WHERE 1=1
";

$params = [];

if ($category !== 'all') {
    $sql .= " AND i.category = ? ";
    $params[] = $category;
}

if ($search !== '') {
    $sql .= " AND (i.title LIKE ? OR i.subtitle LIKE ?) ";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

switch ($sort) {
    case 'title':
        $sql .= " ORDER BY i.title ASC";
        break;
    case 'rarity':
        $sql .= " ORDER BY FIELD(i.rarity,'legendary','epic','rare','common'), i.title ASC";
        break;
    default:
        $sql .= " ORDER BY i.id DESC";
}

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$items = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Inventory</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
        .inventory-container {
            width: 1000px;
            margin: 0 auto;
            color: #eee;
        }

        .inventory-title {
            text-align: center;
            color: #ffcc66;
            margin-bottom: 10px;
        }

        .inv-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .tabs a {
            color: #ccc;
            margin-right: 10px;
            text-decoration: none;
            padding: 4px 8px;
            border-radius: 4px;
            border: 1px solid #444;
        }

        .tabs .active {
            background: #ffcc66;
            color: #000;
        }

        .inventory-grid {
            display: grid;
            grid-template-columns: repeat(8, 70px);
            grid-auto-rows: 70px;
            gap: 6px;
            background: #111;
            padding: 10px;
            border: 1px solid #444;
        }

        .slot {
            background: #1a1a1f;
            border: 1px solid #333;
            position: relative;
            cursor: pointer;
        }

        .slot img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .restricted {
            opacity: 0.3;
            filter: grayscale(100%);
        }

        .rarity-common    { border-color: #777; }
        .rarity-rare      { border-color: #3b82f6; box-shadow: 0 0 6px rgba(59,130,246,0.6); }
        .rarity-epic      { border-color: #a855f7; box-shadow: 0 0 6px rgba(168,85,247,0.7); }
        .rarity-legendary { border-color: #f59e0b; box-shadow: 0 0 8px rgba(245,158,11,0.8); }

        .quantity-badge {
            position: absolute;
            bottom: 2px;
            right: 4px;
            background: rgba(0,0,0,0.8);
            padding: 2px 4px;
            font-size: 11px;
            border-radius: 3px;
        }

        #tooltip {
            position: fixed;
            background: rgba(0,0,0,0.9);
            color: #fff;
            padding: 10px;
            border: 1px solid #aaa;
            border-radius: 6px;
            display: none;
            z-index: 9999;
            max-width: 260px;
            font-size: 13px;
        }

        .item-title { font-weight: bold; color: #ffcc66; }
        .item-subtitle { font-size: 12px; color: #ccc; }
        .restricted-note { color: #ff6666; font-size: 12px; margin-top: 5px; }
    </style>
</head>
<body>

<?php include "../includes/menu.php"; ?>

<div class="inventory-container">

    <h1 class="inventory-title">Inventory</h1>
    <h3 style="text-align:center; margin-bottom:15px;">
        Today’s Champion: <?= $todaysChampion['name'] ?> (<?= $todaysChampion['class_name'] ?>)
    </h3>

    <div class="inv-controls">
        <div class="tabs">
            <?php
            $tabs = [
                'all'         => 'All',
                'supplements' => 'Supplements',
                'medicines'   => 'Medicines',
                'prepost'     => 'Pre & In/Post',
                'misc'        => 'Misc'
            ];
            foreach ($tabs as $key => $label) {
                $cls = $category === $key ? 'active' : '';
                echo "<a class='$cls' href='?cat=$key&sort=$sort&q=" . urlencode($search) . "'>$label</a>";
            }
            ?>
        </div>

        <form method="GET" style="display:flex; gap:8px; align-items:center;">
            <input type="hidden" name="cat" value="<?= htmlspecialchars($category) ?>">
            <input type="text" name="q" placeholder="Search..." value="<?= htmlspecialchars($search) ?>" style="padding:4px 6px;">
            <select name="sort" style="padding:4px 6px;">
                <option value="newest" <?= $sort=='newest'?'selected':'' ?>>Newest</option>
                <option value="title"  <?= $sort=='title'?'selected':'' ?>>Title</option>
                <option value="rarity" <?= $sort=='rarity'?'selected':'' ?>>Rarity</option>
            </select>
            <button type="submit" style="padding:4px 8px;">Go</button>
        </form>
    </div>

    <div class="inventory-grid">

        <?php foreach ($items as $item): ?>
            <?php
            $restricted = ($item['champion_id'] !== null && $item['champion_id'] != $todaysChampionId);
            $rarityClass = $item['rarity'] ? 'rarity-' . strtolower($item['rarity']) : 'rarity-common';

            $qtyText = '';
            if (!is_null($item['quantity']) && !is_null($item['quantity_max']) && $item['quantity_max'] > 0) {
                $percent = round(($item['quantity'] / $item['quantity_max']) * 100);
                $qtyText = $item['quantity'] . '/' . $item['quantity_max'] . ' (' . $percent . '%)';
            } elseif (!is_null($item['quantity'])) {
                $qtyText = $item['quantity'];
            }
            ?>
            <div class="slot <?= $restricted ? 'restricted' : '' ?> <?= $rarityClass ?>"
                 data-title="<?= htmlspecialchars($item['title']) ?>"
                 data-subtitle="<?= htmlspecialchars($item['subtitle']) ?>"
                 data-url="<?= htmlspecialchars($item['item_url']) ?>"
                 data-stats='<?= htmlspecialchars($item['stats_json']) ?>'
                 data-restricted="<?= $restricted ? '1' : '0' ?>"
                 data-champion="<?= htmlspecialchars($item['champion_name']) ?>"
                 data-qty="<?= htmlspecialchars($qtyText) ?>">

                <?php if ($item['image_path']): ?>
                    <img src="../<?= $item['image_path'] ?>" alt="">
                <?php endif; ?>

                <?php if ($qtyText): ?>
                    <div class="quantity-badge"><?= $qtyText ?></div>
                <?php endif; ?>

            </div>
        <?php endforeach; ?>

    </div>

</div>

<div id="tooltip"></div>

<script>
const tooltip = document.getElementById("tooltip");

document.querySelectorAll(".slot").forEach(slot => {

    slot.addEventListener("mousemove", e => {
        const title      = slot.dataset.title;
        const subtitle   = slot.dataset.subtitle;
        const stats      = JSON.parse(slot.dataset.stats || "{}");
        const restricted = slot.dataset.restricted === "1";
        const restrictedTo = slot.dataset.champion;
        const qty        = slot.dataset.qty;

        let html = `<div class='item-title'>${title}</div>`;
        if (subtitle) html += `<div class='item-subtitle'>${subtitle}</div>`;

        if (qty) {
            html += `<div style="margin-top:4px;"><strong>Quantity:</strong> ${qty}</div>`;
        }

        html += "<hr>";

        for (const key in stats) {
            html += `<div><strong>${key}:</strong> ${stats[key]}</div>`;
        }

        if (restricted) {
            html += `<div class='restricted-note'>Usable only by ${restrictedTo}</div>`;
        }

        tooltip.innerHTML = html;
        tooltip.style.left = (e.pageX + 15) + "px";
        tooltip.style.top  = (e.pageY + 15) + "px";
        tooltip.style.display = "block";
    });

    slot.addEventListener("mouseleave", () => {
        tooltip.style.display = "none";
    });

});
</script>

</body>
</html>