<?php
/**
 * Copyright © 2016 Filoblu S.r.l. All rights reserved.
 */

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

use Magento\Backend\Block\Template\Context;
use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;
use Magento\Framework\Module\Manager;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\Element\Html\Select;
use Magento\GiftWrapping\Model\ResourceModel\Wrapping\CollectionFactory;

/**
 * Renderer for Gift Wrap associated products Configuration
 */

class Gwproducts extends AbstractFieldArray
{
    /**
     * @var
     */
    private $moduleManager;

    /**
     * @var \Magento\Framework\ObjectManagerInterface
     */
    private $objectManager;

    /**
     * Constructor
     *
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Framework\ObjectManagerInterface $objectManager
     * @param \Magento\Framework\Module\Manager $moduleManager
     * @param array $data
     */
    public function __construct(
        Context $context,
        ObjectManagerInterface $objectManager,
        Manager $moduleManager,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->moduleManager = $moduleManager;
        $this->objectManager = $objectManager;
    }

    /**
     * @return void
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function _prepareToRender()
    {
        $wrappings = [];

        if ($this->moduleManager->isEnabled('Magento_GiftWrapping')) {
            $wrappingCollectionFactory = $this->objectManager->get(CollectionFactory::class);

            $wrappingCollectionItems = $wrappingCollectionFactory->create()->addStoreAttributesToResult()->getItems();

            foreach ($wrappingCollectionItems as $wrapping) {
                $wrappings[] = ['value' => $wrapping['wrapping_id'], 'label' => __($wrapping['wrapping_id'] . ' - ' . $wrapping['design'])];
            }

            array_unshift($wrappings, ['value' => '*', 'label' => __('-- Any --')]);
        }

        $gwprodBlock = $this->getLayout()->createBlock(Select::class)
            ->setId($this->_getCellInputElementId('<%- _id %>', 'wrapping_id'))
            ->setName($this->_getCellInputElementName('wrapping_id'))
            ->setClass('select')
            ->setOptions($wrappings);

        $this->addColumn('wrapping_id', [
            'label' => __('Gift Wrap'),
            'renderer' => $gwprodBlock
        ]);

        $this->addColumn('product_sku', [
            'label' => __('Product SKU')
        ]);

        $this->_addAfter = false;
        $this->_addButtonLabel = __('Add new mapping');
    }
}
