<?php
/**
 * Mirasvit
 *
 * This source file is subject to the Mirasvit Software License, which is available at https://mirasvit.com/license/.
 * Do not edit or add to this file if you wish to upgrade the to newer versions in the future.
 * If you wish to customize this module for your needs.
 * Please refer to http://www.magentocommerce.com for more information.
 *
 * @category  Mirasvit
 * @package   mirasvit/module-rma
 * @version   2.2.23
 * @copyright Copyright (C) 2023 Mirasvit (https://mirasvit.com/)
 */



namespace Mirasvit\Rma\Service\Item;

use Magento\Framework\Exception\LocalizedException;
use Mirasvit\Rma\Service\Item\ItemManagement\Quantity;

/**
 * Update RMA items
 */
class Update
{
    private $itemAbstractFactory;

    private $itemQuantity;

    /**
     * @param ItemAbstractFactory $itemAbstractFactory
     */
    public function __construct(
        Quantity $itemQuantity,
        ItemAbstractFactory $itemAbstractFactory
    ) {
        $this->itemQuantity               = $itemQuantity;
        $this->itemAbstractFactory = $itemAbstractFactory;
    }

    /**
     * @param \Mirasvit\Rma\Model\Rma $rma
     * @param mixed                   $items
     *
     * @return void
     */
    public function updateItems($rma, $items)
    {
        foreach ($items as $item) {
            $rmaItem = $this->getItem($item);

            if (isset($item['item_id']) && $item['item_id']) {
                $rmaItem->load((int) $item['item_id']);
            }

            unset($item['item_id']);
            $rmaItem->addData($item)
                ->setRmaId($rma->getId());

            $rmaItem->save();
        }
    }

    /**
     * @param mixed $items
     *
     * @return void
     */
    public function checkItemsBeforeSave($items)
    {
        $countItems = count($items);
        foreach ($items as $item) {

            if (isset($item['item_id']) && $item['item_id']) {
                $this->getItem($item)->load((int)$item['item_id']);
            }
            unset($item['item_id']);

            if (!$this->itemQuantity->getQtyAvailable($this->getItem($item)->addData($item))) {
                $countItems -= 1;
            }
        }

        if ($countItems <= 0) {
            throw new LocalizedException(__('RMA for the item(s) already exists'));
        }
    }

    /**
     * @param array $item
     *
     * @return \Mirasvit\Rma\Model\Item|\Mirasvit\Rma\Model\ResourceModel\OfflineItem
     */
    protected function getItem($item)
    {
        $rmaItem = $this->itemAbstractFactory->get($item);

        return $rmaItem;
    }
}
