<?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;


use Magento\Framework\View\Element\Template;

/**
 * Class PreviewCart
 * @package Magetop\Advancepreview\Block
 */
class PreviewCart extends  \Magetop\Advancepreview\Block\AdvancePreviewAbstract
{
    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $customerSession;
    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $customerFactory;
    /**
     * @var \Magento\Checkout\Model\Cart
     */
    protected $cart;
    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $productFactory;
    /**
     * @var \Magento\Catalog\Model\ResourceModel\ProductFactory
     */
    protected $resProductFactory;
    /**
     * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
     */
    protected $colProductFactory;
    /**
     * @var \Magento\Framework\App\Http\Context
     */
    protected $httpContext;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewDiscount\CollectionFactory
     */
    protected $colPreviewDiscountFactory;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewAdditional\CollectionFactory
     */
    protected $colPreviewAdditionalFactory;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewThree\CollectionFactory
     */
    protected $colPreviewThreeFactory;
    protected $addressFactory;
    protected $dailyShippingFactory;


    public function __construct(
        Template\Context $context,
        \Magento\Framework\Pricing\Helper\Data $priceHelper,
        \Magetop\Advancepreview\Helper\Data $advancePreviewHelper,
        \Magento\Framework\App\Http\Context $httpContext,
        \Magento\Checkout\Model\Cart $cart,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Catalog\Model\ResourceModel\ProductFactory $resProductFactory,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $colProductFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewDiscount\CollectionFactory $colPreviewDiscountFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewAdditional\CollectionFactory $colPreviewAdditionalFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewThree\CollectionFactory $colPreviewThreeFactory,
        \Magento\Customer\Model\AddressFactory $addressFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewDailyShipping\CollectionFactory $dailyShippingFactory,
        array $data = []
    )
    {
        parent::__construct($context, $priceHelper, $advancePreviewHelper, $data);
        $this->cart = $cart;
        $this->customerSession = $customerSession;
        $this->customerFactory = $customerFactory;

        $this->productFactory = $productFactory;
        $this->resProductFactory = $resProductFactory;
        $this->colProductFactory = $colProductFactory;
        $this->httpContext = $httpContext;
        $this->colPreviewDiscountFactory = $colPreviewDiscountFactory;
        $this->colPreviewAdditionalFactory = $colPreviewAdditionalFactory;
        $this->colPreviewThreeFactory = $colPreviewThreeFactory;
        $this->addressFactory = $addressFactory;
        $this->dailyShippingFactory = $dailyShippingFactory;
    }

    /**
     * @return array|\Magento\Eav\Model\Entity\Collection\AbstractCollection|null
     */
    public function getAllItemInCart() {
        $items = null;
        if($this->cart->getItems()) {
            $items = $this->cart->getItems();
        }
        return $items;
    }

    /**
     * @param int $productId
     * @return \Magetop\Advancepreview\Model\ResourceModel\PreviewThree\Collection
     */
    public function getPreviewByProductId($productId = 0) {
        $collection = $this->colPreviewThreeFactory->create()
            ->addFieldToSelect('*')
            ->addFieldToFilter('product_id',$productId)
            ->setOrder('position','ASC');
//        echo (string)$collection->getSelect();
        return $collection;
    }


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

    /**
     * @param \Magento\Quote\Model\Quote\Item $item
     * @return array
     */
    public function getItemInforestion($item) {
        $customOptionsRequest = [];
        if($item) {
            $customOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
            if(isset($customOptions['info_buyRequest'])) {
                $customOptionsRequest = $customOptions['info_buyRequest'];
            }
        }

        return $customOptionsRequest;
    }


    public function getCustomTierOurPrice($product, $price = 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;

    }

    public function getAddDiscountAdditionAllPrice($price, $product) {
//        $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;
    }

    /**
     * @param array $parmaOptions
     * @param int $productId
     * @return int
     */
    public function getAdditionalOptionPrice($parmaOptions = [], $productId = 0, $ourprice=0) {
        $collection = $this->getPreviewAdditionalOptions($productId);
        $price = 0;
        if($collection && $collection->getSize() > 0) {
            foreach ($collection as $item) {
                if(in_array($item->getId(), $parmaOptions)) {
                    $dbprice = $item->getData('price');
                    $title = strtolower($item->getData('title'));
                    if(str_contains($title,'5c transparent')){
                        $price+=$ourprice*$dbprice;
                    }
                    else{
                        $price +=$dbprice;
                    }
                }
            }
        }

        return  $price;
    }


    public function checkProductEnable3D($product) {
//        $_product = $this->getProductById($productId);
        $isEnable = false;
        if($product && $product->getData('pcto_is_3d')) {
            $isEnable = true;
        }
        return $isEnable;
    }

    /**
     * @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\PreviewAdditional\Collection
     */
    public function getPreviewAdditionalOptions($productId = 0) {
        return $this->colPreviewAdditionalFactory->create()
            ->addFieldToSelect(array('*'))
            ->addFieldToFilter('product_id',$productId);
    }

    public function getPreviewAdditionalOptionLabels($ids) {
        $collection = $this->colPreviewAdditionalFactory->create()
            ->addFieldToSelect(array('title'))
            ->addFieldToFilter('addition_id',array('in'=>$ids));
        $lables = [];
        foreach ($collection as $item) {
            $lables[] = __(trim($item->getData('title')));
        }
        return count($lables) ? implode(', ',$lables) : '';
    }

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

    /**
     * @param array $tierPriecs
     * @param int $qty
     * @return int|mixed
     */
    public function getTierPriceItemByQty($tierPriecs = [], $qty = 0) {
        $price = 0;
        $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;
    }
    public function getTierPriceByProductId($product) {
        $tierPrices = [];
//        $_product = $this->getProductById($productId);
        if($product != null) {
            $tierPrices = $product->getTierPrice();
        }
        return $tierPrices;
    }


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

    /**
     * @return array
     */
    public function getCartAjaxUrls() {
        $customPlaceUrl = $this->getUrl('advance_preview/checkout/buyWithout');
        return [
            'place_url'=>$customPlaceUrl,
        ];
    }
    public function getCustomerDefaultAddress() {
        $customerId = $this->getCustomerId();
        $address = [];
        if($customerId > 0) {
            $customer = $this->customerFactory->create()->load($customerId);
            $billingAddressId = $customer->getDefaultBilling();
            $billingAddress = $this->addressFactory->create()->load($billingAddressId);
            $shippingAddressId = $customer->getDefaultShipping();
            $shippingAddress = $this->addressFactory->create()->load($shippingAddressId);
            if($billingAddress != null) {
                $address['billing'] = $billingAddress;
            }
            if($shippingAddress != null) {
                $address['shipping'] = $shippingAddress;
            }
        }
        return $address;


    }
    protected function getCustomerId() {
        $customerId = 0;
        if($this->checkIsLogin()) {
            $customerId =  $this->customerSession->getCustomerId();


        }
        return $customerId;
    }
    public function getDailyShippingById($dailyId = 0) {
        if($dailyId > 0) {
            $collection = $this->dailyShippingFactory->create()
//                ->addFieldToSelect(array('*'))
                ->addFieldToFilter('daily_shipping_id',$dailyId);
            return $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
        }
        return  null;
    }


}
