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

 Copyright (c) 2010 - 2013 MailBeez

 Licensing Terms & Other Conditions of this
 Mailbeez Module:

 Unless you have our prior written consent, you must NOT directly or indirectly license,
 sub-license, sell, resell, or provide for free or make an offer to do any of these things.
 All of these things are strictly prohibited with this MailBeez Pro Module.

 One Purchase for one Shop - please contact cord@mailbeez.com for volume discounts and
 reseller agreements.

 OpenSource but not free - please respect this license agreement.

 */


if (!function_exists('mh_admin_product_image')) {
    function mh_admin_product_image($image_data_array)
    {
        $args = func_get_args();

        if (mh_cfg('MH_CONTEXT') == 'STORE') {
            return call_user_func_array('mh_product_image', makeValuesReferenced($args));
        }

        switch (MH_PLATFORM) {
            case 'oscommerce':
            case 'digistore':
            case 'creloaded':
            case 'zencart':
                return call_user_func_array('mh_product_image', makeValuesReferenced($args));
                break;
            case 'xtc':
            case 'gambio':
            case 'mercari':
                $call_args[0] = $args[0]['products_image'];
                $call_args[1] = $args[0]['products_name'];
                return call_user_func_array('xtc_product_thumb_image', makeValuesReferenced($call_args));
                break;
            default:
                echo 'platform not supported';
        }
    }
}


// define directories to look for viewbeez modules


// scan mailbeez modules automatically for "viewbeez" directory
// allow custom modules to overload default modules by loading "others" first
// push configbeez/config_customer_insight to the end


function mh_insight_view_get_module_directory_array()
{
    static $cached_result = null;
    if ($cached_result !== null) {
        return $cached_result;
    }

    // on windows /viewbeez/ doesnot work
    // so add the / later
    $view_module_directory_array = glob(MH_DIR_FS_CATALOG . MH_ROOT_PATH . '*/*/viewbeez', GLOB_ONLYDIR);
    $push_to_end_dir = '';

    if (is_array($view_module_directory_array) && sizeof($view_module_directory_array) > 0) {

        foreach ($view_module_directory_array as $idx => $view_module_directory) {

            $view_module_directory_array[$idx] .= '/';
            $view_module_directory_array[$idx] = str_replace(MH_DIR_FS_CATALOG, '', $view_module_directory_array[$idx]);
            if (stristr($view_module_directory_array[$idx], 'configbeez/config_customer_insight')) {
                $push_to_end_dir = $view_module_directory_array[$idx];
                unset($view_module_directory_array[$idx]);
            }
        }
    }

    $view_module_directory_array[] = $push_to_end_dir;
    $cached_result = $view_module_directory_array;
    return $cached_result;
}

function mh_insight_dashboard($dashboard_module)
{
    global $request_profiler;
    global $mailbeez_insight_all_modules;


    if (is_null($dashboard_module)) {
        $dashboard_module = 'view_dashboard';
    }

    $dashboard_menu = '';
    $mInfo = '';

    foreach ($mailbeez_insight_all_modules as $key => $module) {
        $start_time = microtime(true);
        list($dashboard_menu_current, $mInfo_current) = mh_insight_view_process_modules($dashboard_module, $module, 'dashboard');
        mh_log("processing dashboard module: $module in %s", microtime(true) - $start_time);
        $dashboard_menu .= $dashboard_menu_current;
        $mInfo = is_object($mInfo_current) ? $mInfo_current : $mInfo;
    }


    return array($dashboard_menu, $mInfo);
}

function mh_insight_view($current_module, $process_modules = true, $context = 'view')
{
    global $request_profiler;
    global $mailbeez_insight_all_modules;
    $request_profiler->restart('---config_customer_insight_view_before_read_module_dir---');


    if (!is_array($mailbeez_insight_all_modules)) {
        $mailbeez_insight_all_modules = array();
    }

    if (empty($mailbeez_insight_all_modules)) {
        $view_module_directory_array = mh_insight_view_get_module_directory_array();

        $all_modules_directory = array();
        // read all modules
        foreach ($view_module_directory_array as $view_module_directory_current) {
            $start_time = microtime(true);
            list($all_modules_current, $all_modules_directory_current, $installed_modules_current) = mh_insight_view_load_modules($view_module_directory_current, $context);
            $end_time = microtime(true);
            mh_log("mh_insight_view_load_modules $view_module_directory_current load time: %s", $end_time - $start_time);

            $mailbeez_insight_all_modules = $mailbeez_insight_all_modules + $all_modules_current;
            $all_modules_directory = $all_modules_directory + $all_modules_directory_current;
        }
        // sort all_modules
        uksort($mailbeez_insight_all_modules, "sortbyintvalue");
    }

    if (!$process_modules) {
        return $mailbeez_insight_all_modules;
    }



    // generate output for all modules

    $view_menu = '';
    $mInfo = '';

    $request_profiler->restart('---config_customer_insight_view_before_module_list---');
    foreach ($mailbeez_insight_all_modules as $key => $module) {
        $start_time = microtime(true);

        list($view_menu_current, $mInfo_current) = mh_insight_view_process_modules($current_module, $module, $context);
        mh_log("processing module: $module in %s", microtime(true) - $start_time);

        $view_menu .= $view_menu_current;
        $mInfo = is_object($mInfo_current) ? $mInfo_current : $mInfo;
    }

    return array($view_menu, $mInfo, $mailbeez_insight_all_modules);

}

function mh_insight_view_load_modules($view_module_directory, $context = '')
{
    global $request_profiler;
    $view_module_directory_path = MH_DIR_FS_CATALOG . $view_module_directory;

    $directory_array = mh_read_module_directory($view_module_directory_path);
    sort($directory_array);

    $installed_modules = array();
    $mailbeez_insight_all_modules = array();
    $all_modules_directory = array();

    for ($i = 0, $n = sizeof($directory_array); $i < $n; $i++) {
        $offset = 0;
        $file = $directory_array[$i];
        $class = substr($file, 0, strrpos($file, '.'));

        if (isset($GLOBALS[$class]) && is_object($GLOBALS[$class])) {
            continue;
        }
        $load_start_time = microtime(true);


        $request_profiler->restart('config_customer_insight_view_before_load: ' . $class);

        mh_load_modules_language_files($view_module_directory_path, $class, MH_FILE_EXTENSION);

        // include class
        if (file_exists($view_module_directory_path . $file) && !class_exists($class)) {
            include_once($view_module_directory_path . $file);
        }
        if (class_exists($class)) {
            if (!isset($GLOBALS[$class]) || !is_object($GLOBALS[$class])) {
                mh_log("creating object: %s", $class);
                $GLOBALS[$class] = new $class; // new object
                if (!mh_check_admin_rights($class) || !$GLOBALS[$class]->enabled) {
                    unset($GLOBALS[$class]);
                    continue;
                }
            }

            $GLOBALS[$class]->set_view_module_directory($view_module_directory);
            $GLOBALS[$class]->set_context($context);
            $GLOBALS[$class]->check_customer_support();
            $GLOBALS[$class]->check_prospect_support();

            $view_module = $GLOBALS[$class];

            if ($view_module->sort_order > 0) {
                $all_modules_sortorder = $offset + ($view_module->sort_order * 10000);
            } else {
                $all_modules_sortorder = $offset;
            }

            if ($view_module->enabled && $view_module->do_load) {
                if ($view_module->display_as_submodule_of != '') {
                    $all_modules_sortorder += 900;
                } else {
                    $all_modules_sortorder += 1000;
                }
                $installed_modules[$all_modules_sortorder . $class] = $file; // make key unique but sortable as integer
            } elseif ($view_module->do_load !== true) {
                continue;
            }

            $mailbeez_insight_all_modules[$all_modules_sortorder . $class] = $file;
            $all_modules_directory[$all_modules_sortorder . $class] = $view_module_directory;
        } // if exists

        $load_end_time = microtime(true);
        mh_log("load module $class: %s", $load_end_time - $load_start_time);
    } // for
    return array($mailbeez_insight_all_modules, $all_modules_directory, $installed_modules);
}


function mh_insight_view_process_modules($current_module, $module, $mode = 'view')
{
    global $request_profiler;

    $view_menu = '';
    $file = $module;

    $class = substr($file, 0, strrpos($file, '.'));
    $request_profiler->restart('config_customer_insight_view_before_display: ' . $class);

    if (isset($GLOBALS[$class]) && is_object($GLOBALS[$class])) {
        $view_module = $GLOBALS[$class];
        $mInfo = false;
//            $menu_icon = '../' . $view_module_directory . $view_module->module . '/' . $view_module->icon;
//            $menu_link = mh_href_link(FILENAME_MAILBEEZ, mh_get_all_get_params(array('view_module')) . '&view_module=' . $view_module->module);

        if ((is_null($current_module) && $view_module->module == 'view_overview') || (!is_null($current_module) && ($current_module == $class)) && $mInfo == false) {

            $view_module_info = array('code' => $view_module->get_module_id(),
                'module' => $view_module->module,
                'title' => $view_module->title,
                'is_dashboard' => $view_module->is_dashboard,
                'description' => $view_module->description,
                'description_image_src' => $view_module->description_image,
                'icon' => (isset($view_module->icon) ? $view_module->icon : null),
                'view_content' => ($mode == 'dashboard') ? $view_module->get_view_dashboard_content($view_module->default_template) : $view_module->get_view_content($view_module->default_template),
                'la_widget_content' => $view_module->get_view_la_widget_content($view_module->default_template),
                'la_main_widget_content' => $view_module->get_view_la_main_widget_content($view_module->la_main_widget_template)
            );
            $mInfo = new mh_objectInfo($view_module_info);
        }

        if ($mode == 'view' && $view_module->hidden == true) {
            return array('', $mInfo);
        } elseif ($mode == 'dashboard' && $view_module->hidden_dashboard == true) {
            return array('', $mInfo);
        }

        if (isset($mInfo) && is_object($mInfo) && ($class == $mInfo->code)) {
            $menu_active = true;
        } else {
            $menu_active = false;
        }


        if ($mode == 'dashboard') {
            //$dashboard_menu_entry = $view_module->get_dashboard_menu_entry();
            $menu_link = $view_module->get_menu_link('dashboard');
            $menu_icon = $view_module->get_icon_path('dashboard');
        } elseif ($mode == 'view') {
            $menu_icon = $view_module->get_icon_path('view');
            $menu_link = $view_module->get_menu_link('view');

            $menu_divider_before = $view_module->get_menu_divider_top();
            $menu_divider_after = $view_module->get_menu_divider_bottom();

            $menu_entry = $view_module->get_menu_entry();
        }

        ob_start()
        ?>
        <?php if ($mode == 'dashboard') { ?>
            <?php if ($view_module->has_dashboard_view != false) { ?>
                <?php //echo $dashboard_menu_entry; ?>

                <a data-enhance="false" data-role="none"
                   class="dashboard_menu <?php echo ($menu_active) ? 'active' : '' ?>"
                   title="<?php echo $view_module->title; ?>" href="<?php echo $menu_link; ?>">
                    <img src="<?php echo $menu_icon; ?>" width="36">
                    <br/>
                    <span class="dashboard_menu_title"><?php echo $view_module->title; ?></span>
                    <br/>
                </a>
                <?php
                if ((int)$view_module->menu_cnt > 0) {
                    ?>
                    <span
                        class="dashboard_menu badge_ctn badge_important"><?php echo $view_module->menu_cnt; ?></span><?php
                } elseif (false && (int)$view_module->menu_cnt_default > 0) {
                    ?>
                    <span class="dashboard_menu badge_ctn"><?php echo $view_module->menu_cnt_default; ?></span><?php
                } ?>
                <br/>

            <?php } ?>
        <?php } elseif ($mode == 'view') { ?>
            <?php if ($menu_divider_before != '') { ?>
                <li data-role="list-divider" id="menu-divider"
                    data-dividertheme="a"><?php echo $menu_divider_before ?></li>
            <?php } ?>
            <?php if ($menu_entry) { ?>
                <?php echo $menu_entry; ?>
            <?php } else { ?>
                <li
                    <?php //echo ($menu_active) ? 'data-theme="a"' : '' ?>
                    <?php echo ($menu_active) ? 'class="ui-btn-active"' : '' ?>
                >
                    <a title="<?php echo $view_module->title; ?>" href="<?php echo $menu_link; ?>"
                       style="background-image:url(<?php echo $menu_icon; ?>); background-position: 14px 7px; background-size: 24px 24px;"
                    ><?php echo $view_module->title; ?>
                        <?php if ((int)$view_module->menu_cnt > 0) { ?>
                            <span class="ui-li-count ui-btn-active"
                                  style="margin-top: -11px;"><?php echo $view_module->menu_cnt; ?></span><?php } elseif ((int)$view_module->menu_cnt_default > 0) { ?>

                            <span class="ui-li-count"
                                  style="margin-top: -11px;"><?php echo $view_module->menu_cnt_default; ?></span><?php } elseif ($view_module->menu_cnt_text != '') { ?>

                            <span class="ui-li-count ui-btn-active"
                                  style="margin-top: -11px;"><?php echo $view_module->menu_cnt_text; ?></span><?php } elseif ($view_module->menu_cnt_default_text != '') { ?>

                            <span class="ui-li-count"
                                  style="margin-top: -11px;"><?php echo $view_module->menu_cnt_default_text; ?></span><?php }
                        ?>
                    </a>
                </li>

            <?php } ?>

            <?php if ($menu_divider_after != '') { ?>
                <li data-role="list-divider" id="menu-divider"><?php echo $menu_divider_after ?></li>
            <?php } ?>
        <?php } ?>


        <?php
        $view_menu .= ob_get_clean();
    }
    return array($view_menu, $mInfo);

}

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;
    }
}