<?php

namespace Benhauer\Salesmanago\Controller\Adminhtml\Config;

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;
use \Benhauer\Salesmanago\Model\Login as LoginModel;

class Login extends \Magento\Backend\App\Action
{
    protected $factoryOrganizer;
    protected $model;
    protected $context;
    protected $storeId = 0;
    protected $scope = 'default';
    protected $messageManager;

    public function __construct(
        Action\Context $context,
        FactoryOrganizer $factoryOrganizer,
        LoginModel $model
    ) {
        parent::__construct($context);
        $this->model = $model;
        $this->factoryOrganizer = $factoryOrganizer;
        $this->messageManager = $context->getMessageManager();
    }

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

        $clientLoginData = $this->getRequest()->getParam('client');

        if($clientLoginData['username']) {
            return $this->loginClient($clientLoginData);
        }

        $this->_view->loadLayout();
        $this->_view->renderLayout();
    }

    public function loginClient($clientLoginData)
    {
        $loginAccount = $this->factoryOrganizer->getInst(
            FactoryOrganizer::LOGIN_ACCOUNT_C,
            UserProvider::settingsUser(),
            $this->model
        );

        $response = $loginAccount->loginUser($clientLoginData);

        if (!$response['success']) {
            $this->messageManager->addError(__("{$response['message']}"));
            return $this->_redirect('*/*/login');
        } elseif($response['success']) {
            $this->model->setScopeCheckId($this->storeId);
            $this->messageManager->addSuccess(__("Success"));
            $this->redirectTo();
        } else {
            $this->messageManager->addError(__("Error 0"));
            return $this->_redirect('*/*/login');
        }
    }

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

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

        if ($this->storeId != null) {
            $this->model
                ->setScopeId($this->storeId)
                ->setScope($this->scope);
        }

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

        return false;
    }

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