<?php

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

  Copyright (c) 2010 - 2012 MailBeez

  Released under the GNU General Public License
 */

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

require_once(MH_DIR_CONFIG . 'config_customer_insight/classes/viewbeez.php');
//require_once(MH_DIR_CONFIG . 'config_customer_insight/classes/notificationbeez.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/mailbeez_analytics.php');

//require_once(DIR_WS_CLASSES . 'currencies.php');
//$currencies = new currencies();

class view_mailbeezstats extends viewbeez
{

// class constructor
    function __construct()
    {
        parent::__construct();
        $this->code = 'view_mailbeezstats';
        $this->module = 'view_mailbeezstats';
        $this->version = '1.0';
        $this->title = mh_lng('MAILBEEZ_VIEW_MBSTATS_TITLE');
        $this->description = mh_lng('MAILBEEZ_VIEW_MBSTATS_DESCRIPTION');
        $this->sort_order = 2;
        $this->hidden = false;
        $this->hidden_dashboard = true;
        $this->enabled = true;
        $this->is_prospect_enabled = true;
        $this->set_template();
        $this->menu_cnt_default = $this->cnt_msg();
        $this->app_cache_time = 15 * 60;
        $this->panel_ajax_refresh = true;
    }

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

    function get_view_content($template)
    {
        $smarty = $this->init_view_content($template);

        list($history_result, $history_blocks) = $this->get_mailbeez_history($this->customer->id);
        $smarty->assign('msg_history', $history_result);
        $smarty->assign('block_history', $history_blocks);

        if (mh_cfg('MAILBEEZ_EMAIL_ARCHIVE_STATUS') == 'True') {
            require_once(MH_DIR_CONFIG . 'config_email_archive.php');
            $cfg_ea = new config_email_archive();
            $smarty->assign('email_archive', $cfg_ea->enabled);
        }

        return $this->parse_view_content($smarty, $template);
    }

    function get_view_summary()
    {
        return false;
    }

    function get_view_panel()
    {

        $this->set_cache_id('mailbeez_stats_panel' . mh_cfg('MAILBEEZ_SIMULATION'), 'crm_panel');

        if ($cache = $this->read_cache('app')) {
            return $cache['value'];
        }

        $mb_analytics = new mailbeez_analytics();

        list($cnt_sent, $cnt_opened, $cnt_clicked, $cnt_delivered) = $mb_analytics->get_engagement_data();
        list($revenue_value, $cnt_orders) = $mb_analytics->get_orders_data();

        $pct_delivered = ($cnt_sent > 0) ? $cnt_delivered / $cnt_sent * 100 : 0;

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

        $revenue = mh_price((float)$revenue_value);
//        $revenue = (int) $revenue_value;

        $smarty = $this->init_view_panel($this->module);

        $smarty->assign(array('cnt_sent' => $cnt_sent,
            'cnt_delivered' => $cnt_delivered,
            'cnt_opened' => $cnt_opened,
            'cnt_clicked' => $cnt_clicked,
            'cnt_orders' => $cnt_orders,
            'pct_delivered' => $pct_delivered,
            'pct_opened' => $pct_opened,
            'pct_clicked' => $pct_clicked,
            'pct_ordered' => $pct_ordered,
            'revenue' => $revenue));

        $content = $this->parse_view_panel($smarty);
        return $this->set_cache($content, 'app');

    }

    function get_view_dashboard_widget()
    {
        return false;
    }

    function get_view_dashboard_content($template)
    {
        return false;
    }

    function get_view_la_widget()
    {
        $smarty = $this->init_view_la_widget();

        $limit = 5;

        list($history_result, $history_blocks) = $this->get_mailbeez_history($this->customer->id, $limit);
        $smarty->assign('msg_history', $history_result);
        $smarty->assign('more_msg', $this->cnt_msg() - $limit);

        return $this->parse_view_la_widget($smarty);
    }


    function get_mailbeez_history($customer_id, $limit = 100)
    {
//        return false;
        $this->set_cache_id('msg_history' . MAILBEEZ_SIMULATION, $customer_id);

        if ($cache = $this->read_cache()) {
            $return = $cache['value'];
            $return_history = (is_array($return['history'])) ? array_slice($return['history'], 0, $limit) : $return['history'];
            $return_block = (is_array($return['block'])) ? array_slice($return['block'], 0, $limit) : $return['block'];

//            return array($return_history, $return_block);
        }

        $report_query_raw = "select t.* from " . TABLE_MAILBEEZ_TRACKING . " t
                             where t.customers_id='" . $customer_id . "' and length(t.message_id) > 10 order by t.autoemail_id DESC";
        $query = mh_db_query($report_query_raw);


        $items = array();
        $block_items_raw = array();
        $block_items = array();
        $result = array();

        while ($row = mh_db_fetch_array($query)) {
            $row['view_archive_url'] = mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=config_email_archive/admin_application_plugins/view_email_archive.php&popup=true&message_id=' . $row['message_id']);


            if (MAILBEEZ_SIMULATION == 'False' && $row['simulation'] > 0) {
                continue;
            } elseif (mh_cfg('MAILBEEZ_SIMULATION') == 'True') {
                $row['mode'] = ($row['simulation'] > 0 ? 'SIM' : 'PROD');
            }

            $row['engagement_bounced'] = ($row['bounce_status'] != '') ? $row['bounce_status'] : 0;
            $row['engagement_opened'] = ($row['opened'] != '0000-00-00 00:00:00' && $row['opened'] != '') ? 1 : 0;
            $row['engagement_clicked'] = ($row['clicked'] != '0000-00-00 00:00:00' && $row['clicked'] != '') ? 1 : 0;
            $row['engagement_ordered'] = ($row['ordered'] != '0000-00-00 00:00:00' && $row['ordered'] != '') ? 1 : 0;
//            $row['engagement_blocked'] = ($row['block_dateday'] != '0000-00-00 00:00:00' && $row['block_dateday'] != '') ? 1 : 0;

            $row['engagement_flag'] = ($row['engagement_opened'] || $row['engagement_clicked'] || $row['engagement_ordered']) ? 1 : 0;

            $row['engagement_coupon_sent'] = ($row['coupon_id'] > 0) ? 1 : 0;
            $row['engagement_coupon_applied'] = ($row['coupon_redeemed'] > 0) ? 1 : 0;

            array_push($items, $row);
        }


        $report_block_query_raw = "select b.*, date_format(b.date_block, '%Y-%m-%d') as block_dateday from " . TABLE_MAILBEEZ_BLOCK . " b
                            where b.simulation = 0 and b.customers_id='" . $customer_id . "' order by b.date_block DESC";
        $block_query = mh_db_query($report_block_query_raw);

        while ($block_row = mh_db_fetch_array($block_query)) {
            $row['engagement_blocked'] = ($block_row['block_dateday'] != '0000-00-00 00:00:00' && $block_row['block_dateday'] != '') ? 1 : 0;

            array_push($block_items_raw, $block_row);
        }

        foreach ($block_items_raw as $i => $bitem) {
            if ($bitem['module'] == 'ALL') {
                $block_items = array();
                $block_items[] = $bitem;
                break;
            } else {
                $block_items[] = $bitem;
            }
        }

        $result['rows']['history'] = (sizeof($items) > 0) ? $items : 0;
        $result['rows']['block'] = (sizeof($block_items) > 0) ? $block_items : 0;

        $return = $this->set_cache($result['rows']);


        $return_history = (is_array($return['history'])) ? array_slice($return['history'], 0, $limit) : $return['history'];
        $return_block = (is_array($return['block'])) ? array_slice($return['block'], 0, $limit) : $return['block'];

        return array($return_history, $return_block);

    }

    /*
    public function data_update()
    {
        $this->set_cache_id('mailbeez_stats_panel' . MAILBEEZ_SIMULATION, 'crm_panel');
        $this->purge_cache('app');
    }

    */

    function cnt_msg()
    {
        if ($this->customer->id > 0) {
            list($history_result, $history_blocks) = $this->get_mailbeez_history($this->customer->id);
            $cnt = (is_array($history_result)) ? sizeof($history_result) : $history_result;
            return $cnt;
        } else {
            return 0;
        }
    }
}


