<?php
require_once "../includes/config.php";

$message = "";

// Fetch champions for optional restriction
$champStmt = $pdo->query("SELECT id, name FROM champions ORDER BY name ASC");
$champions = $champStmt->fetchAll();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $title        = $_POST['title'];
    $subtitle     = $_POST['subtitle'];
    $rarity       = $_POST['rarity'] ?? 'none';
    $category     = $_POST['category'] ?? 'misc';
    $champion_id  = !empty($_POST['champion_id']) ? intval($_POST['champion_id']) : null;
    $quantity     = !empty($_POST['quantity']) ? intval($_POST['quantity']) : null;
    $quantity_max = !empty($_POST['quantity_max']) ? intval($_POST['quantity_max']) : null;

    // Stats JSON
    $stats_json = "{}";
    if (!empty($_POST['stat_key']) && !empty($_POST['stat_value'])) {
        $stats = [];
        foreach ($_POST['stat_key'] as $i => $key) {
            $key = trim($key);
            $value = trim($_POST['stat_value'][$i]);
            if ($key !== "" && $value !== "") {
                $stats[$key] = $value;
            }
        }
        $stats_json = json_encode($stats);
    }

    // Handle image upload
    $image_path = null;

    if (!empty($_FILES['image']['name'])) {
        $uploadDir = ITEM_IMAGES_PATH;
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $filename   = time() . "_" . basename($_FILES['image']['name']);
        $targetPath = $uploadDir . $filename;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $targetPath)) {
            $image_path = "assets/images/items/" . $filename;
        }
    }

    // Insert item
    $stmt = $pdo->prepare("
        INSERT INTO items 
        (title, subtitle, image_path, rarity, category, champion_id, quantity, quantity_max, stats_json)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $stmt->execute([
        $title,
        $subtitle,
        $image_path,
        $rarity,
        $category,
        $champion_id,
        $quantity,
        $quantity_max,
        $stats_json
    ]);

    $message = "Item successfully added!";
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Add Item</title>
    <link rel="stylesheet" href="../assets/css/style.css">

    <style>
        .form-container {
            width: 700px;
            margin: 0 auto;
            background: #1a1a1f;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #444;
            color: #eee;
        }

        label { margin-top: 10px; display: block; }
        input, select, textarea {
            width: 100%;
            padding: 6px;
            margin-top: 4px;
            background: #222;
            border: 1px solid #444;
            color: #eee;
            border-radius: 4px;
        }

        .stats-row {
            display: flex;
            gap: 10px;
            margin-bottom: 6px;
        }

        .add-stat-btn {
            background: #444;
            padding: 6px 10px;
            border-radius: 4px;
            cursor: pointer;
            color: #eee;
            margin-top: 6px;
            display: inline-block;
        }

        .submit-btn {
            margin-top: 15px;
            background: #7a0000;
            border: none;
            padding: 10px 14px;
            color: white;
            cursor: pointer;
            border-radius: 4px;
        }

        .submit-btn:hover {
            background: #a00000;
        }

        .success-message {
            background: #2d662d;
            padding: 10px;
            border-radius: 4px;
            color: #c8ffc8;
            margin-bottom: 15px;
        }
    </style>

    <script>
        function addStatRow() {
            const container = document.getElementById("stats-container");
            const row = document.createElement("div");
            row.className = "stats-row";
            row.innerHTML = `
                <input type="text" name="stat_key[]" placeholder="Stat name">
                <input type="text" name="stat_value[]" placeholder="Value">
            `;
            container.appendChild(row);
        }
    </script>
</head>
<body>

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

<div class="form-container">

    <h1>Add New Item</h1>

    <?php if ($message): ?>
        <div class="success-message"><?= $message ?></div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data">

        <label>Title</label>
        <input type="text" name="title" required>

        <label>Subtitle (optional)</label>
        <input type="text" name="subtitle">

        <label>Rarity</label>
        <select name="rarity">
            <option value="none">None</option>
            <option value="common">Common</option>
            <option value="rare">Rare</option>
            <option value="epic">Epic</option>
            <option value="legendary">Legendary</option>
        </select>

        <label>Assign to Tab</label>
        <select name="category">
            <option value="tab1">TAB1</option>
            <option value="tab2">TAB2</option>
            <option value="tab3">TAB3</option>
            <option value="misc">MISC</option>
        </select>

        <label>Champion Restriction (optional)</label>
        <select name="champion_id">
            <option value="">-- None --</option>
            <?php foreach ($champions as $c): ?>
                <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name']) ?></option>
            <?php endforeach; ?>
        </select>

        <label>Quantity</label>
        <input type="number" name="quantity" min="0">

        <label>Max Quantity (optional)</label>
        <input type="number" name="quantity_max" min="0">

        <label>Item Image (optional)</label>
        <input type="file" name="image">

        <h3>Stats (optional)</h3>
        <div id="stats-container"></div>
        <div class="add-stat-btn" onclick="addStatRow()">+ Add Stat</div>

        <button type="submit" class="submit-btn">Save Item</button>

    </form>

</div>

</body>
</html>