<?php
/**
 * Created by PhpStorm.
 * User: jderosa
 * Date: 14/02/20
 * Time: 11.58
 */

namespace FiloBlu\Rma\Plugin\Model\Rma;

use Exception;
use FiloBlu\Rma\Helper\ChangeSizeAttributeHelper;
use Psr\Log\LoggerInterface;
use Throwable;

/**
 *
 */
class RmaDataMapper
{
    /**
     * @var ChangeSizeAttributeHelper
     */
    protected $changeSizeAttributeHelper;

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

    /**
     * RmaDataMapper constructor.
     * @param ChangeSizeAttributeHelper $changeSizeAttributeHelper
     * @param LoggerInterface $logger
     */
    public function __construct(ChangeSizeAttributeHelper $changeSizeAttributeHelper, LoggerInterface $logger)
    {
        $this->changeSizeAttributeHelper = $changeSizeAttributeHelper;
        $this->logger = $logger;
    }


    /**
     * @param \Magento\Rma\Model\Rma\RmaDataMapper $subject
     * @param array $saveRequest
     * @return array
     */
    public function beforeFilterRmaSaveRequest(\Magento\Rma\Model\Rma\RmaDataMapper $subject, array $saveRequest)
    {
        try {
            $changeSizeAttributeId = $this->changeSizeAttributeHelper->getChangeSizeAttributeOptionId();
            if (isset($saveRequest['items']) && is_array($saveRequest['items'])) {
                foreach ($saveRequest['items'] as $key => $itemData) {
                    if (isset($itemData['resolution']) && $itemData['resolution'] == $changeSizeAttributeId) {
                        if (isset($itemData['change_size'])) {
                            $saveRequest['items'][$key]['change_size'] = $itemData['change_size'];
                        }
                    }
                }
            }
            return [$saveRequest];
        } catch (Exception $e) {
            $this->logger->critical($e->getMessage());
            return null;
        } catch (Throwable $t) {
            $this->logger->critical($t->getMessage());
            return null;
        }
    }
}
