<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace FiloBlu\Rma\Plugin\Catalog\Controller\Adminhtml\Product\Initialization;

use FiloBlu\Rma\Helper\RmaHelper;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper;
use Magento\Rma\Model\Product\Source;
use Magento\Rma\Ui\DataProvider\Product\Form\Modifier\Rma;

/**
 * Class HelperPlugin
 */
class HelperPlugin
{
    /**
     * @var RmaHelper
     */
    protected $rmaHelper;

    public function __construct(
        RmaHelper $rmaHelper
    )
    {

        $this->rmaHelper = $rmaHelper;
    }


    /**
     * @param Helper $subject
     * @param ProductInterface $product
     * @param array $productData
     * @return array
     */
    public function beforeInitializeFromData(Helper $subject, ProductInterface $product, array $productData)
    {
        if (!$this->rmaHelper->isUseRmaConfigPluginEnabled()) {
            return null;
        }

        if (isset($productData['use_config_' . Rma::FIELD_IS_RMA_ENABLED]) && 1 === (int)$productData['use_config_' . Rma::FIELD_IS_RMA_ENABLED]) {
            unset($productData['use_config_' . Rma::FIELD_IS_RMA_ENABLED]);
            $productData[Rma::FIELD_IS_RMA_ENABLED] = Source::ATTRIBUTE_ENABLE_RMA_USE_CONFIG;
        }

        if (isset($productData['use_config_' . Rma::FIELD_IS_RMA_ENABLED]) && 0 === (int)$productData['use_config_' . Rma::FIELD_IS_RMA_ENABLED]) {
            unset($productData['use_config_' . Rma::FIELD_IS_RMA_ENABLED]);

            if((int)$productData[Rma::FIELD_IS_RMA_ENABLED] === 1){
                $productData[Rma::FIELD_IS_RMA_ENABLED] = Source::ATTRIBUTE_ENABLE_RMA_YES;
            }else{
                $productData[Rma::FIELD_IS_RMA_ENABLED] = Source::ATTRIBUTE_ENABLE_RMA_NO;
            }
        }

        return [$product, $productData];
    }
}
