<?php

namespace Autogedal\Extend\Model;

use Magento\UrlRewrite\Model\UrlRewriteFactory;
use Magento\UrlRewrite\Model\ResourceModel\UrlRewriteCollectionFactory;
use Magento\UrlRewrite\Model\ResourceModel\UrlRewrite as UrlRewriteResource;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;
use Magento\Catalog\Model\CategoryRepository;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Amasty\ShopbySeo\Helper\Url;
use Magento\Store\Model\App\Emulation;

class RedirectManager
{
    const REDIRECT_TYPE = 'custom_product_disabled';
    const XML_CATEG_ATTR_CODE = 'leadlion/disabled_prod_attr_code/disabled_prod_attr_code';

    protected $scopeConfig;
    protected $urlRewriteFactory;
    protected $urlRewriteCollectionFactory;
    protected $urlRewriteResource;
    protected $categoryCollectionFactory;
    protected $categoryRepository;
    protected $storeManager;
    protected $logger;
    protected $helperUrl;
    protected $emulation;

    public function __construct(
        UrlRewriteFactory $urlRewriteFactory,
        UrlRewriteCollectionFactory $urlRewriteCollectionFactory,
        UrlRewriteResource $urlRewriteResource,
        CategoryCollectionFactory $categoryCollectionFactory,
        CategoryRepository $categoryRepository,
        StoreManagerInterface $storeManager,
        LoggerInterface $logger,
        ScopeConfigInterface $scopeConfig,
        Url $helperUrl,
        Emulation $emulation
    ) {
        $this->urlRewriteFactory = $urlRewriteFactory;
        $this->urlRewriteCollectionFactory = $urlRewriteCollectionFactory;
        $this->urlRewriteResource = $urlRewriteResource;
        $this->categoryCollectionFactory = $categoryCollectionFactory;
        $this->categoryRepository = $categoryRepository;
        $this->storeManager = $storeManager;
        $this->logger = $logger;
        $this->scopeConfig = $scopeConfig;
        $this->helperUrl = $helperUrl;
        $this->emulation = $emulation;
    }

    /**
     * Create redirect for disabled product to its category
     */
    public function createRedirectForDisabledProduct($product)
    {
        try {
            $this->emulation->startEnvironmentEmulation(1, \Magento\Framework\App\Area::AREA_FRONTEND, true);
            $categoryIds = $product->getCategoryIds();
            
            if (empty($categoryIds)) {
                $this->logger->warning("Product {$product->getId()} has no categories, cannot create redirect");
                return false;
            }

            $targetCategoryId = end($categoryIds);
            if (in_array($targetCategoryId, [$this->getRootCategoryId(), 2])) {
                $targetCategoryId = prev($categoryIds);
            }

            $category = $this->categoryRepository->get($targetCategoryId);
            if ($category->getLevel() > 2) {
                $category = $category->getParentCategory();
            }
           
            $productUrlKey = $this->getProductUrlKey($product);
            if (!$productUrlKey) {
                $this->logger->warning("Product {$product->getId()} has no URL key, cannot create redirect");
                return false;
            }

            $categoryUrlKey = $this->getCategoryUrlPath($category);
            if (!$categoryUrlKey) {
                $this->logger->warning("Category {$targetCategoryId} has no URL key, cannot create redirect");
                return false;
            }
            $disableProdMarcaCode = $this->getDisabledProdCatAttrMarca();
            $marcaAttrCode = isset($disableProdMarcaCode[$targetCategoryId]) ? $disableProdMarcaCode[$targetCategoryId] : null;
            
            if ($marcaAttrCode && $product->getData($marcaAttrCode)) {
                $categoryUrlKey = $categoryUrlKey.'/?'.$marcaAttrCode.'='.$product->getData($marcaAttrCode);
            }

            $categorySeoUrl = $this->helperUrl->seofyUrl(
                $categoryUrlKey
            );
            foreach ($product->getStoreIds() as $storeId) {
                $this->createUrlRewrite(
                    $productUrlKey,
                    $categorySeoUrl.'.html',
                    $storeId,
                    $product->getId(),
                    $targetCategoryId
                );
            }
            $this->emulation->stopEnvironmentEmulation();
            $this->logger->info("Created redirect for product {$product->getId()} to category {$targetCategoryId}");
            return true;
            
        } catch (\Exception $e) {
            $this->logger->error("Error creating redirect for product {$product->getId()}: " . $e->getMessage());
            return false;
        }
    }

    protected function getRootCategoryId()
    {
        return $this->storeManager->getStore()->getRootCategoryId();
    }

    private function getDisabledProdCatAttrMarca()
    {
        $confSettings = $this->scopeConfig->getValue(
            self::XML_CATEG_ATTR_CODE,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        $info = [];
        if ($confSettings) {
            $serializer = \Magento\Framework\App\ObjectManager::getInstance()->get(\Magento\Framework\Serialize\SerializerInterface::class);

            $configSett = $serializer->unserialize($confSettings);

            $info = [];
            foreach ($configSett as $config) {
                $info[$config['category_id']] = $config['marca_attribute_code'];
            }
        }
        
        return $info;
    }

    /**
     * Create URL rewrite entry
     */
    private function createUrlRewrite($requestPath, $targetPath, $storeId, $productId, $categoryId)
    {
        $existing = $this->urlRewriteCollectionFactory->create();
        $existing->addFieldToFilter('request_path', $requestPath)
                ->addFieldToFilter('store_id', $storeId);

        foreach ($existing as $item) {
            $this->urlRewriteResource->delete($item);
        }

        $urlRewrite = $this->urlRewriteFactory->create();
        $urlRewrite->setData([
            'request_path' => $requestPath,
            'target_path' => $targetPath,
            'redirect_type' => 301,
            'store_id' => $storeId,
            'description' => self::REDIRECT_TYPE . '_' . $productId,
            'is_autogenerated' => 1,
            'entity_type' => 'custom',
            'entity_id' => 0
        ]);
        
        $this->urlRewriteResource->save($urlRewrite);
        
        $this->logger->info("Created URL rewrite: {$requestPath} -> {$targetPath} for store {$storeId}");
    }

    /**
     * Get product URL key
     */
    private function getProductUrlKey($product)
    {
        $urlKey = $product->getUrlKey();
        if ($urlKey) {
            return $urlKey . '.html';
        }
        return null;
    }

    /**
     * Get category URL path
     */
    private function getCategoryUrlPath($category)
    {
        $urlKey = $category->getUrl();
        $path = ltrim(parse_url($urlKey, PHP_URL_PATH), '/'); 
        $path = str_replace('.html', '', $path);

        return $path;
    }
}
