<?php
namespace ThurData\Servers\KerioEmail\App\UI\Client\EmailAlias\Pages;

use ThurData\Servers\KerioEmail\App\UI\Client\EmailAlias\Buttons\AddEmailAliasButton;
use ThurData\Servers\KerioEmail\App\UI\Client\EmailAlias\Buttons\DeleteEmailAliasButton;
use ThurData\Servers\KerioEmail\App\UI\Client\EmailAlias\Buttons\MassDeleteEmailAliasButton;
use ThurData\Servers\KerioEmail\Core\UI\Interfaces\ClientArea;
use ThurData\Servers\KerioEmail\Core\UI\Widget\DataTable\Column;
use ThurData\Servers\KerioEmail\Core\UI\Widget\DataTable\DataProviders\DataProvider;
use ThurData\Servers\KerioEmail\Core\UI\Widget\DataTable\DataProviders\Providers\ArrayDataProvider;
use ThurData\Servers\KerioEmail\Core\UI\Widget\DataTable\DataTable;
use ThurData\Servers\KerioEmail\Api\KerioWhmcs;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * Date: 18.09.19
 * Time: 11:46
 * Class Aliases
 */
class Aliases extends DataTable implements ClientArea
{
    protected $id    = 'emailAliases';
    protected $name  = 'emailAliases';
    protected $title = null;


    protected function loadHtml()
    {
        $this
            ->addColumn((new Column('email_alias'))
                ->setOrderable(DataProvider::SORT_ASC)
                ->setSearchable(true, Column::TYPE_STRING))
            ->addColumn((new Column('account'))
                ->setOrderable()
                ->setSearchable(true));
    }

    public function initContent()
    {
        $this->addMassActionButton(new MassDeleteEmailAliasButton());

        $addEmailAliasesButton = new AddEmailAliasButton();

        if($this->isCreateButtonDisabled())
        {
            $addEmailAliasesButton->addHtmlAttribute('disabled', true);
        }

        $this->addButton($addEmailAliasesButton);
        $this->addActionButton(new DeleteEmailAliasButton());
    }

    public function loadData()
    {
        $fields = array(
            "id",
            "name",
            "deliverTo");

        $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->getWhmcsParamByKey('domain')){ 
                $this->maildomainID = $maildomain['id'];
                $this->maildomain = $maildomain['name'];
            }
        }
        try {
            $aliases = $api->getAliases($fields,$this->maildomainID);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();

        /**
         * format model to array
         */
        $data = [];
        foreach ($aliases as $alias)
        {
            /* @var $alias AccountAlias */
            $tmp = [
                'id'            => $alias['id'],
                'email_alias'   => $alias['name'] . '@' . $this->maildomain,
                'account'       => $alias['deliverTo']
            ];

            $data[] = $tmp;
        }

        $dataProv = new ArrayDataProvider();
        $dataProv->setDefaultSorting('email_alias', 'ASC')->setData($data);

        $this->setDataProvider($dataProv);
    }

    /**
     *
     * check if add button should be disabled
     * @return bool
     */
    private function isCreateButtonDisabled()
    {
        $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($domain);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        try {
            $accCount = $api->countUser($domainID);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();

        if ($accCount > 0) {
            return FALSE;
        }
        return TRUE;
    }
}