<?php

namespace ThurData\Servers\KerioEmail\App\Http\Client;


use ThurData\Servers\KerioEmail\App\Enums\ControllerEnums;
use ThurData\Servers\KerioEmail\App\Enums\ProductParams;
use ThurData\Servers\KerioEmail\App\Helpers\BuildUrlExtended;
use ThurData\Servers\KerioEmail\App\Helpers\KerioManager;
use ThurData\Servers\KerioEmail\App\Libs\Product\ProductManager;
use ThurData\Servers\KerioEmail\Core\Http\AbstractClientController;
use ThurData\Servers\KerioEmail\Core\Models\Whmcs\Hosting;
use ThurData\Servers\KerioEmail\Core\UI\Traits\WhmcsParams;
use ThurData\Servers\KerioEmail\Core\Helper;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * Date: 10.09.19
 * Time: 10:13
 * Class Webmail
 */
class Webmail extends AbstractClientController
{
    use WhmcsParams;

    /**
     * @return \ThurData\Servers\KerioEmail\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 KerioManager())
            ->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']]);
    }
}