<?php
/******************************************************************************
 *   ______                                                                   *
 *  /       \                                                                 *
 * /$$$$$$  | ________  __    __   ______    ______                           *
 * $$ |__$$ |/        |/  |  /  | /      \  /      \                          *
 * $$    $$ |$$$$$$$$/ $$ |  $$ |/$$$$$$  |/$$$$$$  |                         *
 * $$$$$$$$ |  /  $$/  $$ |  $$ |$$ |  $$/ $$    $$ |                         *
 * $$ |  $$ | /$$$$/__ $$ \__$$ |$$ |      $$$$$$$$/                          *
 * $$ |  $$ |/$$      |$$    $$/ $$ |      $$       |                         *
 * $$/   $$/ $$$$$$$$/  $$$$$$/  $$/        $$$$$$$/                          *
 *                                                                            *
 * @PROJECT    : 3D Preview Extension [Magetop.com]                           *
 * @AUTHOR     : Azure - Developer                                            *
 * @COPYRIGHT  : © 2019  Magetop.com                                          *
 * @LINK       : https://Magetop.com                                          *
 * @CREATED    :  10/01/2022                                                  *
 ******************************************************************************/

namespace Magetop\Advancepreview\Block\ReWrites;


use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Visibility as ProductVisibility;
use Magento\Checkout\Model\ResourceModel\Cart as CartResourceModel;
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\Framework\Module\Manager;


class Related extends \Magento\Catalog\Block\Product\ProductList\Related
{
    protected $registry;
    protected $httpContext;
    protected $coreSession;
    protected $customerSession;
    protected $customerFactory;
    protected $previewhistoryFactory;
    protected $resPreviewhistoryFactory;
    protected $colPreviewhistoryFactory;
    protected $productCollectionFactory;
    public function __construct(
        Context $context,
        CartResourceModel $checkoutCart,
        ProductVisibility $catalogProductVisibility,
        CheckoutSession $checkoutSession,
        Manager $moduleManager,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\App\Http\Context $httpContext,
        \Magento\Framework\Session\SessionManagerInterface $coreSession,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magetop\Advancepreview\Model\PreviewhistoryFactory $previewhistoryFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewhistoryFactory $resPreviewhistoryFactory,
        \Magetop\Advancepreview\Model\ResourceModel\Previewhistory\CollectionFactory $colPreviewhistoryFactory,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        array $data = []
    )
    {
        $this->registry = $registry;
        parent::__construct($context, $checkoutCart, $catalogProductVisibility, $checkoutSession, $moduleManager, $data);
        $this->httpContext = $httpContext;
        $this->coreSession = $coreSession;
        $this->customerSession = $customerSession;
        $this->customerFactory = $customerFactory;
        $this->previewhistoryFactory = $previewhistoryFactory;
        $this->resPreviewhistoryFactory = $resPreviewhistoryFactory;
        $this->colPreviewhistoryFactory = $colPreviewhistoryFactory;
        $this->productCollectionFactory = $productCollectionFactory;
    }

    function _prepareData()
    {
        /* @var $product Product */
        $productIds = $this->getLastOpendProductIds();
        if(count($productIds)) {
            $this->_itemCollection = $this->productCollectionFactory->create()
                ->addAttributeToSelect('*')
                ->addAttributeToFilter('entity_id',array('in'=>implode(',',$productIds)))
                ->setPageSize(12);
            $this->_itemCollection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds());            
            $this->_itemCollection->getSelect()->order('FIELD(entity_id, '.implode(',',$productIds).')');
            $this->_itemCollection->load();
            foreach ($this->_itemCollection as $product) {
                $product->setDoNotUseCategoryId(true);
            }
        }
        else {
            $this->_itemCollection =  $this->_itemCollection = $this->productCollectionFactory->create()
                ->addAttributeToSelect('*')
                ->addAttributeToFilter('entity_id',array('lt'=>0));
            $this->_itemCollection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds());

            $this->_itemCollection->load();

            foreach ($this->_itemCollection as $product) {
                $product->setDoNotUseCategoryId(true);
            }
        }



        return $this;
    }
    public function getLastOpendProductIds() {
        $lastOpens = $this->coreSession->getMagetopProductlastOpens();
        $product = $this->getCustomProduct();
        $productId = $product->getId();
//        $this->getCurrentHistoryId($productId,36);
        if(isset($lastOpens[$productId])) {

        }
        else {
            $lastOpens[$productId] = $product->getName();
            $this->coreSession->setMagetopProductlastOpens($lastOpens);
        }
        if($this->checkIsLogin()) {
            $customerId =  $this->customerSession->getCustomerId();

            $productIds = [];
            foreach ($lastOpens as $key => $lastOpen) {
                $productIds[] = $key;
            }
//            $opendProductIds = $productIds;
            $productIds = implode(',',$productIds);
            // get data from database
            $collection = $this->colPreviewhistoryFactory->create()
                ->addFieldToSelect(array('product_name','product_id'))
//                        ->addFieldToFilter('product_id',$productId)
                ->addFieldToFilter('customer_id',$customerId);
            $collection->getSelect()->where("product_id NOT IN ($productIds)");
            $collection->setOrder('last_access','ASC');
            $collection->setPageSize(12);
            if(count($collection)) {
                foreach ($collection as $item) {
                    $ipId = $item->getData('product_id');
                    $lastOpens[$ipId] = $item->getData('product_name');
                    if(count($lastOpens) > 12) {
                        break;
                    }
                }

            }
            $this->updateHistories($product, $customerId);
        }
        $opendProductIds = [];
        foreach ($lastOpens as $key1 => $lastOpen1) {
            if($key1 == $productId) {
                continue;
            }
            if(count($opendProductIds) > 12) {
                break;
            }
            $opendProductIds[] = $key1;
        }
        return $opendProductIds;
    }
    protected function updateHistories($product, $customerId) {
        $model = $this->previewhistoryFactory->create();
        $currentId = $this->getCurrentHistoryId($customerId, $product->getId());
        if($currentId > 0) {
            $dataSave = array(
                'history_id'=>$currentId,
                'last_access'=>date('Y-m-d H:i:s')
            );
        }
        else {
            $dataSave = array(
                'product_id'=>$product->getId(),
                'product_name'=>$product->getName(),
                'customer_id'=>$customerId,
                'last_access'=>date('Y-m-d H:i:s')
            );
        }
        $model->setData($dataSave);
        try {
            $this->resPreviewhistoryFactory->create()->save($model);

        }
        catch (\Exception $exception) {

        }
    }
    protected function getCurrentHistoryId($customerId, $productId) {
        $collection = $this->colPreviewhistoryFactory->create()
            ->addFieldToFilter('product_id',$productId)
            ->addFieldToFilter('customer_id',$customerId);
        return $collection && $collection->getSize() > 0 ? $collection->getFirstItem()->getId() : 0;

    }
    protected function getCustomProduct() {
        $_product = null;
        if($this->registry->registry('product')) {
            /** @var \Magento\Catalog\Model\Product $_product */
            $_product = $this->registry->registry('product');
        }
        return $_product;
    }
    protected function checkIsLogin() {
        $isLogin = false;
        if($this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH)) {
            $isLogin = true;
        }
        return $isLogin;
    }
}
