<?php


namespace Magetop\Advancepreview\Block\ReWrites;


use Magento\Framework\App\ObjectManager;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactoryInterface;

class HistoryCustom extends \Magento\Sales\Block\Order\History
{
    protected $orderCollectionFactory;
    protected $dailyShippingFactory;
    protected $colPreviewOrderItemsFactory;
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Sales\Model\Order\Config $orderConfig,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewDailyShipping\CollectionFactory $dailyShippingFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItems\CollectionFactory $colPreviewOrderItemsFactory,
        array $data = []
    )
    {
        parent::__construct($context, $orderCollectionFactory, $customerSession, $orderConfig, $data);
        $this->orderCollectionFactory = $orderCollectionFactory;
        $this->dailyShippingFactory = $dailyShippingFactory;
        $this->colPreviewOrderItemsFactory = $colPreviewOrderItemsFactory;
    }
    public function getOrders()
    {
        if (!($customerId = $this->_customerSession->getCustomerId())) {
            return false;
        }
        if (!$this->orders) {
            $incrmentId = $this->getRequest()->getParam('custom_increment_id','');
            $year = (int)$this->getRequest()->getParam('custom_year',0);
            $month = (int)$this->getRequest()->getParam('custom_month',0);
            $fromDate =  $this->getRequest()->getParam('from_date','');
            $fromDate = trim($fromDate);
            $toDate =  $this->getRequest()->getParam('to_date','');
            $toDate = trim($toDate);
//            $projectName = $this->getRequest()->getParam('project_name','');
            $incrmentId = trim($incrmentId);
            $this->orders = $this->getOrderCollectionFactory()->create($customerId)->addFieldToSelect(
                '*'
            )->addFieldToFilter(
                'status',
                ['in' => $this->_orderConfig->getVisibleOnFrontStatuses()]
            )->setOrder(
                'created_at',
                'desc'
            );
            if($incrmentId != '') {
                $tmpOrderIds = $this->getOrderIdByProjctName($incrmentId);
                if(count($tmpOrderIds)) {
                    $this->orders->addFieldToFilter('entity_id',array(
                        array('increment_id'=>$incrmentId),
                        array('in'=>$tmpOrderIds),
                    ));
                }
                else {
                    $this->orders->addFieldToFilter('increment_id',array('like'=>"%{$incrmentId}%"));
                }

            }
            if($year > 0) {
                $this->orders->getSelect()->where("YEAR(created_at) = {$year}");
            }
            if($month > 0) {
                $this->orders->getSelect()->where("MONTH(created_at) = {$month}");
            }

            if($fromDate != '' && $fromDate == $toDate) {
                $this->orders->getSelect()->where("DATE(created_at) = '{$fromDate}'");
            }
            elseif($fromDate != '' && $toDate != '') {
                $this->orders->getSelect()->where("created_at >= '{$fromDate}' AND created_at <= '{$toDate}'");
            }
        }
        return $this->orders;
    }
    public function getCustomOrderTotal(
        \Magento\Sales\Model\Order $order
    ) {
        $items = $order->getAllItems();
        $priceItem = 0;
        foreach ($items as $item) {
            $infoRequest = $item->getProductOptionByCode('info_buyRequest');
          /*  echo '<pre>';
                print_r($infoRequest);
            echo '</pre>';*/
            if (isset($infoRequest['txt_project_final_price'])) {
                $priceItem += $infoRequest['txt_project_final_price'];
            }
        }
//        echo $priceItem;
        return $priceItem;
    }
    public function getCustomProjectNameInOrder(
        \Magento\Sales\Model\Order $order
    ) {
        $items = $order->getAllItems();
        $priceItem = 0;
        $projectNames = '';
        $arProjectName = [];
        $arShippingDailies = [];
        $status = [];
        // $price = 0;
        $statusLabel = [
            'new'=>'New',
            'downloading'=>'Checking design by Myfitmix',
            'design_failed'=>'Design Failed',
            'design_approved'=>'Design Approved',
            'customer_reject'=>'Design Rejected by Customer',
            'design_full_approved'=>'Design Fully Approved',
            'process'=>'In progress',
            'shipping'=>'Ready for shipping/Production done',
            'shipped'=>'Shipped',
            'delivered'=>'Delivered',
        ];
        foreach ($items as $item) {

            /*$customPreviewItem = $this->getCustomPreviewOrderItem($item->getId());
            if(!$customPreviewItem) {
                continue;
            }
            $infoRequest =  $customPreviewItem->getData('info_request');
            $infoRequest  = trim($infoRequest) != '' ? (array)json_decode($infoRequest) : [];
            if(!isset($infoRequest['product'])) {
                continue;
            }*/
            $infoRequest = $item->getProductOptionByCode('info_buyRequest');
            $projectName = isset($infoRequest['custom_project_name']) ? trim($infoRequest['custom_project_name']) : '';
            $gernerateProjoectId = isset($infoRequest['text_project_generate']) ? $infoRequest['text_project_generate'] : 0;
            if($gernerateProjoectId > 0) {
                if($gernerateProjoectId > 1000) {
                    $gernerateProjoectId = $gernerateProjoectId;
                }
                else if($gernerateProjoectId > 100) {
                    $gernerateProjoectId = '0'.$gernerateProjoectId;
                }
                else if($gernerateProjoectId > 10) {
                    $gernerateProjoectId = '00'.$gernerateProjoectId;
                }
                else {
                    $gernerateProjoectId = '000'.$gernerateProjoectId;
                }
            }
            else {
                $gernerateProjoectId = '';
            }
            if($projectName == '') {
                continue;
            }
            if($gernerateProjoectId != '') {
                $projectName = $gernerateProjoectId . ' - ' .$projectName;
            }
            // $arProjectName[] = $projectName . $item->getId();
            $shippingId = isset($infoRequest['txt_daily_shipping']) ? (int)$infoRequest['txt_daily_shipping'] : 0;
            if($shippingId > 0) {
                $shippingDaily = $this->getDailyShippingById($shippingId);
                if($shippingDaily != null) {
                    $arShippingDailies[] =  $shippingDaily->getData('delivery_days');
                }
            }
            // echo '<pre>';
            //     print_r($infoRequest);
            // echo '</pre>';
            $arProjectName[] = $projectName;
            if (isset($infoRequest['txt_project_final_price'])) {
                $priceItem += $infoRequest['txt_project_final_price'];
            }
            // status
            $previewItem = $this->getCustomPreviewOrderItem($item->getId());
            $itemStatus = 'new';
            if($previewItem && $previewItem->getId()) {
                $itemStatus = $previewItem->getData('status');
            }
            $txtStatus = isset($statusLabel[$itemStatus]) ? $statusLabel[$itemStatus] : $itemStatus;
//            $txtStatus = $item->getName() . ' - ' . $txtStatus;
            $status[] = [
                'status'=>$txtStatus,
                'name'=>$item->getName()
            ];
        }
        $projectNames = count($arProjectName) ? implode(',',$arProjectName) : '';
        // $txtShippingDaily = count($arShippingDailies) ? implode(',',$arShippingDailies) : '';
//        echo $priceItem;
        return [
            'project_name'=>$arProjectName,
            'shipping_daily'=>$arShippingDailies,
            'price_item'=>$priceItem,
            'status'=>$status
        ];
    }
    private function getOrderCollectionFactory()
    {
        if ($this->orderCollectionFactory === null) {
            $this->orderCollectionFactory = ObjectManager::getInstance()->get(CollectionFactoryInterface::class);
        }
        return $this->orderCollectionFactory;
    }
    protected 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;
    }
    protected function getCustomPreviewOrderItem($itemId) {
        $collection = $this->colPreviewOrderItemsFactory->create()
            ->addFieldToFilter('item_id',$itemId);
        // echo (string)$collection->getSelect(). '--';
        return $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
    }
    protected function getOrderIdByProjctName($projectName) {
        $collection = $this->colPreviewOrderItemsFactory->create()
            ->addFieldToSelect(array('order_id'))
            ->addFieldToFilter('project_name',array('like'=>"%{$projectName}%"));
        $orderIds = [];
        if($collection && $collection->getSize() > 0) {
            foreach ($collection as $item) {
                $orderIds[] = $item->getData('order_id');
            }
        }
        return $orderIds;
    }
}
