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

$message = "";

// Fetch champions for dropdown
$champions = getAllChampions($pdo);

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

    $title = $_POST['title'];
    $subtitle = $_POST['subtitle'];
    $item_url = $_POST['item_url'];
    $stats_json = $_POST['stats_json'];

    // Champion assignment (NULL = global item)
    $champion_id = !empty($_POST['champion_id']) ? $_POST['champion_id'] : null;

    // Handle image upload
    $image_path = null;

    if (!empty($_FILES['image']['name'])) {
        $uploadDir = "../assets/images/items/";
        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 into database
    $stmt = $pdo->prepare("
        INSERT INTO items (title, subtitle, image_path, item_url, stats_json, champion_id)
        VALUES (?, ?, ?, ?, ?, ?)
    ");

    $stmt->execute([
        $title,
        $subtitle,
        $image_path,
        $item_url,
        $stats_json,
        $champion_id
    ]);

    $message = "Item successfully uploaded!";
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Upload Inventory Item</title>
    <link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>

<div class="form-container">

    <h1>Upload New Inventory Item</h1>

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

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

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

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

        <label>Item URL (optional)</label>
        <input type="url" name="item_url">

        <label>Assign to Champion (optional)</label>
        <select name="champion_id">
            <option value="">Global Item (usable by all)</option>
            <?php foreach ($champions as $champ): ?>
                <option value="<?= $champ['id'] ?>">
                    <?= $champ['name'] ?> (<?= $champ['class_name'] ?>)
                </option>
            <?php endforeach; ?>
        </select>

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

        <label>Item Stats (JSON)</label>
        <textarea name="stats_json" placeholder='{"attack":10,"defense":5,"rarity":"Rare"}'></textarea>

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

    </form>

</div>

</body>
</html>