<?php
namespace ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailAlias\Providers;

use ModulesGarden\Servers\OpenXchange\App\Libs\RestApi;
use ModulesGarden\Servers\OpenXchange\App\Helpers\Helper;
use ModulesGarden\Servers\OpenXchange\Core\Models\Whmcs\Hosting;
use ModulesGarden\Servers\OpenXchange\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 18.09.19
 * Time: 11:50
 * Class AddEmailAliasDataProvider
 */
class AddEmailAliasDataProvider extends BaseDataProvider
{

    public function read()
    {
        $hid                  = $this->getRequestValue('id');
        $hosting              = Hosting::where('id', $hid)->first();
        $this->data['domain'] = $hosting->domain;

        $params  = Helper::moduleParams($_REQUEST['id']);
        $context = new RestApi($params);
        $users   = $context->listAllUsers();

        foreach($users as $user)
        {
            if($user->isContextAdmin == true)
            {
                continue;
            }

            $this->availableValues['mailbox'][$user->name] = Helper::convertEmailFromPunnycode($user->mail);
        }
    }

    public function create()
    {
        $hid     = $this->getRequestValue('id');
        $hosting = Hosting::where('id', $hid)->first();
        $params  = Helper::moduleParams($hid);
        
        $context = new RestApi($params);
        $user    = $context->getUserData($this->formData['mailbox']);

        $aliases        = (array)$user->aliases;
        $punyCodeDomain = \WHMCS\Domains\Idna::toPunycode($hosting->domain);

        if(in_array($this->formData['aliasName'].'@'.$punyCodeDomain, $aliases))
        {
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAliasExists')->setStatusError();
        }

        $limit = Helper::aliasesLimit($params);

        if($this->countAliases($params) >= $limit)
        {
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAliasesLimit')->setStatusError();
        }

        $aliases[] = $this->formData['aliasName'].'@'.$punyCodeDomain;

        try
        {
            $result = $context->addAliases($this->formData['mailbox'], $aliases);
        }
        catch (\Exception $ex)
        {
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAliasCreateError')->setStatusError();
        }
        
        if ($result == '')
        {
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAliasHasBeenCreated')->setStatusSuccess();
        }
        else
        {
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAliasCreateError')->setStatusError();
        }
    }

    public function update()
    {
        
    }

    public function countAliases($params)
    {
        $context = new RestApi($params);
        $users   = $context->listAllUsers();

        foreach($users as $key => &$user)
        {
            if($user->isContextAdmin == true)
            {
                unset($users[$key]);
                continue;
            }

            $aliases = $user->aliases;

            if (!is_array($aliases))
            {
                $aliases = [$aliases];

                if($aliases[0] === null)
                {
                    unset($aliases);
                }
            }

            foreach($aliases as $alias)
            {
                $accountArray = [
                    'user_id'      => $user->name,
                    'alias'        => $alias,
                    'primaryEmail' => $user->mail,
                    'aliases'      => $aliases,
                    'id'           => base64_encode(json_encode([
                        'user_id'      => $user->name,
                        'alias'        => $alias,
                        'primaryEmail' => $user->mail,
                        'aliases'      => $aliases,
                    ])),
                ];
    
                $data[] = $accountArray;
            }
        }

        if (!$data || is_null($data))
        {
            return count([]);
        }

        $totalAliases   = count($data);
        $totalMailboxes = count($users);
        $realAliases    = $totalAliases - $totalMailboxes;

        return $realAliases;
    }
}
