<?php

namespace FiloBlu\Rma\Block\Adminhtml\System\Config;

use Magento\Backend\Block\Template\Context;
use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;
use Magento\Eav\Model\Config;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\View\Element\BlockInterface;
use Magento\Framework\View\Element\Html\Select;
use Magento\Rma\Model\RmaFactory;
use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory as AttributeCollectionFactory;

/**
 *
 */
class ReasonToDisableEmail extends AbstractFieldArray
{

    /**
     * @var Config $eavConfig ,
     */
    protected $eavConfig;

    /**
     * @var Select|null
     */
    protected $reasonRenderer;

    /**
     * @var Select|null
     */
    protected $rmaStatusRenderer;
    /**
     * @var RmaFactory
     */
    protected $rmaFactory;
    /**
     * @var BlockInterface|Select|(Select&BlockInterface)
     */
    protected $productAttributesRenderer;
    /**
     * @var Context
     */
    private $context;
    /**
     * @var AttributeCollectionFactory
     */
    private $attributeCollectionFactory;

    /**
     * Constructor
     *
     * @param Config $eavConfig
     * @param Context $context
     * @param RmaFactory $rmaFactory
     * @param AttributeCollectionFactory $attributeCollectionFactory
     * @param array $data
     */
    public function __construct(
        Config  $eavConfig,
        Context $context,
        RmaFactory $rmaFactory,
        AttributeCollectionFactory $attributeCollectionFactory,
        array   $data = []
    ) {
        parent::__construct($context, $data);
        $this->eavConfig = $eavConfig;
        $this->rmaFactory = $rmaFactory;
        $this->context = $context;
        $this->attributeCollectionFactory = $attributeCollectionFactory;
    }


    /**
     * @throws LocalizedException
     */
    protected function _prepareToRender()
    {
        $this->addColumn('rma_reson', [
            'label'    => __('Rma Reason'),
            'renderer' => $this->getReasonRenderer()
        ]);


        /**
         * TODO: spostare la logica sottostante in una setting diversa.
         * Bisogna poi cambiare le logiche in cui vengono usate.
         * Le classi che la utilizzano partono da RmaHelper controllare tutte le classi che utilizzano
         * i metodi annessi
         */
        $this->addColumn('rma_status_product_attribute_bind', [
            'label'    => __('Product Attribute Is'),
            'renderer' => $this->getRmaStatusProductAttributeBindRenderer()
        ]);

        $this->addColumn('rma_status', [
            'label'    => __('Set Rma Status To'),
            'renderer' => $this->getRmaStatusRenderer()
        ]);


        $this->_addAfter = false;
        $this->_addButtonLabel = __('Add Rma Reason');
    }

    private function getReasonRenderer()
    {
        if (!$this->reasonRenderer) {
            $select = $this->getLayout()->createBlock(
                Select::class,
                '',
                ['data' => []]
            );

            $attribute = $this->eavConfig->getAttribute('rma_item', 'reason');
            $options = [];

            if ($attribute !== null) {
                $options = $attribute->getSource()->getAllOptions();
            }

            $reasonOptions = [];

            foreach ($options as $option) {
                if (!empty($option['value'])) {
                    $reasonOptions[] = ['value' => $option['value'], 'label' => $option['label']];
                }
            }

            array_unshift($reasonOptions, ['value' => '*', 'label' => __('-- Select --')]);

            $select->setOptions($reasonOptions)
                ->setId($this->_getCellInputElementId('<%- _id %>', 'rma_reson'))
                ->setName($this->_getCellInputElementName('rma_reson'))
                ->setClass('select');

            $this->reasonRenderer = $select;
        }

        return $this->reasonRenderer;
    }

    /**
     * Renderer per la colonna Change Rma Status
     *
     * @return Select
     * @throws LocalizedException
     */
    private function getRmaStatusRenderer()
    {
        if (!$this->rmaStatusRenderer) {
            $select = $this->getLayout()->createBlock(
                Select::class,
                '',
                ['data' => []]
            );

            // Recuperiamo gli stati del RMA
            $statusOptions = [
                ['value' => '', 'label' => __('No')] // Opzione default
            ];

            $statuses = $this->getRmaStatuses();

            foreach ($statuses as $code => $label) {
                $statusOptions[] = ['value' => $code, 'label' => $label];
            }

            $select->setOptions($statusOptions)
                ->setId($this->_getCellInputElementId('<%- _id %>', 'rma_status'))
                ->setName($this->_getCellInputElementName('rma_status'))
                ->setClass('select');

            $this->rmaStatusRenderer = $select;
        }

        return $this->rmaStatusRenderer;
    }

    private function getRmaStatuses()
    {
        $rmaStatuses = $this->rmaFactory->create()->getAllStatuses();

        $rmaStatusesForSelect = [];

        foreach ($rmaStatuses as $name => $item) {
            $rmaStatusesForSelect[$name] = $item->getText();
        }

        return $rmaStatusesForSelect;
    }

    private function getRmaStatusProductAttributeBindRenderer()
    {
        if (!$this->productAttributesRenderer) {


            $options = [['value' => '', 'label' => __('-- Please Select --')]];

            foreach ($this->attributeCollectionFactory->create() as $attribute) {
                $options[] = [
                    'value' => $attribute->getAttributeCode(),
                    'label' => $attribute->getStoreLabel()
                ];

            }

            $select = $this->getLayout()->createBlock(
                Select::class,
                '',
                ['data' => []]
            );

            $select->setOptions($options)
                ->setId($this->_getCellInputElementId('<%- _id %>', 'rma_status_product_attribute_bind'))
                ->setName($this->_getCellInputElementName('rma_status_product_attribute_bind'))
                ->setClass('select');

            $this->productAttributesRenderer = $select;
        }

        return $this->productAttributesRenderer;
    }
}
