<?php

declare(strict_types=1);

namespace FiloBlu\ExtBlackbirdMenuManager\Model;

use Blackbird\MenuManager\Model\MenuFactory;
use Blackbird\MenuManager\Model\ResourceModel\Menu;
use Blackbird\MenuManager\Model\ResourceModel\Menu\CollectionFactory;
use Magento\Customer\Model\Context;
use Magento\Customer\Model\Session;
use Magento\Framework\Api\SearchResultsInterfaceFactory;
use Magento\Framework\App\Http\Context as HttpContext;

/**
 * Class MenuRepository
 * @package FiloBlu\ExtBlackbirdMenuManager\Model
 */
class MenuRepository extends \Blackbird\MenuManager\Model\MenuRepository
{
    protected $httpContext;
    protected $customerSession;

    /**
     * @param MenuFactory $objectFactory
     * @param CollectionFactory $collectionFactory
     * @param SearchResultsInterfaceFactory $searchResultsFactory
     * @param Menu $menuResourceModel
     * @param \Blackbird\MenuManager\Model\MenuFactory $menuFactory
     * @param HttpContext $httpContext
     * @param Session $customerSession
     */
    public function __construct(
        MenuFactory $objectFactory,
        CollectionFactory $collectionFactory,
        SearchResultsInterfaceFactory $searchResultsFactory,
        Menu $menuResourceModel,
        MenuFactory $menuFactory,
        HttpContext $httpContext,
        Session $customerSession
    ) {
        parent::__construct(
            $objectFactory,
            $collectionFactory,
            $searchResultsFactory,
            $menuFactory,
            $menuResourceModel
        );
        $this->httpContext = $httpContext;
        $this->customerSession = $customerSession;
    }

    /**
     * @param $identifier
     * @param $storeId
     * @return mixed
     */
    public function get($identifier, $storeId)
    {
        $_currentCustomerGroupId = '-1';
        if ($this->httpContext->getValue(Context::CONTEXT_AUTH)) {
            $_currentCustomerGroupId = '-2,';
            $_currentCustomerGroupId = $_currentCustomerGroupId . $this->customerSession->getCustomer()->getGroupId();
        }

        $collection = $this->collectionFactory->create();
        $collection->addFilter('identifier', $identifier);
        $collection->addFilter('is_active', 1);
        $collection->addFieldToFilter(['customer_group', 'customer_group'], [
            ['in' => $_currentCustomerGroupId],
            ['null' => true]
        ]);
        $collection->join(
            ['stores' => 'blackbird_menumanager_store'],
            'main_table.menu_id = stores.menu_id',
            'store_id'
        );
        $collection->addFieldToFilter(
            ['store_id', 'store_id'],
            [['eq' => $storeId], ['eq' => self::ID_ALL_STORE_VIEW]]
        );
        $collection->setOrder('store_id', 'DESC');

        return $collection->getFirstItem();
    }
}
