<?php

namespace FiloBlu\Storelocator\Controller\Rma\Returns;

use Exception;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Registry;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Rma\Controller\Returns;
use Magento\Rma\Helper\Data;
use Magento\Rma\Model\Rma\Source\Status;
use Magento\Rma\Model\Rma\Status\HistoryFactory;
use Magento\Rma\Model\RmaFactory;
use Magento\Sales\Model\OrderFactory;
use Psr\Log\LoggerInterface;

/**
 *
 */
class Create extends Returns
{
    /**
     * @var \Magento\Sales\Model\OrderFactory
     */
    private $orderFactory;
    /**
     * @var \Magento\Framework\Stdlib\DateTime\DateTime
     */
    private $dateTime;
    /**
     * @var \Magento\Rma\Model\RmaFactory
     */
    private $rmaFactory;
    /**
     * @var \Magento\Rma\Helper\Data
     */
    private $rmaHelper;
    /**
     * @var \Magento\Rma\Model\Rma\Status\HistoryFactory
     */
    private $historyFactory;
    /**
     * @var \Psr\Log\LoggerInterface
     */
    private $logger;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\Registry $coreRegistry
     * @param \Magento\Sales\Model\OrderFactory $orderFactory
     * @param \Magento\Framework\Stdlib\DateTime\DateTime $dateTime
     * @param \Magento\Rma\Model\RmaFactory $rmaFactory
     * @param \Magento\Rma\Helper\Data $rmaHelper
     * @param \Magento\Rma\Model\Rma\Status\HistoryFactory $historyFactory
     * @param \Psr\Log\LoggerInterface $logger
     */
    public function __construct(
        Context $context,
        Registry $coreRegistry,
        OrderFactory $orderFactory,
        DateTime $dateTime,
        RmaFactory $rmaFactory,
        Data $rmaHelper,
        HistoryFactory $historyFactory,
        LoggerInterface $logger
    ) {
        parent::__construct($context, $coreRegistry);
        $this->orderFactory = $orderFactory;
        $this->dateTime = $dateTime;
        $this->rmaFactory = $rmaFactory;
        $this->rmaHelper = $rmaHelper;
        $this->historyFactory = $historyFactory;
        $this->logger = $logger;
    }

    /**
     * Customer create new return
     *
     * @return void
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     */
    public function execute()
    {
        $orderId = (int)$this->getRequest()->getParam('order_id');

        /** @var \Magento\Sales\Model\Order $order */
        $order = $this->orderFactory->create();
        $order->load($orderId);

        if (empty($orderId)) {
            $this->_redirect('sales/order/history');
            return;
        }

        $this->_coreRegistry->register('current_order', $order);

        if (!$this->_loadOrderItems($orderId)) {
            return;
        }

        if (!$this->_canViewOrder($order)) {
            $this->_redirect('sales/order/history');
            return;
        }

        $post = $this->getRequest()->getPostValue();

        if ($post && !empty($post['items'])) {
            try {
                /** @var \Magento\Rma\Model\Rma $rmaModel */
                $rmaModel = $this->rmaFactory->create();
                $rmaData = [
                    'status'                => Status::STATE_PENDING,
                    'date_requested'        => $this->dateTime->gmtDate(),
                    'order_id'              => $order->getId(),
                    'order_increment_id'    => $order->getIncrementId(),
                    'store_id'              => $order->getStoreId(),
                    'customer_id'           => $order->getCustomerId(),
                    'order_date'            => $order->getCreatedAt(),
                    'customer_name'         => $order->getCustomerName(),
                    'customer_custom_email' => $post['customer_custom_email'],
                ];

                if (!$rmaModel->setData($rmaData)->saveRma($post)) {
                    $url = $this->_url->getUrl('*/*/create', ['order_id' => $orderId]);
                    $this->getResponse()->setRedirect($this->_redirect->error($url));
                    return;
                }

                /** @var \Magento\Rma\Model\Rma\Status\History $statusHistory */
                $statusHistory = $this->historyFactory->create();
                $statusHistory->setRmaEntityId($rmaModel->getEntityId());
                $statusHistory->sendNewRmaEmail();
                $statusHistory->saveSystemComment();

                if (isset($post['rma_comment']) && !empty($post['rma_comment'])) {
                    /** @var \Magento\Rma\Model\Rma\Status\History $comment */
                    $comment = $this->historyFactory->create();
                    $comment->setRmaEntityId($rmaModel->getEntityId());
                    $comment->saveComment($post['rma_comment'], true, false);
                }

                $this->messageManager->addSuccess(__('You submitted Return #%1.', $rmaModel->getIncrementId()));
                $this->getResponse()->setRedirect($this->_redirect->success($this->_url->getUrl('*/*/history')));
                return;
            } catch (Exception $exception) {
                $this->messageManager->addError(
                    __('We can\'t create a return right now. Please try again later.')
                );
                $this->logger->critical($exception, ['exception' => $exception]);
            }
        }
        $this->_view->loadLayout();
        $this->_view->getPage()->getConfig()->getTitle()->set(__('Create New Return'));
        if ($block = $this->_view->getLayout()->getBlock('customer.account.link.back')) {
            $block->setRefererUrl($this->_redirect->getRefererUrl());
        }
        $this->_view->renderLayout();
    }

    /**
     * Try to load valid collection of ordered items
     *
     * @param int $orderId
     * @return bool
     */
    protected function _loadOrderItems($orderId)
    {
        if ($this->rmaHelper->canCreateRma($orderId)) {
            return true;
        }

        $incrementId = $this->_coreRegistry->registry('current_order')->getIncrementId();
        $message = __('We can\'t create a return transaction for order #%1.', $incrementId);
        $this->messageManager->addError($message);
        $this->_redirect('sales/order/history');
        return false;
    }
}
