<?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\Observer\Frontend;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class ChangePrice implements ObserverInterface
{
    protected $productFactory;
    protected $resProductFactory;
    protected $optionCollection;
    protected $priceHelper;
    protected $filesystem;
    protected $httpContext;
    protected $customerSession;
    protected $customerFactory;
    protected $colPreviewDiscountFactory;
    protected $colPreviewAdditionalFactory;
    protected $projectCartItemsFactory;
    protected $resProjectCartItemsFactory;
    protected $_wishlistProviderInterface;
    protected $_itemFactory;

    function __construct(
        \Magento\Framework\App\Http\Context $httpContext,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Catalog\Model\ResourceModel\ProductFactory $resProductFactory,
        \Magento\Catalog\Model\ResourceModel\Product\Option\CollectionFactory $optionCollection,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewDiscount\CollectionFactory $colPreviewDiscountFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewAdditional\CollectionFactory $colPreviewAdditionalFactory,
        \Magetop\Advancepreview\Model\ProjectCartItemsFactory $projectCartItemsFactory,
        \Magetop\Advancepreview\Model\ResourceModel\ProjectCartItemsFactory $resProjectCartItemsFactory,
        \Magento\Wishlist\Controller\WishlistProviderInterface $wishlistProviderInterface,
        \Magento\Wishlist\Model\ItemFactory $itemFactory
    )
    {
        $this->productFactory = $productFactory;
        $this->resProductFactory = $resProductFactory;
        $this->optionCollection = $optionCollection;
        $this->filesystem = $filesystem;
        $this->httpContext = $httpContext;
        $this->customerSession = $customerSession;
        $this->customerFactory = $customerFactory;
        $this->colPreviewDiscountFactory = $colPreviewDiscountFactory;
        $this->colPreviewAdditionalFactory = $colPreviewAdditionalFactory;
        $this->projectCartItemsFactory = $projectCartItemsFactory;
        $this->resProjectCartItemsFactory = $resProjectCartItemsFactory;
        $this->_wishlistProviderInterface = $wishlistProviderInterface;
        $this->_itemFactory = $itemFactory;
    }
    public function execute(Observer $observer)
    {
        /** @var \Magento\Quote\Model\Quote\Item $quoteItem*/
        $quoteItem = $observer->getEvent()->getQuoteItem();
        $customOptions = $quoteItem->getProduct()->getTypeInstance(true)->getOrderOptions($quoteItem->getProduct());
//        $product = $quoteItem->getProduct();
        $productId = $quoteItem->getProduct()->getId();
        $customOptionsRequest = $customOptions['info_buyRequest'];
        $designType = isset($customOptionsRequest['txt_custom_preview_design_type']) ? $customOptionsRequest['txt_custom_preview_design_type'] : 0;
        $ourPrice = isset($customOptionsRequest['txt_preview_our_price']) ? $customOptionsRequest['txt_preview_our_price'] : 0;
       /* $customDiscounts = $this->getPreviewDiscounts($productId);
        if($customDiscounts && $customDiscounts->getSize() > 0) {
            $i = 0;
            foreach ($customDiscounts as $customDiscount) {
                if($i == 0) {
                    $i++;
                    continue;
                }
                $priceDiscountItem = $customDiscount->getData('discount_price');
                if($designType == 1 && $i == 1) {
                    $paramAdditionalOptions = isset($customOptionsRequest['preview_additional_options']) ? $customOptionsRequest['preview_additional_options'] : [];
                    $priceDiscountItem += $this->getAdditionalOptionPrice($paramAdditionalOptions, $productId);
                }
                $ourPrice += $this->getAddDiscountAdditionAllPrice($priceDiscountItem, $productId);
                $i++;
            }
        }*/
//        $ourPrice = 0;
        if(isset($customOptionsRequest['text_project_generate']) && (int)$customOptionsRequest['text_project_generate'] > 0) {
            $this->saveProjectCart($customOptionsRequest['text_project_generate']);
        }
        $offerId = isset($customOptionsRequest['custom_offer_id']) ? (int)$customOptionsRequest['custom_offer_id'] : 0;
        if($offerId > 0) {
            $this->deleteItemFromWishlist($offerId);
        }
        $quoteItem->setCustomPrice($ourPrice);
        $quoteItem->setOriginalCustomPrice($ourPrice);
        $quoteItem->getProduct()->setIsSuperMode(true);
        $quoteItem = $observer->getEvent()->getQuoteItem();
       // $customOptions = $quoteItem->getProduct()->getTypeInstance(true)->getOrderOptions($quoteItem->getProduct());
//        $product = $quoteItem->getProduct();
        $productId = $quoteItem->getProduct()->getId();
        //$customOptionsRequest = $customOptions['info_buyRequest'];

        /* $qty = isset($customOptionsRequest['mgt_custom_qty']) ? (int)$customOptionsRequest['mgt_custom_qty'] : 0;
         $finalPrice = isset($customOptionsRequest['txt_project_final_price']) ? (float)$customOptionsRequest['txt_project_final_price'] : 0;
         if($qty > 0 && $finalPrice > 0) {
             $ourPrice = $finalPrice / $qty;
             $quoteItem->setCustomPrice($ourPrice);
             $quoteItem->setOriginalCustomPrice($ourPrice);
             $quoteItem->getProduct()->setIsSuperMode(true);
         }*/
        return $this;

    }
    protected function saveProjectCart($projectId) {
        $dataSave = array(
            'project_item_id'=>$projectId,
            'customer_id'=>0,
            'created_at'=>date('Y-m-d H:i:s')
        );
        $model = $this->projectCartItemsFactory->create()->setData($dataSave);
        try {
            $this->resProjectCartItemsFactory->create()->save($model);
        }
        catch (\Exception $exception) {

        }
    }
    protected function deleteItemFromWishlist($itemId) {
        $item = $this->_itemFactory->create()->load($itemId);
        if (!$item->getId()) {
//            throw new NotFoundException(__('Item not found.'));
        }
        $wishlist = $this->_wishlistProviderInterface->getWishlist($item->getWishlistId());
        if (!$wishlist) {
//            throw new NotFoundException(__('Wishlist not found.'));
        }
        try {
            $item->delete();
            $wishlist->save();
        } catch (\Exception $e) {

        }
    }

    protected function getCustomTierOurPrice($price = 0, $productId = 0) {
        $customerGroup = $this->getCustomerGroup();
        if($customerGroup > 1) {
            $product = $this->getProductById($productId);
            if($product) {
                $discount = $product->getData('pcto_discount');
                if($discount > 0) {
                    $price -= ($price * $discount) / 100;
                }
            }
        }
        return $price;

    }
    protected function getProductById($productId = 0) {
        $product = $this->productFactory->create();
        $this->resProductFactory->create()->load($product, $productId);
        return $product;
    }
    protected function getCustomerGroup() {
        $group = 0;
        if($this->checkIsLogin()) {
            $customerId =  $this->customerSession->getCustomerId();
            $customer = $this->customerFactory->create()->load($customerId);
            $group = $customer->getGroupId();

        }
        return $group;
    }
    protected function checkIsLogin() {
        $isLogin = false;
        if($this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH)) {
            $isLogin = true;
        }
        return $isLogin;
    }
    protected function getPreviewDiscounts($productId = 0) {
        $collection = $this->colPreviewDiscountFactory->create()
            ->addFieldToSelect(array('*'))
            ->addFieldToFilter('product_id',$productId);
        return $collection;
    }
    protected function getAdditionalOptionPrice($parmaOptions = [], $productId = 0) {
        $collection = $this->getPreviewAdditionalOptions($productId);
        $price = 0;
        if($collection && $collection->getSize() > 0) {
            foreach ($collection as $item) {
                if(in_array($item->getId(), $parmaOptions)) {
                    $price += $item->getData('price');
                }
            }
        }

        return  $price;
    }
    public function getPreviewAdditionalOptions($productId = 0) {
        return $this->colPreviewAdditionalFactory->create()
            ->addFieldToSelect(array('*'))
            ->addFieldToFilter('product_id',$productId);
    }
    public function getAddDiscountAdditionAllPrice($price, $productId) {
        $product = $this->getProductById($productId);
        $priceDiscount = $price;
        $customerGroup = $this->getCustomerGroup();
        if($customerGroup > 1) {
            if($product) {
                $discount = $product->getData('pcto_discount');
                if($discount > 0) {
                    $priceDiscount -= ($price * $discount) / 100;
                }
            }
        }

        return $priceDiscount;
    }

}
