<?php
/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Mageplaza.com license that is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_QuickCart
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */
use Hyva\Theme\ViewModel\HeroiconsOutline;
use Magento\Catalog\Block\Product\ReviewRendererInterface;
use Magento\Framework\App\ActionInterface;
use Mageplaza\QuickCart\Block\AjaxCart\Popup;
use Mageplaza\QuickCart\Model\Config\Source\BlockType;
use Magento\Catalog\ViewModel\Product\Listing\PreparePostData;

/** @var Hyva\Theme\ViewModel\HeroiconsOutline $heroicons */
/** @var Popup $block */
$heroicons      = $viewModels->require(HeroiconsOutline::class);
$image = 'product_page_image_medium';
$item = $block->getItem();
?>
<script>
    function initPopupSuccess() {
        return {
            popUpData: <?= /** @noEscape */ $block->getPopupData() ?>,
            checkoutCartUrl: '<?= /** @noEscape */ $block->getUrl('checkout/cart', ['_secure' => true])  ?>',
            timeCountdown: <?= /** @noEscape */ $block->getTimeCountDown()  ?>,
            timer: null,
            stopDownTime: false,
            productSku: '<?= /** @noEscape */ $block->getItem()->getSku() ?>',
            qty: <?= /** @noEscape */ $block->getCurrentQty() ?>,
            updateQtyUrl: '<?= /** @noEscape */ $this->getUpdateQtyUrl() ?>',
            initTimeDown() {
                if (Number(this.timeCountdown) > 0 && !this.stopDownTime) {
                    this.timer = setInterval(() => {
                        if (this.timeCountdown > 0 && !this.stopDownTime) {
                            this.timeCountdown -= 1;
                        } else {
                            clearInterval(this.timer);
                            if(!this.stopDownTime) {
                                this.clickContinue();
                            }
                        }
                    }, 1000);
                }
                let closeBtn = document.querySelector('.wrap-mp-ajaxcart .mfp-close');
                if(closeBtn) {
                    closeBtn.addEventListener('click',()=>{
                        this.stopDownTime = true;
                    })
                }

            },
            clickViewCart() {
                window.location.href = this.checkoutCartUrl;
            },
            getTimeCountDown() {
                if(this.stopDownTime) {
                    return '';
                }
              return '(' + this.timeCountdown + ')';
            },
            clickContinue() {
                let closeBtn = document.querySelector('.wrap-mp-ajaxcart .mfp-close');
                if(closeBtn) {
                    closeBtn.click();
                }
                this.stopDownTime = true;
            },

            clickProceedCheckout() {
                const browserStorage = hyva.getBrowserStorage();
                if (browserStorage) {
                    let dataStorage = (JSON.parse(browserStorage.getItem('mage-cache-storage')));
                    let customer = dataStorage.customer;
                    let cart = dataStorage.cart;
                    if(!customer?.fullname && cart?.isGuestCheckoutAllowed === false) {
                        this.clickContinue();
                        window.dispatchEvent(new CustomEvent('toggle-authentication',
                            {detail: {url: '<?= $escaper->escapeUrl($block->getUrl('checkout')) ?>'}}));
                        return false;
                    }
                }
                window.location.href = this.popUpData.checkoutPageUrl;
            },
            changeQty(e) {
                this.stopDownTime = true;
                this.qty = e.value;
                let updateQtyBtn = document.querySelector('button.mpajaxcart-update');
                if(updateQtyBtn) {
                    updateQtyBtn.style.display = 'block';
                }
            },
            clickUpdateQty(e) {
                let qty = this.qty;
                if (qty <= 0) {
                } else if (!qty) {
                } else {
                    const formData = new FormData();
                    formData.append('sku', this.productSku);
                    formData.append('qty', qty);
                    formData.append('mpquickview', '1');


                    fetch(this.updateQtyUrl, {
                        method: 'POST',
                        headers: {
                            "X-Requested-With": "XMLHttpRequest"
                        },
                        body: formData,
                        mode: "cors",
                        credentials: "include"
                    })
                    .then(response => response.json())
                    .then(res => {
                        if (res.success === false) {
                            typeof window.dispatchMessages !== "undefined" && window.dispatchMessages(
                                [{
                                    type: "error",
                                    text: res?.error_message
                                }], 2000
                            );
                        } else {
                            let shopingcartItems = document.querySelector('.mpajaxcart-msqty strong');
                            if(shopingcartItems) {
                                shopingcartItems.innerHTML = res.itemsQty + ' items';
                            }
                            let subTotals = document.querySelector('.mpajaxcart-mssubtotal strong');
                            if(subTotals) {
                                subTotals.innerHTML = res.subtotal;
                            }
                            e.style.display= 'none';
                            window.dispatchEvent(new CustomEvent('reload-customer-section-data'));
                        }
                    })
                    .catch(error => console.error('Error:', error));
                }

            }
        }
    }
</script>
<div x-data="initPopupSuccess()" x-init="initTimeDown()">
    <div class="mpajaxcart-popup-success grid grid-cols-2 gap-2 pt-6">
        <div class="mp-product-item-photo">
            <?= /** @noEscape */ $block->getImage($item, $image)->toHtml() ?>
        </div>
        <div class="mp-product-item-info">
            <div class="mpajaxcart-popup-title">
                <div class="mpajaxcart-popup-label text-2xl font-semibold">
                    <?= /** @noEscape */ $item->getName() ?>
                </div>
                <span class="mpajaxcart-message"><?= /** @noEscape */ __('has been added to your shopping cart.') ?></span>
            </div>

            <?php if ($block->checkShowControl($item)) : ?>
                <div class="mpajaxcart-control mt-3 flex items-center">
                    <span class="label">Qty</span>
                    <input type="number" name="qty" @change="changeQty($el)" class="mpajaxcart-qty ml-3 w-1/4 rounded" maxlength="12" min="1"
                               value="<?= /** @noEscape */ $block->getCurrentQty() ?>" title="Qty">

                    <button type="button" @click="clickUpdateQty($el)" value="Update" class="mpajaxcart-update border p-2 ml-3 rounded" style="display: none; border-color: black">
                        Update
                    </button>
                </div>

            <?php endif; ?>

            <span class="mp-status mt-3"></span>

            <div class="mpajaxcart-msqty mt-3">
                <label class="label"><?= /** @noEscape */ __('Shopping cart:') ?></label>
                <strong class="qty"><?= /** @noEscape */ __('%1 items', $block->getItemsQty()) ?></strong>
            </div>
            <div class="mpajaxcart-mssubtotal">
                <label class="label"><?= /** @noEscape */ __('Cart Subtotal:') ?></label>
                <strong class="subtotal"><?= /** @noEscape */ $block->getSubtotal() ?></strong>
            </div>
        </div>
    </div>
    <div class="mpajaxcart-success-action flex justify-center flex-wrap">
        <button type="button" @click="clickContinue()" title="Continue shopping" class="action primary continue-shopping mb-3 mt-3 rounded font-semibold flex justify-center items-center">
            <?= /** @noEscape */ $heroicons->chevronLeftHtml('w-5 h-5') ?>
            <span class="mx-3">  <?= /** @noEscape */ __('Continue') ?></span>

            <span class="mpajaxcart-countdown" x-text="getTimeCountDown()"></span>
        </button>
        <button type="button" title="View Cart" @click="clickViewCart()" class="action primary btn-view-cart mb-3 mt-3 rounded font-semibold flex justify-center items-center">
            <?= /** @noEscape */ $heroicons->shoppingCartHtml('w-5 h-5') ?>
            <span class="mx-3">
            <?= /** @noEscape */ __('View Cart') ?>
        </span>
        </button>
        <button type="button" @click="clickProceedCheckout()" title="Proceed to Checkout" class="action primary btn-proceed-checkout mb-3 mt-3 rounded font-semibold flex justify-center items-center">
            <?= /** @noEscape */ __('Proceed to Checkout') ?>
        </button>
    </div>
</div>


<?php
switch ($type = $block->getType()) {
    case BlockType::RELATED:
        if ($exist = $block->getItems()->getSize()) {
            $type  = BlockType::RELATED;
            $class = $type;
            $image = 'related_products_list';
            $title = $block->getHelperData()->getBlockTitle() ?: __('Related Products');
            $items = $block->getItems();
            $limit = 0;
            $shuffle = 0;
            $canItemsAddToCart = $block->canItemsAddToCart();
            $templateType = null;
        }
        break;

    case BlockType::CROSS_SELL:
        if ($exist = count($block->getItems())) {
            $type  = BlockType::CROSS_SELL;
            $class = $type;
            $image = 'cart_cross_sell_products';
            $title = $block->getHelperData()->getBlockTitle() ?: __('More Choices:');
            $items = $block->getItems();
            $templateType = ReviewRendererInterface::SHORT_VIEW;
            $canItemsAddToCart = false;
        }
        break;

    case BlockType::UP_SELL:
        if ($exist = count($block->getItems())) {
            $type  = BlockType::CROSS_SELL;
            $class = $type;
            $image = 'cart_cross_sell_products';
            $title = $block->getHelperData()->getBlockTitle() ?: __('Up Sell Products');
            $items = $block->getItems();
            $limit = 0;
            $shuffle = 0;
            $canItemsAddToCart = $block->canItemsAddToCart();
            $templateType = null;
        }
        break;

    default:
        $exist = null;
}

$_item = null;
?>
<?php if ($type === BlockType::CMS_STATIC_BLOCK) : ?>
    <?= $block->getChildHtml('cms-static-block') ?>
<?php else : ?>
    <?php if ($exist) : ?>
        <?= $block->getLayout()->createBlock('Magento\Catalog\Block\Product\View')
            ->setTemplate('Mageplaza_QuickCart::hyva/ajaxcart/product-slider.phtml')
            ->setTitle($title)->setType($type)->setItems($items)->toHtml() ?>
    <?php endif; ?>
<?php endif; ?>
