<?php

/*
  MailBeez Automatic Trigger Email Campaigns
  http://www.mailbeez.com

  Copyright (c) 2010 MailBeez

  inspired and in parts based on
  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
 */

///////////////////////////////////////////////////////////////////////////////
///																																					 //
///                 MailBeez Core file - do not edit                         //
///                                                                          //
///////////////////////////////////////////////////////////////////////////////
// make path work from admin
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/configbeez.php');

class config_queen extends configbeez
{
// class constructor
    function __construct()
    {
        parent::__construct();
        $this->code = 'config_queen';
        $this->module = 'config_queen';

        $this->version = 4.97909; // float value
        $this->version_display = '4.9.90.9 - V5 Beta 9'; // string value bump

        $this->title = mh_lng('MAILBEEZ_MAILHIVE_TEXT_TITLE');
        $this->description = mh_lng('MAILBEEZ_MAILHIVE_TEXT_DESCRIPTION');
        $this->description_image = 'icon_big.png';
        $this->icon = 'icon.png';
        $this->sort_order = 0;
        $this->enabled = mh_cfg('MAILBEEZ_MAILHIVE_STATUS') == 'True';
        $this->status_key = 'MAILBEEZ_MAILHIVE_STATUS';
        // BeezUI V5 metadata
        $this->beez_ui_ready = true; // expose to BeezUI
        $this->group = self::GROUP_CONFIGURATION; // categorize as configuration
        // small inline SVG icon (gear)
        $this->svg_icon = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c0 .66.39 1.26 1 1.51.16.07.33.1.51.1H21a2 2 0 1 1 0 4h-.09c-.18 0-.35.03-.51.1-.61.25-1 .85-1 1.51z"/></svg>';
        $this->color = 'bg-slate-600 text-white';
        $this->has_submodules = true;
        $this->admin_action_plugins_path = MH_DIR_CONFIG; // default-path to include admin action plugins from
        //$this->admin_action_plugins = 'uninstall.php';

        $this->documentation_key = 'config'; // leave empty if no documentation available
        $this->documentation_root = 'https://www.mailbeez.com/documentation/installation/';

        // update version if necessary
        if ((mh_cfg('MAILBEEZ_VERSION')) && (str_replace(',', '.', mh_cfg('MAILBEEZ_VERSION')) < $this->version)) {
            $action = mh_get('action',  '');
            if ($action != 'config_update_ok') {
                // avoid loop with config cache installed
                $this->update(mh_cfg('MAILBEEZ_VERSION'));
            }
        }


        $this->_blueprint();
    }

    function config_queen()
    {
        self::__construct();
    }

// class methods

    function onSave()
    {
        // reset system check in case the setting was changed
        mh_system_check_refresh();
    }


    function remove()
    {
        $remove_keys = $this->keys();
        if (MH_PLATFORM == 'xtc') {
            // remove additional fields
            $xtc_text_keys = array();
            $keys = $this->keys();
            foreach ($keys as $idx => $key_name) {
                $xtc_text_keys[] = $key_name . '_TITLE';
                $xtc_text_keys[] = $key_name . '_DESC';
            }
            $remove_keys = array_merge($xtc_text_keys, $this->keys());
        }

        $remove_keys[] = 'MAILBEEZ_VERSION';
        $remove_keys[] = 'MAILBEEZ_INSTALLED';
        $remove_keys[] = 'MAILBEEZ_INSTALLED_VERSIONS';
        $remove_keys[] = 'MAILBEEZ_CONFIG_INSTALLED';
        $remove_keys[] = 'MAILBEEZ_CONFIG_INSTALLED_VERSIONS';
        $remove_keys[] = 'MAILBEEZ_FILTER_INSTALLED';
        $remove_keys[] = 'MAILBEEZ_FILTER_INSTALLED_VERSIONS';
        $remove_keys[] = 'MAILBEEZ_REPORT_INSTALLED';
        $remove_keys[] = 'MAILBEEZ_REPORT_INSTALLED_VERSIONS';
        $remove_keys[] = 'MAILBEEZ_DASHBOARD_INSTALLED';
        $remove_keys[] = 'MAILBEEZ_DASHBOARD_INSTALLED_VERSIONS';

        // Google Analytics
        $remove_keys[] = 'MAILBEEZ_MAILHIVE_GA_ENABLED';
        $remove_keys[] = 'MAILBEEZ_MAILHIVE_GA_REWRITE_MODE';
        $remove_keys[] = 'MAILBEEZ_MAILHIVE_GA_REWRITE_FORMAT';
        $remove_keys[] = 'MAILBEEZ_MAILHIVE_GA_MEDIUM';
        $remove_keys[] = 'MAILBEEZ_MAILHIVE_GA_SOURCE';

        // Piwik
        $remove_keys[] = 'MAILBEEZ_MAILHIVE_PIWIK_ENABLED';
        $remove_keys[] = 'MAILBEEZ_MAILHIVE_PIWIK_REWRITE_MODE';
        $remove_keys[] = 'MAILBEEZ_MAILHIVE_PIWIK_REWRITE_FORMAT';
        $remove_keys[] = 'MAILBEEZ_MAILHIVE_PIWIK_CAMPAIGN';

        // Econda
        $remove_keys[] = 'MAILBEEZ_MAILHIVE_ECONDA_ENABLED';
        $remove_keys[] = 'MAILBEEZ_MAILHIVE_ECONDA_REWRITE_MODE';
        $remove_keys[] = 'MAILBEEZ_MAILHIVE_ECONDA_REWRITE_FORMAT';
        $remove_keys[] = 'MAILBEEZ_MAILHIVE_ECONDA_CAMPAIGN';

        $remove_keys[] = 'MAILBEEZ_MAILHIVE_UPDATE_REMINDER_TIMESTAMP';

        $remove_keys[] = 'MAILBEEZ_CONFIG_TEMPLATE_ENGINE_STATUS';
        $remove_keys[] = 'MAILBEEZ_CONFIG_TEMPLATE_ENGINE_COMP_MODE';
        $remove_keys[] = 'MAILBEEZ_CONFIG_DASHBOARD_START';
        $remove_keys[] = 'MAILBEEZ_CONFIG_SIMULATION_EMAIL';
        $remove_keys[] = 'MAILBEEZ_CONFIG_SIMULATION_TRACKING';
        $remove_keys[] = 'MAILBEEZ_MAILHIVE_MODE';
        $remove_keys[] = 'MAILBEEZ_CONFIG_SIMULATION_COPY';

        mh_delete_config_values($remove_keys);
        return mh_delete_config_values_like('MAILBEEZ_');
    }

    // installation methods

    function keys()
    {
        return array('MAILBEEZ_MAILHIVE_STATUS', 'MAILBEEZ_CONFIG_BEEZ_UI', 'MAILBEEZ_MAILHIVE_RUN_SHOW_EMAIL', 'MAILBEEZ_MAILHIVE_COPY', 'MAILBEEZ_MAILHIVE_EMAIL_COPY', 'MAILBEEZ_MAILHIVE_EMAIL_COPY_MAX_COUNT', 'MAILBEEZ_INSTALLED', 'MAILBEEZ_INSTALLED_VERSIONS', 'MAILBEEZ_MAILHIVE_TOKEN', 'MAILBEEZ_MAILHIVE_POPUP_MODE', 'MAILBEEZ_MAILHIVE_UPDATE_REMINDER', 'MH_SYSTEMCHECK_DB_DISABLED', 'MAILBEEZ_WATCHDOG_STATUS', 'MAILBEEZ_WATCHDOG_LIMIT_KILL');
    }

    function install()
    {

        // initial install
        // on Gambio upgrades this setting might get migrated, but table is missing
        mh_delete_config_value('MAILBEEZ_INSIGHT_VIEW_STATUS');


        mh_insert_config_value(array('configuration_title' => 'Let the MailBeez work for you',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_STATUS',
            'configuration_value' => 'True',
            'configuration_description' => 'Choose False to deactivated MailHive and MailBeez',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Mode',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_MODE',
            'configuration_value' => 'simulate',
            'configuration_description' => 'production: emails are send out, tracking active<br>simulate: emails to copy-address only, tracking configurable',
            'set_function' => 'mh_cfg_select_option(array(\'production\', \'simulate\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Send copy',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_COPY',
            'configuration_value' => 'True',
            'configuration_description' => 'send a copy of each email to copy-address',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Sent copy to',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_EMAIL_COPY',
            'configuration_value' => mh_cfg('STORE_OWNER_EMAIL_ADDRESS'),
            'configuration_description' => 'Send a copy of each email to this address<br>(be careful - configure number below)',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'Max. number of copy-emails sent per MailBeez Module',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_EMAIL_COPY_MAX_COUNT',
            'configuration_value' => '10',
            'configuration_description' => 'controll the number of copy-emails',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'Security Token - for internal use only',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_TOKEN',
            'configuration_value' => md5(time()),
            'configuration_description' => 'Security Token to protect public mailhive, leave default value or set to what you like',
            'set_function' => ''
        ));


        mh_insert_config_value(array('configuration_title' => 'Popup mode',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_POPUP_MODE',
            'configuration_value' => 'CeeBox',
            'configuration_description' => 'Popup-Mode, please change if you are having compatibility issues with opening the nice CeeBox AJAX Popups.',
            'set_function' => 'mh_cfg_select_option(array(\'off\', \'CeeBox\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Remind to run update check',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_UPDATE_REMINDER',
            'configuration_value' => 'True',
            'configuration_description' => 'Do you want to get reminder to check for updates?',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'Google Analytics Integration',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_GA_ENABLED',
            'configuration_value' => 'True',
            'configuration_description' => 'Globally enable Google Analytics Integration',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Google Analytics URL Rewrite Mode',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_GA_REWRITE_MODE',
            'configuration_value' => 'all',
            'configuration_description' => 'Globally set Google Analytics URL Rewrite Mode',
            'set_function' => 'mh_cfg_select_option(array(\'all\', \'shop\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'MailBeez Version',
            'configuration_key' => 'MAILBEEZ_VERSION',
            'configuration_value' => $this->version,
            'configuration_description' => 'This is automatically updated. No need to edit.',
            'set_function' => ''
        ));


        mh_db_query("CREATE TABLE IF NOT EXISTS " . DB_PREFIX . "mailbeez_tracking (
			    autoemail_id INT NOT NULL AUTO_INCREMENT,
			    module VARCHAR(255) NOT NULL,
				iteration INT( 11 ) NOT NULL ,
				customers_id INT( 11 ) NOT NULL ,
				customers_email VARCHAR( 96 ) NOT NULL,
				orders_id INT NOT NULL,
				date_sent DATETIME NOT NULL ,
				PRIMARY KEY ( autoemail_id ),
				INDEX ( customers_id, iteration, module(25) ) );");

        // new installations
        // set image cache path
        $image_cache_path = '';
        switch (MH_PLATFORM) {
            case 'oscommerce':
            case 'creloaded':
            case 'digistore':
            case 'zencart':
            case 'mercari':
                $image_cache_path = 'cache_images';
                break;
            case 'xtc':
            case 'gambio':
                if (MH_ROOT_PATH == 'ext/mailhive/') {
                    $image_cache_path = 'ext/mailhive_images';
                } elseif (MH_ROOT_PATH == 'includes/external/mailhive') {
                    $image_cache_path = 'includes/external/mailhive_images';
                }
                break;
            default:
                $image_cache_path = MH_ROOT_PATH . 'images/cache';
        }


        mh_insert_config_value(array('configuration_title' => 'Root for image engine Cache',
            'configuration_key' => 'MAILBEEZ_CONFIG_IMAGE_ENGINE_CACHE_DIR',
            'configuration_value' => $image_cache_path,
            'configuration_description' => 'relativ to store root - empty: default'
        ));


        $this->update($this->version);
    }

    function update($installed_version = null)
    {
        // MailBeez V1.5
        mh_db_query("CREATE TABLE IF NOT EXISTS " . DB_PREFIX . "mailbeez_block (
			  autoemail_id INT NOT NULL AUTO_INCREMENT,
			  module VARCHAR(255) NOT NULL,
				customers_id INT( 11 ) NOT NULL ,
				date_block DATETIME NOT NULL,
				PRIMARY KEY ( autoemail_id ),
				INDEX ( customers_id, module (20) ) );");


        // MailBeez V2
        mh_db_query("CREATE TABLE IF NOT EXISTS " . DB_PREFIX . "mailbeez_event_log (
			  log_id INT NOT NULL AUTO_INCREMENT,
				event_type VARCHAR(255) NOT NULL,
				log_entry TEXT,
				batch_id INT( 11 ) NOT NULL ,
				module VARCHAR(255) NOT NULL,
				class VARCHAR(255) NOT NULL,
				result VARCHAR(255) NOT NULL,
				parameters TEXT,
                log_date DATETIME NOT NULL,
				query_string TEXT,
				simulation INT( 11 ) NOT NULL,
				PRIMARY KEY ( log_id ),
				INDEX ( module ) );");


        // MailBeez V2.5
        // introducing: process locking
        mh_db_query("CREATE TABLE IF NOT EXISTS " . DB_PREFIX . "mailbeez_process (
                        lock_id INT(11) NOT NULL AUTO_INCREMENT,
                        lock_key VARCHAR(255) DEFAULT NULL,
                        lock_value TEXT DEFAULT NULL,
                        batch_id INT( 11 ) NOT NULL ,
                        date_added DATETIME NOT NULL DEFAULT '1000-01-01 00:00:00',
                        PRIMARY KEY  (lock_id),
                        INDEX ( lock_key ) );"
        );


        // MailBeez V2.6
        mh_db_query("CREATE TABLE IF NOT EXISTS " . DB_PREFIX . "mailbeez_bounces (
			    id INT NOT NULL AUTO_INCREMENT,
			    autoemail_id INT NOT NULL,
				customers_email VARCHAR( 96 ) NOT NULL,
				customers_id INT( 11 ) NOT NULL ,
				module VARCHAR(255) NOT NULL,
				date_bounce DATETIME NOT NULL,
				bounce_type VARCHAR(1),
				PRIMARY KEY ( id ),
				KEY autoemail_id (autoemail_id),
				KEY customers_id (customers_id),
				KEY customers_email (customers_email) );");

        mh_db_query("CREATE TABLE IF NOT EXISTS " . DB_PREFIX . "mailbeez_bounces_msg_log (
			    id INT NOT NULL AUTO_INCREMENT,
			    autoemail_id INT NOT NULL,
				bounce_msg TEXT,
				PRIMARY KEY ( id ),
				KEY autoemail_id (autoemail_id) );");

        mh_db_query("CREATE TABLE IF NOT EXISTS " . DB_PREFIX . "mailbeez_opens_log (
			    id INT NOT NULL AUTO_INCREMENT,
			    message_id VARCHAR( 255 ) NOT NULL,
			    date DATETIME NOT NULL,
			    user_agent VARCHAR( 255 ) NOT NULL,
				PRIMARY KEY ( id ),
				KEY message_id (message_id) );");

        mh_db_query("CREATE TABLE IF NOT EXISTS " . DB_PREFIX . "mailbeez_tracking_clicks (
			    id INT NOT NULL AUTO_INCREMENT,
                message_id VARCHAR( 255 ) NOT NULL,
                date_record DATETIME NOT NULL,
				PRIMARY KEY ( id ),
				KEY message_id (message_id) );");


        mh_db_query("CREATE TABLE IF NOT EXISTS " . DB_PREFIX . "mailbeez_tracking_orders (
			    id INT NOT NULL AUTO_INCREMENT,
                message_id VARCHAR( 255 ) NOT NULL,
                orders_id INT( 11 ) NOT NULL,
                customers_id INT( 11 ) NOT NULL,
                date_record DATETIME NOT NULL,
				PRIMARY KEY ( id ),
				KEY message_id (message_id) );");


        mh_insert_config_value(array('configuration_title' => 'Google Analytics Medium',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_GA_MEDIUM',
            'configuration_value' => 'email',
            'configuration_description' => 'Choose how you would like to name the medium (default: email)',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'Google Analytics Source',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_GA_SOURCE',
            'configuration_value' => 'MailBeez',
            'configuration_description' => 'Choose how you would like to name the source (default: MailBeez)',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'Compatibility Mode',
            'configuration_key' => 'MAILBEEZ_CONFIG_TEMPLATE_ENGINE_COMP_MODE',
            'configuration_value' => 'True',
            'configuration_description' => 'Choose True for compatibility with the MailBeez 1.x Template System.',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Startpage',
            'configuration_key' => 'MAILBEEZ_CONFIG_DASHBOARD_START',
            'configuration_value' => 'home',
            'configuration_description' => 'Choose which tab you would like to see when you open MailBeez',
            'set_function' => 'mh_cfg_select_option(array(\'home\', \'mailbeez\', \'config\', \'filter\', \'report\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Sent simulation to',
            'configuration_key' => 'MAILBEEZ_CONFIG_SIMULATION_EMAIL',
            'configuration_value' => mh_cfg('STORE_OWNER_EMAIL_ADDRESS'),
            'configuration_description' => 'Email Adress to send simulation emails to - no limitations',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'Send copy in Simulation mode',
            'configuration_key' => 'MAILBEEZ_CONFIG_SIMULATION_COPY',
            'configuration_value' => 'True',
            'configuration_description' => 'send a copy of each email to the configured copy-address',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Enable Tracking in Simulation Mode',
            'configuration_key' => 'MAILBEEZ_CONFIG_SIMULATION_TRACKING',
            'configuration_value' => 'True',
            'configuration_description' => 'Do you want to enable Tracking in Simulation mode? You can delete the Simulation Tracking with click on "Restart Simulation"',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'Enable Early Check',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_EARLY_CHECK_ENABLED',
            'configuration_value' => 'True',
            'configuration_description' => 'Do you want to enable "Early Check"? This will hide all already sent or filtered results - but might confuse by showing "0 recipients".<br />
"Early Check" adds a SQL query per item per module (slower)',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Optional',
            'configuration_key' => 'MAILBEEZ_CONFIG_EVENT_LOG_LEVEL',
            'configuration_value' => '',
            'configuration_description' => 'Settings',
            'set_function' => 'mh_cfg_select_multioption(array(\'MODULE_INIT\', \'MODULE_SQL\'), '
        ));


        if (MH_PLATFORM != 'xtc' && MH_PLATFORM != 'gambio' && MH_PLATFORM != 'mercari') {
            // only for platforms without smarty by default
            mh_insert_config_value(array('configuration_title' => 'Path to Smarty',
                'configuration_key' => 'MAILBEEZ_CONFIG_TEMPLATE_ENGINE_SMARTY_PATH',
                'configuration_value' => 'Smarty_2.6.26',
                'configuration_description' => 'Path to Smarty Template system<br>located in <br />
																		 ' . MH_ROOT_PATH . 'common/classes/',
                'set_function' => ''
            ));
        }

        // convert field type
        $field_info = mh_db_check_field_exists(TABLE_MAILBEEZ_TRACKING, 'customers_id');
        if ($field_info['Type'] == 'int(11)') {
            mh_db_query("ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " CHANGE customers_id customers_id BIGINT( 20 ) NOT NULL DEFAULT '0'");
        }
        $field_info = mh_db_check_field_exists(TABLE_MAILBEEZ_BLOCK, 'customers_id');
        if ($field_info['Type'] == 'int(11)') {
            mh_db_query("ALTER TABLE " . TABLE_MAILBEEZ_BLOCK . " CHANGE customers_id customers_id BIGINT( 20 ) NOT NULL DEFAULT '0'");
        }

        // advanced simulation
        $sql = array();
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD simulation INT( 11 ) NOT NULL ;";
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD INDEX ( simulation ) ;";
        mh_db_add_field(TABLE_MAILBEEZ_TRACKING, 'simulation', $sql);

        $sql = array();
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_BLOCK . " ADD simulation INT( 11 ) NOT NULL ;";
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_BLOCK . " ADD INDEX ( simulation ) ;";
        mh_db_add_field(TABLE_MAILBEEZ_BLOCK, 'simulation', $sql);


        $sql = array();
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_BLOCK . " ADD source INT( 11 ) DEFAULT 0;";
        mh_db_add_field(TABLE_MAILBEEZ_BLOCK, 'source', $sql);


        $sql = array();
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD channel VARCHAR( 10 ) NOT NULL ;";
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD INDEX ( channel ) ;";
        mh_db_add_field(TABLE_MAILBEEZ_TRACKING, 'channel', $sql);

        // event log
        $sql = array();
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD batch_id INT( 11 ) NOT NULL ;";
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD INDEX ( batch_id ) ;";
        mh_db_add_field(TABLE_MAILBEEZ_TRACKING, 'batch_id', $sql);

        // message tracking
        $sql = array();
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD message_id VARCHAR( 255 ) NOT NULL ;";
        mh_db_add_field(TABLE_MAILBEEZ_TRACKING, 'message_id', $sql);
        $sql = array();
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD opened DATETIME ;";
        mh_db_add_field(TABLE_MAILBEEZ_TRACKING, 'opened', $sql);
        $sql = array();
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD clicked DATETIME ;";
        mh_db_add_field(TABLE_MAILBEEZ_TRACKING, 'clicked', $sql);
        $sql = array();
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD ordered DATETIME ;";
        mh_db_add_field(TABLE_MAILBEEZ_TRACKING, 'ordered', $sql);


        // click tracking
        $sql = array();
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING_CLICKS . " ADD url TEXT ;";
        mh_db_add_field(TABLE_MAILBEEZ_TRACKING_CLICKS, 'url', $sql);

        // bounce handling
        $sql = array();
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD bounce_status VARCHAR( 1 ) DEFAULT NULL ;";
        mh_db_add_field(TABLE_MAILBEEZ_TRACKING, 'bounce_status', $sql);


        // install dashboard default modules, also update
        $default_dashboardbeez = array('dashboard_substat', 'dashboard_intro', 'dashboard_latest_news', 'dashboard_actions', 'dashboard_versioncheck', 'dashboard_review_o_meter', 'dashboard_winback_o_meter', 'dashboard_nopurchase_o_meter', 'dashboard_beez_o_graph', 'dashboard_statsbar', 'dashboard_ga', 'dashboard_loyalty_o_graph', 'dashboard_dq_check');
        if (mh_cfg('MAILBEEZ_DASHBOARD_INSTALLED') != '') {
            $installed_modules_str = str_replace(mh_cfg('MH_FILE_EXTENSION'), '', mh_cfg('MAILBEEZ_DASHBOARD_INSTALLED'));
            $installed_modules = explode(';', $installed_modules_str);
            $default_dashboardbeez_all = array_merge($installed_modules, $default_dashboardbeez);

        } else {
            $default_dashboardbeez_all = $default_dashboardbeez;
        }

        $install_modules = array();
        $cnt = 0;
        foreach ($default_dashboardbeez_all as $idx => $class) {
            if (array_search($class . mh_cfg('MH_FILE_EXTENSION'), $install_modules) === false) {
                if (file_exists(mh_cfg('MH_DIR_DASHBOARD') . $class . mh_cfg('MH_FILE_EXTENSION'))) {
                    $cnt++;
                    include_once(mh_cfg('MH_DIR_DASHBOARD') . $class . mh_cfg('MH_FILE_EXTENSION'));
                    if (!class_exists($class)) {
                        continue;
                    } else {
                        $module = new $class;
                        $module->install();

                        // PHP7.1 A non-numeric value encountered
                        $install_modules['a_' . ((int)$module->sort_order + 0.001 * $cnt)] = $class . mh_cfg('MH_FILE_EXTENSION');
                    }
                }
            }
        }
        ksort($install_modules);

        mh_insert_config_value(array('configuration_title' => 'Installed Modules',
            'configuration_key' => 'MAILBEEZ_DASHBOARD_INSTALLED',
            'configuration_value' => implode(';', $install_modules),
            'configuration_description' => 'This is automatically updated. No need to edit.',
            'set_function' => ''
        ), true);


        // install default reports, also update
        $default_reportbeez = array('report_event_log');
        $installed_modules = array();
        foreach ($default_reportbeez as $idx => $class) {
            if (file_exists(mh_cfg('MH_DIR_REPORT') . $class . mh_cfg('MH_FILE_EXTENSION'))) {
                include_once(mh_cfg('MH_DIR_REPORT') . $class . mh_cfg('MH_FILE_EXTENSION'));
                $module = new $class;
                $module->install();
                $installed_modules[] = $class . mh_cfg('MH_FILE_EXTENSION');
            }
        }

        mh_insert_config_value(array('configuration_title' => 'Installed Modules',
            'configuration_key' => 'MAILBEEZ_REPORT_INSTALLED',
            'configuration_value' => implode(';', $installed_modules),
            'configuration_description' => 'This is automatically updated. No need to edit.',
            'set_function' => ''
        ), true);

        /*
        if (MH_PLATFORM == 'xtc' || MH_PLATFORM == 'gambio') {
            $query_raw = "select * from " . TABLE_CONFIGURATION . " where configuration_key like 'MAILBEEZ_%_TITLE' or configuration_key like 'MAILBEEZ_%_DESC'";
            $query = mh_db_query($query_raw);
            while ($item = mh_db_fetch_array($query)) {
                $data = array('configuration_key' => $item['configuration_key'] . '_DEPR');
                mh_db_perform(TABLE_CONFIGURATION, $data, 'update', "configuration_key='" . $item['configuration_key'] . "'");
            }
        }
        */

        if (!mh_cfg('MH_PLATFORM_GAMBIO_GX_CONFIGURATION')) {
            // update fieldtype of configuration_value to text like in zencart and oscommerce 2.3
            $field_info = mh_db_check_field_exists(TABLE_CONFIGURATION, 'configuration_value');
            if ($field_info['Type'] != 'text') {
                mh_db_query("ALTER TABLE " . TABLE_CONFIGURATION . " CHANGE configuration_value configuration_value TEXT");
            }
        }

        if (!mh_cfg('MH_PLATFORM_GAMBIO_GX_CONFIGURATION')) {
            // update fieldtype of set_function to text
            $field_info = mh_db_check_field_exists(TABLE_CONFIGURATION, 'set_function');
            if ($field_info['Type'] != 'text') {
                mh_db_query("ALTER TABLE " . TABLE_CONFIGURATION . " CHANGE set_function set_function TEXT");
            }
        }

        // make platform info available for mailhive.php
        mh_insert_config_value(array('configuration_title' => 'Detected Platform',
            'configuration_key' => 'MH_PLATFORM_STATIC',
            'configuration_value' => MH_PLATFORM,
            'configuration_description' => 'This is automatically updated. No need to edit.',
            'set_function' => ''
        ));

        if (MH_ID != MH_PLATFORM) {
            mh_insert_config_value(array('configuration_title' => 'Platform ID',
                'configuration_key' => 'MH_ID',
                'configuration_value' => MH_ID,
                'configuration_description' => 'This is automatically updated. No need to edit.',
                'set_function' => ''
            ));
        }


        mh_insert_config_value(array('configuration_title' => 'Activate Process Control',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_PROCESS_CONTROL',
            'configuration_value' => 'True',
            'configuration_description' => 'Choose False to deactivated Process Control',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Lock-Period',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_PROCESS_CONTROL_LOCK_PERIOD',
            'configuration_value' => '600',
            'configuration_description' => 'Lock-Period (sec)',
            'set_function' => ''
        ));


        mh_insert_config_value(array('configuration_title' => 'Show Emails when Sending',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_RUN_SHOW_EMAIL',
            'configuration_value' => 'True',
            'configuration_description' => 'Define if you would like to see the generated emails while sending',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Double Dot Bugfix',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_BUGFIX_1',
            'configuration_value' => 'False',
            'configuration_description' => 'In rare occasions a Dot in filenames is doubled, e.g. file.php becomes file..php, image.png becomes image..png. Try to fix this Bug?',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));


        if (MH_PLATFORM == 'zencart') {
            mh_insert_config_value(array('configuration_title' => 'Override Zencart Email Template System',
                'configuration_key' => 'MAILBEEZ_MAILHIVE_ZENCART_OVERRIDE',
                'configuration_value' => 'True',
                'configuration_description' => 'Do you want to override Zencarts Email Template System?',
                'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
            ));
        }


        // MailBeez V2.6

        mh_insert_config_value(array('configuration_title' => 'Opt-Out link behaviour',
            'configuration_key' => 'MAILBEEZ_CONFIG_OPTOUT_BEHAVIOUR',
            'configuration_value' => 'Module',
            'configuration_description' => 'Choose how the opt-out link should behave. A click blocks ',
            'set_function' => 'mh_cfg_select_option(array(\'Module\', \'Global\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'Newsletter Subscription Check',
            'configuration_key' => 'MAILBEEZ_CONFIG_CHECK_SUBSCRIPTION',
            'configuration_value' => 'False',
            'configuration_description' => 'Activate Newsletter Check for all Modules?',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));


        // MailBeez V2.6
        if (defined('WPOLS_PLUGINS_DIR')) {
            mh_insert_config_value(array('configuration_title' => 'Wordpress Page ID of WP Online Store',
                'configuration_key' => 'MAILBEEZ_MAILHIVE_WPOLS_PAGE_ID',
                'configuration_value' => '',
                'configuration_description' => 'Please enter the page ID of the page where you inserted [WP_online_store]',
                'set_function' => ''
            ));
        }

        // MailBeez V2.6


        if (version_compare(PHP_VERSION, '5.0.0', '<')) {
            mh_insert_config_value(array('configuration_title' => 'Select the Email Engine',
                'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE',
                'configuration_value' => 'Shop',
                'configuration_description' => 'Select which Email Engine to use.',
                'set_function' => 'mh_cfg_select_option(array(\'PHPMailer 2.0.4\', \'Shop\'), '
            ));
        } else {
            mh_insert_config_value(array('configuration_title' => 'Select the Email Engine',
                'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE',
                'configuration_value' => 'Shop',
                'configuration_description' => 'Select which Email Engine to use.',
                'set_function' => 'mh_cfg_select_option(array(\'PHPMailer 5.2.1\', \'Shop\'), '
            ));
        }


        mh_insert_config_value(array('configuration_title' => 'SMTP: Select Transport Method',
            'configuration_key' => 'MAILBEEZ_EMAIL_TRANSPORT',
            'configuration_value' => 'smtp',
            'configuration_description' => 'Select Transport Method - only for SMTP',
            'set_function' => 'mh_cfg_select_option(array(\'smtp\', \'sendmail\', \'mail\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'SMTP: Sendmail Path',
            'configuration_key' => 'MAILBEEZ_SENDMAIL_PATH',
            'configuration_value' => '/usr/sbin/sendmail',
            'configuration_description' => 'Sendmail Path - only for PHPMailer',
            'set_function' => ''
        ));

        // SMTP

        mh_insert_config_value(array('configuration_title' => 'SMTP: Smtp Authentication',
            'configuration_key' => 'MAILBEEZ_SMTP_AUTH',
            'configuration_value' => 'False',
            'configuration_description' => 'Use Smtp Authentication',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'SMTP: Smtp UserName',
            'configuration_key' => 'MAILBEEZ_SMTP_USERNAME',
            'configuration_value' => '',
            'configuration_description' => 'Smtp User name',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'SMTP: Smtp Password',
            'configuration_key' => 'MAILBEEZ_SMTP_PASSWORD',
            'configuration_value' => '',
            'configuration_description' => 'Smtp password',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'SMTP: Smtp Server',
            'configuration_key' => 'MAILBEEZ_SMTP_MAIN_SERVER',
            'configuration_value' => '',
            'configuration_description' => 'Smtp Server',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'SMTP: Smtp Backup Server',
            'configuration_key' => 'MAILBEEZ_SMTP_BACKUP_SERVER',
            'configuration_value' => '',
            'configuration_description' => 'Smtp Backup Server',
            'set_function' => ''
        ));

        mh_insert_config_value(array('SMTP: Smtp Security',
            'configuration_key' => 'MAILBEEZ_SMTP_SECURE',
            'configuration_value' => 'none',
            'configuration_description' => 'Select the smtp security',
            'set_function' => 'mh_cfg_select_option(array(\'none\',\'ssl\', \'tls\'), '
        ));

        mh_insert_config_value(array('SMTP: Smtp port',
            'configuration_key' => 'MAILBEEZ_SMTP_PORT',
            'configuration_value' => '25',
            'configuration_description' => 'Select the smtp port',
            'set_function' => ''
        ));

        if (!version_compare(PHP_VERSION, '5.0.0', '<')) {
            mh_insert_config_value(array('configuration_title' => 'SMTP DKIM Selector',
                'configuration_key' => 'MAILBEEZ_DKIM_SELECTOR',
                'configuration_value' => '',
                'configuration_description' => 'Used with DKIM DNS Resource Record',
                'set_function' => ''
            ));

            mh_insert_config_value(array('configuration_title' => 'SMTP DKIM Identity',
                'configuration_key' => 'MAILBEEZ_DKIM_IDENTIY',
                'configuration_value' => '',
                'configuration_description' => 'Used with DKIM DNS Resource Record
                                             <br />optional, in format of email address "you@yourdomain.com"',
                'set_function' => ''
            ));

            mh_insert_config_value(array('configuration_title' => 'SMTP DKIM Passphrase',
                'configuration_key' => 'MAILBEEZ_DKIM_PASSPHRASE',
                'configuration_value' => '',
                'configuration_description' => 'Used with DKIM DNS Resource Record',
                'set_function' => ''
            ));

            mh_insert_config_value(array('configuration_title' => 'SMTP DKIM Domain',
                'configuration_key' => 'MAILBEEZ_DKIM_DOMAIN',
                'configuration_value' => '',
                'configuration_description' => 'Used with DKIM DNS Resource Record
                                         <br />optional, in format of email address "you@yourdomain.com"',
                'set_function' => ''
            ));

            mh_insert_config_value(array('configuration_title' => 'SMTP DKIM Private',
                'configuration_key' => 'MAILBEEZ_DKIM_PRIVATE',
                'configuration_value' => '',
                'configuration_description' => 'Used with DKIM DNS Resource Record
                                         <br />optional, in format of email address "you@yourdomain.com"',
                'set_function' => ''
            ));
        }

        mh_insert_config_value(array('SMTP: TXT format only',
            'configuration_key' => 'MAILBEEZ_EMAIL_USE_TXT_ONLY',
            'configuration_value' => 'False',
            'configuration_description' => 'send emails only in txt',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));


        // MailBeez Analytics


        mh_insert_config_value(array('configuration_title' => 'Enable MailBeez Analytics',
            'configuration_key' => 'MAILBEEZ_ANALYTICS_STATUS',
            'configuration_value' => 'False',
            'configuration_description' => 'Do you want to enable MailBeez Analytics for Tracking of e.g. open rates, click rates',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Process MailBeez Analytics Information with every run of MailHive',
            'configuration_key' => 'MAILBEEZ_ANALYTICS_DO_RUN',
            'configuration_value' => 'True',
            'configuration_description' => 'If set to False you need to set up a dedicated cronjob or run the Module "Service Handler for MailBeez Analytics" manually',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Insert Tracking Pix automatically',
            'configuration_key' => 'MAILBEEZ_ANALYTICS_AUTOINSERT_PIX',
            'configuration_value' => 'True',
            'configuration_description' => 'If set to False you need to insert the Tracking Tag into your Main Template: <b>{$MAILBEEZ_TRACKER_PIX}</b>',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Real-Time open rates',
            'configuration_key' => 'MAILBEEZ_ANALYTICS_OPEN_RATES_AUTO',
            'configuration_value' => 'True',
            'configuration_description' => 'Update Openrates every 30sec. For high-load sites deactivate and use cronjob instead',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Add Click Tracking in txt Emails',
            'configuration_key' => 'MAILBEEZ_ANALYTICS_REWRITE_FORMAT',
            'configuration_value' => 'True',
            'configuration_description' => 'Rewrite Urls in txt format?',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'Google Analytics URL Rewrite Format',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_GA_REWRITE_FORMAT',
            'configuration_value' => 'True',
            'configuration_description' => 'Rewrite Urls in txt format?',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'Rows per Page',
            'configuration_key' => 'MAILBEEZ_ANALYTICS_SPLITPAGE_NUM',
            'configuration_value' => '50',
            'configuration_description' => 'Number of Datarows per Page',
            'set_function' => ''
        ));


        // bugfix
        mh_insert_config_value(array('configuration_key' => 'MAILBEEZ_CONFIG_DASHBOARD_START',
            'configuration_value' => 'home',
            'set_function' => 'mh_cfg_select_option(array(\'home\', \'mailbeez\', \'configbeez\', \'filterbeez\', \'reportbeez\'), '
        ), true);


        // coupon tracking
        $sql = array();
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD coupon_id INT(11) ;";
        mh_db_add_field(TABLE_MAILBEEZ_TRACKING, 'coupon_id', $sql);
        $sql = array();
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD coupon_redeemed INT(5) NOT NULL DEFAULT '0' ;";
        mh_db_add_field(TABLE_MAILBEEZ_TRACKING, 'coupon_redeemed', $sql);
        // add index, check if index is already there
        if (!mh_db_check_index_on_column_exists(TABLE_MAILBEEZ_TRACKING, 'message_id')) {
            mh_db_query("ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD INDEX ( message_id )");
        }


        // MailBeez V2.7
        mh_insert_config_value(array('configuration_title' => 'Encode Email Subject',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENCODE_SUBJECT',
            'configuration_value' => 'False',
            'configuration_description' => 'Avoid strange characters showing up in subject lines',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));


        // MailBeez V2.7.4
        mh_insert_config_value(array('configuration_title' => 'Convert CSS into inline style',
            'configuration_key' => 'MAILBEEZ_CONFIG_TEMPLATE_ENGINE_EMOGRIFY',
            'configuration_value' => 'True',
            'configuration_description' => 'For best layouts across different email clients set to True. Requires PHP5.',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Set PHPMailer Debug Mode',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE_DEBUG_MODE',
            'configuration_value' => 'False',
            'configuration_description' => 'Activate Debug Mode for PHPMailer',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'TXT Wordwrap',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE_WORDWRAP',
            'configuration_value' => '80',
            'configuration_description' => 'Sets word wrapping on the body of the message to a given number of characters. Set to 0 for disabling wordwrapping.',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'Email Encoding',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE_ENCODING',
            'configuration_value' => '',
            'configuration_description' => 'Set the encoding for emails. Leave empty for automatic encoding detection. Values are e.g. "UTF-8", "ISO-8859-1"',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'PHP Memory Limit',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_PROCESS_CONTROL_MEMORY_LIMIT',
            'configuration_value' => '1024M',
            'configuration_description' => 'Set the PHP memory limit for the sending process, default 1024M',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'Set Ignore User Abort',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_PROCESS_CONTROL_INGORE_USER_ABORT',
            'configuration_value' => 'True',
            'configuration_description' => 'Sets whether a client disconnect should cause a script to be aborted. Default: True',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'PHP Execution Time Limit',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_PROCESS_CONTROL_TIME_LIMIT',
            'configuration_value' => '600',
            'configuration_description' => 'Set the PHP executing time limit. Default: 600sec',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'Disable DB Systemcheck',
            'configuration_key' => 'MH_SYSTEMCHECK_DB_DISABLED',
            'configuration_value' => 'False',
            'configuration_description' => 'Disable check for DB Issues. Default: False',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'Beginning of Time',
            'configuration_key' => 'MAILBEEZ_ANALYTICS_BEGIN_OF_TIME',
            'configuration_value' => '2000-01-01 00:00:00',
            'configuration_description' => 'Set the Beginning of Time for MailBeez Analytics Summary. Should be the date you started tracking orders. Default: 2000-01-01 00:00:00'));


        // add index, check if index is already there
        if (!mh_db_check_index_on_column_exists(TABLE_ORDERS, 'orders_status')) {
            mh_db_query("ALTER TABLE " . TABLE_ORDERS . " ADD INDEX ( orders_status )");
        }
        // add index, check if index is already there
        if (!mh_db_check_index_on_column_exists(TABLE_ORDERS, 'customers_id')) {
            mh_db_query("ALTER TABLE " . TABLE_ORDERS . " ADD INDEX ( customers_id )");
        }
        // add index, check if index is already there
        if (!mh_db_check_index_on_column_exists(TABLE_ORDERS_STATUS_HISTORY, 'orders_status_id')) {
            mh_db_query("ALTER TABLE " . TABLE_ORDERS_STATUS_HISTORY . " ADD INDEX ( orders_status_id )");
        }
        // add index, check if index is already there
        if (!mh_db_check_index_on_column_exists(TABLE_ORDERS_STATUS_HISTORY, 'orders_id')) {
            mh_db_query("ALTER TABLE " . TABLE_ORDERS_STATUS_HISTORY . " ADD INDEX ( orders_id )");
        }
        // add index, check if index is already there
        if (!mh_db_check_index_on_column_exists(TABLE_MAILBEEZ_EVENT_LOG, 'batch_id')) {
            mh_db_query("ALTER TABLE " . TABLE_MAILBEEZ_EVENT_LOG . " ADD INDEX ( batch_id )");
        }


        // V2.81
        // add index, check if index is already there
        if (!mh_db_check_index_on_column_exists(TABLE_MAILBEEZ_TRACKING, 'module')) {
            mh_db_query("ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD INDEX ( module )");
        }

        if (!mh_db_check_field_exists(TABLE_MAILBEEZ_TRACKING, 'mobile')) {
            // V2.8.6
            // mobile user agent analytics
            $sql = array();
            $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD mobile INT( 1 ) DEFAULT '0';";
            $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD INDEX ( mobile ) ;";
            mh_db_add_field(TABLE_MAILBEEZ_TRACKING, 'mobile', $sql);

            // add index, check if index is already there
            if (!mh_db_check_index_on_column_exists(TABLE_MAILBEEZ_OPENS_LOG, 'user_agent')) {
                mh_db_query("ALTER TABLE " . TABLE_MAILBEEZ_OPENS_LOG . " ADD INDEX ( user_agent )");
            }
        }

        if ($this->check() && (float)mh_cfg('MAILBEEZ_VERSION') < 2.94) {
            require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/mailbeez_analytics.php');

            // update historic data
            // from now the mobile information will be updated when user opens an email
            // see clicktracker -> import_log_file()

            $mobile_sql = "update " . TABLE_MAILBEEZ_TRACKING . " t
                            inner join " . TABLE_MAILBEEZ_OPENS_LOG . " o on (t.message_id = o.message_id)
                        set t.mobile = 1
                        where o.user_agent REGEXP '" . mailbeez_analytics::MOBILE_REGEX1 . "' or
                            SUBSTRING(o.user_agent,0,4)  REGEXP '" . mailbeez_analytics::MOBILE_REGEX1 . "'";
            mh_db_query($mobile_sql);
        }


        //V2.9.7 - Newsletter2Go
        if (version_compare(PHP_VERSION, '5.0.0', '<')) {
            mh_insert_config_value(array('configuration_title' => 'Select the Email Engine',
                'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE',
                'configuration_value' => mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE', 'Shop'),
                'configuration_description' => 'Select which Email Engine to use.',
                'set_function' => 'mh_cfg_select_option(array(\'Shop\', \'Newsletter2Go\', \'PHPMailer 2.0.4\'), '
            ), true);
        } else {
            mh_insert_config_value(array('configuration_title' => 'Select the Email Engine',
                'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE',
                'configuration_value' => mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE', 'Shop'),
                'configuration_description' => 'Select which Email Engine to use.',
                'set_function' => 'mh_cfg_select_option(array(\'Shop\', \'Newsletter2Go\', \'PHPMailer 5.2.1\'), '
            ), true);
        }


        mh_insert_config_value(array('configuration_title' => 'Newsletter2Go Apikey',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_KEY',
            'configuration_value' => '',
            'configuration_description' => 'Insert your Newsletter2Go Apikey'
        ));


        // Watchdog
        mh_insert_config_value(array('configuration_title' => 'Watchdog',
            'configuration_key' => 'MAILBEEZ_WATCHDOG_STATUS',
            'configuration_value' => 'False',
            'configuration_description' => 'Set the status of MailBeez Watchdog. Default: True',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Kill time limit',
            'configuration_key' => 'MAILBEEZ_WATCHDOG_LIMIT_KILL',
            'configuration_value' => '120',
            'configuration_description' => 'Kill queries after this number of seconds'
        ));

        // V2.9.9-2 - Testmail sender address: support for mail accounts where username and email address are not the same
        mh_insert_config_value(array('configuration_title' => 'SMTP: Smtp Sender',
            'configuration_key' => 'MAILBEEZ_SMTP_SENDER',
            'configuration_value' => '',
            'configuration_description' => 'Smtp Sender',
            'set_function' => ''
        ));

        if (!mh_db_check_index_on_column_exists(TABLE_ORDERS, 'customers_id')) {
            mh_db_query("ALTER TABLE " . TABLE_ORDERS . " ADD INDEX ( customers_id )");
        }

        if (!mh_db_check_index_on_column_exists(TABLE_MAILBEEZ_BLOCK, 'module')) {
            mh_db_query("ALTER TABLE " . TABLE_MAILBEEZ_BLOCK . " ADD INDEX ( module )");
        }

        if (!mh_db_check_index_on_column_exists(TABLE_CUSTOMERS, 'customers_newsletter')) {
            mh_db_query("ALTER TABLE " . TABLE_CUSTOMERS . " ADD INDEX ( customers_newsletter )");
        }

        // PHPMailer update
        mh_insert_config_value(array('configuration_title' => 'Select the Email Engine',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE',
            'configuration_value' => mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE', 'Shop'),
            'configuration_description' => 'Select which Email Engine to use.',
            'set_function' => 'mh_cfg_select_option_titled(array(\'Shop\', \'Newsletter2Go\', \'PHPMailer\'), array(array(\'Shop\', 0), array(\'Newsletter2Go\', 1), array(\'SMTP\'), 0), ',
            'use_function' => 'configbeez->config_email_engine->show_engine_name',
        ), true);

        if (!mh_cfg('MH_PLATFORM_GAMBIO_GX_CONFIGURATION')) {
            mh_db_query("update " . TABLE_CONFIGURATION . " set configuration_value = 'PHPMailer', last_modified = now() where configuration_key = 'MAILBEEZ_CONFIG_EMAIL_ENGINE' and configuration_value like 'PHPMailer %'");
        }

        // add Piwik
        mh_insert_config_value(array('configuration_title' => 'Piwik Analytics Integration',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_PIWIK_ENABLED',
            'configuration_value' => 'False',
            'configuration_description' => 'Globally enable Piwik Analytics Integration',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Piwik Analytics URL Rewrite Mode',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_PIWIK_REWRITE_MODE',
            'configuration_value' => 'all',
            'configuration_description' => 'Globally set Piwik Analytics URL Rewrite Mode',
            'set_function' => 'mh_cfg_select_option(array(\'all\', \'shop\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'Piwik Analytics URL Rewrite Format',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_PIWIK_REWRITE_FORMAT',
            'configuration_value' => 'True',
            'configuration_description' => 'Rewrite Urls in txt format?',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Piwik Analytics Campaign',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_PIWIK_CAMPAIGN',
            'configuration_value' => 'MailBeez',
            'configuration_description' => 'Choose how you would like to name the Campaign (default: MailBeez)',
            'set_function' => ''
        ));

        // add Econda
        mh_insert_config_value(array('configuration_title' => 'Econda Analytics Integration',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_ECONDA_ENABLED',
            'configuration_value' => 'False',
            'configuration_description' => 'Globally enable Econda Analytics Integration',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Econda Analytics URL Rewrite Mode',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_ECONDA_REWRITE_MODE',
            'configuration_value' => 'all',
            'configuration_description' => 'Globally set Econda Analytics URL Rewrite Mode',
            'set_function' => 'mh_cfg_select_option(array(\'all\', \'shop\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'Econda Analytics URL Rewrite Format',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_ECONDA_REWRITE_FORMAT',
            'configuration_value' => 'True',
            'configuration_description' => 'Rewrite Urls in txt format?',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Econda Analytics Campaign',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_ECONDA_CAMPAIGN',
            'configuration_value' => 'MailBeez',
            'configuration_description' => 'Choose how you would like to name the Campaign (default: MailBeez)',
            'set_function' => ''
        ));


        // add Custom Url Parameter
        mh_insert_config_value(array('configuration_title' => 'Custom URL Parameter',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_ANALYTICS_CUSTOM_ENABLED',
            'configuration_value' => 'False',
            'configuration_description' => 'enable',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'URL Rewrite Mode',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_ANALYTICS_CUSTOM_REWRITE_MODE',
            'configuration_value' => 'all',
            'configuration_description' => 'Globally set Piwik Analytics URL Rewrite Mode',
            'set_function' => 'mh_cfg_select_option(array(\'all\', \'shop\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'Rewrite Format',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_ANALYTICS_CUSTOM_REWRITE_FORMAT',
            'configuration_value' => 'True',
            'configuration_description' => 'Rewrite Urls in txt format?',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Parameter String',
            'configuration_key' => 'MAILBEEZ_MAILHIVE_ANALYTICS_CUSTOM_PARAMETER',
            'configuration_value' => 'a=b&c=d',
            'configuration_description' => 'Parameter string without leading separator, e.g. "a=b&c=d"',
            'set_function' => ''
        ));




        mh_insert_config_value(array('configuration_title' => 'Information for reporting abuse',
            'configuration_key' => 'MAILBEEZ_SMTP_ABUSE_INFO',
            'configuration_value' => 'Please report abuse of this email server',
            'configuration_description' => 'Used for headers X-Abuse-Info, X-Report',
            'set_function' => ''
        ));


        mh_insert_config_value(array('configuration_title' => 'E-mail address for reporting abuse',
            'configuration_key' => 'MAILBEEZ_SMTP_ABUSE_EMAIL_ADDRESS',
            'configuration_value' => (mh_cfg('MAILBEEZ_EMAIL_ABUSE_ADDRESS')) ? mh_cfg('MAILBEEZ_EMAIL_ABUSE_ADDRESS') : mh_cfg('STORE_OWNER_EMAIL_ADDRESS'),
            'configuration_description' => 'Used for headers X-Report-Abuse-To, Abuse-Reports-To, X-Complaints-To',
            'set_function' => ''
        ));


        // breaks html code when active
        mh_insert_config_value(array('configuration_title' => 'disable this filtermodule',
            'configuration_key' => 'MAILBEEZ_FILTER_LAYOUT_OPTIMIZER_STATUS',
            'configuration_value' => False,
        ), true);


        // MAILBEEZ_ADD_HEADER_REPLY_TO
        mh_insert_config_value(array('configuration_title' => 'SMTP: Add reply-to Header',
            'configuration_key' => 'MAILBEEZ_ADD_HEADER_REPLY_TO',
            'configuration_value' => 'False',
            'configuration_description' => 'Add reply-to header when sending using an SMTP Server',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'Automation in Simulation mode',
            'configuration_key' => 'MAILBEEZ_CONFIG_SIMULATION_ENABLE_AUTOMATION',
            'configuration_value' => 'False',
            'configuration_description' => 'enable automation in simulation mode',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'Total Module for Revenue Calculation',
            'configuration_key' => 'MAILBEEZ_ANALYTICS_SUBTOTAL_MODULE',
            'configuration_value' => 'ot_subtotal',
            'configuration_description' => 'Select the order total module for calculation revenue',
            'set_function' => 'configbeez->config_analytics->list_modules',
        ));


        // only happens when v1, check if api v1 is used, otherwise switch to v2
        mh_insert_config_value(array('configuration_title' => 'N2Go API Version',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_VERSION',
            'configuration_value' => ((preg_match('/Newsletter2Go/', mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE')) || (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_KEY') != '')) ? 'v1' : 'v2'),
            'configuration_description' => 'Select, which API Version to use',
            'set_function' => 'mh_cfg_select_option(array(\'v1\', \'v2\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'N2Go API V2 authKey',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_V2_AUTH_KEY',
            'configuration_value' => '',
            'configuration_description' => 'authKey',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'N2Go API V2 accessToken',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_V2_ACCESS_TOKEN',
            'configuration_value' => '',
            'configuration_description' => 'accessToken',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'N2Go API V2 refreshToken',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_V2_REFRESH_TOKEN',
            'configuration_value' => '',
            'configuration_description' => 'refreshToken',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'N2Go API V2 Campaign Data',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_V2_LIST_ID',
            'configuration_value' => '',
            'configuration_description' => 'list id',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'N2Go API V2 Campaign Data',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_V2_CAMPAIGN_DATA',
            'configuration_value' => '[]',
            'configuration_description' => 'campaign Data',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'N2Go API V2 Domains Data',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_V2_DOMAINS_DATA',
            'configuration_value' => '[]',
            'configuration_description' => 'domains Data',
            'set_function' => ''
        ));


        mh_insert_config_value(array('configuration_title' => 'N2Go Debug Mode',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_DEBUG_MODE',
            'configuration_value' => 'False',
            'configuration_description' => 'Activate Debug Mode for N2Go',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));


        // add index, check if index is already there
        if (!mh_db_check_index_on_column_exists(TABLE_MAILBEEZ_TRACKING, 'ordered')) {
            mh_db_query("ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD INDEX ( ordered )");
        }

        // add index, check if index is already there
        if (!mh_db_check_index_on_column_exists(TABLE_MAILBEEZ_TRACKING, 'customers_email_bounce_status')) {
            mh_db_query("ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD INDEX customers_email_bounce_status ( customers_email, bounce_status )");
        }


        // mailbeez shortener
        mh_db_query("CREATE TABLE IF NOT EXISTS " . DB_PREFIX . "mailbeez_shrtnr_idx (
                token VARCHAR( 32 ) NOT NULL,
                shrtnr_value TEXT,
                date_added DATETIME DEFAULT NULL,
                last_read DATETIME DEFAULT NULL,
				PRIMARY KEY ( token ) );");

        if (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_VERSION') == 'v1') {
            mh_update_config_value(array('configuration_title' => 'N2Go API Version',
                'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_VERSION',
                'configuration_value' => ((preg_match('/Newsletter2Go/', mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE')) && (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_KEY') != '')) ? 'v1' : 'v2'),
            ));
        }


        // updates
        // keep legacy cache path
        mh_insert_config_value(array('configuration_title' => 'Root for image engine Cache',
            'configuration_key' => 'MAILBEEZ_CONFIG_IMAGE_ENGINE_CACHE_DIR',
            'configuration_value' => MH_ROOT_PATH . 'images/cache',
            'configuration_description' => 'relativ to store root - empty: default'
        ));


        // install default configbeez also update
        $default_configbeez = array('config_tour');
        $installed_modules = array();
        foreach ($default_configbeez as $idx => $class) {
            if (file_exists(MH_DIR_CONFIG . $class . MH_FILE_EXTENSION)) {
                include_once(MH_DIR_CONFIG . $class . MH_FILE_EXTENSION);
                $module = new $class;
                $module->install();
                $installed_modules[] = $class . MH_FILE_EXTENSION;
            }
        }


        // support insecure server certificates
        // https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting#php-56-certificate-verification-failure
        mh_insert_config_value(array('configuration_title' => 'Allow insecure connections',
            'configuration_key' => 'MAILBEEZ_SMTP_DISABLE_SSL_VERIFICATION',
            'configuration_value' => 'False',
            'configuration_description' => 'Allow insecure SMTP connections',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        // preview settings

        mh_insert_config_value(array('configuration_title' => 'preview firstname',
            'configuration_key' => 'MAILBEEZ_PREVIEW_FIRSTNAME',
            'configuration_value' => 'TestFirstName',
            'configuration_description' => 'preview firstname',
            'set_function' => ''
        ));
        mh_insert_config_value(array('configuration_title' => 'preview lastname',
            'configuration_key' => 'MAILBEEZ_PREVIEW_LASTNAME',
            'configuration_value' => 'TestLastName',
            'configuration_description' => 'preview lastname',
            'set_function' => ''
        ));
        mh_insert_config_value(array('configuration_title' => 'preview customer id',
            'configuration_key' => 'MAILBEEZ_PREVIEW_CUSTOMERS_ID',
            'configuration_value' => '42',
            'configuration_description' => 'preview customer id',
            'set_function' => ''
        ));
        mh_insert_config_value(array('configuration_title' => 'preview order id',
            'configuration_key' => 'MAILBEEZ_PREVIEW_ORDERS_ID',
            'configuration_value' => '4242',
            'configuration_description' => 'preview order id',
            'set_function' => ''
        ));
        mh_insert_config_value(array('configuration_title' => 'N2Go API V2 Secret',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_V2_SECRET',
            'configuration_value' => md5(date('Y-m-d H:i:s')),
            'configuration_description' => 'N2Go API V2 Secret',
            'set_function' => ''
        ));

        // add index, check if index is already there
        if (!mh_db_check_index_on_column_exists(TABLE_CUSTOMERS_BASKET, 'customers_id')) {
            mh_db_query("ALTER TABLE " . TABLE_CUSTOMERS_BASKET . "  ADD INDEX customers_id (customers_id)");
        }


        $product_ids = array();
        $update_product_ids = false;
        if (!mh_cfg('MAILBEEZ_PREVIEW_PRODUCT_IDS') || !(stristr(mh_cfg('MAILBEEZ_PREVIEW_PRODUCT_IDS'), ','))) {
            // select 10 random products for testing
            $query_products_raw = "SELECT p.products_id FROM " . TABLE_PRODUCTS . " p WHERE p.products_status = '1' ORDER BY RAND() LIMIT 10";
            $query_products = mh_db_query($query_products_raw);

            while ($products_item = mh_db_fetch_array($query_products)) {
                $product_ids[] = $products_item['products_id'];
            }
            $update_product_ids = true;
        }

        mh_insert_config_value(array('configuration_title' => 'Product Id for testing',
            'configuration_key' => 'MAILBEEZ_PREVIEW_PRODUCT_IDS',
            'configuration_value' => implode(',', $product_ids),
            'configuration_description' => 'list of product IDs e.g "42,123,99',
            'set_function' => ''
        ), $update_product_ids);


        // introducing workers
        $sql = array();
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_PROCESS . " ADD worker_id int(32) default 1 AFTER batch_id ;";
        mh_db_add_field(TABLE_MAILBEEZ_PROCESS, 'worker_id', $sql);


        // add index, check if index is already there
        if (!mh_db_check_index_on_column_exists(TABLE_MAILBEEZ_TRACKING, 'date_sent')) {
            mh_db_query("ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD INDEX ( date_sent )");
        }

        // add index, check if index is already there
        if (!mh_db_check_index_on_column_exists(TABLE_MAILBEEZ_TRACKING, 'iteration')) {
            mh_db_query("ALTER TABLE " . TABLE_MAILBEEZ_TRACKING . " ADD INDEX ( iteration )");
        }


        // fix gambio 4.2
        if (mh_cfg('MH_PLATFORM_GAMBIO_GX_CONFIGURATION')) {
//            mh_db_query("delete from `gx_configurations` where `key` like 'configuration/CLOUDLOADER_%'");
        }


        // removing configuration option
        mh_insert_config_value(array('configuration_key' => 'MAILBEEZ_MAILHIVE_EARLY_CHECK_ENABLED',
            'configuration_value' => 'True'
        ), true);


        // Adding MailBeez Email Delivery System
        mh_insert_config_value(array('configuration_title' => 'Select the Email Engine',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE',
            'configuration_value' => mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE', 'Shop'),
            'configuration_description' => 'Select which Email Engine to use.',
            'set_function' => 'mh_cfg_select_option_titled(array(\'Shop\', \'mlbz_ubvx\', \'mlbz_hysndr\', \'PHPMailer\', \'Newsletter2Go\'), array(array(\'Shop\', 0), array(\'MailBeez.Email V4\', 0), array(\'MailBeez.Email\', 1), array(\'SMTP\'), 0), ',
            'use_function' => 'configbeez->config_email_engine->show_engine_name',
        ), true);


        mh_insert_config_value(array('configuration_title' => 'Set MailBeez.Email Debug Mode',
            'configuration_key' => 'MAILBEEZ_CONFIG_EMAIL_ENGINE_MLBZ_DEBUG_MODE',
            'configuration_value' => 'False',
            'configuration_description' => 'Activate Debug Mode for MailBeez.Email',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'MailBeez.Email old: Smtp UserName',
            'configuration_key' => 'MAILBEEZ_MLBZ_UBVX_USERNAME',
            'configuration_value' => '',
            'configuration_description' => 'Username',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'MailBeez.Email old: Smtp Password',
            'configuration_key' => 'MAILBEEZ_MLBZ_UBVX_PASSWORD',
            'configuration_value' => '',
            'configuration_description' => 'Password',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'MailBeez.Email: Smtp UserName',
            'configuration_key' => 'MAILBEEZ_MLBZ_HYSNDR_USERNAME',
            'configuration_value' => '',
            'configuration_description' => 'Username',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'MailBeez.Email: Smtp Password',
            'configuration_key' => 'MAILBEEZ_MLBZ_HYSNDR_PASSWORD',
            'configuration_value' => '',
            'configuration_description' => 'Password',
            'set_function' => ''
        ));


        mh_insert_config_value(array('configuration_title' => 'MailBeez.Email ESP webhook token',
            'configuration_key' => 'MAILBEEZ_MLBZ_ESP_WEBHOOK_TOKEN',
            'configuration_value' => mh_cfg('MAILBEEZ_MLBZ_ESP_WEBHOOK_TOKEN', ''),
            'configuration_description' => 'Token used to validate incoming ESP webhook requests',
            'set_function' => ''
        ), true);

        mh_insert_config_value(array('configuration_title' => 'Softbounce: Delay',
            'configuration_key' => 'MAILBEEZ_MLBZ_BOUNCE_SOFT_DAYS',
            'configuration_value' => '5',
            'configuration_description' => 'how many days to wait before trying again to send an email to a softbounced email-address',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'Softbounce: Convert into Hardbounce Count',
            'configuration_key' => 'MAILBEEZ_MLBZ_BOUNCE_SOFT_HARD_COUNT',
            'configuration_value' => '5',
            'configuration_description' => 'After this number a softbounce becomes a hardbounce',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'Softbounce: Convert into Hardbounce Timeframe',
            'configuration_key' => 'MAILBEEZ_MLBZ_BOUNCE_SOFT_HARD_COUNT_DAYS',
            'configuration_value' => '60',
            'configuration_description' => 'the number of configured softbounces appeared in within this number of days',
            'set_function' => ''
        ));


        mh_insert_config_value(array('configuration_title' => 'Beez UI',
            'configuration_key' => 'MAILBEEZ_CONFIG_BEEZ_UI',
            'configuration_value' => 'False',
            'configuration_description' => 'Activate Beez UI - MailBeez V5',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));


        mh_delete_config_value('MAILBEEZ_CONFIG_BEEZ_UI_DATA');

        
        // bounce handling
        $sql = array();
        $sql[] = "ALTER TABLE " . TABLE_MAILBEEZ_BOUNCE . " ADD reference VARCHAR( 40 ) DEFAULT NULL ;";
        mh_db_add_field(TABLE_MAILBEEZ_BOUNCE, 'reference', $sql);


//        if ( 'mlbz_ubvx' == mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE') && $installed_version < 4.509) {
        // clean up
//        }

        // mailbeez lock
        mh_db_query("CREATE TABLE IF NOT EXISTS " . DB_PREFIX . "mailbeez_lock (
                lock_key varchar(36) not null,
                owner varchar(128) default null,
                expiration int not null,
				PRIMARY KEY ( lock_key ) ,
				INDEX (expiration )
				);");

        mh_db_query("CREATE TABLE IF NOT EXISTS " . TABLE_MAILBEEZ_ESP_EVENTS . " (
                id INT NOT NULL AUTO_INCREMENT,
                provider VARCHAR(32) NOT NULL,
                provider_event_id VARCHAR(128) DEFAULT NULL,
                provider_message_id VARCHAR(128) DEFAULT NULL,
                mailbeez_message_id VARCHAR(255) DEFAULT NULL,
                autoemail_id INT DEFAULT NULL,
                event_hash CHAR(64) NOT NULL,
                event_type VARCHAR(32) NOT NULL,
                event_time DATETIME NOT NULL,
                recipient_email VARCHAR(255) NOT NULL,
                severity VARCHAR(32) NOT NULL,
                bounce_type VARCHAR(1) DEFAULT NULL,
                bounce_code VARCHAR(32) DEFAULT NULL,
                reason TEXT,
                url TEXT,
                process_status VARCHAR(24) NOT NULL DEFAULT 'pending',
                process_error TEXT DEFAULT NULL,
                processed_at DATETIME DEFAULT NULL,
                raw_payload MEDIUMTEXT NOT NULL,
                created_at DATETIME NOT NULL,
                PRIMARY KEY (id),
                UNIQUE KEY uniq_event_hash (event_hash),
                KEY provider_message_id (provider, provider_message_id),
                KEY mailbeez_message_id (mailbeez_message_id),
                KEY autoemail_id (autoemail_id),
                KEY recipient_email (recipient_email),
                KEY event_type_time (event_type, event_time)
                );");

        mh_db_query("CREATE TABLE IF NOT EXISTS " . TABLE_MAILBEEZ_ESP_MESSAGE_STATE . " (
                autoemail_id INT NOT NULL,
                mailbeez_message_id VARCHAR(255) NOT NULL,
                provider VARCHAR(32) NOT NULL,
                provider_message_id VARCHAR(128) DEFAULT NULL,
                status VARCHAR(32) NOT NULL,
                last_event_type VARCHAR(32) NOT NULL,
                last_event_time DATETIME NOT NULL,
                last_reason TEXT,
                attempt_count INT NOT NULL DEFAULT 0,
                soft_bounce_count INT NOT NULL DEFAULT 0,
                hard_bounce_count INT NOT NULL DEFAULT 0,
                complaint_count INT NOT NULL DEFAULT 0,
                unsubscribe_count INT NOT NULL DEFAULT 0,
                open_count INT NOT NULL DEFAULT 0,
                click_count INT NOT NULL DEFAULT 0,
                updated_at DATETIME NOT NULL,
                PRIMARY KEY (autoemail_id),
                KEY mailbeez_message_id (mailbeez_message_id),
                KEY provider_message_id (provider, provider_message_id),
                KEY status (status)
                );");

        mh_db_query("CREATE TABLE IF NOT EXISTS " . TABLE_MAILBEEZ_ESP_MESSAGE_MAP . " (
                provider VARCHAR(32) NOT NULL,
                provider_message_id VARCHAR(128) NOT NULL,
                mailbeez_message_id VARCHAR(255) NOT NULL,
                autoemail_id INT DEFAULT NULL,
                recipient_email VARCHAR(255) DEFAULT NULL,
                date_created DATETIME NOT NULL,
                PRIMARY KEY (provider, provider_message_id),
                KEY mailbeez_message_id (mailbeez_message_id),
                KEY autoemail_id (autoemail_id),
                KEY recipient_email (recipient_email)
                );");

        // unified flow HTML cache
        mh_db_query("CREATE TABLE IF NOT EXISTS " . DB_PREFIX . "mailbeez_flow_cache (
                owner_type VARCHAR(32) NOT NULL,
                owner_id VARCHAR(191) NOT NULL,
                lang VARCHAR(16) NOT NULL,
                flow_html MEDIUMTEXT,
                updated_at DATETIME NOT NULL DEFAULT '1000-01-01 00:00:00',
				PRIMARY KEY ( owner_type, owner_id, lang ),
				INDEX ( owner_type, owner_id )
				);");



        // data fix
        if (mh_cfg('MAILBEEZ_VERSION') < 4.923) {
            mh_db_query("UPDATE " . TABLE_MAILBEEZ_BLOCK . " SET simulation = 0 WHERE module = 'ALL' AND simulation = 1;");
        }

        // 4.9605 - Invalidate all legacy flow caches (no legacy read fallback)
        if ((float)$installed_version < 4.9702) {
            // Legacy module flow cache in mailbeez_module_configuration
            if (mh_db_check_table_exists(TABLE_MAILBEEZ_MODULE_CONFIGURATION)) {
                mh_db_query("DELETE FROM " . TABLE_MAILBEEZ_MODULE_CONFIGURATION . " WHERE cfg_key LIKE '%_flow_html%'");
            }

            // Legacy per-row JSON caches
            if (mh_db_check_table_exists(DB_PREFIX . "mailbeez_newsletter_items")
                && mh_db_check_field_exists(DB_PREFIX . "mailbeez_newsletter_items", 'newsletter_item_meta')) {
                mh_db_query("UPDATE " . DB_PREFIX . "mailbeez_newsletter_items SET newsletter_item_meta = NULL");
            }
            if (mh_db_check_table_exists(DB_PREFIX . "mailbeez_newsletter_lists")
                && mh_db_check_field_exists(DB_PREFIX . "mailbeez_newsletter_lists", 'newsletter_list_meta')) {
                mh_db_query("UPDATE " . DB_PREFIX . "mailbeez_newsletter_lists SET newsletter_list_meta = NULL");
            }

            // Start new unified cache table from a clean state
            if (mh_db_check_table_exists(DB_PREFIX . "mailbeez_flow_cache")) {
                mh_db_query("DELETE FROM " . DB_PREFIX . "mailbeez_flow_cache");
            }
        }

        // 4.9605 - Invalidate all legacy flow caches (no legacy read fallback)
        if ((float)$installed_version < 4.9800) {
            // Start new unified cache table from a clean state
            if (mh_db_check_table_exists(DB_PREFIX . "mailbeez_flow_cache")) {
                mh_db_query("DELETE FROM " . DB_PREFIX . "mailbeez_flow_cache");
            }
        }

// owner is unused - only for reference
//        if ($this->check() && (float)mh_cfg('MAILBEEZ_VERSION') < 4.8024) {
//            mh_db_query("ALTER TABLE " . mailbeez_lock . " CHANGE owner owner varchar(128) default null");
//        }

        // update version - last thing after everything was updated
        mh_insert_config_value(array('configuration_key' => 'MAILBEEZ_VERSION',
            'configuration_value' => $this->version
        ), true);

        mh_insert_config_value(array('configuration_key' => 'MAILBEEZ_VERSION_DISPLAY',
            'configuration_value' => $this->version_display
        ), true);


        // clear caches
        // todo: generic solution
        $this->remove_legacy_files();
        mh_version_core_check_refresh();
        unset($_SESSION['mh_tour_cnt']);

        // redirect
        if (mh_cfg('MAILBEEZ_VERSION') && (str_replace(',', '.', mh_cfg('MAILBEEZ_VERSION')) < $this->version)) {
            // updated
            mh_redirect(mh_href_link(mh_fn('FILENAME_MAILBEEZ'), 'action=config_update_ok&tab=home'));
        } else {
            mh_redirect(mh_href_link(mh_fn('FILENAME_MAILBEEZ'), 'tab=home'));
        }
    }

    private function remove_legacy_files()
    {
        if (!defined('MH_DIR_APP')) {
            return;
        }

        $files = [
            'newsletter_campaign_modal.php',
            'newsletter_campaigns_list.php',
            'flows_collections.php',
            'flows_layout_list.php',
            'flows_layout_tiles.php',
            'newsletter_list_delete.php',
            'newsletter_list_modal.php',
            'newsletter_lists.php'
        ];

        foreach ($files as $file) {
            $path = MH_DIR_APP . 'pages/components/' . $file;
            if (file_exists($path)) {
                @unlink($path);
            }
        }
    }

}
