<?php

namespace FiloBlu\Flow\Helper;

use FiloBlu\Core\Model\Eav\Config;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Exception\LocalizedException;

class SwatchColor extends AbstractHelper
{
    /**
     * @var ResourceConnection
     */
    private $resourceConnection;
    /**
     * @var Config
     */
    private $eavConfig;

    /**
     * @param Context $context
     * @param ResourceConnection $resourceConnection
     */
    public function __construct(
        Context $context,
        ResourceConnection $resourceConnection,
        Config $eavConfig
    )
    {
        parent::__construct($context);
        $this->resourceConnection = $resourceConnection;
        $this->eavConfig = $eavConfig;
    }

    public function getOptionIdsByValue($value, $attributeCode): array
    {
        /** @var ResourceConnection $resource */
        $connection = $this->resourceConnection->getConnection();

        $attributeId = $this->getSwatchColorAttributeIdByCode($attributeCode);

        $optionTable = $connection->getTableName('eav_attribute_option');
        $optionValueTable = $connection->getTableName('eav_attribute_option_value');

        $select = $connection->select()
            ->from(['eaov' => $optionValueTable], ['option_id'])
            ->joinInner(
                ['eao' => $optionTable],
                'eaov.option_id = eao.option_id'
                . ' AND eao.attribute_id = ' . (int)$attributeId,
                []
            )
            ->where('eaov.value = ?', $value)
            ->where('eaov.store_id = ?', 0);

        return $connection->fetchCol($select);
    }

    /**
     * Inserisce record in eav_attribute_option_swatch
     *
     * @param array|int $optionId  uno o più option_id
     * @param string $value         valore swatch (es. #FF0000 o filename)
     * @param int $type             tipo (1=color, 2=image, 0=text)
     * @param int $storeId          id store (default 0)
     * @throws LocalizedException
     */
    public function insertOptionValue($optionId, string $value, int $type = 1, int $storeId = 0)
    {
        $connection = $this->resourceConnection->getConnection();
        $table = $this->resourceConnection->getTableName('eav_attribute_option_swatch');

        if (empty($optionId)) {
            throw new LocalizedException(__('No option IDs provided'));
        }

        $data[] = [
            'option_id' => (int)$optionId,
            'store_id'  => $storeId,
            'type'      => $type,
            'value'     => $this->checkValue($value),
        ];

        try {
            // Inserimento multiplo (insertOnDuplicate gestisce già esistenze)
            $connection->insertOnDuplicate($table, $data, ['option_id', 'store_id','value', 'type']);

        } catch (\Exception $exception) {
            throw new LocalizedException(__($exception->getMessage()));
        }
    }

    public function getSwatchColorAttributeIdByCode($attributeCode)
    {
        /** @var \Magento\Eav\Model\Config $eavConfig */
        $attribute = $this->eavConfig->getAttribute(
            \Magento\Catalog\Model\Product::ENTITY, // entità (prodotto in questo caso)
            $attributeCode                               // attribute_code
        );

        return (int)$attribute->getAttributeId();
    }

    public function checkValue($value)
    {
        if (strpos($value, '#') === false) {
            return '#' . $value;
        }

        return $value;
    }
}
