<?php

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

  Copyright (c) 2010, 2011 MailBeez

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

  Released under the GNU General Public License
 */

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


class dashboard_statsbar extends dashboardbeez_analytics
{

    var $code;
    var $module;
    var $title;
    var $description;
    var $sort_order;
    var $enabled = false;


    function __construct($widget_mode = false, $autoinit = true)
    {
        parent::__construct();
        $this->code = 'dashboard_statsbar';
        $this->module = 'dashboard_statsbar';
        $this->version = '3.02'; // float value
        $this->required_mb_version = 3;
        $this->title = mh_lng('MAILBEEZ_DASHBOARD_STATSBAR_TITLE_LONG');
        $this->description = mh_lng('MAILBEEZ_DASHBOARD_STATSBAR_DESC');
        $this->description_image = '../../common/images/icon_ma_64.png';
        $this->icon = '../../common/images/icon_ma.png';
        //$this->removable = false; // can't be removed
        $this->enabled = true;
        $this->removable = false; // can't be removed

        $this->status_key = 'MAILBEEZ_DASHBOARD_STATSBAR_STATUS';
        $this->documentation_root = 'https://www.mailbeez.com/documentation/dashboardbeez/';
        $this->documentation_key = $this->module;

        $this->admin_action_plugins_path = MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'dashboardbeez/'; // default-path to include admin action plugins from
        $this->admin_action_plugins = '';


        $this->sort_order = mh_cfg('MAILBEEZ_DASHBOARD_STATSBAR_SORT_ORDER');
        // set cache reference

        $this->check_update();

        if ($autoinit) {
            $this->set_widget_mode(mh_get('widget_mode', $widget_mode));
            $this->set_widget_module_id(mh_get('widget_module_id'));
            $this->set_selected_module(mh_get('selected_module'));
            $this->set_selected_campaign(mh_get('selected_campaign'));
            $this->set_selected_campaign_item(mh_get('selected_campaign_item'));
            $this->set_date_frame(mh_get('selected_startdate'), mh_get('selected_enddate'));
            $this->set_leaderboard_include(mh_get('leaderboard_include'));

        }
        $this->_set_cache_id();

        if ($this->widget_mode) {
            mh_session_write_close();
        }
    }

    function dashboard_statsbar($widget_mode = false)
    {
        self::__construct($widget_mode);
    }


    function generateData($refresh = false)
    {
        $statsbar_parameter = array(
            'limit_module' => $this->selected_module,
            'limit_campaign_item_ids' => $this->selected_campaign_item_ids,
            'limit_startdate_db' => $this->start_date_db,
            'limit_enddate_db' => $this->end_date_db,
        );


        // return cached value if exists
        // also return if outdated
        if (!$refresh && $cache = $this->read_cache("app", true)) {
            return $cache['value'];
        }


        $analytics = new mailbeez_analytics($statsbar_parameter);


        list($cnt_sent, $cnt_opened, $cnt_clicked, $cnt_delivered) = $analytics->get_engagement_data();
        list($revenue_value, $cnt_orders, $coupon_value) = $analytics->get_orders_data();
        list($cnt_mobile) = $analytics->get_mobile_useragent_data();

        $pct_delivered = ($cnt_sent > 0) ? $cnt_delivered / $cnt_sent * 100 : 0;
        $pct_opened = ($cnt_delivered > 0) ? $cnt_opened / $cnt_delivered * 100 : 0;
        $pct_clicked = ($cnt_opened > 0) ? $cnt_clicked / $cnt_opened * 100 : 0;
        $pct_ordered = ($cnt_clicked > 0) ? $cnt_orders / $cnt_clicked * 100 : 0;
        $pct_mobile = ($cnt_opened > 0) ? $cnt_mobile / $cnt_opened * 100 : 0;

        $revenue_email_value = ($cnt_sent > 0) ? $revenue_value / $cnt_sent : 0;

        $revenue = mh_price((float)$revenue_value);
        $revenue_email = mh_price((float)$revenue_email_value);
        $coupon_val = mh_price((float)$coupon_value);
        //$revenue = (int) $revenue_value;
        $smarty = new mh_Smarty;
        $smarty->setTemplateDir(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/templates/');
        $smarty->setCompileId('statsbar');

        list($smarty_config_dir) = $smarty->getConfigDir();

// lngrefactor


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


        $data = array('cnt_sent' => $cnt_sent,
            'cnt_delivered' => $cnt_delivered,
            'cnt_opened' => $cnt_opened,
            'cnt_clicked' => $cnt_clicked,
            'cnt_orders' => $cnt_orders,
            'cnt_mobile' => $cnt_mobile,
            'pct_delivered' => $pct_delivered,
            'pct_opened' => $pct_opened,
            'pct_clicked' => $pct_clicked,
            'pct_ordered' => $pct_ordered,
            'pct_mobile' => $pct_mobile,
            'revenue' => $revenue,
            'revenue_email' => $revenue_email,
            'coupon_val' => $coupon_val,
            'beginning_of_time' => $analytics->timeframe_start
        );


        return $this->set_cache($data, 'app'); // session | request | app

    }


    function generateOutput($ajax = false, $refresh = false)
    {

        $data = $this->generateData($refresh);

        $smarty = new mh_Smarty;
        $smarty->setTemplateDir(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/templates/');
        $smarty->setConfigDir(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'reportbeez/report_kpi_suite/languages/');

        $smarty->setCompileId('statsbar');

        list($smarty_config_dir) = $smarty->getConfigDir();

// lngrefactor


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

        $smarty->assign(array('cnt_sent' => $data['cnt_sent'],
                'cnt_delivered' => $data['cnt_delivered'],
                'cnt_opened' => $data['cnt_opened'],
                'cnt_clicked' => $data['cnt_clicked'],
                'cnt_orders' => $data['cnt_orders'],
                'cnt_mobile' => $data['cnt_mobile'],
                'pct_delivered' => $data['pct_delivered'],
                'pct_opened' => $data['pct_opened'],
                'pct_clicked' => $data['pct_clicked'],
                'pct_ordered' => $data['pct_ordered'],
                'pct_mobile' => $data['pct_mobile'],
                'revenue' => $data['revenue'],
                'revenue_email' => $data['revenue_email'],
                'coupon_val' => $data['coupon_val'],
                'beginning_of_time' => $data['beginning_of_time'],
                'hide_timeago' => $this->start_date_db || $this->end_date_db,
                'MH_CATALOG_URL' => MH_CATALOG_SERVER . MH_DIR_WS_CATALOG,
                'MH_ROOT_PATH' => MH_ROOT_PATH
            )
        );


        ob_start();
        ?>


        <script language="javascript"
                src="<?php echo mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH'); ?>common/js/easy-pie/jquery.easy-pie-chart.js"></script>

        <script type="text/javascript">

            var color_delivered = '#a0a0a0';
            var color_open = '#9ac2df';
            var color_click = '#f8933c';
            var color_order = '#abd37f';


            var initPieChartDashboard = function () {

                jQuery('.sb_percentage-delivered').easyPieChart({
                    barColor: color_delivered,
                    size: 50,
                    trackColor: 'rgba(214, 176, 252, .2)',
                    scaleColor: false,
                    lineCap: 'round',
                    lineWidth: 5,
                    animate: 500
                });

                jQuery('.sb_percentage-open').easyPieChart({
                    barColor: color_open,
                    size: 50,
                    trackColor: 'rgba(154, 194, 223, .2)',
                    scaleColor: false,
                    lineCap: 'round',
                    lineWidth: 5,
                    animate: 500
                });

                jQuery('.sb_percentage-click').easyPieChart({
                    barColor: color_click,
                    size: 50,
                    trackColor: 'rgba(248, 147, 60, .2)',
                    scaleColor: false,
                    lineCap: 'round',
                    lineWidth: 5,
                    animate: 500
                });
                jQuery('.sb_percentage-order').easyPieChart({
                    barColor: color_order,
                    size: 50,
                    trackColor: 'rgba(171, 211, 127, .2)',
                    scaleColor: false,
                    lineCap: 'round',
                    lineWidth: 5,
                    animate: 500
                });


            };

        </script>

        <style type="text/css">

            <?php if ($this->widget_mode) { ?>
            #statsbar:hover {
                cursor: pointer;
                opacity: 0.8;
            }

            <?php } ?>
        </style>
        <?php if ($this->widget_mode) { ?>
        <div id="WidgetTitle" style="position: absolute;margin-top: 0px; " class="subtext"><i class="fa fa-envelope"
                                                                                              style="color: #737373; margin-top: -1px;"></i> <?php echo mh_lng('MAILBEEZ_DASHBOARD_STATSBAR_TITLE'); ?>
        </div>
        <!--            <div id="WidgetSubTitle" style="display: inline-block; margin-top: -8px;">--><?php //echo mh_lng('MAILBEEZ_DASHBOARD_STATSBAR_DESC'); ?><!--</div>-->
    <?php } ?>
        <div style="clear:both; height: 1px;"></div>

        <div id="statsbar"
            <?php if ($this->widget_mode) { ?>
                style="width: 100%; height: 90px;  margin-top: 0px;"
                onclick="parent.document.location='<?php echo mh_href_link(FILENAME_MAILBEEZ); ?>'"
            <?php } else { ?>
                style="width: 100%; min-height: 100px;  margin-top: 10px;"
            <?php } ?>
        >
            <div style="position: relative">
                <?php if (mh_cfg('MAILBEEZ_ANALYTICS_STATUS') == 'False') { ?>
                    <div class="sb_disabled_message_container">
                       <span class="sb_disabled_message">
                           <?php echo mh_lng('MAILBEEZ_DASHBOARD_ANALYTICS_MSG'); ?>
                           <br>

                           <?php if ($this->widget_mode) { ?>
                               <?php echo mb_admin_button(mh_href_link(FILENAME_MAILBEEZ), mh_lng('MAILBEEZ_ANALYTICS_STATUS_BUTTON'), '', 'link', 'link', '', 'document', '', '_parent'); ?>
                               <?php
                           } else { ?>
                               <?php echo mb_admin_button(mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=config_analytics/admin_application_plugins/confirm.php&popup=true'), mh_lng('MAILBEEZ_ANALYTICS_STATUS_BUTTON'), '', 'popup', 'link', '', 'document', 'iframe width:600 height:500'); ?>
                           <?php } ?>
                       </span>
                    </div>
                <?php } ?>


                <div class="<?php if (mh_cfg('MAILBEEZ_ANALYTICS_STATUS') == 'False') { ?>sb_disabled<?php } ?>">
                    <?php
                    $content = $smarty->fetch('dashboard_statsbar.tpl');
                    echo $content;
                    ?>
                </div>

                <?php if (file_exists(MH_DIR_REPORT . 'report_analytics_advanced/report_analytics_advanced.php') && !$this->widget_mode) {
                    include_once(MH_DIR_REPORT . 'report_analytics_advanced.php');
                    ?>
                    <div style="text-align: center; color: #808080 !important;">


                        <div style="border: 1px solid #808080; display: inline-block; padding: 5px 10px; margin-top: -15px; margin-bottom: 5px">
                            <?php if (!method_exists('report_analytics_advanced', 'getLink')) {
                                ?>
                                Please run the Pro-Update

                                <?php
                            } else {?>
                            <a onclick="return openReportPopup('<?php echo report_analytics_advanced::getLink(); ?>')"
                               href="<?php echo report_analytics_advanced::getLink(); ?>"
                               style="color: #808080 !important"
                            ><i class="fa fa-line-chart"></i> <?php echo mh_lng('MAILBEEZ_ANALYTICS_ADVANCED_OPEN_BUTTON'); ?>
                            </a>
                            <?php
                            }
                            ?>
                        </div>

                    </div>
                <?php } ?>

            </div>
        </div>
        <script type="text/javascript">
            jQuery(document).ready(function () {
                initPieChartDashboard();
            });
        </script>


        <?php
        $output = ob_get_contents();
        ob_end_clean();


        return $output;
    }

    function check()
    {
        return true;
    }


    function keys()
    {
        if (MH_PLATFORM_GAMBIO >= 2.5) {
            return array('MAILBEEZ_STATSBAR_ADMIN_POSITION');

        }
        return array();
    }

    function install()
    {
        return $this->update(0);
    }


    function update($installed_version = null)
    {

        if (MH_PLATFORM_GAMBIO >= 2) {
            mh_insert_config_value(array('configuration_title' => 'position on Gambin admin dashboard',
                'configuration_key' => 'MAILBEEZ_STATSBAR_ADMIN_POSITION',
                'configuration_value' => '2',
                'configuration_description' => 'Do you want to send winback emails?',
                'set_function' => 'mh_cfg_select_option(array(\'OFF\', \'1\', \'2\', \'3\'), '
            ));
        }


        return parent::update($this->module);
    }

}
