<?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.php');
require_once(MH_DIR_CONFIG . 'config_dq_check/classes/data_quality_check.php');

class dashboard_dq_check extends dashboardbeez
{
    var $code;
    var $module;
    var $title;
    var $description;
    var $sort_order;
    var $enabled = false;

    function __construct()
    {
        parent::__construct();
        $this->code = 'dashboard_dq_check';
        $this->module = 'dashboard_dq_check';
        $this->version = '3.0'; // float value
        $this->required_mb_version = 2.99;
        $this->title = mh_lng('MAILBEEZ_DASHBOARD_DQ_CHECK_TITLE');
        $this->description = mh_lng('MAILBEEZ_DASHBOARD_DQ_CHECK_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 = ((mh_cfg('MAILBEEZ_DASHBOARD_DQ_CHECK_STATUS') == 'True') ? true : false);
        $this->status_key = 'MAILBEEZ_DASHBOARD_DQ_CHECK_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_DQ_CHECK_SORT_ORDER');

        $this->set_cache_id($this->code, 'dashboard');
        $this->mlbz = false;
        if ($this->modeSaas()) {
             $this->enabled = false;
             $this->hidden = true;
         }
    }



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


        $customer_accounts_cnt = $data_customer_quality['cnt_all'];
        $customer_accounts_unique_cnt = $data_customer_quality['cnt_distinct'];
        $customer_accounts_quality_perc = ($customer_accounts_cnt > 0) ? round($customer_accounts_unique_cnt / $customer_accounts_cnt * 100, 1) : 0;


        $data_accounts_abandoned = data_quality_check::get_abandoned_account_cnt();
        $accounts_abandoned = $data_accounts_abandoned['cnt'];
        $accounts_abandoned_perc = ($customer_accounts_unique_cnt) ? round($accounts_abandoned / $customer_accounts_unique_cnt * 100, 1) : 0;

        $data_orphan_orders = data_quality_check::get_orphan_order_cnt();
        $orpha_order_cnt = $data_orphan_orders['cnt'];


        // returns array
        $data_guest_account_redundancy = data_quality_check::get_guest_account_redundancy();


        $data = array($customer_accounts_quality_perc, $customer_accounts_cnt, $customer_accounts_unique_cnt, $accounts_abandoned, $accounts_abandoned_perc, $data_guest_account_redundancy, $orpha_order_cnt);

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

    }

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

        list($customer_accounts_quality_perc, $customer_accounts_cnt, $customer_accounts_unique_cnt, $accounts_abandoned, $accounts_abandoned_perc, $data_guest_account_redundancy, $orpha_order_cnt) = $this->generateData($refresh);


        ob_start();

        ?>
        <link rel="stylesheet" type="text/css" media="print, projection, screen"
              href="<?php echo mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH'); ?>dashboardbeez/dashboard_dq_check/dashboard_dq_check.css">


        <script type="text/javascript">

            var color_blue = '#9ac2df';
            var color_red = '#da4f49';
            var color_yellow = '#fff7a5';
            var color_orange = '#f8933c';
            var color_green = '#abd37f';


            var initPieChartDashboardDqCheck = function () {

//                http://stackoverflow.com/questions/7128675/from-green-to-red-color-depend-on-percentage
                jQuery('.dqc_unique_customer').easyPieChart({
                    barColor: function (percent) {
                        percent /= 100;

                        if (percent < 0.65) {
                            return color_red
                        } else if (percent < 0.75) {
                            return color_red
                        } else if (percent < 0.95) {
                            return color_orange
                        } else {
                            return color_green;
                        }
                        //var hue = ((percent) * 120).toString(10);
                        //return ["hsl(", hue, ",80%,50%)"].join("");
                    },
                    size: 50,
                    trackColor: '#e0e0e0',
                    scaleColor: false,
                    lineCap: 'round',
                    lineWidth: 5,
                    animate: 500
                });

                jQuery('.dqc_abandoned_customer').easyPieChart({
                    barColor: function (percent) {
                        percent /= 100;

                        if (percent < 0.05) {
                            // good
                            return color_green;

                        } else if (percent < 0.1) {
                            // ok
                            return color_orange

                        } else if (percent < 0.15) {
                            // bad
                            return color_red

                        } else {
                            // really bad
                            return color_red

                        }
                    },
                    size: 50,
                    trackColor: '#e0e0e0',
                    scaleColor: false,
                    lineCap: 'round',
                    lineWidth: 5,
                    animate: 500
                });

            };

        </script>

        <div id="WidgetTitle"><?php echo MAILBEEZ_DASHBOARD_DQ_CHECK_TITLE ?></div>
        <div
            id="WidgetSubTitle"><?php echo mh_lng('MAILBEEZ_DASHBOARD_DQ_CHECK_DESC'); ?>
        </div><br clear="all" style="padding:0px; margin:0px;height: 0px;line-hei ght: 11px;">
        <hr noshade size="1" style="padding: 0px; margin: -10px; margin-top: -10px; margin-bottom: 0px; color: #c0c0c0">
        <div align="center"
             style="margin: auto;padding-top: 10px"
             class="dq_check dashboard_dcq_chart_container">
            <div class="dqc_chart">
                <div class="dqc_unique_customer" data-percent="<?php echo $customer_accounts_quality_perc ?>" style="margin: auto">
                    <span><?php echo $customer_accounts_quality_perc ?></span>%
                </div>
                <div class="label"><?php echo mh_lng('MAILBEEZ_DASHBOARD_DQ_UNIQUE_CUSTOMERS'); ?> <br/>
                    <?php echo $customer_accounts_cnt; ?> /
                    <?php echo $customer_accounts_unique_cnt; ?>
                </div>
            </div>


            <div class="dqc_chart_number">
                <div class="number"><?php echo $data_guest_account_redundancy['summary']['weighted_avg']; ?></div>
                <div class="label"><?php echo mh_lng('MAILBEEZ_DASHBOARD_DQ_GUEST_RED'); ?>
                    <a href="#" onClick="openCBTip(jQuery('#infoDqGuest').html(), 600, 400 );return false;">
                        (?)
                    </a>
                    <span id="infoDqGuest" style="display: none">
                        <div style="padding: 20px;">
                            <?php echo $data_guest_account_redundancy['summary']['cnt_unique']; ?> <?php echo mh_lng('MAILBEEZ_DASHBOARD_DQ_GUEST_TEXT_GUEST'); ?> <?php echo $data_guest_account_redundancy['summary']['cnt_redundant']; ?> <?php echo mh_lng('MAILBEEZ_DASHBOARD_DQ_GUEST_TEXT_ACCOUNTS'); ?>

                            <table style="width: 70%">
                                <tr>
                                    <td style="width: 50%">#<?php echo mh_lng('MAILBEEZ_DASHBOARD_DQ_GUEST_RED_GUESTS_TITLE'); ?></td>
                                    <td style="width: 50%">#<?php echo mh_lng('MAILBEEZ_DASHBOARD_DQ_GUEST_RED_ACCOUNTS_TITLE'); ?></td>
                                </tr>
                                <?php

                                foreach ($data_guest_account_redundancy as $cnt => $cnt_data) {

                                    if ($cnt == 'summary') {
                                        continue;
                                    }
                                    ?>
                                    <tr>
                                        <td><?php echo $cnt_data['cnt_unique'] ?></td>
                                        <td><?php echo $cnt; ?></td>
                                    </tr>
                                    <?php
                                }
                                ?>

                            </table>
                        </div>
                    </span>
                </div>

            </div>


            <div class="dqc_chart">
                <div class="dqc_abandoned_customer" data-percent="<?php echo $accounts_abandoned_perc ?>" style="margin: auto">
                    <span><?php echo $accounts_abandoned_perc ?></span>%
                </div>
                <div class="label"><?php echo mh_lng('MAILBEEZ_DASHBOARD_DQ_ABANDONED'); ?> <br/>

                    <?php echo $accounts_abandoned; ?> /
                    <?php echo $customer_accounts_unique_cnt; ?>
                </div>
            </div>

            <div class="dqc_chart_number">
                <div class="number"><?php echo $orpha_order_cnt; ?></div>
                <div class="label"><?php echo mh_lng('MAILBEEZ_DASHBOARD_DQ_ORPHAN'); ?>
                </div>
            </div>

        </div>
        <div style="clear: both; padding-top: 18px;padding-left: 20px">
            <?php if (mh_cfg('MAILBEEZ_CONFIG_ACCOUNT_AGGREGATION_STATUS') != 'True') { ?>
                <div>
                    <a href="<?php echo mh_lng('MAILBEEZ_DASHBOARD_DQ_LINK'); ?>"
                       target="_blank"><?php echo mh_lng('MAILBEEZ_DASHBOARD_DQ_CONTACT'); ?></a>
                </div>
            <?php } else { ?>
                <div style="color: #808080;">
                    <?php echo mh_lng('MAILBEEZ_DASHBOARD_DQ_RUNNING'); ?>
                </div>
            <?php } ?>
        </div>

        <script type="text/javascript">
            jQuery(document).ready(function () {
                initPieChartDashboardDqCheck();
            });
        </script>
        <?php
        $output = ob_get_contents();
        ob_end_clean();

        return $output;
    }


    function install()
    {
        mh_insert_config_value(array('configuration_title' => 'Show Shop Data Quality Check',
            'configuration_key' => 'MAILBEEZ_DASHBOARD_DQ_CHECK_STATUS',
            'configuration_value' => 'True',
            'configuration_description' => 'Do you want to show the MailBeez Data Quality Check on the dashboard? (recommended)',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'Sort order of display.',
            'configuration_key' => 'MAILBEEZ_DASHBOARD_DQ_CHECK_SORT_ORDER',
            'configuration_value' => '40',
            'configuration_description' => 'Sort order of display. Lowest is displayed first.',
            'set_function' => ''
        ));
    }


    function keys()
    {
        return array('MAILBEEZ_DASHBOARD_DQ_CHECK_STATUS', 'MAILBEEZ_DASHBOARD_DQ_CHECK_SORT_ORDER');
    }

}

