<?php
/**
 * Copyright © 2019 Wyomind. All rights reserved.
 * See LICENSE.txt for license details.
 */


namespace Wyomind\ElasticsearchLayeredNavigation\Model\ResourceModel;


use Magento\Framework\App\ResourceConnection;
use Wyomind\ElasticsearchLayeredNavigation\Helper\Config;

class Category
{
    /**
     * @var ResourceConnection
     */
    protected $resourceConnection;
    /**
     * @var Config
     */
    protected $configHelper;

    /**
     * Category constructor.
     * @param ResourceConnection $resourceConnection
     * @param Config $configHelper
     */
    public function __construct(
        ResourceConnection $resourceConnection,
        Config $configHelper
    )
    {
        $this->resourceConnection = $resourceConnection;
        $this->configHelper = $configHelper;
    }

    /**
     * @return array
     */
    public function searchCategoryId($requestPath, $storeId)
    {
        $connection = $this->resourceConnection->getConnection();
        $ur = $this->resourceConnection->getTableName('url_rewrite');
        $cce = $this->resourceConnection->getTableName('catalog_category_entity');
        $sql = 'SELECT ur.entity_id, ur.request_path FROM ' . $ur . ' ur'
            . ' LEFT JOIN ' . $cce . ' cce on ur.entity_id = cce.entity_id'
            . ' WHERE "' . $requestPath . '" REGEXP concat("^", REPLACE(ur.request_path, "'.$this->configHelper->getSEOCategoryUrlSuffix($storeId).'", ""), "/") and ur.store_id = ' . $storeId
            . ' AND ur.entity_type="category"'
            . ' ORDER BY cce.level desc'
            . ' LIMIT 1';
        $row = $connection->fetchRow($sql);
        return $row;
    }

}