<?php
namespace ThurData\Servers\KerioEmail\App\UI\Client\DistributionList\Pages;
use ThurData\Servers\KerioEmail\App\UI\Client\DistributionList\Buttons\AddListButton;
use ThurData\Servers\KerioEmail\App\UI\Client\DistributionList\Buttons\DeleteListButton;
use ThurData\Servers\KerioEmail\App\UI\Client\DistributionList\Buttons\EditListButton;
use ThurData\Servers\KerioEmail\App\UI\Client\DistributionList\Buttons\MassDeleteListButton;
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:28
 * Class Lists
 */
class Lists extends DataTable implements ClientArea
{
    protected $id    = 'lists';
    protected $name  = 'lists';
    protected $title = null;

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

    public function initContent()
    {
        $this->addMassActionButton(new MassDeleteListButton());
        $this->addButton(new AddListButton());
        $this->addActionButton(new EditListButton());
        $this->addActionButton(new DeleteListButton());
    }

    public function loadData()
    {
        $domain = $this->getWhmcsParamByKey('domain');
        $fields = array(
            "id",
            "name",
            "description");

        $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 {
            $lists = $api->getMailingLists($fields,$domainID);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }

        $listQuery = array(
            "emailAddress",
            "kind"
        );

        $data = [];
        foreach($lists as $list)
        {
            /* @var $list  DistributionList */
            try {
                $members = $api->getMlUserList($listQuery, $list['id']);
            } catch (KerioApiException $error) {
                logModuleCall(
                    'kerioEmail',
                    __FUNCTION__,
                    $error,
                    'Debug Error',
                    $error->getMessage()
                );
            };
            $memberCount = 0;
            unset($moderator);
            foreach($members as $member) {
                if($member['kind'] === 'Member') {
                    $memberCount++;
                };
                if($member['kind'] === 'Moderator') {
                    $moderator = $member['emailAddress'];
                };
            }
            $tmp = [
                'id' => $list['id'],
                'email' => $list['name'] . '@' . $domain,
                'description' => $list['description'],
                'members' => $memberCount,
                'moderator' => $moderator
            ];

           $data[] = $tmp;
        }
        $api->logout();

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

        $this->setDataProvider($dataProv);
    }

}