<?php
/**
 * Class CreateAccountCosQuota
 * User: ThurData
 * Date: 2019-10-07
 * Time: 14:05
 * @package ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Services\Create
 */

namespace ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Services\Create;


use ThurData\Servers\KerioEmail\App\Enums\ProductParams;
use ThurData\Servers\KerioEmail\App\Enums\Size;
use ThurData\Servers\KerioEmail\App\Enums\Kerio;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Models\Account;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Models\ClassOfService;

class CreateAccountCosQuota extends CreateAccount
{
    /**
     * array with class of service models
     * @var array
     */
    protected $cosModels = [];

    /**
     * configure service before will run
     */
    protected function config()
    {
        /**
         *
         * load class of service models
         */
        $this->cosModels = $this->api->repository()->cos->all();

        /**
         * parent configuration
         */
        parent::config();
    }

    /**
     *
     * @return bool
     */
    public function isValid()
    {
        /**
         *
         * if parent service is not valid, return false
         */
        if (!$result = parent::isValid())
        {
            return $result;
        }
        /**
         * check limits for dedicated class of service
         */
        $groupedByCos = $this->api->repository()->accounts->getGroupedByCos($this->formData['domain']);
        $cosLimits    = $this->productManager->getSettingCos();

        /**
         *
         * if is configured one quote in product configuration and provided by client is not the same
         */
        if(is_string($cosLimits) &&  $cosLimits !== $this->formData['cosId'])
        {
            $this->setError('Quota id is not valid.');
            return false;
        }

        /**
         *
         * if is configured one quote
         */
        if(is_string($cosLimits) &&  $cosLimits === $this->formData['cosId']){

            return true;
        }

        /**
         * check if type of quote is availabel for client
         */
        if(!array_key_exists($this->formData['cosId'], $cosLimits))
        {
            $this->setError('There is no quota available to use');
            return false;
        }

        /**
         * check if limit has been reached
         */
        if(is_countable($groupedByCos[$this->formData['cosId']])) {
            if ($cosLimits[$this->formData['cosId']] !== Size::UNLIMITED && count($groupedByCos[$this->formData['cosId']]) >= $cosLimits[$this->formData['cosId']] && $this->formData['cosId'] !== $this->formData['currentCosId'])
            {
                $this->setError('There are too many mailboxes with selected quota limit');
                return false;
            }
        }
        return true;
    }

    /**
     * @return Account
     */
    protected function getModel()
    {
        /**
         * create new account in kerio
         */
        $account = new Account();
        $account->setName($this->formData['username'].'@'.$this->formData['domain']);
        $account->setPassword(html_entity_decode($this->formData['password']), ENT_QUOTES);
        /**
         *  set account attributes
         */
        $account->setAttr(Account::ATTR_FIRSTNAME, $this->formData['firstname']);
        $account->setAttr(Account::ATTR_LASTNAME, $this->formData['lastname']);
        $account->setAttr(Account::ATTR_PHONE, $this->formData['phone']);
        $account->setAttr(Account::ATTR_MOBILE_PHONE, $this->formData['mobile_phone']);
        $account->setAttr(Account::ATTR_FAX, $this->formData['fax']);
        $account->setAttr(Account::ATTR_PAGER, $this->formData['pager']);
        $account->setAttr(Account::ATTR_HOME_PHONE, $this->formData['home_phone']);
        $account->setAttr(Account::ATTR_COUNTRY, $this->formData['country']);
        $account->setAttr(Account::ATTR_STATE, $this->formData['state']);
        $account->setAttr(Account::ATTR_POSTAL_CODE, $this->formData['post_code']);
        $account->setAttr(Account::ATTR_CITY, $this->formData['city']);
        $account->setAttr(Account::ATTR_PROF_TITLE, $this->formData['title']);
        $account->setAttr(Account::ATTR_STREET, $this->formData['street']);
        $account->setAttr(Account::ATTR_COMPANY, $this->formData['company']);
        $account->setAttr(Account::ATTR_ACCOUNT_STATUS, $this->formData['status']);
        $account->setAttr(Account::ATTR_DISPLAY_NAME, $this->formData['display_name']);

        /* @var $cos ClassOfService*/
        $cos = $this->cosModels[$this->formData['cosId']];

        /**
         * set quota by class of service
         */
        $account->setAttr(Account::ATTR_MAIL_QUOTA, $cos->getDataResourceA(Account::ATTR_MAIL_QUOTA));

        /**
         * define class of services attribute for account
         */
        $cosAttrs = $cos->getAllDataResourcesAAttributes();

        foreach(Kerio::BASE_ACCOUNT_CONFIG as $key)
        {
            $value = $cosAttrs[$key] ? $cosAttrs[$key] : Kerio::ATTR_DISABLED;
            $account->setAttr($key, $value);
        }

        /**
         *
         * set class of service id as account attribute
         */
        $account->setAttr(Account::ATTR_CLASS_OF_SERVICE_ID, $cos->getId());

        return $account;
    }

    /**
     * @return mixed
     */
    protected function getMailboxes()
    {
        $mailBoxes = $this->api->repository()->accounts->getMailboxes($this->formData['domain']);

        $filterbyCOS = $this->productManager->get('filterAccountsByCOS');

        /**
         * todo should be taken from option or from configurable options, is depend if from config option or dedicated class of service has been selected
         */
        $getConfigOptCos = $this->formData['cosId'];

        /**
         * filter mailboxes if required
         */
        if($getConfigOptCos && $filterbyCOS === ProductParams::SWITCHER_ENABLED)
        {
            $mailBoxes = array_filter($mailBoxes, function($row) use ($getConfigOptCos)
            {
                /* @var $row  Account*/
                return $row->getDataResourceA(Account::ATTR_CLASS_OF_SERVICE_ID) == $getConfigOptCos;
            });
        }

        return $mailBoxes;
    }

}