<?php
// define('STRICT_ERROR_REPORTING', true); // zencart
//error_reporting(E_ALL & ~E_NOTICE);
if (isset($_GET['module'])) {
    // the module parameter can contain characters like / which are filtered out e.g. on zencart 1.5.5
    $_GET['module'] = $_REQUEST['module']; // restore original value
}
if (isset($_POST) && is_array($_POST)) {
    // fix behaviour of zencart 1.5.5
    foreach ($_POST as $k => $v) {
        $_POST[$k] = $_REQUEST[$k]; // restore original value
    }
}


error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
ini_set('display_errors', 1);


if (!defined('MH_ROOT_PATH')) {
    define('MH_ROOT_PATH', 'mailhive/');
}

require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/compatibility.php');
$request_profiler->restart('top_load_compatibility');


require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/query_watchdog.php');

require_once(MH_DIR_CONFIG . 'config_cloudbeez.php');


//if (!defined('MAILBEEZ_MAILHIVE_STATUS') || (int) mh_get_conf('MAILBEEZ_VERSION') < 2) {
if (!mh_template_check_writeable()) {
    echo mh_lng('MAILBEEZ_INSTALL_WARNING_TEMPLATE_C');
    exit();
}
//}


// moved to cloudbeez_status_handler

if (mh_get('cloudloader_done') == 'ok') {
    unset($_SESSION['cloudbeez_purchase']);
    unset($_SESSION['cache_cloudbeez_status_handler_time']);
    unset($_SESSION['cache_cloudbeez_status_handler']);

    mh_storage_destroy('subscription_check_result');
    mh_storage_destroy('subscription_check_result_subscription_info');

    $_SESSION['cloudloader_refresh_connection'] = true;
    if (mh_beezui()) {
        cloudbeez_status_handler::getStatus();
        mh_redirect(mh_href_link(FILENAME_MAILBEEZ, ''));
    }
}



if (mh_get('cloudbeez_purchase') == 'ok') {
    // redirect after purchase detected

    if (mh_get('clbk')) {
        mh_insert_config_value(array(
            'configuration_key' => 'CLOUDLOADER_API_KEY',
            'configuration_value' => mh_get('clbk')
        ), true);
    }


    $_SESSION['cloudbeez_purchase'] = true;

    // redirect to get rid of url parameters
    mh_redirect(mh_href_link(FILENAME_MAILBEEZ, ''));

}


// include the modules language translations
// load language file for modules.php
if (MH_PLATFORM == 'zencart') {
    $current_page = basename(FILENAME_MODULES . '.php');
    if (file_exists(DIR_WS_LANGUAGES . $_SESSION['language'] . '/' . $current_page)) {
        include(DIR_WS_LANGUAGES . $_SESSION['language'] . '/' . $current_page);
    }
} elseif (MH_PLATFORM == 'xtc' || MH_PLATFORM == 'gambio') {
    $current_page = basename(FILENAME_MODULES);
    if (file_exists(DIR_FS_LANGUAGES . $_SESSION['language'] . '/admin/' . $current_page)) {
        include(DIR_FS_LANGUAGES . $_SESSION['language'] . '/admin/' . $current_page);
    }
} elseif (defined('MH_PLATFORM_OSC_WPOS')) {
    // WP online store
    if (file_exists(MH_DIR_FS_CATALOG . DIR_WS_INCLUDES . DIR_WS_LANGUAGES . $_SESSION['language'] . '/' . FILENAME_MODULES)) {
        include(MH_DIR_FS_CATALOG . DIR_WS_INCLUDES . DIR_WS_LANGUAGES . $_SESSION['language'] . '/' . FILENAME_MODULES);
    }

} else {
    if (file_exists(DIR_WS_LANGUAGES . $_SESSION['language'] . '/' . FILENAME_MODULES)) {
        include(DIR_WS_LANGUAGES . $_SESSION['language'] . '/' . FILENAME_MODULES);
    }
}

$watchdog_killed = false;
$watchdog = new query_watchdog();
$watchdog_killed = $watchdog->watch();


$request_profiler->restart('top_load_languages');

$set = mh_get('set', '');

$module_type = '';


$trustpilot_evaluate = (isset($trustpilot_evaluate)) ? $trustpilot_evaluate
    : 'http://www.trustpilot.com/evaluate/www.mailbeez.com';

$app_action = mh_get('action', '');

$custom_app_include = '';
$config_cache_detected = false;
$config_cache_refreshed = false;
$config_updated = false;
$default_action = '';
if (file_exists(MH_DIR_CONFIG . 'config_queen.php')) {
    if (!mh_class_exists('config_queen')) {
        include_once(MH_DIR_CONFIG . 'config_queen.php');
        $config = new config_queen();
    }
} else {
    echo "fatal error: can't find config_queen.php";
}

if (file_exists(MH_DIR_CONFIG . 'config_template_selector.php')) {
    include_once(MH_DIR_CONFIG . 'config_template_selector.php');
}


if (mh_not_null($app_action)) {
    $config_cache_detected = mh_reset_config_cache();

    if ($config_cache_detected == true) {
        $default_action .= '&action=update_cache';
    }

    switch ($app_action) {
        case 'save':
            foreach (mh_post('configuration') as $key => $value) {
                if (is_array($value)) {
                    $value = implode(", ", $value);
                    $value = preg_replace("/, --none--/", "", $value);
                }
                mh_update_config_value(
                    array(
                        'configuration_key' => $key,
                        'configuration_value' => mh_add_magic_slashes($value)
                    )
                );

            }


            $class = basename(mh_get('module'));
            if (file_exists(MH_DIR_MODULE . $class . MH_FILE_EXTENSION)) {
                include_once(MH_DIR_MODULE . $class . MH_FILE_EXTENSION);
            } elseif (file_exists(MH_DIR_CONFIG . $class . MH_FILE_EXTENSION)) {
                include_once(MH_DIR_CONFIG . $class . MH_FILE_EXTENSION);
            } elseif (file_exists(MH_DIR_FILTER . $class . MH_FILE_EXTENSION)) {
                include_once(MH_DIR_FILTER . $class . MH_FILE_EXTENSION);
            } elseif (file_exists(MH_DIR_REPORT . $class . MH_FILE_EXTENSION)) {
                include_once(MH_DIR_REPORT . $class . MH_FILE_EXTENSION);
            } elseif (file_exists(MH_DIR_DASHBOARD . $class . MH_FILE_EXTENSION)) {
                include_once(MH_DIR_DASHBOARD . $class . MH_FILE_EXTENSION);
            }

            if (mh_class_exists($class)) {
                $module = new $class;
                if ($module->on_cfg_save_clear_template_c == true) {
                    mh_smarty_clear_compile_dir();
                }
                $module->onSave();
            }

            mh_redirect(mh_href_link(mh_fn('FILENAME_MAILBEEZ'), 'set=' . $set . '&module=' . mh_get('module') . $default_action));
            break;
        case 'install':
        case 'remove':
            if (isset($PHP_SELF) && $PHP_SELF != '') {
                // oscommerce, zencart
                $file_extension = substr($PHP_SELF, strrpos($PHP_SELF, '.'));
            } else {
                // xtc
                $file_extension = substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'], '.'));
            }

            $class = basename(mh_get('module'));
            if (file_exists(MH_DIR_MODULE . $class . MH_FILE_EXTENSION)) {
                include_once(MH_DIR_MODULE . $class . MH_FILE_EXTENSION);
            } elseif (file_exists(MH_DIR_CONFIG . $class . MH_FILE_EXTENSION)) {
                include_once(MH_DIR_CONFIG . $class . MH_FILE_EXTENSION);
            } elseif (file_exists(MH_DIR_FILTER . $class . MH_FILE_EXTENSION)) {
                include_once(MH_DIR_FILTER . $class . MH_FILE_EXTENSION);
            } elseif (file_exists(MH_DIR_REPORT . $class . MH_FILE_EXTENSION)) {
                include_once(MH_DIR_REPORT . $class . MH_FILE_EXTENSION);
            } elseif (file_exists(MH_DIR_DASHBOARD . $class . MH_FILE_EXTENSION)) {
                include_once(MH_DIR_DASHBOARD . $class . MH_FILE_EXTENSION);
            }

            if (mh_class_exists($class)) {
                $module = new $class;
                if ($app_action == 'install') {
                    $module->install();
                } elseif ($app_action == 'remove') {
                    $module->remove();
                }
            }
            mh_redirect(mh_href_link(FILENAME_MAILBEEZ, 'set=' . $set . '&module=' . $class . $default_action));
            break;
        case 'update_cache':
            // reload to make updated cache visible
            mh_redirect(mh_href_link(FILENAME_MAILBEEZ, 'set=' . $set . '&module=' . mh_get('module') . '&action=config_cache_refreshed'));
            break;
        case 'config_cache_refreshed':
            // show message
            $config_cache_refreshed = true;
            break;
        case 'config_update_ok':
            // show message
            $config_updated = true;
            break;
    }
}

$request_profiler->restart('top_after_actions');

$tab = mh_cfg('MAILBEEZ_CONFIG_DASHBOARD_START', 'home');
$tab_mode = 'config';

// tab control

//$_GET['module'] = (isset($_GET['module'])) ? $_GET['module'] : '';

$current_module = mh_get('module', '');

if (mh_get('tab')) {
    $tab = mh_get('tab');
} elseif (preg_match('/^config/', $current_module)) {
    $tab = 'configbeez';
} elseif (preg_match('/^filter/', $current_module)) {
    $tab = 'filterbeez';
} elseif (preg_match('/^report/', $current_module)) {
    $tab = 'reportbeez';
} elseif (preg_match('/^dashboard/', $current_module)) {
    $tab = 'dashboardbeez';
} elseif (mh_get('module', '') != '') {
    $tab = 'mailbeez';
}

$tab_mode = mh_get('tab_mode', $tab_mode);


// set modul paths
switch ($tab) {
    case 'mailbeez':
        mh_define('MH_MODULE_DIRECTORY_CURRENT', MH_DIR_MODULE);
        mh_define('MH_MODULE_DIRECTORY_CURRENT_WS', MH_MODULE_DIRECTORY_WS);

        $appRequest = array(
            'MH_MODULE_KEY_CURRENT' => 'MAILBEEZ_INSTALLED',
            'MH_MODULE_VERSION_KEY_CURRENT' => 'MAILBEEZ_INSTALLED_VERSIONS',
        );

        break;
    case 'configbeez':
        mh_define('MH_MODULE_DIRECTORY_CURRENT', MH_DIR_CONFIG);
        mh_define('MH_MODULE_DIRECTORY_CURRENT_WS', MH_CONFIG_MODULE_DIRECTORY_WS);

        $appRequest = array(
            'MH_MODULE_KEY_CURRENT' => 'MAILBEEZ_CONFIG_INSTALLED',
            'MH_MODULE_VERSION_KEY_CURRENT' => 'MAILBEEZ_CONFIG_INSTALLED_VERSIONS',
        );
        break;
    case 'filterbeez':
        mh_define('MH_MODULE_DIRECTORY_CURRENT', MH_DIR_FILTER);
        mh_define('MH_MODULE_DIRECTORY_CURRENT_WS', MH_FILTER_MODULE_DIRECTORY_WS);

        $appRequest = array(
            'MH_MODULE_KEY_CURRENT' => 'MAILBEEZ_FILTER_INSTALLED',
            'MH_MODULE_VERSION_KEY_CURRENT' => 'MAILBEEZ_FILTER_INSTALLED_VERSIONS',
        );
        break;
    case 'reportbeez':
        mh_define('MH_MODULE_DIRECTORY_CURRENT', MH_DIR_REPORT);
        mh_define('MH_MODULE_DIRECTORY_CURRENT_WS', MH_REPORT_MODULE_DIRECTORY_WS);

        $appRequest = array(
            'MH_MODULE_KEY_CURRENT' => 'MAILBEEZ_REPORT_INSTALLED',
            'MH_MODULE_VERSION_KEY_CURRENT' => 'MAILBEEZ_REPORT_INSTALLED_VERSIONS',
        );
        break;
    case 'dashboardbeez':
    case 'home':

        mh_define('MH_MODULE_DIRECTORY_CURRENT', MH_DIR_DASHBOARD);
        mh_define('MH_MODULE_DIRECTORY_CURRENT_WS', MH_DASHBOARD_MODULE_DIRECTORY_WS);

        $appRequest = array(
            'MH_MODULE_KEY_CURRENT' => 'MAILBEEZ_DASHBOARD_INSTALLED',
            'MH_MODULE_VERSION_KEY_CURRENT' => 'MAILBEEZ_DASHBOARD_INSTALLED_VERSIONS',
        );
        break;
}

// Expose current keys as constants for easier cross-context access (legacy + BeezUI)
if (isset($appRequest['MH_MODULE_KEY_CURRENT'])) {
    mh_define('MH_MODULE_KEY_CURRENT', $appRequest['MH_MODULE_KEY_CURRENT']);
}
if (isset($appRequest['MH_MODULE_VERSION_KEY_CURRENT'])) {
    mh_define('MH_MODULE_VERSION_KEY_CURRENT', $appRequest['MH_MODULE_VERSION_KEY_CURRENT']);
}

mh_define('MH_DIR_CURRENT', mh_cfg('MH_MODULE_DIRECTORY_CURRENT'));
// Filesystem root for the Beez UI
if (!defined('BEEZUI_ROOT')) {
    define('BEEZUI_ROOT', MH_DIR_APP);
    mh_define('DEFAULT_LANGUAGE_ID', mh_session('languages_id', 1));
}

// BEEZUI class autoloader
if (phpversion() >= '7.4') {
    spl_autoload_register(function ($class) {
        $prefix = 'Components\\';
        if (strpos($class, $prefix) === 0) {
            $file = BEEZUI_ROOT . 'components/' . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php';
            if (is_file($file)) {
                require_once $file;
            } else {
                dd('spl_autoload_register Class not found: ' . $class);
            }
        }
    });
}

require_once BEEZUI_ROOT . '/components/Legacy/LegacyRouter.php';
require_once BEEZUI_ROOT . '/components/Legacy/legacy_routes.php';


if (mh_beezui()) {

    // load language definitions
    if (isset($_SESSION['language']) && $_SESSION['language'] != 'english') {
        $lang_file = BEEZUI_ROOT . 'languages/' . $_SESSION['language'] . '.php';
        if (file_exists($lang_file)) {
            include($lang_file);
        }
    }
    $fallback_file = BEEZUI_ROOT . 'languages/english.php';
    if (file_exists($fallback_file)) {
        include($fallback_file);
    }

    @ini_set('display_errors', '1');
    @ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);



    // Web path prefix for static assets when running via admin/mailbeez.php
    if (!defined('BEEZUI_WEB_ROOT')) {
        define('BEEZUI_WEB_ROOT', '../' . MH_ROOT_PATH . MH_DIR_BEEZUI);
    }
    // Integration mode: ensure all in-app links route through the admin entrypoint as well
    if (!defined('BEEZUI_ENTRYPOINT')) {
        define('BEEZUI_ENTRYPOINT', 'mailbeez.php?main=1');
    }
    define('BEEZ_UI_DEV', false);



    // bypass MailBeez V5 for legacy urls
    if (mh_get('app') == 'load_app') {
        mh_define('MH_BYPASS_MAILBEEZ_V5', true);
        if (!mh_get('popup') && !(
            mh_get('dashboard_action') == 'load' ||
            mh_get('dashboard_action') == 'refresh' ||
            mh_get('panel_action') == 'load' ||
            mh_get('panel_action') == 'refresh' ||
            stristr(mh_get('app_path'), 'ajax.php') ||
            stristr(mh_get('app_path'), 'run_observer.php')

            )) {

            mh_define('MH_POPUP', true);
        }
    }
    if (phpversion() < 7.4) {
        mh_define('MH_BYPASS_MAILBEEZ_V5', true);
    }


    mh_define('MH_BYPASS_MAILBEEZ_V5', false);
}



$app_include = mh_get('app');
if ($app_include == 'load_app') {
    $custom_app_include = (mh_get('app_path')) ? str_replace('%2F', '/', mh_get('app_path')) : '';
    if (mh_get('module')) {
        $class = basename(mh_get('module'));
        mh_load_modules_language_files(MH_MODULE_DIRECTORY_CURRENT, $class);
    }
}

$request_profiler->restart('top_after_load_apps');


if (!function_exists('sortbyintvalue')) {
    function sortbyintvalue($a, $b)
    {
        $aint = (int)$a;
        $bint = (int)$b;

        //echo "$aint $bint<br>";

        if ($aint == $bint)
            $r = 0;
        if ($aint < $bint)
            $r = -1;
        if ($aint > $bint)
            $r = 1;
        return $r;
    }
}

if (!mh_beezui() ) {

if (mh_cfg('MAILBEEZ_MAILHIVE_MODE') == 'simulate') {
    $messageStack->reset();
    $messageStack->add(mh_lng('WARNING_SIMULATE'), 'warning');
    mh_setDefaultMessage($messageStack);
}

if (mh_cfg('MAILBEEZ_MAILHIVE_STATUS') == 'False') {
    $messageStack->reset();
    //$messageStack->add(WARNING_OFFLINE, 'warning');
    mh_setDefaultMessage($messageStack);
}
if ($config_cache_refreshed == true) {
    $messageStack->add('config cache refreshed', 'success');
    mh_setDefaultMessage($messageStack);
}

if ($config_updated == true) {
    $messageStack->add('MailBeez updated!', 'success');
    mh_setDefaultMessage($messageStack);
}
}


if ($watchdog_killed == true) {

    $messageStack->add($watchdog_killed, 'warning');
    mh_setDefaultMessage($messageStack);
}


mh_update_reminder_timestamp();

$request_profiler->restart('top_before_smarty');

$smarty_admin = new mh_Smarty;


$smarty_admin->setTemplateDir(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/templates/');
$smarty_admin->setCompileId('admin_main' . $_SESSION['language']);

$request_profiler->restart('top_before_load_header');
$ADMIN_TEMPLATE_TOP = '';
if (MH_PLATFORM_OSC_23 || MH_PLATFORM_OSC_PHOENIX) {
    ob_start();
    require(DIR_WS_INCLUDES . 'template_top.php');
    $ADMIN_TEMPLATE_TOP = ob_get_contents();
    ob_end_clean();
}

if (!(mh_saas() && mh_beezui())) {
    ob_start();
    require(DIR_WS_INCLUDES . 'header.php');
    $request_profiler->restart('top_after_load_header');
    $ADMIN_HEADER = ob_get_contents();
    ob_end_clean();
}


if (mh_cfg('MH_PLATFORM') != 'zencart' && mh_cfg('MH_PLATFORM') != 'digistore' && !mh_cfg('MH_PLATFORM_OSC_23') && !mh_cfg('MH_PLATFORM_OSC_PHOENIX') && !mh_cfg('MH_PLATFORM_XTC_ECB') && !(mh_cfg('USE_ADMIN_TOP_MENU') == 'true') && !(mh_saas() && mh_beezui())) {
    // USE_ADMIN_TOP_MENU according Ticket RAO-AWKUS-336
    // no column left
    ob_start();
    require(DIR_WS_INCLUDES . 'column_left.php');
    $ADMIN_COLUMN_LEFT = ob_get_contents();
    ob_end_clean();
}
$request_profiler->restart('top_after_load_column_left');


$smarty_admin->assign(array('trustpilot_evaluate' => $trustpilot_evaluate));
$smarty_admin->assign(array('MH_CATALOG_URL' => MH_CATALOG_SERVER . MH_DIR_WS_CATALOG,
    'MH_ROOT_PATH' => MH_ROOT_PATH,
    'MH_ADMIN_DIR_WS_IMAGES' => MH_ADMIN_DIR_WS_IMAGES,
    'MH_RATE_TRUSTPILOT_LINK' => MH_RATE_TRUSTPILOT_LINK));
$smarty_admin->assign(array('SHOW_HBND' => ($_SESSION['language'] == 'german') ? true : false));
$smarty_admin->assign(array('SHOW_HBND_EN' => ($_SESSION['language'] != 'german') ? true : false));
$MAILBEEZ_FOOTER = $smarty_admin->fetch('main_footer.tpl'); // smarty template
ob_start();
$MAILBEEZ_TABS_MODE = '';

if (!mh_cfg('MAILBEEZ_MAILHIVE_STATUS')) {
    // install screen
    $MAILBEEZ_TABS = '';
    require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/install.php');
} else {
    // start of admin screen main area
    // $_GET['module']
    if ($custom_app_include != '') {
        // load custom application

        if (file_exists(MH_DIR_FS_CATALOG . MH_ROOT_PATH . $custom_app_include)) {
            require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . $custom_app_include);
        } else {
            if (preg_match('/^common/', $custom_app_include)) {
                require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . '' . $custom_app_include);
            } elseif (preg_match('/^config/', $custom_app_include)) {
                require_once(MH_DIR_CONFIG . $custom_app_include);
            } elseif (preg_match('/^filter/', $custom_app_include)) {
                require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'filterbeez/' . $custom_app_include);
            } elseif (preg_match('/^report/', $custom_app_include)) {
                require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'reportbeez/' . $custom_app_include);
            } elseif (preg_match('/^dashboard/', $custom_app_include)) {
                require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'dashboardbeez/' . $custom_app_include);
            } else {
                require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'mailbeez/' . $custom_app_include);
            }
        }

    } elseif (!mh_beezui()) {


        switch ($tab) {
            case 'mailbeez':
                $MAILBEEZ_TABS = mh_tabs(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/tabs.php', $tab);
                $MAILBEEZ_TABS_MODE = mh_tabs(MH_DIR_CONFIG . 'config_modules_visual/admin_action_plugins/tabs_mode.php', $tab_mode);
                require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/main_mailbeez_modules.php');
                break;

            case 'configbeez':
            case 'filterbeez':
            case 'reportbeez':
                $MAILBEEZ_TABS = mh_tabs(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/tabs.php', $tab);
                require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/main_mailbeez.php');
                break;
            case 'dashboardbeez':
                $MAILBEEZ_TABS = mh_tabs(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/back_dashboardbeez.php', $tab);
                require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/main_mailbeez.php');
                break;

            case 'about':
                $MAILBEEZ_TABS = mh_tabs(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/tabs.php', $tab);
                require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/main_mailbeez_' . $tab . '.php');
                break;
            default:
                $MAILBEEZ_TABS = mh_tabs(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/tabs.php', $tab);
                require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/main_mailbeez_' . $tab . '.php');
                break;
        }
    }
}

$MAILBEEZ_MAIN_CONTENT = ob_get_contents();;
ob_end_clean();
$ADMIN_FOOTER = '';
if (!mh_cfg('MH_PLATFORM_OSC_23')) {

    ob_start();
    if ($app_include != '') {
        mh_define('MAILBEEZ_CUSTOMER_INSIGHT_LOADED', true);
    }

    require(DIR_WS_INCLUDES . 'footer.php');
    $ADMIN_FOOTER = ob_get_contents();
    ob_end_clean();
}

$request_profiler->restart('top_after_load_footer');


ob_start();
if (mh_cfg('MAILBEEZ_MAILHIVE_STATUS')) {
    if ($app_include == '') {
// autoload customer insight if available but not installed
        if (!mh_cfg('MAILBEEZ_CUSTOMER_INSIGHT_LOADED')) {
            mh_define('MAILBEEZ_CUSTOMER_INSIGHT_NOT_INSTALLED', true);
            if (file_exists(MH_DIR_CONFIG . 'config_customer_insight/includes/admin_footer_include.php')) {
                require(MH_DIR_CONFIG . 'config_customer_insight/includes/admin_footer_include.php');
            }
        }
    }
}

$ADMIN_FOOTER_INSIGHT_CODE = ob_get_contents();
ob_end_clean();


$ADMIN_TEMPLATE_BOTTOM = '';
if (MH_PLATFORM_OSC_23) {
    ob_start();
    require(DIR_WS_INCLUDES . 'template_bottom.php');
    $ADMIN_TEMPLATE_BOTTOM = ob_get_contents();
    ob_end_clean();
    $ADMIN_TEMPLATE_BOTTOM .= $ADMIN_FOOTER_INSIGHT_CODE;
} else {
    $ADMIN_FOOTER .= $ADMIN_FOOTER_INSIGHT_CODE;
}


$request_profiler->restart('top_after_load_application_bottom');
$changelogBox = mh_saas() ? '' : mh_admin_modal(mh_language_documentation_url('https://www.mailbeez.com/documentation/changelog'), mh_lng('MH_CHANGELOG_TEXT', 'changelog'), 760, null, false);

$beezUiVersion = (phpversion() < 7.4) ? ' (PHP7.4+)' : '';


$switchV5 = mb_admin_button(mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=common/admin_application_plugins/switch_v5.php'), mh_lng('MAILBEEZ_SWITCH_V5_BUTTON', 'MailBeez V5 Preview') .  $beezUiVersion, '', 'link', 'link', '', 'document', '', '_self');

$smarty_admin->assign(array('MAILBEEZ_MAILHIVE_POPUP_MODE' => mh_cfg('MAILBEEZ_MAILHIVE_POPUP_MODE'),
    'MAILBEEZ_MAILHIVE_STATUS' => mh_cfg('MAILBEEZ_MAILHIVE_STATUS'),
    'HTML_PARAMS' => mh_cfg('HTML_PARAMS'),
    'TITLE' => mh_cfg('TITLE'),
    'HEADING_TITLE' => mh_cfg('MH_HEADING_TITLE'),
    'MAILBEEZ_VERSION' => mh_cfg('MAILBEEZ_VERSION_DISPLAY'),
    'MAILBEEZ_VERSION_CHECK_URL' => mh_cfg('MAILBEEZ_VERSION_CHECK_URL'),
    'MAILBEEZ_MAILHIVE_MODE' => mh_cfg('MAILBEEZ_MAILHIVE_MODE'),
    'MAILBEEZ_MAILHIVE_MODE_TEXT' => (mh_cfg('MAILBEEZ_MAILHIVE_MODE') == 'simulate')
        ? mh_cfg('MAILBEEZ_MODE_SET_SIMULATE_TEXT') : mh_cfg('MAILBEEZ_MODE_SET_PRODUCTION_TEXT'),
    'MAILBEEZ_MAILHIVE_MODE_SWITCH_TEXT' => mh_cfg('MAILBEEZ_MAILHIVE_MODE_SWITCH_TEXT'),
    'MAILBEEZ_MAILHIVE_MODE_SWITCH_URL' => mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=common/admin_application_plugins/toggle_mode.php'),
    'MAILBEEZ_CIS_URL' => mh_cfg('MH_CIS_URL'),
    'MAILBEEZ_MAILHIVE_MODE_SIM_RESTART' => mb_admin_button(mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=config_simulation/admin_application_plugins/simulation_restart.php&app_action=restart&popup=true'), mh_lng('MAILBEEZ_MAILHIVE_MODE_SIM_RESTART_BUTTON'), '', 'popup', 'link', '', 'document', 'iframe width:300 height:200'),


    'MAILBEEZ_MAILHIVE_ADMIN_RIGHTS_TITLE' => mh_lng('MH_HEADING_ADMIN_RIGHTS_TITLE'),

    'MAILBEEZ_MAILHIVE_CLOUDLOADER_UPDATE_CORE' => false,
    'MAILBEEZ_CHANGELOG_BOX' => $changelogBox,
    'MAILBEEZ_SWITCH_V5' => $switchV5
));

$show_update_core = mh_session('mh_version_core_check');

if ($show_update_core) {
    if ((mh_session('mh_version_core_check') > mh_cfg('MAILBEEZ_VERSION'))) {
        $new_version = mh_session('mh_version_core_check');
        $smarty_admin->assign('MAILBEEZ_MAILHIVE_CLOUDLOADER_UPDATE_CORE', mb_admin_button(mh_href_link(FILENAME_MAILBEEZ, 'cloudloader_mode=update_core'), sprintf(mh_lng('MAILBEEZ_MAILHIVE_CLOUDLOADER_UPDATE_CORE_BUTTON'), $new_version), '', 'popup', 'link', '', 'document', 'iframe', '_top'));
    } else {
        // somehow the session value was not cleared during update
        mh_version_core_check_refresh();
    }
}

$MAILBEEZ_UPDATE_REMINDER = false;
if (mh_cfg('MAILBEEZ_MAILHIVE_UPDATE_REMINDER') == 'True' && mh_cfg('MAILBEEZ_MAILHIVE_UPDATE_REMINDER_TIMESTAMP') < time()) {
    // fire updatereminder
    $MAILBEEZ_UPDATE_REMINDER = true;
}

$smarty_admin->assign(array('MAILBEEZ_FOOTER' => $MAILBEEZ_FOOTER));

ob_start();

// loaded6 compatiblity
if (method_exists($messageStack, 'tableBoxMessagestack')) {
    echo $messageStack->output('class="messageBox"');
} else {
    echo $messageStack->output();
}

$MESSAGE_STACK = ob_get_contents();
ob_end_clean();

$smarty_admin->assign(array('MESSAGE_STACK' => $MESSAGE_STACK));

list($MAILBEEZ_MAILHIVE_ADMIN_RIGHTS, $MAILBEEZ_MAILHIVE_ADMIN_RIGHTS_OTHER_VALUES) = mh_check_admin_rights_hook('mailhive', 'mailhive', 'main_common_content');

$smarty_admin->assign(array('MAILBEEZ_MAIN_CONTENT' => $MAILBEEZ_MAIN_CONTENT,
        'ADMIN_TEMPLATE_TOP' => $ADMIN_TEMPLATE_TOP ?? '',
        'ADMIN_TEMPLATE_BOTTOM' => $ADMIN_TEMPLATE_BOTTOM ?? '',
        'MAILBEEZ_VERSION_CHECK_BUTTON' => mb_admin_button(mh_cfg('MAILBEEZ_VERSION_CHECK_URL'), mh_cfg('MH_BUTTON_VERSION_CHECK'), 'mbUpd'),
        'ADMIN_BOX_WIDTH' => mh_cfg('BOX_WIDTH'),
        'ADMIN_HEADER' => $ADMIN_HEADER ?? '',
        'ADMIN_COLUMN_LEFT' => $ADMIN_COLUMN_LEFT ?? '',
        'ADMIN_PAGE_HEADING_SEPARATOR' => mh_draw_separator('pixel_trans.gif', mh_cfg('HEADING_IMAGE_HEIGHT'), 1),
        'ADMIN_FOOTER' => $ADMIN_FOOTER ?? '',
        'GAMBIO_SCREEN' => mh_session('screen_width', ''),
        'SESSION_CHARSET' => mh_session('language_charset', mh_cfg('CHARSET')),
        'GAMBIO_COUNTER_ACTION_LINK' => mh_href_link('gm_counter_action.php'),
        'MH_PLATFORM_XTCMODIFIED' => MH_PLATFORM_XTCM,
        'MAILBEEZ_MAILHIVE_ADMIN_RIGHTS' => $MAILBEEZ_MAILHIVE_ADMIN_RIGHTS,
        'BEEZ_UI' => mh_cfg('MAILBEEZ_CONFIG_BEEZ_UI'),
        'BYPASS_BEEZ_UI' => mh_cfg('MH_BYPASS_MAILBEEZ_V5'),
    )
);

$admin_template = 'main_osc.tpl';
$admin_template_popup = 'popup.tpl';
mh_define('MH_BYPASS_TEMPLATE', false); // might have been set in admin_application_plugins
mh_define('MH_POPUP', false); // might have been set in admin_application_plugins
mh_define('MH_POP_EXCLUDE_SHOPCSS', false); // might have been set in admin_application_plugins
mh_define('MH_POP_EXCLUDE_MAINCSS', false); // might have been set in admin_application_plugins
mh_define('MH_POP_EXCLUDE_MAINSTYLE', false); // might have been set in admin_application_plugins
mh_define('MH_POP_EXCLUDE_COMMONLIBS', false); // might have been set in admin_application_plugins
mh_define('MH_POP_INCLUDE_BOOTSTRAP', false); // might have been set in admin_application_plugins

$_MH_ADMIN_CSS_DIR = 'includes/'; // dir to e.g. stylesheet.css
$_MH_ADMIN_JS_DIR = 'includes/'; // dir to e.g. general.js

$custom_app_main = '';
if (defined('MAILBEEZ_APP_CUSTOM_MAIN')) {
    $custom_app_main = MH_DIR_FS_CATALOG . MH_ROOT_PATH . MAILBEEZ_APP_CUSTOM_MAIN;
}


if (defined('MAILBEEZ_APP_CUSTOM_MAIN') && file_exists($custom_app_main) && is_file($custom_app_main)) {
    require_once($custom_app_main);
} else {
    switch (MH_PLATFORM) {
        case 'oscommerce':
            if (MH_PLATFORM_OSC_23) {
                $admin_template = 'main_osc23.tpl';
            }
            if (MH_PLATFORM_OSCMAX_25) {
                $admin_template = 'main_oscmax25.tpl';
            }
            if (MH_PLATFORM_OSC_PHOENIX) {
                $admin_template = 'main_oscphoenix_1_0.tpl';
            }
            if (MH_PLATFORM_TRUELOADED) {
                $admin_template = 'main_trueloaded.tpl';
            }
            break;
        case 'creloaded':


            if (mh_cfg('INSTALLED_VERSION_MAJOR') == 6 && mh_cfg('INSTALLED_VERSION_MINOR') == 2) {
                $admin_template = 'main_creloaded_62.tpl';
            } elseif (mh_cfg('INSTALLED_VERSION_MAJOR') == 6 && mh_cfg('INSTALLED_VERSION_MINOR') == 5 && mh_cfg('INSTALLED_PATCH') >= 3) {
                $admin_template = 'main_loaded6ce.tpl';
            } elseif (mh_cfg('INSTALLED_VERSION_MAJOR') == 6 && mh_cfg('INSTALLED_VERSION_MINOR') == 4) {
                $METATAGS = '';
                $BREADCRUMB = '';
                ob_start();
                require(DIR_WS_INCLUDES . 'toolbar.php');
                $TOOLBAR = ob_get_contents();
                ob_end_clean();
                $smarty_admin->assign(array('TOOLBAR' => $TOOLBAR));
                if (file_exists(DIR_WS_INCLUDES . 'meta_tags.php')) {
                    ob_start();
                    require(DIR_WS_INCLUDES . 'meta_tags.php');
                    $METATAGS = ob_get_contents();
                    ob_end_clean();
                }
                $smarty_admin->assign(array('METATAGS' => $METATAGS));
                if (file_exists(DIR_WS_INCLUDES . 'productbreadcrumb.php')) {
                    ob_start();
                    require(DIR_WS_INCLUDES . 'productbreadcrumb.php');
                    $BREADCRUMB = ob_get_contents();
                    ob_end_clean();
                }
                $smarty_admin->assign(array('BREADCRUMB' => $BREADCRUMB));

                $admin_template = 'main_creloaded_64.tpl';
            } elseif (mh_cfg('INSTALLED_VERSION_MAJOR') == 6 && mh_cfg('INSTALLED_VERSION_MINOR') == 5) {
                $admin_template = 'main_creloaded_65.tpl';
            } else {
                $admin_template = 'main_creloaded.tpl';
            }

            break;
        case 'digistore':
            $admin_template = 'main_digistore.tpl';
            break;
        case 'zencart':
            if ((float)MH_PLATFORM_ZENCART >= 2.0) {
                $admin_template = 'main_zc_2.tpl';
            } elseif ((float)MH_PLATFORM_ZENCART >= 1.56) {
                $admin_template = 'main_zc_156.tpl';
            } elseif ((float)MH_PLATFORM_ZENCART >= 1.55) {
                $admin_template = 'main_zc_155.tpl';
            } else {
                $admin_template = 'main_zc.tpl';
            }
            break;
        case 'mercari':
            $admin_template = 'main_mercari.tpl';
            ob_start();
            require(DIR_WS_INCLUDES . 'metatag.php');
            $MERCARI_METATAG = ob_get_contents();
            ob_end_clean();
            $smarty_admin->assign(array('MERCARI_METATAG' => $MERCARI_METATAG));
            break;
        case 'xtc':
            // if (MH_PLATFORM_XTCM) {}
            $admin_template = 'main_xtc.tpl';
            if (MH_PLATFORM_XTCM) {
                switch (MH_PLATFORM_XTC_XTCM_VERSION) {

                    case '2':
                        $admin_template = 'main_xtc_mod_v2.tpl';

                        ob_start();
                        require(DIR_WS_INCLUDES . 'head.php');
                        $box = isset($box) ? $box : false;

                        if (xtc_not_null($app_action) && !$box) {
                            echo '<link href="includes/css/module_box_full.css" rel="stylesheet" type="text/css" />';
                            if (isset($module_class) && file_exists('includes/css/' . basename($module_class) . '.css')) {
                                echo '<link href="includes/css/' . basename($module_class) . '.css" rel="stylesheet" type="text/css" />';
                            }
                        }
                        $MOD2_HEAD = ob_get_contents();
                        ob_end_clean();
                        $smarty_admin->assign(array('MOD2_HEAD' => $MOD2_HEAD));

                        break;
                    default:
                        $admin_template = 'main_xtc.tpl';
                        break;
                }

                if (!isset($xtPrice) || !is_object($xtPrice)) {
                    require_once (DIR_FS_CATALOG.'includes/classes/xtcPrice.php');
                    $xtPrice = new xtcPrice($_SESSION['currency'], $_SESSION['customers_status']['customers_status_id']);
                }

            }
            if (MH_PLATFORM_XTC_SEO) {

                switch (MH_PLATFORM_XTC_SEO_VERSION) {
                    case '2.1':
                        $admin_template = 'main_xtc_seo_v21.tpl';
                        break;
                    default:
                        $admin_template = 'main_xtc_seo.tpl';
                        break;
                }

                ob_start();
                require(DIR_WS_INCLUDES . 'metatag.php');
                $CSEO_METATAG = ob_get_contents();
                ob_end_clean();
                $smarty_admin->assign(array('CSEO_METATAG' => $CSEO_METATAG));
            }

            if (MH_PLATFORM_XTC_ECB) {
                $admin_template = 'main_xtc_ecb.tpl';
            }


            break;
        case 'gambio':
            if (MH_PLATFORM_GAMBIO == 1) {
                $admin_template = 'main_gambiogx.tpl';
            } elseif (MH_PLATFORM_GAMBIO >= 4.1) {
                $admin_template = 'main_gambiogx4_1.tpl';
                $_MH_ADMIN_CSS_DIR = 'html/assets/styles/legacy/';
                $_MH_ADMIN_JS_DIR = 'html/assets/javascript/legacy/gm/';


                // Add Mailbeez Permissions on GX
                if (class_exists('StaticGXCoreLoader')) {
                    $adminAccessService = StaticGXCoreLoader::getService('AdminAccess');


                    $identifier = new NonEmptyStringType('mailbeez.php');
                    try {
                        $adminAccessService->getGroupByPage($identifier);
                    } catch (\GroupNotFoundException $exception) {
                        unset($exception);

                        $moduleName = 'MailBeez';

                        try {
                            /** @var LanguagesReadService $langReadService */
                            $langReadService = StaticGXCoreLoader::getService('LanguagesRead');
                            $cfgLanguages = [];
                            foreach ($langReadService->getLanguages() as $langCode) {
                                $cfgLanguages[strtoupper($langCode->code())] = $moduleName;
                            }
                        } catch (\DomainException $exception) {
                            // backwards compatibility
                            $db = StaticGXCoreLoader::getDatabaseQueryBuilder();
                            $query = $db->select('languages_id, code')
                                ->get('languages')
                                ->result_array();
                            $languages = [];
                            /** @var array $query */
                            foreach ($query as $row) {
                                $cfgLanguages[strtoupper($row['code'])] = $moduleName;

                            }
                            unset($exception);
                        }


                        $name = new KeyValueCollection($cfgLanguages);

                        $description = new KeyValueCollection($cfgLanguages);

                        $parentGroup = new IdType(39);
                        $sortOrder = new IntType(100);

                        $createdGroup = $adminAccessService->createNewGroup(
                            $name,
                            $description,
                            $parentGroup,
                            $sortOrder
                        );

                        $roleId = new IdType(1);

                        $groupId = new IdType($createdGroup->getId());
                        $type = new NonEmptyStringType('PAGE');

                        $adminAccessService->addItemToGroup($groupId, $identifier, $type);

                        $adminAccessService
                            ->grantReadingPermissionToRole($groupId, $roleId)
                            ->grantWritingPermissionToRole($groupId, $roleId)
                            ->grantDeletingPermissionToRole($groupId, $roleId);
                    }

                }

            } elseif (MH_PLATFORM_GAMBIO >= 3.9) {
                $admin_template = 'main_gambiogx3_9.tpl';
                $_MH_ADMIN_CSS_DIR = 'html/assets/styles/legacy/';
                $_MH_ADMIN_JS_DIR = 'html/assets/javascript/legacy/gm/';
            } elseif (MH_PLATFORM_GAMBIO >= 3.7) {

//                $admin_template =  'main_gambiogx3_7.tpl';
                $admin_template = mh_saas() && mh_beezui() ? 'main_saas.tpl' : 'main_gambiogx3_7.tpl';
                $_MH_ADMIN_CSS_DIR = 'html/assets/styles/legacy/';
                $_MH_ADMIN_JS_DIR = 'html/assets/javascript/legacy/gm/';
            } elseif (MH_PLATFORM_GAMBIO >= 3.1) {
                $admin_template = 'main_gambiogx3_1.tpl';
                $_MH_ADMIN_CSS_DIR = 'styles/legacy/';
                $_MH_ADMIN_JS_DIR = 'javascript/legacy/gm/';
            } elseif (MH_PLATFORM_GAMBIO >= 2.6) {
                $admin_template = 'main_gambiogx2_6.tpl';
            } elseif (MH_PLATFORM_GAMBIO >= 2.1) {
                $admin_template = 'main_gambiogx2_1.tpl';
            } elseif (MH_PLATFORM_GAMBIO >= 2) {
                $admin_template = 'main_gambiogx2.tpl';
            }
            break;
        default:
    }
//dd(MH_PLATFORM_GAMBIO);
//dd($admin_template);
}
mh_define('MH_ADMIN_CSS_DIR', $_MH_ADMIN_CSS_DIR);
mh_define('MH_ADMIN_JS_DIR', $_MH_ADMIN_JS_DIR);

$smarty_admin->assign(array('MH_ADMIN_CSS_DIR' => MH_ADMIN_CSS_DIR));
$smarty_admin->assign(array('MH_ADMIN_JS_DIR' => MH_ADMIN_JS_DIR));


if (MH_BYPASS_TEMPLATE) {
    $admin_template = 'main_direct.tpl';
}

if (mh_beezui() && !mh_cfg('MH_BYPASS_MAILBEEZ_V5')) {
    // Serve the application without the admin wrapper
    // If called as iframe entrypoint (admin/mailbeez.php?main=1), deliver the app directly
    if (mh_get('main')) {
        require(MH_DIR_APP . 'app.php');
        exit;
    }

    // Normal admin view: render wrapper with iframe pointing to the admin entrypoint
    if (!defined('BEEZUI_ENTRYPOINT')) {
        define('BEEZUI_ENTRYPOINT', 'mailbeez.php?main=1');
    }

    ob_start();
    require(MH_DIR_APP . 'wrapper.php');
    $BEEZ_UI_APP = ob_get_contents();
    ob_end_clean();
    $smarty_admin->assign(array('BEEZ_UI_APP' => $BEEZ_UI_APP));
}

ob_start();
require(DIR_WS_INCLUDES . 'application_bottom.php');
$ADMIN_APPLICATION_BOTTOM = ob_get_contents();
ob_end_clean();

$smarty_admin->assign(array('ADMIN_APPLICATION_BOTTOM' => $ADMIN_APPLICATION_BOTTOM));

if (MH_POPUP) {
    $smarty_admin->assign(array('MH_ADMIN_CSS_PATH' => ''));
    echo $smarty_admin->fetch($admin_template_popup); // smarty template
} else {
    $smarty_admin->assign(array('MH_ADMIN_CSS_PATH' => ''));
    echo $smarty_admin->fetch($admin_template); // smarty template
}


if (isset($request_profiler)) {
    $request_profiler->stop('bottom_end');
}

if (defined('DISPLAY_REQUEST_PROFILER') && DISPLAY_REQUEST_PROFILER == 'true') {
    if (isset($request_profiler)) {
        $request_profiler->output();
    }
}

// end of admin screen main area
if (isset($_SESSION['languages_id_backup'])) {
    $_SESSION['languages_id'] = $_SESSION['languages_id_backup'];
    unset($_SESSION['languages_id_backup']);
}
