<?php

namespace Benhauer\Salesmanago\Controller\Adminhtml\Config;

use Benhauer\Salesmanago\Helper\Config as ConfigHelper;
use Magento\Backend\App\Action;
use Magento\Framework\Message\ManagerInterface;

use SALESmanago\Factories\FactoryOrganizer;
use SALESmanago\Provider\UserProvider;

use Benhauer\Salesmanago\Model\User as UserModel;

class Index extends \Magento\Backend\App\Action
{
    public $storeManager;
    protected $storeId;
    protected $scope = 'default';

    public function __construct(
        Action\Context $context,
        UserModel $model,
        FactoryOrganizer $factoryOrganizer,
        ConfigHelper $config
    ) {
        parent::__construct($context);
        $this->model = $model;
        $this->factoryOrganizer = $factoryOrganizer;
    }

    public function execute()
    {
        $smGoToConfigutation = $this->getRequest()->getParam('smconfiguration');

        if ($this->getRequest()->getParam('smconfiguration') == "true") {
            return $this->_redirect('adminhtml/system_config/edit/section/salesmanago_account_settings');
        }

        if ($loadByStoreCheck = $this->loadByStoreCheck()) {
            return $loadByStoreCheck;
        }

        if ($this->model->isPluginConfActive()) {
            $this->_view->loadLayout();
            $this->_view->renderLayout();
        } else {
            return $this->_redirect('*/*/login');
        }
    }

    public function loadByStoreCheck()
    {
        $this->storeId = $this->getRequest()->getParam('store');

        if ($this->storeId == null) {
            $this->storeId = 0;
            $this->scope = 'default';
        }

        if ($this->storeId) {
            $this->model
                ->setScopeId($this->storeId);
        }

        if (($this->storeId || $this->storeId === 0)
            && !$this->model->isPluginConfActive()
        ) {
            return $this->redirectTo();
        }

        return false;
    }

    public function redirectTo($redirectTo = 'login')
    {
        $store = '';
        if (!empty($this->storeId)) {
            $store = '/store/'.$this->storeId;
        }
        return $this->_redirect('*/*/'.$redirectTo.$store);
    }
}
