<?php

namespace Autogedal\InternalLinks\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Autogedal\InternalLinks\Model\Config;
use Autogedal\InternalLinks\Model\SlugHandler;
use Magento\UrlRewrite\Model\UrlRewriteFactory;
use Magento\UrlRewrite\Model\ResourceModel\UrlRewriteCollectionFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\ResourceConnection;
use Psr\Log\LoggerInterface;

class CatalogProductAttributeSave implements ObserverInterface
{
    private $config;
    private $slugHandler;
    private $urlRewriteFactory;
    private $urlRewriteCollectionFactory;
    private $storeManager;
    private $resourceConnection;
    private $logger;
    private $originalOptions = [];

    public function __construct(
        Config $config,
        SlugHandler $slugHandler,
        UrlRewriteFactory $urlRewriteFactory,
        UrlRewriteCollectionFactory $urlRewriteCollectionFactory,
        StoreManagerInterface $storeManager,
        ResourceConnection $resourceConnection,
        LoggerInterface $logger
    ) {
        $this->config = $config;
        $this->slugHandler = $slugHandler;
        $this->urlRewriteFactory = $urlRewriteFactory;
        $this->urlRewriteCollectionFactory = $urlRewriteCollectionFactory;
        $this->storeManager = $storeManager;
        $this->resourceConnection = $resourceConnection;
        $this->logger = $logger;
    }

    public function execute(Observer $observer)
    {
        $this->logger->info('CatalogProductAttributeSave observer executed');

        if (!$this->config->isEnabled()) {
            $this->logger->info('Plugin disabled, returning');
            return;
        }

        /** @var \Magento\Eav\Model\Entity\Attribute $attribute */
        $attribute = $observer->getEvent()->getAttribute();

        if ($attribute->getEntityTypeId() != 4 || $attribute->getAttributeId() != $this->config->getBrandAttributeId()) {
            return;
        }

        try {
            $this->updateAllBrandUrlRewrites($attribute);
        } catch (\Exception $e) {
            $this->logger->error('Error in CatalogProductAttributeSave observer: ' . $e->getMessage());
        }
    }

    private function updateAllBrandUrlRewrites($attribute)
    {
        $attributeId = $attribute->getAttributeId();
        $newOptions = $attribute->getData('option');

        if (!$newOptions) {
            return;
        }

        $stores = $this->storeManager->getStores();

        foreach ($stores as $store) {
            $storeId = $store->getId();
            $options = $newOptions['value'] ?? [];

            foreach ($options as $id => $newVal) {
                $brandSlug = $this->slugHandler->createSlug($newVal[0]);
                $requestPath = 'catalog-branduri/' . $brandSlug . '.html';
                $targetPath = 'catalog-branduri/index/details/brand/' . $brandSlug . '/';

                $this->createOrUpdateUrlRewrite($requestPath, $targetPath, $storeId);
            }
        }

        $this->removeOrphanUrlRewrites($options);
    }

    private function createOrUpdateUrlRewrite($requestPath, $targetPath, $storeId)
    {
        $collection = $this->urlRewriteCollectionFactory->create()
            ->addFieldToFilter('request_path', $requestPath)
            ->addFieldToFilter('store_id', $storeId)
            ->addFieldToFilter('entity_type', 'custom');

        if ($collection->getSize() > 0) {
            $urlRewrite = $collection->getFirstItem();
        } else {
            $urlRewrite = $this->urlRewriteFactory->create();
        }

        $urlRewrite->setEntityType('custom')
            ->setEntityId(0)
            ->setRequestPath($requestPath)
            ->setTargetPath($targetPath)
            ->setRedirectType(0)
            ->setStoreId($storeId)
            ->setDescription(null)
            ->setIsAutogenerated(0)
            ->setMetadata(null);

        try {
            $urlRewrite->save();
            $this->logger->info('URL rewrite saved: ' . $requestPath . ' -> ' . $targetPath);
        } catch (\Exception $e) {
            $this->logger->error('Error saving URL rewrite: ' . $e->getMessage());
        }
    }

    private function removeOrphanUrlRewrites($options)
    {
        $validOptions = [];
            foreach ($options as $id => $newVal) {
                $brandSlug = $this->slugHandler->createSlug($newVal[0]);
                $validOptions[] = $brandSlug;
            }

        $collection = $this->urlRewriteCollectionFactory->create()
            ->addFieldToFilter('entity_type', 'custom')
            ->addFieldToFilter('request_path', ['like' => 'catalog-branduri%']);

        foreach ($collection as $urlRewrite) {
            $requestPath = $urlRewrite->getRequestPath();
            $requestPath = str_replace('catalog-branduri/', '', $requestPath);
            $requestPath = str_replace('.html', '', $requestPath);

            if (!in_array($requestPath, $validOptions)) {
                $urlRewrite->delete();
            }
        }
    }
}
