<?php
/**
 * @category Mageants SimpleConfigurable
 * @package Mageants_SimpleConfigurable
 * @copyright Copyright (c) 2017 Mageants
 * @author Mageants Team <info@mageants.com>
 */

namespace Mageants\SimpleConfigurable\Controller;

class Router implements \Magento\Framework\App\RouterInterface
{   
    public $categoryRepository;
    public $categoryFactory;
    public $productCategory;
    /**
     * @var \Magento\Framework\App\ActionFactory
     */
    private $actionFactory;

    /**
     * @var \Magento\Framework\Event\ManagerInterface
     */
    private $eventManager;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var \Magento\Framework\App\ResponseInterface
     */
    private $response;

    /**
     * @var \Magento\Catalog\Model\ResourceModel\Product\Collection
     */
    private $productCollection;

    /**
     * @param \Magento\Framework\App\ActionFactory $actionFactory
     * @param \Magento\Framework\Event\ManagerInterface $eventManager
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Catalog\Model\ProductCategoryList $productCategory
     * @param \Magento\Catalog\Model\CategoryFactory $categoryFactory
     * @param \Magento\Catalog\Model\CategoryRepository $categoryRepository
     * @param \Magento\Framework\App\ResponseInterface $response
     * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection
     */
    public function __construct(
        \Magento\Framework\App\ActionFactory $actionFactory,
        \Magento\Framework\Event\ManagerInterface $eventManager,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\ProductCategoryList $productCategory,
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        \Magento\Catalog\Model\CategoryRepository $categoryRepository,
        \Magento\Framework\App\ResponseInterface $response,
        \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection
    ) {
        $this->actionFactory = $actionFactory;
        $this->eventManager = $eventManager;
        $this->storeManager = $storeManager;
        $this->productCategory = $productCategory;
        $this->categoryFactory = $categoryFactory;
        $this->categoryRepository = $categoryRepository;
        $this->response = $response;
        $this->productCollection = $productCollection;
    }

    /**
     * Validate and Match Shopbylook Pages and modify request
     *
     * @param \Magento\Framework\App\RequestInterface $request
     * @return bool
     */
    public function match(\Magento\Framework\App\RequestInterface $request)
    {
        $curl = $request->getUri();
        $curl = explode('/', $curl);
        $curl = end($curl);

        $categoryUrl = [];

        $main = $this->storeManager->getStore()->getBaseUrl() . $curl;
        $categoryUrl[] = $main;

        if (strpos($curl, '.html') !== false) {
            $curl = str_replace('.html', '', $curl);
        }

        $curl = $this->getProductCleanUrl($request);
        if ($curl == "") {
            return false;
        }
        /** Apply filters here */
        $collection = $this->productCollection->addAttributeToSelect('*')
            ->addAttributeToFilter('url_key', $curl)
            ->addAttributeToFilter('status', 1)
            ->load();

        $storeId = $this->storeManager->getStore()->getId();

        foreach ($collection as $product) {

            $catId = $this->productCategory->getCategoryIds($product->getId());
            $catId = end($catId);
            $category = $this->categoryFactory->create()->load($catId);
            $parentCategories = $category->getParentCategories();

            foreach ($parentCategories as $value) {
                $temp_cat = $this->categoryFactory->create()->load($value->getId())->getParentCategories();
                if (count($temp_cat) != 1) {
                    $category = $this->categoryRepository->get($value->getId(), $storeId);
                    $tempUrl = $category->getUrl();
                    if (strpos($tempUrl, '.html') !== false) {
                        $tempUrl = str_replace('.html', '/', $tempUrl);
                    }
                    $categoryUrl[] = $tempUrl . $curl . '.html';
                }
            }

            if (in_array($request->getUri(), $categoryUrl)) {
                if ($product->getId()) {
                    $request->setModuleName('catalog')
                        ->setControllerName('product')
                        ->setActionName('view')
                        ->setParam('id', $product->getId());
                    return false;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
    }

    /**
     * get Product Id By Url
     *
     * @return void
     */
    public function getProductCleanUrl($request)
    {
        $fullUrl = $request->getUri();
        $baseUrl = $this->storeManager->getStore()->getBaseUrl();
        $cleanUrl_ = str_replace($baseUrl, '', $fullUrl);
        $cleanUrl = ltrim(explode('?', $cleanUrl_, 2)[0], '/');

        $queryString = '';
        if (strpos($fullUrl, '?') !== false) {
            $queryString = explode('?', $fullUrl, 2)[1];
        }

        $curl = $cleanUrl;

        $categoryUrl = [];

        $main = $this->storeManager->getStore()->getBaseUrl() . $curl;
        $main = $queryString ? $main."?".$queryString : $main;
        $categoryUrl[] = $main;

        if (strpos($curl, '.html') !== false) {
            $curl = str_replace('.html', '', $curl);
        }

        return $curl;
    }
}
