<?php
namespace ThurData\Servers\KerioEmail\App\UI\Client\EmailAccount\Providers;
use ThurData\Servers\KerioEmail\App\Enums\ProductParams;
use ThurData\Servers\KerioEmail\App\Enums\Size;
use ThurData\Servers\KerioEmail\App\Enums\Kerio;
use ThurData\Servers\KerioEmail\App\Helpers\KerioManager;
use ThurData\Servers\KerioEmail\App\Http\Admin\ProductConfiguration;
use ThurData\Servers\KerioEmail\App\Libs\Product\ProductManager;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Helpers\ServiceFactory;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Models\Account;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Models\ClassOfService;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Repository\ClassOfServices;
use ThurData\Servers\KerioEmail\App\Services\ConfigurableOptions\Strategy\Types\ClassOfServicesOptions;
use function ThurData\Servers\KerioEmail\Core\Helper\di;
use ThurData\Servers\KerioEmail\Core\Http\JsonResponse;
use ThurData\Servers\KerioEmail\Core\Models\Whmcs\Hosting;
use ThurData\Servers\KerioEmail\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ThurData\Servers\KerioEmail\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;
use ThurData\Servers\KerioEmail\Api\KerioWhmcs;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * Date: 10.09.19
 * Time: 13:06
 * Class AccountDataProvider
 */
class AccountDataProvider extends BaseDataProvider
{

    public function read()
    {
        /**
         * hosting id
         */
        $hid = $this->request->get('id');
        $hosting = Hosting::where('id', $hid)->first();
        $this->data['domain'] = $this->getWhmcsParamByKey('customfields')['maildomain'];
        $this->data['quota'] = 0;
        $lang = di('lang');
        $this->availableValues['status'] = [
            Kerio::ACC_STATUS_ACTIVE        => $lang->absoluteT('kerio','account','status','active'),
            Kerio::ACC_STATUS_CLOSED        => $lang->absoluteT('kerio','account','status','closed'),
        ];
        $this->availableValues['unit'] = [
            'MegaBytes' => 'MB',
            'GigaBytes' => 'GB',
        ];

    }

    public function create()
    {
        /**
         * hosting id
         */
        $hid = $this->request->get('id');

        $fieldToProtection = ['firstname', 'lastname', 'display_name', 'office', 'title', 'department', 'profession'];

        foreach ($this->formData as $field => &$value)
        {
            $value = in_array($field, $fieldToProtection) ? htmlentities($value) : $value;
        }

        /**
         * product manager allow to check product settings
         */
        $productManager = new ProductManager();
        $productManager->loadByHostingId($hid);

        $maildomain = $this->getWhmcsParamByKey('customfields')['maildomain'];
        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
            $domainID = $api->getDomainId($maildomain);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }             
        if ($domainID === FALSE) {
            return "Error: Domain $maildomain not found";
        }
        $active = $this->formData['status'] === 'active' ? TRUE : FALSE;
        try {
            $userID = $api->createUser($domainID, $this->formData['username'], $this->formData['password'], $active)['result'][0]['id'];
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }             
        $account['fullName'] = $this->formData['display_name'];
        if ($this->formData['quota'] > 0) {
            $account['diskSizeLimit']['isActive'] = TRUE;
            $account['diskSizeLimit']['limit']['value'] = intval($this->formData['quota']);
            $account['diskSizeLimit']['limit']['units'] = $this->formData['unit'];
        }
        try {
            $result1 = $api->modifyUser($userID, $account);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $fields['firstName'] = $this->formData['firstname'];
        $fields['surName'] = $this->formData['lastname'];
        $fields['commonName'] = $this->formData['display_name'];
        $fields['postalAddressWork']['extendedAddress'] = $this->formData['office'];
        $fields['titleBefore'] = $this->formData['title'];
        $fields['phoneNumberWorkVoice'] = $this->formData['work_phone'];
        $fields['phoneNumberMobile'] = $this->formData['mobile_phone'];
        $fields['departmentName'] = $this->formData['department'];
        $fields['profession'] = $this->formData['profession'];
        try {
            $result2 = $api->setAddress($userID, $fields);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }

        return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAccountHasBeenAdded')->setStatusSuccess();

    }

    public function updateStatus()
    {


    }

    public function update()
    {
        /**
         * hosting id
         */
        $hid = $this->request->get('id');

        /**
         * product manager allow to check product settings
         */
        $productManager = new ProductManager();
        $productManager->loadByHostingId($hid);

        $status['isEnabled'] = $this->formData['status'] === 'active' ? TRUE : FALSE;
        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }

        /**
         * run service for each id
         */
        foreach($this->request->get('massActions') as $id)
        {
            try {
                $result = $api->modifyUser($id, $status);
            } catch (KerioApiException $error) {
                logModuleCall(
                    'kerioEmail',
                    __FUNCTION__,
                    $error,
                    'Debug Error',
                    $error->getMessage()
                );
                return ['error' => $error->getMessage()];
            }
        }
        $api->logout();

        /**
         * return success
         */
        return (new HtmlDataJsonResponse())->setMessageAndTranslate('massEmailAccountStatusHasBeenUpdated')->setStatusSuccess();
    }

    /**
     *
     * read data per cos_name
     */
    protected function readCosParams()
    {
        $hid = $this->request->get('id');


        /**
         *
         * load product manager
         */
        $productManager = new ProductManager();
        $productManager->loadByHostingId($hid);

        /**
         *
         * check if class of services should be selectable
         */
        if($productManager->get('cos_name') === ClassOfServices::CLASS_OF_SERVICE_QUOTA)
        {
            /**
             *
             * get soap create domain  service
             */
            $api =(new KerioManager())
                ->getApiByHosting($hid)
                ->soap;

            /**
             *
             * get cos from API
             */
            $classOfServices = $api->repository()->cos->all();

            /**
             *
             * load configurable options coses
             */
            $supportedCos = $productManager->getSettingCos();

            /**
             *
             * add COS to array
             */
            $configoptions = $this->getFilteredCosConfigurableOptions();

            foreach($classOfServices as $cos)
            {
                /**
                 *
                 *
                 * skip COS which is not used in configurable options
                 */
                if(!($supportedCos && array_key_exists($cos->getId(), $supportedCos)))
                {
                    continue;
                }

                /**
                 * 1. check if config opts are available
                 * 2. skip if class of services doesnt exists in config option list
                 */
                if($configoptions && !array_key_exists('cosQuota_'.$cos->getId(), $configoptions))
                {
                    continue;
                }

                /**
                 * 1. check if config opts are available
                 * 2. skip not purchased as CO
                 */
                if ($configoptions && $configoptions['cosQuota_'.$cos->getId()] == 0)
                {
                    continue;
                }

                /**
                 * 1. check if config opts are not available
                 * 2. skip if quantity === 0
                 */
                if(!$configoptions && $supportedCos[$cos->getId()] == 0)
                {
                    continue;
                }

                /* @var $cos ClassOfService*/
                $this->availableValues['cosId'][$cos->getId()] = $cos->getMbMailQuote().' MB';
            }


            return $this;
        }


        /**
         *
         * check if class of service is choosen by config opt
         */
        if($productManager->get('cos_name') === ClassOfServices::KERIO_CONFIG_OPTIONS)
        {

            $this->data['cosId'] = key($productManager->getSettingCos());
            return $this;
        }

        /**
         *
         * if cos_name is dedicated (loaded from API)
         */
        if($productManager->get('cos_name') !== ClassOfServices::CUSTOM_KERIO)
        {
            /**
             * if dedicated class of service has been selected
             */
            $this->data['cosId'] = $productManager->get('cos_name');
            return $this;
        }

        return $this;
    }

    /**
     * @return bool|mixed
     */
    protected function getFilteredCosConfigurableOptions()
    {
        $configoptions = $this->getWhmcsParamByKey('configoptions');

        foreach($configoptions as $key => $value)
        {
            if(strpos($key, ClassOfServicesOptions::COS_CONFIG_OPT_PREFIX) === false)
            {
                unset($configoptions[$key]);
            }

        }

        return $configoptions;
    }
}