<?php
/** @var \Magento\Catalog\Block\Product\View $block */
$themeSettingConfig = $this->helper('MGS\ThemeSettings\Helper\Config');
$isStickyCartEnable = $themeSettingConfig->getStoreConfig('themesettings/product_details/product_sticky_cart_enable');
$_product = $block->getProduct();
$sku = $_product->getSku();
$productId = $_product->getId();
$productType = $_product->getTypeId();
$productImage = $_product->getMediaGalleryImages()->getFirstItem()->getUrl();
$productAttribute = $_product->getData();
$optionsProduct = $_product->getOptions();
$optionProducts = [];

function generateCombinations($data, $index = 0, $prefix = [], &$results = [])
{
    if ($index === count($data)) {
        $id = [];
        $value = [];

        foreach ($prefix as $item) {
            $id[] = "@{$item['valueType']}-{$item['typeId']}*{$item['id']}";
            $value[] = $item['value'];
        }

        $results[] = [
            'id'  => implode('', $id),
            'sku' => implode(' / ', $value)
        ];

        return;
    }
    foreach ($data[$index]['items'] as $item) {
        $currentPrefix = array_merge($prefix, [
            [
                'typeId'    => $data[$index]['id'],
                'valueType' => $data[$index]['value'],
                'id'        => $item['id'],
                'value'     => $item['value']
            ]
        ]);

        generateCombinations($data, $index + 1, $currentPrefix, $results);
    }
}

if ($productType == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
    $configurableProduct = $_product->getTypeInstance();
    $childProducts = $configurableProduct->getUsedProducts($_product);
    $configurableAttributes = $configurableProduct->getConfigurableAttributes($_product);
    $attributes = [];
    foreach ($configurableAttributes as $attribute) {
        $attributeId = $attribute->getProductAttribute()->getId();
        $attributeCode = $attribute->getProductAttribute()->getAttributeCode();
        $attributeLabel = $attribute->getProductAttribute()->getFrontend()->getLabel();

        $attributes[] = [
            'attribute_id'    => $attributeId,
            'attribute_code'  => $attributeCode,
            'attribute_label' => $attributeLabel,
        ];
    }
    foreach ($childProducts as $childProduct) {
        $value = '';
        foreach ($attributes as $attribute) {
            $value .= '@' . $attribute['attribute_code'] . '-' . $attribute['attribute_id'] . '*' .
                $childProduct[$attribute['attribute_code']];
        }

        $optionProducts[] = [
            'id'  => $value,
            'sku' => str_replace($sku . '-', '', $childProduct->getSku()),
        ];
    }
}
if ($productType == \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE && !empty($optionsProduct)) {
    $aRawOptions = [];
    foreach ($optionsProduct as $option) {
        $items = [];
        $values = $option->getValues();
        if ($values) {
            foreach ($values as $value) {
                $items[] = [
                    'id'    => (int)$value->getId(),
                    'value' => $value->getTitle()
                ];

            }
        }
        $aRawOptions[] = [
            'id'    => (int)$option->getId(),
            'value' => $option->getTitle(),
            'items' => $items
        ];
    }
    if (!empty($aRawOptions)) {
        $results = [];
        generateCombinations($aRawOptions, 0, [], $results);
        $optionProducts = $results;
    }

}
$priceRender = $block->getLayout()->getBlock('product.price.render.default');
if (!$priceRender) {
    $priceRender = $block->getLayout()
        ->createBlock(\Magento\Framework\Pricing\Render::class, 'product.price.render.default');
}
$buttonTitle = __('Add to Cart');
$priceHtml = $priceRender->render(
    \Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE,
    $_product,
    [
        'display_minimal_price' => false,
        'zone'                  => \Magento\Framework\Pricing\Render::ZONE_ITEM_VIEW,
        'list_category_page'    => true
    ]
);
$callHelper = $this->helper('MGS\Callforprice\Helper\Data');
?>
<?php if (!empty($isStickyCartEnable) && $_product->isSaleable()) : ?>
    <div
        id="sticky-cart-content"
        data-sticky-addtocart=""
         class="cl-sticky-atc">
        <div class="cl-sticky-atc__wrap">
            <div class="cl-sticky-atc__info">
                <div data-sticky-img="" class="info-img">
                    <img class="cl-lz--fadeIn" src="<?= $productImage ?>">
                </div>
                <div class="cl-sticky-atc__infos">
                    <div class="cl-sticky-atc__title"><?= $_product->getName(); ?></div>
                    <div data-sticky-price="" class="cl-sticky-atc__price">
                        <?php if (!$callHelper->getConfig('mgscallforprice/general/isenabled')) : ?>
                            <?= /* @noEscape */
                            $priceHtml ?>
                        <?php endif; ?>
                    </div>
                    <input type="hidden" id="sticky-cart-product-id" value="<?= $productId ?>">
                    <input type="hidden" id="sticky-cart-is-option" value="<?= !empty($optionsProduct) ?>">
                </div>
                <div data-sticky-v-title="" class="cl-sticky-atc__v-title">
                    <?php if (!empty($optionProducts)): ?>
                        <select name="product-att" id="sticky-cart-select">
                            <?php foreach ($optionProducts as $product): ?>
                                <option value="<?= $product['id'] ?>"><?= str_replace('-', ' / ',
                                        $product['sku']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    <?php endif; ?>
                </div>
            </div>
            <div class="cl-sticky-atc__btns">
            <div class="box-tocart">
                <?php if ($block->shouldRenderQuantity()): ?>
                    <div class="field qty">
                        <div class="control">
                            <span class="edit-qty minus" onclick="arrowMinusQty('qty')">-</span>
                            <input type="number"
                                name="qty"
                                id="sticky-cart-qty"
                                min="0"
                                value="<?= $block->getProductDefaultQty() * 1 ?>"
                                title="<?= $block->escapeHtmlAttr(__('Qty')) ?>"
                                class="input-text qty"
                                data-validate="<?= $block->escapeHtml(json_encode($block->getQuantityValidators())) ?>"
                            />
                            <span class="edit-qty plus" onclick="arrowPlusQty('qty')">+</span>
                        </div>
                    </div>
                <?php endif; ?>

                <div class="actions">
                    <button type="submit" title="<?= $block->escapeHtmlAttr($buttonTitle) ?>"
                            class="action primary tocart" id="sticky-cart-addtocart-button" disabled>
                        <span><?= $block->escapeHtml($buttonTitle) ?></span>
                    </button>
                </div>
                <?= $block->getChildHtml('', true) ?>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>
<script type="text/javascript">
    function addToCartByAttribute(productId, qty, type, data) {
        require(['jquery', 'mage/url', 'Magento_Customer/js/customer-data'], function ($, urlBuilder, customerData) {
            let formKey = $.cookie('form_key')
            let addToCartUrl = urlBuilder.build('checkout/cart/add');
            let formData = {};
            switch (type) {
                case 'simple':
                    formData = {
                        product: parseInt(productId),
                        qty: parseInt(qty),
                        form_key: formKey
                    };
                    break;
                case 'configurations':
                    formData = {
                        product: parseInt(productId),
                        qty: parseInt(qty),
                        super_attribute: data,
                        form_key: formKey
                    };
                    break;
                case 'options':
                    formData = {
                        product: parseInt(productId),
                        qty: parseInt(qty),
                        options: data,
                        form_key: formKey
                    };
            }

            $.ajax({
                url: addToCartUrl,
                type: 'POST',
                data: formData,
                beforeSend: function (xhr, options) {
                    $('#mgs-ajax-loading').show();
                },
                success: function (response) {
                    $('#mgs-ajax-loading').hide();
                    if (response.backUrl) {
                        window.location.href = response.backUrl;
                    } else {
                        customerData.reload(['cart'], true);
                        // setTimeout(()=>{
                        //     window.location.reload();
                        // },6000)
                    }
                },
                error: function () {
                    $('#mgs-ajax-loading').hide();
                    console.log('Could not add the product to the cart.');
                }
            });
        });
    }

    function showLoading() {
        require(['jquery'], function ($) {
            $('body').trigger('processStart');
        })
    }

    function hideLoading() {
        require(['jquery'], function ($) {
            $('body').trigger('processStop');
        })
    }

    require(['jquery'], function ($) {
        $(document).ready(function () {
            $('#sticky-cart-addtocart-button').on('click', function () {
                let productId = $('#sticky-cart-product-id').val();
                let optionValue = $('#sticky-cart-select').val();
                let qty = $('#sticky-cart-qty').val();
                let isProductOption = $('#sticky-cart-is-option').val();

                if (isProductOption) {
                    if (productId && optionValue && qty) {
                        const regex = /(\d+\*\d+)/g;
                        const matches = optionValue.match(regex);

                        const option = matches.map(pair => pair.split('*'))
                            .reduce((acc, [key, value]) => {
                                acc[parseInt(key)] = parseInt(value);
                                return acc;
                            }, {});
                        addToCartByAttribute(productId, qty, 'options', option);
                    }
                } else {
                    if (productId && optionValue && qty) {
                        const regex = /(\d+\*\d+)/g;
                        const matches = optionValue.match(regex);

                        const option = matches.map(pair => pair.split('*'))
                            .reduce((acc, [key, value]) => {
                                acc[parseInt(key)] = parseInt(value);
                                return acc;
                            }, {});
                        addToCartByAttribute(productId, qty, 'configurations', option);
                    } else {
                        if (productId && qty) {
                            addToCartByAttribute(productId, qty, 'simple', '');
                        }
                    }
                }
            });
        });
        $(window).on('scroll', function () {
            let scrollPosition = $(window).scrollTop();

            if (scrollPosition >= 400) {
                $('#sticky-cart-content').addClass('is-show');
            } else {
                $('#sticky-cart-content').removeClass('is-show');
            }
        });

    });
</script>
