<?php

namespace ThurData\Servers\KerioEmail\App\UI\Client\EmailAccount\Pages;

use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Helpers\AccountHelper;
use ThurData\Servers\KerioEmail\App\UI\Admin\Custom\Fields\EnabledField;
use ThurData\Servers\KerioEmail\App\UI\Client\EmailAccount\Buttons\AddAccountButton;
use ThurData\Servers\KerioEmail\App\UI\Client\EmailAccount\Buttons\ChangePasswordButton;
use ThurData\Servers\KerioEmail\App\UI\Client\EmailAccount\Buttons\ChangeStatusButton;
use ThurData\Servers\KerioEmail\App\UI\Client\EmailAccount\Buttons\DeleteAccountButton;
use ThurData\Servers\KerioEmail\App\UI\Client\EmailAccount\Buttons\EditAccountButton;
use ThurData\Servers\KerioEmail\App\UI\Client\EmailAccount\Buttons\MassChangeStatusButton;
use ThurData\Servers\KerioEmail\App\UI\Client\EmailAccount\Buttons\MassDeleteAccountButton;
use ThurData\Servers\KerioEmail\App\UI\Client\EmailAccount\Buttons\SpanDropdownButton;
use function ThurData\Servers\KerioEmail\Core\Helper\di;
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\Interfaces\ClientArea;
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: 10.09.19
 * Time: 10:51
 * Class Accounts
 */
class Accounts extends DataTable implements ClientArea
{

    /**
     * labels for statuses
     */
    const STATUS_LABEL = [
        'active'        => 'success',
        'closed'        => 'default',
        'default'       => 'default'
    ];

    protected $id    = 'accounts';
    protected $name  = 'accounts';
    protected $title = null;

    /**
     * load columns
     */
    protected function loadHtml()
    {
        $this
            ->addColumn((new Column('mailbox'))
                ->setOrderable(DataProvider::SORT_ASC)
                ->setSearchable(true, Column::TYPE_STRING))
            ->addColumn((new Column('last_login'))
                ->setOrderable()
                ->setSearchable(true))
            ->addColumn((new Column('size'))
                ->setOrderable()
                ->setSearchable(true, Column::TYPE_INT))
            ->addColumn((new Column('quota'))
                ->setOrderable()
                ->setSearchable(true, Column::TYPE_INT))
            ->addColumn((new Column('forward'))
                ->setOrderable()
                ->setSearchable(true, Column::TYPE_STRING))
            ->addColumn((new Column('status'))
                ->setOrderable()
                ->setSearchable(true));
    }

    /**
     * @param $key
     * @param $row
     * @return mixed
     */
    public function replaceFieldStatus($key, $row)
    {
        $status = self::STATUS_LABEL[$row[$key]] ? self::STATUS_LABEL[$row[$key]] : self::STATUS_LABEL['default'];
        $label = di('lang')->absoluteT('kerio','account','status',$row[$key]);

        $field = new EnabledField();
        $field->setRawType($status);
        $field->setRawTitle($label);

        return $field->getHtml();
    }

    /**
     * @param $key
     * @param $row
     * @return mixed
     */
    public function replaceFieldLast_login($key, $row)
    {
        return $row[$key] ? $row[$key] : '-';
    }

    /**
     * load buttons
     */
    public function initContent()
    {

        $this->addMassActionButton(new MassChangeStatusButton());
        $this->addMassActionButton(new MassDeleteAccountButton());

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


        $this->addActionButton(new EditAccountButton());
        $this->addActionButton(new DeleteAccountButton());

        $actions = new SpanDropdownButton('actions');
        $actions->addButton(new ChangeStatusButton());
        $actions->addButton(new ChangePasswordButton());

        $this->addActionButton($actions);

    }

    /**
     * load data
     */
    public function loadData()
    {
        $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()];
        }
        $fields = array(
            "id",
            "loginName",
            "isEnabled",
            "diskSizeLimit",
            "consumedSize",
            "lastLoginInfo",
            "emailForwarding");
        try {
            $accounts = $api->getUsers($fields,$domainID);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();

        $data = [];
        foreach ($accounts as $account)
        {

            $accountArray = [
                'id'           => $account['id'],
                'mailbox'      => $account['loginName'] . '@' . $domain,
                'last_login'   => AccountHelper::getFormattedData($account['lastLoginInfo']['dateTime'], 'd/m/Y H:i'),
                'size'         => AccountHelper::getQuotaAsMb($account['consumedSize']['value'],$account['consumedSize']['units']),
                'quota'        => $account['diskSizeLimit']['isActive'] ?  AccountHelper::getQuotaAsMb($account['diskSizeLimit']['limit']['value'],$account['diskSizeLimit']['limit']['units']) : '∞',
                'forward'      => $account['emailForwarding']['emailAddresses'][0],
                'status'       => $account['isEnabled'] ? 'active' : 'default',

            ];

            $data[] = $accountArray;
        }
        $dataProv = new ArrayDataProvider();
        $dataProv->setDefaultSorting('mailbox', 'ASC')->setData($data);

        $this->setDataProvider($dataProv);
    }

}