<?php
namespace ModulesGarden\Servers\ZimbraEmail\App\UI\Client\DomainAlias\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\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\Create\CreateDomainAlias;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Services\Delete\DeleteDomainAlias;
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:39
 * Class AddDomainAliasDataProvider
 */
class AddDomainAliasDataProvider extends BaseDataProvider
{

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

        /**
         * get API
         */
        $api =(new ZimbraManager())
            ->getApiByServer($hosting->server)
            ->soap;

        /**
         * load domain from repo
         */
        $domain = $api->repository()
            ->domains
            ->getByName($hosting->domain);

        $this->data['domainId'] = $domain->getId();
        $this->data['domain']   = $hosting->domain;

    }

    public function update()
    {

    }

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

        /**
         * load product configuration
         */
        $productManager = new ProductManager();
        $productManager->loadByHostingId($hid);

        /**
         * load zimbra manager by hosting id
         */
        $service = (new ZimbraManager())
            ->getApiByHosting($hid)
            ->soap
            ->service()
            ->createDomainAlias()
            ->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('domainAliasHasBeenCreated')->setStatusSuccess();
    }


}