<?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\Controller\Catalog;

use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ProductFactory;
use Magento\Checkout\Model\Cart;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\View\Design\Theme\ThemeProviderInterface;
use Mageplaza\QuickCart\Helper\QuickViewData as HelperData;

/**
 * Class ProductNextPrev
 * @package Mageplaza\QuickCart\Controller\Catalog
 */
class ProductNextPrev extends Action
{
    /**
     * @var HelperData
     */
    protected $_helperData;

    /**
     * @var ProductFactory
     */
    protected $productFactory;

    /**
     * @var ThemeProviderInterface
     */
    protected $themeProviderInterface;

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

    public function __construct(
        Context $context,
        HelperData $helperData,
        Cart $cart,
        ProductFactory $productFactory,
        ThemeProviderInterface $themeProviderInterface
    ) {
        $this->_helperData            = $helperData;
        $this->productFactory         = $productFactory;
        $this->themeProviderInterface = $themeProviderInterface;
        $this->cart                   = $cart;

        parent::__construct($context);
    }

    /**
     * @return ResponseInterface|ResultInterface
     * @throws LocalizedException
     */
    public function execute()
    {
        $productId = $this->getRequest()->getParam('productId');
        $prevNext  = $this->getRequest()->getParam('prevNext');

        if ($productId) {
            $params  = [
                'productId'   => $productId,
                'listCartVal' => false,
                'itemId'      => false
            ];
            $product = $this->productFactory->create()->load($productId);

            if ($product && $this->getCurrentTheme() === 'Smartwave/porto') {
                if ($prevNext === 'next') {
                    $nextProduct         = $this->getNextProduct($product);
                    $params['productId'] = $nextProduct->getId();
                }

                if ($prevNext === 'prev') {
                    $prevProduct         = $this->getPrevProduct($product);
                    $params['productId'] = $prevProduct->getId();
                }
            }

            $quote = $this->cart->getQuote();
            foreach ($quote->getAllItems() as $item) {
                if ($params['productId'] === $item->getProductId()) {
                    $params['itemId']      = $item->getId();
                    $params['listCartVal'] = true;
                    break;
                }
            }

            return $this->getResponse()->representJson(HelperData::jsonEncode($params));
        }

        return $this->getResponse()->representJson(HelperData::jsonEncode([]));
    }

    /**
     * check theme using.
     *
     * @return string
     */
    public function getCurrentTheme()
    {
        return $this->themeProviderInterface->getThemeById($this->_helperData->getCurrentThemeId())->getCode();
    }

    /**
     * get Category Ids
     *
     * @param $currentCategory
     *
     * @return mixed
     */
    public function getCategoryProductIds($currentCategory)
    {
        $categoryProducts = $currentCategory->getProductCollection()
            ->addAttributeToSelect('*')
            ->addAttributeToSort('position', 'asc');

        return $categoryProducts->getAllIds();
    }

    /**
     * get preview Product
     *
     * @param $product
     *
     * @return bool|Product
     */
    public function getPrevProduct($product)
    {
        $currentCategory = $product->getCategory();
        if (!$currentCategory) {
            foreach ($product->getCategoryCollection() as $parentCat) {
                $currentCategory = $parentCat;
                break;
            }
        }
        if (!$currentCategory) {
            return false;
        }
        $catProdIds = $this->getCategoryProductIds($currentCategory);
        $pos        = array_search($product->getId(), $catProdIds, true);
        if (isset($catProdIds[$pos - 1])) {
            return $this->productFactory->create()->load($catProdIds[$pos - 1]);
        }

        return false;
    }

    /**
     * get next Product
     *
     * @param $product
     *
     * @return bool|Product
     */
    public function getNextProduct($product)
    {
        $currentCategory = $product->getCategory();
        if (!$currentCategory) {
            foreach ($product->getCategoryCollection() as $parentCat) {
                $currentCategory = $parentCat;
                break;
            }
        }
        if (!$currentCategory) {
            return false;
        }
        $catProdIds = $this->getCategoryProductIds($currentCategory);

        $pos = array_search($product->getId(), $catProdIds, true);
        if (isset($catProdIds[$pos + 1])) {
            return $this->productFactory->create()->load($catProdIds[$pos + 1]);
        }

        return false;
    }
}
