<?php

namespace ModulesGarden\Servers\OpenXchange\App\Libs;

use Exception;

class RestApi extends Api
{
    public function __construct($params)
    {
        $this->params = $params;
        $this->setProductSettings();
        $this->setCredentials();
    }

    public function __call($name, $vars)
    {
        $this->endpoint = null;
        $this->requestMethod = null;
        $this->postfields = [];
        call_user_func_array([$this, $name], $vars);
        return (new RestCurl($this))->request()->response();
    }

    private function createForwarder($recipient, $alias)
    {
        $this->endpoint = "/cloudapi/v2/mail/forwards?name={$this->params['customfields']['context_name']}";
        $this->requestMethod = 'POST';
        $this->postfields = [
            'address'   => $alias,
            'forwardTo' => [$recipient]
        ];
    }

    private function updateForwarder($recipient, $alias)
    {
        $this->endpoint = "/cloudapi/v2/mail/forwards?name={$this->params['customfields']['context_name']}";
        $this->requestMethod = 'PUT';
        $this->postfields = [
            'address'   => $alias,
            'forwardTo' => [$recipient]
        ];
    }

    private function deleteForwarder($alias)
    {
        $this->endpoint = "/cloudapi/v2/mail/forwards/{$alias}?name={$this->params['customfields']['context_name']}";
        $this->requestMethod = 'DELETE';
    }

    private function getForwarders()
    {
        $this->endpoint = "/cloudapi/v2/mail/forwards?name={$this->params['customfields']['context_name']}";
        $this->requestMethod = 'GET';
    }

    private function getForwarder($alias)
    {
        $this->endpoint = "/cloudapi/v2/mail/forwards?name={$this->params['customfields']['context_name']}";
        $this->requestMethod = 'GET';
        $this->postfields = [
            'address'   => $alias
        ];
    }
    
    private function listContexts()
    {
        $this->endpoint      = "/cloudapi/v2/contexts";
        $this->requestMethod = 'GET';
    }
    
    private function createContext()
    {
        //get domain and convert to punnycode
        $domain      = \WHMCS\Domains\Idna::toPunycode($this->params['domain']);
        $contextName = $this->username . "_" . str_replace('=', '', base64_encode($domain));

        $this->endpoint      = "/cloudapi/v2/contexts";
        $this->requestMethod = 'POST';
        $this->postfields    = [
            //'name'          => $this->username . "_" . uniqid(),
            'name'          => $contextName,
            'maxQuota'      => '10240',
            'adminPassword' => htmlspecialchars_decode($this->params['OxAdminPassword']),
            'adminLogin'    => 'admin-' . $domain,
            'theme'         => ThemeHelper::config()
        ];
    }
    
    private function getContextInfo()
    {
        $this->endpoint      = "/cloudapi/v2/contexts/".$this->params['customfields']['context_name'];
        $this->requestMethod = 'GET';
    }
    
    private function listAllUsers()
    {
        $this->endpoint      = "/cloudapi/v2/users?name=".$this->params['customfields']['context_name'];
        $this->requestMethod = 'GET';
    }
    
    private function terminateContext()
    {
        $this->endpoint      = "/cloudapi/v2/contexts/".$this->params['customfields']['context_name'];
        $this->requestMethod = 'DELETE';
    }
    
    private function changeUser($name, $classOfService)
    {
        $this->endpoint      = "/cloudapi/v2/users/".$name.'?name='.$this->params['customfields']['context_name'];
        $this->requestMethod = 'PUT';
        $this->postfields    = [
            'classOfService' => [$classOfService]
        ];
    }
    
    private function changePasswordAccess($name, $enableChange)
    {
        $this->endpoint      = "/cloudapi/v2/users/".$name.'/permissions'.'?name='.$this->params['customfields']['context_name'];
        $this->requestMethod = 'PUT';
        
        if ($enableChange)
        {
            $this->postfields = [
                'editPassword' => true
            ];
        }
        else
        {
            $this->postfields = [
                'editPassword' => false
            ];
        }
    }
    
    private function changeQuota()
    {
        $this->endpoint      = "/cloudapi/v2/contexts/".$this->params['customfields']['context_name'];
        $this->requestMethod = 'PUT';
        $this->postfields    = [
            'maxQuota' => '10240'
        ];
    }
    
    private function getUserPermissions($name)
    {
        $this->endpoint      = "/cloudapi/v2/users/".$name.'/permissions'.'?name='.$this->params['customfields']['context_name'];
        $this->requestMethod = 'GET';
    }
    
    private function suspendUser($name)
    {
        $this->endpoint      = "/cloudapi/v2/users/".$name.'/permissions'.'?name='.$this->params['customfields']['context_name'];
        $this->requestMethod = 'PUT';
        $this->postfields    = [
            'send'      => false,
            'receive'   => false,
            'maillogin' => false,
            'weblogin'  => false
        ];
    }

    private function unsuspendUser($name)
    {
        $this->endpoint      = "/cloudapi/v2/users/".$name.'/permissions'.'?name='.$this->params['customfields']['context_name'];
        $this->requestMethod = 'PUT';
        $this->postfields    = [
            'send'      => true,
            'receive'   => true,
            'maillogin' => true,
            'weblogin'  => true
        ];
    }

    private function createUser($parameters)
    {
        $this->endpoint      = "/cloudapi/v2/users?name=".$this->params['customfields']['context_name'];
        $this->requestMethod = 'POST';
        $this->postfields    = [
            'name'         => $parameters['name'],
            'password'     => htmlspecialchars_decode($parameters['password']),
            'givenName'    => $parameters['given_name'],
            'surName'      => $parameters['sur_name'],
            'mail'         => $parameters['primaryEmail'],
            'displayName'  => $parameters['display_name'],
            'unifiedQuota' => $parameters['quota'],
            'language'     => $parameters['language'],
            'timezone'     => $parameters['timezone'],
        ];

        if (isset($parameters['emailType']))
        {
            $this->postfields['classOfService'] = $parameters['emailType'];
        }

        if (isset($parameters['editPasswordPerm']))
        {
            $permissionsObject                   = new \stdClass();
            $permissionsObject->editPassword     = $parameters['editPasswordPerm'];
            $this->postfields['userPermissions'] = $permissionsObject;
        }
    }

    private function deleteUser($name)
    {
        $this->endpoint      = "/cloudapi/v2/users/".$name.'?name='.$this->params['customfields']['context_name'];
        $this->requestMethod = 'DELETE';
    }

    private function getUserData($name)
    {
        $this->endpoint      = "/cloudapi/v2/users/".$name.'?name='.$this->params['customfields']['context_name'];
        $this->requestMethod = 'GET';
    }

    private function updateUser($name, $parameters)
    {
        $this->endpoint      = "/cloudapi/v2/users/".$name.'?name='.$this->params['customfields']['context_name'];
        $this->requestMethod = 'PUT';
        $this->postfields    = [
            //'name'        => $parameters['name'],
            'givenName'    => $parameters['given_name'],
            'surName'      => $parameters['sur_name'],
            'mail'         => $parameters['primaryEmail'],
            //'displayName' => $parameters['display_name'],
            'unifiedQuota' => $parameters['quota'],
            'language'     => $parameters['language'],
            'timezone'     => $parameters['timezone']
        ];

        if ($parameters['resetPassword'] && $parameters['resetPassword'] != '')
        {
            $this->postfields['password'] = htmlspecialchars_decode($parameters['resetPassword']);
        }

        if (isset($parameters['emailType']))
        {
            $this->postfields['classOfService'] = $parameters['emailType'];
        }

        if (isset($parameters['editPasswordPerm']))
        {
            $permissionsObject                   = new \stdClass();
            $permissionsObject->editPassword     = $parameters['editPasswordPerm'];
            $this->postfields['userPermissions'] = $permissionsObject;
        }
    }

    private function updateUserUnifiedQuota($name, $parameters)
    {
        $this->endpoint      = "/cloudapi/v2/users/".$name.'?name='.$this->params['customfields']['context_name'];
        $this->requestMethod = 'PUT';
        $this->postfields    = [
            'unifiedQuota' => $parameters['unifiedQuota']
        ];
    }

    private function addAliases($name, $aliases)
    {
        $this->endpoint      = "/cloudapi/v2/users/".$name.'?name='.$this->params['customfields']['context_name'];
        $this->requestMethod = 'PUT';
        $this->postfields    = [
            'aliases' => $aliases
        ];
    }

    private function listDomainCatchall()
    {
        $this->endpoint      = "/cloudapi/v2/mail/catchall?name=".$this->params['customfields']['context_name'];
        $this->requestMethod = 'GET';
    }

    private function createDomainCatchall($login)
    {
        //get domain and convert to punnycode
        $domain = $domain = \WHMCS\Domains\Idna::toPunycode($this->params['domain']);

        $this->endpoint      = "/cloudapi/v2/mail/catchall?name=".$this->params['customfields']['context_name'];
        $this->requestMethod = 'POST';
        $this->postfields    = [
            'domain' => $domain,
            'login'  => $login
        ];
    }

    private function deleteDomainCatchall($login)
    {
        //get domain and convert to punnycode
        $domain = $domain = \WHMCS\Domains\Idna::toPunycode($this->params['domain']);

        $this->endpoint      = "/cloudapi/v2/mail/catchall/domain/".$domain."/login/".$login."?name=".$this->params['customfields']['context_name'];
        $this->requestMethod = 'DELETE';
    }
}
