<?php

namespace ModulesGarden\Servers\ZimbraEmail\App\UI\Client\DistributionList\Providers;


use ModulesGarden\Servers\ZimbraEmail\App\Enums\ProductParams;
use ModulesGarden\Servers\ZimbraEmail\App\Enums\Zimbra;
use ModulesGarden\Servers\ZimbraEmail\App\Helpers\ZimbraManager;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Product\ProductManager;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Models\DistributionList;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Repository;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Services\Create\CreateDistributionList;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Services\Update\UpdateDistributionList;
use function ModulesGarden\Servers\ZimbraEmail\Core\Helper\di;
use ModulesGarden\Servers\ZimbraEmail\Core\Models\Whmcs\Hosting;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 02.10.19
 * Time: 08:36
 * Class EditListDataProvider
 */
class EditListDataProvider extends AddListDataProvider
{

    public function read()
    {

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

        /**
         * load api
         */
        $api = (new ZimbraManager())->getApiByServer($hosting->server);

        $repository = new Repository($api->soap);

        $list             = $repository->lists()->getDistributionListBydId($this->actionElementId);
        $this->data['id'] = $list->getId();

        $res                    = explode('@', $list->getName());
        $this->data['listmail'] = $res[0];
        $this->data['domain']   = $res[1];

        $this->data['emailAliases']  = implode(',', $list->getResourceAliases());
        $this->data['owners']        = implode(',', $list->getResourceOwners());

        /**
         * 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();

        $this->data['displayName']           = $list->getDataResourceA(DistributionList::ATTR_DISPLAY_NAME);
        $this->data['description']           = $list->getDataResourceA(DistributionList::ATTR_DESCRIPTION);
        $this->data['subscriptionRequest']   = $list->getDataResourceA(DistributionList::ATTR_SUBSCRIPTION_REQUEST);
        $this->data['unsubscriptionRequest'] = $list->getDataResourceA(DistributionList::ATTR_UNSUBSCRIPTION_REQUEST);
        $this->data['replyDisplayName']      = $list->getDataResourceA(DistributionList::REPLY_TO_DISPLAY);
        $this->data['replyEmailAddress']     = $list->getDataResourceA(DistributionList::REPLY_TO_ADDRESS);
        $this->data['sharesNotify']          = $list->getDataResourceA(DistributionList::ATTR_NOTIFY_SHARES) === Zimbra::ATTR_ENABLED ? ProductParams::SWITCHER_ENABLED : ProductParams::SWITCHER_DISABLED;
        $this->data['hideGal']               = $list->getDataResourceA(DistributionList::ATTR_HIDE_IN_GAL) === Zimbra::ATTR_ENABLED ? ProductParams::SWITCHER_ENABLED : ProductParams::SWITCHER_DISABLED;
        $this->data['receiveMail']           = $list->getDataResourceA(DistributionList::ATTR_MAIL_STATUS) === Zimbra::ENABLED ? ProductParams::SWITCHER_ENABLED : ProductParams::SWITCHER_DISABLED;
        $this->data['replyEmail']            = $list->getDataResourceA(DistributionList::REPLY_TO_ENABLED) === Zimbra::ATTR_ENABLED ? ProductParams::SWITCHER_ENABLED : ProductParams::SWITCHER_DISABLED;
        /**
         * is dynamic group
         */
        $this->data['dynamicGroup']          = (int)$list->isDynamic() === Zimbra::ENABLED_AS_INT ? ProductParams::SWITCHER_ENABLED : ProductParams::SWITCHER_DISABLED;


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

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

        /**
         * subscription requests
         */
        $this->availableValues['subscriptionRequest'] = [
            Zimbra::STATUS_ACCEPT   => $lang->absoluteT('Automatically accept'),
            Zimbra::STATUS_APPROVAL => $lang->absoluteT('Require list owner approval'),
            Zimbra::STATUS_REJECT   => $lang->absoluteT('Automatically reject')
        ];

        /**
         * unsubscription requests
         */
        $this->availableValues['unsubscriptionRequest'] = [
            Zimbra::STATUS_ACCEPT   => $lang->absoluteT('Automatically accept'),
            Zimbra::STATUS_APPROVAL => $lang->absoluteT('Require list owner approval'),
            Zimbra::STATUS_REJECT   => $lang->absoluteT('Automatically reject')
        ];

        $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 zimbra manager by hosting id
         */
        $service = (new ZimbraManager())
            ->getApiByHosting($hid)
            ->soap
            ->service()
            ->updateDistributionList()
            ->setFormData($this->formData)
            ->setProductManager($productManager)

        ;

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

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

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

    }
}