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

use Magento\Backend\Block\Template;
use Magento\Directory\Helper\Data as DirectoryHelper;
use Magento\Framework\Json\Helper\Data as JsonHelper;

class CustomItems extends Template
{
    /**
     * @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 $priceHelper;
    protected $colPreviewOrderItemsFactory;
    protected $previewHelper;
    protected $_storeManager ;
    function __construct(
        Template\Context $context,
        \Magento\Framework\Pricing\Helper\Data $priceHelper,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \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,
        \Magetop\Advancepreview\Helper\Data $advancePreviewHelper,
        array $data = [], JsonHelper $jsonHelper = null,
        DirectoryHelper $directoryHelper = null
    )
    {
        parent::__construct($context, $data, $jsonHelper, $directoryHelper);
        $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->priceHelper = $priceHelper;
        $this->colPreviewOrderItemsFactory = $colPreviewOrderItemsFactory;
        $this->previewHelper = $advancePreviewHelper;
        $this->_storeManager = $storeManager;
    }

    /**
     * @param \Magento\Sales\Model\Order\Item $item
     * @return array|null
     */
    public function getCustomItemDetail(
        \Magento\Sales\Model\Order\Item $item
    ) {
         $infoRequest = $item->getProductOptionByCode('info_buyRequest');
        // return $infoRequest;
      /*  $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)) {
                    $dbprice =$item->getData('price');
                    if($requestOptions && isset($requestOptions['ict_addition_price'][$item->getId()])){
                        $dbprice = $requestOptions['ict_addition_price'][$item->getId()];
                    }
                    $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;
    }
    public function getProductById($productId = 0, $storeId = 0 ) {
        // $product = $this->productFactory->create();
        // $this->resProductFactory->create()->load($product, $productId);

        $collection = $this->colProductFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->addAttributeToFilter('entity_id', array(
            'in' => array($productId))
        );
        if($storeId !=0){
            $collection->addStoreFilter($storeId); 
        }
        $product = $collection->getFirstItem();
        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[] = $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('amount','delivery_days'))
                ->addFieldToFilter('daily_shipping_id',$dailyId);
            return $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
        }
        return  null;
    }

    /**
     * @param int $itemId
     * @return \Magento\Framework\DataObject|null
     */
    public function getPreviewItemByItemId($itemId = 0) {
        $collection = $this->colPreviewOrderItemsFactory->create()
            ->addFieldToFilter('item_id',$itemId);
        $previewItem = $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
        return $previewItem;

    }
    function convertNumberToPrice($price) {
        return $this->priceHelper->currency($price,true,false);
    }
    public function getAdminAjaxUrl() {
        $updateStatusUrl = $this->previewHelper->getOpdAdminUrl('advancepreview/order/updateItemStatus');
        $updateCustomDesignPrint = $this->previewHelper->getOpdAdminUrl('advancepreview/order/updateCustomDesignPrint');
        $uploadProofUrl = $this->previewHelper->getOpdAdminUrl('advancepreview/order/uploadProof');
        $trackingItemUrl = $this->previewHelper->getOpdAdminUrl('advancepreview/orderTracking/Items');
        $editTrackingUrl = $this->previewHelper->getOpdAdminUrl('advancepreview/orderTracking/Edit');
        $saveTrackingUrl = $this->previewHelper->getOpdAdminUrl('advancepreview/orderTracking/save');
        $deleteTrackingUrl = $this->previewHelper->getOpdAdminUrl('advancepreview/orderTracking/dellItem');
        $updatePaidStatus = $this->previewHelper->getOpdAdminUrl('advancepreview/order/updatePaidStatus');
        return [
            'update_status_url'=>$updateStatusUrl,
            'update_custom_design_print'=>$updateCustomDesignPrint,
            'uplolad_proofUrl'=>$uploadProofUrl,
            'tracking_items_url'=>$trackingItemUrl,
            'tracking_edit_url'=>$editTrackingUrl,
            'tracking_save_url'=>$saveTrackingUrl,
            'tracking_dell_url'=>$deleteTrackingUrl,
            'update_paid_status'=>$updatePaidStatus,
        ];

    }
    public function getMediaUrl() {
        return $this ->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA );

    }
}
