<?php


namespace Magetop\Advancepreview\Block\ReWrites;


use Magento\Customer\Model\Session;
use Magento\Framework\View\Element\Template\Context;
use Magento\Sales\Model\Order\Config;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
use Magento\Store\Model\StoreManagerInterface;

class RecentCustom extends \Magento\Sales\Block\Order\Recent
{
    protected $dailyShippingFactory;
    protected $colPreviewOrderItemsFactory;
    public function __construct(
        Context $context,
        CollectionFactory $orderCollectionFactory,
        Session $customerSession,
        Config $orderConfig,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewDailyShipping\CollectionFactory $dailyShippingFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItems\CollectionFactory $colPreviewOrderItemsFactory,
        array $data = [],
        StoreManagerInterface $storeManager = null
    )
    {
        parent::__construct($context, $orderCollectionFactory, $customerSession, $orderConfig, $data, $storeManager);
        $this->dailyShippingFactory = $dailyShippingFactory;
        $this->colPreviewOrderItemsFactory = $colPreviewOrderItemsFactory;
    }
    public function getCustomProjectNameInOrder(
        \Magento\Sales\Model\Order $order
    ) {
        $items = $order->getAllItems();
        $priceItem = 0;
        $projectNames = '';
        $arProjectName = [];
        $arShippingDailies = [];
        $status = [];
        // $price = 0;
        $statusLabelsstandard = [
            'new'=>'New',
            'process'=>'In progress',
            'shipping'=>'Ready for shipping/Production done',
            'shipped'=>'Shipped'
        ];
        $statusLabel = [
            'new'=>'New – design uploaded, please wait for proof',
            'downloading'=>'Checking design by Myfitmix',
            'design_failed'=>'Design Failed, please upload a new design',
            'design_approved'=>'Design Approved',
            'customer_reject'=>'Proof Rejected by Customer',
            'design_full_approved'=>'Design Fully Approved',
            'process'=>'In progress',
            'shipping'=>'Ready for shipping/Production done',
            'shipped'=>'Shipped',
            'delivered'=>'Delivered',
        ];
        $statusCustomNoPrintLabels = [
            'new'=>'New – please upload design',
            'downloading'=>'Checking design by Myfitmix',
            'design_failed'=>'Design Failed, please upload a new design',
            'design_approved'=>'Design Approved',
            'customer_reject'=>'Proof 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) {

            $infoRequest = $item->getProductOptionByCode('info_buyRequest');
            $designType = $infoRequest['txt_custom_preview_design_type'];

            $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;
            }
            /* Changed by Nalini*/
            // 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());
            $isNewProof = 0;
            $isNewProof = $previewItem->getData('is_new_proof');
            $adminUploadFile = $previewItem->getData('admin_upload_design');

            $itemStatus = 'new';
            if($previewItem && $previewItem->getId()) {
                $itemStatus = $previewItem->getData('status');
            }
            //$txtStatus = isset($statusLabel[$itemStatus]) ? $statusLabel[$itemStatus] : $itemStatus;

            if ($designType == 0) {
                $txtStatus = isset($statusLabelsstandard[$itemStatus]) ? $statusLabelsstandard[$itemStatus] : $itemStatus;
            }else if ($previewItem->getCustomDesign() == '') {
                $txtStatus = isset($statusCustomNoPrintLabels[$itemStatus]) ? $statusCustomNoPrintLabels[$itemStatus] : $itemStatus;
            }else{
                if ($isNewProof == 2 && ($itemStatus == 'customer_reject' || $itemStatus == 'design_approved')) {
                    $txtStatus = 'Proof is uploaded, please verify and approve';
                }else{
                    $txtStatus = isset($statusLabel[$itemStatus]) ? $statusLabel[$itemStatus] : $itemStatus;
                }
            }
            if ($adminUploadFile != null && $itemStatus == 'new') {
                $txtStatus = 'New';
            }

            $getName = $item->getName();
            //$txtStatus = $item->getName() . ' - ' . $txtStatus;
            $status[] = [
                'status'=>$txtStatus,
                // 'name'=>$item->getProduct()->getName()
                'name'=>$getName
            ];
        }
        $projectNames = count($arProjectName) ? implode(',',$arProjectName) : '';
        // echo 'projectNames:' .$projectNames;
            // exit();
        // $txtShippingDaily = count($arShippingDailies) ? implode(',',$arShippingDailies) : '';
        //echo $priceItem;
        return [
            'project_name'=>$arProjectName,
            'shipping_daily'=>$arShippingDailies,
            'price_item'=>$priceItem,
            'status'=>$status
        ];
    }
    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;
    }
}
