<?php
namespace ModulesGarden\Servers\ZimbraEmail\App\UI\Client\DistributionList\Providers;
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\Helpers\ServiceFactory;
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 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: 18.09.19
 * Time: 13:32
 * Class AddListDataProvider
 */
class AddListDataProvider extends BaseDataProvider
{

    public function read()
    {
        $hosting = Hosting::where('id', $this->getRequestValue('id'))->first();
        $this->data['domain'] = $hosting->domain;

        /**
         * load api
         */
        $accounts     = (new ZimbraManager())
            ->getApiByServer($hosting->server)
            ->soap
            ->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')
        ];



        /**
         *
         */
        foreach($accounts as $account)
        {
            $this->availableValues['memberList'][$account->getName()] = $account->getName();
        }

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

    }

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

    }

    public function create()
    {
        /**
         *
         * 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;
            }
        }

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

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

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

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

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

        /**
         * load zimbra manager by hosting id
         */
        $service = (new ZimbraManager())
            ->getApiByHosting($hid)
            ->soap
            ->service()
            ->createDistributionList()
            ->setFormData($this->formData)
        ;

        /**
         * load product configuration
         */
        $productManager = new ProductManager();
        $productManager->loadByHostingId($hid);
        $service->setProductManager($productManager);
        $result= $service->run();
        if(!$result)
        {
            return (new HtmlDataJsonResponse())->setMessage($service->getError())->setStatusError();
        }

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

    }

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