<?php
namespace ThurData\Servers\KerioEmail\App\UI\Client\DistributionList\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: 13:32
 * Class AddListDataProvider
 */
class AddListDataProvider extends BaseDataProvider
{

    public function read()
    {
        $domain = $this->getWhmcsParamByKey('domain');
        $this->data['domain'] = $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()];
        }
        $fields = array(
            "id",
            "loginName");
        try {
            $accounts = $api->getUsers($fields,$domainID);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();

        $lang = di('lang');

        $this->availableValues['moderator']['none'] = $lang->absoluteT('none');
        foreach($accounts as $account)
        {
            $this->availableValues['memberList'][$account['loginName']] = $account['loginName'] . '@' . $domain;
            $this->availableValues['moderator'][$account['loginName']] = $account['loginName'] . '@' . $domain;
        }

        /**
         * subscription requests
         */
        $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')
        ];

        /**
         * postings
         */
        $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->availableValues['nonMemberPosting'] = [
            Kerio::STATUS_REJECT   => $lang->absoluteT('Automatically reject'),
            Kerio::STATUS_APPROVAL => $lang->absoluteT('Require moderator approval'),
            Kerio::STATUS_ACCEPT   => $lang->absoluteT('Automatically accept')
        ];

        /**
         * replayTo
         */
        $this->availableValues['replyEmailAddress'] = [
            'Sender' => $lang->absoluteT('Sender'),
            'ThisList' => $lang->absoluteT('ThisList'),
            'SenderThisList' => $lang->absoluteT('SenderThisList')
        ];

        $this->availableValues['lang'] = [ 'de' => $lang->absoluteT('german'), 'en' => $lang->absoluteT('english') ];

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

    }

    /**
     *
     */
    public function loadReloadedData()
    {
        foreach($this->formData as $key => $value)
        {
            $this->data[$key] = $value;
        }

    }

    public function create()
    {
        
        $domain = $this->getWhmcsParamByKey('domain');
        // add domain to members
        foreach($this->formData['memberList'] as $member) {
            $memberList[] = $member . '@' . $domain;
        }

        /**
         * custom members
         */
        $customMembers = explode(',',$this->formData['customMember']);
        foreach($customMembers as $customMember)
        {
            if($customMember !== '' && !in_array($customMember, $this->formData['memberList']))
            {
                $customMemberList[] = $customMember;
            }
        }

        $paramsCreate['name'] = $this->formData['listmail'];
        $paramsCreate['description'] = $this->formData['description'];
        $paramsCreate['languageId'] = $this->formData['lang'];
        $paramsCreate['subscription']['type'] = $this->formData['subscriptionRequest'];
        $paramsCreate['subscription']['moderatorNotification'] = $this->formData['subscriptionNotify'] === 'on' ? true : false;
        $paramsCreate['replyTo'] = $this->formData['replyEmailAddress'];
        $paramsCreate['posting']['memberPosting'] = $this->formData['memberPosting'];
        $paramsCreate['posting']['nonMemberPosting'] = $this->formData['nonMemberPosting'];
        $paramsCreate['posting']['sendErrorsToModerator'] = $this->formData['sendErrorsToModerator'] === 'on' ? true : false;

        $paramsAddMembers = array();
        if($this->formData['moderator'] != 'none') {
            $moderator = array(
                "hasId" => true,
                "emailAddress" => $this->formData['moderator'] . '@' . $domain,
                "fullName" => '',
                "kind" => "Moderator"
            );
            array_push($paramsAddMembers, $moderator);
        }

        foreach($memberList as $member) {
            $intMember = array(
                "hasId" => true,
                "emailAddress" => $member,
                "fullName" => '',
                "kind" => "Member"
            );
            array_push($paramsAddMembers, $intMember);
        }

        foreach($customMemberList as $customMember) {
            $extMember = array(
                "hasId" => false,
                "emailAddress" => $customMember,
                "fullName" => '',
                "kind" => "Member"
            );
            array_push($paramsAddMembers, $extMember);
        }

        $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()];
        }

        $paramsCreate['domainId'] = $domainID;

        try {
            $result = $api->createMailinglist($paramsCreate);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }

        $listID = $result[0]['id'];

        try {
            $result = $api->addMlUserList($paramsAddMembers, $listID);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }

        $api->logout();

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

    }

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