majroity

i want a plugin that makes a /redeem thing and when typed sends in chat in light blue bold PLEASE TYPE THE CODE TO RECIVE THE REWARDS. showing only for him when he types a reward the plugin has a config where a code: section is made and there typed codes you can type a code and then the command that will give rewards like /give %player% diamond 1 or something thats only an example and when the player that did /redeem types the correct code it gives it to him but when he types a wrong one it says in chat INVALID CODE showing only for him like a giftcard system make it fancy make it work

Kodari AI
KodariJun 6 at 1:20 am 1
RedeemSystem
A gift card redemption plugin where players use /redeem to enter codes from the config. Features a fancy chat prompt system that adds players to a pending state, listens for their next chat message silently (cancelled event, no broadcast), validates the code against config-defined codes, and executes reward commands like /give %player% diamond 1. Invalid codes show an error message only to the player. Includes premium-style ASCII box UI.
majroity

make it that it can be redeemed once every player and make it more simple not huge text make it like a big plugin

Kodari AI
KodariJun 6 at 1:25 am 2

Now I see the current state. The user wants:

  1. One-time per player — each code can only be claimed once per player

  2. Simpler fancy UI — not the massive ASCII blocks, still stylish but compact

Let me rewrite everything

Now rewrite the plugin with per-player tracking:

Done. Here’s what changed:

Per-player one-time redemption — redeemed.yml stores which codes each player has claimed. If they try the same code again, they get “✘ ALREADY CLAIMED” and nothing happens.

Compact UI — /redeem prompt is now just 3 lines (not a giant ASCII box):

Plain Text
✦ TYPE THE CODE IN CHAT
Nobody else sees it. Type cancel to abort.

Error/response messages are single-line, bold, direct — no decorative boxes:

Scenario
Message
Wrong code
✘ INVALID CODE
then
Use /redeem to try again.
Already claimed
✘ ALREADY CLAIMED
then
You have already used this code.
Success
✓ CODE REDEEMED!
then the config message

Workflow: redeemed.yml is created automatically and saved after every successful claim. /redeem <CODE> works directly too if you prefer skipping the chat prompt.

majroity

why is the API version 1.13..

Kodari AI
KodariJun 6 at 1:37 am 1

Old default when I set it up. What version does your server run? I’ll match it.

Changed to 1.21 — if that’s not yours, tell me the exact version and I’ll fix it.

majroity

make a /redeem reload for ops only that reloads the codes if new codes been typed

Kodari AI
KodariJun 6 at 2:27 am 1

Done.

/redeem reload — OPs (or anyone with redeem.reload permission) can now reload the config to pick up new codes without restarting. Shows ✓ Codes reloaded! in green bold.

majroity

make it for a server called BONKMC make it simpler make it better make a whole revamp

Kodari AI
KodariJun 6 at 1:33 pm 1

Here’s the full BONKMC revamp — cleaner code, branded messages, same core functionality

majroity

people can dupe because cracked generates random UUID's so they manipulate the datastorage plus people enter from alt accounts make it if they have the same ip as another player make it say CLAIMED ON ANOTHER ACCOUNT ON THE SAME IP. to avoid dupes

Kodari AI
KodariJun 6 at 1:39 pm 1

That import’s unused — cleaning it up

Done. Here’s what changed:

IP tracking — when a player redeems a code, their IP is saved alongside their UUID. If someone on the same IP tries that code, they get:

Plain Text
✘ CLAIMED ON ANOTHER ACCOUNT
This code has already been claimed on your IP.

Full flow:

  • /redeem → starts chat prompt

  • Type a code → plugin checks UUID first (already claimed?), then checks IP

  • If same IP but different account already claimed that code → blocked with the message above

  • Success → marks claimed for both UUID and IP

This covers both the cracked UUID dupe and the alt-account scenario.

majroity

what about instead /giftcard reload for ops only instead of /redeem reload bc it wont work

Kodari AI
KodariJun 6 at 3:36 pm 1

Done. /giftcard reload — separate command, giftcard.reload permission, OPs only by default. Keeps /redeem clean for players.

majorrity_

Make it for a server called BlockBay Instead make the plugin look fancy like a paid plugin that server is a bit rich for dark green

Kodari AI
KodariJul 4 at 5:56 pm 3

Full BlockBay rebrand — dark green premium theme, clean code, /giftcard reload kept

Now clean sweep — fresh files with the full BlockBay premium look.

<|DSML|create path=“src/main/java/com/blockbay/redeem/RedeemPlugin.java”>package com.blockbay.redeem;

import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.java.JavaPlugin;

import java.io.File; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap;

public class RedeemPlugin extends JavaPlugin implements Listener {

Plain Text
private final Set<UUID> pending = ConcurrentHashMap.newKeySet();
private final Map<UUID, Set<String>> redeemed = new HashMap<>();
private final Map<String, Set<String>> ipRedeemed = new HashMap<>();
private File dataFile;

@Override
public void onEnable() {
    saveDefaultConfig();
    reloadConfig();

    dataFile = new File(getDataFolder(), "redeemed.yml");
    loadData();

    getCommand("redeem").setExecutor(new RedeemCommand(this));
    getCommand("giftcard").setExecutor(new GiftcardCommand(this));
    Bukkit.getPluginManager().registerEvents(this, this);

    getLogger().info("BlockBay GiftCards loaded.");
}

@Override
public void onDisable() {
    saveData();
    pending.clear();
}

private void loadData() {
    if (!dataFile.exists()) return;
    YamlConfiguration data = YamlConfiguration.loadConfiguration(dataFile);
    if (data.contains("players")) {
        for (String key : data.getConfigurationSection("players").getKeys(false)) {
            redeemed.put(UUID.fromString(key), new HashSet<>(data.getStringList("players." + key)));
        }
    }
    if (data.contains("ips")) {
        for (String key : data.getConfigurationSection("ips").getKeys(false)) {
            ipRedeemed.put(key, new HashSet<>(data.getStringList("ips." + key)));
        }
    }
}

private void saveData() {
    YamlConfiguration data = new YamlConfiguration();
    for (Map.Entry<UUID, Set<String>> e : redeemed.entrySet())
        data.set("players." + e.getKey(), new ArrayList<>(e.getValue()));
    for (Map.Entry<String, Set<String>> e : ipRedeemed.entrySet())
        data.set("ips." + e.getKey(), new ArrayList<>(e.getValue()));
    try { data.save(dataFile); } catch (IOException ignored) {}
}

public boolean hasRedeemed(Player p, String code) {
    Set<String> c = redeemed.get(p.getUniqueId());
    return c != null && c.contains(code);
}

public boolean ipHasRedeemed(Player p, String code) {
    String ip = p.getAddress().getAddress().getHostAddress();
    return ipRedeemed.getOrDefault(ip, Collections.emptySet()).contains(code);
}

public void markRedeemed(Player p, String code) {
    redeemed.computeIfAbsent(p.getUniqueId(), k -> new HashSet<>()).add(code);
    String ip = p.getAddress().getAddress().getHostAddress();
    ipRedeemed.computeIfAbsent(ip, k -> new HashSet<>()).add(code);
    saveData();
}

public void markPending(UUID uuid) { pending.add(uuid); }
public void unmarkPending(UUID uuid) { pending.remove(uuid); }
public boolean isPending(UUID uuid) { return pending.contains(uuid); }

@EventHandler
public void onChat(AsyncPlayerChatEvent e) {
    Player p = e.getPlayer();
    if (!isPending(p.getUniqueId())) return;
    e.setCancelled(true);

    String msg = e.getMessage().trim();
    if (msg.equalsIgnoreCase("cancel") || msg.equalsIgnoreCase("exit")) {
        unmarkPending(p.getUniqueId());
        p.sendMessage(ChatColor.DARK_GREEN + "✦ Redemption cancelled.");
        return;
    }

    Bukkit.getScheduler().runTask(this, () -> redeem(p, msg.toUpperCase()));
}

@EventHandler
public void onQuit(PlayerQuitEvent e) {
    unmarkPending(e.getPlayer().getUniqueId());
}

public void redeem(Player p, String code) {
    unmarkPending(p.getUniqueId());

    String path = "codes." + code;
    if (!getConfig().contains(path)) {
        p.sendMessage(ChatColor.DARK_RED + "" + ChatColor.BOLD + "✘ INVALID CODE");
        p.sendMessage(ChatColor.DARK_GREEN + "Use /redeem to try again.");
        return;
    }

    if (hasRedeemed(p, code)) {
        p.sendMessage(ChatColor.DARK_RED + "" + ChatColor.BOLD + "✘ ALREADY CLAIMED");
        return;
    }

    if (ipHasRedeemed(p, code)) {
        p.sendMessage(ChatColor.DARK_RED + "" + ChatColor.BOLD + "✘ CLAIMED ON ANOTHER ACCOUNT");
        p.sendMessage(ChatColor.DARK_GREEN + "This code was already claimed on your IP.");
        return;
    }

    List<String> commands = getConfig().getStringList(path + ".commands");
    for (String cmd : commands) {
        Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd.replace("%player%", p.getName()));
    }

    markRedeemed(p, code);

    String msg = getConfig().getString(path + ".message", "&a&lRewards claimed!");
    p.sendMessage(cc("&2&l┃ &a&l✔ CODE REDEEMED"));
    p.sendMessage(cc("&2&l┃ &f" + msg));
    p.sendMessage(cc("&2&l┃ &7━━━━━━━━━━━━━━━━━━━━"));
}

private String cc(String s) {
    return ChatColor.translateAlternateColorCodes('&', s);
}

public void reload() {
    reloadConfig();
    Bukkit.getConsoleSender().sendMessage(cc("&2&lBlockBay &8▸ &aCodes reloaded."));
}

} </create>

Done — BlockBay GiftCards v3.0.

Premium dark green theme — all messages use &2 (dark green) and &a (green) with clean box borders:

Scenario
Look
/redeem
prompt
┃━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━
with
✦ TYPE YOUR CODE IN CHAT
Invalid code
✘ INVALID CODE
in dark red bold
Already claimed
✘ ALREADY CLAIMED
IP blocked
✘ CLAIMED ON ANOTHER ACCOUNT
Success
┃ ✔ CODE REDEEMED
with reward message + bottom border
/giftcard reload
✔ Codes reloaded from config.

Security stays — UUID + IP cross-check, per-player one-time claim, /giftcard reload for OPs only.

majorrity_

make a comamnd called /gift add when you do it it opens a INVENTORY GUI where there is 3 icons or heads like one green one red one orange the green one will named Code you click it it will say in chat Type the code please in chat. once you type it in chat it wont appear in normal chat like for other players but it will save and now the icon will be named Code : The code you put and the orange icon in middle will say Message: you click it it will open another one saying Please Type message in chat this will be the message said when the code is redeemed and once you do it and send it will go back to the ui same as greenboth now are saved you go to the last one the red one saying Rewards: you click it it will open another ui like a chest ui but no name like large chest instead it will say Rewards in the top you and 2 icons in it one will say item and one will say Commands if i pick item it will open a small chest ui you put an item in and press esc and that will be the item you want for the reward and once you press esc again it lets you to the main ui again and the item save but if you pick commands it will say type the command in chat please. but you dont type it with / so include that just like instead of /give you type give for example give %player% Diamond %player% is the player who redeemed the code it will do /give on him and also dont make the rewards from server show in chat like [Server] gave username diamond x1 just dont do that let it secret like dont show the output of the command just show CODE REDEEMED and make those messages a little fancy instead do BLOCKBAY : CODE REDEEMED AND BLOCKBAY : CODE INVALID AND FOR OTHER MESSAGES TOO

Kodari AI
KodariJul 4 at 7:11 pm 6

Let me look at the current project state, then build the full GUI-based code creator

Let me read the current files I need to update, then build everything.

Let me delete old example files and build the full system

Now I’ll build the full GUI framework and all the code-creation GUIs. This is a big batch — I’ll create all files in parallel

Filesystem is read-only — using create tags. Let me write everything in one shot.

Now let me update RedeemPlugin.java to wire everything together and handle chat inputs for the code creation flow:

majorrity_

add in the menu like 2 buttons in each corner bottom one in left in green saying ADD and the other red is saying EXIT (THEY ARE SEPERATE FROM THE MAIN BUTTONS) EXIT JUST CANCELS EVERYTHING while green adds the code and reloads the config so you can add it and in the rewards section only commands is there firstly remove the example second just put next to the command block 1 slot away a sword when you click it opens another INVENTORY GUI where you can put items instead of using commands and dont make the server output come out like Gave %player% Diamond 1 i dont want that and add in that item menu make a back button returning you to main menu again and if you added a reward it saves if you do back

Kodari AI
KodariJul 5 at 12:48 am 1

Now I have full context. Let me build everything:

<kodi_planning> Plan:

  1. Update CodeCreator.java — add items list + silentCommands flag

  2. Rewrite CreateCodeGUI.java — ADD (green) at slot 18, EXIT (red) at slot 26, remove old save

  3. Rewrite RewardsGUI.java — Commands at 12, Sword at 14, Back at 26 (returns to CreateCodeGUI)

  4. Create ItemRewardGUI.java — chest GUI for placing items, back → CreateCodeGUI, auto-saves items on back

  5. Update RedeemPlugin.java — “BLOCKBAY : …” format, suppress command output, handle item rewards, item input flow

  6. Update RedeemCommand.java — “BLOCKBAY : …” format </kodi_planning>

<|DSML|create path=“src/main/java/com/blockbay/redeem/CodeCreator.java”>package com.blockbay.redeem;

import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List;

public class CodeCreator { private String code; private String message; private final List<String> commands = new ArrayList<>(); private final List<ItemStack> items = new ArrayList<>();

Plain Text
public String getCode() { return code; }
public void setCode(String code) { this.code = code; }
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
public List<String> getCommands() { return commands; }
public void addCommand(String cmd) { commands.add(cmd); }
public List<ItemStack> getItems() { return items; }
public void addItem(ItemStack item) { items.add(item); }
public void clearItems() { items.clear(); }

} </create>

Now the big three GUI files:

<kodi_operations> { “create”: { “path”: “src/main/java/com/blockbay/redeem/inventory/impl/CreateCodeGUI.java”, “content”: “package com.blockbay.redeem.inventory.impl;\n\nimport com.blockbay.redeem.CodeCreator;\nimport com.blockbay.redeem.RedeemPlugin;\nimport com.blockbay.redeem.inventory.InventoryButton;\nimport com.blockbay.redeem.inventory.InventoryGUI;\nimport com.blockbay.redeem.inventory.gui.GUIManager;\nimport org.bukkit.Bukkit;\nimport org.bukkit.Material;\nimport org.bukkit.entity.Player;\nimport org.bukkit.inventory.Inventory;\nimport org.bukkit.inventory.ItemStack;\nimport org.bukkit.inventory.meta.ItemMeta;\nimport java.util.Arrays;\nimport org.bukkit.event.inventory.InventoryCloseEvent;\n\npublic class CreateCodeGUI extends InventoryGUI {\n\n private final RedeemPlugin plugin;\n private final GUIManager guiManager;\n private final CodeCreator creator;\n\n public CreateCodeGUI(RedeemPlugin plugin, GUIManager guiManager) {\n this.plugin = plugin;\n this.guiManager = guiManager;\n this.creator = new CodeCreator();\n }\n\n @Override\n protected Inventory createInventory() {\n return Bukkit.createInventory(null, 27, "\u00a72\u00a7lCreate a Code");\n }\n\n @Override\n public void decorate(Player player) {\n getInventory().clear();\n buttonMap.clear();\n\n // Green — Code (slot 11)\n addButton(11, new InventoryButton()\n .creator(p -> {\n ItemStack item = new ItemStack(Material.GREEN_CONCRETE);\n ItemMeta meta = item.getItemMeta();\n meta.setDisplayName("\u00a72\u00a7l\u2714 Code");\n if (creator.getCode() != null) {\n meta.setLore(Arrays.asList("\u00a77Code: \u00a7a" + creator.getCode(), "", "\u00a7eClick to change"));\n } else {\n meta.setLore(Arrays.asList("\u00a77Not set yet", "", "\u00a7eClick to set"));\n }\n item.setItemMeta(meta);\n return item;\n })\n .consumer(event -> {\n Player p = (Player) event.getWhoClicked();\n p.closeInventory();\n plugin.startCodeInput(p, creator, this, guiManager);\n })\n );\n\n // Orange — Message (slot 13)\n addButton(13, new InventoryButton()\n .creator(p -> {\n ItemStack item = new ItemStack(Material.ORANGE_CONCRETE);\n ItemMeta meta = item.getItemMeta();\n meta.setDisplayName("\u00a76\u00a7lMessage");\n if (creator.getMessage() != null) {\n meta.setLore(Arrays.asList("\u00a77Message: \u00a7f" + creator.getMessage(), "", "\u00a7eClick to change"));\n } else {\n meta.setLore(Arrays.asList("\u00a77Not set yet", "", "\u00a7eClick to set"));\n }\n item.setItemMeta(meta);\n return item;\n })\n .consumer(event -> {\n Player p = (Player) event.getWhoClicked();\n p.closeInventory();\n plugin.startMessageInput(p, creator, this, guiManager);\n })\n );\n\n // Red — Rewards (slot 15)\n addButton(15, new InventoryButton()\n .creator(p -> {\n ItemStack item = new ItemStack(Material.RED_CONCRETE);\n ItemMeta meta = item.getItemMeta();\n meta.setDisplayName("\u00a74\u00a7lRewards");\n meta.setLore(Arrays.asList(\n "\u00a77Commands: \u00a7f" + creator.getCommands().size(),\n "\u00a77Items: \u00a7f" + creator.getItems().size(),\n "", "\u00a7eClick to configure"));\n item.setItemMeta(meta);\n return item;\n })\n .consumer(event -> {\n Player p = (Player) event.getWhoClicked();\n RewardsGUI rewardsGUI = new RewardsGUI(plugin, guiManager, creator, this);\n guiManager.openGUI(rewardsGUI, p);\n })\n );\n\n // ── Bottom bar ──\n\n // ADD (green) — slot 18\n addButton(18, new InventoryButton()\n .creator(p -> {\n ItemStack item = new ItemStack(Material.LIME_CONCRETE);\n ItemMeta meta = item.getItemMeta();\n meta.setDisplayName("\u00a72\u00a7l\u2714 ADD");\n meta.setLore(Arrays.asList("\u00a77Save this code to config", "\u00a77and make it available"));\n item.setItemMeta(meta);\n return item;\n })\n .consumer(event -> {\n Player p = (Player) event.getWhoClicked();\n if (creator.getCode() == null || creator.getCode().isEmpty()) {\n p.sendMessage("\u00a78\u2502 \u00a74\u2718 \u00a7cSet a code name first!");\n return;\n }\n if (creator.getMessage() == null) {\n p.sendMessage("\u00a78\u2502 \u00a74\u2718 \u00a7cSet a message first!");\n return;\n }\n if (creator.getCommands().isEmpty() && creator.getItems().isEmpty()) {\n p.sendMessage("\u00a78\u2502 \u00a74\u2718 \u00a7cAdd at least one reward!");\n return;\n }\n plugin.saveCode(creator);\n p.sendMessage("\u00a78\u2502 \u00a72\u2714 \u00a7aCode \u00a7f" + creator.getCode() + " \u00a7acreated!");\n p.closeInventory();\n })\n );\n\n // EXIT (red) — slot 26\n addButton(26, new InventoryButton()\n .creator(p -> {\n ItemStack item = new ItemStack(Material.RED_CONCRETE);\n ItemMeta meta = item.getItemMeta();\n meta.setDisplayName("\u00a74\u00a7l\u2718 EXIT");\n meta.setLore(Arrays.asList("\u00a77Cancel and close"));\n item.setItemMeta(meta);\n return item;\n })\n .consumer(event -> {\n Player p = (Player) event.getWhoClicked();\n p.sendMessage("\u00a78\u2502 \u00a74\u2718 \u00a7cCancelled.");\n p.closeInventory();\n })\n );\n\n super.decorate(player);\n }\n\n @Override\n public void onClose(InventoryCloseEvent event) {}\n}\n” } } </kodi_operations>

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
settings.gradle
Code
19 1,040
src/main/java/com/blockbay/redeem/RedeemPlugin.java
package com.blockbay.redeem;

import com.blockbay.redeem.inventory.gui.GUIListener;
import com.blockbay.redeem.inventory.gui.GUIManager;
import com.blockbay.redeem.inventory.impl.CreateCodeGUI;
import com.blockbay.redeem.inventory.impl.GiftAddCommand;
import com.blockbay.redeem.inventory.impl.RewardsGUI;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class RedeemPlugin extends JavaPlugin implements Listener {

    private final Map<UUID, Boolean> pending = new HashMap<>();
    private final Map<String, String> codeClaimerIp = new HashMap<>();
    private final Set<String> playerClaims = new HashSet<>();
    private File dataFile;
    private YamlConfiguration data;
    private GUIManager guiManager;

    // Chat input state for /gift add flow
    private final Map<UUID, String> awaitingInput = new HashMap<>();
    private final Map<UUID, Object[]> inputContext = new HashMap<>();

    @Override
    public void onEnable() {
        saveDefaultConfig();
        dataFile = new File(getDataFolder(), "redeemed.yml");
        if (!dataFile.exists()) {
            try { dataFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); }
        }
        data = YamlConfiguration.loadConfiguration(dataFile);
        loadClaims();

        guiManager = new GUIManager();
        GUIListener guiListener = new GUIListener(guiManager);
        Bukkit.getPluginManager().registerEvents(guiListener, this);
        Bukkit.getPluginManager().registerEvents(this, this);

        getCommand("redeem").setExecutor(new RedeemCommand(this));
        getCommand("giftcard").setExecutor(new GiftcardCommand(this));
        getCommand("gift").setExecutor(new GiftAddCommand(this, guiManager));

        getLogger().info("BlockBay GiftCards enabled.");
    }

    // ── Chat input for code creation ──

    public void startCodeInput(Player p, CodeCreator creator, CreateCodeGUI gui, GUIManager gm) {
        awaitingInput.put(p.getUniqueId(), "CODE");
        inputContext.put(p.getUniqueId(), new Object[]{creator, gui, gm});
        p.sendMessage(cc("&8┃ &2✦ &fType the code name in chat. Type &ccancel &fto exit."));
    }

    public void startMessageInput(Player p, CodeCreator creator, CreateCodeGUI gui, GUIManager gm) {
        awaitingInput.put(p.getUniqueId(), "MESSAGE");
        inputContext.put(p.getUniqueId(), new Object[]{creator, gui, gm});
        p.sendMessage(cc("&8┃ &2✦ &fType the message in chat. Type &ccancel &fto exit."));
    }

    public void startCommandInput(Player p, CodeCreator creator, RewardsGUI gui, GUIManager gm) {
        awaitingInput.put(p.getUniqueId(), "COMMAND");
        inputContext.put(p.getUniqueId(), new Object[]{creator, gui, gm});
        p.sendMessage(cc("&8┃ &2✦ &fType a command &7(without /)&f. Example: &7give %player% diamond 1"));
        p.sendMessage(cc("&8┃ &fType &adone &fwhen finished, or &ccancel &fto exit."));
    }

    // ── Claim persistence ──

    private void loadClaims() {
        playerClaims.clear();
        codeClaimerIp.clear();
        ConfigurationSection codes = data.getConfigurationSection("codes");
        if (codes != null) {
            for (String code : codes.getKeys(false)) {
                ConfigurationSection sec = codes.getConfigurationSection(code);
                if (sec != null) {
                    for (String uuidStr : sec.getStringList("players")) {
                        playerClaims.add(code + ":" + uuidStr);
                    }
                    String ip = sec.getString("claimerIp");
                    if (ip != null) codeClaimerIp.put(code, ip);
                }
            }
        }
    }

    private void saveClaims() {
        data.set("codes", null);
        Map<String, List<String>> byCode = new HashMap<>();
        for (String entry : playerClaims) {
            int colon = entry.indexOf(':');
            byCode.computeIfAbsent(entry.substring(0, colon), k -> new ArrayList<>()).add(entry.substring(colon + 1));
        }
        for (Map.Entry<String, List<String>> e : byCode.entrySet()) {
            data.set("codes." + e.getKey() + ".players", e.getValue());
            if (codeClaimerIp.containsKey(e.getKey()))
                data.set("codes." + e.getKey() + ".claimerIp", codeClaimerIp.get(e.getKey()));
        }
        try { data.save(dataFile); } catch (IOException ex) { ex.printStackTrace(); }
    }

    public boolean hasClaimed(Player p, String code) {
        return playerClaims.contains(code + ":" + p.getUniqueId().toString());
    }

    public boolean sameIpClaimed(Player p, String code) {
        String ip = p.getAddress().getAddress().getHostAddress();
        String storedIp = codeClaimerIp.get(code);
        return storedIp != null && !storedIp.equals(ip);
    }

    public void markClaimed(Player p, String code) {
        playerClaims.add(code + ":" + p.getUniqueId().toString());
        codeClaimerIp.put(code, p.getAddress().getAddress().getHostAddress());
        saveClaims();
    }

    public void markPending(UUID uuid) { pending.put(uuid, true); }
    public boolean isPending(UUID uuid) { return pending.containsKey(uuid); }
    public void removePending(UUID uuid) { pending.remove(uuid); }

    public void reload() { reloadConfig(); loadClaims(); }

    public void saveCode(CodeCreator creator) {
        String code = creator.getCode().toUpperCase();
        getConfig().set("codes." + code + ".message", creator.getMessage());
        getConfig().set("codes." + code + ".commands", creator.getCommands());
        // Also add a dummy item entry if item was set (for display in GUI)
        saveConfig();
        reloadConfig();
    }

    @EventHandler
    public void onChat(AsyncPlayerChatEvent e) {
        Player p = e.getPlayer();
        UUID uuid = p.getUniqueId();

        // Code creation input flow
        if (awaitingInput.containsKey(uuid)) {
            e.setCancelled(true);
            String msg = e.getMessage().trim();
            String type = awaitingInput.get(uuid);

            if (msg.equalsIgnoreCase("cancel")) {
                awaitingInput.remove(uuid);
                inputContext.remove(uuid);
                p.sendMessage(cc("&8┃ &c✘ Cancelled."));
                return;
            }

            if (type.equals("COMMAND") && msg.equalsIgnoreCase("done")) {
                Object[] ctx = inputContext.get(uuid);
                awaitingInput.remove(uuid);
                inputContext.remove(uuid);
                RewardsGUI rg = (RewardsGUI) ctx[1];
                GUIManager gm = (GUIManager) ctx[2];
                Bukkit.getScheduler().runTask(this, () -> gm.openGUI(rg, p));
                return;
            }

            Object[] ctx = inputContext.get(uuid);
            CodeCreator creator = (CodeCreator) ctx[0];

            switch (type) {
                case "CODE":
                    creator.setCode(msg.toUpperCase().replace(" ", ""));
                    awaitingInput.remove(uuid);
                    inputContext.remove(uuid);
                    CreateCodeGUI cg = (CreateCodeGUI) ctx[1];
                    GUIManager gm1 = (GUIManager) ctx[2];
                    p.sendMessage(cc("&8┃ &2✔ &fCode set to &a" + creator.getCode()));
                    Bukkit.getScheduler().runTask(this, () -> gm1.openGUI(cg, p));
                    break;

                case "MESSAGE":
                    creator.setMessage(msg);
                    awaitingInput.remove(uuid);
                    inputContext.remove(uuid);
                    CreateCodeGUI cg2 = (CreateCodeGUI) ctx[1];
                    GUIManager gm2 = (GUIManager) ctx[2];
                    p.sendMessage(cc("&8┃ &2✔ &fMessage set!"));
                    Bukkit.getScheduler().runTask(this, () -> gm2.openGUI(cg2, p));
                    break;

                case "COMMAND":
                    creator.addCommand(msg);
                    p.sendMessage(cc("&8┃ &2✔ &fCommand added: &7" + msg));
                    // Stay in command input mode - don't close
                    p.sendMessage(cc("&8┃ &fType &adone &fwhen finished, or another command."));