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


use Magento\Framework\View\Element\Template;

class CustomOrderView extends  \Magetop\Advancepreview\Block\AdvancePreviewAbstract
{
    /**
     * @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;
    protected $colPreviewOrderItemsFactory;
    public function __construct(
        Template\Context $context,
        \Magento\Framework\Pricing\Helper\Data $priceHelper,
        \Magetop\Advancepreview\Helper\Data $advancePreviewHelper,
        \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,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItems\CollectionFactory $colPreviewOrderItemsFactory,
        array $data = []
    )
    {
        parent::__construct($context, $priceHelper, $advancePreviewHelper, $data);
        $this->customerFactory = $customerFactory;
        $this->productFactory = $productFactory;
        $this->resProductFactory = $resProductFactory;
        $this->colProductFactory = $colProductFactory;
        $this->colPreviewDiscountFactory = $colPreviewDiscountFactory;
        $this->colPreviewAdditionalFactory = $colPreviewAdditionalFactory;
        $this->colPreviewThreeFactory = $colPreviewThreeFactory;
        $this->addressFactory = $addressFactory;
        $this->dailyShippingFactory = $dailyShippingFactory;
        $this->colPreviewOrderItemsFactory = $colPreviewOrderItemsFactory;
    }
    /**
     * @param \Magento\Sales\Model\Order\Item $item
     * @return array|null
     */
    public function getCustomItemDetail(
        \Magento\Sales\Model\Order\Item $item
    ) {
         $infoRequest = $item->getProductOptionByCode('info_buyRequest');
       /* $itemId = $item->getId();
        $previewOrderItem = $this->getPreviewItemByItemId($itemId);
        $infoRequest = [];
        if($previewOrderItem && $previewOrderItem->getId()) {
            $txt = $previewOrderItem->getData('info_request');
            if(trim($txt) != '') {
                $infoRequest = (array)json_decode($txt);
            }
        }*/
        return $infoRequest;
    }
    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;
    }
    public function getCustomTierOurPrice($product, $price = 0, $customerId = 0) {

        $customerGroup = $this->getCustomerGroup($customerId);
        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, $customerId = 0,$requestOption = null) {
//        $product = $this->getProductById($productId);
        $priceDiscount = $price;
        $customerGroup = $this->getCustomerGroup($customerId);
        if($customerGroup > 1) {
            if($product) {
                $discount = $product->getData('pcto_discount');
                if($requestOption && isset($requestOption['txt_pcto_discount'])){
                    $discount = $requestOption['txt_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,$requestOptions = null) {
        $collection = $this->getPreviewAdditionalOptions($productId);
        $price = 0;
        if($collection && $collection->getSize() > 0) {
            foreach ($collection as $item) {
                if(in_array($item->getId(), $parmaOptions)) {
                    $title = trim($item->getData('title'));
                    $dbprice = $item->getData('price');
                    if($requestOptions && isset($requestOptions['ict_addition_price'][$item->getId()])){
                        $dbprice = $requestOptions['ict_addition_price'][$item->getId()];
                    }
                    $titles[] = __($title);
                    if (str_contains(strtolower($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;
    }
    public function getProductById($productId = 0) {
        $product = $this->productFactory->create();
        $this->resProductFactory->create()->load($product, $productId);
        return $product;
    }
    public function getPreviewAdditionalOptions($productId = 0) {
        return $this->colPreviewAdditionalFactory->create()
            ->addFieldToSelect(array('*'))
            ->addFieldToFilter('product_id',$productId);
    }
    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 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) : '';
    }
    public function getTierPriceByProductId($product) {
        $tierPrices = [];
//        $_product = $this->getProductById($productId);
        if($product != null) {
            $tierPrices = $product->getTierPrice();
        }
        return $tierPrices;
    }

    public function getCustomerGroup($customerId = 0) {
        $group = 0;
//        $customerId =  $this->customerSession->getCustomerId();
        $customer = $this->customerFactory->create()->load($customerId);
        $group = $customer->getGroupId();
        return $group;
    }
    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;
    }
    public function getPreviewItemByItemId($itemId = 0) {
        $collection = $this->colPreviewOrderItemsFactory->create()
            ->addFieldToFilter('item_id',$itemId);
        $previewItem = $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
        return $previewItem;

    }
    public function getAjaxUrls() {
        $reUploadDesignUrl = $this->getUrl('advance_preview/order/ReUploadCustomDesign');
        $updateCustomItemPrint = $this->getUrl('advance_preview/order/updateCustomItemPrint');
        return [
            're_upload_design_url'=>$reUploadDesignUrl,
            'update_item_status'=>$updateCustomItemPrint,
        ];
    }
}
