document.addEventListener("DOMContentLoaded", () => {
    const shoppingTableBody = document.querySelector("#shoppingTable tbody");

    // Funktion zum Laden der Artikel
    const loadList = async () => {
        const storeFile = new URLSearchParams(window.location.search).get("store");
        const response = await fetch(`data/${storeFile}`);
        const items = await response.json();
        renderTable(items);
    };

    // Tabelle rendern
    const renderTable = (items) => {
        shoppingTableBody.innerHTML = "";
        items.forEach((item, index) => {
            const row = document.createElement("tr");
            row.draggable = true;
            row.dataset.index = index;

            row.innerHTML = `
                <td class="drag-handle">⬍</td>
                <td>${item.name}</td>
                <td>${item.price ? item.price.toFixed(2) : "0.00"} €</td>
                <td>${item.amount}</td>
                <td>${item.unit}</td>
                <td><button data-index="${index}" class="delete-btn">Löschen</button></td>
            `;

            shoppingTableBody.appendChild(row);

            // Drag-and-Drop Events
            row.addEventListener("dragstart", handleDragStart);
            row.addEventListener("dragover", handleDragOver);
            row.addEventListener("drop", handleDrop);
            row.addEventListener("dragend", handleDragEnd);
        });
    };

    let draggedRow = null;

    const handleDragStart = (e) => {
        draggedRow = e.target;
        e.target.classList.add("dragging");
    };

    const handleDragOver = (e) => {
        e.preventDefault();
        const afterElement = getDragAfterElement(shoppingTableBody, e.clientY);
        if (afterElement == null) {
            shoppingTableBody.appendChild(draggedRow);
        } else {
            shoppingTableBody.insertBefore(draggedRow, afterElement);
        }
    };

    const handleDrop = async () => {
        await saveNewOrder();
    };

    const handleDragEnd = (e) => {
        e.target.classList.remove("dragging");
    };

    const getDragAfterElement = (container, y) => {
        const draggableElements = [...container.querySelectorAll("tr:not(.dragging)")];

        return draggableElements.reduce(
            (closest, child) => {
                const box = child.getBoundingClientRect();
                const offset = y - box.top - box.height / 2;
                if (offset < 0 && offset > closest.offset) {
                    return { offset, element: child };
                } else {
                    return closest;
                }
            },
            { offset: Number.NEGATIVE_INFINITY }
        ).element;
    };

    // Funktion, um die neue Reihenfolge zu speichern
    const saveNewOrder = async () => {
        const newOrder = [...shoppingTableBody.children].map((row) => {
            return {
                name: row.children[1].textContent,
                price: parseFloat(row.children[2].textContent.replace(" €", "")),
                amount: parseInt(row.children[3].textContent),
                unit: row.children[4].textContent,
            };
        });

        const storeFile = new URLSearchParams(window.location.search).get("store");

        const response = await fetch("php/update_order.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ storeFile, items: newOrder }),
        });

        if (!response.ok) {
            console.error("Fehler beim Speichern der Reihenfolge auf dem Server.");
        }
    };

    // Artikel löschen
    shoppingTableBody.addEventListener("click", async (e) => {
        if (e.target.classList.contains("delete-btn")) {
            const index = e.target.getAttribute("data-index");
            const storeFile = new URLSearchParams(window.location.search).get("store");
            const response = await fetch("php/delete_item.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ storeFile, index }),
            });
            const updatedList = await response.json();
            renderTable(updatedList);
        }
    });

    loadList();
});
