<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Myfitmix\CustomImport\Model\Export;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\Ui\Component\MassAction\Filter;
use \Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Ui\Model\Export\MetadataProvider;
use Magento\Ui\Model\Export\ConvertToCsv as ConvertToCsvParent;

/**
 * Class ConvertToCsv
 */
class ConvertToCsv extends ConvertToCsvParent
{
    /**
     * @var DirectoryList
     */
    protected $directory;

    /**
     * @var MetadataProvider
     */
    protected $metadataProvider;

    /**
     * @var int|null
     */
    protected $pageSize = null;

    /**
     * @var Filter
     */
    protected $filter;

    protected $_orderRepository;

    protected $dailyShippingFactory;

    protected $colPreviewOrderItemsFactory;

    protected $priceHelper;

    /**
     * @param Filesystem $filesystem
     * @param Filter $filter
     * @param MetadataProvider $metadataProvider
     * @param int $pageSize
     * @throws FileSystemException
     */
    public function __construct(
        Filesystem $filesystem,
        Filter $filter,
        MetadataProvider $metadataProvider,
        $pageSize = 200,
        OrderRepositoryInterface $orderRepository,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewDailyShipping\CollectionFactory $dailyShippingFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItems\CollectionFactory $colPreviewOrderItemsFactory,
        \Magento\Framework\Pricing\Helper\Data $priceHelper
    ) {
        $this->filter = $filter;
        $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
        $this->metadataProvider = $metadataProvider;
        $this->pageSize = $pageSize;
        $this->_orderRepository = $orderRepository;
        $this->dailyShippingFactory = $dailyShippingFactory;
        $this->colPreviewOrderItemsFactory = $colPreviewOrderItemsFactory;
        $this->priceHelper = $priceHelper;
        parent::__construct($filesystem, $filter, $metadataProvider, $pageSize);
    }

    /**
     * Returns CSV file
     *
     * @return array
     * @throws LocalizedException
     */
    public function getCsvFile()
    {
        $component = $this->filter->getComponent();

        $name = md5(microtime());
        $file = 'export/'. $component->getName() . $name . '.csv';

        $this->filter->prepareComponent($component);
        $this->filter->applySelectionOnTargetProvider();
        $dataProvider = $component->getContext()->getDataProvider();
        $fields = $this->metadataProvider->getFields($component);
        $options = $this->metadataProvider->getOptions();

        $header = $this->metadataProvider->getHeaders($component);
        if($component->getName() == 'sales_order_grid'){
            unset($header[5]);
            unset($header[6]);
            unset($header[7]);
            unset($header[13]);
            unset($header[10]);
            unset($header[14]);

            unset($fields[5]);
            unset($fields[6]);
            unset($fields[7]);
            unset($fields[13]);
            unset($fields[10]);
            unset($fields[14]);
            $fields[20] = 'status';
            $fields[21] = 'grand_total';
        }elseif($component->getName() == 'sales_order_invoice_grid'){
            unset($header[5]);
            unset($header[6]);
            unset($header[7]);
            unset($header[16]);
            unset($header[15]);
            unset($header[17]);

            unset($fields[5]);
            unset($fields[6]);
            unset($fields[7]);
            unset($fields[16]);
            unset($fields[15]);
            unset($fields[17]);
            unset($fields[18]);
           // $fields[18] = 'grand_total';
            $fields[19] = 'state';
        }

        $this->directory->create('export');
        $stream = $this->directory->openFile($file, 'w+');
        $stream->lock();
        $stream->writeCsv($header);
        $i = 1;
        $searchCriteria = $dataProvider->getSearchCriteria()
            ->setCurrentPage($i)
            ->setPageSize($this->pageSize);
        $totalCount = (int) $dataProvider->getSearchResult()->getTotalCount();
        while ($totalCount > 0) {
            $items = $dataProvider->getSearchResult()->getItems();
            foreach ($items as $item) {
                if($component->getName() == 'sales_order_grid'){
                    $order = $this->_orderRepository->get($item->getData('entity_id'));
                    $customStatus = $this->getCustomProjectNameInOrder($order);
                    $item->setStatus(count($customStatus) ? implode(',',$customStatus) :  $order->getStatus());

                    $priceItem = $this->getCustomProjectNameInOrder2($order);
                    $item->setGrandTotal($priceItem);
                }elseif($component->getName() == 'sales_order_invoice_grid'){
                    $order = $this->_orderRepository->get($item->getData('order_id'));
                    $invoiceId = $item->getData('entity_id');
                    $textStatus = 'Unpaid';
                    $previewOrerItem = $this->getOrderItemByInvoiceId($invoiceId);
                    if($previewOrerItem) {
                        $status = $previewOrerItem->getData('paid_status');
                        if($status == 'paid') {
                            $textStatus = 'Paid';
                        }
                    }
                    $item->setState($textStatus);

                    $priceItem = $this->getCustomProjectNameInOrder2($order);
                    //$item->setGrandTotal($priceItem);
                }

                $this->metadataProvider->convertDate($item, $component->getName());
                $stream->writeCsv($this->metadataProvider->getRowData($item, $fields, $options));
            }
            $searchCriteria->setCurrentPage(++$i);
            $totalCount = $totalCount - $this->pageSize;
        }
        $stream->unlock();
        $stream->close();

        return [
            'type' => 'filename',
            'value' => $file,
            'rm' => true  // can delete file after use
        ];
    }

    public function getCustomProjectNameInOrder(
        \Magento\Sales\Model\Order $order
    ) {
        $items = $order->getAllItems();
        $status = [];
        $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'
        ];
        foreach ($items as $item) {
            $infoRequest = $item->getProductOptionByCode('info_buyRequest');
            $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[] = $txtStatus;
        }
        return $status;
    }
    public function getCustomProjectNameInOrder2(
        \Magento\Sales\Model\Order $order
    ) {
        $items = $order->getAllItems();
        $priceItem = 0;
        foreach ($items as $item) {
            $infoRequest = $item->getProductOptionByCode('info_buyRequest');
            if (isset($infoRequest['txt_project_final_price'])) {
                $priceItem += $infoRequest['txt_project_final_price'];
            }

        }
        return $priceItem;
    }
    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);
        return $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
    }
    protected function getOrderItemByInvoiceId($invoiceId) {
        $collection = $this->colPreviewOrderItemsFactory->create()
            ->addFieldToFilter('invoice_id',$invoiceId);
        return $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
    }
}
