<?php

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

use ThurData\Servers\KerioEmail\App\Enums\Response;
use ThurData\Servers\KerioEmail\App\Helpers\KerioManager;
use ThurData\Servers\KerioEmail\App\Libs\Product\ProductManager;
use ThurData\Servers\KerioEmail\App\Traits\ExtensionsCheckerTrait;
use ThurData\Servers\KerioEmail\Core\App\Controllers\Instances\AddonController;
use ThurData\Servers\KerioEmail\App\Models\ProductConfiguration;
use ThurData\Servers\KerioEmail\Api\KerioWhmcs;
use ThurData\Servers\KerioEmail\Core\Helper\ConfigOptionsHelper;
use ThurData\Servers\KerioEmail\Core\Helper\UpdateLimit;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * Date: 09.09.19
 * Time: 15:15
 * Class ChangePackage
 */
class ChangePackage extends AddonController
{
    use ExtensionsCheckerTrait;

    /**
     * @param null $params
     * @return string|void
     */
    public function execute($params = null)
    {
        try{

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

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

    }

    /**
     * @param null $params
     * @return string
     */
    protected function kerioRunService($params = null)
    {

        $productManager = new ProductManager();
        $configOption = new ConfigOptionsHelper;
        $updateLimit = new UpdateLimit;
        $productManager->loadById($params['pid']);
        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($params['serverhostname'], $params['serverusername'], $params['serverpassword']);
            $domainID = $api->getDomainId($params['domain']);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }             
        if ($domainID === FALSE) {
            return "Error: Domain $domain not found";
        }

        $acc_base = $productManager->get('acc_base') ? $productManager->get('acc_base') : 0;
        $acc_limit = $productManager->get('acc_limit') ? $productManager->get('acc_limit') : 0;
        $acc_add = $params['configoptions']['acc_add'] + $params['configoptions']['acc_new'];
        $acc_new = 0;
        // update
        $acc_addObj = $configOption->getConfigurableOption($params['serviceid'], 'acc_add');
        if(isset($acc_addObj->id)) {
            $configOption->updateConfigurableOption($acc_addObj->id, ['qty' => $acc_add]);
        }
        $acc_newObj = $configOption->getConfigurableOption($params['serviceid'], 'acc_new');
        if(isset($acc_newObj->id)) {
            $configOption->updateConfigurableOption($acc_newObj->id, ['qty' => $acc_new]);
        }
        $accounts = $acc_base + $acc_add;
        // set user count attributes
        if ($acc_limit > 0) {
            $attr['userMaxCountCheckbox'] = TRUE;
            if ($accounts > $acc_limit) {
                $accounts = $acc_limit;
            }
            $attr['userMaxCount'] = $accounts;
        } else {
            $attr['userMaxCountCheckbox'] = FALSE;
        }

        $domainBaseSize = $productManager->get('domainBaseSize') ? $productManager->get('domainBaseSize') : 0;
        $domainMaxSize = $productManager->get('domainMaxSize') ? $productManager->get('domainMaxSize') : 0;
        $domainAddSize = $params['configoptions']['domainAddSize'] + $params['configoptions']['domainNewSize'];
        $domainNewSize = 0;
        // update
        $domainAddSizeObj = $configOption->getConfigurableOption($params['serviceid'], 'domainAddSize');
        if(isset($domainAddSizeObj->id)) {
            $configOption->updateConfigurableOption($domainAddSizeObj->id, ['qty' => $domainAddSize]);
        }
        $domainNewSizeObj = $configOption->getConfigurableOption($params['serviceid'], 'domainNewSize');
        if(isset($domainNewSizeObj->id)) {
            $configOption->updateConfigurableOption($domainNewSizeObj->id, ['qty' => $domainNewSize]);
        }
        $domainSize = $domainBaseSize + $domainAddSize;
        // set domain size attributes
        if ($domainMaxSize > 0) {
            $attr['domainQuota']['diskSizeLimit']['isActive'] = TRUE;
            if ($domainSize > $domainMaxSize) {
                $domainSize = $domainMaxSize;
            }
            $attr['domainQuota']['diskSizeLimit']['limit']['value'] = $domainSize;
            $attr['domainQuota']['diskSizeLimit']['limit']['units'] = 'GigaBytes';
        } else {
            $attr['domainQuota']['diskSizeLimit']['isActive'] = FALSE;
        }
        $attr['domainQuota']['email'] = $params['clientsdetails']['email'];
        try {
            $result = $api->modifyDomain($domainID, $attr);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }             
        $api->logout();
        $updateLimit->updateDiskLimit($params['serviceid'], $domainSize * 1024);
        $updateLimit->updateBWLimit($params['serviceid'], $accounts);

        return Response::SUCCESS;
    }
}