<?php
namespace ThurData\Servers\KerioEmail\App\UI\Client\EmailAlias\Providers;
use ThurData\Servers\KerioEmail\App\Helpers\KerioManager;
use ThurData\Servers\KerioEmail\App\Libs\Product\ProductManager;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Models\AccountAlias;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Repository;
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: 18.09.19
 * Time: 11:50
 * Class AddEmailAliasDataProvider
 */
class AddEmailAliasDataProvider extends BaseDataProvider
{

    public function read()
    {
        /**
         * hosting id
         */
        $hid = $this->getRequestValue('id');

        /**
         * hosting model
         */
        $hosting = Hosting::where('id', $hid)->first();

        /**
         * hosting domain
         */
        $this->data['domain'] = $hosting->domain;
        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
            $domains = $api->getDomains(['id','name']);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        foreach($domains as $maildomain) {
            if(($maildomain['name']) === $this->data['domain']){ 
                $this->maildomainID = $maildomain['id'];
                $this->maildomain = $maildomain['name'];
            }
        }
        $productManager = new ProductManager();
        $productManager->loadByHostingId($hosting->id);
        $fields = array(
            "id",
            "loginName"
        );
        $accounts = $api->getUsers($fields,$this->maildomainID);
        $api->logout();

        /**
         * available accounts
         */
        foreach($accounts as $account)
        {
            $this->availableValues['mailbox'][$account['loginName']] = $account['loginName'] . '@' . $this->maildomain;
        }

    }

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

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

        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
            $domains = $api->getDomains(['id','name']);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        foreach($domains as $maildomain) {
            if(($maildomain['name']) === $this->formData['domain']){ 
                $this->maildomainID = $maildomain['id'];
                $this->maildomain = $maildomain['name'];
            }
        }
        try {
            $result = $api->createAlias($this->maildomainID, $this->formData['aliasName'], $this->formData['mailbox'] . '@' . $this->maildomain);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }

        return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAliasHasBeenCreated')->setStatusSuccess();
    }

    public function update()
    {
        // TODO: Implement update() method.
    }
}