<?php

namespace Leadlion\AutogedalWarehouses\Ui\Component\Listing\Column;

class SalesOrderGrid extends \Magento\Ui\Component\Listing\Columns\Column
{
    public function __construct(
        \Magento\Framework\View\Element\UiComponent\ContextInterface $context,
        \Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory,
        \Leadlion\AutogedalWarehouses\Block\Warehouse $warehouseBlock,
        array $components = [],
        array $data = []
    ) {
        $this->warehouseBlock = $warehouseBlock;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            $warehouseName = ''; $carrierName = '';
            foreach ($dataSource['data']['items'] as &$item) {
                $warehouseId = $item["autogedal_allocated_warehouse"];
                $carrierId = $item["autogedal_allocated_carrier"];
                $warehouseOptions = $this->warehouseBlock->getOrderWarehousee();
                if (count($warehouseOptions) > 0) {
                    foreach ($warehouseOptions as $warehouseVal) {
                        if ($warehouseVal['value'] == $warehouseId) {
                            $warehouseName = $warehouseVal['label'];
                        }
                    }
                }
                if (!empty($carrierId) && is_numeric($carrierId)) {
                    $carrierOptions = $this->warehouseBlock->getOrderCarrier();
                    if (count($carrierOptions) > 0) {
                        foreach ($carrierOptions as $key => $carrierVal) {
                            if ($key == $carrierId) {
                                $carrierName = $carrierVal;
                            }
                        }
                    }
                    $item["autogedal_allocated_carrier"] = $carrierName;
                }
                $item["autogedal_allocated_warehouse"] = $warehouseName;
            }
        }
        return $dataSource;
    }
}
