<?php
namespace ThurData\Servers\KerioEmail\App\UI\Client\DistributionList\Pages;
use ThurData\Servers\KerioEmail\App\Helpers\KerioManager;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Models\DistributionList;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Repository;
use ThurData\Servers\KerioEmail\App\UI\Admin\Custom\Fields\EnabledField;
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 function ThurData\Servers\KerioEmail\Core\Helper\di;
use ThurData\Servers\KerioEmail\Core\Models\Whmcs\Hosting;
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()
    {
        /**
         * load hosting
         */
        $hosting = Hosting::where('id', $this->getRequestValue('id'))->first();
        $fields = array(
            "id",
            "name",
            "description");

        $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 {
            $lists = $api->getMailingLists($fields,$this->maildomainID);
        } 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;
            foreach($members as $member) {
                if($member['kind'] === 'Member') {
                    $memberCount++;
                };
                if($member['kind'] === 'Moderator') {
                    $moderator = $member['emailAddress'];
                };
            }
            $tmp = [
                'id' => $list['id'],
                'email' => $list['name'] . '@' . $this->maildomain,
                'description' => $list['description'],
                'members' => $memberCount,
                'moderator' => $moderator
            ];

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

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

        $this->setDataProvider($dataProv);
    }

}