<?php

/**
 * Created by PhpStorm.
 * User: jderosa
 * Date: 26/03/20
 * Time: 9.00
 */

namespace FiloBlu\Rma\Block\Email\ChangeSizeOrder;

use FiloBlu\Rma\Api\RmaExtensionAttributesRepositoryInterface;
use Magento\Eav\Model\Config;
use Magento\Eav\Model\Form\Factory;
use Magento\Framework\Data\Collection\ModelFactory;
use Magento\Framework\View\Element\Template\Context;
use Magento\Rma\Api\RmaRepositoryInterface;
use Magento\Rma\Block\Email\Items;
use Magento\Rma\Helper\Eav;
use Magento\Sales\Api\Data\OrderInterface;

/**
 *
 */
class Details extends Items
{
    /**
     * @var RmaExtensionAttributesRepositoryInterface
     */
    private $rmaExtensionAttributesRepository;

    /**
     * @var RmaRepositoryInterface
     */
    private $rmaRepository;

    /**
     * Details constructor.
     * @param Context $context
     * @param ModelFactory $modelFactory
     * @param Factory $formFactory
     * @param Config $eavConfig
     * @param Eav $rmaEav
     * @param RmaExtensionAttributesRepositoryInterface $rmaExtensionAttributesRepository
     * @param RmaRepositoryInterface $rmaRepository
     * @param array $data
     */
    public function __construct(
        Context $context,
        ModelFactory $modelFactory,
        Factory $formFactory,
        Config $eavConfig,
        Eav $rmaEav,
        RmaExtensionAttributesRepositoryInterface $rmaExtensionAttributesRepository,
        RmaRepositoryInterface $rmaRepository,
        array $data = []
    ) {
        parent::__construct($context, $modelFactory, $formFactory, $eavConfig, $rmaEav, $data);
        $this->rmaExtensionAttributesRepository = $rmaExtensionAttributesRepository;
        $this->rmaRepository = $rmaRepository;
    }

    /**
     * @param OrderInterface $order
     * @return string
     */
    public function getChangeSizeOrderDetails(OrderInterface $order)
    {
        try {
            $additionalInformation = $order->getPayment()->getAdditionalInformation();
            if ($additionalInformation === null) {
                return '';
            }

            if (isset($additionalInformation['rma_id'])) {
                $rma = $this->rmaRepository->get($additionalInformation['rma_id']);
                return $rma->getIncrementId();
            }
        } catch (\Exception $exception) {
            $this->_logger->critical($exception->getMessage(), ['exception' => $exception]);
            return '';
        } catch (\Throwable $throwable) {
            $this->_logger->critical($throwable->getMessage(), ['exception' => $throwable]);
            return '';
        }
    }
}
