<?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;
    protected $colPreviewThreeFactory;
    protected $file;
    protected $cart;
    protected $dailyShippingFactory;
    protected $wishlistOptionFactory;
    protected $orderItemRepository;
    protected $colPreviewOrderItemsFactory;
    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\Filesystem\Driver\File $file,
        \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,
        \Magento\Checkout\Model\Cart $cart,
        \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,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewThree\CollectionFactory $colPreviewThreeFactory,
         \Magetop\Advancepreview\Model\ResourceModel\PreviewDailyShipping\CollectionFactory $dailyShippingFactory,
        \Magento\Wishlist\Model\ResourceModel\Item\Option\CollectionFactory $wishlistOptionFactory,
        \Magento\Sales\Api\OrderItemRepositoryInterface $orderItemRepository,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItems\CollectionFactory $colPreviewOrderItemsFactory,
        array $data = []
    )
    {
        parent::__construct($context, $priceHelper, $advancePreviewHelper, $data);
        $this->httpContext = $httpContext;
        $this->registry = $registry;
        $this->file = $file;
        $this->productFactory = $productFactory;
        $this->resProductFactory = $resProductFactory;
        $this->colProductFactory = $colProductFactory;
        $this->coreSession = $coreSession;
        $this->customerSession = $customerSession;
        $this->customerFactory = $customerFactory;
        $this->cart = $cart;
        $this->previewhistoryFactory = $previewhistoryFactory;
        $this->resPreviewhistoryFactory = $resPreviewhistoryFactory;
        $this->colPreviewhistoryFactory = $colPreviewhistoryFactory;
        $this->colPreviewDiscountFactory = $colPreviewDiscountFactory;
        $this->taxHelper = $taxHelper;
        $this->colPreviewAdditionalFactory = $colPreviewAdditionalFactory;
        $this->colPreviewThreeFactory = $colPreviewThreeFactory;
        $this->dailyShippingFactory = $dailyShippingFactory;
        $this->wishlistOptionFactory = $wishlistOptionFactory;
        $this->orderItemRepository = $orderItemRepository;
        $this->colPreviewOrderItemsFactory = $colPreviewOrderItemsFactory;
    }

    /**
     * @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;

    }
    public function getPreviewItemRequest() {
        $params = [
            'item'=>0,
            'extra_option_all_price'=>0,
            'txt_preview_type'=>0,
            'mgt_custom_qty'=>1,
            'final_price_discount_pro'=>0,
            'custom_project_name'=>'',
            'txt_custom_preview_design_type'=>0,
            'txt_preview_selected'=>0,
            'qty'=>0,
            'text_project_generate'=>0,
            'txt_daily_shipping'=>0,
            'preview_additional_options'=>[],
            'customer_upload_design'=>''
        ];
        $itemId = (int)$this->getRequest()->getParam('id',0);
        $offerId = (int)$this->getRequest()->getParam('offer_id',0);
        if($this->getRequest()->getActionName() == 'configure' && $itemId > 0) {
            $items = $this->cart->getQuote()->getAllItems();
            if(count($items)) {
                /** @var \Magento\Quote\Model\Quote\Item $item */
                foreach ($items as $item) {
                    if($item->getItemId() == $itemId) {
                        $params = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
                        $params = isset($params['info_buyRequest']) ? $params['info_buyRequest'] : array();
                        break;
                    }
                }
            }
        }
        else if($offerId > 0) {
            $wishlistOption = $this->getWishlistOption($offerId);
            if(count($wishlistOption)) {
                $params = $wishlistOption;
            }
        }
        return $params;
    }

    /**
     * @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;
            }
        }*/
        $lastIndex = count($tierPriecs) ? count($tierPriecs) - 1 : 0;
        $lastItem = isset($tierPriecs[$lastIndex]) ? $tierPriecs[$lastIndex] : [];
        if($lastIndex > 0 && isset($lastItem['price_qty']) && $qty >= $lastItem['price_qty']) {
            $price = $lastItem['price'];
        }
        else {
            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 getPreviewByProductId($productId = 0) {
        $collection = $this->colPreviewThreeFactory->create()
            ->addFieldToSelect('*')
            ->addFieldToFilter('product_id',$productId)
            ->setOrder('is_default','ASC')
            ->setOrder('position','ASC');
//        echo (string)$collection->getSelect();
        return $collection;
    }
    public function getPreviewById($previewId = 0) {
        $collection = $this->colPreviewThreeFactory->create()
            ->addFieldToSelect('*')
            ->addFieldToFilter('threed_id',$previewId);
//        echo (string)$collection->getSelect();
        return $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
    }
    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();
            
            if($group > 1) {
                if($group == 4){
                    if(\Magento\Framework\App\ObjectManager::getInstance()->create('Magetop\Marketplace\Model\Sellers')->getCollection()->addFieldToFilter('user_id', $customerId)->getFirstItem()->getUserstatus() == 0){
                        $group = 1;
                    }
                }
            }
        }
        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');
        $addWishlistUrl = $this->getUrl('advance_preview/product/addProductToWishlist');
        $generateProjectId = $this->getUrl('advance_preview/product/GenerateProjectName');
        $previewOptionsUrl = $this->getUrl('advance_preview/product/getPreviewOptions');
        $reUploadDesignUrl = $this->getUrl('advance_preview/order/ReUploadCustomDesign');
        $saveNewDesignUrl = $this->getUrl('advance_preview/order/saveNewDesign');
        $cloneDesignUrl = $this->getUrl('advance_preview/product/cloneDesign');
        return [
          'extra_price'=>$urlExtraPrice,
          'upload_custom_design'=>$uploadCustomDesign,
          'custom_discount_url'=>$customDiscountUrl,
          'custom_tierprice_url'=>$tierPriceUrl,
          'add_to_wishlist'=>$addWishlistUrl,
          'generate_project_id'=>$generateProjectId,
          'preview_option_url'=>$previewOptionsUrl,
          're_upload_design_url'=>$reUploadDesignUrl,
          'clone_design_url'=>$cloneDesignUrl,
          'save_new_design_url'=>$saveNewDesignUrl,
        ];
    }

    /**
     * @param $productId
     * @return \Magetop\Advancepreview\Model\ResourceModel\PreviewDailyShipping\Collection
     */
    public function getDailyShipping($productId) {
        return $this->dailyShippingFactory->create()
            ->addFieldToFilter('product_id',$productId);
    }
    protected function getWishlistOption($wItemId) {
        $collection = $this->wishlistOptionFactory->create()
            ->addFieldToSelect(array('value'))
            ->addFieldToFilter('wishlist_item_id',$wItemId)
            ->addFieldToFilter('code','info_buyRequest');
        $infoBuyRequest = $collection && $collection->getSize() > 0 ? $collection->getFirstItem()->getData('value') : '';
        $infoBuyRequest = $infoBuyRequest != '' ? (array)json_decode($infoBuyRequest) : [];
        if(count($infoBuyRequest)) {
            $infoBuyRequest['is_offer'] = 1;
            $infoBuyRequest['offer_id'] = $wItemId;
        }
        return $infoBuyRequest;
    }

    /**
     * @param int $dailyId
     * @return \Magento\Framework\DataObject|null
     */
    public function getDailyShippingById($dailyId = 0) {
        if($dailyId > 0) {
            $collection = $this->dailyShippingFactory->create()
                ->addFieldToFilter('daily_shipping_id',$dailyId);
            return $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
        }
       return  null;
    }
    public function getSamplePdfFile($productId) {
        $mediaPath = $this->getMediaDirectory()->getAbsolutePath();
//        if(is_f)
        $image = '';
        if($this->file->isExists($mediaPath.'advancepreview/custom_previews/product_id_'.$productId.'/own_pdf/own_design.pdf')) {
            $image = $this->getMediaUrl().'advancepreview/custom_previews/product_id_'.$productId.'/own_pdf/own_design.pdf';
        }
        return $image;
    }
    public function getSampleAiFile($productId) {
        $mediaPath = $this->getMediaDirectory()->getAbsolutePath();
//        if(is_f)
        $image = '';
        if($this->file->isExists($mediaPath.'advancepreview/custom_previews/product_id_'.$productId.'/own_ai/own_design.ai')) {
            $image = $this->getMediaUrl().'advancepreview/custom_previews/product_id_'.$productId.'/own_ai/own_design.ai';
        }
        return $image;
    }
    public function getRefererUrl() {
        $url  = $this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]);
        return $this->getUrl('customer/account/login', array('referer' => base64_encode($url)));
    }
    public function getOrderItem($itemId)
    {
        /** @var \Magento\Sales\Model\Order\Item $itemCollection*/
        $item = null;
        try {
            $item = $this->orderItemRepository->get($itemId);
        }
        catch (\Exception $exception) {

        }
        return $item;
//        return  $item->getProductOptionByCode('info_buyRequest');
    }
    public function getPreviewItemByItemId($itemId = 0) {
        $collection = $this->colPreviewOrderItemsFactory->create()
            ->addFieldToSelect(array('*'))
            ->addFieldToFilter('item_id',$itemId);
        $previewItem = $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
        return $previewItem;

    }
}
