<?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\Domain;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Traits\ProductManagerHandler;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * 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(is_countable($domainAliases)){
            if(count($domainAliases) >= $domainAliasesLimit && $domainAliasesLimit !== ProductParams::SIZE_UNLIMITED)
            {
                $this->setError('Domain aliases limit has been reached');
                return false;
            }
        }
        return true;
    }

    /**
     * @return bool|mixed|Domain|\ThurData\Servers\KerioEmail\App\Libs\Kerio\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']);
        $domain->setAttr(Domain::ATTR_ALIAS_CATCHALL, '@' . $this->formData['domain']);

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

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

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

}