<?php
namespace ModulesGarden\Servers\ZimbraEmail\App\UI\Client\EmailAlias\Providers;
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\AccountAlias;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Repository;
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: 11:50
 * Class AddEmailAliasDataProvider
 */
class AddEmailAliasDataProvider extends BaseDataProvider
{

    public function read()
    {
        /**
         * hosting id
         */
        $hid = $this->getRequestValue('id');

        /**
         * hosting model
         */
        $hosting = Hosting::where('id', $hid)->first();

        /**
         * hosting domain
         */
        $this->data['domain'] = $hosting->domain;

        /**
         * load api
         * load repo
         * load accounts from repo
         */
        $accounts =(new ZimbraManager())
            ->getApiByHosting($hid)
            ->soap
            ->repository()
            ->accounts
            ->getByDomainName($hosting->domain);

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

    }

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

        /**
         * product manager allow to check product settings
         */
        $productManager = new ProductManager();
        $productManager->loadByHostingId($hid);

        /**
         *
         * get soap create alias service
         * set service configuration
         */
        $service =(new ZimbraManager())
            ->getApiByHosting($hid)
            ->soap
            ->service()
            ->createAccountAlias()
            ->setProductManager($productManager)
            ->setFormData($this->formData);

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

        /**
         *
         * return success or error response
         */
        if(!$result)
        {
            return (new HtmlDataJsonResponse())->setMessage($service->getError())->setStatusError();
        }

        return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAliasHasBeenCreated')->setStatusSuccess();
    }

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