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

$productId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$product = getProductById($productId);

if ($product === null) {
    header("Location: index.php");
    exit();
}

$pageTitle = $product["name"];
$sizes = getProductSizes($product);
$productCategoryIds = getProductCategoryIds($product);

if ($_SERVER['REQUEST_METHOD'] === "POST" && isset($_POST['add_to_cart'])) {
    // Validate CSRF token
    if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
        $error = "Ungültiges Token. Bitte versuchen Sie es erneut.";
    } else {
        $size = trim((string) ($_POST['size'] ?? ""));

        if (
            !empty($sizes) &&
            ($size === "" || !in_array($size, $sizes, true))
        ) {
            $error = "Bitte wählen Sie eine Größe aus.";
        } else {
            $result = addCartItem($product["id"], $size);
            if (!$result["success"]) {
                $error =
                    "Der Artikel konnte nicht in den Warenkorb gelegt werden.";
            } elseif ($result["status"] === "replaced") {
                setFlashMessage(
                    "cart_notice",
                    "success",
                    "Die Größe für diesen Artikel wurde im Warenkorb aktualisiert.",
                );
                header("Location: cart.php");
                exit();
            } elseif ($result["status"] === "unchanged") {
                setFlashMessage(
                    "cart_notice",
                    "info",
                    "Dieser Artikel ist bereits mit der gewählten Größe im Warenkorb.",
                );
                header("Location: cart.php");
                exit();
            } else {
                setFlashMessage(
                    "cart_notice",
                    "success",
                    "Der Artikel wurde zum Warenkorb hinzugefügt.",
                );
                header("Location: cart.php");
                exit();
            }
        }
    }
}

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

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

<div class="product-detail-grid">
    <div>
        <?php $imagePath = getUploadPath($product["image"] ?? ""); ?>
        <?php $imageUrl = getUploadUrl($product["image"] ?? ""); ?>
        <?php if (
            $imagePath !== null &&
            $imageUrl !== null &&
            file_exists($imagePath)
        ): ?>
            <img class="product-image" src="<?php echo escape(
                $imageUrl,
            ); ?>" alt="<?php echo escape($product["name"]); ?>">
        <?php else: ?>
            <img class="product-image" src="assets/no-image.jpg" alt="Kein Bild verfügbar">
        <?php endif; ?>
    </div>

    <div class="product-copy">
        <h1><?php echo escape($product["name"]); ?></h1>
        <?php if (!empty($productCategoryIds)): ?>
            <div class="product-category-list" aria-label="Kategorien">
                <?php foreach ($productCategoryIds as $productCategoryId): ?>
                    <?php $chipPalette = getCategoryChipPalette($productCategoryId); ?>
                    <span class="category-chip" style="background-color: <?php echo escape(
                        $chipPalette["background"],
                    ); ?>; border-color: <?php echo escape(
    $chipPalette["border"],
); ?>; color: <?php echo escape($chipPalette["text"]); ?>;">
                        <?php echo escape(getCategoryLabel($productCategoryId)); ?>
                    </span>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <div class="product-description-block">
            <h3>Beschreibung</h3>
            <p class="product-description"><?php echo nl2br(
                escape($product["description"]),
            ); ?></p>
        </div>

        <form method="POST" class="product-form">
            <?php echo csrfField(); ?>
            <?php if (!empty($sizes)): ?>
                <div class="form-group">
                    <label for="size">Größe *</label>
                    <select id="size" name="size" required onchange="updateAvailabilityNotice()">
                        <option value="">Bitte wählen</option>
                        <?php foreach ($sizes as $sizeOption): ?>
                            <?php $label = getAvailabilityLabel(
                                $product,
                                $sizeOption,
                            ); ?>
                            <option value="<?php echo escape(
                                $sizeOption,
                            ); ?>" data-label="<?php echo escape($label); ?>">
                                <?php echo escape($sizeOption); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div id="availabilityNotice" class="alert alert-warning is-hidden"></div>
            <?php endif; ?>

            <button type="submit" name="add_to_cart" class="btn btn-block">In den Warenkorb</button>
        </form>

        <?php if (!empty($sizes)): ?>
            <script>
                function updateAvailabilityNotice() {
                    const sizeSelect = document.getElementById('size');
                    const notice = document.getElementById('availabilityNotice');
                    const selectedOption = sizeSelect.options[sizeSelect.selectedIndex];
                    const text = selectedOption ? selectedOption.getAttribute('data-label') : '';

                    if (text) {
                        notice.textContent = text;
                        notice.classList.remove('is-hidden');
                    } else {
                        notice.textContent = '';
                        notice.classList.add('is-hidden');
                    }
                }
            </script>
        <?php endif; ?>

        <div class="mt-4">
            <a href="index.php" class="btn btn-secondary">Zurück zur Übersicht</a>
        </div>
    </div>
</div>

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