<?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: 10.09.19
 * Time: 13:06
 * Class AccountDataProvider
 */
class AccountDataProvider extends BaseDataProvider
{

    public function read()
    {

        $this->data['domain'] = $this->getWhmcsParamByKey('domain');
        $this->data['quota'] = 0;
        $lang = di('lang');
        $this->availableValues['status'] = [
            Kerio::ACC_STATUS_ACTIVE        => $lang->absoluteT('kerio','account','status','active'),
            Kerio::ACC_STATUS_CLOSED        => $lang->absoluteT('kerio','account','status','closed'),
        ];
        $this->availableValues['unit'] = [
            'MegaBytes' => 'MB',
            'GigaBytes' => 'GB',
        ];

    }

    public function create()
    {
        $fieldToProtection = ['firstname', 'lastname', 'display_name', 'office', 'title', 'department', 'profession'];
        foreach ($this->formData as $field => &$value)
        {
            $value = in_array($field, $fieldToProtection) ? htmlentities($value) : $value;
        }

        $maildomain = $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($maildomain);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }             
        if ($domainID === FALSE) {
            return "Error: Domain $maildomain not found";
        }
        $active = $this->formData['status'] === 'active' ? TRUE : FALSE;
        try {
            $userID = $api->createUser($domainID, $this->formData['username'], $this->formData['password'], $active)['result'][0]['id'];
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }             
        $account['fullName'] = $this->formData['display_name'];
        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'];
        try {
            $result = $api->modifyUser($userID, $account);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $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'];
        try {
            $result = $api->setAddress($userID, $fields);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }

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

    }

    public function updateStatus()
    {

    }

    public function update()
    {
        $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()];
        }

        /**
         * run service for each id
         */
        foreach($this->request->get('massActions') as $id)
        {
            try {
                $result = $api->modifyUser($id, $status);
            } catch (KerioApiException $error) {
                logModuleCall(
                    'kerioEmail',
                    __FUNCTION__,
                    $error,
                    'Debug Error',
                    $error->getMessage()
                );
                return ['error' => $error->getMessage()];
            }
        }
        $api->logout();

        /**
         * return success
         */
        return (new HtmlDataJsonResponse())->setMessageAndTranslate('massEmailAccountStatusHasBeenUpdated')->setStatusSuccess();
    }

}