<?php
/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Shop by Base for Magento 2 (System)
 */

namespace Amasty\ShopbyBase\Model\Source;

use Magento\Framework\Option\ArrayInterface;
use Magento\Eav\Model\Config as EavConfig;

class Attribute implements ArrayInterface
{
    /**
     * @var EavConfig
     */
    private EavConfig $eavConfig;

    /**
     * @var array|null
     */
    private ?array $attributes = null;

    /**
     * @var int|null
     */
    private ?int $skipAttributeId = null;

    public function __construct(
        EavConfig $eavConfig
    ) {
        $this->eavConfig = $eavConfig;
    }

    /**
     * Options getter
     *
     * @return array
     */
    public function toOptionArray($boolean = 1)
    {
        $optionArray = [];
        $arr = $this->toArray($boolean);
        foreach ($arr as $value => $label) {
            $optionArray[] = [
                'value' => $value,
                'label' => $label
            ];
        }
        return $optionArray;
    }

    /**
     * Get options in "key-value" format
     *
     * @return array
     */
    public function toArray($boolean = 1)
    {
        if ($this->attributes === null) {
            $this->attributes = [];
            /** @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection $collection */
            $collection = $this->eavConfig->getEntityType(
                \Magento\Catalog\Model\Product::ENTITY
            )->getAttributeCollection();

            $collection->join(
                ['catalog_eav' => $collection->getTable('catalog_eav_attribute')],
                'catalog_eav.attribute_id=main_table.attribute_id',
                []
            )->addFieldToFilter('catalog_eav.is_filterable', ['neq' =>  0]);

            if ($this->skipAttributeId !== null) {
                $collection->addFieldToFilter('main_table.attribute_id', ['neq' => $this->skipAttributeId]);
            }
            if (!$boolean) {
                $collection->addFieldToFilter('main_table.frontend_input', ['neq' => 'boolean']);
            }
            /** @var \Magento\Eav\Model\Attribute $item */
            foreach ($collection as $item) {
                $this->attributes[$item->getId()] = $item->getFrontendLabel();
            }
        }

        return $this->attributes;
    }

    /**
     * @param $skipAttributeId
     * @return $this
     */
    public function skipAttributeId($skipAttributeId)
    {
        $this->skipAttributeId = (int)$skipAttributeId;
        return $this;
    }
}
