<?php

namespace ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Services\Create;


use ModulesGarden\Servers\ZimbraEmail\App\Enums\ProductParams;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Interfaces\ApiService;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Models\AccountAlias;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Traits\ProductManagerHandler;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * 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(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->getError());
            return false;
        }

        return $result;
    }

}