<?php

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

use ThurData\Servers\KerioEmail\App\Enums\ProductParams;
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\Api\KerioWhmcs;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * Date: 02.10.19
 * Time: 08:36
 * Class EditListDataProvider
 */
class EditListDataProvider extends AddListDataProvider
{

    public function read()
    {
        $fields = array(
            "id",
            "name",
            "description",
            "languageId",
            "subscription",
            "replyTo",
            "posting"
        );
        $cond = array(
            "fieldName" => "id",
            "comparator" => "Eq",
            "value" => $this->actionElementId
        );
        $userFields = array(
            "hasId",
            "emailAddress",
            "kind"
        );
        $domain = $this->getWhmcsParamByKey('domain');
        $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 {
            $domainID = $api->getDomainId($domain);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        try {
            $list = $api->getMailingLists($fields,$domainID,[ $cond ]);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        try {
            $members = $api->getMlUserList($userFields, $this->actionElementId);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $accountFields = array(
            "id",
            "loginName");
        try {
            $accounts = $api->getUsers($accountFields,$domainID);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }

        $api->logout();

        foreach($members as $member) {
            if($member['kind'] === 'Moderator') {
                $this->data['moderator'] = $member['emailAddress'];
            } elseif ($member['hasId'] == TRUE) {
                $intMembers[] = $member['emailAddress'];
                $allMembers[] = $member['emailAddress'];
            } else {
                $extMembers[] = $member['emailAddress'];
                $allMembers[] = $member['emailAddress'];
            }
        }
        $this->data['oldModerator'] = $this->data['moderator'];
        foreach($accounts as $account) {
            $users[] = $account['loginName'] . '@' . $domain;
        }

        $lang = di('lang');

        $this->data['id'] = $list[0]['id'];

        $this->data['listmail']     = $list[0]['name'];
        $this->data['domain']       = $domain;
        $this->data['description']  = $list[0]['description'];
        $this->data['lang']         = $list[0]['languageId'];
        $this->availableValues['lang'] = [ 'de' => $lang->absoluteT('german'), 'en' => $lang->absoluteT('english') ];
        $this->data['subscriptionRequest'] = $list[0]['subscription']['type'];
        $this->availableValues['subscriptionRequest'] = [
            Kerio::STATUS_REJECT   => $lang->absoluteT('Automatically reject'),
            Kerio::STATUS_APPROVAL => $lang->absoluteT('Require moderator approval'),
            Kerio::STATUS_ACCEPT   => $lang->absoluteT('Automatically accept')
        ];
        $this->data['subscriptionNotify'] = $list[0]['subscription']['moderatorNotification'] === TRUE ? ProductParams::SWITCHER_ENABLED : ProductParams::SWITCHER_DISABLED;
        $this->data['memberPosting']      = $list[0]['posting']['memberPosting'];
        $this->availableValues['memberPosting'] = [
            Kerio::STATUS_ACCEPT   => $lang->absoluteT('Automatically accept'),
            Kerio::STATUS_APPROVAL => $lang->absoluteT('Require moderator approval'),
            Kerio::STATUS_REJECT   => $lang->absoluteT('Automatically reject')
        ];
        $this->data['nonMemberPosting']      = $list[0]['posting']['nonMemberPosting'];
        $this->availableValues['nonMemberPosting'] = [
            Kerio::STATUS_REJECT   => $lang->absoluteT('Automatically reject'),
            Kerio::STATUS_APPROVAL => $lang->absoluteT('Require moderator approval'),
            Kerio::STATUS_ACCEPT   => $lang->absoluteT('Automatically accept')
        ];
        $this->data['sendErrorsToModerator'] = $list[0]['posting']['sendErrorsToModerator'] === TRUE ? ProductParams::SWITCHER_ENABLED : ProductParams::SWITCHER_DISABLED;
        $this->data['replyEmailAddress']      = $list[0]['replyTo'];
        $this->availableValues['replyEmailAddress'] = [
            'Sender' => $lang->absoluteT('Sender'),
            'ThisList' => $lang->absoluteT('ThisList'),
            'SenderThisList' => $lang->absoluteT('SenderThisList')
        ];

        foreach($intMembers as $intMember) {
            $this->data['memberList'][] = $intMember;
        }
        $this->availableValues['moderator']['none'] = 'none';
        foreach($users as $user) {
            $this->availableValues['memberList'][$user] = $user;
            $this->availableValues['moderator'][$user] = $user;
        }
        foreach($allMembers as $availableMember) {
            $this->data['memberListActually'][$availableMember] = $availableMember;
            $this->availableValues['memberListActually'][$availableMember] = $availableMember;
        }
        $this->data['customMember'] = implode(',',$extMembers);

        if($this->formData)
        {
            $this->loadReloadedData();
        }

    }

    /**
     *
     */
    public function update()
    {
        // prepare data
        // get settings
        $paramsSet['name'] = $this->formData['listmail'];
        $paramsSet['description'] = $this->formData['description'];
        $paramsSet['languageId'] = $this->formData['lang'];
        $paramsSet['subscription']['type'] = $this->formData['subscriptionRequest'];
        $paramsSet['subscription']['moderatorNotification'] = $this->formData['subscriptionNotify'] === 'on' ? true : false;
        $paramsSet['replyTo'] = $this->formData['replyEmailAddress'];
        $paramsSet['posting']['memberPosting'] = $this->formData['memberPosting'];
        $paramsSet['posting']['nonMemberPosting'] = $this->formData['nonMemberPosting'];
        $paramsSet['posting']['sendErrorsToModerator'] = $this->formData['sendErrorsToModerator'] === 'on' ? true : false;
        // find new internal members to add
        foreach($this->formData['memberList'] as $intMember) {
            if(!in_array($intMember, $this->formData['memberListActually'])) {
                $addIntMembers[] = $intMember;
            }
        }
        // prepare
        if(!empty($addIntMembers)){
            foreach($addIntMembers as $addIntMember) {
                $paramsAdd[] = array(
                    'hasId' => TRUE,
                    'emailAddress' => $addIntMember,
                    'kind' => 'Member'
                );
            }
        }
        // find new external members to add
        if(!empty($this->formData['customMember'])){
            $customMembers = explode(',',$this->formData['customMember']);
            foreach($customMembers as $extMember) {
                if(!in_array($extMember, $this->formData['memberListActually'])) {
                    $addExtMembers[] = $extMember;
                }
            }
        }
        // prepare
        if(!empty($addExtMembers)){
            foreach($addExtMembers as $addExtMember) {
                $paramsAdd[] = array(
                    'hasId' => FALSE,
                    'emailAddress' => $addExtMember,
                    'kind' => 'Member'
                );
            }
        }
        // find members to remove
        foreach($this->formData['memberListActually'] as $oldMember) {
            if((!in_array($oldMember,$this->formData['memberList'])) && (!in_array($oldMember,$customMembers))){
                $delMembers[] = $oldMember;
            }
        }
        // prepare
        if(!empty($delMembers)){
            foreach($delMembers as $delMember) {
                $paramsDel[] = array(
                    'emailAddress' => $delMember,
                    'kind' => 'Member'
                );
            }
        }
        // change moderator
        if($this->formData['moderator'] != $this->formData['oldModerator']) {
            if(!empty($this->formData['oldModerator'])) {
                $paramsDel[] = array(
                    'emailAddress' => $this->formData['oldModerator'],
                    'kind' => 'Moderator'
                );
            }
            if($this->formData['moderator'] != 'none') {
                $paramsAdd[] = array(
                    'hasId' => TRUE,
                    'emailAddress' => $this->formData['moderator'],
                    'kind' => 'Moderator'
                );
            }
        }

        $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()];
        }
        // change settings
        try {
            $api->modifyMailinglist($paramsSet, $this->formData['id']);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        // delete mebers
        if($paramsDel){
            try {
                $api->delMlUserList($paramsDel, $this->formData['id']);
            } catch (KerioApiException $error) {
                logModuleCall(
                    'kerioEmail',
                    __FUNCTION__,
                    $error,
                    'Debug Error',
                    $error->getMessage()
                );
                return ['error' => $error->getMessage()];
            }
        }
        // add members
        if($paramsAdd){
            try {
                $api->addMlUserList($paramsAdd, $this->formData['id']);
            } catch (KerioApiException $error) {
                logModuleCall(
                    'kerioEmail',
                    __FUNCTION__,
                    $error,
                    'Debug Error',
                    $error->getMessage()
                );
                return ['error' => $error->getMessage()];
            }
        }
        $api->logout();
        return (new HtmlDataJsonResponse())->setMessageAndTranslate('distributionListHasBeenUpdated')->setStatusSuccess();

    }
}