<?php
// --- Dosya Yolları ---
$mob_proto_file = "mob_proto.txt";
$mob_names_file = "mob_names.txt";
$mob_icon_folder = "icon/mob/";

// --- Go Microservice Olay Tetikleme Fonksiyonu ---
function trigger_go_event($type, $data = []) {
    $url = "http://localhost:8080/event";
    $payload = [
        "type" => $type,
        "data" => $data,
        "timestamp" => time()
    ];
    $opts = [
        "http" => [
            "method" => "POST",
            "header" => "Content-Type: application/json\r\n",
            "content" => json_encode($payload)
        ]
    ];
    $context = stream_context_create($opts);
    @file_get_contents($url, false, $context);
}

// --- Yardımcı Fonksiyonlar ---
function getMobNames($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 getMobImagePath($mobVnum, $folder = "icon/mob/") {
    $imgPath = $folder . $mobVnum . ".png";
    return file_exists(__DIR__ . "/" . $imgPath) ? $imgPath : $folder . "no_img.png";
}

// --- Dosya Okuma ---
$mob_names = getMobNames($mob_names_file);

$mob_list = [];
$header = [];
if (file_exists($mob_proto_file)) {
    $lines = file($mob_proto_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $header = explode("\t", $lines[0]);
    for ($i = 1; $i < count($lines); $i++) {
        $values = explode("\t", $lines[$i]);
        $row = array_combine($header, $values);
        $mob_list[] = $row;
    }
} else {
    die("<div class='fatal-error'><b>mob_proto.txt bulunamadı!</b></div>");
}

$selected_vnum = isset($_GET['vnum']) ? $_GET['vnum'] : null;

// --- Tekli Kayıt (Yüzdeyle Değiştir veya Kaydet) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_percent']) && isset($_POST['vnum']) && isset($_POST['field']) && isset($_POST['value'])) {
    foreach ($mob_list as &$mob) {
        if ($mob['Vnum'] == $_POST['vnum']) {
            $mob[$_POST['field']] = $_POST['value'];
        }
    }
    $out = [];
    $out[] = implode("\t", $header);
    foreach ($mob_list as $mob) {
        $row = [];
        foreach ($header as $col) $row[] = $mob[$col] ?? "";
        $out[] = implode("\t", $row);
    }
    file_put_contents($mob_proto_file, implode("\n", $out) . "\n");
    // --- Go microservice olay tetikle ---
    trigger_go_event("single_save_percent", [
        "vnum" => $_POST['vnum'],
        "field" => $_POST['field'],
        "value" => $_POST['value']
    ]);
    echo "OK";
    exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save']) && isset($_POST['vnum'])) {
    foreach ($mob_list as &$mob) {
        if ($mob['Vnum'] == $_POST['vnum']) {
            $mob['MinGold'] = trim($_POST['MinGold']);
            $mob['MaxGold'] = trim($_POST['MaxGold']);
            $mob['Exp']     = trim($_POST['Exp']);
        }
    }
    $out = [];
    $out[] = implode("\t", $header);
    foreach ($mob_list as $mob) {
        $row = [];
        foreach ($header as $col) $row[] = $mob[$col] ?? "";
        $out[] = implode("\t", $row);
    }
    file_put_contents($mob_proto_file, implode("\n", $out) . "\n");
    // --- Go microservice olay tetikle ---
    trigger_go_event("single_save", [
        "vnum" => $_POST['vnum'],
        "MinGold" => $_POST['MinGold'],
        "MaxGold" => $_POST['MaxGold'],
        "Exp" => $_POST['Exp']
    ]);
    header("Location: mob_proto_edit.php?vnum=" . $_POST['vnum'] . "&success=1");
    exit;
}

// --- Toplu Yüzdesel Değiştirme ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_percent']) && isset($_POST['bulk_vnums']) && isset($_POST['bulk_field']) && isset($_POST['bulk_percent_value'])) {
    $vnums = explode(",", $_POST['bulk_vnums']);
    $field = $_POST['bulk_field'];
    $percent = floatval($_POST['bulk_percent_value']);
    foreach ($mob_list as &$mob) {
        if (in_array($mob['Vnum'], $vnums)) {
            $val = floatval($mob[$field]);
            $mob[$field] = round($val * (1 + $percent / 100));
        }
    }
    $out = [];
    $out[] = implode("\t", $header);
    foreach ($mob_list as $mob) {
        $row = [];
        foreach ($header as $col) $row[] = $mob[$col] ?? "";
        $out[] = implode("\t", $row);
    }
    file_put_contents($mob_proto_file, implode("\n", $out) . "\n");
    // --- Go microservice olay tetikle ---
    trigger_go_event("bulk_percent", [
        "vnums" => $vnums,
        "field" => $field,
        "percent" => $percent
    ]);
    echo "OK";
    exit;
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Mob Proto Düzenleyici</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="style.css?v=17">
    <style>
        body { background: linear-gradient(120deg,#e8f3ff 60%,#f8fafc 100%); }
        .admin-header-logo { box-shadow: 0 4px 12px #2581c633; }
        .dashboard-wrapper { display:flex; gap:24px; max-width:1180px; margin:22px auto; box-shadow:0 4px 32px #2581c614; border-radius:20px; background:#fff;}
        .mob-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;}
        .mob-list-bar { display:flex; align-items:center; gap:12px; padding:0 18px 7px 18px;}
        .mob-list-bar-btn { background:#2581c6; color:#fff; border:none; font-size:1.09rem; border-radius:8px; padding:4px 12px; cursor:pointer;}
        .mob-list-bar-btn:disabled { background:#e3e3e3; color:#aaa; cursor:not-allowed;}
        .mob-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; }
        .mob-list-item { padding:7px 7px; cursor:pointer; display:flex; align-items:center; border-radius:10px; transition:.2s; font-size:1.08rem; margin-bottom:2px;}
        .mob-list-item.active { background:#e8f3ff; border:2px solid #43d47b;}
        .mob-list-img { width:32px; height:32px; border-radius:6px; margin-right:7px; box-shadow:0 2px 10px #2581c633; object-fit:cover;}
        .mob-list-name { font-weight:500; margin-right:6px;}
        .mob-list-vnum { font-size:.97em; color:#2581c6; opacity:.71;}
        .mob-check {margin-right:7px;}
        .bulk-panel { padding:13px 14px; background:#e8f3ff; border-radius:12px; margin:14px 0 8px 0; }
        .bulk-panel label, .bulk-panel select, .bulk-panel input, .bulk-panel button { font-size:1.04em;}
        .bulk-panel input[type="number"] { width:60px; }
        .bulk-panel button { background:#43d47b;color:#fff;border-radius:8px;padding:5px 15px;border:none;}
        .mob-content { flex:1; padding:30px 24px;}
        .mob-image-area { text-align:center; margin-bottom:28px;}
        .mob-image { width:180px; max-width:100%; border-radius:16px; box-shadow:0 2px 16px #2581c633; }
        .mob-content-title { font-size:1.45rem; color:#2581c6; margin-bottom:18px;}
        .edit-form { max-width:400px; 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="number"] { width:120px; padding:8px 11px; border-radius:8px; border:1px solid #e3e3e3;}
        .percent-controls { display:flex; gap:2px; align-items:center;}
        .percent-controls input[type="number"] { width:60px; padding:5px 7px; margin-right:2px;}
        .percent-btn { background:#2581c6; color:#fff; border:none; border-radius:6px; font-size:1.01rem; padding:2px 8px; cursor:pointer;}
        .percent-btn:disabled { background:#e3e3e3; color:#aaa; cursor:not-allowed;}
        .btn-save { background:#43d47b; color:#fff; font-size:1.13rem; padding:9px 24px; border-radius:12px;}
        .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; }
            .mob-sidebar { border-radius:20px 20px 0 0;}
        }
    </style>
</head>
<body>
<audio id="notifySound" src="new-notification.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">Mob Proto Düzenleyici</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="dashboard-wrapper">
    <aside class="mob-sidebar">
        <div class="mob-list-bar">
            <form method="get" style="margin-bottom:0;flex:1;">
                <input type="text" name="search" id="mobSearch" placeholder="Mob 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="mob-list-bar-btn" id="mobScrollUp">&#9650;</button>
            <button type="button" class="mob-list-bar-btn" id="mobScrollDown">&#9660;</button>
        </div>
        <div class="bulk-panel">
            <label>Toplu Yüzdesel Düzenle:</label>
            <select id="bulkField">
                <option value="MinGold">MinGold</option>
                <option value="MaxGold">MaxGold</option>
                <option value="Exp">Exp</option>
            </select>
            <input type="number" id="bulkPercent" value="50" min="-99" max="500" title="Yüzdeyle değiştir">
            <button type="button" onclick="bulkPercentChange()">Seçili Moblarda Uygula</button>
            <span style="font-size:.97em;color:#888;">(Seçili moblarda ilgili alanı % ile değiştirir.)</span>
        </div>
        <ul class="mob-list-ul" id="mobList">
            <?php
            $searchQuery = isset($_GET['search']) ? mb_strtolower(trim($_GET['search'])) : '';
            $mobCount = 0;
            foreach ($mob_list as $mob):
                $vnum = $mob['Vnum'];
                $name = isset($mob_names[$vnum]) ? $mob_names[$vnum] : $mob['Name'];
                if ($searchQuery &&
                    strpos(mb_strtolower($name), $searchQuery) === false &&
                    strpos(mb_strtolower($vnum), $searchQuery) === false) continue;
                $mobCount++;
                $imgPath = getMobImagePath($vnum, $mob_icon_folder);
            ?>
<li class="mob-list-item<?= ($selected_vnum == $vnum) ? ' active' : '' ?>">
    <input type="checkbox" class="mob-check" value="<?= htmlspecialchars($vnum) ?>">
    <img src="<?= htmlspecialchars($imgPath) ?>" class="mob-list-img" alt="Mob">
    <span class="mob-list-name" style="cursor:pointer;" onclick="window.location.href='?vnum=<?= $vnum ?>'"><?= htmlspecialchars($name) ?></span>
    <span class="mob-list-vnum onclick="window.location.href='?vnum=<?= $vnum ?>'>(<?= htmlspecialchars($vnum) ?>)</span>
    <span style="flex:1"></span>
    <button type="button" class="percent-btn" title="Seç ve Düzenle" style="width: 255px;height: 25px;" onclick="window.location.href='?vnum=<?= $vnum ?>'">Düzenle</button>
</li>
            <?php endforeach; ?>
            <?php if ($mobCount == 0): ?>
                <li><em>Hiç mob bulunamadı.</em></li>
            <?php endif; ?>
        </ul>
    </aside>
    <main class="mob-content">
        <?php
        if (isset($_GET['success']) && $_GET['success']==1) {
            echo '<div class="toast-notify">&#10003; Kayıt başarıyla güncellendi.</div>';
        }
        $selectedMob = null;
        foreach ($mob_list as $mob) {
            if ($mob['Vnum'] == $selected_vnum) {
                $selectedMob = $mob;
                break;
            }
        }
        if ($selectedMob):
            $mobVnum = $selectedMob['Vnum'];
            $mobName = isset($mob_names[$mobVnum]) ? $mob_names[$mobVnum] : $selectedMob['Name'];
            $mobImgPath = getMobImagePath($mobVnum, $mob_icon_folder);
        ?>
<div class="mob-image-area">
    <img src="<?= htmlspecialchars($mobImgPath) ?>" class="mob-image" alt="Mob Görseli">
    <div style="margin-top:7px; color:#2581c6; font-size:1.11rem;">
        Mob: <b><?= htmlspecialchars($mobName) ?></b> (Vnum: <b><?= htmlspecialchars($mobVnum) ?></b>)
        <br>
        Level: <b><?= htmlspecialchars($selectedMob['Level'] ?? '-') ?></b>
    </div>
</div>
        <h2 class="mob-content-title"><?= htmlspecialchars($mobName) ?> Özellikleri</h2>
        <form method="post" class="edit-form" id="mobEditForm" onsubmit="return false;">
            <input type="hidden" name="vnum" value="<?= htmlspecialchars($mobVnum) ?>">
            <div class="edit-row">
                <label for="MinGold">MinGold:</label>
                <input type="number" id="MinGold" name="MinGold" value="<?= htmlspecialchars($selectedMob['MinGold'] ?? '') ?>" required min="0">
                <div class="percent-controls">
                    <input type="number" id="percentMinGold" value="50" min="-99" max="500" title="Yüzdeyle değiştir">
                    <button type="button" class="percent-btn" onclick="applyPercentAndSave('MinGold')">Yüzdeyle Değiştir</button>
                </div>
            </div>
            <div class="edit-row">
                <label for="MaxGold">MaxGold:</label>
                <input type="number" id="MaxGold" name="MaxGold" value="<?= htmlspecialchars($selectedMob['MaxGold'] ?? '') ?>" required min="0">
                <div class="percent-controls">
                    <input type="number" id="percentMaxGold" value="50" min="-99" max="500" title="Yüzdeyle değiştir">
                    <button type="button" class="percent-btn" onclick="applyPercentAndSave('MaxGold')">Yüzdeyle Değiştir</button>
                </div>
            </div>
            <div class="edit-row">
                <label for="Exp">Exp:</label>
                <input type="number" id="Exp" name="Exp" value="<?= htmlspecialchars($selectedMob['Exp'] ?? '') ?>" required min="0">
                <div class="percent-controls">
                    <input type="number" id="percentExp" value="50" min="-99" max="500" title="Yüzdeyle değiştir">
                    <button type="button" class="percent-btn" onclick="applyPercentAndSave('Exp')">Yüzdeyle Değiştir</button>
                </div>
            </div>
            <button type="submit" name="save" class="btn-save" onclick="manualSave()">Kaydet</button>
        </form>
        <?php else: ?>
            <div class="empty">
                <img src="https://cdn-icons-png.flaticon.com/512/565/565547.png" width="96" alt="Mob seç">
                <div>Bir mob 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') ?> Mob Proto Editör - Tasarım & Kodlama: <b>DepDarkMor</b><br><a>v1.0.13</a>
</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) {} }
}

// Anlık arama
document.addEventListener("DOMContentLoaded", function() {
    var mobSearch = document.getElementById("mobSearch");
    var mobList = document.getElementById("mobList");
    mobSearch.addEventListener("input", function(){
        var query = mobSearch.value.trim().toLowerCase();
        mobList.querySelectorAll(".mob-list-item").forEach(function(li){
            var name = (li.querySelector('.mob-list-name')?.textContent || "").toLowerCase();
            var vnum = (li.querySelector('.mob-list-vnum')?.textContent || "").toLowerCase();
            if(query === "" || name.includes(query) || vnum.includes(query)) {
                li.style.display = "";
            }else{
                li.style.display = "none";
            }
        });
    });
    // Seçili mob otomatik ortala
    var activeMob = mobList.querySelector(".active");
    if (activeMob) {
        setTimeout(function(){
            activeMob.scrollIntoView({block:"center",behavior:"smooth"});
        }, 120);
    }
    // Scroll bar buttons
    var mobListUl = document.getElementById("mobList");
    document.getElementById("mobScrollUp").addEventListener("click", function(){
        mobListUl.scrollBy({top:-100,behavior:"smooth"});
    });
    document.getElementById("mobScrollDown").addEventListener("click", function(){
        mobListUl.scrollBy({top:100,behavior:"smooth"});
    });

    // WebSocket ile Go'dan anlık bildirim!
    const ws = new WebSocket("ws://localhost:8080/ws");
    ws.onmessage = function(event) {
        try {
            const data = JSON.parse(event.data);
            showToast("Mob Proto değişti! Tip: " + (data.type || "bilgi"));
            playNotifySound();
        } catch(e) {}
    };
});

// Tekli: Yüzdeyle değiştir & kaydet + bildirim (AJAX)
function applyPercentAndSave(field) {
    var input = document.getElementById(field);
    var percentInput = document.getElementById("percent" + field);
    var current = parseFloat(input.value);
    var percent = parseFloat(percentInput.value) || 0;
    if (isNaN(current) || percent === 0) return;
    var newVal = Math.round(current * (1 + percent / 100));
    input.value = newVal;

    var vnum = document.querySelector('input[name="vnum"]').value;
    var formData = new FormData();
    formData.append("save_percent", "1");
    formData.append("vnum", vnum);
    formData.append("field", field);
    formData.append("value", newVal);

    fetch(window.location.pathname, {
        method: "POST",
        body: formData
    })
    .then(r=>r.text())
    .then(r=>{
        showToast("Kayıt başarıyla güncellendi.");
        playNotifySound();
    });
}

// Manuel Kaydet (form submit)
function manualSave() {
    var vnum = document.querySelector('input[name="vnum"]').value;
    var minGold = document.getElementById("MinGold").value;
    var maxGold = document.getElementById("MaxGold").value;
    var exp = document.getElementById("Exp").value;
    var formData = new FormData();
    formData.append("save", "1");
    formData.append("vnum", vnum);
    formData.append("MinGold", minGold);
    formData.append("MaxGold", maxGold);
    formData.append("Exp", exp);

    fetch(window.location.pathname, {
        method: "POST",
        body: formData
    })
    .then(r=>r.text())
    .then(r=>{
        showToast("Kayıt başarıyla güncellendi.");
        playNotifySound();
        setTimeout(()=>window.location.reload(), 700);
    });
    return false;
}

// Toplu Yüzdesel Düzenleme (checkbox ile)
function bulkPercentChange() {
    var selected = Array.from(document.querySelectorAll('.mob-check:checked')).map(e=>e.value);
    if (selected.length == 0) { showToast("Mob seçiniz!"); return; }
    var field = document.getElementById("bulkField").value;
    var percent = parseFloat(document.getElementById("bulkPercent").value) || 0;
    if (percent === 0) { showToast("Yüzde giriniz!"); return; }

    var formData = new FormData();
    formData.append("bulk_percent", "1");
    formData.append("bulk_vnums", selected.join(","));
    formData.append("bulk_field", field);
    formData.append("bulk_percent_value", percent);

    fetch(window.location.pathname, {
        method: "POST",
        body: formData
    })
    .then(r=>r.text())
    .then(r=>{
        showToast("Toplu kayıt başarıyla güncellendi.");
        playNotifySound();
        setTimeout(()=>window.location.reload(), 700);
    });
}
</script>
</body>
</html>