<?php
declare(strict_types=1);

require __DIR__ . '/auth.php';

// Schutz: nur eingeloggte User dürfen hier hin
requireLogin();
$user = currentUser();

// Geschäfte aus DB laden
$stmt = $pdo->query("
    SELECT s.id,
           s.name,
           s.file,
           COUNT(i.id) AS article_count
    FROM stores s
    LEFT JOIN items i ON i.store_id = s.id
    GROUP BY s.id
    ORDER BY s.sort_order, s.name
");
$stores = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="de">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EKL - Meine Gesch&auml;fte</title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="icon" href="icons/logo.png" type="image/png">
</head>

<body>
    <div id="app">
        <div class="user-info">
            Eingeloggt als
            <?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?>
            | <a href="logout.php">Logout</a>
        </div>

        <h1>Meine Gesch&auml;fte</h1>

        <form id="addStoreForm" method="post" action="php/add_store.php">
            <input type="text" name="name" placeholder="Gesch&auml;ftsname" required>
            <button type="submit" class="btn-with-icon">
                <span class="icon" aria-hidden="true">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M12 5v14"></path>
                        <path d="M5 12h14"></path>
                    </svg>
                </span>
                Gesch&auml;ft hinzuf&uuml;gen
            </button>
        </form>

        <ul id="storeList">
            <?php if ($stores): ?>
                <?php foreach ($stores as $store): ?>
                    <li class="store-item"
                        draggable="true"
                        data-id="<?= (int)$store['id'] ?>"
                        data-file="<?= htmlspecialchars($store['file']) ?>">

                        <span>
                            <?= htmlspecialchars($store['name']) ?>
                            (<?= (int)$store['article_count'] ?> Artikel)
                        </span>

                        <div class="store-actions">
                            <a href="articles.php?store=<?= urlencode($store['file']) ?>"
                               class="view-store btn-with-icon"
                               title="Artikel anzeigen">
                                <span class="icon" aria-hidden="true">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <path d="M2 12s4-6 10-6 10 6 10 6-4 6-10 6-10-6-10-6z"></path>
                                        <circle cx="12" cy="12" r="3"></circle>
                                    </svg>
                                </span>
                                Anzeigen
                            </a>
                             <a href="store_pdf.php?store=<?= urlencode($store['file']) ?>"
                                class="pdf-store btn-with-icon"
                                title="PDF Einkaufsliste"
                                target="_blank"
                                rel="noopener noreferrer">
                                <span class="icon" aria-hidden="true">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <path d="M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z"></path>
                                        <path d="M14 2v5h5"></path>
                                        <path d="M8 13h8"></path>
                                        <path d="M8 17h6"></path>
                                    </svg>
                                </span>
                                PDF
                            </a>


                            <form method="post"
                                  action="php/delete_store.php"
                                  onsubmit="return confirmDelete('<?= htmlspecialchars($store['name']) ?>');">
                                <input type="hidden" name="store_id" value="<?= (int)$store['id'] ?>">
                                <button type="submit"
                                        class="delete-store btn-with-icon"
                                        title="Gesch&auml;ft l&ouml;schen">
                                    <span class="icon" aria-hidden="true">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                            <path d="M3 6h18"></path>
                                            <path d="M8 6V4h8v2"></path>
                                            <path d="M19 6l-1 14H6L5 6"></path>
                                            <path d="M10 11v6"></path>
                                            <path d="M14 11v6"></path>
                                        </svg>
                                    </span>
                                    L&ouml;schen
                                </button>
                            </form>
                        </div>
                    </li>
                <?php endforeach; ?>
            <?php else: ?>
                <p>Keine Gesch&auml;fte gefunden.</p>
            <?php endif; ?>
        </ul>
    </div>

    <?php include 'footer.php'; ?>

    <script>
        const storeList = document.getElementById("storeList");
        let draggedStore = null;

        function confirmDelete(storeName) {
            return confirm("Moechten Sie das Geschaeft \"" + storeName + "\" wirklich loeschen?");
        }

        storeList.addEventListener("dragstart", (e) => {
            const li = e.target.closest('.store-item');
            if (!li) return;
            draggedStore = li;
            draggedStore.classList.add("dragging");
        });

        storeList.addEventListener("dragend", () => {
            if (!draggedStore) return;
            draggedStore.classList.remove("dragging");
            const stores = [...storeList.querySelectorAll(".store-item")];
            const updatedOrder = stores.map((store) => ({
                file: store.dataset.file
            }));
            fetch("php/update_store_order.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(updatedOrder),
            }).then((response) => {
                if (!response.ok) {
                    alert("Fehler beim Speichern der neuen Reihenfolge!");
                }
            });
        });

        storeList.addEventListener("dragover", (e) => {
            e.preventDefault();
            const afterElement = getDragAfterElement(storeList, e.clientY);
            if (afterElement == null) {
                storeList.appendChild(draggedStore);
            } else {
                storeList.insertBefore(draggedStore, afterElement);
            }
        });

        function getDragAfterElement(container, y) {
            const draggableElements = [...container.querySelectorAll(".store-item: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: offset, element: child };
                    } else {
                        return closest;
                    }
                },
                { offset: Number.NEGATIVE_INFINITY }
            ).element;
        }
    </script>
</body>

</html>




