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

namespace WriteTextAI\WriteTextAI\Helper;

use Magento\Store\Model\StoreManagerInterface;
use Magento\Store\Model\Store;
use Laminas\Uri\UriFactory;

class Cannibalization extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     * Constructor
     *
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        StoreManagerInterface $storeManager
    ) {
        $this->storeManager = $storeManager;
    }

    /**
     * Get the store id from the url
     *
     * @param string $fullUrl
     * @return int|null
     */
    public function getStoreIdFromUrl($fullUrl)
    {
        try {
            $inputUri = UriFactory::factory($fullUrl);
            $inputHost = $inputUri->getHost();
            $inputPath = $inputUri->getPath();

            $storeId = Store::DEFAULT_STORE_ID;
            foreach ($this->storeManager->getStores() as $store) {
                $storeBaseUrl = $store->getBaseUrl();
                $storeUri = UriFactory::factory($storeBaseUrl);
                $storeHost = $storeUri->getHost();
                $storePath = rtrim($storeUri->getPath(), '/');
                
                if ($inputHost === $storeHost) {
                    if ($storePath) {
                        if (strpos($inputPath, $storePath) === 0) {
                            $storeId = $store->getId();
                        }
                    }
                    
                    if ($storeId === Store::DEFAULT_STORE_ID) {
                        $storeId = $store->getId();
                    }
                }
            }

            return $storeId;
        } catch (\Exception $e) {
            return Store::DEFAULT_STORE_ID;
        }
    }

    /**
     * Get the store path from store ID
     *
     * @param int $storeId
     * @return string|null
     */
    public function getStorePathFromStoreId($storeId)
    {
        try {
            $store = $this->storeManager->getStore($storeId);
            $storeBaseUrl = $store->getBaseUrl();
            $storeUri = UriFactory::factory($storeBaseUrl);
            $storePath = $storeUri->getPath();
            return trim($storePath, '/');
        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * Get the store url
     *
     * @param int $storeId
     * @return string|null
     */
    public function getStoreUrl($storeId)
    {
        try {
            $store = $this->storeManager->getStore($storeId);
            $storeBaseUrl = $store->getBaseUrl();
            return $storeBaseUrl;
        } catch (\Exception $e) {
            return null;
        }
    }
}
