<?php
/**
 * @module  Autogedal_SeoCanonical
 * @author  Autogedal
 * @licence OSL 3.0
 */

namespace Autogedal\SeoCanonical\Block\Adminhtml\Form\Field;

use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory;
use Magento\Framework\View\Element\Context;
use Magento\Framework\View\Element\Html\Select;

class AttributeColumn extends Select
{
    /**
     * @var CollectionFactory
     */
    protected $attributeCollectionFactory;

    /**
     * @param Context $context
     * @param CollectionFactory $attributeCollectionFactory
     * @param array $data
     */
    public function __construct(
        Context $context,
        CollectionFactory $attributeCollectionFactory,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->attributeCollectionFactory = $attributeCollectionFactory;
    }

    /**
     * Set "name" for <select> element
     *
     * @param string $value
     * @return $this
     */
    public function setInputName($value)
    {
        return $this->setName($value);
    }

    /**
     * Set "id" for <select> element
     *
     * @param string $value
     * @return $this
     */
    public function setInputId($value)
    {
        return $this->setId($value);
    }

    /**
     * Render block HTML
     *
     * @return string
     */
    public function _toHtml()
    {
        if (!$this->getOptions()) {
            $this->setOptions($this->getAttributeOptions());
        }
        return parent::_toHtml();
    }

    /**
     * Get all filterable product attributes as options
     *
     * @return array
     */
    private function getAttributeOptions()
    {
        $options = [['value' => '', 'label' => __('-- Please Select --')]];

        $collection = $this->attributeCollectionFactory->create();
        $collection->addFieldToFilter('is_filterable', ['gt' => 0]);

        foreach ($collection as $attribute) {
            $options[] = [
                'value' => $attribute->getAttributeId(),
                'label' => $attribute->getFrontendLabel() . ' (' . $attribute->getAttributeCode() . ')'
            ];
        }

        return $options;
    }
}
