<?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
 */

namespace Mageplaza\QuickCart\Block\AjaxCart;

use Magento\Catalog\Block\Product\AbstractProduct;
use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Checkout\Model\Cart;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Pricing\Helper\Data as PriceHelper;
use Mageplaza\QuickCart\Helper\QuickViewData as HelperData;
use Mageplaza\QuickCart\Model\Config\Source\ApplyFor;

/**
 * Class Popup
 * @package Mageplaza\QuickCart\Block\AjaxCart
 */
class Popup extends AbstractProduct
{
    /**
     * @var CollectionFactory
     */
    protected $collection;

    /**
     * @var ManagerInterface
     */
    protected $messageManager;

    /**
     * @var Cart
     */
    protected $_cart;

    /**
     * @var PriceHelper
     */
    protected $_priceHelper;

    /**
     * @var HelperData
     */
    public $_helperData;

    /**
     * @var Visibility
     */
    private $catalogProductVisibility;

    /**
     * Popup constructor.
     *
     * @param ManagerInterface $messageManager
     * @param CollectionFactory $collection
     * @param Context $context
     * @param Cart $cart
     * @param PriceHelper $priceHelper
     * @param HelperData $helperData
     * @param Visibility $catalogProductVisibility
     * @param array $data
     */
    public function __construct(
        ManagerInterface $messageManager,
        CollectionFactory $collection,
        Context $context,
        Cart $cart,
        PriceHelper $priceHelper,
        HelperData $helperData,
        Visibility $catalogProductVisibility,
        array $data = []
    ) {
        $this->messageManager           = $messageManager;
        $this->collection               = $collection;
        $this->_cart                    = $cart;
        $this->_priceHelper             = $priceHelper;
        $this->_helperData              = $helperData;
        $this->catalogProductVisibility = $catalogProductVisibility;

        parent::__construct($context, $data);
    }

    /**
     * @return mixed
     */
    public function getItem()
    {
        return $this->getProductItem();
    }

    /**
     * @return array
     */
    public function getMessage()
    {
        $lastMessage = $this->messageManager->getMessages()->getLastAddedMessage();
        if (!$lastMessage) {
            return [
                'type'    => $lastMessage->getType(),
                'message' => $lastMessage->getText()
            ];
        }

        return [];
    }

    /**
     * Get data for popyup success
     *
     * @return string
     */
    public function getPopupData()
    {
        $data = [
            'productSku'      => $this->getItem()->getSku(),
            'updateQtyUrl'    => $this->getUpdateQtyUrl(),
            'price'           => $this->getItem()->getPrice(),
            'timeCountdown'   => $this->getTimeCountDown(),
            'checkoutCartUrl' => $this->getUrl('checkout/cart', ['_secure' => true]),
            'checkoutPageUrl' => $this->getCheckoutPageUrl()
        ];

        return HelperData::jsonEncode($data);
    }

    /**
     * @return string
     */
    private function getCheckoutPageUrl()
    {
        if ($this->_helperData->isModuleOutputEnabled('Mageplaza_Osc')) {
            $oscHelper = $this->_helperData->getObject(\Mageplaza\Osc\Helper\Data::class);

            return $this->getUrl($oscHelper->getOscRoute(), ['_secure' => true]);
        }

        return $this->getUrl('checkout', ['_secure' => true]);
    }

    /**
     * Get Ajax add to cart data
     *
     * @return string
     */
    public function getAjaxCartData()
    {
        $data = [
            'isAnimate'   => $this->isEnableAnimate(),
            'isApplyQV'   => $this->_helperData->isAjaxCartQuickView(),
            'isApplyPage' => $this->checkApply(),
            'detailUrl'   => $this->getUrl('catalog/product/view')
        ];

        return HelperData::jsonEncode($data);
    }

    /**
     * @return string
     */
    public function getUpdateQtyUrl()
    {
        return $this->getUrl('checkout/sidebar/updateItemQty');
    }

    /**
     * Get Current Qty of product
     *
     * @return float|int|mixed
     */
    public function getCurrentQty()
    {
        $product = $this->getItem();
        $sku     = $product->getSku();
        $items   = $this->_cart->getQuote()->getAllVisibleItems();
        $qty     = 1;

        foreach ($items as $item) {
            if ($sku === $item->getSku()) {
                $qty = $item->getQty();
            }
        }

        return $qty;
    }

    /**
     * get subtotal in cart
     *
     * @return float|int|string
     */
    public function getSubtotal()
    {
        $quote = $this->_cart->getQuote();

        $subtotal = $quote->getSubtotal();
        $currency = $quote->getQuoteCurrencyCode();

        return $this->_helperData->getPriceCurrency($subtotal, $currency);
    }

    /**
     * Check show update control
     *
     * @param $item
     *
     * @return bool
     */
    public function checkShowControl($item)
    {
        return !in_array($item->getTypeId(), ['grouped', 'bundle']);
    }

    /**
     * Sub qty in cart
     *
     * @return float|int
     */
    public function getItemsQty()
    {
        return $this->_cart->getItemsQty();
    }

    /**
     * is enable animate fly to cart
     *
     * @return mixed
     */
    public function isEnableAnimate()
    {
        return $this->_helperData->getAjaxCartConfig('animate');
    }

    /**
     * Get time countdown to close popup
     *
     * @return int|mixed
     */
    public function getTimeCountDown()
    {
        return $this->_helperData->getAjaxCartConfig('countdown_time') ?: 10;
    }

    /**
     * Check page to apply action
     *
     * @return bool
     */
    public function checkApply()
    {
        $action = $this->_request->getFullActionName();
        $config = $this->_helperData->getAjaxCartConfig('apply_for');

        if (in_array($action, explode(',', $config), false)) {
            return true;
        }

        if ($action === 'catalogsearch_result_index'
            && in_array(ApplyFor::PRODUCT_LIST_PAGE, explode(',', $config), false)
        ) {
            return true;
        }

        return false;
    }

    /**
     * @return string
     */
    public function wishListAndCompareData()
    {
        $data = [
            'isApplyQV'   => $this->_helperData->isAjaxCartQuickView(),
            'isApplyPage' => $this->checkApply(),
            'loginUrl'    => $this->getUrl('customer/account/login')
        ];

        return HelperData::jsonEncode($data);
    }

    /**
     * @return HelperData
     */
    public function getHelperData()
    {
        return $this->_helperData;
    }

    /**
     * @return \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection
     */
    public function getItems()
    {
        /** @var \Magento\Catalog\Model\Product $product */
        $product = $this->getItem();
        if ($this->getType() === 'related') {
            $collection        = $product->getRelatedProductCollection();
            $productAttributes = 'required_options';
            if ($this->_helperData->isModuleOutputEnabled('Magento_Checkout')) {
                $this->_addProductAttributesAndPrices($collection);
            }
            $collection->setVisibility($this->catalogProductVisibility->getVisibleInCatalogIds());
        } elseif ($this->getType() === 'crosssell') {
            $collection        = $product->getCrossSellProductCollection();
            $productAttributes = $this->_catalogConfig->getProductAttributes();
        } else {
            $collection        = $product->getUpSellProductCollection();
            $productAttributes = $this->_catalogConfig->getProductAttributes();
        }

        $collection->addAttributeToSelect(
            $productAttributes
        )->setPositionOrder()->addStoreFilter();

        if ($qtyLimit = $this->_helperData->getBlockQtyLimit()) {
            $collection->setPageSize($qtyLimit);
        }

        $collection->load();
        foreach ($collection as $product) {
            $product->setDoNotUseCategoryId(true);
        }

        return $collection;
    }

    /**
     * Find out if some products can be easy added to cart
     *
     * @return bool
     */
    public function canItemsAddToCart()
    {
        foreach ($this->getItems() as $item) {
            if (!$item->isComposite() && $item->isSaleable() && !$item->getRequiredOptions()) {
                return true;
            }
        }

        return false;
    }
}