<?php

namespace Autogedal\InternalLinks\Block;

use Magento\Framework\View\Element\Template;
use Autogedal\InternalLinks\Model\Config;
use Autogedal\InternalLinks\Model\SlugHandler;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory as OptionCollectionFactory;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;

class BrandList extends Template
{
    private $config;
    private $optionCollectionFactory;
    private $storeManager;
    private $resourceConnection;
    private $slugHandler;
    private $scopeConfig;
    private $productCollectionFactory;

    public function __construct(
        Template\Context $context,
        Config $config,
        SlugHandler $slugHandler,
        OptionCollectionFactory $optionCollectionFactory,
        StoreManagerInterface $storeManager,
        ResourceConnection $resourceConnection,
        ProductCollectionFactory $productCollectionFactory,
        array $data = []
    ) {
        $this->config = $config;
        $this->slugHandler = $slugHandler;
        $this->optionCollectionFactory = $optionCollectionFactory;
        $this->storeManager = $storeManager;
        $this->resourceConnection = $resourceConnection;
        $this->productCollectionFactory = $productCollectionFactory;
        $this->scopeConfig = $context->getScopeConfig();
        parent::__construct($context, $data);
    }

    public function getBrands()
    {
        $brandAttributeId = $this->config->getBrandAttributeId();
        if (!$brandAttributeId) {
            return [];
        }

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

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

        $orderedBrandIds = [];
        if ($brandOrder) {
            $orderedBrandIds = explode(',', $brandOrder);
        }

        $select = $connection->select()
            ->from(['option' => $this->resourceConnection->getTableName('eav_attribute_option')], ['option_id'])
            ->join(
                ['value' => $this->resourceConnection->getTableName('eav_attribute_option_value')],
                'option.option_id = value.option_id',
                ['value']
            )
            ->join(
                ['product_varchar' => $this->resourceConnection->getTableName('catalog_product_entity_varchar')],
                'product_varchar.value = option.option_id',
                []
            )
            ->join(
                ['product' => $this->resourceConnection->getTableName('catalog_product_entity')],
                'product.entity_id = product_varchar.entity_id',
                []
            )
            ->joinLeft(
                ['status_attr' => $this->resourceConnection->getTableName('eav_attribute')],
                'status_attr.attribute_code = "status" AND status_attr.entity_type_id = 4',
                []
            )
            ->joinLeft(
                ['status' => $this->resourceConnection->getTableName('catalog_product_entity_int')],
                'status.entity_id = product.entity_id AND status.attribute_id = status_attr.attribute_id AND status.store_id IN (0, ' . $storeId . ')',
                []
            )
            ->where('option.attribute_id = ?', $brandAttributeId)
            ->where('value.store_id IN (?)', [0, $storeId])
            ->where('product_varchar.attribute_id = ?', $brandAttributeId)
            ->where('product_varchar.store_id IN (?)', [0, $storeId])
            ->where('(status.value = 1 OR status.value IS NULL)')
            ->distinct()
            ->order('value.value ASC');

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

        $brandData = [];
        $orderedBrands = [];

        foreach ($results as $row) {
            $brandData[$row['option_id']] = [
                'id' => $row['option_id'],
                'value' => $row['value'],
                'label' => $row['value'],
                'slug' => $this->slugHandler->createSlug($row['value']),
                'image_url' => $this->getBrandImageUrl($this->slugHandler->createSlug($row['value']))
            ];
        }

        foreach ($orderedBrandIds as $brandId) {
            if (isset($brandData[$brandId])) {
                $orderedBrands[] = $brandData[$brandId];
                unset($brandData[$brandId]);
            }
        }

        return array_merge($orderedBrands, array_values($brandData));
    }

    public function getBrandLimit()
    {
        return $this->config->getBrandLimit();
    }

    private function getBrandImageUrl($slug)
    {
        $mediaUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
        $imagePath = 'wysiwyg/auto_brands/' . $slug . '.jpg';

        return $mediaUrl . $imagePath;
    }

    public function brandImageExists($slug)
    {
        $mediaPath = $this->storeManager->getStore()->getBaseMediaDir();
        $imagePath = $mediaPath . '/wysiwyg/auto_brands/' . $slug . '.jpg';

        return file_exists($imagePath);
    }

    public function buildBrandUrl($brandSlug)
    {
        $secureBaseUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_WEB, true);
        return $secureBaseUrl . 'catalog-branduri/' . $brandSlug . '.html';
    }
}
