<?php

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


use ModulesGarden\Servers\ZimbraEmail\App\Enums\ControllerEnums;
use ModulesGarden\Servers\ZimbraEmail\App\Helpers\BuildUrlExtended;
use ModulesGarden\Servers\ZimbraEmail\App\Helpers\ZimbraManager;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Product\ProductManager;
use ModulesGarden\Servers\ZimbraEmail\App\Traits\ExtensionsCheckerTrait;
use ModulesGarden\Servers\ZimbraEmail\Core\App\Controllers\Instances\AddonController;
use ModulesGarden\Servers\ZimbraEmail\Core\Helper;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Traits\WhmcsParams;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 08.11.19
 * Time: 09:47
 * Class AdminSingleSignOn
 */
class AdminSingleSignOn extends AddonController
{

    use ExtensionsCheckerTrait;
    /**
     *
     *
     * @param null $params
     * @return array
     */
    public function execute($params = null)
    {
        try
        {
            /**
             *
             */
            $this->checkExtensionOrThrowError();
            /**
             * zimbra API manager
             */
            $manager = (new ZimbraManager());
            $api = $manager->getApiByServer($params['serverid']);


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


            /**
             * Build URL
             */
            $redirectTo = $connection->getServerUrl().'/service/preauth?'.http_build_query([
                    'authtoken' => $connection->getAuthToken()
            ]);

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