<?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\Controller\Adminhtml\Shipping;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Backend\Model\Session\Quote as QuoteSession;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\View\Result\LayoutFactory;
use Magento\Sales\Model\OrderFactory;
use Magento\Sales\Model\ResourceModel\Order\Shipment\CollectionFactory;
use Magento\Setup\Exception;
use Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader;
use Magento\Ui\Component\MassAction\Filter;
use Mageplaza\EditOrder\Model\Order\Create as EditOderCreate;

/**
 * Class Track
 * @package Mageplaza\EditOrder\Controller\Adminhtml\Shipping\Method
 */
class Track extends Action
{
    /**
     * @var LayoutFactory
     */
    protected $resultLayoutFactory;

    /**
     * @var QuoteSession
     */
    protected $quoteSession;

    /**
     * @var JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * @var OrderFactory
     */
    protected $orderFactory;

    /**
     * @var EditOderCreate
     */
    protected $editOderCreate;

    /**
     * @var ShipmentLoader
     */
    protected $shipmentLoader;

    /**
     * @var CollectionFactory
     */
    protected $collectionFactory;

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

    /**
     * ListMethod constructor.
     * @param Context $context
     * @param JsonFactory $resultJsonFactory
     * @param LayoutFactory $resultLayoutFactory
     * @param QuoteSession $quoteSession
     * @param OrderFactory $orderFactory
     * @param EditOderCreate $editOderCreate
     * @param ShipmentLoader $shipmentLoader
     * @param CollectionFactory $collectionFactory
     * @param Filter $filter
     */
    public function __construct(
        Context $context,
        JsonFactory $resultJsonFactory,
        LayoutFactory $resultLayoutFactory,
        QuoteSession $quoteSession,
        OrderFactory $orderFactory,
        EditOderCreate $editOderCreate,
        ShipmentLoader $shipmentLoader,
        CollectionFactory $collectionFactory,
        Filter $filter
    ) {
        $this->resultLayoutFactory = $resultLayoutFactory;
        $this->resultJsonFactory   = $resultJsonFactory;
        $this->quoteSession        = $quoteSession;
        $this->orderFactory        = $orderFactory;
        $this->editOderCreate      = $editOderCreate;
        $this->shipmentLoader      = $shipmentLoader;
        $this->collectionFactory   = $collectionFactory;
        $this->filter              = $filter;

        parent::__construct($context);
    }

    /**
     * @return ResponseInterface|Json|ResultInterface
     * @throws LocalizedException
     */
    public function execute()
    {
        $resultLayout = $this->resultLayoutFactory->create();
        $result       = $this->resultJsonFactory->create();
        $orderId      = $this->getRequest()->getParam('order_id');

        try {
            if ($orderId) {
                $order = $this->orderFactory->create()->load($orderId);

                if (
                    $shipment = $order->getShipmentsCollection()
                        ->addFieldToFilter('shipment_status', ['null' => true])->getFirstItem()
                ) {
                    $this->shipmentLoader->setOrderId($order->getId());
                    $this->shipmentLoader->setShipment($shipment);
                    $this->shipmentLoader->setShipmentId($shipment->getId());
                    $this->shipmentLoader->load();
                }

                $trackingHtml = $resultLayout->getLayout()
                    ->createBlock(\Magento\Shipping\Block\Adminhtml\Order\Tracking::class)
                    ->setTemplate('Mageplaza_EditOrder::order/tracking.phtml')
                    ->setOrderId($orderId)
                    ->toHtml();
            } else {
                $shipments = $this->filter->getCollection($this->collectionFactory->create())
                    ->setOrder('entity_id', 'DESC');

                $trackingHtml = $resultLayout->getLayout()
                    ->createBlock(\Mageplaza\EditOrder\Block\Adminhtml\Shipment\Tracking::class)
                    ->setTemplate('Mageplaza_EditOrder::shipment/tracking.phtml')
                    ->setOrderShipments($shipments)
                    ->toHtml();
            }
        } catch (Exception $e) {
            $result->setData(['error' => $e->getMessage()]);

            return $result;
        }

        $result->setData(['success' => $trackingHtml]);

        return $result;
    }
}
