<?php

namespace Autogedal\InternalLinks\Model;

use Magento\Framework\App\ResourceConnection;
use Magento\Store\Model\StoreManagerInterface;
use Autogedal\InternalLinks\Model\SlugHandler;
use Magento\Framework\App\Config\ScopeConfigInterface;

class Brand
{
    private $resourceConnection;
    private $storeManager;
    private $slugHandler;
    private $config;
    private $scopeConfig;

    public function __construct(
        ResourceConnection $resourceConnection,
        StoreManagerInterface $storeManager,
        SlugHandler $slugHandler,
        Config $config,
        ScopeConfigInterface $scopeConfig
    ) {
        $this->resourceConnection = $resourceConnection;
        $this->storeManager = $storeManager;
        $this->slugHandler = $slugHandler;
        $this->config = $config;
        $this->scopeConfig = $scopeConfig;
    }

    public function getBySlug($slug)
    {
        $attributeId = $this->config->getBrandAttributeId();

        $connection = $this->resourceConnection->getConnection();
        $storeId = $this->storeManager->getStore()->getId();

        $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 = ?', $attributeId)
            ->where('value.store_id IN (?)', [0, $storeId]);

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

        foreach ($results as $row) {
            if ($this->slugHandler->createSlug($row['value']) === $slug) {
                return (object) $row;
            }
        }

        return null;
    }

    public function getOrderedBrands($storeId = null)
    {
        $brandAttributeId = $this->config->getBrandAttributeId($storeId);

        $brandOrder = $this->scopeConfig->getValue(
            'autogedal_internal_links/brand_ordering/brand_order',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
            $storeId
        );

        if (!$brandAttributeId) {
            return [];
        }

        $connection = $this->resourceConnection->getConnection();
        $currentStoreId = $storeId ?: $this->storeManager->getStore()->getId();

        $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)
            ->where('value.store_id IN (?)', [0, $currentStoreId])
            ->order('value.value ASC');

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

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

        if ($brandOrder) {
            $orderedIds = explode(',', $brandOrder);
            $orderedBrands = [];

            foreach ($orderedIds as $id) {
                if (isset($brands[$id])) {
                    $orderedBrands[] = $brands[$id];
                }
            }

            return $orderedBrands;
        }

        return array_values($brands);
    }
}

