<?php

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


use ModulesGarden\Servers\ZimbraEmail\App\Enums\ControllerEnums;
use ModulesGarden\Servers\ZimbraEmail\App\Enums\ProductParams;
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\Core\Http\AbstractClientController;
use ModulesGarden\Servers\ZimbraEmail\Core\Models\Whmcs\Hosting;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Traits\WhmcsParams;
use ModulesGarden\Servers\ZimbraEmail\Core\Helper;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 10.09.19
 * Time: 10:13
 * Class Webmail
 */
class Webmail extends AbstractClientController
{
    use WhmcsParams;

    /**
     * @return \ModulesGarden\Servers\ZimbraEmail\Core\Http\JsonResponse
     */
    public function index()
    {
        $productManager = new ProductManager();
        $productManager->loadByHostingId($this->request->get('id'));
        if ($this->getWhmcsParamByKey('status') !== 'Active' || !$productManager->isControllerAccessible(ControllerEnums::WEBMAIL_PAGE))
        {
            return Helper\redirectByUrl(BuildUrlExtended::getProvisioningUrl('',false,false));
        }

        $link = $productManager->get('login_link');

        if(!$link)
        {
            $link = $productManager->getClientUrl();
        }

        return Helper\redirectByUrl($link, []);
    }

    /**
     * @throws \Exception
     */
    public function clientSso()
    {
        /**
         *
         * product managet
         */
        $productManager = new ProductManager();
        $productManager->loadByHostingId($this->request->get('id'));

        /**
         *
         * load API
         */
        $api = (new ZimbraManager())
            ->getApiByServer($productManager->getHosting()->server)
            ->soap;

        /**
         *
         * load sso service
         */
        $sso = $api
            ->service()
            ->clientSingleSignOnToken()
            ->setFormData(['id' => $this->getRequestValue('actionElementId')]);

        /**
         *
         * run service
         */
        $result = $sso->run();

        /**
         *
         * throw error if without result
         */
        if(!$result)
        {
            throw new \Exception($sso->getError());
        }

        $url = $productManager->getClientUrl().'service/preauth';

        return Helper\redirectByUrl($url, ['authtoken' => $result['authToken']]);
    }
}