<?php

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

  Copyright (c) 2010 - 2012 MailBeez

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

  Released under the GNU General Public License

 */


///////////////////////////////////////////////////////////////////////////////
///																																					 //
///                 MailBeez Core file - do not edit                         //
///                                                                          //
///////////////////////////////////////////////////////////////////////////////

require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/mailbeez_cache.php');
require_once(MH_DIR_CONFIG . 'config_customer_insight/classes/context_customer.php');
require_once(MH_DIR_CONFIG . 'config_customer_insight/classes/context_prospect.php');
require_once(MH_DIR_CONFIG . 'config_customer_insight/classes/context_admin.php');
require_once(MH_DIR_CONFIG . 'config_customer_insight/classes/context_order.php');
require_once(MH_DIR_CONFIG . 'config_customer_insight/classes/notificationbeez.php');
require_once(MH_DIR_CONFIG . 'config_customer_insight/classes/observer.php');


mh_define('MAILBEEZ_CONTEXT_VIEW_URL', mh_href_link(mh_fn('FILENAME_MAILBEEZ'), 'app=load_app&app_path=config_customer_insight/admin_application_plugins/context_view.php' . (mh_get('popup') == 'true') ? '&popup=true' : ''));

if (mh_cfg('MAILBEEZ_BEEZDESK_ADMIN_DIR')) {
    mh_define('MAILBEEZ_LA_CONTEXT_VIEW_URL', mh_href_link_plain(mh_cfg('MAILBEEZ_BEEZDESK_ADMIN_DIR') . mh_fn('FILENAME_MAILBEEZ'), 'app=load_app&app_path=config_customer_insight/admin_application_plugins/context_view.php&popup=true&view_module='));
}

class viewbeez extends mailbeez_cache implements Observer
{
    var $version;
    var $subviewpage;
    var $viewpage;
    var $default_template;
    var $summary_template;
    var $dashboard_template;
    var $panel_template;
    var $view_module_directory;
    var $view_module_directory_path;
    var $common_tpl_directory;
    var $order_id;
    var $enabled;
    var $customer_id;
    var $is_customer_enabled = true;
    var $is_prospect;
    var $is_prospect_enabled;
    var $is_visitor;
    var $is_visitor_enabled = true;
    var $cache;
    var $cache_id;
    var $cache_reference;
    var $do_load = true;
    var $chat_cart_session_id = null;
    var $customer = null;
    var $admin = null;
    var $display_as_submodule_of = null;
    var $notficationsObj;
    var $smarty;
    var $platform;
    var $page;
    var $hooks_template_dir;
    var $headers_template_dir;
    var $headers_config_dir;
    var $content_view_url;
    var $helpdesk_inline_url;
    var $dashboard_viewpage;

    var $admin_link;

    var $icon;
    var $module;
    var $title;
    var $description;
    var $sort_order;
    var$sort_order_dashboard;
    var $description_image;
    var $icon_dashboard;
    var $hidden;
    /**
     * @var false
     */
    var $hidden_dashboard;
    /**
     * @var false
     */
    var $is_dashboard;
    /**
     * @var false
     */
    var $has_dashboard_view;
    var $exclude_params;
    /**
     * @var false
     */
    var $menu_cnt;
    var $menu_cnt_text;
    /**
     * @var false
     */
    var $menu_cnt_default;
    var $menu_cnt_default_text;
    /**
     * @var false
     */
    var $panel_ajax_refresh;
    /**
     * @var false
     */
    var $visitor_enabled;
    /**
     * @var mixed|string
     */
    var $language;
    var $dashboard_widget_template;
    var $la_widget_template;
    var $la_main_widget_template;

    var $order;

    function __construct()
    {
        parent::__construct();
        $this->code = ''; // unique id for report-module
        $this->module = ''; //
        $this->title = '';
        $this->description = '';
        $this->sort_order = '';
        $this->sort_order_dashboard = '';
        $this->enabled = true;
        $this->description_image = 'icon_big.png';
        $this->icon = 'icon.png';
        $this->icon_dashboard = 'icon_dashboard.png';
        $this->hidden = false;
        $this->hidden_dashboard = false;
        $this->is_dashboard = false;
        $this->has_dashboard_view = false;
        $this->exclude_params = array();
        $this->menu_cnt = false;
        $this->menu_cnt_text = '';
        $this->menu_cnt_default = false;
        $this->menu_cnt_default_text = '';
        $this->panel_ajax_refresh = false; // allow to refresh the panel with ajax call
        $this->visitor_enabled = false;
        $this->is_visitor = false;
        $this->is_prospect = false;
        $this->session_cache_time = 60;
        $this->app_cache_time = 60;

        $cached = false;

        $this->customer = (object)array(
            'id' => 0,
            'is_prospect' => null,
            'email' => null,
            'user_image' => null
        );


        if (isset($GLOBALS['mh_chat_cart_session_id'])) {
            $this->chat_cart_session_id = $GLOBALS['mh_chat_cart_session_id'];
        }

        if (isset($GLOBALS['mh_insight_is_visitor']) && $GLOBALS['mh_insight_is_visitor'] === true) {
            $this->do_load = false;

            return false;
        }

        // caching for other modules
        if (isset($GLOBALS['mh_insight_customer'])) {
            $this->customer = $GLOBALS['mh_insight_customer'];
            $this->order = $GLOBALS['mh_insight_order'];
            $this->admin = $GLOBALS['mh_insight_admin'];
            mh_log("reading class cache mh_insight_customer: %s", $GLOBALS['mh_insight_customer']);
            mh_log("reading class cache mh_insight_order: %s", $GLOBALS['mh_insight_order']);
            mh_log("reading class cache mh_insight_admin: %s", $GLOBALS['mh_insight_admin']);
            $cached = true;
        }


        if (is_null($this->admin)) {
            $this->admin = new mh_insight_admin();
        }

        $customer_email = false;

        // lngrefactor
        $this->language = ($_SESSION['language'] == '') ? 'german' : $_SESSION['language'];

        if ($this->language == '') $this->language = 'german'; // todo: default language

        if ($cached) {
            return true;
        }
        if (isset($GLOBALS['mh_insight_is_visitor']) && $GLOBALS['mh_insight_is_visitor'] === true) {
            $this->is_visitor = true;
            $this->customer = (object)array('id' => 0);

            $this->order = false;

        } else {
            // prospect
            if (mh_get('cID') > 0 &&
                mh_cfg('MAILBEEZ_NEWSLETTER_SOURCE_PROSPECT_ID_OFFSET', 10000000) && (mh_get('cID') > mh_cfg('MAILBEEZ_NEWSLETTER_SOURCE_PROSPECT_ID_OFFSET', 10000000)) && (mh_get('cID') < mh_cfg('MAILBEEZ_NEWSLETTER_SOURCE_PROSPECT_ID_OFFSET_MAX', 11000000))) {
                $this->order = false;
                $this->set_customer_id(mh_get('cID'));

                if (file_exists(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'mailbeez/mb_newsletter/sourcebeez/prospects_subscriber.php')) {
                    require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'mailbeez/mb_newsletter/sourcebeez/prospects_subscriber.php');

                    $this->customer = new mh_insight_prospect(mh_get('cID'), $this->admin->language, $this->language);

                    if ($this->customer->id > 0) {
                        $this->is_prospect = true;
                        // found prospect
                    } else {
                        // no orderid, no customer email
                        return false;
                    }

                }

            } else {

                // get customers email / information
                if (mh_get('oID') > 0) {
                    $this->set_order_id(mh_get('oID'));
                }
                if (mh_get('cID') > 0) {
                    $this->set_customer_id(mh_get('cID'));
                }

                // load order, customer

                if ($this->order_id) {
                    $this->order = new mh_insight_order($this->order_id);
                    $customer_email = $this->order->customer['email_address'];
                } elseif ($this->customer_id) {
                    // customers id given
                    $this->order = false;
                    $query_sql = "SELECT c.customers_email_address
                            FROM " . TABLE_CUSTOMERS . " c
                          WHERE c.customers_id = '" . $this->customer_id . "'";
                    $query = mh_db_query($query_sql);
                    if (mh_db_num_rows($query) > 0) {
                        $customer = mh_db_fetch_array($query);
                        $customer_email = $customer['customers_email_address'];
                    } else {
                        // no orderid, no customer email
                        return false;
                    }
                }

                // try to get customers email address
                if (!$customer_email) {
                    if (mh_get('email',  null, 'email_string')) {
                        $customer_email = mh_get('email',  null, 'email_string');
                    } elseif (mh_get('username',  null, 'email_string')) {
                        $customer_email = mh_get('username',  null, 'email_string');
                    } else {
                        // no orderid, no customer email
                        return false;
                    }
                }
                $this->customer = new mh_insight_customer($customer_email, $this->admin->language, $this->language);
            }

            //$this->customer->bounces;
            //$this->customer->hasHardBounce;

            if ((int)$this->customer_id == 0) {
                $this->customer_id = $this->customer->id;
            }
        }


        // request caching for other modules
        $GLOBALS['mh_insight_customer'] = $this->customer;
        $GLOBALS['mh_insight_admin'] = $this->admin;
        $GLOBALS['mh_insight_order'] = $this->order;

        mh_log("writing class cache mh_insight_customer: %s", $GLOBALS['mh_insight_customer']);
        mh_log("writing class cache mh_insight_admin: %s", $GLOBALS['mh_insight_admin']);
        mh_log("writing class cache mh_insight_order: %s", $GLOBALS['mh_insight_order']);


        return true;
    }

    function viewbeez()
    {
        return self::__construct();
    }

// class methods

    // called after creation, before sorting and processing
    function set_context($context)
    {
        return false;
    }


    function visitor_init()
    {
        // init call for visitor (chat) enabled modules
        if (isset($GLOBALS['mh_insight_is_visitor']) && $GLOBALS['mh_insight_is_visitor'] === true) {
            if ($this->visitor_enabled === true) {
                $this->is_visitor = true;

                $this->customer = (object)array('id' => 0);

                $this->order = false;
                $this->admin = new mh_insight_admin();
                $this->do_load = true;
                return true;
            }
        }
        return false;
    }

    function install()
    {
        // to be done by instance
    }

    function set_template($template = false)
    {
        // todo: refactor
        if (!$template) {
            $this->default_template = $this->get_module_id() . '.tpl.html';
        }
        $this->summary_template = $this->get_module_id() . '_summary.tpl.html';
        $this->dashboard_template = $this->get_module_id() . '_dashboard.tpl.html';
        $this->dashboard_widget_template = $this->get_module_id() . '_dashboard_widget.tpl.html';
        $this->la_widget_template = $this->get_module_id() . '_la_widget.tpl.html';
        $this->la_main_widget_template = $this->get_module_id() . '_la_main_widget.tpl.html';
        $this->panel_template = $this->get_module_id() . '_panel.tpl.html';
    }

    function check_customer_support()
    {
//        if ($this->customer && !$this->customer->is_prospect) {
        if ($this->customer && !(property_exists($this->customer, 'is_prospect') && $this->customer->is_prospect)) {
            $this->enabled = ($this->is_customer_enabled) ? $this->enabled : false;
            $this->do_load = ($this->is_customer_enabled) ? $this->do_load : false;
        }
    }

    function check_prospect_support()
    {
//        if ($this->customer && $this->customer->is_prospect) {
            if ($this->customer && property_exists($this->customer, 'is_prospect') && $this->customer->is_prospect) {
            $this->enabled = ($this->is_prospect_enabled) ? $this->enabled : false;
            $this->do_load = ($this->is_prospect_enabled) ? $this->do_load : false;
        }
    }

    function get_view_content($template)
    {
        // view content - extend in module
        return false;
    }

    function get_view_la_widget_content($template)
    {
        // view la widget content - extend in module
        return false;
    }

    function get_view_la_main_widget_content($template)
    {
        // view la main widget content - extend in module
        return false;
    }

    function get_view_summary()
    {
        // view summary  - extend in module
        return false;
    }

    function get_view_dashboard_widget()
    {
        // view dashboard  - extend in module
        return false;
    }


    function get_view_dashboard_content($template)
    {
        // view dashboard content - extend in module
        return false;
    }


    function get_view_panel()
    {
        // view panel  - extend in module
        return false;
    }

    function get_view_la_widget()
    {
        // view la widget  - extend in module
        return false;
    }

    function get_view_la_main_widget()
    {
        // view la widget  - extend in module
        return false;
    }


    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // common methods
    function get_module_id()
    {
        return $this->code;
    }


    function init_view_content($template, $config_module = 'config_customer_insight')
    {
        $smarty = new mh_Smarty;
        $smarty->setCaching(false);
        $smarty->setTemplateDir($this->view_module_directory_path . $this->get_module_id() . '/templates/');
        $smarty->setCompileCheck(true);
        $smarty->setCompileId(crc32($this->view_module_directory_path) . $this->get_module_id());
        $smarty->setConfigDir($this->view_module_directory_path . $this->module . '/languages/');
        list($smarty_config_dir) = $smarty->getConfigDir();

        /*

        if (method_exists($smarty, 'setConfigDir')) {
            // smarty 3.1
        } else {
            $smarty->config_dir = $this->view_module_directory_path . $this->module . '/languages/';
            $smarty_config_dir = $smarty->config_dir;
        }

        */


        // lngrefactor
        if (stream_resolve_include_path($smarty_config_dir . $_SESSION['language'] . '.conf')) {
            $smarty->assign('language', $_SESSION['language']);
        } else {
            $smarty->assign('language', 'english');
        }


        $smarty->assign('customer', $this->customer);
        $smarty->assign('admin', $this->admin);
        $smarty->assign('customers_id', $this->customer->id);
        $smarty->assign('orders_id', (isset($this->order->id) && $this->order->id > 0) ? $this->order->id : false);

        $smarty->assign('css_server_url', mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH')); // root for css
        $smarty->assign('module_path', MH_CATALOG_SERVER . MH_DIR_WS_CATALOG . $this->view_module_directory . $this->get_module_id() . '/'); // path of current module
        $smarty->assign('jquery_server_url', mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH') . 'common/js/');

        $smarty->assign('mailhive_server_url', mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH') . '');


        $this->common_tpl_directory = MH_DIR_CONFIG . 'config_customer_insight/viewbeez/common_templates';

        $smarty->assign('common_tpl_dir', $this->common_tpl_directory);

        $smarty->assign('order_edit_url', mh_href_link(FILENAME_ORDERS, 'action=edit'));

        $smarty->assign('page_link', $this->get_menu_link());
        $smarty->assign('dashboard_page_link', $this->get_menu_link('dashboard'));

        $smarty->assign('CONTEXT_VIEW_URL', MAILBEEZ_CONTEXT_VIEW_URL);
        $smarty->assign('mode_saas', mh_saas());
        if (defined('MAILBEEZ_LA_CONTEXT_VIEW_URL')) {
            $smarty->assign('LA_CONTEXT_VIEW_URL', MAILBEEZ_LA_CONTEXT_VIEW_URL . $this->module);
        }

        return $smarty;
    }

    function get_menu_link($mode = 'view')
    {
        $exclude_params_array = array('view_module', 'dashboard_module', 'view_page', 'dashboard_viewpage', 'subview_page', 'cpn', 'notification_action', 'notification_id', 'panel_action');
        $exclude_params_array = array_merge($exclude_params_array, $this->exclude_params);

        if ($mode == 'view') {
            return mh_href_link(FILENAME_MAILBEEZ, mh_get_all_get_params($exclude_params_array) . '&view_module=' . $this->module);
        } elseif ($mode == 'dashboard') {
            return mh_href_link(FILENAME_MAILBEEZ, mh_get_all_get_params($exclude_params_array) . '&view_module=view_dashboard&dashboard_module=' . $this->module);
        } elseif ($mode == 'dashboard_static') {
            return mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=config_customer_insight/admin_application_plugins/context_view.php&popup=false&view_module=view_dashboard&dashboard_module=' . $this->module);
        } elseif ($mode == 'la_widget' || $mode == 'la_main_widget') {
            return mh_href_link_plain(mh_cfg('MAILBEEZ_BEEZDESK_ADMIN_DIR') . FILENAME_MAILBEEZ, 'app=load_app&app_path=config_customer_insight/admin_application_plugins/context_view.php&popup=true&view_module=' . $this->module);

        }

    }

    function get_icon_path($mode = 'view', $relative_path = true)
    {
        if ($mode == 'view') {
            $path = $this->view_module_directory . $this->module . '/' . $this->icon;
        } elseif ($mode == 'dashboard') {
            $path = $this->view_module_directory . $this->module . '/' . $this->icon_dashboard;
        }

        if ($relative_path) {
            return '../' . $path;
        } else {

            // fix for gambio SEO URLs
            $icon_path = mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . $path;
            return $icon_path;
            /*

            $icon_path = mh_href_link_plain($path);
            // fix for zencart 1.3.8
            $icon_path = str_replace('index.php?main_page=', '', $icon_path);
            $icon_path = str_replace('mailhive.php?main_page=', '', $icon_path);
            $icon_path = str_replace('mailbeez.php&amp;', 'mailbeez.php?', $icon_path);
            $icon_path = str_replace('mailbeez.php&', 'mailbeez.php?', $icon_path);
            return $icon_path;
            */
        }
    }


    function get_menu_divider_top()
    {
        return false;
    }

    function get_menu_divider_bottom()
    {
        return false;
    }

    function get_menu_entry()
    {
        return false;
    }

    function get_dashboard_menu_entry()
    {
        return false;
    }

    function parse_view_content($smarty, $template)
    {
        if (mh_smarty_template_exists($smarty, $template)) {
            return $smarty->fetch($template);
        } else {
            return 'viewbeez: template ' . $template . ' not found - must be located in ' . $smarty->template_dir;
        }
    }

    function init_view_summary($config_module = 'config_customer_insight')
    {
        return $this->init_view_content($this->view_module_directory_path, $config_module);
    }

    function init_view_la_widget($config_module = 'config_customer_insight')
    {
        return $this->init_view_content($this->view_module_directory_path, $config_module);
    }

    function init_view_la_main_widget($config_module = 'config_customer_insight')
    {
        return $this->init_view_content($this->view_module_directory_path, $config_module);
    }

    function init_view_dashboard_widget($config_module = 'config_customer_insight')
    {
        return $this->init_view_content($this->view_module_directory_path, $config_module);
    }

    function init_view_dashboard($config_module = 'config_customer_insight')
    {
        return $this->init_view_content($this->view_module_directory_path, $config_module);
    }

    function init_view_panel($config_module = 'config_customer_insight')
    {
        return $this->init_view_content($this->view_module_directory_path, $config_module);
    }


    function parse_view_summary($smarty)
    {
        return $this->parse_view_content($smarty, $this->summary_template);
    }

    function parse_view_dashboard($smarty)
    {
        return $this->parse_view_content($smarty, $this->dashboard_template);
    }

    function parse_view_dashboard_widget($smarty)
    {
        return $this->parse_view_content($smarty, $this->dashboard_widget_template);
    }

    function parse_view_la_widget($smarty)
    {
        return $this->parse_view_content($smarty, $this->la_widget_template);
    }

    function parse_view_la_main_widget($smarty)
    {
        return $this->parse_view_content($smarty, $this->la_main_widget_template);
    }

    function parse_view_panel($smarty)
    {
        return $this->parse_view_content($smarty, $this->panel_template);
    }

    function panel_parse_widget($smarty, $widget_tpl = 'panel_box.tpl.html')
    {
        return $this->parse_view_content($smarty, $this->common_tpl_directory . '/' . $widget_tpl);
    }


    function set_view_module_directory($view_module_directory)
    {
        $this->view_module_directory = $view_module_directory;
        $this->view_module_directory_path = MH_DIR_FS_CATALOG . $view_module_directory;
    }

    function set_exclude_params($exclude_params)
    {
        $this->exclude_params = $exclude_params;
    }

    function set_order_id($order_id)
    {
        $this->order_id = $order_id;
    }

    function set_customer_id($customer_id)
    {
        $this->customer_id = $customer_id;
    }

    public function observer_update(Subject $Subject)
    {
        $start_time = microtime(true);
        $this->data_update();
        $end_time = microtime(true);
        mh_log("observer_update: " . $this->code . " in %s", $end_time - $start_time);
        return false;
    }

    function data_update()
    {
        return false;
    }

}

// end of class
