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

use ThurData\Servers\KerioEmail\App\UI\Client\DomainAlias\Buttons\AddDomainAliasButton;
use ThurData\Servers\KerioEmail\App\UI\Client\DomainAlias\Buttons\DeleteDomainAliasButton;
use ThurData\Servers\KerioEmail\App\UI\Client\DomainAlias\Buttons\MassDeleteDomainAliasButton;
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: 13:37
 * Class DomainAliases
 */
class DomainAliases extends DataTable implements ClientArea
{
    protected $id    = 'lists';
    protected $name  = 'lists';
    protected $title = null;

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

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

        $this->addButton(new AddDomainAliasButton());

        $this->addActionButton(new DeleteDomainAliasButton());
    }

    public function loadData()
    {

        $maildomain = $this->getWhmcsParamByKey('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','aliasList']);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        foreach($domains as $domain) {
            if(($domain['name']) === $maildomain){ 
                $aliasList = $domain['aliasList'];
            }
        }

        /**
         *
         * prepare new array
         */
        $data = [];

        /**
         * parse aliases
         */
        foreach ($aliasList as $alias)
        {
            /* @var $alias Alias */
            $tmp = [
                'id'    => $alias,
                'name'  => $alias,
            ];

            $data[] = $tmp;
        }

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

        $this->setDataProvider($dataProv);

    }
}