<?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\Create as CreateModel;
use Benhauer\Salesmanago\Helper\Config as ConfigHelper;

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

    public function __construct(
        Action\Context $context,
        CreateModel $model,
        FactoryOrganizer $factoryOrganizer,
        ConfigHelper $config,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        parent::__construct($context);
        $this->model = $model;
        $this->factoryOrganizer = $factoryOrganizer;
        $this->config = $config;
        $this->messageManager = $context->getMessageManager();
        $this->storeManager = $storeManager;
    }

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

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

        if ($clientCreateData['username']) {
            $this->createClient($clientCreateData);
        }

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

    public function createClient($clientCreateData)
    {
        $bhrSso = $this->config->getBhrSso();

        $connectSm = $this->factoryOrganizer->getInst(
            FactoryOrganizer::CREATE_ACCOUNT_C,
            UserProvider::settingsAccount(),
            $this->model
        );

        $consentDetails = $this->consentDetailsCheck($clientCreateData);

        if ($consentDetails) {
            $response = $connectSm->createAccount(
                [
                    'email' => htmlspecialchars($clientCreateData['username']),
                    'password' => htmlspecialchars($clientCreateData['password']),
                    'lang' => htmlspecialchars($bhrSso['lang']),
                    'name' => htmlspecialchars($clientCreateData['name']),
                    'phone' => htmlspecialchars($clientCreateData['phone']),
                    'website' => $this->storeManager->getStore($this->storeId)->getBaseUrl(),
                    'consentDetails' => $consentDetails,
                    'platform' => $bhrSso['platform'],
                ],
                ['0', '1', '2', '3']
            );

            if (!$response['success']) {
                $this->messageManager->addError(__("{$response['message']}"));
                return $this->_redirect('*/*/create');
            } elseif ($response['success']) {
                $this->model->setScopeCheckId($this->storeId);
                $this->messageManager->addSuccess(__("Success"));
                return $this->_redirect('*/*/index');
            } else {
                $this->messageManager->addError(__("Error 0"));
                return $this->_redirect('*/*/create');
            }
        } else {
            $this
                ->messageManager
                ->addErrorMessage(__("To create SALESmanago account you must accept our terms and conditions and marketing consent"));
        }
    }

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

        if ($this->storeId == null) {
            $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 consentDetailsCheck($clientCreateData)
    {
        $consentDetails = [];

        if (isset($clientCreateData['zgoda_eng_przetwarzanie'])
            && $clientCreateData['zgoda_eng_przetwarzanie'] != 0) {
            $consentDetails[] = [
                'consentName' => 'ZGODA_ENG_PRZETWARZANIE',
                'consentAccept' => true,
            ];
        }

        if (isset($clientCreateData['zgoda_eng_handlowa'])
            && $clientCreateData['zgoda_eng_handlowa'] != 0) {
            $consentDetails[] = [
                'consentName' => 'ZGODA_ENG_HANDLOWA',
                'consentAccept' => true,
            ];
        }

        if (!empty($consentDetails) && count($consentDetails)) {
            $consentDetails[] = [
                'consentName' => 'ZGODA_ENG_OSOBOWE_REGULAMIN',
                'consentAccept' => true,
            ];
            return $consentDetails;
        }

        return false;
    }

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