<?php
/**
 * Created by PhpStorm.
 * User: jderosa
 * Date: 10/04/19
 * Time: 11.09
 */

namespace FiloBlu\Rma\Handlers;

use Exception;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\Sales\Model\OrderRepository;
use Psr\Log\LoggerInterface;
use Throwable;

use function is_object;
use function is_string;

/**
 * Class DisablePersonalizedOrderRmaHanlder
 * @package FiloBlu\Rma\Handlers
 */
class DisablePersonalizedOrderRmaHanlder
{
    /** @var string */
    const RMA_CONFIG_PATH = 'filoblu_disablerma_section/rma_group/allow_customized_product_return';

    /**
     * @var OrderRepository
     */
    protected $orderRepository;

    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var OrderInterfaceFactory
     */
    protected $orderInterfaceFactory;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var Registry
     */
    private $registry;

    /**
     * DisablePersonalizedOrderRma constructor.
     * @param Context $context
     * @param OrderRepository $orderRepository
     * @param ScopeConfigInterface $scopeConfig
     * @param LoggerInterface $logger
     * @param Registry $registry
     * @param OrderInterfaceFactory $orderInterfaceFactory
     */
    public function __construct(
        Context $context,
        OrderRepository $orderRepository,
        ScopeConfigInterface $scopeConfig,
        LoggerInterface $logger,
        Registry $registry,
        OrderInterfaceFactory $orderInterfaceFactory
    ) {
        $this->orderRepository = $orderRepository;
        $this->scopeConfig = $scopeConfig;
        $this->request = $context->getRequest();
        $this->logger = $logger;
        $this->registry = $registry;
        $this->orderInterfaceFactory = $orderInterfaceFactory;
    }

    /**
     * @param $result
     * @param $currentOrder
     * @return false|mixed
     */
    public function canCreateRmaForPersonalizedOrder($result, $currentOrder)
    {
        try {
            $config = $this->scopeConfig->getValue(self::RMA_CONFIG_PATH) ?? 0;
            $post = $this->request->getPostValue();
            if (!empty($post)) {
                //check in configuration if allow RMA request for personalized orders
                if (!$config && isset($post['items'][0]['order_item_id'])) {
                    foreach ($post['items'] as $postItem) {
                        $orderItemId = $postItem['order_item_id'];
                        try {
                            $order = $this->registry->registry('current_order');

                            if (!is_object($currentOrder) && !$order) {
                                $order = $this->orderInterfaceFactory->create()->load($currentOrder);
                            }

                            $allItems = $order->getAllItems();
                            //check if request has personalizations
                            foreach ($allItems as $item) {
                                $options = $item->getProductOptions();
                                //check if one of product is personalized and set Param to send to ShowCustomErrorMessageForRma.php
                                if (($item->getItemId() == $orderItemId) && isset($options['options'])) {
                                    $result = false;
                                    $this->request->setParams(['isPersonalized' => true]);
                                } else {
                                    $this->request->setParams(['isPersonalized' => false]);
                                }
                            }
                        } catch (Exception $e) {
                            $this->request->setParams(['errorMessageFromPlugin' => $e]);
                        }
                    }
                }
            } elseif ($this->request->getParam('order_id')) {
                $order = $this->registry->registry('current_order');
                if (is_string($order)) {
                    $order = $this->orderRepository->get($order);
                }
                $myOrderitems = $order->getItems();
                $personalizedItems = [];
                if (!$config) {
                    foreach ($myOrderitems as $item) {
                        $options = $item->getProductOptions();
                        if (!empty($options['options'])) {
                            $personalizedItems [] = $item->getItemId();
                        }
                    }
                }
                $this->request->setParams(['personalizedItems' => $personalizedItems]);
            }
            return $result;
        } catch (Exception $e) {
            $this->logger->critical($e->getMessage(), ['exception' => $e]);
        } catch (Throwable $t) {
            $this->logger->critical($t->getMessage(), ['exception' => $t]);
        }

        return true;
    }

    /**
     * @return OrderInterface|mixed|null
     * @throws InputException
     * @throws NoSuchEntityException
     */
    public function getOrder()
    {
        $orderId = $this->request->getParam('order_id');

        $order = $this->registry->registry("filoblu_rma_order_{$orderId}");

        if (!$order) {
            $order = $this->orderRepository->get($orderId);
            $this->registry->register("filoblu_rma_order_{$orderId}", $order);
        }

        return $order;
    }
}
