<?php
declare(strict_types=1);

namespace FiloBlu\Refilo\Observer;

use FiloBlu\Refilo\Helper\Catalog\ProductAttributeHelper;
use Magento\Bundle\Model\Product\Type;
use Magento\Catalog\Api\CategoryLinkManagementInterface;
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\ProductRepository;
use Magento\Catalog\Model\ResourceModel\Product\Action;
use Magento\Eav\Model\Config as EavConfig;
use Magento\Framework\App\{ResourceConnectionFactory, ResourceConnection};
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\LocalizedException;
use Zend_Db;

/**
 * Class AfterCatalogProductSaveEntityObserver
 * @package FiloBlu\Refilo\Observer
 */
class AfterCatalogProductSaveEntityObserver implements ObserverInterface
{
    /**
     * @var Action
     */
    protected $productAction;
    /**
     * @var ResourceConnectionFactory
     */
    private $resourceConnectionFactory;
    /**
     * @var EavConfig
     */
    private $eavConfig;
    /**
     * @var ProductAttributeHelper
     */
    private $productAttributeHelper;


    /**
     * @param ResourceConnectionFactory $resourceConnectionFactory
     * @param EavConfig $eavConfig
     * @param ProductAttributeHelper $productAttributeHelper
     * @param ProductRepository $productRepository
     * @param Action $productAction
     */
    public function __construct(
        ResourceConnectionFactory $resourceConnectionFactory,
        EavConfig $eavConfig,
        ProductAttributeHelper $productAttributeHelper,
        Action $productAction
    ) {
        $this->resourceConnectionFactory = $resourceConnectionFactory;
        $this->eavConfig = $eavConfig;
        $this->productAttributeHelper = $productAttributeHelper;
        $this->productAction = $productAction;
    }

    /**
     * @param Observer $observer
     * @return void
     * @throws LocalizedException
     */
    public function execute(Observer $observer)
    {
        /** @var ProductInterface $product */
        if (!$product = $observer->getData('product')) {
            return;
        }

        $prodTypeId = $this->eavConfig
            ->getEntityType(ProductAttributeInterface::ENTITY_TYPE_CODE)
            ->getEntityTypeId();

        /** @var ResourceConnection $resourceConnection */
        $resourceConnection = $this->resourceConnectionFactory->create();
        $eavAttributeTable = $resourceConnection->getTableName('eav_attribute');
        $catalogEavAttribute = $resourceConnection->getTableName('catalog_eav_attribute');

        $sql = "SELECT
                    ea.attribute_code
                FROM
                    {$eavAttributeTable} ea
                LEFT JOIN {$catalogEavAttribute} cea ON
                    ea.attribute_id = cea.attribute_id
                WHERE ea.entity_type_id = {$prodTypeId} AND cea.is_pagebuilder_enabled = 1";

        $pageBuilderAttributes = $resourceConnection
            ->getConnection()
            ->fetchAll($sql, [], Zend_Db::FETCH_ASSOC);

        if (count($pageBuilderAttributes) === 0) {
            return;
        }

        $attributesToUpdate = [];

        foreach ($pageBuilderAttributes as $attribute) {
            $attributeCode = $attribute['attribute_code'];
            if ($product->getData($attributeCode) !== null && !is_bool($product[$attributeCode])) {
                $attributesToUpdate[$attributeCode] = $this->productAttributeHelper->checkHtmlAttribute($product[$attributeCode]);
            }
        }

        if (!empty($attributesToUpdate)) {
            $this->productAction->updateAttributes([$product->getId()], $attributesToUpdate, $product->getStoreId());
        }
    }
}
