<?php

namespace FiloBlu\Refilo\Observer;

use FiloBlu\Refilo\Helper\Data;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Store\Model\StoreManagerInterface;

class AfterBuildCanonicalUrlResultsFetch implements ObserverInterface
{
    /**
     * @var Data
     */
    protected $helper;
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;
    /**
     * @var array
     */
    protected $storeCodes = [];

    /**
     * @param Data $helper
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        Data $helper,
        StoreManagerInterface $storeManager
    )
    {
        $this->helper = $helper;
        $this->storeManager = $storeManager;
        $this->getStoreCodes();
    }

    public function execute(Observer $observer)
    {
        if (!$this->helper->isCanonicalUrlObserverEnabled()) {
            return;
        }

        $canonicalUrlModifier = $observer->getEvent()->getCanonicalUrlModifier();

        $storeCode = $canonicalUrlModifier->getStoreCode();
        $path = $canonicalUrlModifier->getPath();
        $url = $canonicalUrlModifier->getUrl();


        $canonicalUrlModifier->setPath($this->cleanUrl($path, $storeCode, $url));
        $canonicalUrlModifier->setUrl($this->cleanUrl($url, $storeCode));

    }

    protected function cleanUrl($url, $storeCode, $fallBack = null)
    {
        if (empty($url)) {
            return $url;
        }

        if (strpos(trim($url, "/"), "{$storeCode}/") !== false) {
             $url = str_replace("{$storeCode}/", '', trim($url, '/'));
        }

        return $url;
    }

    public function getStoreCodes() {

        foreach ($this->storeManager->getStores() as $store) {
            $this->storeCodes[] = $store->getCode();
        }


    }
}
