<?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\Framework\Webapi\Request;
use Magento\Rma\Model\Rma;
use Magento\Sales\Model\Order\AddressFactory;
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;
    /**
     * @var AddressFactory
     */
    private $addressFactory;
    /**
     * @var Request
     */
    private $webApiRequest;

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

    /**
     * @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') {
            $this->setRmaExtensionAttributes($result);
        }

        foreach ($subject->getItems() as $item) {
            if ($item->getResolution() == $this->changeSizeAttributeHelper->getChangeSizeAttributeOptionId()) {
                if ($this->state->getAreaCode() == 'adminhtml') {
                    //$returnType = 'easy-return';
                    $this->setRmaExtensionAttributes($result, true);
                    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()) {
                $easyReturn = $this->request->getParam('easy_return');
                if (empty($returnType) && $easyReturn) {
                    $returnType = 'easy-return';
                }
                $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();
        $formData['items'] = $subject->getItems();
        $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);
    }

    public function setRmaExtensionAttributes($rma, $isChangeSize = false)
    {
        //$returnType = 'easy-return';
        $postParams = $this->request->getParams();
        $isEasyReturn = array_key_exists('easy_return', $postParams) ? (bool)$postParams['easy_return'] : false;

        if (!$isEasyReturn && $isChangeSize) {
            $isEasyReturn = true;
        }

        //$returnType = $isEasyReturn ? 'easy-return' : 'normal-return';
        $this->setItemsExtensionAttributes($rma, $postParams);

        $extensionAttributes = $rma->getExtensionAttributes();
        $extensionAttributes->setEasyReturn($isEasyReturn);

        $shippingAddress = $this->addressFactory->create();

        foreach ($rma->getOrder()->getShippingAddress()->toArray() as $key => $value) {
            if (!array_key_exists($key, $postParams)) {
                continue;
            }

            $value = $postParams[$key];

            $shippingAddress->setData($key, $value);
        }

        if ($isEasyReturn) {
            $extensionAttributes->setPickupAddress($shippingAddress);
        }

        $rma->setExtensionAttributes($extensionAttributes);
    }

    public function setItemsExtensionAttributes($rma, $postParams)
    {
        foreach ($rma->getItems() as $key => $item) {
            $itemExtensionAttributes = $item->getExtensionAttributes();
            if ($itemExtensionAttributes === null) {
                $itemExtensionAttributes = $this->easyReturnFactory->create()->getExtensionAttributes();
            }

            if (isset($postParams['items']['new' . $key]['change_size'])) {

                $itemExtensionAttributes->setChangeSize($postParams['items']['new' . $key]['change_size']);
            }



            $item->setExtensionAttributes($itemExtensionAttributes);
        }
    }
}
