<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes. All rights reserved.
 * See COPYING.txt for license details.
 */

declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\HyvaCsp;
use Hyva\Theme\ViewModel\ProductStockItem;
use Magento\Catalog\Block\Product\View;
use Magento\Catalog\Model\Product;
use Magento\Framework\Escaper;

// phpcs:disable Generic.WhiteSpace.ScopeIndent.Incorrect

/** @var View $block */
/** @var Escaper $escaper */
/** @var HyvaCsp $hyvaCsp */
/** @var ViewModelRegistry $viewModels */

/** @var Product $product */
$product = $block->getProduct();

/** @var ProductStockItem $stockItemViewModel */
$stockItemViewModel = $viewModels->require(ProductStockItem::class);
$minSalesQty = $stockItemViewModel->getMinSaleQty($product);
$maxSalesQty = $stockItemViewModel->getMaxSaleQty($product);
$defaultQty = $block->getProductDefaultQty() * 1;

$step = $stockItemViewModel->getQtyIncrements($product)
    ? $stockItemViewModel->getQtyIncrements($product)
    : null;

/**
 * sets minimum and maximum values taking into account the values set in the admin,
 * but taking into account the value of Qty Increments
 */
if ($step) {
    $minSalesQty = ceil($minSalesQty / $step) * $step;
    $maxSalesQty = floor($maxSalesQty / $step) * $step;
    $defaultQty = ceil($defaultQty / $step) * $step;
}

$maxSalesQtyLength = ($maxSalesQty ? strlen((string) $maxSalesQty) : 4)
    + (/* add one if decimal for separator */ (int) $stockItemViewModel->isQtyDecimal($product));


?>
<?php if ($block->shouldRenderQuantity()): ?>
    <script>
        function initQtyField() {

            function findPathParam(key) {
                // get all path pairs after BASE_URL/front_name/action_path/action
                const baseUrl = (BASE_URL.substring(0, 2) === '//' ? 'http:' : '') + BASE_URL;
                const baseUrlParts = (new URL(baseUrl)).pathname.replace(/\/$/, '').split('/');
                const pathParts = window.location.pathname.split('/').slice(baseUrlParts.length + 3);
                for (let i = 0; i < pathParts.length; i += 2) {
                    if (pathParts[i] === key && pathParts.length > i) {
                        return pathParts[i + 1];
                    }
                }
            }

            return {
                qty: <?= /** @noEscape */ $defaultQty ?>,
                itemId: (new URLSearchParams(window.location.search)).get('id') || findPathParam('id'),
                productId: '<?= (int)$product->getId() ?>',
                init() {
                    this.$dispatch('update-qty-<?= (int)$product->getId() ?>', this.qty);
                },
                <?php /* populate the qty when editing a product from the cart */ ?>
                onGetCartData() {
                    const data = this.$event.detail.data;
                    const cart = data && data.data && data.data.cart;
                    if (this.itemId && cart && cart.items) {
                        const cartItem = cart.items.find((item) => {
                            return item.item_id === this.itemId && item.product_id === this.productId;
                        });
                        if (cartItem && cartItem.qty) {
                            this.qty = cartItem.qty;
                            this.$dispatch('update-qty-' + this.productId, this.qty);
                        }
                    }
                },
                onInput() {
                    this.qty = hyva.safeParseNumber(this.$event.target.value);
                    this.$dispatch('update-qty-<?= (int)$product->getId() ?>', this.qty);
                }
            };
        }
        window.addEventListener('alpine:init', () => Alpine.data('initQtyField', initQtyField), {once: true})
    </script>
    <?php $hyvaCsp->registerInlineScript() ?>

    <?php if ($product->isSaleable()): ?>
        <label
            for="qty[<?= (int)$product->getId() ?>]"
            class="sr-only"
        ><?= $escaper->escapeHtml(__('Quantity')) ?></label>

        <input
            id="qty[<?= (int)$product->getId() ?>]"
            name="qty"
            form="product_addtocart_form"
            value="<?= $block->getProductDefaultQty() * 1 ?>"
            class="form-input px-2 py-2 w-20 text-center invalid:ring-2 invalid:ring-red-500"
            <?php if ($stockItemViewModel->isQtyDecimal($product)): ?>
                type="text"
                pattern="[0-9]+(\.[0-9]{1,<?= /** @noEscape */ $maxSalesQtyLength ?>})?"
                inputmode="decimal"
            <?php else: ?>
                type="number"
                pattern="[0-9]{0,<?= /** @noEscape */ $maxSalesQtyLength ?>}"
                inputmode="numeric"
                <?php if ($minSalesQty): ?>
                    min="<?= /** @noEscape */ $minSalesQty ?>"
                <?php endif; ?>
                <?php if ($maxSalesQty): ?>
                    max="<?= /** @noEscape */ $maxSalesQty ?>"
                <?php endif; ?>
                <?php if ($step): ?>
                    step="<?= /** @noEscape */ $step ?>"
                <?php endif; ?>
            <?php endif; ?>
            x-data="initQtyField"
            :value="qty"
            @private-content-loaded.window="onGetCartData"
            @input="onInput"
        >
    <?php endif; ?>
<?php endif; ?>
