<?php

namespace Autogedal\InternalLinks\Model\Config\Source;

use Magento\Framework\Data\OptionSourceInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ResourceConnection;

class BrandValues implements OptionSourceInterface
{
    private $scopeConfig;
    private $resourceConnection;

    public function __construct(
        ScopeConfigInterface $scopeConfig,
        ResourceConnection $resourceConnection
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->resourceConnection = $resourceConnection;
    }

    public function toOptionArray()
    {
        $options = [];
        $brandAttributeId = $this->scopeConfig->getValue('autogedal_internal_links/general/brand_attribute_id');

        if (!$brandAttributeId) {
            return $options;
        }

        $connection = $this->resourceConnection->getConnection();

        $select = $connection->select()
            ->from(['option' => $this->resourceConnection->getTableName('eav_attribute_option')], ['option_id', 'sort_order'])
            ->join(
                ['value' => $this->resourceConnection->getTableName('eav_attribute_option_value')],
                'option.option_id = value.option_id',
                ['value']
            )
            ->where('option.attribute_id = ?', $brandAttributeId)
            ->order('value.value ASC');

        $results = $connection->fetchAll($select);

        foreach ($results as $row) {
            if ($row['value']) {
                $options[] = [
                    'value' => $row['option_id'],
                    'label' => $row['value']
                ];
            }
        }

        return $options;
    }
}
