<?php

/**
 * Created by PhpStorm.
 * User: jderosa
 * Date: 15/01/20
 * Time: 8.59
 */

namespace FiloBlu\Rma\Helper;

use Exception;
use FiloBlu\Rma\Logger\Logger;
use FiloBlu\Rma\Model\Payment\ChangeSizePay;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Model\AttributeRepository;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use Psr\Log\LoggerInterface;
use Throwable;

/**
 *
 */
class ChangeSizeAttributeHelper
{
    const REASON_CHANGE_SIZE_LABEL = 'Change Size';
    const REASON_CHANGE_SIZE_ENTITY_CODE = 'rma_item';
    const RMA_RESOLUTION_ATTRIBUTE_CODE = 'resolution';
    const ORDER_STATUS_CHANGESIZE_CODE = 'change_size';
    const ORDER_STATUS_CHANGESIZE_LABEL = 'Change Size Order';
    const CHANGE_SIZE_RMA_ATTRIBUTE_CODE = 'change_size';
    const RESOLUTION_CHANGE_SIZE_OPTION_CODE = 'change_size';
    const RMA_CHANGE_SIZE_OPTION_MAPPING = 'filoblu_disablerma_section/rma_group/changesize_option_mapping';
    const CHANGE_SIZE_OPTION_ENABLE = 'filoblu_disablerma_section/rma_group/rma_change_size';
    const ALLOW_CHANGESIZEORDER_TO_USE_CHANGESIZE = 'filoblu_disablerma_section/rma_group/rma_change_sizeorder_can_use_changesize';
    const ALLOW_CHANGESIZEORDER_ADD_SHIPPING_COSTS = 'filoblu_disablerma_section/rma_group/add_shipping_costs';

    /**
     * @var AttributeRepository
     */
    protected $attributeRepository;

    /**
     * @var LoggerInterface
     */
    protected $logger;


    /**
     * @var CollectionFactory
     */
    protected $attributeOptionCollectionFactory;

    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;
    /**
     * @var Logger
     */
    private $filobluLogger;
    /**
     * @var ChangeSizePay
     */
    private $changeSizePay;

    /**
     * ChangeSizeAttributeHelper constructor.
     * @param AttributeRepository $attributeRepository
     * @param LoggerInterface $logger
     * @param CollectionFactory $attributeOptionCollectionFactory
     * @param ScopeConfigInterface $scopeConfig
     * @param Logger $filobluLogger
     * @param ChangeSizePay $changeSizePay
     */
    public function __construct(
        AttributeRepository $attributeRepository,
        LoggerInterface $logger,
        CollectionFactory $attributeOptionCollectionFactory,
        ScopeConfigInterface $scopeConfig,
        Logger $filobluLogger,
        ChangeSizePay $changeSizePay
    ) {
        $this->attributeRepository = $attributeRepository;
        $this->logger = $logger;
        $this->attributeOptionCollectionFactory = $attributeOptionCollectionFactory;
        $this->scopeConfig = $scopeConfig;
        $this->filobluLogger = $filobluLogger;
        $this->changeSizePay = $changeSizePay;
    }

    /**
     * @return array|AttributeOptionInterface[]|null
     */
    public function getAllResolutionOptions()
    {
        try {
            $resolution = $this->attributeRepository->get(
                self::REASON_CHANGE_SIZE_ENTITY_CODE,
                self::RMA_RESOLUTION_ATTRIBUTE_CODE
            );
            return $resolution->getOptions();
        } catch (Exception $e) {
            $this->logger->critical($e->getMessage(), ['exception' => $e]);

        }

        return [];
    }

    /**
     * @param int $storeId
     * @return string
     */
    public function getChangeSizeLabelByStoreId($storeId = 0)
    {
        try {
            $changeSizeOption = $this->attributeOptionCollectionFactory->create()
                ->addFieldToFilter('main_table.option_id', ['eq' => $this->getChangeSizeAttributeOptionId()])
                ->setStoreFilter($storeId)->getFirstItem();
            return $changeSizeOption->getValue() ?? $changeSizeOption->getDefaultValue();
        } catch (Exception $e) {
            $this->logger->critical($e->getMessage(), ['exception' => $e]);
            return '';
        }
    }

    /**
     * @return int
     */
    public function getChangeSizeAttributeOptionId()
    {
        try {
            return (int)$this->scopeConfig->getValue(self::RMA_CHANGE_SIZE_OPTION_MAPPING);
        } catch (Exception $e) {
            $this->logger->critical($e->getMessage(), ['exception' => $e]);
            return 0;
        }
    }

    /**
     * @return array
     */
    public function getAllChangeSizeLabel()
    {
        $labels = [];
        try {
            $changeSizeOptions = $this->attributeOptionCollectionFactory->create()
                ->addFieldToFilter('main_table.option_id', ['eq' => $this->getChangeSizeAttributeOptionId()])
                ->distinct(true)
                ->getItems();

            foreach ($changeSizeOptions as $option) {
                $labels [] = $option->getValue();
            }
        } catch (Exception $e) {
            $this->logger->critical($e->getMessage(), ['exception' => $e]);
        }

        return $labels;
    }

    /**
     * @param null $websiteId
     * @return bool
     */
    public function isChangeSizeEnabled($websiteId = null)
    {
        return $this->scopeConfig->isSetFlag(
            self::CHANGE_SIZE_OPTION_ENABLE,
            ScopeInterface::SCOPE_WEBSITE,
            $websiteId
        );
    }

    /**
     * @param null $websiteId
     * @return bool
     */
    public function canChangesizeOrderUseChangesize($websiteId = null)
    {
        return $this->scopeConfig->isSetFlag(
            self::ALLOW_CHANGESIZEORDER_TO_USE_CHANGESIZE,
            ScopeInterface::SCOPE_WEBSITE,
            $websiteId
        );
    }

    /**
     * @param $order
     * @return bool
     */
    public function isChangeSizeOrder($order)
    {
        try {
            return $order->getPayment()->getMethod() == $this->changeSizePay->getCode();
        } catch (Exception $e) {
            $this->filobluLogger->debug($e->getMessage(), ['exception' => $e]);
        } catch (Throwable $t) {
            $this->filobluLogger->debug($t->getMessage(), ['exception' => $t]);
        }
        return false;
    }

    public function mustAddShippingCosts($websiteId = null)
    {
        return $this->scopeConfig->isSetFlag(
            self::ALLOW_CHANGESIZEORDER_ADD_SHIPPING_COSTS,
            ScopeInterface::SCOPE_STORE,
            $websiteId
        );
    }
}
