<?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\HeroiconsOutline;

use Hyva\Theme\ViewModel\ProductPage;
use Hyva\Theme\ViewModel\StoreConfig;

use Magento\Framework\Escaper;
use Magento\Framework\View\Element\Template;
use Hyva\BssAjaxCart\ViewModels\Helper as ModuleViewModel;

/** @var Template $block */
/** @var Escaper $escaper */
/** @var ViewModelRegistry $viewModels */


/** @var HeroiconsOutline $heroicons */
$heroicons = $viewModels->require(HeroiconsOutline::class);
/** @var ProductPage $productViewModel */
$productViewModel = $viewModels->require(ProductPage::class);
/** @var StoreConfig $storeConfig */
$storeConfig = $viewModels->require(StoreConfig::class);
$moduleViewModel = $viewModels->require(ModuleViewModel::class);
$helperAjaxCart = $moduleViewModel->getHelper();
/** ✅ Get current product safely */
$product = $productViewModel->getProduct();
$request = $block->getRequest();

$clickForPrice = $product->getData('click_for_price');
$callForPrice = $product->getData('call_for_price');
$revealPrice = $request->getParam('reveal_price');
$storePhone = $storeConfig->getStoreConfig('general/store_information/phone');
?>

<?php if (!$clickForPrice && !$callForPrice || $revealPrice): ?>
    <!-- Default Add to Cart Button -->
    <?php if ($helperAjaxCart->isEnabled() && $helperAjaxCart->isEnabledProductView() && $block->getRequest()->getFullActionName() !== 'checkout_cart_configure'): ?>

        <?php
        $uniqueId = "_" . uniqid();
        $currentProduct = $block->getParentBlock()->getProduct();
        $postData = $moduleViewModel->getPostDataJson($block, $currentProduct);
        ?>
        <script>
            'use strict';

            function initAjaxCart<?= $escaper->escapeHtmlAttr($uniqueId) ?>() {
                return {
                    isLoading: false,
                    postData: JSON.parse(<?= /** @noEscape */ $moduleViewModel->serializeJson($postData) ?>),
                    flyToCart: <?= $moduleViewModel->getConfigFlyToCart()?>,
                    action: "<?= $escaper->escapeJs($block->getUrl('ajaxcart')) ?>",
                    typeProduct: "<?= $escaper->escapeJs($currentProduct->getTypeId()) ?>",
                    getOffset(element) {
                        if (!element.getClientRects().length) {
                            return { top: 0, left: 0 };
                        }
                        var rect = element.getBoundingClientRect();
                        var win = element.ownerDocument.defaultView;
                        return ({
                            top: rect.top + win.pageYOffset,
                            left: rect.left + win.pageXOffset
                        });
                    },
                    ajaxFlyToCart(element) {
                        var speed = this.flyToCart.speed,
                            transparent = this.flyToCart.transparent,
                            miniCart = document.getElementById('menu-cart-icon'),
                            imgElement = element.querySelector('#gallery img');

                        var imgclone = imgElement.cloneNode();
                        imgclone.style.top = this.getOffset(imgElement).top + 'px';
                        imgclone.style.left = this.getOffset(imgElement).left + 'px';
                        imgclone.style.height = imgElement.offsetHeight + 'px';
                        imgclone.style.width  = imgElement.offsetWidth + 'px';
                        imgclone.className = 'clone-image';
                        document.body.appendChild(imgclone);
                        var translateX = this.getOffset(miniCart).left - this.getOffset(imgclone).left;
                        var translateY = this.getOffset(miniCart).top - this.getOffset(imgclone).top;

                        imgclone.style.height = "30px";
                        imgclone.style.width = "30px";
                        imgclone.style.transform = `translate(${translateX}px,${translateY}px)`;
                        imgclone.style.transition = `all ${speed}s`;
                        if (transparent) {
                            imgclone.style.opacity = "0.5";
                        }

                        setTimeout(function () {
                            imgclone.remove();
                        }, (parseInt(speed) + 0.5)*1000);

                    },
                    addToCartSubmit() {
                        var self = this;
                        const $productInfoContainer = this.$el.closest('.product-info-main');
                        this.isLoading = true;

                        if (this.flyToCart.enable == 1) {
                            setTimeout(function () {
                                self.isLoading = false;
                                self.ajaxFlyToCart($productInfoContainer);
                            }, 1000);
                        }

                        let postData = { ...this.postData.data };
                        const form = $productInfoContainer.querySelector('form#product_addtocart_form');

                        if (form) {
                            const formData = new FormData(form);
                            for (let field of formData.entries()) {
                                postData[field[0]] = field[1];
                            }
                        }

                        if (!postData?.form_key) {
                            postData.form_key = hyva.getFormKey();
                        }
                        postData.id = postData.product;
                        var requestConfigs = {
                            method: "POST",
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                                'X-Requested-With': 'XMLHttpRequest'
                            },
                            mode: 'cors',
                            credentials: 'include',
                            dataType: 'json',
                            body: new URLSearchParams(postData)
                        };
                        const addToCartRequesting = fetch(this.action, requestConfigs);
                        addToCartRequesting
                            .then(response => {
                                if (response.redirected) {
                                    window.location.href = response.url;
                                } else if (response.ok) {
                                    return response.json();
                                }
                            }).then(response => {
                            if (response.backUrl) {
                                window.location.href = response.backUrl;
                            } else if (response?.messages) {
                                response.messages.map((msg) => {
                                    if (msg.type !== 'error') {
                                        return null;
                                    }
                                    window.dispatchMessages([
                                        {
                                            type: msg.type,
                                            text: msg.text
                                        }
                                    ], 3000);
                                });
                            } else if (response.popup) {
                                if (window.parent.document.getElementById('popup-content')) {
                                    var popupContent = window.parent.document.getElementById('popup-content');
                                } else {
                                    var popupContent = document.getElementById("popup-content");
                                }

                                popupContent.textContent ="";
                                popupContent.insertAdjacentHTML("beforeend", response.popup);
                                let scripts = popupContent.getElementsByTagName("script");

                                while (scripts.length) {
                                    const script = scripts[0];
                                    script.parentNode.removeChild(script);
                                    const newScript = window.parent.document.createElement("script");
                                    newScript.setAttribute('type', 'text/javascript');

                                    const scriptId = script.getAttribute('id');
                                    if (scriptId) {
                                        const existedSript = window.parent.document.getElementById(scriptId);
                                        if (existedSript) {
                                            continue;
                                        }
                                        newScript.setAttribute('id', scriptId);
                                    }
                                    if (script.src) {
                                        newScript.src = script.src;
                                    } else if (script.textContent) {
                                        newScript.textContent = script.textContent;
                                    } else if (script.innerText) {
                                        newScript.innerText = script.innerText;
                                    }
                                    window.parent.document.body.appendChild(newScript);
                                }
                                window.parent.postMessage('ajax-cart-message','*');

                                this.isLoading = false;
                                window.dispatchEvent(new CustomEvent("ajax-cart-popup"));
                            }
                            window.dispatchEvent(new CustomEvent("reload-customer-section-data"));
                        }).catch(err => {
                            if (this.typeProduct != 'grouped') {
                                window.dispatchMessages([
                                    {
                                        type: 'error',
                                        text: err
                                    }
                                ], 3000);
                            } else {
                                window.dispatchEvent(new CustomEvent("reload-customer-section-data"));
                            }
                        });
                        return false;
                    },
                    eventListeners: {
                        ['@submit-form-addtocart.window']() {
                            this.addToCartSubmit();
                        }
                    }
                }
            }
            window.onload = function() {
                document.getElementById("product_addtocart_form").onsubmit = function(e) {
                    e.preventDefault();
                    window.dispatchEvent(new CustomEvent("submit-form-addtocart", {}));
                };
            };

        </script>

        <button type="submit"
                x-data="initAjaxCart<?= $escaper->escapeHtmlAttr($uniqueId) ?>()"
                x-spread="eventListeners"
                x-bind="eventListeners"
                form="product_addtocart_form"
                title="<?= $escaper->escapeHtmlAttr(__('Add to Basket')) ?>"
                class="px-2 md:px-4 btn bg-primary-darker w-fullflex gap-2 h-12 items-center justify-center row-full-width-inner w-full"
                id="product-addtocart-button"
                data-addto="cart"
        >
            <div class="flex flex-row justify-center items-center w-full h-full fixed select-none"
                 style="z-index: 9999; left: 50%;top: 50%;transform: translateX(-50%) translateY(-50%);background: rgba(255,255,255,0.7);"
                 x-show="isLoading"
                 x-transition:enter="ease-out duration-200"
                 x-transition:enter-start="opacity-0"
                 x-transition:enter-end="opacity-100"
                 x-transition:leave="ease-in duration-200"
                 x-transition:leave-start="opacity-100"
                 x-transition:leave-end="opacity-0">
                <svg class="animate-spin h-10 w-10 text-primary" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10"
                            stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor"
                          d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/>
                </svg>
            </div>
            <svg class="border-current hidden sm:block" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"  width="24" height="24" role="img">
                <path stroke-linecap="round" stroke-linejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"></path>
                </svg>
            <span class="font-bold lg:block sm:block sm:text-xl text-sm">
            <?= $block->getData('is_cart_configure')
                ? $escaper->escapeHtml(__('Update item'))
                : $escaper->escapeHtml(__('Add to Basket')) ?>
        </span>
        </button>

        <?= $block->getChildHtml('', true) ?>
    <?php endif; ?>

    <?php if ($block->getRequest()->getFullActionName() === 'checkout_cart_configure' && !$clickForPrice && !$callForPrice): ?>
        <!-- Fallback button for cart configure page when AJAX cart is disabled -->
        <button type="submit"
                form="product_addtocart_form"
                title="<?= $escaper->escapeHtmlAttr(__('Update item')) ?>"
                class="btn bg-primary-darker flex gap-2 h-12 items-center justify-center row-full-width-inner w-full"
                id="product-addtocart-button"
                data-addto="cart"
        >
            <?= $heroicons->shoppingCartHtml('hidden lg:block border-current'); ?>
            <span class="font-bold lg:block sm:block sm:text-xl text-sm">
                <?= $escaper->escapeHtml(__('Update item')) ?>
            </span>
        </button>
        <?= $block->getChildHtml('', true) ?>
    <?php endif; ?>
<?php elseif ($clickForPrice): ?>
    <!-- Click for Price Button - Redirects to Form -->
    <a
        title="<?= $escaper->escapeHtmlAttr(__('Click For Price')) ?>"
        href="<?= $escaper->escapeUrl($block->getUrl('callprice/form/index', ['id' => $product->getId()])) ?>"
        class="btn bg-primary-darker flex gap-2 h-12 items-center justify-center row-full-width-inner w-full"
        id="product-addtocart-button"
        data-addto="cart"
    >
        <svg xmlns="http://www.w3.org/2000/svg" width="21" height="21" viewBox="0 0 21 21" fill="none">
            <path d="M10 6.71094C8.9 6.71094 7.95833 7.1026 7.175 7.88594C6.39167 8.66927 6 9.61094 6 10.7109C6 11.4609 6.18767 12.1526 6.563 12.7859C6.93833 13.4193 7.459 13.9109 8.125 14.2609C8.39167 14.3943 8.57933 14.5899 8.688 14.8479C8.79667 15.1059 8.79233 15.3686 8.675 15.6359C8.55833 15.8693 8.38333 16.0443 8.15 16.1609C7.91667 16.2776 7.68333 16.2776 7.45 16.1609C6.4 15.6609 5.56267 14.9193 4.938 13.9359C4.31333 12.9526 4.00067 11.8776 4 10.7109C4 9.04427 4.58333 7.6276 5.75 6.46094C6.91667 5.29427 8.33333 4.71094 10 4.71094C11.1833 4.71094 12.271 5.0236 13.263 5.64894C14.255 6.27427 14.9923 7.12827 15.475 8.21094C15.575 8.44427 15.571 8.6776 15.463 8.91094C15.355 9.14427 15.184 9.31094 14.95 9.41094C14.6833 9.5276 14.4167 9.5276 14.15 9.41094C13.8833 9.29427 13.6833 9.1026 13.55 8.83594C13.2 8.16927 12.7083 7.6486 12.075 7.27394C11.4417 6.89927 10.75 6.7116 10 6.71094ZM10 2.71094C7.76667 2.71094 5.875 3.48594 4.325 5.03594C2.775 6.58594 2 8.4776 2 10.7109C2 12.8109 2.69167 14.6109 4.075 16.1109C5.45833 17.6109 7.19167 18.4609 9.275 18.6609C9.55833 18.6943 9.804 18.8193 10.012 19.0359C10.22 19.2526 10.316 19.5026 10.3 19.7859C10.284 20.0693 10.1797 20.3026 9.987 20.4859C9.79433 20.6693 9.557 20.7526 9.275 20.7359C7.975 20.6526 6.76233 20.3276 5.637 19.7609C4.51167 19.1943 3.52833 18.4566 2.687 17.5479C1.84567 16.6393 1.18733 15.5976 0.712001 14.4229C0.236668 13.2483 -0.000665266 12.0109 1.40056e-06 10.7109C1.40056e-06 9.3276 0.262668 8.0276 0.788001 6.81094C1.31333 5.59427 2.02567 4.53594 2.925 3.63594C3.82434 2.73594 4.88267 2.0236 6.1 1.49894C7.31734 0.974271 8.61733 0.711604 10 0.710938C12.6167 0.710938 14.896 1.6026 16.838 3.38594C18.78 5.16927 19.8423 7.36927 20.025 9.98594C20.0583 10.2526 19.9793 10.4819 19.788 10.6739C19.5967 10.8659 19.359 10.9699 19.075 10.9859C18.791 11.0019 18.537 10.9103 18.313 10.7109C18.089 10.5116 17.9597 10.2699 17.925 9.98594C17.675 7.98594 16.8043 6.2736 15.313 4.84894C13.8217 3.42427 12.0507 2.7116 10 2.71094ZM17.55 20.2109L14.25 16.9359L13.5 19.2109C13.4167 19.4443 13.2583 19.5569 13.025 19.5489C12.7917 19.5409 12.6333 19.4199 12.55 19.1859L10.275 11.6109C10.2083 11.4276 10.25 11.2609 10.4 11.1109C10.55 10.9609 10.7167 10.9193 10.9 10.9859L18.475 13.2609C18.7083 13.3443 18.8293 13.5026 18.838 13.7359C18.8467 13.9693 18.734 14.1276 18.5 14.2109L16.225 14.9609L19.525 18.2609C19.8083 18.5443 19.95 18.8693 19.95 19.2359C19.95 19.6026 19.8083 19.9276 19.525 20.2109C19.2417 20.4943 18.9127 20.6359 18.538 20.6359C18.1633 20.6359 17.834 20.4943 17.55 20.2109Z" fill="white"/>
        </svg>
        <span class="font-bold lg:block sm:block sm:text-xl text-sm">
            <?= $block->getData('is_cart_configure')
                ? $escaper->escapeHtml(__('Update item'))
                : $escaper->escapeHtml(__('Click For Price')) ?>
        </span>
    </a>

<?php elseif ($callForPrice): ?>
    <!-- Call for Price Button with Popup -->
    <div x-data="{ showPhonePopup: false }" class="w-full">
        <button type="button"
                id="product-addtocart-button"
                class="w-full h-12 row-full-width-inner flex items-center justify-center gap-2 btn bg-primary-darker"
                title="<?= $escaper->escapeHtmlAttr(__('Call for Price')) ?>"
                @click="showPhonePopup = true">
            <?= $heroicons->phoneHtml('border-current'); ?>
            <span class="ml-2"><?= __('Call for Price') ?></span>
        </button>

        <!-- Phone Number Popup -->
        <div x-show="showPhonePopup"
             class="fixed inset-0 z-50 flex items-center justify-center"
             x-cloak>
            <div class="absolute inset-0 bg-black opacity-50" @click="showPhonePopup = false"></div>
            <div class="relative bg-white p-6 rounded-lg shadow-lg max-w-md mx-auto">
                <div class="absolute top-2 right-2 cursor-pointer" @click="showPhonePopup = false">
                    <?= $heroicons->xHtml('w-6 h-6'); ?>
                </div>
                <h3 class="text-lg font-bold mb-4"><?= __('Call Us for Pricing') ?></h3>
                <p class="mb-4"><?= __('Please call us at the number below for pricing information on this product:') ?></p>
                <div class="text-xl font-bold text-center mb-4">
                    <a href="tel:<?= $escaper->escapeHtmlAttr(preg_replace('/[^0-9+]/', '', $storePhone)) ?>" class="text-primary-darker hover:underline">
                        <?= $escaper->escapeHtml($storePhone) ?>
                    </a>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>
