<?php

namespace MGModule\DNSManager2;
use MGModule\DNSManager2 as main;
use MGModule\DNSManager2\mgLibs\custom\manager\GlobalSettingHelper;
use MGModule\DNSManager2\models\custom\globalsetting\GlobalSettingEnum;
use MGModule\DNSManager2\mgLibs\custom\dns\exceptions\DNSSubmoduleException;
use MGModule\DNSManager2\mgLibs\custom\dns\SubmoduleExceptionCodes;
use MGModule\DNSManager2\mgLibs\custom\AjaxResponse;
use MGModule\DNSManager2\mgLibs\lang;
use MGModule\DNSManager2\mgLibs\custom\helpers\HTML5Pattern;
/**
 * Description of Addon
 *
 * @author Michal Czech <michael@modulesgarden.com>
 */
class addon extends main\mgLibs\process\abstractMainDriver{
    /**
     * Load Addon WHMCS Configuration
     * 
     * 
     */
    function loadAddonConfiguration(){
       $result = mgLibs\MySQL\query::select(
                array(
                        'setting'
                        ,'value'
                    )
                , 'tbladdonmodules'
                ,array(
                    'module'    => $this->configuration()->systemName
                )
        );

        while($row = $result->fetch())
        {
            $this->configuration()->{$row['setting']} = $row['value'];
        }
    }
    
    /**
     * Return Tempalates Path
     * 
     * @param boolean $relative
     * @return string
     */
    static function getModuleTemplatesDir($relative = false){
        
        $dir = ($relative)?'':(__DIR__.DS);
        
        $dir .= 'templates'.DS;
        
        if(self::I()->isAdmin())
        {
            return $dir.'admin';
        }
        else
        {
            $template = GlobalSettingHelper::getSetting(GlobalSettingEnum::DEFAULT_TEMPLATE)?:'default';
            
            if(file_exists(__DIR__.DS.'templates'.DS.'clientarea'.DS.$template))
            {
                return $dir.'clientarea'.DS.$template;
            }
            else
            {
                return $dir.'clientarea'.DS.'default';
            }
        }
    }
    
    public function getAssetsURL() {        
        if($this->isAdmin())
        {
            return '../modules/addons/'.$this->configuration()->systemName.'/templates/admin/assets';
        }
        else
        {
            return 'modules/addons/'.$this->configuration()->systemName.'/'.str_replace('\\','/',self::getModuleTemplatesDir(true)).'/assets';
        }
    }
    
    public function getType() {
        return 'addon';
    }
    
    public static function getMainDIR() {
        return __DIR__;
    }

    static function getUrl($page = null,$action=null,$params = array()){
        if(self::I()->isAdmin())
        {
            $url = 'addonmodules.php?module='.self::I()->configuration()->systemName;
        }
        else
        {
            $url = 'index.php?m='.self::I()->configuration()->systemName;
        }
        
        if($page)
        {
            $url .= '&mg-page='.$page;
            if($action){
                $url .= '&mg-action='.$action;
            }
            
            if($params)
            {
                $url .= '&'.http_build_query($params);
            }
        }

        return $url;
    }
    
    static function genCustomPageUrl($page = null,$action=null,$params = array()){
        if(self::I()->isAdmin())
        {
            $url = 'addonmodules.php?module='.self::I()->configuration()->systemName.'&customPage=1';
        }
        else
        {
            $url = 'index.php?m='.self::I()->configuration()->systemName.'&customPage=1';
        }
        
        if($page)
        {
            $url .= '&mg-page='.$page;
        }
        
        if($action){
            $url .= '&mg-action='.$action;
        }
        
        if($params)
        {
            $url .= '&'.http_build_query($params);
        }
        
        return $url;
    }
    
    static function genJSONUrl($page){
        if(self::I()->isAdmin())
        {
            return 'addonmodules.php?module='.self::I()->configuration()->systemName.'&json=1&mg-page='.$page;
        }
        else
        {
            return 'index.php?m='.self::I()->configuration()->systemName.'&json=1&mg-page='.$page;
        }
    }
    
    static function config(){
        return array
        (
            'name'           =>  self::I()->configuration()->name
            ,'description'   =>  self::I()->configuration()->description
            ,'version'       =>  self::I()->configuration()->version
            ,'author'        =>  self::I()->configuration()->author
            ,'fields'        =>  self::I()->configuration()->getAddonWHMCSConfig()
        );
    }
    
    static function activate(){
        try{
            self::I()->configuration()->activate();
            
            return array(
                'status'=>'success'
            );
        } catch (\Exception $ex) {
            return array(
                'status'        => 'error'
                ,'description'  => $ex->getMessage()
            );
        }
    }
    
    static function deactivate(){
        self::I()->configuration()->deactivate();
    }
    
    static function upgrade($vars){

        $moduleVersion    = isset($vars['version']) ? $vars['version'] : $vars[self::I()->configuration()->systemName]['version'];
        self::I()->configuration()->upgrade($moduleVersion);
    }
            
    static function getHTMLAdminCustomPage($input)
    {
        try{     
            self::I()->isAdmin(true);
            self::I()->setMainLangContext();
            
            $page   = empty($input['mg-page'])?'dashboard':$input['mg-page']; 
            $action = empty($input['mg-action'])?'index':$input['mg-action'];
            
            list($content) = self::I()->runControler($page,$action,$input,'CustomHTML');
            return $content;
        } catch (\Exception $ex) {
            self::dump($ex);
            mgLibs\smarty::I()->setTemplateDir(self::I()->getModuleTemplatesDir());

            $message = $ex->getMessage();
            if(method_exists($ex, 'getToken'))
            {
                $message .= mgLibs\lang::absoluteT('token').$ex->getToken();
            }
            
            return mgLibs\smarty::I()->view('fatal',array(
                'message'   => $message
            ));
        }
    }
    
    static function getHTMLAdminPage($input){
        try{      
            self::I()->isAdmin(true);
            self::I()->setMainLangContext();
            
            if(self::I()->isDebug())
            {
                self::I()->configuration()->activate();
            }
            
            $menu = array();
            foreach(self::I()->configuration()->getAddonMenu() as $catName => $category)
            {
                if(isset($category['submenu']))
                {
                    foreach($category['submenu'] as $subName => &$subPage)
                    {
                        if(empty($subPage['url']))
                        {
                            $subPage['url'] = self::getUrl($catName,$subName);
                        }
                    }
                }

                $category['url'] = self::getUrl($catName);
                
                $menu[$catName] = $category;
            }

            $page   = empty($input['mg-page'])?'dashboard':$input['mg-page']; 
            $action = empty($input['mg-action'])?'index':$input['mg-action'];
            
            $vars = array(
                'assetsURL'         => self::I()->getAssetsURL()
                ,'mainURL'          => self::I()->getUrl()
                ,'mainName'         => self::I()->configuration()->name
                ,'menu'             => $menu
                ,'JSONCurrentUrl'   => self::I()->genJSONUrl($page)
                ,'currentPageName'  => $page
                ,'Addon'            => self::I()
                ,'patterns'         => HTML5Pattern::getPatternsArray()
            );

            try{                 
                list($content,$success,$error) = self::I()->runControler($page,$action,$input,'HTML');
                $vars['content'] = $content;
                $vars['success'] = $success;
                $vars['error'] = $error;
            } catch (\Exception $ex) {
                self::dump($ex);
                main\mgLibs\error\register::register($ex);
                $vars['error'] = $ex->getMessage();
                if(method_exists($ex, 'getToken'))
                {
                    $vars['error'] .= mgLibs\lang::absoluteT('token').$ex->getToken();
                }
            }
            
            mgLibs\smarty::I()->setTemplateDir(self::I()->getModuleTemplatesDir());

            $html = mgLibs\smarty::I()->view('main',$vars);
            
            if(self::I()->isDebug())
            {
                $tmp = '<div style="color: #a94442;background-color: #f2dede;border-color: #dca7a7;font-size:20px;padding:10px;"><strong>Module is under development Mode!!!!!!!!!!!!!!!</strong></div>';

                if($langs = mgLibs\lang::getMissingLangs())
                {
                    $tmp .= '<pre>';
                    foreach($langs as $lk => $lang)
                    {
                        $tmp .= $lk." = ".$lang."\n";
                    }
                    $tmp .= '</pre>';
                }
                $html = $tmp.$html;
            }
            
            return $html;
        } catch (\Exception $ex) {
            self::dump($ex);
            
            main\mgLibs\error\register::register($ex);
            mgLibs\smarty::I()->setTemplateDir(self::I()->getModuleTemplatesDir());

            $message = $ex->getMessage();
            if(method_exists($ex, 'getToken'))
            {
                $message .= mgLibs\lang::absoluteT('token').$ex->getToken();
            }
            
            return mgLibs\smarty::I()->view('fatal',array(
                'message'       => $message
                ,'assetsURL'    => self::I()->getAssetsURL()

            ));
        }
    }
    
    function getHTMLClientAreaPage($input){
        $output = array(
            'pagetitle'         => mgLibs\lang::absoluteT(self::I()->configuration()->systemName,'ClientAreaPageTitle'),
            'templatefile'	=> self::I()->getModuleTemplatesDir(true).'/main',
            'requirelogin'	=> isset($_SESSION['uid']) ? false : true,
        );
        
        $breadcrumb = [self::I()->getUrl() => mgLibs\lang::absoluteT(self::I()->configuration()->systemName,'ClientAreaBreadcrumbTitle')];

        try{
            self::I()->setMainLangContext();
            
            $page = 'dashboard';
            if(!empty($input['mg-page']))
            {
                $page = $input['mg-page'];
                $url = self::I()->getUrl($input['mg-page']);
                $breadcrumb[$url] = $input['mg-page'];
            }
            $action = empty($input['mg-action'])?'index':$input['mg-action'];
            $vars = array(
                'assetsURL'         => self::I()->getAssetsURL()
                ,'mainURL'          => self::I()->getUrl()
                ,'mainName'         => self::I()->configuration()->clientareaName
                ,'mainJSONURL'      => self::I()->genJSONUrl($page)
                ,'currentPageName'  => $page
                ,'patterns'         => HTML5Pattern::getPatternsArray()
                
            );

            try{     
                try {
                    list($content,$success,$error) = self::I()->runControler($page,$action,$input,'HTML');

                } catch (DNSSubmoduleException $exc) {

                    $error = self::I()->parseDNSException($exc);
                }


                $vars['MGLANG'] = mgLibs\lang::getInstance();
                
                if(self::I()->isDebug())
                {
                    $html = '<div style="color: #a94442;background-color: #f2dede;border-color: #dca7a7;font-size:20px;padding:10px;"><strong>Module is under development Mode!!!!!!!!!!!!!!!</strong></div>';
                    
                    if($langs = mgLibs\lang::getMissingLangs())
                    {
                        $html .= '<pre>';
                        foreach($langs as $lk => $lang)
                        {
                            $html .= $lk." = ".$lang."\n";
                        }
                        $html .= '</pre>';
                    }
                    
                    $content = $html.$content;
                }
                
                $vars['mgcontent'] = $content;
                $vars['success'] = $success;
                $vars['error'] = $error;
                
            } catch (\Exception $ex) {
                self::dump($ex);
                main\mgLibs\error\register::register($ex);
                $vars['error'] = mgLibs\lang::absoluteT('generalError');
                if(method_exists($ex, 'getToken'))
                {
                    $vars['error'] .= mgLibs\lang::absoluteT('token').$ex->getToken();
                }
            }
        } catch (\Exception $ex) {
            self::dump($ex);
            main\mgLibs\error\register::register($ex);
            $vars['error'] = mgLibs\lang::absoluteT('generalError');
            if(method_exists($ex, 'getToken'))
            {
                $vars['error'] .= mgLibs\lang::absoluteT('token').$ex->getToken();
            }
        }
        
        $output['breadcrumb'] = $breadcrumb;
        $output['vars'] = $vars;
        
        return $output;
    }
    
    public static function getJSONAdminPage($input){        
        $content = array();

        $page = 'dashboard';
        if(!empty($input['mg-page']))
        {
            $page = $input['mg-page'];
        }
        $action = empty($input['mg-action'])?'index':$input['mg-action'];
        try{
            self::I()->isAdmin(true);
            self::I()->setMainLangContext();
            
            try {
                list($result,$success,$error) = self::I()->runControler($page,$action,$input,'JSON');
            } catch (DNSSubmoduleException $exc) {
                AjaxResponse::I()->addRawError(self::I()->parseDNSException($exc, false));
                $result = AjaxResponse::I()->toArray();
            }

            if($error)
            {
                $content['error']  = $error;
                $content['result'] = 'error';
            }
            elseif($success)
            {
                $content['success'] = $success;
                $content['result']  = 'success';
            }
                        
            if($langs = mgLibs\lang::getMissingLangs())
            {
                $html = '<pre>';
                foreach($langs as $lk => $lang)
                {
                    $html .= $lk." = ".$lang."\n";
                }
                $html .= '</pre>';

                $content['error']  = $html;
                $content['result'] = 'error';
            }
            
            $content['data']    = $result;
            
        } catch (\Exception $ex) {
            self::dump($ex);
            main\mgLibs\error\register::register($ex);
            $content['result'] = 'error';
            $content['error']  = $ex->getMessage();
            if(method_exists($ex, 'getToken'))
            {
                $content['error'] .= mgLibs\lang::absoluteT('token').$ex->getToken();
            }
        }

        $content['data'] = mb_convert_encoding($content['data'], 'UTF-8','UTF-8');

        return 'JSONRESPONSE#'.json_encode($content, JSON_HEX_QUOT | JSON_HEX_TAG).'#ENDJSONRESPONSE';
    }
    
    private function parseDNSException($exc, $isCA = true) {
        switch($exc->getCode()) {
            case SubmoduleExceptionCodes::CONNECTION_PROBLEM:
                $message = lang::absoluteT($isCA?'addonCA':'addonAA', 'dns_submodule_connection_problem') . ' ' . ($isCA?'':' Reason: ' . $exc->getMessage());
                break;
            case SubmoduleExceptionCodes::COMMAND_ERROR:
                $message = lang::absoluteT($isCA?'addonCA':'addonAA', 'dns_submodule_command_error') . ' ' . $exc->getMessage();
                break;
            case SubmoduleExceptionCodes::INVALID_PARAMETERS:
                $message = lang::absoluteT($isCA?'addonCA':'addonAA', 'dns_submodule_invalid_parameters') . ' ' . $exc->getMessage();
                break;
            case SubmoduleExceptionCodes::INVALID_RESPONSE:
                $message = lang::absoluteT($isCA?'addonCA':'addonAA', 'dns_submodule_invalid_response') . ' ' . $exc->getMessage();
                break;
        }
        return $message;
    }
    
    function getJSONClientAreaPage($input)
    {
        $content = array();

        $page = 'dashboard';
        if(!empty($input['page']))
        {
            $page = $input['page'];
        }
        $action = empty($input['mg-action'])?'index':$input['mg-action'];

        try{
            self::I()->setMainLangContext();
            
            try {
                list($result,$success,$error) = self::I()->runControler($page,$action,$input,'JSON');
            } catch (DNSSubmoduleException $exc) {
                AjaxResponse::I()->addRawError($this->parseDNSException($exc));
                $result = AjaxResponse::I()->toArray();
            }

            if($error)
            {
                $content['error']  = $error;
                $content['result'] = 'error';
            }
            elseif($success)
            {
                $content['success'] = $success;
                $content['result']  = 'success';
            }
            
            if($langs = mgLibs\lang::getMissingLangs())
            {
                $html = '<pre>';
                foreach($langs as $lk => $lang)
                {
                    $html .= $lk." = ".$lang."\n";
                }
                $html .= '</pre>';

                $content['error']  = $html;
                $content['result'] = 'error';
            }

            $content['data']    = $result;

        } catch (\Exception $ex) {
            self::dump($ex);
            $content['result'] = 'error';
            main\mgLibs\error\register::register($ex);
            $content['error'] = mgLibs\lang::absoluteT('generalError');
            if(method_exists($ex, 'getToken'))
            {
                $content['error'] .= mgLibs\lang::absoluteT('token').$ex->getToken();
            }
        }
                
        return 'JSONRESPONSE#'.json_encode($content, JSON_HEX_QUOT | JSON_HEX_TAG).'#ENDJSONRESPONSE';
    }
    
    static function cron(){       
        try{
            self::I()->isAdmin(true);
            self::I()->setMainLangContext();
            
            self::I()->runControler('cron','index',array(),'CRON');
        } catch (\Exception $ex) {
            self::dump($ex);
            main\mgLibs\error\register::register($ex);
        }
    }
        
    static function localAPI($action,$arguments){    
        $output = array(
            'action'  => $action
        );
                
        try{
            self::I()->isAdmin(true);
            self::I()->setMainLangContext();
            
            list($result,$success,$error) = self::I()->runControler('localAPI',$action,$arguments,'API');
            $output['success'] = $result;
        } catch (\Exception $ex) {
            self::dump($ex);
            main\mgLibs\error\register::register($ex);
            $output['error'] = array(
                'message'   => $ex->getMessage()
                ,'code'     => $ex->getCode()
            );
        }

        return $output;
    }
}