<?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;

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)
    {
        $inputHost = parse_url($fullUrl, PHP_URL_HOST);
        $inputPath = parse_url($fullUrl, PHP_URL_PATH);

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

        return $storeId;
    }

    /**
     * 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();
            $storePath = parse_url($storeBaseUrl, PHP_URL_PATH);
            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;
        }
    }
}
