<?php


namespace ModulesGarden\Servers\ZimbraEmail\App\Http\Actions;


use ModulesGarden\Servers\ZimbraEmail\App\Helpers\ZimbraManager;
use ModulesGarden\Servers\ZimbraEmail\Core\App\Controllers\Instances\AddonController;
use ModulesGarden\Servers\ZimbraEmail\Core\Models\Whmcs;

class UsageUpdate extends AddonController
{
    protected $moduleParams;

    public function execute($params = null)
    {
        $this->moduleParams = $params;

        $domains =(new ZimbraManager())
            ->getApiByServer($this->moduleParams['serverid'])
            ->soap
            ->repository()
            ->domains()
            ->getAll();
        foreach ($domains as $domain)
        {
            try
            {
                $domainName = $domain->getName();
                $usage = $this->getDomainUsage($domainName);
                $mailboxes = $usage['mailboxes'];
                $storage = $usage['usage'];
                $storage = $storage == 0 ? 0 : round($storage/1024/1024);
                $serverId =$params['serverid'];

                Whmcs\Hosting::where('server', $serverId)->where('domain', $domainName)->update(['bwusage' => $mailboxes]);
                Whmcs\Hosting::where('server', $serverId)->where('domain', $domainName)->update(['diskusage' => $storage]);

                usleep(5000);
            }
            catch (\Exception $ex)
            {

            }

        }
    }

    private function getDomainUsage($tenant)
    {
        $client = (new ZimbraManager())
            ->getApiByServer($this->moduleParams['serverid'])
            ->soap
            ->repository()
            ->accounts;
        $accounts = $client->getUsages($tenant);
        $mailboxes = count($client->getMailboxes($tenant));
        $totalUsage = 0;
        foreach ($accounts as $account)
        {
            $usage = $account->getUsed();
            $totalUsage += $usage;
        }

        return array('usage' => $totalUsage, 'mailboxes' => $mailboxes);
    }
}