<?php
// --- Dosya Yolları ---
$group_file = "special_item_group.txt";
$item_names_file = "names.txt";
$item_icon_folder = "icon/item/";
$item_list_file = "item_list.txt";

// --- Yardımcı Fonksiyonlar ---
function getItemNames($filename) {
    $map = [];
    if (!file_exists($filename)) return $map;
    foreach (file($filename) as $line) {
        $line = trim($line);
        if ($line === "" || strpos($line, "VNUM") === 0) continue;
        $parts = preg_split('/\s+/', $line, 2);
        if (count($parts) === 2) $map[$parts[0]] = $parts[1];
    }
    return $map;
}
function getItemIconPath($itemVnum, $folder = "icon/item/", $itemListFile = "item_list.txt") {
    static $cache = [];
    if (isset($cache[$itemVnum])) return $cache[$itemVnum];
    if (!file_exists($itemListFile)) return $folder . "no_img.png";
    foreach (file($itemListFile) as $line) {
        $line = trim($line);
        if ($line === '') continue;
        $parts = preg_split('/\s+/', $line);
        if (count($parts) >= 2 && $parts[0] == $itemVnum) {
            $imgPath = $folder . $parts[1];
            $cache[$itemVnum] = file_exists(__DIR__ . "/" . $imgPath) ? $imgPath : $folder . "no_img.png";
            return $cache[$itemVnum];
        }
    }
    return $folder . "no_img.png";
}

// --- Grup Dosyasını Oku ---
function parse_special_item_group_file($filename) {
    $groups = [];
    $current = null;
    $type = "";
    $inGroup = false;
    if (!file_exists($filename)) return [];
    foreach (file($filename) as $line) {
        $line = trim($line);
        if ($line === "") continue;
        if (preg_match('/^Group\s+"?(.*?)"?$/', $line, $m)) {
            if ($current && $type !== "ATTR" && $type !== "SPECIAL") $groups[] = $current;
            $current = ["name"=>$m[1], "vnum"=>"", "type"=>"", "items"=>[]];
            $type = "";
            $inGroup = true;
        } elseif ($line==="{" && $inGroup) {
        } elseif (preg_match('/^Vnum\s+(.*)$/', $line, $m)) {
            $current["vnum"] = $m[1];
        } elseif (preg_match('/^Type\s*(.*)$/i', $line, $m)) {
            $current["type"] = isset($m[1]) ? $m[1] : "";
            $type = strtoupper(trim($m[1]));
        } elseif ($line==="}") {
            if ($current && $type!=="ATTR" && $type!=="SPECIAL") $groups[] = $current;
            $current = null;
            $type = "";
            $inGroup = false;
        } elseif ($inGroup && preg_match('/^(\d+)\s+(\d+)\s+(\d+)(.*)$/', $line, $m)) {
            $item = [
                "order" => $m[1],
                "item_vnum" => $m[2],
                "count" => $m[3],
                "chance" => trim($m[4])
            ];
            $current["items"][] = $item;
        }
    }
    return $groups;
}

    

function save_special_item_group_file($filename, $groups) {
    $lines = [];
    foreach ($groups as $group) {
        // Grup başlığı
        $lines[] = 'Group ' . $group['name'];
        $lines[] = '{';
        // Vnum satırı
        $lines[] = 'Vnum ' . $group['vnum'];
        // Type satırı eğer boş değilse
        if (isset($group['type']) && $group['type'] !== "") {
            $lines[] = 'Type ' . $group['type'];
        }
        // Item satırları
        foreach ($group['items'] as $item) {
            $line = $item['order'] . ' ' . $item['item_vnum'] . ' ' . $item['count'];
            if (isset($item['chance']) && $item['chance'] !== "") {
                $line .= ' ' . $item['chance'];
            }
            $lines[] = $line;
        }
        $lines[] = '}';
    }
    // Dosya sonuna fazladan boş satır eklemez!
    file_put_contents($filename, implode("\n", $lines), LOCK_EX);
}

// Yükle
$item_names = getItemNames($item_names_file);
$groups = parse_special_item_group_file($group_file);

// --- En son seçili grup (cookie ile takip) ---
if (isset($_GET['group'])) {
    setcookie('last_group', intval($_GET['group']), time() + 3600, '/');
}
$selected = isset($_GET['group'])
    ? intval($_GET['group'])
    : (isset($_COOKIE['last_group']) ? intval($_COOKIE['last_group']) : null);

// --- Tekli Kayıt (Düzenle ve Kaydet) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save']) && isset($_POST['group_idx'])) {
    $idx = intval($_POST['group_idx']);
    $groups[$idx]['name'] = trim($_POST['group_name']);
    $groups[$idx]['vnum'] = trim($_POST['group_vnum']);
    $groups[$idx]['type'] = trim($_POST['group_type']);
    save_special_item_group_file($group_file, $groups);
    echo "OK";
    exit;
}

// --- Item Düzenleme / Ekleme / Silme (AJAX) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['item_action'])) {
    $res = ['success'=>false,'msg'=>''];
    $group_idx = intval($_POST['group']);
    if ($_POST['item_action'] == "edit") {
        $item_idx = intval($_POST['item_idx']);
        $groups[$group_idx]['items'][$item_idx] = [
            "order" => $item_idx + 1,
            "item_vnum" => $_POST['item_id'],
            "count" => $_POST['count'],
            "chance" => trim($_POST['chance'])
        ];
        save_special_item_group_file($group_file, $groups);
        $res['success']=true;
        $res['msg']="Item güncellendi!";
    } elseif ($_POST['item_action'] == "add") {
        $groups[$group_idx]['items'][] = [
            "order" => count($groups[$group_idx]['items']) + 1,
            "item_vnum" => $_POST['item_id'],
            "count" => $_POST['count'],
            "chance" => trim($_POST['chance'])
        ];
        save_special_item_group_file($group_file, $groups);
        $res['success']=true;
        $res['msg']="Item eklendi!";
    } elseif ($_POST['item_action'] == "delete") {
        $item_idx = intval($_POST['item_idx']);
        array_splice($groups[$group_idx]['items'], $item_idx, 1);
        foreach ($groups[$group_idx]['items'] as $i => &$item) {
            $item["order"] = $i + 1;
        }
        save_special_item_group_file($group_file, $groups);
        $res['success']=true;
        $res['msg']="Item silindi!";
    }
    header('Content-Type: application/json');
    echo json_encode($res);
    exit;
}

// --- Yeni Grup Ekleme (AJAX) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_group'])) {
    $name = trim($_POST['new_group_name']);
    $vnum = trim($_POST['new_group_vnum']);
    $type = trim($_POST['new_group_type']);
    if ($name !== "" && $vnum !== "" && strtoupper($type)!=="ATTR" && strtoupper($type)!=="SPECIAL") {
        $groups[] = ["name"=>$name,"vnum"=>$vnum,"type"=>$type,"items"=>[]];
        save_special_item_group_file($group_file, $groups);
        echo "OK";
        exit;
    }
    echo "ERR";
    exit;
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Özel Eşya Grup Editörü</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="style.css?v=19">
    <style>
        body { background: linear-gradient(120deg,#e8f3ff 60%,#f8fafc 100%); }
        .dashboard-wrapper { display:flex; gap:24px; max-width:1180px; margin:22px auto; box-shadow:0 4px 32px #2581c614; border-radius:20px; background:#fff;}
        .group-sidebar { min-width:340px; border-right:1px solid #e3e3e3; background:#f5fafe; border-radius:20px 0 0 20px; padding:20px 0 20px 0; display:flex; flex-direction:column;}
        .group-list-bar { display:flex; align-items:center; gap:12px; padding:0 18px 7px 18px;}
        .group-list-bar-btn { background:#2581c6; color:#fff; border:none; font-size:1.09rem; border-radius:8px; padding:4px 12px; cursor:pointer;}
        .group-list-bar-btn:disabled { background:#e3e3e3; color:#aaa; cursor:not-allowed;}
        .group-list-ul { list-style:none; padding:0 0 0 0; margin:0; max-height:410px; overflow-y:auto; border-radius:11px; border:1px solid #e3e3e3; }
        .group-list-item { padding:7px 7px; cursor:pointer; display:flex; align-items:center; border-radius:10px; transition:.2s; font-size:1.08rem; margin-bottom:2px;}
        .group-list-item.active { background:#e8f3ff; border:2px solid #43d47b;}
        .item-icon { width:32px; height:32px; border-radius:6px; margin-right:7px; box-shadow:0 2px 10px #2581c633; object-fit:cover;}
        .group-list-name { font-weight:500; margin-right:6px;}
        .group-list-vnum { font-size:.97em; color:#2581c6; opacity:.71;}
        .btn-edit { background:#2581c6; color:#fff; border:none; border-radius:6px; font-size:1.01rem; padding:2px 8px; cursor:pointer; }
        .btn-edit:disabled { background:#e3e3e3; color:#aaa; cursor:not-allowed;}
        .add-group-panel { padding:13px 14px; background:#e8f3ff; border-radius:12px; margin:14px 0 8px 0; }
        .add-group-panel label, .add-group-panel input, .add-group-panel button { font-size:1.04em;}
        .add-group-panel input { width:90px; margin-right:8px; }
        .add-group-panel button { background:#43d47b;color:#fff;border-radius:8px;padding:5px 15px;border:none;}
        .group-content { flex:1; padding:30px 24px;}
        .group-content-title { font-size:1.45rem; color:#2581c6; margin-bottom:18px;}
        .edit-form { max-width:440px; margin:0 auto; }
        .edit-form label { display:block; font-weight:500; margin-bottom:7px; color:#324a5e;}
        .edit-row { display:flex; align-items:center; gap:8px; margin-bottom:14px;}
        .edit-form input[type="text"], .edit-form select { width:140px; padding:8px 11px; border-radius:8px; border:1px solid #e3e3e3;}
        .btn-save { background:#43d47b; color:#fff; font-size:1.13rem; padding:9px 24px; border-radius:12px;}
        .item-table { width:100%; border-collapse:collapse; box-shadow:0 2px 24px #43d47b16; margin-bottom:24px;}
        .item-table th, .item-table td { padding:9px 8px; text-align:left; border-bottom:1px solid #f0f0f0;}
        .item-table tr:hover td { background:#e8f3ff;}
        .item-table th { background:#f8fafc; font-weight:600; color:#2581c6;}
        .toast-notify { background:#e8ffe3; color:#2581c6; font-weight:500; padding:12px 20px; border-radius:15px; margin-bottom:17px; display:inline-block; position:fixed;top:40px;right:40px;z-index:99;}
        audio {display:none;}
        @media (max-width: 900px) {
            .dashboard-wrapper { flex-direction:column; }
            .group-sidebar { border-radius:20px 20px 0 0;}
        }
    </style>
</head>
<body>
<audio id="notifySound" src="success.mp3" preload="auto"></audio>
<header class="admin-header">
    <div class="admin-header-left">
        <img src="https://gf1.geo.gfsrv.net/cdn98/191b803adbf82f4b8febe3a2c38c2c.ico" alt="Drop" class="admin-header-logo">
        <span class="admin-header-title">Özel Eşya Grup Editörü</span>
        <a href="index.php" class="admin-header-btn" style="margin-left:18px; padding:6px 14px; background:#2581c6; color:white; border-radius:4px; text-decoration:none; font-weight:500;">
            ← Drop Paneline Dön
        </a>
    </div>
    <div class="admin-header-right">
        <span class="admin-header-user">👨‍💻 Yönetici</span>
        <span class="admin-header-role">Panel</span>
    </div>
</header>
        <div class="dev-info" style="background:#fff2ce;color:#b17d00;font-weight:500;padding:16px 0;text-align:center;font-size:1.17rem;border-bottom:2px solid #ffe79d;">
    &#9888; Bu Sayfa Geliştiriliyor.
</div>dw

<div class="dashboard-wrapper">
    <aside class="group-sidebar">
        <div class="group-list-bar">
            <form method="get" style="margin-bottom:0;flex:1;">
                <input type="text" name="search" id="groupSearch" placeholder="Grup adı veya Vnum ile ara..." autocomplete="off"
                    style="width:99%;padding:8px 10px;border-radius:8px;border:1px solid #e3e3e3;"
                    value="<?= isset($_GET['search']) ? htmlspecialchars($_GET['search']) : '' ?>">
            </form>
            <button type="button" class="group-list-bar-btn" id="groupScrollUp">&#9650;</button>
            <button type="button" class="group-list-bar-btn" id="groupScrollDown">&#9660;</button>
        </div>
        <div class="add-group-panel">
            <label>Yeni Grup:</label>
            <input type="text" id="newGroupName" placeholder="Ad">
            <input type="text" id="newGroupVnum" placeholder="Vnum">
            <input type="text" id="newGroupType" placeholder="Type">
            <button type="button" onclick="addNewGroup()">Ekle</button>
        </div>
        <ul class="group-list-ul" id="groupList">
            <?php
            $searchQuery = isset($_GET['search']) ? mb_strtolower(trim($_GET['search'])) : '';
            $groupCount = 0;
            foreach ($groups as $idx => $group):
                $vnum = $group["vnum"];
                $name = isset($item_names[$vnum]) ? $item_names[$vnum] : $group["name"];
                if ($searchQuery &&
                    strpos(mb_strtolower($name), $searchQuery) === false &&
                    strpos(mb_strtolower($vnum), $searchQuery) === false) continue;
                $groupCount++;
                $imgPath = getItemIconPath($vnum, $item_icon_folder, $item_list_file);
            ?>
<li class="group-list-item<?= ($selected == $idx) ? ' active' : '' ?>" data-group="<?= $idx ?>">
    <!-- DEBUG: icon path: <?= htmlspecialchars($imgPath) ?> - exists: <?= file_exists(__DIR__ . '/' . $imgPath) ? 'yes' : 'no' ?> -->
    <img src="<?= htmlspecialchars($imgPath) ?>" class="item-icon" alt="Item">
    <span class="group-list-name" style="cursor:pointer;" onclick="window.location.href='?group=<?= $idx ?>'"><?= htmlspecialchars($name) ?></span>
    <span class="group-list-vnum onclick="window.location.href='?group=<?= $idx ?>'>(<?= htmlspecialchars($vnum) ?>)</span>
    <span style="flex:1"></span>
    <button type="button" class="btn-edit" onclick="window.location.href='?group=<?= $idx ?>'">Düzenle</button>
    <!-- Son işlem bildirimi için işaretleme -->
    <?php if ($selected == $idx): ?>
        <span style="margin-left:14px;color:#43d47b;font-weight:bold;">← Son işlem burada</span>
    <?php endif; ?>
</li>
            <?php endforeach; ?>
            <?php if ($groupCount == 0): ?>
                <li><em>Hiç grup bulunamadı.</em></li>
            <?php endif; ?>
        </ul>
    </aside>
    <main class="group-content">
        <?php
        if (isset($_GET['success']) && $_GET['success']==1) {
            echo '<div class="toast-notify">&#10003; Kayıt başarıyla güncellendi.</div>';
        }
        $selectedGroup = isset($groups[$selected]) ? $groups[$selected] : null;
        if ($selectedGroup):
            $groupVnum = $selectedGroup['vnum'];
            $groupName = isset($item_names[$groupVnum]) ? $item_names[$groupVnum] : $selectedGroup['name'];
            $groupImgPath = getItemIconPath($groupVnum, $item_icon_folder, $item_list_file);
        ?>
        <div class="group-image-area" style="text-align:center; margin-bottom:28px;">
            <img src="<?= htmlspecialchars($groupImgPath) ?>" class="item-icon" style="width:110px;height:110px;border-radius:16px;box-shadow:0 2px 16px #2581c633;">
            <div style="margin-top:7px; color:#2581c6; font-size:1.11rem;">
                Grup: <b><?= htmlspecialchars($groupName) ?></b> (Vnum: <b><?= htmlspecialchars($groupVnum) ?></b>)
            </div>
        </div>
        <h2 class="group-content-title"><?= htmlspecialchars($groupName) ?> Ayarları</h2>
        <form method="post" class="edit-form" id="groupEditForm" onsubmit="return saveGroup();">
            <input type="hidden" name="group_idx" value="<?= $selected ?>">
            <div class="edit-row">
                <label for="group_name">Adı:</label>
                <input type="text" id="group_name" name="group_name" value="<?= htmlspecialchars($selectedGroup['name']) ?>" required>
                <label for="group_vnum">Vnum:</label>
                <input type="text" id="group_vnum" name="group_vnum" value="<?= htmlspecialchars($selectedGroup['vnum']) ?>" required>
                <label for="group_type">Type:</label>
                <select name="group_type" id="group_type">
                    <option value="" <?= $selectedGroup['type']=="" ? "selected" : "" ?>>(Boş)</option>
                    <option value="drop" <?= $selectedGroup['type']=="drop"?"selected":"" ?>>drop</option>
                    <option value="pct" <?= $selectedGroup['type']=="pct"?"selected":"" ?>>pct</option>
                    <option value="mob" <?= $selectedGroup['type']=="mob"?"selected":"" ?>>mob</option>
                    <?php
                    if ($selectedGroup['type']!="" && !in_array($selectedGroup['type'],["drop","pct","mob"])) {
                        echo '<option value="'.htmlspecialchars($selectedGroup['type']).'" selected>'.htmlspecialchars($selectedGroup['type']).'</option>';
                    }
                    ?>
                </select>
                <button type="submit" class="btn-save">Kaydet</button>
            </div>
        </form>
        <h3 style="margin-top:38px;color:#2581c6;">Itemlar</h3>
        <table class="item-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Item</th>
                    <th>Icon</th>
                    <th>Adet</th>
                    <th>Şans</th>
                    <th>İşlem</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($selectedGroup['items'] as $i => $item): ?>
                <tr>
                    <td><?= $i+1 ?></td>
                    <td>
                        <span style="font-weight:500"><?= htmlspecialchars($item_names[$item['item_vnum']] ?? $item['item_vnum']) ?></span>
                        <span style="color:#888;font-size:.95em">(<?= htmlspecialchars($item['item_vnum']) ?>)</span>
                    </td>
                    <td>
                        <?php
                            $iconPath = getItemIconPath($item['item_vnum'], $item_icon_folder, $item_list_file);
                            $itemName = isset($item_names[$item['item_vnum']]) ? $item_names[$item['item_vnum']] : '';
                            echo '<!-- DEBUG: icon path: ' . htmlspecialchars($iconPath) . ' - exists: ' . (file_exists(__DIR__ . '/' . $iconPath) ? 'yes' : 'no') . ' -->';
                            if ($iconPath && file_exists(__DIR__ . '/' . $iconPath)) {
                                echo '<span class="tooltip-wrap">
                                        <img src="' . htmlspecialchars($iconPath) . '" alt="" class="item-icon" style="width:32px;">
                                        <span class="tooltip">' . htmlspecialchars($itemName) . '</span>
                                      </span>';
                            } else {
                                echo '<span class="icon-missing tooltip-wrap" style="color:#888;">Yok<span class="tooltip">' . htmlspecialchars($itemName) . '</span></span>';
                            }
                        ?>
                    </td>
                    <td>
                        <input type="number" style="width:70px;" min="1" value="<?= htmlspecialchars($item['count']) ?>"
                               id="item_count_<?= $i ?>">
                    </td>
                    <td>
                        <input type="text" style="width:70px;" value="<?= htmlspecialchars($item['chance']) ?>"
                               id="item_chance_<?= $i ?>">
                    </td>
                    <td style="white-space:nowrap;">
                        <button type="button" class="btn-edit" onclick="editItem(<?= $selected ?>, <?= $i ?>)">Kaydet</button>
                        <button type="button" class="btn-edit" style="background:#f43a5e;" onclick="deleteItem(<?= $selected ?>, <?= $i ?>)">Sil</button>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <div style="margin-top:22px;">
            <input type="text" id="addItemVnum" placeholder="Item Vnum" style="width:85px;">
            <input type="number" id="addItemCount" placeholder="Adet" min="1" style="width:70px;">
            <input type="text" id="addItemChance" placeholder="Şans" style="width:70px;">
            <button type="button" class="btn-edit" style="background:#43d47b;" onclick="addItem(<?= $selected ?>)">Ekle</button>
        </div>
        <?php else: ?>
            <div class="empty" style="text-align:center;margin-top:70px;">
                <img src="https://cdn-icons-png.flaticon.com/512/565/565547.png" width="96" alt="Grup seç">
                <div>Bir grup seçiniz soldan.</div>
            </div>
        <?php endif; ?>
    </main>
</div>
<footer style="text-align:center;padding:18px 0;color:#2581c6;font-size:1rem;opacity:.8;">
    &copy; <?= date('Y') ?> Özel Eşya Grup Paneli - Tasarım & Kodlama: <b>DepDarkMor</b>
</footer>
<script>
function showToast(msg) {
    var toast = document.createElement("div");
    toast.className = "toast-notify";
    toast.innerHTML = "&#10003; " + msg;
    document.body.appendChild(toast);
    setTimeout(function(){ toast.remove(); }, 2100);
}
function playNotifySound() {
    var snd = document.getElementById("notifySound");
    if (snd) { try { snd.currentTime = 0; snd.play(); } catch(e) {} }
}

document.addEventListener("DOMContentLoaded", function() {
    var groupSearch = document.getElementById("groupSearch");
    var groupList = document.getElementById("groupList");
    groupSearch.addEventListener("input", function(){
        var query = groupSearch.value.trim().toLowerCase();
        groupList.querySelectorAll(".group-list-item").forEach(function(li){
            var name = (li.querySelector('.group-list-name')?.textContent || "").toLowerCase();
            var vnum = (li.querySelector('.group-list-vnum')?.textContent || "").toLowerCase();
            if(query === "" || name.includes(query) || vnum.includes(query)) {
                li.style.display = "";
            }else{
                li.style.display = "none";
            }
        });
    });
    // Seçili grup otomatik ortala
    var activeGroup = groupList.querySelector(".active");
    if (activeGroup) {
        setTimeout(function(){
            activeGroup.scrollIntoView({block:"center",behavior:"smooth"});
        }, 120);
    }
    // Scroll bar buttons
    var groupListUl = document.getElementById("groupList");
    document.getElementById("groupScrollUp").addEventListener("click", function(){
        groupListUl.scrollBy({top:-100,behavior:"smooth"});
    });
    document.getElementById("groupScrollDown").addEventListener("click", function(){
        groupListUl.scrollBy({top:100,behavior:"smooth"});
    });
});

function saveGroup() {
    var fd = new FormData(document.getElementById('groupEditForm'));
    fd.append("save", "1");
    fetch(window.location.pathname, {
        method: "POST",
        body: fd
    }).then(r=>r.text()).then(r=>{
        if (r.trim() === "OK") {
            showToast("Grup güncellendi!");
            playNotifySound();
            setTimeout(()=>window.location.reload(), 700);
        } else {
            alert("Kaydetme başarısız! Sunucu yanıtı: " + r);
        }
    });
    return false;
}

function editItem(groupIdx, itemIdx) {
    var count = document.getElementById("item_count_" + itemIdx).value;
    var chance = document.getElementById("item_chance_" + itemIdx).value;
    var fd = new FormData();
    fd.append("item_action", "edit");
    fd.append("group", groupIdx);
    fd.append("item_idx", itemIdx);
    fd.append("item_id", document.querySelectorAll('tr')[itemIdx+1].querySelectorAll('td')[1].innerText.match(/\((\d+)\)/)[1]);
    fd.append("count", count);
    fd.append("chance", chance);
    fetch(window.location.pathname, {
        method: "POST",
        body: fd
    }).then(r=>r.json()).then(function(resp){
        if(resp.success){
            showToast(resp.msg);
            playNotifySound();
            setTimeout(()=>window.location.reload(), 700);
        }else{
            alert("Hata oluştu!");
        }
    });
}
function deleteItem(groupIdx, itemIdx) {
    if(!confirm("Silinsin mi?")) return;
    var fd = new FormData();
    fd.append("item_action", "delete");
    fd.append("group", groupIdx);
    fd.append("item_idx", itemIdx);
    fetch(window.location.pathname, {
        method: "POST",
        body: fd
    }).then(r=>r.json()).then(function(resp){
        if(resp.success){
            showToast(resp.msg);
            playNotifySound();
            setTimeout(()=>window.location.reload(), 700);
        }else{
            alert("Hata oluştu!");
        }
    });
}
function addItem(groupIdx) {
    var vnum = document.getElementById("addItemVnum").value;
    var count = document.getElementById("addItemCount").value;
    var chance = document.getElementById("addItemChance").value;
    if(!vnum || !count) { showToast("Vnum ve adet gerekli!"); return; }
    var fd = new FormData();
    fd.append("item_action", "add");
    fd.append("group", groupIdx);
    fd.append("item_id", vnum);
    fd.append("count", count);
    fd.append("chance", chance);
    fetch(window.location.pathname, {
        method: "POST",
        body: fd
    }).then(r=>r.json()).then(function(resp){
        if(resp.success){
            showToast(resp.msg);
            playNotifySound();
            setTimeout(()=>window.location.reload(), 700);
        }else{
            alert("Hata oluştu!");
        }
    });
}
function addNewGroup() {
    var name = document.getElementById("newGroupName").value;
    var vnum = document.getElementById("newGroupVnum").value;
    var type = document.getElementById("newGroupType").value;
    if(!name || !vnum) { showToast("Grup adı ve vnum gerekli!"); return; }
    var fd = new FormData();
    fd.append("add_group", "1");
    fd.append("new_group_name", name);
    fd.append("new_group_vnum", vnum);
    fd.append("new_group_type", type);
    fetch(window.location.pathname, {
        method: "POST",
        body: fd
    }).then(r=>r.text()).then(function(resp){
        if(resp=="OK"){
            showToast("Grup eklendi!");
            playNotifySound();
            setTimeout(()=>window.location.reload(), 700);
        }else{
            alert("Hata oluştu!");
        }
    });
}
</script>
</body>
</html>