<?php
namespace FiloBlu\Rma\Block\Returns;

use Exception;
use FiloBlu\Rma\Api\EasyReturnRepositoryInterface;
use FiloBlu\Rma\Api\RmaExtensionAttributesRepositoryInterface;
use FiloBlu\Rma\Helper\ChangeSizeAttributeHelper;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Helper\Session\CurrentCustomer;
use Magento\Customer\Helper\View as MagentoView;
use Magento\Directory\Model\RegionFactory;
use Magento\Eav\Model\Config;
use Magento\Eav\Model\Form\Factory;
use Magento\Framework\App\Http\Context;
use Magento\Framework\Data\Collection\ModelFactory;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Template\Context as TemplateContext;
use Magento\Rma\Helper\Data;
use Magento\Rma\Model\Item\FormFactory;
use Magento\Rma\Model\ItemFactory;
use Magento\Rma\Model\ResourceModel\Item\CollectionFactory as ItemCollectionFactory;
use Magento\Rma\Model\ResourceModel\Rma\Status\History\CollectionFactory;
use Magento\Rma\Model\Rma;
use Magento\Sales\Api\Data\OrderAddressInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order\Address;
use Throwable;

use function is_string;

/**
 *
 */
class View extends \Magento\Rma\Block\Returns\View
{
    const RMA_CUSTOM_CARRIER = 'filoblu_disablerma_section/rma_group/rma_option_carrier';
    /**
     * @var RmaExtensionAttributesRepositoryInterface
     */
    private $rmaExtensionAttributesRepository;
    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;
    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;
    /**
     * @var ChangeSizeAttributeHelper
     */
    private $changeSizeAttributeHelper;
    /**
     * @var EasyReturnRepositoryInterface
     */
    private $easyReturnRepository;
    /**
     * @var RegionFactory
     */
    private $regionFactory;


    /**
     * View constructor.
     * @param TemplateContext $context
     * @param ModelFactory $modelFactory
     * @param Factory $formFactory
     * @param Config $eavConfig
     * @param ItemCollectionFactory $itemsFactory
     * @param CollectionFactory $historiesFactory
     * @param ItemFactory $itemFactory
     * @param FormFactory $itemFormFactory
     * @param CurrentCustomer $currentCustomer
     * @param MagentoView $customerView
     * @param Context $httpContext
     * @param Data $rmaData
     * @param Registry $registry
     * @param CustomerRepositoryInterface $customerRepository
     * @param RmaExtensionAttributesRepositoryInterface $rmaExtensionAttributesRepository
     * @param OrderRepositoryInterface $orderRepository
     * @param ProductRepositoryInterface $productRepository
     * @param ChangeSizeAttributeHelper $changeSizeAttributeHelper
     * @param EasyReturnRepositoryInterface $easyReturnRepository
     * @param RegionFactory $regionFactory
     * @param array $data
     */
    public function __construct(
        TemplateContext $context,
        ModelFactory $modelFactory,
        Factory $formFactory,
        Config $eavConfig,
        ItemCollectionFactory $itemsFactory,
        CollectionFactory $historiesFactory,
        ItemFactory $itemFactory,
        FormFactory $itemFormFactory,
        CurrentCustomer $currentCustomer,
        MagentoView $customerView,
        Context $httpContext,
        Data $rmaData,
        Registry $registry,
        CustomerRepositoryInterface $customerRepository,
        RmaExtensionAttributesRepositoryInterface $rmaExtensionAttributesRepository,
        OrderRepositoryInterface $orderRepository,
        ProductRepositoryInterface $productRepository,
        ChangeSizeAttributeHelper $changeSizeAttributeHelper,
        EasyReturnRepositoryInterface $easyReturnRepository,
        RegionFactory $regionFactory,
        array $data = []
    ) {
        parent::__construct(
            $context,
            $modelFactory,
            $formFactory,
            $eavConfig,
            $itemsFactory,
            $historiesFactory,
            $itemFactory,
            $itemFormFactory,
            $currentCustomer,
            $customerView,
            $httpContext,
            $rmaData,
            $registry,
            $customerRepository,
            $data
        );
        $this->rmaExtensionAttributesRepository = $rmaExtensionAttributesRepository;
        $this->orderRepository = $orderRepository;
        $this->productRepository = $productRepository;
        $this->changeSizeAttributeHelper = $changeSizeAttributeHelper;
        $this->easyReturnRepository = $easyReturnRepository;
        $this->regionFactory = $regionFactory;
    }

    /**
     * Gets attribute value by rma item id and attribute code
     *
     * @param int $itemId
     * @param string $attributeCode
     * @return string
     * @throws NoSuchEntityException
     */
    public function getAttributeValue($itemId, $attributeCode)
    {
        if (empty($this->_realValueAttributes)) {
            $this->_realValueAttributes = $this->_getAdditionalData();
        }

        if (!isset($this->_realValueAttributes[$itemId][$attributeCode])) {
            return false;
        }

        if (!empty($this->_realValueAttributes[$itemId][$attributeCode]['html'])) {
            $html = $this->_realValueAttributes[$itemId][$attributeCode]['html'];
        } else {
            if ($attributeCode == ChangeSizeAttributeHelper::ORDER_STATUS_CHANGESIZE_CODE) {
                $html = $this->escapeHtml($this->getChangeSizeItems($itemId)['value']);
            } else {
                if (
                    $this->_getAdditionalData(
                    )[$itemId][$attributeCode]['value'] == $this->changeSizeAttributeHelper->getChangeSizeLabelByStoreId(
                        $this->_storeManager->getStore()->getId()
                    )
                ) {
                    $html = '<span>' . $this->_getAdditionalData(
                    )[$itemId][$attributeCode]['value'] . '</span><br/>' . $this->getItems()->getItems(
                    )[$itemId]->getProductName() .
                        "<dl class=\"item options\"><dt>" . $this->getItemOptions(
                            $this->getItems()->getItems()[$itemId]
                        )[0]['label'] . '</dt><dd>' . $this->getChangeSizeItems($itemId)['value'] . '</dd></dl>';
                } else {
                    $html = $this->escapeHtml($this->_realValueAttributes[$itemId][$attributeCode]['value']);
                }
            }
        }
        return $html;
    }

    /**
     * @param array|string $data
     * @param null $allowedTags
     * @return string
     * @throws NoSuchEntityException
     */
    public function escapeHtml($data, $allowedTags = null)
    {
        $label = $this->changeSizeAttributeHelper->getChangeSizeLabelByStoreId($this->_storeManager->getStore()->getId());

        if ($label && is_string($data) && strpos($data, $label) !== false) {
            return $data;
        }

        return parent::escapeHtml($data, $allowedTags);
    }

    /**
     * @param $myItemId
     * @return array
     */
    public function getChangeSizeItems($myItemId)
    {

        try {
            $newSize = array_fill_keys(['label', 'value'], '');
            $changeSizeOrderId = $this->rmaExtensionAttributesRepository->getChangeSizeOrderId($myItemId);
            if ($changeSizeOrderId) {
                $changeSizeOrder = $this->orderRepository->get($changeSizeOrderId);
                $items = $changeSizeOrder->getItems();
                foreach ($items as $item) {
                    $product = $this->productRepository->get($item->getSku());
                    $newSize ['label'] = $item->getProduct()->getName();
                    $newSize ['value'] = $product->getResource()->getAttribute('size')->getFrontend()->getValue($product);
                }
            } else {
                $newSize['value'] = 'No';
            }
            return $newSize;
        } catch (Exception $exception) {
            $this->_logger->critical($exception->getMessage(), ['exception' => $exception]);
            return array_fill_keys(['label', 'value'], '');
        }
    }

    /**
     * @return bool
     */
    public function isCustomCarrierEnabled()
    {
        return $this->_scopeConfig->getValue(self::RMA_CUSTOM_CARRIER) ?? false;
    }

    /**
     * @return OrderAddressInterface|Address|null
     */
    public function getPickupAddress()
    {
        try {
            /** @var Rma $rma */
            $rmaId = $this->getRma()->getEntityId();
            $easyReturn = $this->easyReturnRepository->getByRmaId($rmaId);

            if (!$easyReturn) {
                return $rma->getOrder()->getShippingAddress();
            }

            if ($easyReturn->getRegionId()) {
                $regionName = $this->regionFactory->create()->load($easyReturn->getRegionId());
                $easyReturn->setRegion($regionName->getName());
            }

            return $easyReturn->getPickUpAddress();
        } catch (Exception $exception) {
            $this->_logger->critical($exception->getMessage(), ['exception' => $exception]);
        } catch (Throwable $throwable) {
            $this->_logger->critical($throwable->getMessage(), ['exception' => $throwable]);
        }

        return null;
    }
}
