<?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 = "Bestellungen";
$message = "";
$messageType = "";

if (
    $_SERVER['REQUEST_METHOD'] === "POST" &&
    isset($_POST['toggle_item_backorder'])
) {
    if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
        $message = "Ungültiges Token. Bitte versuchen Sie es erneut.";
        $messageType = "error";
    } else {
        $result = toggleOrderItemBackorder(
            $_POST['order_id'] ?? "",
            (int) ($_POST['item_index'] ?? -1),
        );
        $message = $result["success"]
            ? "Nachbestellstatus wurde aktualisiert."
            : $result["message"];
        $messageType = $result["success"] ? "success" : "error";

        if ($result["success"]) {
            logAccess("Admin toggled order item backorder", [
                "admin" => $_SESSION['admin_username'] ?? "unknown",
                "order_id" => $_POST['order_id'] ?? "",
                "item_index" => $_POST['item_index'] ?? -1,
            ]);
        }
    }
}

if (
    $_SERVER['REQUEST_METHOD'] === "POST" &&
    isset($_POST['toggle_item_processed'])
) {
    // Validate CSRF token
    if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
        $message = "Ungültiges Token. Bitte versuchen Sie es erneut.";
        $messageType = "error";
    } else {
        $result = toggleOrderItemProcessed(
            $_POST['order_id'] ?? "",
            (int) ($_POST['item_index'] ?? -1),
        );
        $message = $result["success"]
            ? "Position wurde aktualisiert."
            : $result["message"];
        $messageType = $result["success"] ? "success" : "error";

        if ($result["success"]) {
            logAccess("Admin toggled order item", [
                "admin" => $_SESSION['admin_username'] ?? "unknown",
                "order_id" => $_POST['order_id'] ?? "",
                "item_index" => $_POST['item_index'] ?? -1,
            ]);
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === "POST" && isset($_POST['cancel_order'])) {
    // Validate CSRF token
    if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
        $message = "Ungültiges Token. Bitte versuchen Sie es erneut.";
        $messageType = "error";
    } else {
        $adminUsername = $_SESSION['admin_username'] ?? "";
        $result = cancelOrder(
            $_POST['order_id'] ?? "",
            $adminUsername,
            $_POST['cancellation_reason'] ?? "",
        );
        $message = $result["success"]
            ? "Bestellung wurde storniert."
            : $result["message"];
        $messageType = $result["success"] ? "success" : "error";

        if ($result["success"]) {
            logAccess("Admin cancelled order", [
                "admin" => $adminUsername,
                "order_id" => $_POST['order_id'] ?? "",
            ]);
        }
    }
}

$orders = getOrders();
usort($orders, function ($left, $right) {
    return strcmp($right["created_at"], $left["created_at"]);
});

$filter = trim((string) ($_GET['filter'] ?? "all"));
$searchOrderId = trim((string) ($_GET['order_id'] ?? ""));
$selectedOrderId = trim((string) ($_GET['details'] ?? $searchOrderId));

if ($searchOrderId !== "") {
    $orders = array_values(
        array_filter($orders, function ($order) use ($searchOrderId) {
            return stripos($order["id"], $searchOrderId) !== false;
        }),
    );
}

if ($filter !== "all") {
    $orders = array_values(
        array_filter($orders, function ($order) use ($filter) {
            switch ($filter) {
                case "unconfirmed":
                    return $order["confirmation_status"] === "pending";
                case "expired":
                    return $order["confirmation_status"] === "expired";
                case "open":
                    return $order["confirmation_status"] !== "pending" &&
                        $order["status"] === "open";
                case "partial":
                    return $order["status"] === "partial";
                case "processed":
                    return $order["status"] === "processed";
                case "cancelled":
                    return $order["status"] === "cancelled";
            }
            return true;
        }),
    );
}

$selectedOrder =
    $selectedOrderId !== "" ? getOrderById($selectedOrderId) : null;

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

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

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

<div class="panel">
    <form method="GET" class="admin-filter-form">
        <div class="admin-filter-field admin-filter-field-wide">
            <label for="order_id">Bestellnummer suchen</label>
            <input type="text" id="order_id" name="order_id" value="<?php echo escape(
                $searchOrderId,
            ); ?>" placeholder="z. B. FWFS-2026-001">
        </div>
        <div>
            <label for="filter">Filter</label>
            <select id="filter" name="filter">
                <option value="all" <?php echo $filter === "all"
                    ? "selected"
                    : ""; ?>>Alle</option>
                <option value="unconfirmed" <?php echo $filter === "unconfirmed"
                    ? "selected"
                    : ""; ?>>Unbestätigt</option>
                <option value="expired" <?php echo $filter === "expired"
                    ? "selected"
                    : ""; ?>>Bestätigung abgelaufen</option>
                <option value="open" <?php echo $filter === "open"
                    ? "selected"
                    : ""; ?>>Offen</option>
                <option value="partial" <?php echo $filter === "partial"
                    ? "selected"
                    : ""; ?>>Teilweise bearbeitet</option>
                <option value="processed" <?php echo $filter === "processed"
                    ? "selected"
                    : ""; ?>>Bearbeitet</option>
                <option value="cancelled" <?php echo $filter === "cancelled"
                    ? "selected"
                    : ""; ?>>Storniert</option>
            </select>
        </div>
        <div class="admin-filter-actions">
            <button type="submit" class="btn">Filtern</button>
            <a href="orders.php" class="btn btn-secondary">Zurücksetzen</a>
        </div>
    </form>
</div>

<?php if (empty($orders)): ?>
    <div class="alert alert-info">
        <p>Keine Bestellungen gefunden.</p>
    </div>
<?php else: ?>
    <div class="table-responsive">
        <table class="responsive-table">
            <thead>
                <tr>
                    <th>Bestellnummer</th>
                    <th>Name</th>
                    <th>Organisation</th>
                    <th>Artikel</th>
                    <th>Erstellt</th>
                    <th>Status</th>
                    <th>Aktionen</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orders as $order): ?>
                    <tr>
                        <td data-label="Bestellnummer"><strong><?php echo escape(
                            $order["id"],
                        ); ?></strong></td>
                        <td data-label="Name"><?php echo escape(
                            $order["customer_name"],
                        ); ?></td>
                        <td data-label="Organisation"><?php echo escape(
                            $order["organization_label"],
                        ); ?></td>
                        <td data-label="Artikel"><?php echo count(
                            $order["items"],
                        ); ?></td>
                        <td data-label="Erstellt"><?php echo escape(
                            formatDate($order["created_at"]),
                        ); ?></td>
                        <td data-label="Status"><span class="status <?php echo escape(
                            getOrderStatusClass($order),
                        ); ?>"><?php echo escape(
    getOrderStatusLabel($order),
); ?></span></td>
                        <td data-label="Aktionen">
                            <a href="orders.php?details=<?php echo urlencode(
                                $order["id"],
                            ); ?>" class="btn btn-small">Details</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

<?php if ($selectedOrder !== null): ?>
    <div class="panel">
        <h3>Bestellung <?php echo escape($selectedOrder["id"]); ?></h3>
        <p><strong>Status:</strong> <span class="status <?php echo escape(
            getOrderStatusClass($selectedOrder),
        ); ?>"><?php echo escape(
    getOrderStatusLabel($selectedOrder),
); ?></span>
        <?php if (orderHasBackorder($selectedOrder)): ?>
            <span class="status status-backorder">Nachbestellung</span>
        <?php endif; ?>
        </p>
        <p><strong>Name:</strong> <?php echo escape(
            $selectedOrder["customer_name"],
        ); ?></p>
        <p><strong>E-Mail:</strong> <?php echo escape(
            $selectedOrder["customer_email"],
        ); ?></p>
        <p><strong>Organisation:</strong> <?php echo escape(
            $selectedOrder["organization_label"],
        ); ?></p>
        <p><strong>Erstellt:</strong> <?php echo escape(
            formatDate($selectedOrder["created_at"]),
        ); ?></p>
        <?php if ($selectedOrder["confirmed_at"] !== ""): ?>
            <p><strong>Bestätigt:</strong> <?php echo escape(
                formatDate($selectedOrder["confirmed_at"]),
            ); ?></p>
        <?php endif; ?>
        <?php if ($selectedOrder["confirmation_status"] === "pending"): ?>
            <p><strong>Bestätigung offen bis:</strong> <?php echo escape(
                formatDate($selectedOrder["confirmation_expires_at"]),
            ); ?></p>
        <?php endif; ?>
        <?php if ($selectedOrder["admin_notified_at"] !== ""): ?>
            <p><strong>Intern weitergeleitet:</strong> <?php echo escape(
                formatDate($selectedOrder["admin_notified_at"]),
            ); ?></p>
        <?php endif; ?>
        <p><strong>Kommentar:</strong><br><?php echo $selectedOrder[
            "comment"
        ] !== ""
            ? nl2br(escape($selectedOrder["comment"]))
            : "Kein Kommentar"; ?></p>

        <?php if ($selectedOrder["status"] === "cancelled"): ?>
            <div class="alert alert-warning">
                <p><strong>Storniert am:</strong> <?php echo escape(
                    formatDate($selectedOrder["cancelled_at"]),
                ); ?></p>
                <p><strong>Storniert durch:</strong> <?php echo escape(
                    $selectedOrder["cancelled_by"],
                ); ?></p>
                <p><strong>Stornogrund:</strong><br><?php echo $selectedOrder[
                    "cancellation_reason"
                ] !== ""
                    ? nl2br(escape($selectedOrder["cancellation_reason"]))
                    : "Kein Grund angegeben"; ?></p>
            </div>
        <?php endif; ?>

        <h4>Positionen</h4>
        <div class="table-responsive">
            <table class="responsive-table table-compact">
                <thead>
                    <tr>
                        <th>Artikel</th>
                        <th>Größe</th>
                        <th>Lieferhinweis</th>
                        <th>Bearbeitet</th>
                        <th>Nachbestellung</th>
                        <th>Aktion</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach (
                        $selectedOrder["items"]
                        as $index => $item
                    ): ?>
                        <tr>
                            <td data-label="Artikel"><?php echo escape(
                                $item["product_name"],
                            ); ?></td>
                            <td data-label="Größe"><?php echo $item["size"] !==
                            ""
                                ? escape($item["size"])
                                : "-"; ?></td>
                            <td data-label="Lieferhinweis"><?php echo $item[
                                "availability_label"
                            ] !== ""
                                ? escape($item["availability_label"])
                                : "-"; ?></td>
                            <td data-label="Bearbeitet">
                                <span class="status <?php echo !empty(
                                    $item["is_processed"]
                                )
                                    ? "status-processed"
                                    : "status-open"; ?>">
                                    <?php echo !empty($item["is_processed"])
                                        ? "Ja"
                                        : "Nein"; ?>
                                </span>
                            </td>
                            <td data-label="Nachbestellung">
                                <?php
                                $backorderStatus = (string) ($item["backorder_status"] ?? "");
                                if ($backorderStatus !== ""): ?>
                                    <span class="status <?php echo escape(
                                        getBackorderStatusClass($backorderStatus),
                                    ); ?>"><?php echo escape(
    getBackorderStatusLabel($backorderStatus),
); ?></span>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td data-label="Aktionen">
                                <?php if (
                                    $selectedOrder["status"] !== "cancelled" &&
                                    $selectedOrder["confirmation_status"] !==
                                        "pending" &&
                                    $selectedOrder["confirmation_status"] !==
                                        "expired"
                                ): ?>
                                    <form method="POST" class="inline-form">
                                        <?php echo csrfField(); ?>
                                        <input type="hidden" name="order_id" value="<?php echo escape(
                                            $selectedOrder["id"],
                                        ); ?>">
                                        <input type="hidden" name="item_index" value="<?php echo (int) $index; ?>">
                                        <button type="submit" name="toggle_item_processed" class="btn btn-small">
                                            <?php echo !empty(
                                                $item["is_processed"]
                                            )
                                                ? "Als offen markieren"
                                                : "Als bearbeitet markieren"; ?>
                                        </button>
                                    </form>
                                    <?php
                                    $canToggleBackorder =
                                        $backorderStatus === "" ||
                                        $backorderStatus === "to_be_backordered";
                                    if ($canToggleBackorder): ?>
                                    <form method="POST" class="inline-form">
                                        <?php echo csrfField(); ?>
                                        <input type="hidden" name="order_id" value="<?php echo escape(
                                            $selectedOrder["id"],
                                        ); ?>">
                                        <input type="hidden" name="item_index" value="<?php echo (int) $index; ?>">
                                        <button type="submit" name="toggle_item_backorder" class="btn btn-small btn-secondary">
                                            <?php echo $backorderStatus === "to_be_backordered"
                                                ? "Nachbestellung aufheben"
                                                : "Als Nachbestellung markieren"; ?>
                                        </button>
                                    </form>
                                    <?php endif; ?>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php if ($selectedOrder["status"] !== "cancelled"): ?>
            <h4>Bestellung stornieren</h4>
            <form method="POST" onsubmit="return confirm('Bestellung wirklich stornieren?');">
                <?php echo csrfField(); ?>
                <input type="hidden" name="order_id" value="<?php echo escape(
                    $selectedOrder["id"],
                ); ?>">
                <div class="form-group">
                    <label for="cancellation_reason">Stornogrund</label>
                    <textarea id="cancellation_reason" name="cancellation_reason" rows="3" placeholder="Optionaler Grund"></textarea>
                </div>
                <button type="submit" name="cancel_order" class="btn">Bestellung stornieren</button>
            </form>
        <?php endif; ?>
    </div>
<?php endif; ?>

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