<?php

namespace ThurData\Servers\KerioEmail\App\UI\Client\EmailAccount\Providers;

use ThurData\Servers\KerioEmail\App\Enums\Kerio;
use function ThurData\Servers\KerioEmail\Core\Helper\di;
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: 09:35
 * Class EditAccountDataProvider
 */
class EditAccountDataProvider extends BaseDataProvider
{

    /**
     *
     */
    public function read()
    {
        $domain = $this->getWhmcsParamByKey('domain');
        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        $fields =array(
            'id',
            'companyContactId',
            'loginName',
            'fullName',
            'description',
            'emailForwarding',
            'isEnabled',
            'emailAddresses',
            'diskSizeLimit',
        );
        $cond = array(
            array(
                "fieldName" => "id",
                "comparator" => "Eq",
                "value" => $this->actionElementId
            )
        );

        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        try {
            $domainID = $api->getDomainId($domain);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        try {
            $account = $api->getUsers($fields,$domainID,$cond);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        try {
            $address = $api->getAddress($this->actionElementId);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();
        $this->data['id']           = $account[0]['id'];
        $this->data['username']     = $account[0]['loginName'];
        $this->data['domain']       = $domain;
        $this->data['firstname']    = $address['contacts'][0]['firstName'];
        $this->data['lastname']     = $address['contacts'][0]['surName'];
        $this->data['display_name'] = $address['contacts'][0]['commonName'];
        $this->data['status']       = $account['isEnabled'];
        $this->data['title']        = $address['contacts'][0]['titleBefore'];
        $this->data['profession']   = $address['contacts'][0]['profession'];
        $this->data['work_phone']   = $address['contacts'][0]['phoneNumberWorkVoice'];
        $this->data['mobile_phone'] = $address['contacts'][0]['phoneNumberMobile'];
        $this->data['department']   = $address['contacts'][0]['departmentName'];
        $this->data['office']       = $address['contacts'][0]['postalAddressWork']['extendedAddress'];
        if ($account[0]['diskSizeLimit']['isActive'] === TRUE) {
            $this->data['quota'] = $account[0]['diskSizeLimit']['limit']['value'];
            $this->data['unit'] = $account[0]['diskSizeLimit']['limit']['units'];
        } else {
            $this->data['quota'] = 0;
        }
        if ($account[0]['emailForwarding']['mode'] === 'UForwardYes') {
            $this->data['forward'] = 'on';
            $this->data['target'] = $account[0]['emailForwarding']['emailAddresses'][0];
        }
        $lang = di('lang');
        if ($this->data['status'] == 1) {
            $this->availableValues['status'] = [
                Kerio::ACC_STATUS_ACTIVE        => $lang->absoluteT('kerio','account','status','active'),
                Kerio::ACC_STATUS_CLOSED        => $lang->absoluteT('kerio','account','status','closed')
            ];
        } else {
            $this->availableValues['status'] = [
                Kerio::ACC_STATUS_CLOSED        => $lang->absoluteT('kerio','account','status','closed'),
                Kerio::ACC_STATUS_ACTIVE        => $lang->absoluteT('kerio','account','status','active')
            ];
        }
        $this->availableValues['unit'] = [
            'MegaBytes' => 'MB',
            'GigaBytes' => 'GB',
        ];

    }

    /**
     * @return HtmlDataJsonResponse
     */
    public function update()
    {
        $fieldToProtection = ['firstname', 'lastname', 'display_name', 'office', 'title', 'department', 'profession'];

        foreach ($this->formData as $field => &$value)
        {
            $value = in_array($field, $fieldToProtection) ? htmlentities($value) : $value;
        }

        $account['isEnabled'] = $this->formData['status'] === 'active' ? TRUE : FALSE;
        if ($this->formData['quota'] > 0) {
            $account['diskSizeLimit']['isActive'] = TRUE;
        } else {
            $account['diskSizeLimit']['isActive'] = FALSE;
        }
        $account['diskSizeLimit']['limit']['value'] = intval($this->formData['quota']);
        $account['diskSizeLimit']['limit']['units'] = $this->formData['unit'];

        if ( $this->formData['forward'] == 'on') {
            $account['emailForwarding']['mode'] = 'UForwardYes';
            $account['emailForwarding']['emailAddresses'] = [ $this->formData['target'] ];
        } else {
            $account['emailForwarding']['mode'] = 'UForwardNone';
            $account['emailForwarding']['emailAddresses'] = [];
        }

        $fields['firstName'] = $this->formData['firstname'];
        $fields['surName'] = $this->formData['lastname'];
        $fields['commonName'] = $this->formData['display_name'];
        $fields['postalAddressWork']['extendedAddress'] = $this->formData['office'];
        $fields['titleBefore'] = $this->formData['title'];
        $fields['phoneNumberWorkVoice'] = $this->formData['work_phone'];
        $fields['phoneNumberMobile'] = $this->formData['mobile_phone'];
        $fields['departmentName'] = $this->formData['department'];
        $fields['profession'] = $this->formData['profession'];

        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        try {
            $result = $api->modifyUser($this->formData['id'], $account);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        try {
            $result = $api->setAddress($this->formData['id'], $fields);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();
        return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAccountHasBeenUpdated')->setStatusSuccess();
    }

    /**
     * @return HtmlDataJsonResponse
     */
    public function updateStatus()
    {
        $status['isEnabled'] = $this->formData['status'] === 'active' ? TRUE : FALSE;
        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        try {
            $result = $api->modifyUser($this->formData['id'], $status);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();

        return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAccountStatusHasBeenUpdated')->setStatusSuccess();

    }

    /**
     * @return HtmlDataJsonResponse
     */
    public function changePassword()
    {
        $fields['password'] = $this->formData['password'];
        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        try {
            $result = $api->modifyUser($this->formData['id'], $fields);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();

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

}