<?php

namespace ModulesGarden\Servers\ZimbraEmail\App\Http\Actions;


use ModulesGarden\Servers\ZimbraEmail\App\Enums\Response;
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\Domain;
use ModulesGarden\Servers\ZimbraEmail\App\Traits\ExtensionsCheckerTrait;
use ModulesGarden\Servers\ZimbraEmail\Core\App\Controllers\Instances\AddonController;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 09.09.19
 * Time: 15:14
 * Class CreateAccount
 */
class CreateAccount extends AddonController
{
    use ExtensionsCheckerTrait;

    /**
     * create domain in zimbra
     *
     * @param null $params
     * @return string
     */
    public function execute($params = null)
    {
        try{

            /**
             * check if extensions are installed
             */
            $this->checkExtensionOrThrowError();

            /**
             * run zimbra service
             */
            $result =  $this->zimbraRunService($params);
            return $result;
        }catch (\Exception $ex)
        {
            /**
             * return some crit error
             */
            return $ex->getMessage();
        }

    }

    /**
     * @param null $params
     * @return mixed|string
     */
    protected function zimbraRunService($params = null)
    {
        /**
         *
         * get soap create domain  service
         */
        $service =(new ZimbraManager())
            ->getApiByServer($params['serverid'])
            ->soap
            ->service()
            ->createDomain();

        /**
         * product manager allow to check product settings
         */
        $productManager = new ProductManager();
        $productManager->loadByHostingId($params['serviceid']);

        /**
         *
         * set params
         * run service (Create domain in Zimbra API)
         */
        $result = $service
            ->setProductManager($productManager)
            ->setFormData($params)
            ->run();

        /**
         * check service result & return error
         */
        if(!$result)
        {
            return $service->getError();
        }

        /**
         * return success response
         */
        return Response::SUCCESS;
    }
}