<?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 ThurData\Servers\KerioEmail\App\Helpers\KerioManager;
use ThurData\Servers\KerioEmail\App\Libs\Product\ProductManager;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Models\DistributionList;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Repository;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Services\Create\CreateDistributionList;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Services\Update\UpdateDistributionList;
use function ThurData\Servers\KerioEmail\Core\Helper\di;
use ThurData\Servers\KerioEmail\Core\Models\Whmcs\Hosting;
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: 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"
        );

        $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($this->getWhmcsParamByKey('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'];
            } else {
                $extMembers[] = $member['emailAddress'];
            }
        }

        foreach($accounts as $account) {
            $users[] = $account['loginName'] . '@' . $this->getWhmcsParamByKey('domain');
        }

        $availableMembers = array_values(array_diff($users, $intMembers));

        logModuleCall(
            'kerioEmail',
            __FUNCTION__,
            $intMembers,
            'Debug Members',
            $extMembers
        );

        logModuleCall(
            'kerioEmail',
            __FUNCTION__,
            $availableMembers,
            'Debug Moderator',
            $this->data['moderator']
        );

        /**
         * load hosting
         */
        $hosting = Hosting::where('id', $this->getRequestValue('id'))->first();

        /**
         * load lang
         */
        $lang = di('lang');

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

        $this->data['listmail']     = $list[0]['name'];
        $this->data['domain']       = $this->getWhmcsParamByKey('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;
        }
        $allMembers = array_merge($intMember, $extMembers);
        foreach($allMembers as $availableMember) {
            $this->data['memberListActually'][$availableMember] = 
            $this->availableValues['memberListActually'][$availableMember] = 
            $this->availableValues['memberList'][$availableMember] =
            $availableMember;
        }
        $this->data['customMember'] = implode(',',$extMembers);

        logModuleCall(
            'kerioEmail',
            __FUNCTION__,
            $this->data,
            'Debug Data',
            $this->availableValues
        );

        /**
         * allow to check which should be removed
         */
//        $this->availableValues['memberListActually']   = $this->data['memberListActually']      = $list->getResourceMembers();
//        $this->availableValues['emailAliasesActually'] = $this->data['emailAliasesActually']    = $list->getResourceAliases();
//        $this->availableValues['ownersActually']       = $this->data['ownersActually']          = $list->getResourceOwners();


        /**
         * available members
         */
//        $accounts = $repository->accounts->getByDomainName($hosting->domain);

//        $members = $list->getResourceMembers();

        /**
         *
         */
//        foreach ($accounts as $account)
//        {
//            if(in_array($account->getName(),$members))
//           {
//               $this->data['memberList'][] = $account->getName();
//             }

//            $this->availableValues['memberList'][$account->getName()] = $account->getName();
//        }

        /**
         * add custom members to array
         */
//        $ownMembers = $this->data['memberList'] ? $this->data['memberList'] : [];
//        $this->data['customMember'] = implode(',',array_diff($members, $ownMembers));

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

    }

    /**
     *
     */
    public function update()
    {

        /**
         *
         * provided aliases
         */
        $customEmails = explode(',',$this->formData['emailAliases']);
        $this->formData['emailAliases'] = [];
        foreach($customEmails as $email)
        {
            if ($email !== '')
            {
                $this->formData['emailAliases'][] = $email;
            }
        }

        /**
         * provided owners
         */
        $owners = explode(',',$this->formData['owners']);
        $this->formData['owners'] = [];
        foreach($owners as $email)
        {
            if ($email !== '')
            {
                $this->formData['owners'][] = $email;
            }
        }

        /**
         *  display name
         */
        $this->formData['displayName'] = htmlentities($this->formData['displayName']);

        /**
         *  reply display name
         */
        $this->formData['replyDisplayName'] = htmlentities($this->formData['replyDisplayName']);

        /**
         * custom members
         */
        $customMembers = explode(',',$this->formData['customMember']);

        foreach($customMembers as $customMember)
        {
            if($customMember !== '' && !in_array($customMember, $this->formData['memberList']))
            {
                $this->formData['memberList'][]  = $customMember;
            }
        }
        $members = $this->formData['memberList'] ? $this->formData['memberList']  : [];

        $this->formData['memberList'] = array_merge($customMembers, $members);

        /**
         * hosting id
         */
        $hid = $this->request->get('id');

        /**
         * get product manager
         */
        $productManager = new ProductManager();
        $productManager->loadByHostingId($hid);

        /**
         * load kerio manager by hosting id
         */
        $service = (new KerioManager())
            ->getApiByHosting($hid)
            ->soap
            ->service()
            ->updateDistributionList()
            ->setFormData($this->formData)
            ->setProductManager($productManager)

        ;

        /**
         *
         */
        $result = $service->run();

        if(!$result)
        {
            return (new HtmlDataJsonResponse())->setMessageAndTranslate($service->getError())->setStatusError();
        }

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

    }
}