<?php

require __DIR__ . '/../../../../../app/bootstrap.php';

use FiloBlu\Rma\Helper\ChangeSizeAttributeHelper;
use FiloBlu\Rma\Helper\EasyReturnHelper;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Area;
use Magento\Framework\App\Bootstrap;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\State;
use Magento\Rma\Api\Data\RmaInterface;
use Magento\Rma\Model\ItemFactory;
use Magento\Rma\Model\RmaFactory;
use Magento\Rma\Model\Service\RmaManagement;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\SalesSequence\Model\Manager;

use const Filoblu\Storelocator\Model\Rma\ItemFactory;


$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

/** @var State $state */
$state = $objectManager->get(State::class);
$state->setAreaCode(Area::AREA_FRONTEND);
$objectManager = ObjectManager::getInstance();

/*
 *
AB48735E3M8644
AB48835E360042
AB48835E311042
MK33Z31E2E8444
 *
 */


$changeSizeItems = [
    'AB48735E3M8640' => [
        'product_id'  => 16710,
        'product_sku' => 'AB48735E3M8644'
    ],
    'AB48835E360040' => [
        'product_id'  => 17089,
        'product_sku' => 'AB48835E311042'
    ],
    'MK33Z31E2E8442' => [
        'product_id'  => 9725,
        'product_sku' => 'MK33Z31E2E8444'
    ]
];

class SimulateChangeSize
{
    /**
     * @var RmaManagement
     */
    protected $rmaManagement;
    /**
     * @var string[]
     */
    protected $orderSkus = [
        'AL0A82C40611007'
    ];
    /**
     * @var array[]
     */
    protected $changeSizeItems = [
        'AL0A82C40611007' => [
            'product_id'  => 7878,
            'product_sku' => 'AL0A82C40611010'
        ]
    ];
    /**
     * @var OrderRepositoryInterface
     */
    protected $orderRepository;
    /**
     * @var RmaFactory
     */
    protected $rmaFactory;
    /**
     * @var ItemFactory
     */
    protected $itemFactory;
    /**
     * @var ProductRepositoryInterface
     */
    protected $productRepository;
    /**
     * @var Manager
     */
    protected $sequenceManager;
    /**
     * @var ChangeSizeAttributeHelper
     */
    protected $changeSizeAttributeHelper;
    /**
     * @var EasyReturnHelper
     */
    protected $easyReturnHelper;

    /**
     * @param RmaManagement $rmaManagement
     * @param OrderRepositoryInterface $orderRepository
     * @param RmaFactory $rmaFactory
     * @param ItemFactory $itemFactory
     * @param ProductRepositoryInterface $productRepository
     * @param Manager $sequenceManager
     * @param ChangeSizeAttributeHelper $changeSizeAttributeHelper
     * @param EasyReturnHelper $easyReturnHelper
     */
    public function __construct(
        RmaManagement $rmaManagement,
        OrderRepositoryInterface $orderRepository,
        RmaFactory $rmaFactory,
        ItemFactory $itemFactory,
        ProductRepositoryInterface $productRepository,
        Manager $sequenceManager,
        ChangeSizeAttributeHelper $changeSizeAttributeHelper,
        EasyReturnHelper $easyReturnHelper
    ) {
        $this->rmaManagement = $rmaManagement;
        $this->orderRepository = $orderRepository;
        $this->rmaFactory = $rmaFactory;
        $this->itemFactory = $itemFactory;
        $this->productRepository = $productRepository;
        $this->sequenceManager = $sequenceManager;
        $this->changeSizeAttributeHelper = $changeSizeAttributeHelper;
        $this->easyReturnHelper = $easyReturnHelper;
    }

    public function simulate($orderId)
    {
        $order = $this->orderRepository->get($orderId);

        /** @var RmaInterface $rma */
        $rma = $this->generateRma($order);

        $this->rmaManagement->saveRma($rma);
    }

    public function generateRma(OrderInterface $order)
    {
        $rma = $this->rmaFactory->create();
        $rma->setOrderId($order->getEntityId());
        $rma->setCustomerId($order->getCustomerId());
        $rma->setOrderIncrementId($order->getIncrementId());
        $rma->setIncrementId($this->getRmaIncrementId($order->getStoreId()));
        $rma->setCustomerName($order->getCustomerFirstname() . ' ' . $order->getCustomerLastname());
        $rma->setCustomerEmail($order->getCustomerEmail());
        $rma->setCustomerIsGuest($order->getCustomerIsGuest());
        $rma->setStatus('pending'); // Set the initial status of the RMA
        $rma->setStoreId($order->getStoreId());

        $extensionAttributes = $rma->getExtensionAttributes();

        $extensionAttributes->setEasyReturn($this->easyReturnHelper->isEasyReturnEnabled($order->getStoreId()));
        $extensionAttributes->setCustomerFirstname($order->getCustomerFirstname());
        $extensionAttributes->setCustomerLastname($order->getCustomerLastname());

        $rma->setExtensionAttributes($extensionAttributes);

        $items = $this->generateRmaItems($rma, $order);

        $rma->setItems($items);


        return $rma;
    }

    /**
     * @param $storeId
     * @return string
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function getRmaIncrementId($storeId)
    {
        return $this->sequenceManager->getSequence('rma_item', $storeId)
                                     ->getNextValue()
        ;
    }

    public function generateRmaItems(RmaInterface $rma, OrderInterface $order)
    {
        $changeSizeResolution = $this->changeSizeAttributeHelper->getChangeSizeAttributeOptionId();

        $items = [];

        foreach ($order->getAllItems() as $item)
        {
            if ($item->getProductType() == 'configurable')
            {
                continue;
            }

            $sku = $item->getProduct()
                        ->getSku()
            ;

            if (!in_array($sku, $this->orderSkus))
            {
                continue;
            }

            $rmaItem = $this->itemFactory->create();
            //$rmaItem->setRmaEntityId($rma->getEntityId());
            $rmaItem->setOrderItemId($item->getId());
            $rmaItem->setProductId($item->getProductId());
            $rmaItem->setQtyRequested($item->getQtyOrdered());
            $rmaItem->setQtyAuthorized($item->getQtyOrdered());
            $rmaItem->setResolvedOrderId($item->getResolvedOrderId());
            $rmaItem->setResolution($changeSizeResolution);
            $rmaItem->setReason(82);
            $rmaItem->setCondition(8);
            $rmaItem->setStatus('pending');
            $rmaItem->getExtensionAttributes()
                    ->setChangeSize($this->changeSizeItems[$sku]['product_id'])
            ;

            $items[] = $rmaItem;
        }

        return $items;
    }
}

$simulateChangeSize = $objectManager->get(SimulateChangeSize::class);
$simulateChangeSize->simulate(81832);
