<?php
namespace ThurData\Servers\KerioEmail\App\UI\Client\DomainAlias\Providers;
use ThurData\Servers\KerioEmail\App\Helpers\KerioManager;
use ThurData\Servers\KerioEmail\App\Libs\Product\ProductManager;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Repository;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Services\Create\CreateDistributionList;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Services\Create\CreateDomainAlias;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Services\Delete\DeleteDomainAlias;
use ThurData\Servers\KerioEmail\Core\Models\Whmcs\Hosting;
use ThurData\Servers\KerioEmail\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ThurData\Servers\KerioEmail\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * 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 KerioManager())
            ->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 kerio manager by hosting id
         */
        $service = (new KerioManager())
            ->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())->setMessageAndTranslate($service->getError())->setStatusError();
        }

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


}