<?php
/**
 * Created by PhpStorm.
 * User: jderosa
 * Date: 31/10/19
 * Time: 12.23
 */

namespace FiloBlu\Rma\Plugin\Block\Form\Renderer;

use Exception;
use FiloBlu\Rma\Api\Model\Config\Reader;
use FiloBlu\Rma\Helper\ChangeSizeAttributeHelper;
use FiloBlu\Rma\Helper\SerializerHelper;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;
use Throwable;

/**
 *
 */
class Select
{

    /**
     * @var Reader
     */
    protected $reader;

    /**
     * @var SerializerHelper
     */
    protected $serializer;

    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var OrderInterface
     */
    protected $orderInterface;

    /**
     * @var ChangeSizeAttributeHelper
     */
    protected $changeSizeAttributeHelper;

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

    /**
     * Select constructor.
     * @param Reader $reader
     * @param SerializerHelper $serializer
     * @param ScopeConfigInterface $scopeConfig
     * @param StoreManagerInterface $storeManager
     * @param RequestInterface $request
     * @param OrderInterface $orderInterface
     * @param ChangeSizeAttributeHelper $changeSizeAttributeHelper
     * @param LoggerInterface $logger
     */
    public function __construct(
        Reader $reader,
        SerializerHelper $serializer,
        ScopeConfigInterface $scopeConfig,
        StoreManagerInterface $storeManager,
        RequestInterface $request,
        OrderInterface $orderInterface,
        ChangeSizeAttributeHelper $changeSizeAttributeHelper,
        LoggerInterface $logger
    ) {
        $this->reader = $reader;
        $this->serializer = $serializer;
        $this->scopeConfig = $scopeConfig;
        $this->storeManager = $storeManager;
        $this->request = $request;
        $this->orderInterface = $orderInterface;
        $this->changeSizeAttributeHelper = $changeSizeAttributeHelper;
        $this->logger = $logger;
    }

    /**
     * @param \Magento\Rma\Block\Form\Renderer\Select $subject
     * @param $result
     * @return mixed
     */
    public function afterGetOptions(\Magento\Rma\Block\Form\Renderer\Select $subject, $result)
    {
        try {
            foreach ($result as $k => $value) {
                if (isset($value['value']) && $value['value'] == '') {
                    array_splice($result, $k, 1);
                }
            }
            $attribute_code = $subject->getAttributeObject()->getAttributeCode();

            $all_options = $result;

            if ($attribute_code === 'reason') {
                $this->reader->read();
                $configData = $this->scopeConfig->getValue('sales/rma_reason/reason') ?? '';

                if ($configData != '') {
                    $mapping = $this->serializer->unserialize($configData);
                    $allowedReason = [];
                    if (count($mapping) > 0) {
                        foreach ($all_options as $option) {
                            foreach ($mapping as $map) {
                                if (($map['brand_reason'] == $option['value']) && $map['is_visible'] == 1) {
                                    $allowedReason[] = $option;
                                }
                            }
                        }
                    }
                    return $allowedReason;
                }

                return $all_options;
            }

            /**
             * L'opzione "change_size" dell'attributo "resolution" NON va mostrata nei seguenti casi:
             * 1. se la funzionalità Cambio Taglia è disabilitata in:
             *    Stores -> Configuration -> FiloBlu -> RMA Configuration -> Allow User to choose Change Size Option
             * 2. se l'ordine di cui sto chiedendo il reso ha come metodo di pagamento "Change Size Pay":
             *    non si può chiedere il cambio taglia per la seconda volta (solo area personale cliente - il CC sa quello che fa)
             */
            if ($attribute_code == 'resolution') {
                $_order = $this->orderInterface->load($this->request->getParam('order_id'));
                $payment_method = $_order->getPayment()->getMethod();

                if (!$this->changeSizeIsEnabled(
                    $this->storeManager->getWebsite()->getId()
                ) || $payment_method == 'changesizepay') {
                    $allowed = [];
                    foreach ($all_options as $option) {
                        if ($option['value'] != $this->changeSizeAttributeHelper->getChangeSizeAttributeOptionId()) {
                            $allowed [] = $option;
                        }
                    }
                    $all_options = $allowed;
                }
            }

            return $all_options;
        } catch (Exception $e) {
            $this->logger->critical($e->getMessage());
            return $result;
        } catch (Throwable $t) {
            $this->logger->critical($t->getMessage());
            return $result;
        }
    }

    /**
     * @param null $websiteId
     * @return bool|mixed
     */
    public function changeSizeIsEnabled($websiteId = null)
    {
        return $this->changeSizeAttributeHelper->isChangeSizeEnabled($websiteId);
    }
}
