<?php
    use Magento\Framework\App\Action\Action;

    $viewMode = 'grid';
    $image = 'category_page_grid';
    $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
    $_product = $this->getLoadProduct($this->getProductId());
    $_productNameStripped = $block->stripTags($_product->getName(), null, true);
    $productImage = $block->getImage($_product, $image);
    $_helper = $this->helper('Magento\Catalog\Helper\Output');
    $builderHelper = $this->helper('MGS\Fbuilder\Helper\Data');
    $hideName = $this->getBlockData('hide_name');
    $hideReview = $this->getBlockData('hide_review');
    $getShowReviewsSummary = $this->getShowReviewsSummary() ? true : false;
    $hidePrice = $this->getBlockData('hide_price');
    $hideAddCart = $this->getBlockData('hide_addcart');
    $hideAddWishlist = $this->getBlockData('hide_addwishlist');
    $hideAddCompare = $this->getBlockData('hide_addcompare');
    $themeSettingConfig = $this->helper('MGS\ThemeSettings\Helper\Config');
    $_imagehelper = $this->helper('MGS\ThemeSettings\Helper\Image');
    $lazyLoad = $themeSettingConfig->getStoreConfig('themesettings/general/lazy_load');
    $baseImage = $this->getViewFileUrl('MGS_ThemeSettings::images/blank.png');

$callHelper = $this->helper('MGS\Callforprice\Helper\Data');
$test = $this->getLayout()->createBlock('MGS\Callforprice\Block\RequestQuote')->getFormAction();
$_product = $block->getProduct();
$priceRender = $block->getLayout()->getBlock('product.price.render.default');
if (!$priceRender) {
    $priceRender = $block->getLayout()->createBlock(\Magento\Framework\Pricing\Render::class, 'product.price.render.default');
}

$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
    ]
);


/** @var \Magento\Customer\Model\Session $customerSession */
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get(\Magento\Customer\Model\Session::class);
$UrlInterface = $objectManager->get(\Magento\Framework\UrlInterface::class);
?>
<div class="product-item-info" data-container="product-list">
        <div class="product-image">
            <?php
            $ratio = $this->getRatio() ? $this->getRatio() : null;
            $size = $themeSettingConfig->getImageSize($ratio);
            $padding = $themeSettingConfig->getImagePadding();
            if ($ratio == 1) {
                $padding = '100%';
            }
            ?>

            <?php
            $productImage = $_imagehelper->init($_product, $image)->setImageFile($_product->getData('small_image'))->resize($size['width'], $size['height'])->getUrl();
            $productImageHover = $_imagehelper->init($_product, $image)->setImageFile($_product->getData('thumbnail'))->resize($size['width'], $size['height'])->getUrl();
            ?>
            <?php if(!$lazyLoad): ?>
                <?php $baseImage = $productImage ?>
            <?php endif ?>

            <!-- Product Image-->
            <a href="<?php echo $_product->getProductUrl() ?>"
               class="product photo product-item-photo <?php if ((basename($_product->getData('thumbnail') ?? '') != 'no_selection') && (basename($_product->getData('thumbnail') ?? '') != basename($_product->getData('small_image') ?? ''))): ?> has-hover-image<?php endif ?>"
               style="padding-bottom: <?php echo $padding ?>;" tabindex="-1">

                <img src="<?php echo $baseImage ?>" alt="<?php echo $_productNameStripped ?>"
                     class="img-responsive <?php if ($lazyLoad): ?>arrow-lazy<?php endif ?>"
                     loading="lazy"
                     data-src="<?php echo $productImage ?>"/>
            </a>
            <ul class="actions-link actions-secondary">
                <li>
                    <a data-productid="<?= $_product->getId(); ?>" class="action quickview qv-list" aria-label="Quickview" title="Quickview" href="<?= $this->getUrl().'aquickview/index/index/catalog/product/id/'.$_product->getId(); ?>">
                        <span><?= __('Quickview'); ?></span>
                    </a>
                </li>
                <?php if(($hideAddWishlist!=1)): ?>
                    <?php if ($this->helper('Magento\Wishlist\Helper\Data')->isAllow() && ($hideAddWishlist!=1)): ?>
                        <li>
                            <button class="action towishlist"
                                    title="<?php echo $block->escapeHtml(__('Add to Wish List')); ?>"
                                    data-title="<?php echo __('Add to Wish List') ?>"
                                    aria-label="<?php echo $block->escapeHtml(__('Add to Wish List')); ?>"
                                    data-post='<?php /* @escapeNotVerified */ echo $block->getAddToWishlistParams($_product); ?>'
                                    data-action="add-to-wishlist"
                                    role="button">
                                <i class="pe-7s-like"></i>
                            </button>
                        </li>
                    <?php endif ?>
                <?php endif ?>

                <?php if($hideAddCompare!=1): ?>
                    <?php $compareHelper = $this->helper('Magento\Catalog\Helper\Product\Compare'); ?>
                    <li>
                        <button class="action tocompare"
                                title="<?php echo $block->escapeHtml(__('Add to Compare')); ?>"
                                data-title="<?php echo __('Add to Compare') ?>"
                                aria-label="<?php echo $block->escapeHtml(__('Add to Compare')); ?>"
                                data-post='<?php /* @escapeNotVerified */ echo $compareHelper->getPostDataParams($_product); ?>'
                                role="button">
                            <i class="pe-7s-graph3"></i>
                        </button>
                    </li>
                <?php endif ?>

            </ul>
        </div>

        <?php // Product Detail ?>
        <div class="product details product-item-details">

            <?php if ($hideName!=1): ?>
                <h5 class="product name product-item-name">
                    <a class="product-item-link"
                       href="<?php echo $_product->getProductUrl() ?>">
                        <?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?>
                    </a>
                </h5>
            <?php endif ?>

            <?php if ($hideReview!=1): ?>
                <?php echo $block->getReviewsSummaryHtml($_product, $templateType,$getShowReviewsSummary) ?>
            <?php endif ?>

            <?php if ($hidePrice != 1): ?>
                <?php if (!$callHelper->getConfig('mgscallforprice/general/isenabled')) : ?>
                    <?= /* @noEscape */$priceHtml ?>
                <?php else: ?>
                    <?php if ($callHelper->getConfig('mgscallforprice/general/choosetype') == '1') : ?>
                        <a href="tel: <?php echo $callHelper->getConfig('mgscallforprice/general/vendorphonenumber') ?>"
                           class="action primary tocart"><span><i
                                    class="pe-7s-call"></i><?php echo $callHelper->getConfig('mgscallforprice/general/callforpricetextbutton') ?></span></a>
                    <?php elseif ($callHelper->getConfig('mgscallforprice/general/choosetype') == '2'): ?>
                        <button type="button" class="action primary tocart request-quote-<?php echo
                        $block->getProduct()->getId(); ?>">
                            <span><?php echo $callHelper->getConfig('mgscallforprice/general/requestquote') ?></span></button>
                        <form class="form quote-request test" action="<?php echo $test; ?>"
                              id="quote-request-form-<?php echo $block->getProduct()->getId() ?>" method="post"
                              data-hasrequired="<?= $block->escapeHtmlAttr(__('* Required Fields')) ?>"
                              data-mage-init='{"validation":{}}' style="display: none;">
                            <fieldset class="fieldset">
                                <legend class="legend"><span><?= $block->escapeHtml(__('Write Us')) ?></span></legend>
                                <br/>
                                <div class="field note no-label">
                                    <?= $block->escapeHtml(__('Jot us a note and we’ll get back to you as quickly as possible.')) ?>
                                </div>
                                <div class="field name required">
                                    <label class="label" for="name"><span><?= $block->escapeHtml(__('Name')) ?></span></label>
                                    <div class="control">
                                        <input name="name" id="name-<?php echo $block->getProduct()->getId(); ?>"
                                               title="<?= $block->escapeHtmlAttr(__('Name')) ?>" value="" class="input-text"
                                               type="text" data-validate="{required:true}"/>
                                    </div>
                                </div>
                                <div class="field telephone">
                                    <label class="label"
                                           for="telephone"><span><?= $block->escapeHtml(__('Phone Number')) ?></span></label>
                                    <div class="control">
                                        <input name="telephone" id="telephone-<?php echo $_product->getId(); ?>"
                                               title="<?= $block->escapeHtmlAttr(__('Phone Number')) ?>" value=""
                                               class="input-text" type="text"/>
                                    </div>
                                </div>
                                <div class="field email required">
                                    <label class="label" for="email"><span><?= $block->escapeHtml(__('Email')) ?></span></label>
                                    <div class="control">
                                        <input name="email" id="email-<?php echo $_product->getId(); ?>"
                                               title="<?= $block->escapeHtmlAttr(__('Email')) ?>" value=""
                                               class="input-text" type="email" data-validate="{required:true, 'validate-email':true}"/>
                                    </div>
                                </div>

                                <div class="field productId">
                                    <label class="label productId"
                                           for="productId"><span><?= $block->escapeHtml(__('Product ID')) ?></span></label>
                                    <div class="control">
                                        <input name="productId" id="productId-<?php echo $_product->getId(); ?>"
                                               title="<?= $block->escapeHtmlAttr(__('Product ID')) ?>"
                                               value="<?php echo $_product->getId(); ?>" class="input-text" type="hidden"
                                               readonly="readonly"/>
                                    </div>
                                </div>
                                <div class="field productSku">
                                    <label class="label productSku"
                                           for="productSku"><span><?= $block->escapeHtml(__('Product SKU')) ?></span></label>
                                    <div class="control">
                                        <input name="productSku" id="productSku-<?php echo $_product->getId(); ?>"
                                               title="<?= $block->escapeHtmlAttr(__('Product SKU')) ?>"
                                               value="<?php echo $_product->getSku(); ?>" class="input-text" type="hidden"
                                               readonly="readonly"/>
                                    </div>
                                </div>
                                <div class="field productName">
                                    <label class="label productName"
                                           for="productName"><span><?= $block->escapeHtml(__('Product Name')) ?></span></label>
                                    <div class="control">
                                        <input name="productName" id="productName-<?php echo $_product->getId(); ?>"
                                               title="<?= $block->escapeHtmlAttr(__('Product Name')) ?>"
                                               value="<?php echo $_product->getName(); ?>" class="input-text" type="hidden"
                                               readonly="readonly"/>
                                    </div>
                                </div>
                                <div class="field comment">
                                    <label class="label" for="comment">
                                        <span><?= $block->escapeHtml(__('Comment')) ?></span>
                                    </label>
                                    <div class="control">
															<textarea name="comment"
                                                                      id="comment-<?php echo $_product->getId(); ?>"
                                                                      title="<?= $block->escapeHtmlAttr(__('Comment')) ?>"
                                                                      class="input-text" cols="5" rows="3"></textarea>
                                    </div>
                                </div>
                                <?= $block->getChildHtml('form.additional.info') ?>
                            </fieldset>
                            <div class="actions-toolbar">
                                <div class="primary">
                                    <input type="hidden" name="hideit" id="hideit" value=""/>
                                    <button type="submit" title="<?= $block->escapeHtmlAttr(__('Submit')) ?>"
                                            class="action submit primary">
                                        <span><?= $block->escapeHtml(__('Submit')) ?></span>
                                    </button>
                                </div>
                            </div>
                        </form>
                    <?php else: ?>
                        <?php if (!$customerSession->isLoggedIn()):?>
                            <a href="<?= $UrlInterface->getUrl('customer/account/login') ?>"
                               alt="Login to see price" class="logintoseeprice">
                                <span><?= __('Login to see price') ?></span>
                            </a>
                        <?php else: ?>
                            <?= /* @noEscape */$priceHtml ?>
                        <?php endif;?>
                    <?php endif; ?>
                <?php endif; ?>
            <?php endif ?>

            <?php if (($hideAddCart!=1)): ?>
                <div class="product-item-inner">
                    <div class="product actions product-item-actions">
                        <?php if ($hideAddCart!=1): ?>
                            <div class="actions-primary">
                                <?php if ($_product->isSaleable()): ?>
                                    <?php $postParams = $block->getAddToCartPostParams($_product); ?>
                                    <form data-role="tocart-form" data-product-sku="<?php echo  /* @NoEscape */ $_product->getSku() ?>" action="<?php echo /* @NoEscape */ $postParams['action'] ?>" method="post">
                                        <input type="hidden" name="product" value="<?php echo /* @escapeNotVerified */ $postParams['data']['product'] ?>">
                                        <input type="hidden" name="<?php echo /* @escapeNotVerified */ Action::PARAM_NAME_URL_ENCODED ?>" value="<?php echo /* @escapeNotVerified */ $postParams['data'][Action::PARAM_NAME_URL_ENCODED] ?>">
                                        <?php echo $block->getBlockHtml('formkey') ?>

                                        <?php if($_product->getTypeId() == 'simple'): ?>
                                            <button type="submit"
                                                    title="<?php echo $block->escapeHtml(__('Add to Cart')) ?>"
                                                    class="action tocart btn btn-default btn-xs">
                                                <span><?php echo /* @escapeNotVerified */ __('Add to Cart') ?></span>
                                            </button>
                                        <?php else: ?>
                                            <button type="submit"
                                                    title="<?php echo $block->escapeHtml(__('Add to Cart')) ?>"
                                                    class="action tocart btn btn-default btn-xs"
                                                    onclick="window.location.href = '<?php echo $block->getProductUrl($_product)?>'">
                                                <span><?php echo /* @escapeNotVerified */ __('Add to Cart') ?></span>
                                            </button>
                                        <?php endif; ?>
                                        <?php
                                        if ($callHelper->getConfig('buynow/general/enable_widget_buider')) {
                                            echo $this->getLayout()
                                                ->createBlock(\MGS\BuyNow\Block\Product\ListProduct::class)
                                                ->setProduct($_product)
                                                ->setButtonTitle('Buy Now')
                                                ->setTemplate('MGS_BuyNow::buynow.phtml')
                                                ->toHtml();
                                        }
                                        ?>
                                    </form>
                                <?php else: ?>
                                    <?php if ($_product->isAvailable()): ?>
                                        <div class="stock available"><span><?php echo /* @escapeNotVerified */ __('In stock') ?></span></div>
                                    <?php else: ?>
                                        <div class="stock unavailable"><span><?php echo /* @escapeNotVerified */ __('Out of stock') ?></span></div>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                        <?php endif ?>
                    </div>
                </div>
            <?php endif ?>
        </div>
    </div>
<script type="text/javascript">
    require(["jquery", "Magento_Ui/js/modal/modal"],function($, modal) {
			var options = {
            type: 'popup', // popup or slide
			responsive: true, // true = on smaller screens the modal slides in from the right
			modalClass: 'see-detail-modal',
			};
			$(".request-quote-<?php echo $block->getProduct()->getId() ?>").on('click',function() {
				$('#quote-request-form-<?php echo $block->getProduct()->getId() ?>').modal(options).modal('openModal');
			});

    });
     document.addEventListener('DOMContentLoaded', () => {

             require([
        'jquery',
        'Magento_Ui/js/modal/alert',
        'Magento_Customer/js/customer-data',
        'Magento_Catalog/js/catalog-add-to-cart'
        ], function($, alert, customerData) {
        $(document).ready(function() {
            $('.mageprince-buy-now-btn').on('click', function(event) {
                event.preventDefault();
                var form = $('#product_addtocart_form');
                var formData = form.serializeArray();
                formData.push({name: 'isAjax', value: 1});

                $.ajax({
                    url: form.attr('action'),
                    data: $.param(formData),
                    type: 'post',
                    dataType: 'json',
                    success: function(response) {
                        if (response.backUrl) {
                            window.location.href = response.backUrl;
                        } else if (response.redirectUrl) {
                            window.location.href = response.redirectUrl;
                        } else {
                            window.location.href = '/checkout';
                        }
                    },
                    error: function() {
                        alert({
                            content: 'An error occurred while processing your request. Please try again later.'
                        });
                    }
                });
            });
        });
    });

     })

</script>
