<?php

namespace FiloBlu\Rma\Console;

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\Framework\App\State;
use Magento\Rma\Api\RmaRepositoryInterface;
use Magento\Rma\Model\ResourceModel\Rma\CollectionFactory;
use Magento\Sales\Model\OrderRepository;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class GenerateMissingEasyReturnData extends  Command
{
    /**
     * @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;
    /**
     * @var State
     */
    private $state;


    /**
     * @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,
        State $state,
        $name = null
    )
    {
        parent::__construct($name);
        $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;
        $this->state = $state;
    }

    protected function configure()
    {
        $this->setName('filoblu:easyrma:generate:missing')
            ->setDescription('Rma entity id list')
            ->addOption(
                'identifier',
                '-i',
                InputOption::VALUE_REQUIRED | InputArgument::IS_ARRAY,
                'Rma entity id list'
            );

        $this->setDescription(
            'Run this code to generate missing Easy Return data took from changesize order or rma'
        );
        parent::configure();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->state->setAreaCode('adminhtml');

        $rmaIds = explode(',', $input->getOption('identifier'));

        foreach ($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());
        }
    }
}
