<?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;
        $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) {

            $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->getProduct()->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
        ];
    }
    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;
    }
}
