<?php

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

use FiloBlu\Rma\Api\Data\EasyReturnInterface;
use FiloBlu\Rma\Handlers\EasyReturnHandler;
use FiloBlu\Rma\Helper\EasyReturnHelper;
use FiloBlu\Rma\Model\EasyReturnFactory;
use FiloBlu\Rma\Model\EasyReturnRepository;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Rma\Api\RmaRepositoryInterface;
use Magento\Rma\Model\ResourceModel\Rma\CollectionFactory;
use Magento\Sales\Model\OrderRepository;
use Magento\Framework\App\Area;
use Magento\Framework\App\Bootstrap;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\State;

use Psr\Log\LoggerInterface;
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();


class TestGenerateMissingEasyReturnItems
{
    /**
     * @var OrderRepository
     */
    protected $orderRepository;
    /**
     * @var RmaRepositoryInterface
     */
    protected $rmaRepository;
    /**
     * @var array
     */
    protected $easyReturnItems = [];
    /**
     * @var CollectionFactory
     */
    private $rmaCollection;
    /**
     * @var ResourceConnection
     */
    private $resourceConnection;
    /**
     * @var EasyReturnRepository
     */
    private $easyReturnRepository;
    /**
     * @var EasyReturnHandler
     */
    private $easyReturnHandler;
    /**
     * @var EasyReturnHelper
     */
    private $easyReturnHelper;
    /**
     * @var EasyReturnFactory
     */
    private $easyReturnFactory;
    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;
    /**
     * @var LoggerInterface
     */
    private $logger;


    /**
     * @param OrderRepository $orderRepository
     * @param RmaRepositoryInterface $rmaRepository
     * @param CollectionFactory $rmaCollection
     * @param ResourceConnection $resourceConnection
     * @param EasyReturnRepository $easyReturnRepository
     * @param EasyReturnHandler $easyReturnHandler
     * @param EasyReturnHelper $easyReturnHelper
     * @param EasyReturnFactory $easyReturnFactory
     * @param ProductRepositoryInterface $productRepository
     * @param LoggerInterface $logger
     */
    public function __construct(
        OrderRepository $orderRepository,
        RmaRepositoryInterface $rmaRepository,
        CollectionFactory $rmaCollection,
        ResourceConnection $resourceConnection,
        EasyReturnRepository $easyReturnRepository,
        EasyReturnHandler $easyReturnHandler,
        EasyReturnHelper $easyReturnHelper,
        EasyReturnFactory $easyReturnFactory,
        ProductRepositoryInterface $productRepository,
        LoggerInterface $logger,
        $name = null
    )
    {
        $this->orderRepository = $orderRepository;
        $this->rmaRepository = $rmaRepository;
        $this->rmaCollection = $rmaCollection;
        $this->resourceConnection = $resourceConnection;
        $this->easyReturnRepository = $easyReturnRepository;
        $this->easyReturnHandler = $easyReturnHandler;
        $this->easyReturnHelper = $easyReturnHelper;
        $this->easyReturnFactory = $easyReturnFactory;
        $this->productRepository = $productRepository;
        $this->logger = $logger;
    }

    public function generateMissingEasyReturnItems($rmaIds)
    {
        foreach (explode(',', $rmaIds) as $rmaId) {
            $rma = $this->rmaRepository->get($rmaId);

            $request = [];
            $address = null;
            $order = null;

            foreach ($rma->getItems() as $rmaItem) {
                $orderId = $rmaItem->getExtensionAttributes()->getChangeSizeOrderId();

                if (empty($orderId)) {
                    $orderId = $rma->getOrderId();
                }

                if (empty($orderId)) {
                    continue;
                }

                $order = $this->orderRepository->get($orderId);

                if (empty($address)) {
                    $address = $order->getShippingAddress();
                }

            }

            if (empty($order)) {
                continue;
            }

            $request['store'] = $order->getStore();
            $request['city'] = $address->getCity();
            $request['customer_firstname'] = $address->getFirstname();
            $request['customer_lastname'] = $address->getLastname();
            $request['isPersonalized'] = $address->getLastname();
            $request['order_id'] = $rma->getOrderId();
            $request['postcode'] = $address->getPostcode();
            $request['region_id'] = $address->getRegionId();
            $request['country_id'] = $address->getCountryId();
            $request['return_type'] = 'easy-return';
            $request['street'] = implode(', ', $address->getStreet());
            $request['telephone'] = $address->getTelephone();
            $request['items'] = $rma->getItems();
            $request['weight'] = 0;
            $request['rma_entity_id'] = $rma->getEntityId();

            $this->setEasyReturnData($request);

            echo sprintf("I dati di easy return per il reso %s sono stati creati correttamente!", $rma->getIncrementId()), PHP_EOL;
        }
    }

    public function setEasyReturnData($data)
    {
        try {

            foreach ($data['items'] as $rmaItem) {

                $sku = $rmaItem->getProductSku();
                $orderItemId = $rmaItem->getOrderItemId();

                if ($this->easyReturnHelper->isABundleSku($orderItemId)) {
                    $bundleSku = $this->easyReturnHelper->getBundleSku($orderItemId);

                    $skus = $this->easyReturnHelper->resolveBundleSkus($bundleSku, $sku);

                    if (is_array($skus)) {
                        foreach ($skus as $sku) {
                            $data['weight'] += $rmaItem->getQtyRequested() * $this->productRepository->get($sku)->getWeight();
                        }
                        continue;
                    }

                    $sku = $skus;
                }

                $data['weight'] += $rmaItem->getQtyRequested() * $this->productRepository->get($sku)->getWeight();
            }
            $easyReturnRepository = $this->easyReturnRepository;
            /** @var EasyReturnInterface $easyReturn */
            $easyReturn = $this->easyReturnFactory->create();
            $easyReturn->setEasyReturnData($data);
            $easyReturnRepository->save($easyReturn);
        } catch (Exception $e) {
            echo sprintf('Errore durante la generazione di easy return item, controllare i log.'), PHP_EOL;
            $this->logger->error($e->getMessage());
        } catch (Throwable $t) {
            echo sprintf('Errore durante la generazione di easy return item, controllare i log.'), PHP_EOL;
            $this->logger->error($t->getMessage());
        }
    }
}

$rmaIdList = '26305,26306,26307,26308,26310,26318,26326,26328,26329,26330,26341,26363,26364,26373,26374,26375,26378,26380,26384,26385,26397,26406,26407,26411,26414,26415,26421,26422,26426,26427,26446,26447,26448,26449';
$rmaIdList = '20336,20357';
$generateMissingEasyReturnItems = $objectManager->get(TestGenerateMissingEasyReturnItems::class);
$generateMissingEasyReturnItems->generateMissingEasyReturnItems($rmaIdList);
