<?php

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


use ThurData\Servers\KerioEmail\App\Enums\ProductParams;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Interfaces\ApiService;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Models\AccountAlias;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Traits\ProductManagerHandler;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * Date: 09.10.19
 * Time: 09:08
 * Class CreateAccountAlias
 */
class CreateAccountAlias extends ApiService
{
    use ProductManagerHandler;

    /**
     * @return bool|void
     */
    public function isValid()
    {
        $limit = $this->productManager->get(ProductParams::ALIAS_LIMIT);
        $createdAlias = $this->api->repository()->accounts->getAccountAliasesByDomainName($this->formData['domain']);
        if(is_countable($createdAlias)){
            if(count($createdAlias) >= $limit && $limit !== ProductParams::SIZE_UNLIMITED)
            {
                $this->setError('Account alias limit has been reached');
                return false;
            }
        }
        return true;
    }

    /**
     * @return mixed|void
     */
    public function process()
    {
        /**
         * prepare model
         */
        $alias = $alias = $this->formData['aliasName'].'@'.$this->formData['domain'];
        $aliasAccount = new AccountAlias();
        $aliasAccount->setAlias($alias);
        $aliasAccount->setAccountId($this->formData['mailbox']);

        /**
         * create account alias in API
         */
        $result = $this->api->account->createAlias($aliasAccount);

        /**
         * problem with create account
         */
        if(!$result)
        {
            $this->setError($this->api->account->getLastResult()->getLastErrorCode());
            return false;
        }

        return $result;
    }

}