<?php

namespace FiloBlu\Rma\Plugin\Model;

use Magento\Rma\Api\Data\RmaInterface;
use Magento\Sales\Model\Order\ItemRepository;

class FixBundleRmaItems
{
    /**
     * @var \Magento\Sales\Model\Order\ItemRepository
     */
    private $orderItemRepository;

    /**
     * @param ItemRepository $orderItemRepository
     */
    public function __construct(
        \Magento\Sales\Model\Order\ItemRepository $orderItemRepository
    )
    {

        $this->orderItemRepository = $orderItemRepository;
    }

    public function beforeSaveRma(RmaInterface $subject, $data)
    {
        $items = [];

        foreach ($data['items'] as $key => $item) {

            $currentOrderItem = $this->orderItemRepository->get($item['order_item_id']);

            if ($currentOrderItem->getProductType() !== 'bundle') {
                $items[]  = $item;
                continue;
            }

            $item['items'] = $currentOrderItem->getChildrenItems();

            if (!empty($item['items'])) {
                foreach ($item['items'] as $orderItem) {
                    $items[] = [
                        'qty_requested' => $item['qty_requested'],
                        'order_item_id' => $orderItem->getItemId(),
                        'condition' => $item['condition'],
                        'reason' => $item['reason'],
                        'resolution' => $item['resolution']
                    ];
                }
            }
        }

        if (empty($items)) {
            return [$data];
        }

        $data['items'] = $items;

        return [$data];
    }
}
