<?php

namespace ModulesGarden\Servers\ZimbraEmail\App\UI\Client\EmailAccount\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\Services\Delete\DeleteAccount;
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:28
 * Class DeleteAccountDataProvider
 */
class DeleteAccountDataProvider extends BaseDataProvider
{

    public function read()
    {
        $this->data['id'] = $this->actionElementId;
    }

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

    public function delete()
    {

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

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

        /**
         *
         * get soap create domain  service
         */
        $service =(new ZimbraManager())
            ->getApiByHosting($hid)
            ->soap
            ->service()
            ->deleteAccount();
        /**
         *
         * set product manager & form data to service
         */
        $service
            ->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('emailAccountHasBeenDeleted')->setStatusSuccess();

    }

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

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

        /**
         *
         * get soap create domain  service
         */
        $service =(new ZimbraManager())
            ->getApiByHosting($hid)
            ->soap
            ->service()
            ->deleteAccount();

        /**
         *
         */
        foreach($this->request->get('massActions') as $id)
        {
            $service->setFormData(['id' => $id]);
            $result = $service->run();
        }

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