<?php
declare(strict_types=1);

/**
ET-Chat Copyright by SEDesign | ET-Chat v3.x.x Lizenz: CCPL | Autor: Evgeni Tcherkasski (info@s-e-d.de)
ET-Chat_T-FISH-MOD Weiterentwicklungen, Optimierungen und Ergänzungen am Code sind das geistige Eigentum von Tommy (Thomas Kuhn) und Harlekin (Bernd Witte).

Die darauf folgende Optimierungen und Ergänzungen am Code sind das Geistige Eigentum von Powermen (Christian K.)
und wird unter der Namenserweiterung M.C.v.x.x.x. geführt. 
PHP 8/9 Ready, XML Parser, PDO Prepared Statements Get Set sicherheit usw.
 */

$csrf = (string)($_SESSION['etchat_' . $this->_prefix . 'csrf_token'] ?? '');

function e(string $v): string {
    return htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
}

ob_start();
?>

<p>
    <small>Reihenfolge per Drag & Drop lässt sich nur innerhalb einer Kategorie ändern und speichern.</small>
</p>

<div style="display:flex; gap:15px; flex-wrap:wrap; align-items:center;">
    <a href="./?AdminCreateNewSmilies" class="admin-button">
        <?= e($lang->smilie[0]->tagData ?? 'Neuer Smiley') ?>
    </a>

    <a href="./?AdminCreateNewSmiliesgrupp" class="admin-button">
        Kategorien mit Smileys befüllen
    </a>
</div>

<br>

<div class="admin-toolbar">

    <div class="admin-toolbar-box">
        <?= $list3 ?>
    </div>

    <div class="admin-toolbar-box">
        <?= $list4 ?>
    </div>

    <div class="admin-toolbar-box">
        <?= $list2 ?>
    </div>

    <div class="admin-toolbar-box">
        <?= $list5 ?>
    </div>
	


</div>
	    <?= $savedMsg ?>
<!-- Tabelle -->
<form id="catOrderForm">
<table id="smileyTable">
    <thead>
        <tr>
            <th></th>
            <th>Bild</th>
            <th>Kürzel</th>
            <th>Kategorie</th>
            <th>Umbenennen</th>
            <th>Löschen</th>
            <th>Gewicht</th>
        </tr>
    </thead>
    <tbody>
        <?= $list ?>
    </tbody>
</table>
</form>
<br>

<button id="backToTopBtn" title="Nach oben">↑</button>

<script>
const CSRF_TOKEN = "<?= e($csrf) ?>";

// =========================
// STATE
// =========================
let unsavedChanges = false;
let dragSrcRow = null;

// =========================
// DOM READY
// =========================
document.addEventListener("DOMContentLoaded", () => {

    initDragAndDrop();
    initSaveSystem();
    initNavigationGuard();
    initSiteSelector();
    initSuccessBanner();

    initBackToTop();
});


// =========================
// DRAG & DROP
// =========================
function initDragAndDrop() {

    const urlParams = new URLSearchParams(window.location.search);
    const currentKat = urlParams.get('kat') || '';
    const saveBtn = document.getElementById('saveSmileyBtn');

    if (saveBtn) saveBtn.disabled = true;

    const placeholder = document.createElement("tr");
    placeholder.classList.add("dragging");
    placeholder.innerHTML = "<td colspan='7'>&nbsp;</td>";

    document.querySelectorAll("tr[draggable='true']").forEach(row => {

        if (!currentKat || row.dataset.kat !== currentKat) {
            row.draggable = false;

            const img = row.querySelector(".img_verschieben");
            if (img) img.classList.add("img_drag_disabled");

            return;
        }

        row.addEventListener("dragstart", e => {
            dragSrcRow = row;
            e.dataTransfer.setData("text/plain", row.dataset.id);

            row.parentNode.insertBefore(placeholder, row.nextSibling);
            setTimeout(() => row.style.display = "none", 0);
        });

        row.addEventListener("dragend", () => {
            placeholder.parentNode.insertBefore(dragSrcRow, placeholder);
            dragSrcRow.style.display = "";
            placeholder.remove();

            unsavedChanges = true;
            if (saveBtn) saveBtn.disabled = false;
        });

        row.addEventListener("dragover", e => {
            e.preventDefault();

            const target = e.target.closest("tr[draggable='true']");
            if (!target || target === placeholder) return;

            target.parentNode.insertBefore(placeholder, target.nextSibling);
        });
    });
}


// =========================
// SAVE SYSTEM
// =========================
function initSaveSystem() {

    window.saveOrder = function () {

        const params = new URLSearchParams(window.location.search);
        const currentSite = params.get('site') || 1;
        const currentKat = params.get('kat') || '';

        if (!currentKat) {
            alert("Speichern nur möglich, wenn eine Kategorie gewählt ist.");
            return;
        }

        const rows = Array.from(document.querySelectorAll("tr[draggable='true']"))
            .filter(r => r.dataset.kat === currentKat);

        if (!rows.length) {
            alert("Keine Smileys vorhanden.");
            return;
        }

        const ids = rows.map(r => r.dataset.id);

        fetch(`./?AdminSmiliesIndex&SaveSmileyOrder=1&site=${currentSite}&kat=${encodeURIComponent(currentKat)}`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-CSRF-Token": CSRF_TOKEN
            },
            body: JSON.stringify({ kat: currentKat, site: currentSite, ids })
        })
        .then(r => r.text())
        .then(txt => {

            if (txt.trim() === "Gespeichert") {

                unsavedChanges = false;

                const btn = document.getElementById('saveSmileyBtn');
                if (btn) btn.disabled = true;

                const url = new URL(window.location.href);
                url.searchParams.set("saved", "1");

                setTimeout(() => {
                    window.location.href = url.toString();
                }, 50);

            } else {
                alert(txt);
            }
        })
        .catch(err => alert("Fehler: " + err));
    };
}


// =========================
// NAVIGATION GUARD
// =========================
function initNavigationGuard() {

    window.addEventListener("beforeunload", e => {
        if (!unsavedChanges) return;

        const saveBtn = document.getElementById('saveSmileyBtn');
        if (saveBtn && saveBtn.disabled) return;

        e.preventDefault();
        e.returnValue = "";
    });

    document.addEventListener("click", e => {
        if (!unsavedChanges) return;

        const target = e.target.closest("a");
        if (!target) return;

        if (!confirm("Ungespeicherte Änderungen verwerfen?")) {
            e.preventDefault();
        }
    });
}


// =========================
// SITE SELECTOR
// =========================
function initSiteSelector() {

    const sel = document.getElementById("site_selecter");
    if (!sel) return;

    const params = new URLSearchParams(window.location.search);
    sel.value = params.get("site") || "1";

    sel.addEventListener("change", () => {

        if (unsavedChanges && !confirm("Es gibt ungespeicherte Änderungen. Wirklich wechseln?")) {
            sel.value = params.get("site") || "1";
            return;
        }

        const p = new URLSearchParams(window.location.search);

        p.set("AdminSmiliesIndex", "1");
        p.set("site", sel.value);

        const kat = params.get("kat");
        if (kat) p.set("kat", kat);

        window.location.search = p.toString();
    });
}


// =========================
// SUCCESS BANNER
// =========================
function initSuccessBanner() {

    window.closeSuccessBanner = function () {
        const el = document.getElementById("successBanner");
        if (el) el.remove();
    };

    const el = document.getElementById("successBanner");

    if (el) {
        setTimeout(() => {
            el.style.transition = "opacity 0.5s ease";
            el.style.opacity = "0";

            setTimeout(() => el.remove(), 500);
        }, 5000);
    }
}


// =========================
// BACK TO TOP
// =========================
function initBackToTop() {

    const btn = document.getElementById("backToTopBtn");
    if (!btn) return;

    window.addEventListener("scroll", () => {
        btn.style.display = (window.scrollY > 300) ? "block" : "none";
    });

    btn.addEventListener("click", () => {
        window.scrollTo({ top: 0, behavior: "smooth" });
    });
}
</script>

<?php
$content = ob_get_clean();

$pageTitle = $lang->title[0]->tagData ?? 'Smiley Verwaltung';
$backLink  = './?AdminIndex';
$footerNote = $lang->note[0]->tagData ?? 'Beachte, dass administratorische Änderungen bei den Smilies sofort sichtbar werden.';
include __DIR__ . '/admin_master_template.php';
?>