<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */
declare(strict_types=1);

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Cannibalization;

use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Magento\UrlRewrite\Model\UrlRewriteFactory;
use WriteTextAI\WriteTextAI\Helper\Cannibalization;
use Magento\Store\Model\Store;
use Laminas\Uri\UriFactory;

class AnalyzeSlugs extends \Magento\Backend\App\Action
{
    /**
     * @var UrlRewriteFactory
     */
    protected $urlRewriteFactory;

    /**
     * @var Cannibalization
     */
    protected $cannibalization;

    /**
     * @var array
     */
    protected $productIds = [];

    /**
     * @var array
     */
    protected $categoryIds = [];

    /**
     * @var array
     */
    protected $cmsUrls = [];

    /**
     * @var array
     */
    protected $storeUrls = [];

    /**
     * @var int
     */
    protected $storeId = Store::DEFAULT_STORE_ID;

    /**
     * Constructor
     *
     * @param Context $context
     * @param UrlRewriteFactory $urlRewriteFactory
     * @param Cannibalization $cannibalization
     */
    public function __construct(
        Context $context,
        UrlRewriteFactory $urlRewriteFactory,
        Cannibalization $cannibalization
    ) {
        parent::__construct($context);
        $this->urlRewriteFactory = $urlRewriteFactory;
        $this->cannibalization = $cannibalization;
    }

    /**
     * Execute action
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultFactory->create(ResultFactory::TYPE_JSON);

        $slugs = $this->getRequest()->getParam('slugs', '');
        $slugArray = array_map('trim', explode(',', $slugs));

        if ($slugs) {
            foreach ($slugArray as $slug) {
                $product = $this->getEntityByUrl($slug);
            }
        }
        
        return $result->setData([
            'hasProducts' => !empty($this->productIds),
            'hasCategories' => !empty($this->categoryIds),
            'cmsUrls' => $this->cmsUrls,
            'productIds' => $this->productIds,
            'categoryIds' => $this->categoryIds,
            'storeId' => $this->storeId,
            'storeUrls' => $this->storeUrls
        ]);
    }

    /**
     * Get the entity by the url path
     *
     * @param string $urlPath
     * @return \Magento\Catalog\Model\Product|null
     */
    public function getEntityByUrl($urlPath)
    {
        $storeId = $this->cannibalization->getStoreIdFromUrl($urlPath);
        
        // Remove base URL if present
        try {
            $uri = UriFactory::factory($urlPath);
            $pathFromUrl = $uri->getPath();
        } catch (\Exception $e) {
            $pathFromUrl = $urlPath;
        }
        $cleanPath = ltrim($pathFromUrl, '/');

        // Remove store path if present
        $storePath = $this->cannibalization->getStorePathFromStoreId($storeId);
        if ($storePath && strpos($cleanPath, $storePath) === 0) {
            $cleanPath = substr($cleanPath, strlen($storePath));
            $cleanPath = ltrim($cleanPath, '/');
        }

        // Get the store url
        $storeUrl = $this->cannibalization->getStoreUrl($storeId);
        $this->storeUrls[$storeId] = $storeUrl;

        try {
            // Load URL rewrite
            $urlRewrite = $this->urlRewriteFactory->create()
                ->getCollection()
                ->addFieldToFilter('request_path', $cleanPath)
                ->addFieldToFilter('store_id', $storeId)
                ->getFirstItem();

            if ($urlRewrite->getEntityType() === 'product') {
                $this->productIds[$storeId][] = $urlRewrite->getEntityId();
                if ($this->storeId === Store::DEFAULT_STORE_ID) {
                    $this->storeId = $storeId;
                }
            } elseif ($urlRewrite->getEntityType() === 'category') {
                $this->categoryIds[$storeId][] = $urlRewrite->getEntityId();
                if ($this->storeId === Store::DEFAULT_STORE_ID) {
                    $this->storeId = $storeId;
                }
            } else {
                $this->cmsUrls[] = $urlPath;
            }
        } catch (\Exception $e) {
            $this->cmsUrls[] = $urlPath;
        }
    }
}
