<?php


namespace Magetop\Advancepreview\Block;


use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Customer\Model\CustomerFactory;
use Magento\Framework\View\Element\Template;

/**
 * Class CustomProduct
 * @package Magetop\Advancepreview\Block
 */
class CustomProduct extends  \Magetop\Advancepreview\Block\AdvancePreviewAbstract
{
    /**
     * @var \Magento\Framework\Registry
     */
    protected $registry;

    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $productFactory;
    /**
     * @var \Magento\Catalog\Model\ResourceModel\ProductFactory
     */
    protected $resProductFactory;
    /**
     * @var CollectionFactory
     */
    protected $colProductFactory;
    /**
     * @var \Magento\Framework\Session\SessionManagerInterface
     */
    protected $coreSession;
    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $customerSession;
    /**
     * @var CustomerFactory
     */
    protected $customerFactory;
    /**
     * @var \Magetop\Advancepreview\Model\PreviewhistoryFactory
     */
    protected $previewhistoryFactory;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewhistoryFactory
     */
    protected $resPreviewhistoryFactory;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\Previewhistory\CollectionFactory
     */
    protected $colPreviewhistoryFactory;
    /**
     * @var \Magento\Framework\App\Http\Context
     */
    protected $httpContext;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewDiscount\CollectionFactory
     */
    protected $colPreviewDiscountFactory;
    protected $taxHelper;
    protected $colPreviewAdditionalFactory;

    public function __construct(
        Template\Context $context,
        \Magento\Framework\App\Http\Context $httpContext,
        \Magento\Framework\Pricing\Helper\Data $priceHelper,
        \Magetop\Advancepreview\Helper\Data $advancePreviewHelper,
        \Magento\Framework\Registry $registry,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Catalog\Model\ResourceModel\ProductFactory $resProductFactory,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $colProductFactory,
        \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,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewDiscount\CollectionFactory $colPreviewDiscountFactory,
        \Magento\Catalog\Helper\Data $taxHelper,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewAdditional\CollectionFactory $colPreviewAdditionalFactory,
        array $data = []
    )
    {
        parent::__construct($context, $priceHelper, $advancePreviewHelper, $data);
        $this->httpContext = $httpContext;
        $this->registry = $registry;
        $this->productFactory = $productFactory;
        $this->resProductFactory = $resProductFactory;
        $this->colProductFactory = $colProductFactory;
        $this->coreSession = $coreSession;
        $this->customerSession = $customerSession;
        $this->customerFactory = $customerFactory;
        $this->previewhistoryFactory = $previewhistoryFactory;
        $this->resPreviewhistoryFactory = $resPreviewhistoryFactory;
        $this->colPreviewhistoryFactory = $colPreviewhistoryFactory;
        $this->colPreviewDiscountFactory = $colPreviewDiscountFactory;
        $this->taxHelper = $taxHelper;
        $this->colPreviewAdditionalFactory = $colPreviewAdditionalFactory;
    }

    /**
     * @return array|float
     */
    public function getTierPrice() {
        $tierPrices = [];
        $_product = $this->getCurrentProduct();
        if($_product != null) {
            $tierPrices = $_product->getTierPrice();
        }
        return $tierPrices;
    }

    /**
     * @param $productId
     * @return array|float
     */
    public function getTierPriceByProductId($productId) {
        $tierPrices = [];
        $_product = $this->getProductById($productId);
        if($_product != null) {
            $tierPrices = $_product->getTierPrice();
        }
        return $tierPrices;
    }

    /**
     * @param int $productId
     * @return int|mixed|null
     */
    public function getCustomPreviewDiscount($productId = 0) {
        if($productId > 0) {
            $_product = $this->getProductById($productId);
        }
        else {
            $_product = $this->getCurrentProduct();
        }
        $previewDiscount = 0;
        if($_product && $_product->getId()) {
            $previewDiscount = $_product->getData('pcto_discount');
        }
        return $previewDiscount;
    }
    public function getProductTax($productId = 0) {
        if($productId > 0) {
            $_product = $this->getProductById($productId);
        }
        else {
            $_product = $this->getCurrentProduct();
        }
        $price = $this->taxHelper->getTaxPrice($_product, $_product->getFinalPrice(), true);
        return $price;

    }

    /**
     * @param array $tierPriecs
     * @param int $qty
     * @return int|mixed
     */
    public function getTierPriceItemByQty($tierPriecs = [], $qty = 0) {
        $price = 0;
//        print_r($tierPriecs);
        /*foreach ($tierPriecs as $tierPrice) {
            $tierQty = $tierPrice['price_qty'];
            if($qty <= $tierQty) {
                $price = $tierPrice['price'];
                break;
            }
        }*/
        for($i = 0; $i < count($tierPriecs); $i++) {
            if($i == 0 && $qty < $tierPriecs[0]['price_qty']) {
                $price = $tierPriecs[0]['price'];
                break;
            }
           if($i + 1 < count($tierPriecs)) {
               $currentTeir = $tierPriecs[$i];
               $nextTier = $tierPriecs[$i + 1];
               if($qty >= $currentTeir['price_qty'] && $qty < $nextTier['price_qty']) {
                   $price = $currentTeir['price'];
                   break;
               }
           }
        }
        return $price;
    }
    /**
     * @return \Magento\Catalog\Model\Product|null
     */
    public function getPreviewProductData() {
        return $this->getCurrentProduct();
    }
    public function getPreviewAdditionalOptions($productId = 0) {
        return $this->colPreviewAdditionalFactory->create()
            ->addFieldToSelect(array('*'))
            ->addFieldToFilter('product_id',$productId);
    }
    public function getAdditionPriceByIds($ids = []) {
        $price = 0;
        if(count($ids)) {
            $collection = $this->colPreviewAdditionalFactory->create()
                ->addFieldToSelect(array('price'))
                ->addFieldToFilter('addition_id', array('in'=>implode(',',$ids)));
            // echo (string)$collection->getSelect();   
            if($collection && $collection->getSize() > 0) {
                foreach ($collection as $item) {
                    $price += $item->getData('price');
                }
            }    
        }
        return $price;
    }

    /**
     * @param $product
     * @return array
     */
    public function checkPreviewProduct($product) {
        $lastOpens = $this->coreSession->getMagetopProductlastOpens();
        $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','DESC');
            $collection->setPageSize(6);
            if(count($collection)) {
                foreach ($collection as $item) {
                    $ipId = $item->getData('product_id');
                    $lastOpens[$ipId] = $item->getData('product_name');
                    if(count($lastOpens) > 6) {
                        break;
                    }
                }

            }
            $this->updateHistories($product, $customerId);
        }
        $opendProductIds = [];
        foreach ($lastOpens as $key1 => $lastOpen1) {
            if($key1 == $productId) {
                continue;
            }
            $opendProductIds[] = $key1;
        }
        $collection = null;
        $products = [];
        if(count($opendProductIds) > 0) {

//            $opendProductIds = array_reverse($opendProductIds);
            $txtOpendProductIds = implode(',',$opendProductIds);
            $collection = $this->colProductFactory->create()
                ->addAttributeToSelect(array('*'))
                ->addAttributeToFilter('entity_id',array('in'=>$txtOpendProductIds));
//            return $collection->getData();
            if($collection->getSize() > 0) {
                foreach ($opendProductIds as $opendProductId) {
                    foreach ($collection as $item) {
                        if($item->getId() == $opendProductId) {
                            $products[] = $item;
                            break;
                        }

                    }
                }

            }

        }
        return  $products;
    }

    /**
     * @param $product
     * @param $customerId
     */
    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) {

        }
    }

    /**
     * @param $customerId
     * @param $productId
     * @return int
     */
    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;

    }

    /**
     * @return int
     */
    public function getCustomerGroup() {
        $group = 0;
        if($this->checkIsLogin()) {
            $customerId =  $this->customerSession->getCustomerId();
            $customer = $this->customerFactory->create()->load($customerId);
            $group = $customer->getGroupId();

        }
        return $group;
    }

    /**
     * @return bool
     */
    protected function checkIsLogin() {
        $isLogin = false;
        if($this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH)) {
            $isLogin = true;
        }
        return $isLogin;
    }


    /**
     * @return Collection|null
     */
    public function getRerateProducts () {
        $product = $this->getCurrentProduct();
        $productRates  =  $product->getRelatedProducts();
        $rateIds = [];
        foreach ($productRates as $productRate) {
            $rateIds = $productRate->getId();
            if(count($rateIds) >= 6) {
                break;
            }
        }
        $collection = null;
        if(count($rateIds) > 0) {
            $rateIds = implode(',',$rateIds);
            $collection = $this->colProductFactory->create()
                ->addAttributeToFilter('entity_id',array('in'=>$rateIds));

        }
        return  $collection;
    }

    /**
     * @param int $productId
     * @return \Magento\Catalog\Model\Product
     */
    public function getProductById($productId = 0) {
        $product = $this->productFactory->create();
        $this->resProductFactory->create()->load($product, $productId);
        return $product;
    }

    /**
     * @param int $productId
     * @return \Magetop\Advancepreview\Model\ResourceModel\PreviewDiscount\Collection
     */
    public function getPreviewDiscounts($productId = 0) {
        $collection = $this->colPreviewDiscountFactory->create()
            ->addFieldToSelect(array('*'))
            ->addFieldToFilter('product_id',$productId);
        return $collection;
    }

    /**
     * @return \Magento\Catalog\Model\Product|null
     */
    protected function getCurrentProduct() {
        $_product = null;
        if($this->registry->registry('product')) {
            /** @var \Magento\Catalog\Model\Product $_product */
            $_product = $this->registry->registry('product');
        }
        return $_product;
    }

    /**
     * @return array
     */
    public function getPreviewAjaxUrls() {
        $urlExtraPrice = $this->getUrl('advance_preview/product/getExtraPrice');
        $urlExtraPrice = $this->formatAjaxUrl($urlExtraPrice);
        $uploadCustomDesign = $this->getUrl('advance_preview/product/uploadCustomDesign');
        $customDiscountUrl = $this->getUrl('advance_preview/product/UpdatePreviewDiscount');
        $tierPriceUrl = $this->getUrl('advance_preview/product/getTierPrices');
        return [
          'extra_price'=>$urlExtraPrice,
          'upload_custom_design'=>$uploadCustomDesign,
          'custom_discount_url'=>$customDiscountUrl,
          'custom_tierprice_url'=>$tierPriceUrl,
        ];
    }



}
