<?php

namespace FiloBlu\ActiveCampaign\Block\Adminhtml\System\Config\Order;

use FiloBlu\ActiveCampaign\Api\FieldsRepositoryInterface;
use FiloBlu\ActiveCampaign\Block\Adminhtml\System\Config\AbstractConfig;
use Magento\Backend\Block\Template\Context;
use Magento\Catalog\Model\Product;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\View\Element\Html\Select;

/**
 * Class ItemsExtraAttributes
 * @package FiloBlu\ActiveCampaign\Block\Adminhtml\System\Config\Order
 */
class ItemsExtraAttributes extends AbstractConfig
{
    /**
     * Product Object
     *
     * @var Product
     */
    protected $model;

    /**
     * @var string
     */
    protected $id = 'item';

    /**
     * @var string
     */
    protected $type = 'eav';

    /**
     * ItemsExtraAttributes constructor.
     * @param Product $product
     * @param Context $context
     * @param ResourceConnection $resourceConnection
     * @param FieldsRepositoryInterface $fieldsRepository
     * @param array $data
     */
    public function __construct(
        Product $product,
        Context $context,
        ResourceConnection $resourceConnection,
        FieldsRepositoryInterface $fieldsRepository,
        array $data = []
    ) {
        $this->model = $product;
        parent::__construct($context, $resourceConnection, $fieldsRepository, $data);
    }

    /**
     * Prepare to render
     *
     * @return void
     * @throws LocalizedException
     */
    protected function _prepareToRender()
    {
        $customAttributes = $this->getAttributesToRender();
        array_unshift($customAttributes, ['value' => '', 'label' => __('-- Select an attribute --')]);

        $customAttributesBlock =
            $this->getLayout()
                ->createBlock(Select::class)
                ->setId($this->_getCellInputElementId('<%- _id %>', $this->id.'_magento_field'))
                ->setName($this->_getCellInputElementName($this->id.'_magento_field'))
                ->setClass('select')
                ->setOptions($customAttributes);

        $this->addColumn("{$this->id}_magento_field", [
            'label' => __('Magento Field'),
            'renderer' => $customAttributesBlock,
            'style' => 'min-width:100px'
        ]);
        $this->addColumn("{$this->id}_activecampaign_field", [
            'label' => __('Active Campaign Field'),
            'style' => 'min-width:200px'
        ]);

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

}
