<?php
namespace ModulesGarden\Servers\ZimbraEmail\App\Http\Actions;

use ModulesGarden\Servers\ZimbraEmail\App\Helpers\ZimbraManager;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Api;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Client;
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: 27.08.19
 * Time: 14:54
 * Class TestConnection
 */
class TestConnection extends AddonController
{

    use ExtensionsCheckerTrait;
    /**
     *
     *
     * @param null $params
     * @return array
     */
    public function execute($params = null)
    {
        try{

            /**
             *
             */
            $this->checkExtensionOrThrowError();
            /**
             * zimbra API manager
             */
            $manager = (new ZimbraManager());

            /**
             * set API params
             */
            if($params['serverusername'] )
            {
                /**
                 *
                 * override secure param
                 */
                $params['serversecure'] = $params['serversecure'] ? 'on' : 'off';

                $api = $manager->getApi()->setParams($params);
            }else{
                $api = $manager->getApiByServer($params['serverid']);
            }

            /**
             * API Connection
             */
            $connection = $api->soap->getConnection();

            /**
             * check if connected and return true
             */
            if($connection->isConnected())
            {
                return ['success' => true];
            }

            /**
             *
             * return connection error
             */
            return ['error' => $connection->getConnectionError()];
        }
        catch (\Exception $ex)
        {
            /**
             * return some crit error
             */
            return ['error' => $ex->getMessage()];
        }

    }
}