<?php

namespace FiloBlu\Rma\Controller\Adminhtml\ChangeSizeItems;

use FiloBlu\Rma\Api\Data\ChangeSizeItemsInterface;
use FiloBlu\Rma\Api\RmaExtensionAttributesRepositoryInterface;
use FiloBlu\Rma\Console\RestoreOrderRma;
use FiloBlu\Rma\Helper\ChangeSizeItemsHelper;
use FiloBlu\Rma\Logger\Logger;
use FiloBlu\Rma\Model\ChangeSizeItemsFactory;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Rma\Api\Data\RmaInterface;
use Magento\Rma\Api\RmaRepositoryInterface;
use Magento\Rma\Model\Item;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Framework\DataObject;
use Magento\Framework\Message\ManagerInterface;

class GenerateOrders extends Action
{
    protected $resultFactory;
    /**
     * @var ChangeSizeItemsFactory
     */
    protected $changeSizeItemsFactory;
    /**
     * @var OrderRepositoryInterface
     */
    protected $orderRepository;
    /**
     * @var RestoreOrderRma
     */
    protected $restoreOrderRma;
    /**
     * @var RmaRepositoryInterface
     */
    protected $rmaRepository;
    /**
     * @var ChangeSizeItemsHelper
     */
    protected $changeSizeItemsHelper;
    /**
     * @var Logger
     */
    protected $logger;
    /**
     * @var RmaExtensionAttributesRepositoryInterface
     */
    protected $rmaExtensionAttributesRepository;
    /**
     * @var ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @param Context $context
     * @param ResultFactory $resultFactory
     * @param ChangeSizeItemsFactory $changeSizeItemsFactory
     * @param OrderRepositoryInterface $orderRepository
     * @param RestoreOrderRma $restoreOrderRma
     * @param RmaRepositoryInterface $rmaRepository
     * @param ChangeSizeItemsHelper $changeSizeItemsHelper
     * @param Logger $logger
     * @param RmaExtensionAttributesRepositoryInterface $rmaExtensionAttributesRepository
     * @param ManagerInterface $messageManager
     * @param ProductRepositoryInterface $productRepository
     */
    public function __construct(
        Context $context,
        ResultFactory $resultFactory,
        ChangeSizeItemsFactory $changeSizeItemsFactory,
        OrderRepositoryInterface $orderRepository,
        RestoreOrderRma $restoreOrderRma,
        RmaRepositoryInterface $rmaRepository,
        ChangeSizeItemsHelper $changeSizeItemsHelper,
        Logger $logger,
        RmaExtensionAttributesRepositoryInterface $rmaExtensionAttributesRepository,
        ManagerInterface $messageManager,
        ProductRepositoryInterface $productRepository
    ) {
        parent::__construct($context);
        $this->resultFactory = $resultFactory;
        $this->changeSizeItemsFactory = $changeSizeItemsFactory;
        $this->orderRepository = $orderRepository;
        $this->restoreOrderRma = $restoreOrderRma;
        $this->rmaRepository = $rmaRepository;
        $this->changeSizeItemsHelper = $changeSizeItemsHelper;
        $this->logger = $logger;
        $this->rmaExtensionAttributesRepository = $rmaExtensionAttributesRepository;
        $this->messageManager = $messageManager;
        $this->productRepository = $productRepository;
    }

    public function execute()
    {
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);

        $id = $this->getRequest()->getParam('id');
        $resultRedirect->setUrl($this->_url->getUrl('filoblu_rma/changesizeitems/index'));

        if (!$id) {
            $this->messageManager->addErrorMessage(__('Impossibile creare un ordine Cambio Taglia per questo item.'));
            return $resultRedirect;
        }

        $changeSizeItem = $this->changeSizeItemsFactory->create()->load($id);

        $rma = $this->rmaRepository->get($changeSizeItem->getRmaId());

        $items = (array)$rma->getItems();

        $rmaItem = $items[$changeSizeItem->getRmaItemId()];

        $orderId = $this->rmaExtensionAttributesRepository->getChangeSizeOrderId($rmaItem->getId());

        if (!$this->changeSizeItemsHelper->doesOrderExists($orderId)) {
            $this->generateOrder($rma, $rmaItem, $changeSizeItem, $resultRedirect);
        }

        return $resultRedirect;
    }

    public function generateOrder(RmaInterface $rma, Item $rmaItem, ChangeSizeItemsInterface $changeSizeItem, $resultRedirect)
    {
        $newProduct = $this->productRepository->get($changeSizeItem->getNewProductSku());

        $data = new DataObject([
            'order' => $this->orderRepository->get($changeSizeItem->getParentOrderId()),
            'rma_item' => $rmaItem,
            'product_id' => $rmaItem->getChangeSize() ?: $newProduct->getId(),
            'parent_sku' => $changeSizeItem->getParentProductSku(),
            'rma_entity_id' => $changeSizeItem->getRmaId(),
            'original_order_item_id' => $changeSizeItem->getParentOrderItem(),
            'rma' => $rma
        ]);


        try {
            /** @var \Magento\Sales\Model\Order $order */
            $order = $this->changeSizeItemsHelper->generateOrder($data);

            $changeSizeItem->setChangeSizeOrderId($order->getId());
            $changeSizeItem->setChangeSizeOrderIncrementId($order->getIncrementId());
            $changeSizeItem->save();

        } catch (\Exception $e) {
            $this->messageManager->addErrorMessage(__('Impossibile creare un ordine Cambio Taglia per questo item.'));
            return $resultRedirect;
        }

        $this->messageManager->addSuccessMessage(__("L'ordine Cambio Taglia è stato generato con successo."));
        return $resultRedirect;
    }
}
