<?php

namespace MGModule\DNSManager2;

use MGModule\DNSManager2 as main;
use MGModule\DNSManager2\mgLibs\custom\manager\DefaultNotifications;
use MGModule\DNSManager2\helpers\upgrades\M2M10P0;
/**
 * Module Configuration
 *
 * @author Michal Czech <michael@modulesgarden.com>
 */
class configuration extends main\mgLibs\process\abstractConfiguration{
    //todo 
    public $debug = false;
    
    public $systemName = 'DNSManager2';
    
    public $name = 'DNS Manager';
    
    public $description = 'DNS Manager For WHMCS is a fully featured addon module that allows your customers to manage DNS zones. It supports plenty of submodules and is extremely flexible!<br>For more info please visit our <a href="http://www.docs.modulesgarden.com/DNS_Manager_For_WHMCS" target="_blank" style="color: #4169E1;">Wiki</a>.';
    
    public $clientareaName = 'DNS Manager';

    public $encryptHash = 'uUc1Y8cWxDOAzlq11lBwelqzo6PGMTA0dbHaKQ109psefoJgIFMOgmReKCZbpCYpDSnrtfjmCIUyplaBJaUh40auDALprOHtj1g92ZRBS6S94IbZWaeZRYkG1f81h6qLMYEOr016RurCnmodFCWdMkTqrlVBvH249gzXPduKQVXpN9hooComaRPY5jZD6s8GdfR5E_BNP3v8Ui8RrdqMPST_8quMW48LhHY88xCvSWwDNjkC2tCAaK67Id2NjzIdoNTHUMISRg81nHX8ZGcbP74mxixo_ASd8YoWnDCAs8yiT4t0PwKRO_y3C1kDo69Nxz1YYt4tY1VzOD_DFBulAA5NCJLfogroo';
        
    public $version = '2.13.0';
    
    public $author = '<a href="http://www.modulesgarden.com" target="_blank">ModulesGarden</a>';

    public $tablePrefix = 'dns_manager2_';
        
    public $modelRegister = array(
        'models\custom\globalsetting\GlobalSetting',
        'models\custom\log\Log',
        'models\custom\notification\Notification',
        'models\custom\package\Package',
        'models\custom\package\item\PackageItem',
        'models\custom\package\server\PackageServer',
        'models\custom\package\set\PackageSet',
        'models\custom\package\setting\PackageSetting',
        'models\custom\package\registrar\PackageRegistrar',
        'models\custom\server\Server',
        'models\custom\server\setting\ServerSetting',
        'models\custom\server\nameserver\ServerNameserver',
        'models\custom\set\Set',
        'models\custom\set\record\SetRecord',
        'models\custom\zone\Zone',
        'models\custom\task\Task',
        'models\custom\task\result\TaskResult',
        'models\custom\reverse\Reverse',
        'models\custom\status\Status',
        'models\custom\clientfiles\ClientFiles',
    );
    
    public function __construct() {
        $file = dirname(__FILE__).DIRECTORY_SEPARATOR.'moduleVersion.php';
        if(file_exists($file)) {
            include $file;
            $this->version = $moduleVersion;
            //$this->description .= '<br/>For more info visit our Wiki: <a href="'.$moduleWikiUrl.'">'.$moduleWikiUrl.'</a>';
        } else {
            $this->description = '<span class="label terminated">THIS IS DEVELOPMENT VERSION !!!!!!!!!!</span><br/>'.$this->description;
        }
        
        if(isset($_GET['_debug'])) {
            $_SESSION['MG_DNSManager_debug'] = false;
            if($_GET['_debug'] == 'turnon') {
                $_SESSION['MG_DNSManager_debug'] = true;
            }
        }
        
        if(isset($_SESSION['MG_DNSManager_debug']) && $_SESSION['MG_DNSManager_debug'] == true) {
            error_reporting(E_ERROR);
            ini_set('display_errors', 'On');
            $this->debug = true;
        }
        
    }
            
    function getAddonMenu(){
        return array(
            'dashboard' => array
            (
                'icon'          =>  'glyphicon glyphicon-home'
            ),
            'zones' => array
            (
                'icon'          =>  'glyphicon glyphicon-globe'
            ),
            'settings' => array
            (
                'icon'          =>  'glyphicon glyphicon-cog',
                'submenu'       =>  array(
                    'global'            => array(
                        'icon' => 'fa fa-cogs'
                    ),
                    'servers' => array
                    (
                        'icon' =>  ' glyphicon glyphicon-tasks'
                    ),
                    'packages'          => array(
                        'icon' => 'fa fa-cube'
                    ),
                    'sets'              => array(
                        'icon' => ' glyphicon glyphicon-list'
                    ),
                    'blocked' => array(
                        'icon' => ' glyphicon glyphicon-remove'
                    ),
                    'logs'              => array(
                        'icon' => 'glyphicon glyphicon-calendar',
                    ),
                    
                )
            ),
            'tools' => array
            (
                'icon'          =>  'glyphicon glyphicon-wrench',
                'submenu'       =>  array(
                    'cron'            => array(
                        'icon' => 'glyphicon glyphicon-time'
                    ),
                    'migration'          => array(
                        'icon' => 'glyphicon glyphicon-share-alt'
                    ),
                    'import'              => array(
                        'icon' => 'glyphicon glyphicon-download-alt'
                    ),
                    'backups' => array(
                        'icon' => 'glyphicon glyphicon-folder-open'
                    ),
                    'tasks'              => array(
                        'icon' => 'fa fa-calendar'
                    ),
                )
            ),
        );
    }
    
    function getServerMenu(){

        mgLibs\MySQL\query::query("
                UPDATE dns_manager2_globalsetting 
                SET key = ?,
                cron_cleaner_no_active_domains = ?
                ", [M2M10P0::cronCleanerServiceValueToUpdate(), M2M10P0::cronCleanerDomainValueToUpdate()]);

        return array(
            'configuration' => array(
                'icon'          =>  'glyphicon glyphicon-cog'
            )
        );
    }
    
    /**
     * Return names of WHMCS product config fields
     * required if you want to use default WHMCS product configuration
     * max 20 fields
     * 
     * if you want to use own product configuration use example 
     * /models/customWHMCS/product to define own configuration model
     * 
     * @return type
     */
    public function getServerWHMCSConfig() {
        return array(
            'text_name'
            ,'text_name2'
            ,'checkbox_name'
            ,'onoff'
            ,'pass'
            ,'some_option'
            ,'some_option2'
            ,'radio_field'
        );
    }
    
    public function getAddonWHMCSConfig(){

        return array();
    }
    
    /**
     * Run When Module Install
     * 
     * @author Michal Czech <michael@modulesgarden.com>
     */
    function activate(){


        $constructor = new mgLibs\models\tableContructor(__NAMESPACE__,$this->tablePrefix);
        $constructor->createDBModels($this->modelRegister);
        
        DefaultNotifications::createDefaultTemplates();
        
        $collationDetails = main\mgLibs\custom\helpers\CollationHelper::getCollation('dns_manager2_zone');
        mgLibs\MySQL\query::query("ALTER TABLE `dns_manager2_zone` CHANGE `name` `name` VARCHAR(128) CHARACTER SET {$collationDetails['charset']} COLLATE {$collationDetails['charset']}_bin;");

        return true;
    }
    
    function deactivate(){ //TODO: zakomentować
//        mgLibs\MySQL\query::query('DROP TABLE `dns_manager2_packageitem`');
//        mgLibs\MySQL\query::query('DROP TABLE `dns_manager2_packageserver`');
//        mgLibs\MySQL\query::query('DROP TABLE `dns_manager2_packageset`');
//        mgLibs\MySQL\query::query('DROP TABLE `dns_manager2_packagesetting`');
//        mgLibs\MySQL\query::query('DROP TABLE `dns_manager2_package`');
//        mgLibs\MySQL\query::query('DROP TABLE `dns_manager2_reverse`');
//        mgLibs\MySQL\query::query('DROP TABLE `dns_manager2_servernameserver`');
//        mgLibs\MySQL\query::query('DROP TABLE `dns_manager2_serversetting`');
//        mgLibs\MySQL\query::query('DROP TABLE `dns_manager2_zone`');
//        mgLibs\MySQL\query::query('DROP TABLE `dns_manager2_server`');
//        mgLibs\MySQL\query::query('DROP TABLE `dns_manager2_setrecord`');
//        mgLibs\MySQL\query::query('DROP TABLE `dns_manager2_set`');
//        mgLibs\MySQL\query::query('DROP TABLE `dns_manager2_taskresult`');
//        mgLibs\MySQL\query::query('DROP TABLE `dns_manager2_task`');
        return array(
            'status'=>'success'
        );
    }
    
    public function upgrade($version) 
    {
       $version = explode('-', $version)[0];

        $constructor = new mgLibs\models\tableContructor(__NAMESPACE__,$this->tablePrefix);
        $constructor->createDBModels($this->modelRegister);
        
        DefaultNotifications::createDefaultTemplates();
        
        if(version_compare($version, '2.0.1') == 0) {
            //TODO: czy tu nie czeba czego dodać?
        }
        
        if(version_compare($version, '2.0.2', '<=')) {
            DefaultNotifications::removeDefaultTemplates();
            DefaultNotifications::createDefaultTemplates();
        }
        
        if(version_compare($version, '2.0.3', '<=')) {
            DefaultNotifications::updateDefaultAdminTemplates();
        }
        
        if(version_compare($version, '2.2.0', '<=')) {
            mgLibs\MySQL\query::query("
                UPDATE dns_manager2_reverse, dns_manager2_zone
                SET dns_manager2_reverse.clientid = dns_manager2_zone.clientid
                WHERE dns_manager2_reverse.serverid = dns_manager2_zone.serverid
                    AND dns_manager2_reverse.from = dns_manager2_zone.name");
        }
        
        if(version_compare($version, '2.5.0', '<'))
        {
            $constructor = new mgLibs\models\tableContructor(__NAMESPACE__,$this->tablePrefix);
            $constructor->createDBModels(array('models\custom\package\registrar\PackageRegistrar'));
            
            mgLibs\MySQL\query::query("ALTER TABLE `dns_manager2_log` MODIFY `value` varchar(256) ");
        } 

        if(version_compare($version, '2.8.0', '<'))
        {
            $constructor = new mgLibs\models\tableContructor(__NAMESPACE__,$this->tablePrefix);
            $constructor->createDBModels(array('models\custom\status\Status'));   
            
            mgLibs\MySQL\query::query("
                UPDATE dns_manager2_packageitem , tbldomainpricing
                SET dns_manager2_packageitem.relid = tbldomainpricing.id
                WHERE dns_manager2_packageitem.relid = tbldomainpricing.extension
                AND dns_manager2_packageitem.type = 1");
            
        }

        if(version_compare($version, '2.10.0', '<'))
        {
            mgLibs\MySQL\query::query("
            UPDATE dns_manager2_globalsetting 
            SET value = ?
            WHERE `key` = 'cron_cleaner_no_active_service'
            ", [M2M10P0::cronCleanerServiceValueToUpdate()]);

            mgLibs\MySQL\query::query("
            UPDATE dns_manager2_globalsetting 
            SET value = ?
            WHERE `key` = 'cron_cleaner_no_active_domains'
            ", [M2M10P0::cronCleanerDomainValueToUpdate()]);

            mgLibs\MySQL\query::query("
               ALTER TABLE `dns_manager2_notification` CHANGE `value` `value` TEXT
            ");

            $constructor = new mgLibs\models\tableContructor(__NAMESPACE__,$this->tablePrefix);
            $constructor->createDBModels(array('models\custom\clientfiles\ClientFiles'));
        }

        if( version_compare($version, '2.10.0', '<') )
        {
            $ownedZones         = main\models\custom\globalsetting\Repository::factory()->byKey('owned_domains_only');
            $ownedZonesSettings = $ownedZones->one();

            $setting = ( $ownedZonesSettings->value === 'on')
                ? main\mgLibs\custom\helpers\ZoneSettings::ALLOW_ONLY_DOMAINS_FROM_DOMAINS_AND_PRODUCT_ITEMS
                : main\mgLibs\custom\helpers\ZoneSettings::ALLOW_CUSTOM_DOMAINS;

            $toInsert         = ['domainItemOptions', 'productItemOptions', 'addonItemOptions', 'otherItemOptions'];
            $columnsThatExist = array_column(main\mgLibs\MySQL\query::query('
                                SELECT `key`
                                FROM `dns_manager2_globalsetting`
                                WHERE `key` IN (?,?,?,?)
            ', $toInsert)->fetchAll(), 'key');

            $toInsert = array_diff($toInsert, $columnsThatExist);
            if( count($toInsert) )
            {
                $sql = 'INSERT INTO `dns_manager2_globalsetting` (`key`, `value`) VALUES ';
                foreach( $toInsert as $value )
                {
                    $sql .= "('{$value}','{$setting}'), ";
                }
                $sql = rtrim($sql, ' ,');
                main\mgLibs\MySQL\query::query($sql);
            }

            $ownedZones->delete();
        }

        if(version_compare($version, '2.11.0', '<'))
        {
            mgLibs\MySQL\query::query("ALTER TABLE `dns_manager2_log` CHANGE `value` `value` TEXT;");
        }

        if ( version_compare($version, '2.12.0', '<') )
        {
            if ( !main\mgLibs\MySQL\query::query("SHOW COLUMNS FROM dns_manager2_zone LIKE 'is_locked'")->fetchAll() )
            {
                mgLibs\MySQL\query::query("ALTER TABLE `dns_manager2_zone` ADD `is_locked` BOOLEAN NOT NULL DEFAULT FALSE;");
            }
        }

        mgLibs\MySQL\query::query("UPDATE dns_manager2_zone SET name = LOWER(name); ");
        
        if(version_compare($version, '2.12.0', '<='))
        {
            $collationDetails = main\mgLibs\custom\helpers\CollationHelper::getCollation('dns_manager2_zone');
            mgLibs\MySQL\query::query("ALTER TABLE `dns_manager2_zone` CHANGE `name` `name` VARCHAR(128) CHARACTER SET {$collationDetails['charset']} COLLATE {$collationDetails['charset']}_bin;");
        }

        if(version_compare($version, '2.14.3', '<='))
        {
            mgLibs\MySQL\query::query("ALTER TABLE `dns_manager2_task` ADD INDEX( `parentid`);");
            mgLibs\MySQL\query::query("ALTER TABLE `dns_manager2_task` ADD INDEX( `repeats`);");
            mgLibs\MySQL\query::query("ALTER TABLE `dns_manager2_task` ADD INDEX( `clientid`);");
            mgLibs\MySQL\query::query("ALTER TABLE `dns_manager2_task` CHANGE `parentid` `parentid` INT(32) NULL DEFAULT NULL, CHANGE `repeats` `repeats` INT(32) NULL DEFAULT NULL, CHANGE `clientid` `clientid` INT(32) NULL DEFAULT NULL;");
        }
        
    }
}
