<?php

namespace FiloBlu\Rma\Handlers;

use Exception;
use FiloBlu\Rma\Api\Data\EasyReturnInterface;
use FiloBlu\Rma\Api\Data\EasyReturnInterfaceFactory;
use FiloBlu\Rma\Api\EasyReturnRepositoryInterface;
use FiloBlu\Rma\Helper\EasyReturnHelper;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\State;
use Magento\Rma\Model\Rma;
use Psr\Log\LoggerInterface;
use Throwable;
use FiloBlu\Rma\Helper\ChangeSizeAttributeHelper;

/**
 *
 */
class EasyReturnHandler
{
    /**
     * @var EasyReturnHelper
     */
    private $easyReturnHelper;
    /**
     * @var RequestInterface
     */
    private $request;
    /**
     * @var EasyReturnRepositoryInterface
     */
    private $easyReturnRepository;
    /**
     * @var EasyReturnInterfaceFactory
     */
    private $easyReturnFactory;
    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;
    /**
     * @var LoggerInterface
     */
    private $logger;
    /**
     * @var ChangeSizeAttributeHelper
     */
    private $changeSizeAttributeHelper;
    /**
     * @var State
     */
    private $state;

    /**
     * @param EasyReturnHelper $easyReturnHelper
     * @param RequestInterface $request
     * @param EasyReturnRepositoryInterface $easyReturnRepository
     * @param EasyReturnInterfaceFactory $easyReturnFactory
     * @param ProductRepositoryInterface $productRepository
     * @param LoggerInterface $logger
     * @param ChangeSizeAttributeHelper $changeSizeAttributeHelper
     * @param State $state
     */
    public function __construct(
        EasyReturnHelper $easyReturnHelper,
        RequestInterface $request,
        EasyReturnRepositoryInterface $easyReturnRepository,
        EasyReturnInterfaceFactory $easyReturnFactory,
        ProductRepositoryInterface $productRepository,
        LoggerInterface $logger,
        ChangeSizeAttributeHelper $changeSizeAttributeHelper,
        State $state
    ) {
        $this->easyReturnHelper = $easyReturnHelper;
        $this->request = $request;
        $this->easyReturnRepository = $easyReturnRepository;
        $this->easyReturnFactory = $easyReturnFactory;
        $this->productRepository = $productRepository;
        $this->logger = $logger;
        $this->changeSizeAttributeHelper = $changeSizeAttributeHelper;
        $this->state = $state;
    }

    /**
     * @param Rma $subject
     * @param $result
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function saveEasyReturnFields(Rma $subject, $result)
    {
        if (!$this->easyReturnHelper->isEasyReturnEnabled($subject->getStoreId())) {
            return;
        }

        $orderId = $this->request->getParam('order_id');
        $returnType  = $this->request->getParam('return_type');

        if (empty($returnType) && $this->state->getAreaCode() == 'adminhtml') {
            $returnType = 'easy-return';
        }

        foreach ($subject->getItems() as $item) {
            if ($item->getResolution() == $this->changeSizeAttributeHelper->getChangeSizeAttributeOptionId()) {
                if ($this->state->getAreaCode() == 'adminhtml') {
                    $returnType = 'easy-return';
                    continue;
                }
                $returnType = 'change_size';
                break;
            }
        }

        try {
            if ($orderId && in_array($returnType , ['easy-return', 'change_size'])) {
                $this->saveEasyReturnByRequest($subject, $result);
                return;
            }

            if ($result->getExtensionAttributes() !== null && $result->getExtensionAttributes()->getEasyReturn()) {
                $this->saveEasyReturnByApi($subject, $result, $returnType);
            }
        } catch (Exception $e) {
            $this->logger->critical($e->getMessage(), ['exception' => $e]);
        } catch (Throwable $t) {
            $this->logger->critical($t->getMessage(), ['exception' => $t]);
        }
    }

    /**
     * @param $subject
     * @param $result
     */
    public function saveEasyReturnByRequest($subject, $result)
    {
        try {
            $formData = $this->request->getParams();
            $formData['rma_entity_id'] = $subject->getEntityId();
            $formData['weight'] = 0;

            if ($this->state->getAreaCode() == 'adminhtml' && empty($formData['return_type'])) {
                $formData['return_type'] = 'easy_return';
            }

            foreach ($result->getItems() 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) {
                            $formData['weight'] += $rmaItem->getQtyRequested() * $this->productRepository->get($sku)->getWeight();
                        }
                        continue;
                    }

                    $sku = $skus;
                }

                $formData['weight'] += $rmaItem->getQtyRequested() * $this->productRepository->get($sku)->getWeight();
            }
            $formData['store'] = $subject->getOrder()->getStore();
            $easyReturnRepository = $this->easyReturnRepository;
            /** @var EasyReturnInterface $easyReturn */
            $easyReturn = $this->easyReturnFactory->create();
            $easyReturn->setEasyReturnData($formData);
            $easyReturnRepository->save($easyReturn);
        } catch (Exception $e) {
            $this->logger->critical($e->getMessage(), ['exception' => $e]);
        } catch (Throwable $t) {
            $this->logger->critical($t->getMessage(), ['exception' => $t]);
        }
    }

    /**
     * @param $subject
     * @param $result
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function saveEasyReturnByApi($subject, $result, $returnType = 'easy-return')
    {
        $formData = $this->request->getParams();
        $formData['return_type'] = $returnType;
        if ($result->getExtensionAttributes()->getPickUpAddress()) {
            foreach ($result->getExtensionAttributes()->getPickUpAddress()->getData() as $k => $val) {
                $formData[$k] = $val;
            }
        }
        $formData['customer_firstname'] = $result->getExtensionAttributes()->getPickUpAddress()['firstname'];
        $formData['customer_lastname'] = $result->getExtensionAttributes()->getPickUpAddress()['lastname'];
        $formData['rma_entity_id'] = $subject->getEntityId();
        $formData['weight'] = 0;
        foreach ($result->getItems() as $rmaItem) {
            $formData['weight'] += $rmaItem->getQtyRequested() * $this->productRepository->get($rmaItem->getProductSku())->getWeight();
        }
        $formData['store'] = $subject->getOrder()->getStore();
        $formData['order_id'] = $subject->getOrder()->getId();
        $easyReturnRepository = $this->easyReturnRepository;
        $easyReturn = $this->easyReturnFactory->create()->setEasyReturnData($formData);
        $easyReturnRepository->save($easyReturn);
    }

    /**
     * @param $subject
     * @param $result
     * @return void
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function saveChangeSizeByApi($subject, $result)
    {
        $formData = $this->request->getParams();
        $formData['return_type'] = 'change_size';
        if ($result->getExtensionAttributes()->getPickUpAddress()) {
            foreach ($result->getExtensionAttributes()->getPickUpAddress()->getData() as $k => $val) {
                $formData[$k] = $val;
            }
        }



        $formData['customer_firstname'] = $result->getExtensionAttributes()->getPickUpAddress() ? $result->getExtensionAttributes()->getPickUpAddress()['firstname'] : $formData['customer_firstname'];
        $formData['customer_lastname'] = $result->getExtensionAttributes()->getPickUpAddress() ? $result->getExtensionAttributes()->getPickUpAddress()['lastname'] : $formData['customer_lastname'];
        $formData['rma_entity_id'] = $subject->getEntityId();
        $formData['weight'] = 0;
        foreach ($result->getItems() as $rmaItem) {
            $formData['weight'] += $rmaItem->getQtyRequested() * $this->productRepository->get($rmaItem->getProductSku())->getWeight();
        }
        $formData['store'] = $subject->getOrder()->getStore();
        $formData['order_id'] = $subject->getOrder()->getId();
        $easyReturnRepository = $this->easyReturnRepository;
        $easyReturn = $this->easyReturnFactory->create()->setEasyReturnData($formData);
        $easyReturnRepository->save($easyReturn);
    }
}
