<?php
namespace ThurData\Servers\KerioEmail\App\UI\Client\DomainAlias\Providers;

use ThurData\Servers\KerioEmail\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ThurData\Servers\KerioEmail\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;
use ThurData\Servers\KerioEmail\Api\KerioWhmcs;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * Date: 18.09.19
 * Time: 13:39
 * Class AddDomainAliasDataProvider
 */
class AddDomainAliasDataProvider extends BaseDataProvider
{

    public function read()
    {
        $domain = $this->getWhmcsParamByKey('domain');
        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
            $domainID = $api->getDomainId($domain);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();
        $this->data['domainId'] = $domainID;
        $this->data['domain']   = $domain;

    }

    public function update()
    {

    }

    public function create()
    {

        $maildomain = $this->getWhmcsParamByKey('domain');
        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
            $domains = $api->getDomains(['id','name','aliasList']);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        foreach($domains as $domain) {
            if($domain['name'] === $maildomain){ 
                $domainID = $domain['id'];
                $aliasList = $domain['aliasList'];
            }
        }
        array_push($aliasList, $this->formData['alias']);
        $attr = array('aliasList' => $aliasList);
        try {
            $result = $api->modifyDomain($domainID,$attr);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();

        return (new HtmlDataJsonResponse())->setMessageAndTranslate('domainAliasHasBeenCreated')->setStatusSuccess();
    }


}