<?php
/**
 * Created by PhpStorm.
 * User: jderosa
 * Date: 20/04/20
 * Time: 10.54
 */

namespace FiloBlu\Storelocator\Plugin\Helper;

use FiloBlu\Rma\Handlers\DisablePersonalizedOrderRmaHanlder;
use Magento\Framework\Registry;
use Magento\Rma\Helper\Data;
use Magento\Sales\Api\OrderRepositoryInterface;
use Psr\Log\LoggerInterface;
use FiloBlu\Rma\Handlers\CanCreateRmaHandler;
use FiloBlu\Rma\Handlers\CustomCarrierHandler;

/**
 *
 */
class RmaHelperDataProcessor
{
    /**
     * @var OrderRepositoryInterface
     */
    protected $orderRepository;
    /**
     * @var Registry
     */
    protected $registry;
    /**
     * @var DisablePersonalizedOrderRmaHanlder
     */
    private $disablePersonalizedOrderRmaHanlder;
    /**
     * @var LoggerInterface
     */
    private $logger;
    /**
     * @var CanCreateRmaHandler
     */
    private $canCreateRmaHandler;
    /**
     * @var CustomCarrierHandler
     */
    private $carrierHandler;

    /**
     * RmaHelperDataProcessor constructor.
     * @param DisablePersonalizedOrderRmaHanlder $disablePersonalizedOrderRmaHanlder
     * @param LoggerInterface $logger
     * @param CanCreateRmaHandler $canCreateRmaHandler
     * @param CustomCarrierHandler $carrierHandler
     * @param OrderRepositoryInterface $orderRepository
     * @param Registry $registry
     */
    public function __construct(
        DisablePersonalizedOrderRmaHanlder $disablePersonalizedOrderRmaHanlder,
        LoggerInterface $logger,
        CanCreateRmaHandler $canCreateRmaHandler,
        CustomCarrierHandler $carrierHandler,
        OrderRepositoryInterface $orderRepository,
        Registry $registry
    ) {
        $this->disablePersonalizedOrderRmaHanlder = $disablePersonalizedOrderRmaHanlder;
        $this->logger = $logger;
        $this->canCreateRmaHandler = $canCreateRmaHandler;
        $this->carrierHandler = $carrierHandler;
        $this->orderRepository = $orderRepository;
        $this->registry = $registry;
    }


    /**
     * @param Data $subject
     * @param $result
     * @param $order
     * @param false $forceCreate
     * @return false|mixed|null
     */
    public function afterCanCreateRma(Data $subject, $result, $order, $forceCreate = false)
    {

        if (is_numeric($order)) {
            if (!$this->registry->registry('current_order')) {
                $orderObject = $this->orderRepository->get($order);
                $this->registry->register('current_order', $orderObject);
            }
            return $result;
        }

        if (!$order->getPickupInStoreId()) {
            return $result;
        }

        if (!in_array($order->getStatus(), ['complete_in_store'])) {
            return false;
        }

        return $result;
    }
}
