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

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

expirePendingOrders();

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

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();

$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>

<?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 include __DIR__ . "/../includes/footer.php"; ?>
