<?php

namespace ModulesGarden\Servers\ZimbraEmail\App\UI\Client\EmailAccount\Pages;

use ModulesGarden\Servers\ZimbraEmail\App\Helpers\BuildUrlExtended;
use ModulesGarden\Servers\ZimbraEmail\App\Helpers\ZimbraManager;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Product\ProductManager;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Connection;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Helpers\AccountHelper;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Models\Account;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Repository\ClassOfServices;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Filters\EmailAccounts\FilterByCosId;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Admin\Custom\Fields\EnabledField;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\EmailAccount\Buttons\AddAccountButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\EmailAccount\Buttons\ChangePasswordButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\EmailAccount\Buttons\ChangeStatusButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\EmailAccount\Buttons\DeleteAccountButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\EmailAccount\Buttons\EditAccountButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\EmailAccount\Buttons\LoginToPanelButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\EmailAccount\Buttons\MassChangeStatusButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\EmailAccount\Buttons\MassDeleteAccountButton;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Client\EmailAccount\Buttons\SpanDropdownButton;
use function ModulesGarden\Servers\ZimbraEmail\Core\Helper\di;
use ModulesGarden\Servers\ZimbraEmail\Core\Models\Whmcs\Hosting;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdown;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Widget\DataTable\Column;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Widget\DataTable\DataProviders\DataProvider;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Widget\DataTable\DataProviders\Providers\ArrayDataProvider;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Widget\DataTable\DataTable;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 10.09.19
 * Time: 10:51
 * Class Accounts
 */
class Accounts extends DataTable implements ClientArea
{

    /**
     * labels for statuses
     */
    const STATUS_LABEL = [
        'active'        => 'success',
        'locked'        => 'default',
        'maintenance'   => 'warning',
        'closed'        =>'default',
        'lockout'       => 'info',
        'pending'       => 'warning',
        '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('date_created'))
                ->setOrderable()
                ->setSearchable(true))
            ->addColumn((new Column('date_created'))
                ->setOrderable()
                ->setSearchable(true))
            ->addColumn((new Column('last_login'))
                ->setOrderable()
                ->setSearchable(true))
            ->addColumn((new Column('quota'))
                ->setOrderable()
                ->setSearchable(true, Column::TYPE_INT))
            ->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('zimbra','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()
    {
        $productManager = new ProductManager();
        $productManager->loadByHostingId($this->getRequestValue('id'));

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

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


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

        $mailBox = new LoginToPanelButton();
        $mailBox
            ->setRawUrl(BuildUrlExtended::getProvisioningUrl('webmail', true, true,'clientSso'))
            ->setRedirectParams(['actionElementId' => 'true']);

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

        if ($productManager->get('ca_logInToMailboxButton') === 'on')
        {
            $actions->addButton($mailBox);
        }

        $this->addActionButton($actions);

    }

    /**
     * load data
     */
    public function loadData()
    {
        /**
         * load hosting
         */
        $hosting = Hosting::where('id', $this->getRequestValue('id'))->first();


        $accounts = (new ZimbraManager())
            ->getApiByServer($hosting->server)
            ->soap
            ->repository()
            ->accounts
            ->getByDomainName($hosting->domain);

        $productManager = new ProductManager();
        $productManager->loadByHostingId($hosting->id);

        if($productManager->get('filterAccountsByCOS') === 'on' && $productManager->get('cos_name') !=  ClassOfServices::CUSTOM_ZIMBRA)
        {
            $availableCoses = is_array($productManager->getSettingCos()) ? array_keys($productManager->getSettingCos()) : [$productManager->getSettingCos()];
            $filter = new FilterByCosId();
            $filter->setAvailableCoses($availableCoses);
            $accounts = $filter->filter($accounts);
        }

        /**
         * format model to array
         */
        $data = [];
        foreach ($accounts as $account)
        {
            /* @var $account Account */

            $accountArray = [
                'id'           => $account->getId(),
                'mailbox'      => $account->getName(),
                'date_created' => AccountHelper::getFormattedData($account->getDataResourceA('zimbraCreateTimestamp')),
                'last_login'   => AccountHelper::getFormattedData($account->getDataResourceA('zimbraLastLogonTimestamp'), 'd/m/Y H:i'),
                'quota'        => AccountHelper::getQuotaAsMb($account->getDataResourceA('zimbraMailQuota')),
                'status'       => $account->getDataResourceA('zimbraAccountStatus'),

            ];

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

        $this->setDataProvider($dataProv);
    }

}