<?php

namespace ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailAccount\Sections;

use ModulesGarden\Servers\OpenXchange\App\Traits\FormExtendedTrait;
use ModulesGarden\Servers\OpenXchange\App\Libs\Product\ProductManager;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\Forms\Fields\Text;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\Forms\Fields\Select;
use ModulesGarden\Servers\OpenXchange\App\Validators\PasswordsValidator;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\Forms\Fields\Password;
use ModulesGarden\Servers\OpenXchange\App\Validators\RepeatPasswordValidator;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\Forms\Fields\Switcher;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\Forms\Sections\InputGroup;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\Others\Fields\OptGroupSelect;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\Others\Fields\ExtendedInputField;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\Forms\Fields\InputGroupElements;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\Others\Sections\FreeFieldsSection;
use function \ModulesGarden\Servers\OpenXchange\Core\Helper\di;
use ModulesGarden\Servers\OpenXchange\App\Helpers\Helper;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\Forms\Fields\Hidden;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\Customs\Fields\PasswordGenerateExtended;
use ModulesGarden\Servers\OpenXchange\App\Models\ProductConfiguration;
use ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailAccount\Constants;
use ModulesGarden\Servers\OpenXchange\App\Models\MailboxDeleteList;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 12.11.19
 * Time: 13:52
 * Class EditGeneralSection
 */
class EditGeneralSection extends FreeFieldsSection
{
    protected $id   = 'editGeneralSection';
    protected $name = 'editGeneralSection';

    use FormExtendedTrait;

    public function initContent()
    {
        $showStatusField = true;

        $hiddenField = new Hidden('autofillGen');
        $this->addField($hiddenField);

        $emialTypeField = (new Select('emailType'))->notEmpty();
        $this->addField($emialTypeField);

        $hostingId       = $this->request->getValue('id');
        $params          = Helper::moduleParams($hostingId);
        $availableAddons = $this->getAvailableAddons($params);

        if (!empty($availableAddons))
        {
            $emialAddonField = (new Select('emailAddonType'))->enableMultiple();
            $this->addField($emialAddonField);
        }

        $this->generateDoubleSection([(new Text('firstname'))->notEmpty(), (new Text('lastname'))->notEmpty()]);
        $this->generateDoubleSection([/*(new Text('display_name'))->notEmpty(),*/(new ExtendedInputField('quota'))->setFieldType(ExtendedInputField::TYPE_NUMBER)]);
        $this->generateDoubleSection([(new OptGroupSelect('timezone'))->notEmpty(), (new Select('language'))->notEmpty()]);

        $email = new InputGroup('usernameGroup');

        $email->addTextField('primaryEmail', false, true);
        $email->addInputAddon('emailSign', false, '@');
        $email->addInputComponent((new InputGroupElements\Text('domain'))->addHtmlAttribute('readonly', 'true'));

        $mailboxId = strip_tags(html_entity_decode($this->request->getValue('actionElementId')));

        if (!empty($mailboxId) && $mailboxId != '')
        {
            $deleteRequestExists = MailboxDeleteList::where('mailbox_name', '=', $mailboxId)->exists();
            
            if ($deleteRequestExists)
            {
                $showStatusField = false;
            }
        }

        if ($showStatusField)
        {
            $field = new Switcher('mailenabled');
            $this->addField($field);
        }

        $this->addSection($email);

        //$passwd = new Password('resetPassword');
        $passwd = new PasswordGenerateExtended('resetPassword');
        $lang = di('lang');
        $description = $lang->T('resetPassDescription');
        $passwd->setDescription($description);
        $passwd->addValidator(new PasswordsValidator());

        $repPasswd = (new Text('repeatPasswordToReset'))->addValidator(new RepeatPasswordValidator());

        $this->generateDoubleSection([$passwd, $repPasswd]);
    }

    private function getAvailableAddons($params)
    {
        $configOptions     = $params['configoptions'];
        $allowedAddonsData = [];
        
        if ($configOptions && !empty($configOptions))
        {
            if (isset($configOptions['acc_limit_guard']) && $configOptions['acc_limit_guard'] > 0)
            {
                $allowedAddonsData['guard'] = array_search('guard', Constants::getTranslatedAddons());
            }
            
            if (isset($configOptions['acc_limit_ai']) && $configOptions['acc_limit_ai'] > 0)
            {
                $allowedAddonsData['ai'] = array_search('ai', Constants::getTranslatedAddons());
            }
        }

        if (empty($allowedAddonsData))
        {
            $config = ProductConfiguration::config($params['packageid']);

            if ($config['email_accounts_guard'] && $config['email_accounts_guard'] != 0)
            {
                $allowedAddonsData['guard'] = array_search('guard', Constants::getTranslatedAddons());
            }

            if ($config['email_accounts_ai'] && $config['email_accounts_ai'] != 0)
            {
                $allowedAddonsData['ai'] = array_search('ai', Constants::getTranslatedAddons());
            }
        }

        return $allowedAddonsData;
    }
}
