<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes 2020-present. All rights reserved.
 * This product is licensed per Magento install
 * See https://hyva.io/license
 */

declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
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 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() ?>',
                <?php /* populate the qty when editing a product from the cart */ ?>
                onGetCartData: function onGetCartData(data, $dispatch) {
                    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;
                            $dispatch('update-qty-' + this.productId, this.qty);
                        }
                    }
                }
            };
        }
    </script>
    <div x-data="initQtyField()"
         x-init="$dispatch('update-qty-<?= (int)$product->getId() ?>', qty)"
   class="flex items-center  overflow-hidden justify-between" >
        <?php if ($product->isSaleable()): ?>

                <button type="button" @click="qty = Math.max(1, qty - 1)"
                        class="sm:w-20 w-44 rounded-l-md bg-gray-100 border-b border-l border-t w-24 h-12 bg-gray-100 hover:bg-gray-200 text-black text-lg">
                    − </button>

                <input name="qty"
                       @private-content-loaded.window="onGetCartData($event.detail, $dispatch)"
                       id="qty[<?= (int)$product->getId() ?>]"
                       form="product_addtocart_form"
                    <?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; ?>
                       :value="qty"
                       value="<?= $block->getProductDefaultQty() * 1 ?>"
                       class="form-input h-12 invalid:ring-2 invalid:ring-red-500 lg:w-full px-2 py-2 rounded-none text-center w-10"
                       x-model.number="qty"
                       @input="$dispatch('update-qty-<?= (int)$product->getId() ?>', qty)"
                />


                <button type="button" @click="qty++"
                        class="sm:w-20 w-44 border-b border-r border-t rounded-r-md w-24 h-12 bg-gray-100 hover:bg-gray-200 text-black text-lg">
                    + </button>
        <?php endif; ?>
    </div>
<?php endif; ?>





<!--<div x-data="initQtyField()" x-init="$dispatch('update-qty-3', qty)"
     class="flex items-center border rounded overflow-hidden justify-between">
    <button type="button" @click="qty = Math.max(1, qty - 1)" class="w-8 h-11 bg-gray-100 hover:bg-gray-200 text-black text-lg">
        − </button>
    <input name="qty" @private-content-loaded.window="onGetCartData($event.detail, $dispatch)" id="qty[3]" form="product_addtocart_form" type="number" pattern="[0-9]{0,5}" inputmode="numeric" min="1" max="10000" :value="qty" value="1" class="form-input px-2 py-2 w-20 text-center invalid:ring-2 invalid:ring-red-500" x-model.number="qty" @input="$dispatch('update-qty-3', qty)" style="visibility: visible;">
    <button type="button" @click="qty++" class="w-8 h-11 bg-gray-100 hover:bg-gray-200 text-black text-lg">
        + </button>
</div>-->
