<?php
/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Mageplaza.com license that is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_EditOrder
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */

namespace Mageplaza\EditOrder\Block\Adminhtml\Shipment;

use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Sales\Model\Order\Shipment;
use Magento\Sales\Model\Order\Shipment\Track;
use Magento\Sales\Model\ResourceModel\Order\Shipment\Collection as ShipmentCollection;
use Magento\Shipping\Model\Config;

/**
 * Class Tracking
 *
 * @package Mageplaza\EditOrder\Block\Adminhtml\Shipment
 * @method Tracking setOrderShipments(array $shipments)
 * @method ShipmentCollection getOrderShipments()
 */
class Tracking extends Template
{
    /**
     * @var Config
     */
    protected $_shippingConfig;

    /**
     * Tracking constructor.
     * @param Context $context
     * @param Config $shippingConfig
     * @param array $data
     */
    public function __construct(
        Context $context,
        Config $shippingConfig,
        array $data = []
    ) {
        $this->_shippingConfig     = $shippingConfig;

        parent::__construct($context, $data);
    }

    /**
     * Retrieve carriers
     *
     * @param Shipment $shipment
     *
     * @return array
     */
    public function getCarriers($shipment)
    {
        $carriers           = [];
        $carrierInstances   = $this->_getCarriersInstances($shipment);
        $carriers['custom'] = __('Custom Value');
        foreach ($carrierInstances as $code => $carrier) {
            if ($carrier->isTrackingAvailable()) {
                $carriers[$code] = $carrier->getConfigData('title');
            }
        }

        return $carriers;
    }

    /**
     * @param array $tracks
     *
     * @return array|string
     */
    public function getCarrier($tracks)
    {
        $trackingTitle = [];
        foreach ($tracks as $track) {
            /** @var Track $track */
            $trackingTitle[] = $track->isCustom() ? __('Custom') : $track->getTitle();
        }
        return implode(',', $trackingTitle);
    }

    /**
     * @param Shipment $shipment
     *
     * @return array
     */
    protected function _getCarriersInstances($shipment)
    {
        return $this->_shippingConfig->getAllCarriers($shipment->getStoreId());
    }
}
