<?php
namespace ThurData\Servers\KerioEmail\App\UI\Client\Ressource\Providers;

use ThurData\Servers\KerioEmail\App\Enums\Kerio;
use function ThurData\Servers\KerioEmail\Core\Helper\di;
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 RessourceDataProvider
 */
class RessourceDataProvider extends BaseDataProvider
{

    public function read()
    {
        $this->data['domain'] = $this->getWhmcsParamByKey('domain');

        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
            $domainID = $api->getDomainId($this->getWhmcsParamByKey('domain'));
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $fields = array(
            "id",
            "loginName",
            "isEnabled");
        try {
            $users = $api->getUsers($fields,$domainID);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();

        foreach($users as $user) {
            if($user['isEnabled']){
                $this->availableValues['manager'][ $user['id']] = $user['loginName'] . '@' . $this->getWhmcsParamByKey('domain');
            }
        }

        $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['type'] = [
            Kerio::RES_TYPE_LOCATION        => $lang->absoluteT('kerio','ressource','type','location'),
            Kerio::RES_TYPE_EQUIPMENT       => $lang->absoluteT('kerio','ressource','type','equipment')
        ];
    }

    public function create()
    {
        $fieldToProtection = [
            'name',
            'status',
            'manager',
            'type',
            'description'
        ];

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

        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
            $domainID = $api->getDomainId($this->getWhmcsParamByKey('domain'));
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        try {
            $ressourceID = $api->createResouce($this->formData, $domainID);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();

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

    }

    public function updateStatus()
    {


    }

    public function update()
    {
        $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()];
        }

        $isEnabled = $this->formData['status'] === Kerio::ACC_STATUS_ACTIVE ? true : false;

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