<?php
namespace ThurData\Servers\KerioEmail\App\UI\Client\EmailAlias\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: 11:50
 * Class AddEmailAliasDataProvider
 */
class AddEmailAliasDataProvider extends BaseDataProvider
{

    public function read()
    {
        $this->data['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($this->data['domain']);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }

        $fields = array(
            "id",
            "loginName"
        );
        $accounts = $api->getUsers($fields,$domainID);
        $api->logout();

        /**
         * available accounts
         */
        foreach($accounts as $account)
        {
            $this->availableValues['mailbox'][$account['loginName']] = $account['loginName'] . '@' . $this->data['domain'];
        }

    }

    public function create()
    {
        $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()];
        }
        try {
            $result = $api->createAlias($domainID, $this->formData['aliasName'], $this->formData['mailbox'] . '@' . $domain);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }

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

    public function update()
    {
        // TODO: Implement update() method.
    }
}