<?php
require_once __DIR__ . "/../config.php";
require_once __DIR__ . "/../includes/functions.php";

if (empty($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit();
}

$pageTitle = "Nachbestellungen";
$message = "";
$messageType = "";

if ($_SERVER['REQUEST_METHOD'] === "POST" && isset($_POST['add_manual_backorder'])) {
    if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
        $message = "Ungültiges Token. Bitte versuchen Sie es erneut.";
        $messageType = "error";
    } else {
        $result = addManualBackorderItems(
            $_POST['product_id'] ?? 0,
            $_POST['size'] ?? "",
            $_POST['quantity'] ?? 0,
        );
        $message = $result["success"]
            ? ($result["added"] ?? 0) . " Position(en) zur Nachbestellung hinzugefügt."
            : $result["message"];
        $messageType = $result["success"] ? "success" : "error";

        if ($result["success"]) {
            logAccess("Admin added manual backorder items", [
                "admin" => $_SESSION['admin_username'] ?? "unknown",
                "product_id" => $_POST['product_id'] ?? 0,
                "size" => $_POST['size'] ?? "",
                "quantity" => $_POST['quantity'] ?? 0,
            ]);
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === "POST" && isset($_POST['mark_ordered'])) {
    if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
        $message = "Ungültiges Token. Bitte versuchen Sie es erneut.";
        $messageType = "error";
    } else {
        $result = markBackorderItemsOrdered(
            $_POST['product_id'] ?? 0,
            $_POST['size'] ?? "",
            $_POST['quantity'] ?? 0,
        );
        $message = $result["success"]
            ? ($result["updated"] ?? 0) .
                " Position(en) als bestellt markiert."
            : $result["message"];
        $messageType = $result["success"] ? "success" : "error";

        if ($result["success"]) {
            logAccess("Admin marked backorder items ordered", [
                "admin" => $_SESSION['admin_username'] ?? "unknown",
                "product_id" => $_POST['product_id'] ?? 0,
                "size" => $_POST['size'] ?? "",
                "quantity" => $_POST['quantity'] ?? 0,
            ]);
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === "POST" && isset($_POST['mark_delivered'])) {
    if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
        $message = "Ungültiges Token. Bitte versuchen Sie es erneut.";
        $messageType = "error";
    } else {
        $result = markBackorderItemsDelivered(
            $_POST['product_id'] ?? 0,
            $_POST['size'] ?? "",
            $_POST['quantity'] ?? 0,
        );
        $message = $result["success"]
            ? ($result["updated"] ?? 0) .
                " Position(en) als geliefert markiert."
            : $result["message"];
        $messageType = $result["success"] ? "success" : "error";

        if ($result["success"]) {
            logAccess("Admin marked backorder items delivered", [
                "admin" => $_SESSION['admin_username'] ?? "unknown",
                "product_id" => $_POST['product_id'] ?? 0,
                "size" => $_POST['size'] ?? "",
                "quantity" => $_POST['quantity'] ?? 0,
            ]);
        }
    }
}

$groups = getBackorderGroups();
$products = getProducts();
$productSizeMap = [];
foreach ($products as $product) {
    $sizes = getProductSizes($product);
    if (empty($sizes)) {
        $sizes = ["Standard"];
    }
    $productSizeMap[(int) $product["id"]] = $sizes;
}

$bodyClass = "admin-page";
include __DIR__ . "/../includes/header.php";
?>

<div class="admin-header">
    <h2>Nachbestellungen</h2>
    <div>
        <a href="index.php" class="btn btn-secondary">Zurück zum Dashboard</a>
        <a href="orders.php" class="btn btn-secondary">Bestellungen</a>
    </div>
</div>

<?php if ($message !== ""): ?>
    <div class="alert alert-<?php echo escape($messageType); ?>">
        <?php echo escape($message); ?>
    </div>
<?php endif; ?>

<p class="text-muted">
    Artikel werden nach Produkt und Größe zusammengefasst. Aktionen bearbeiten die ältesten Bestellungen zuerst (FIFO).
</p>

<div class="admin-panel backorder-add-panel">
    <h3>Artikel manuell hinzufügen</h3>
    <p class="text-muted">
        Für Bedarf ohne zugehörige Kundenbestellung (z.&nbsp;B. Lagerauffüllung).
    </p>
    <?php if (empty($products)): ?>
        <p>Keine Artikel im Katalog vorhanden.</p>
    <?php else: ?>
        <form method="POST" class="admin-filter-form backorder-add-form">
            <?php echo csrfField(); ?>
            <div class="admin-filter-field">
                <label for="manual_backorder_product">Artikel</label>
                <select id="manual_backorder_product" name="product_id" required>
                    <option value="">Bitte wählen</option>
                    <?php foreach ($products as $product): ?>
                        <option value="<?php echo (int) $product["id"]; ?>">
                            <?php echo escape($product["name"]); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="admin-filter-field">
                <label for="manual_backorder_size">Größe</label>
                <select id="manual_backorder_size" name="size" required disabled>
                    <option value="">Zuerst Artikel wählen</option>
                </select>
            </div>
            <div class="admin-filter-field">
                <label for="manual_backorder_quantity">Anzahl</label>
                <input
                    type="number"
                    id="manual_backorder_quantity"
                    name="quantity"
                    min="1"
                    max="100"
                    value="1"
                    required
                    class="backorder-qty-input"
                >
            </div>
            <button type="submit" name="add_manual_backorder" class="btn">
                Zur Nachbestellung hinzufügen
            </button>
        </form>
    <?php endif; ?>
</div>

<?php if (empty($groups)): ?>
    <div class="alert alert-info">
        <p>Keine Nachbestellungen vorhanden.</p>
    </div>
<?php else: ?>
    <div class="table-responsive">
        <table class="responsive-table">
            <thead>
                <tr>
                    <th>Artikel</th>
                    <th>Größe</th>
                    <th>Nachzubestellen</th>
                    <th>Wartet auf Lieferung</th>
                    <th>Als bestellt markieren</th>
                    <th>Lieferung eingetroffen</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($groups as $group): ?>
                    <tr>
                        <td data-label="Artikel"><?php echo escape(
                            $group["product_name"],
                        ); ?></td>
                        <td data-label="Größe"><?php echo $group["size"] !== ""
                            ? escape($group["size"])
                            : "-"; ?></td>
                        <td data-label="Nachzubestellen">
                            <strong><?php echo (int) $group[
                                "to_be_backordered"
                            ]; ?></strong>
                        </td>
                        <td data-label="Wartet auf Lieferung">
                            <strong><?php echo (int) $group["ordered"]; ?></strong>
                        </td>
                        <td data-label="Als bestellt markieren">
                            <?php if ($group["to_be_backordered"] > 0): ?>
                                <form method="POST" class="backorder-action-form">
                                    <?php echo csrfField(); ?>
                                    <input type="hidden" name="product_id" value="<?php echo (int) $group[
                                        "product_id"
                                    ]; ?>">
                                    <input type="hidden" name="size" value="<?php echo escape(
                                        $group["size"],
                                    ); ?>">
                                    <label class="sr-only" for="qty_ordered_<?php echo (int) $group[
                                        "product_id"
                                    ]; ?>_<?php echo escape(
    preg_replace("/[^a-z0-9]/i", "_", $group["size"]),
); ?>">Menge</label>
                                    <input
                                        type="number"
                                        id="qty_ordered_<?php echo (int) $group[
                                            "product_id"
                                        ]; ?>_<?php echo escape(
    preg_replace("/[^a-z0-9]/i", "_", $group["size"]),
); ?>"
                                        name="quantity"
                                        min="1"
                                        max="<?php echo (int) $group[
                                            "to_be_backordered"
                                        ]; ?>"
                                        value="1"
                                        class="backorder-qty-input"
                                    >
                                    <button type="submit" name="mark_ordered" class="btn btn-small">
                                        Als bestellt markieren
                                    </button>
                                </form>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td data-label="Lieferung eingetroffen">
                            <?php if ($group["ordered"] > 0): ?>
                                <form method="POST" class="backorder-action-form">
                                    <?php echo csrfField(); ?>
                                    <input type="hidden" name="product_id" value="<?php echo (int) $group[
                                        "product_id"
                                    ]; ?>">
                                    <input type="hidden" name="size" value="<?php echo escape(
                                        $group["size"],
                                    ); ?>">
                                    <label class="sr-only" for="qty_delivered_<?php echo (int) $group[
                                        "product_id"
                                    ]; ?>_<?php echo escape(
    preg_replace("/[^a-z0-9]/i", "_", $group["size"]),
); ?>">Menge</label>
                                    <input
                                        type="number"
                                        id="qty_delivered_<?php echo (int) $group[
                                            "product_id"
                                        ]; ?>_<?php echo escape(
    preg_replace("/[^a-z0-9]/i", "_", $group["size"]),
); ?>"
                                        name="quantity"
                                        min="1"
                                        max="<?php echo (int) $group["ordered"]; ?>"
                                        value="1"
                                        class="backorder-qty-input"
                                    >
                                    <button type="submit" name="mark_delivered" class="btn btn-small btn-secondary">
                                        Lieferung eingetroffen
                                    </button>
                                </form>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

<?php if (!empty($productSizeMap)): ?>
<script>
(function () {
    const sizesByProduct = <?php echo json_encode(
        $productSizeMap,
        JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT,
    ); ?>;
    const productSelect = document.getElementById("manual_backorder_product");
    const sizeSelect = document.getElementById("manual_backorder_size");

    if (!productSelect || !sizeSelect) {
        return;
    }

    function updateSizeOptions() {
        const productId = productSelect.value;
        const sizes = sizesByProduct[productId] || [];
        sizeSelect.innerHTML = "";

        if (sizes.length === 0) {
            sizeSelect.disabled = true;
            const option = document.createElement("option");
            option.value = "";
            option.textContent = "Zuerst Artikel wählen";
            sizeSelect.appendChild(option);
            return;
        }

        sizes.forEach(function (size) {
            const option = document.createElement("option");
            option.value = size;
            option.textContent = size;
            sizeSelect.appendChild(option);
        });
        sizeSelect.disabled = false;
    }

    productSelect.addEventListener("change", updateSizeOptions);
})();
</script>
<?php endif; ?>

<?php include __DIR__ . "/../includes/footer.php"; ?>
