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

$pageTitle = "Warenkorb";

if (
    $_SERVER['REQUEST_METHOD'] === "POST" &&
    isset($_POST['remove_product_id'])
) {
    if (validateCsrfToken($_POST['csrf_token'] ?? "")) {
        removeCartItem(
            (int) ($_POST['remove_product_id'] ?? 0),
            (string) ($_POST['remove_size'] ?? ""),
        );
    } else {
        setFlashMessage(
            "cart_notice",
            "error",
            "Ungültiges Token. Bitte versuchen Sie es erneut.",
        );
        header("Location: cart.php");
        exit();
    }
}

$cartItems = getCartItemsDetailed();
$cartNotice = consumeFlashMessage("cart_notice");

include __DIR__ . "/includes/header.php";
?>

<h2>Warenkorb</h2>

<?php if ($cartNotice !== null): ?>
    <div class="alert alert-<?php echo escape($cartNotice["type"]); ?>">
        <?php echo escape($cartNotice["message"]); ?>
    </div>
<?php endif; ?>

<?php if (empty($cartItems)): ?>
    <div class="alert alert-info">
        <p>Ihr Warenkorb ist leer.</p>
        <a href="index.php" class="btn">Weiter zur Produktübersicht</a>
    </div>
<?php else: ?>
    <?php foreach ($cartItems as $cartItem): ?>
        <div class="cart-item">
            <div class="cart-item-info">
                <h3><?php echo escape($cartItem["product"]["name"]); ?></h3>
                <?php if ($cartItem["size"] !== ""): ?>
                    <p><strong>Größe:</strong> <?php echo escape(
                        $cartItem["size"],
                    ); ?></p>
                <?php endif; ?>
                <?php if ($cartItem["availability_label"] !== ""): ?>
                    <p><strong>Lieferhinweis:</strong> <?php echo escape(
                        $cartItem["availability_label"],
                    ); ?></p>
                <?php endif; ?>
            </div>
            <div class="cart-item-actions">
                <form method="POST">
                    <?php echo csrfField(); ?>
                    <input type="hidden" name="remove_product_id" value="<?php echo (int) $cartItem[
                        "product"
                    ]["id"]; ?>">
                    <input type="hidden" name="remove_size" value="<?php echo escape(
                        $cartItem["size"],
                    ); ?>">
                    <button type="submit" class="btn btn-secondary btn-small">Entfernen</button>
                </form>
            </div>
        </div>
    <?php endforeach; ?>

    <div class="cart-actions">
        <div class="cart-buttons">
            <a href="index.php" class="btn btn-secondary">Weiter auswählen</a>
            <a href="checkout.php" class="btn">Zur Bestellung</a>
        </div>
    </div>
<?php endif; ?>

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