<?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\Ui\Component\Orders\Listing\Column;
use \Magento\Sales\Api\OrderRepositoryInterface;
use \Magento\Framework\View\Element\UiComponent\ContextInterface;
use \Magento\Framework\View\Element\UiComponentFactory;
use \Magento\Ui\Component\Listing\Columns\Column;
use \Magento\Framework\Api\SearchCriteriaBuilder;

class CustomStatus extends Column
{
    protected $_orderRepository;
    protected $_searchCriteria;
    protected $dailyShippingFactory;
    protected $colPreviewOrderItemsFactory;
    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        OrderRepositoryInterface $orderRepository,
        SearchCriteriaBuilder $criteria,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewDailyShipping\CollectionFactory $dailyShippingFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItems\CollectionFactory $colPreviewOrderItemsFactory,
        array $components = [],
        array $data = []
    ) {
        $this->_orderRepository = $orderRepository;
        $this->_searchCriteria  = $criteria;
        $this->dailyShippingFactory = $dailyShippingFactory;
        $this->colPreviewOrderItemsFactory = $colPreviewOrderItemsFactory;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }
    public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as & $item) {

                $order  = $this->_orderRepository->get($item["entity_id"]);
                $customStatus = $this->getCustomProjectNameInOrder($order);
//                $customStatus = isset($previewCustomData['status']) ? $previewCustomData['status'] : [];
                // $this->getData('name') returns the name of the column so in this case it would return export_status
                $item[$this->getData('name')] = count($customStatus) ? implode(',',$customStatus) :  $order->getStatus();
            }
        }

        return $dataSource;
    }

    public function getCustomProjectNameInOrder(
        \Magento\Sales\Model\Order $order
    ) {
        $items = $order->getAllItems();
        $status = [];
        // $price = 0;
        $statusLabelsstandard = [
            'new'=>'New',
            'process'=>'In progress',
            'shipping'=>'Ready for shipping/Production done',
            'shipped'=>'Shipped'
        ];
        $statusLabel = [
            'new' => 'New – design uploaded',
            'downloading' => 'Checking design by Myfitmix',
            'design_failed' => 'Design Failed, customer must 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 – No design',
            'downloading' => 'Checking design by Myfitmix',
            'design_failed' => 'Design Failed, customer must 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'];


            // status
            $isNewProof = 0;
            $previewItem = $this->getCustomPreviewOrderItem($item->getId());            
            $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, waiting for customer approval';
                }else{
                    $txtStatus = isset($statusLabel[$itemStatus]) ? $statusLabel[$itemStatus] : $itemStatus;
                }
            }
            if ($adminUploadFile != null && $itemStatus == 'new') {
                $txtStatus = 'New';
            }

            $txtStatus = $item->getName() . ' - ' . $txtStatus;
            $status[] = $txtStatus;

        }
        return $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;
    }

}
