<?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\Domain;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Traits\ProductManagerHandler;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 02.10.19
 * Time: 13:05
 * Class DomainAlias
 */
class CreateDomainAlias extends ApiService
{
    use ProductManagerHandler;

    protected function isValid()
    {
        /**
         * check if domain alias is provided
         */
        if(!$this->formData['alias'])
        {
            $this->setError('Domain alias can not been created. No alias found.');
            return false;
        }

        /**
         * check if domain alias is provided
         */
        if(!$this->formData['domainId'])
        {
            $this->setError('Domain alias can not been created. No domain ID found.');
            return false;
        }

        /**
         * check limits
         */
        $domainAliasesLimit = $this->productManager->get(ProductParams::DOMAIN_ALIAS_LIMIT);

        /**
         * get created domains
         */
        $domainAliases = $this->api->repository()->domains->getAliases($this->formData['domain']);

        if(count($domainAliases) >= $domainAliasesLimit && $domainAliasesLimit !== ProductParams::SIZE_UNLIMITED)
        {
            $this->setError('Domain aliases limit has been reached');
            return false;
        }

        return true;
    }

    /**
     * @return bool|mixed|Domain|\ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Response
     */
    protected function process()
    {
        /**
         *
         * prepare alias model
         */
        $domain = new Domain();
        $domain->setName($this->formData['alias']);
        $domain->setAttr(Domain::ATTR_ALIAS_TARGET_ID, $this->formData['domainId']);
        $domain->setAttr(Domain::ATTR_DOMAIN_TYPE, Domain::TYPE_ALIAS);
        $domain->setAttr(Domain::ATTR_DESCRIPTION, $this->formData['description']);

        /**
         *
         * send request to ZIMBRA
         */
        $result = $this->api->domain->create($domain);

        /**
         * check if error occurred
         */
        if(!$result)
        {
            $this->setError($this->api->domain->getError());
            return false;
        }

        /**
         * return result
         */
        return $result;
    }

}