<?php

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

  Copyright (c) 2010 - 2012 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.

 */

// make path work from admin

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

// compatibility

if (!function_exists('mh_log')) {
    function mh_log($logmsg, $logval)
    {
        return false;
    }
}


class config_customer_insight extends configbeez
{

    function __construct()
    {
        // call constructor
        parent::__construct();

        // set some stuff:
        $this->code = 'config_customer_insight';
        $this->module = 'config_customer_insight'; // same as folder name
        $this->version = 4.1; // float value
        $this->required_mb_version = 2.93; // required mailbeez version
        $this->title = mh_lng('MAILBEEZ_INSIGHT_VIEW_TEXT_TITLE');
        $this->description = mh_lng('MAILBEEZ_INSIGHT_VIEW_TEXT_DESCRIPTION');
        $this->icon = 'icon.png';
        $this->sort_order = 50;
        $this->enabled = mh_cfg('MAILBEEZ_INSIGHT_VIEW_STATUS') == 'True';
        $this->status_key = 'MAILBEEZ_INSIGHT_VIEW_STATUS';
        $this->certificate_key = mh_cfg('MAILBEEZ_INSIGHT_VIEW_CERT');
        $this->common_admin_action_plugins = '';

        $this->documentation_key = $this->module; // leave empty if no documentation available
        // $this->documentation_root = 'http:://yoursite.com/' // modify documentation root if necessary

        $this->admin_action_plugins_path = MH_DIR_CONFIG; // default-path to include admin action plugins from
        $this->admin_action_plugins = 'reset_notifications.php';

        // self installing
        if (!mh_cfg($this->status_key)) {
            $this->install();
        } else {
            $this->check_update();
        }

    }

// class methods

    static function db_field_exists($table_const_name, $field_name)
    {

        if (!defined($table_const_name)) return false;

        // caching
        if (!isset($GLOBALS['platform_db_fields_supported_' . $table_const_name])) {
            $GLOBALS['platform_db_fields_supported_' . $table_const_name] = config_customer_insight::mh_db_get_fields(constant($table_const_name));
        }

        return isset($GLOBALS['platform_db_fields_supported_' . $table_const_name][$field_name]);
    }


    function mh_db_check_field_exists_multiple($table, $field_array)
    {
        $fields_exist_array = array();
        $query_raw = "SHOW COLUMNS FROM " . $table . "";
        $query = mh_db_query($query_raw);
        while ($item = mh_db_fetch_array($query)) {
            foreach ($field_array as $field) {
                if ($item['Field'] == $field) {
                    $fields_exist_array[$field] = $field;
                }
            }
        }
        return $fields_exist_array;
    }

    static function mh_db_get_fields($table)
    {
        $fields_exist_array = array();
        $query_raw = "SHOW COLUMNS FROM " . $table . "";
        $query = mh_db_query($query_raw);
        while ($item = mh_db_fetch_array($query)) {
            $fields_exist_array[$item['Field']] = $item['Field'];
        }
        return $fields_exist_array;
    }

    static function getBounces($contact_id) {

        $sql_query_raw = "select module, date_bounce, bounce_type, reference from " . TABLE_MAILBEEZ_BOUNCE . " where customers_id = '" . $contact_id . "'";
        $sql_query = mh_db_query($sql_query_raw);

        $data = array();
        if (mh_db_num_rows($sql_query) > 0) {
            while ($query = mh_db_fetch_array($sql_query)) {
                $data[] = $query;
            }

        }
        return $data;
    }

    static function hasHardBounce($bounceData) {
        foreach ($bounceData as $b) {
            if ($b['bounce_type'] == 'H') return true;
        }
        return false;
    }

    // installation methods

    function keys()
    {
        if (isset($this->keys)) return $this->keys;

        if (MH_PLATFORM == 'gambio' && MH_PLATFORM_GAMBIO < 2.5 || MH_PLATFORM == 'zencart') {
            return array('MAILBEEZ_INSIGHT_VIEW_STATUS', 'MAILBEEZ_INSIGHT_PANEL_TAB_SIZE', 'MAILBEEZ_INSIGHT_PANEL_TAB_POS_RELATIVE', 'MAILBEEZ_INSIGHT_PANEL_TAB_POS_VALUE', 'MAILBEEZ_INSIGHT_EXCLUDE_PAGES', 'MAILBEEZ_INSIGHT_WELCOME_CONVERSATION_HIDE');
        }
        // 'MAILBEEZ_INSIGHT_VIEW_MODE', removed
        return array('MAILBEEZ_INSIGHT_VIEW_STATUS',  'MAILBEEZ_INSIGHT_PANEL_TAB_SIZE', 'MAILBEEZ_INSIGHT_PANEL_TAB_POS_RELATIVE', 'MAILBEEZ_INSIGHT_PANEL_TAB_POS_VALUE', 'MAILBEEZ_INSIGHT_EXCLUDE_PAGES', 'MAILBEEZ_INSIGHT_WELCOME_CONVERSATION_HIDE');
    }

    function install()
    {

        mh_insert_config_value(array('configuration_title' => 'Activate Customer Insight?',
            'configuration_key' => 'MAILBEEZ_INSIGHT_VIEW_STATUS',
            'configuration_value' => 'True',
            'configuration_description' => 'Do you want to activate the Customer Insight Module?',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Hide Welcome Conversation?',
            'configuration_key' => 'MAILBEEZ_INSIGHT_WELCOME_CONVERSATION_HIDE',
            'configuration_value' => 'False',
            'configuration_description' => 'Do you want to hide the welcome conversation example?',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_db_query("CREATE TABLE IF NOT EXISTS " . DB_PREFIX . "mailbeez_notifications (
			    id int NOT NULL auto_increment,
			    title varchar(255),
			    notification_summary varchar(255),
			    notification text,
			    link text,
				ref INT NOT NULL,
				iteration INT( 11 ) DEFAULT NULL ,
			    module varchar(255) DEFAULT NULL,
				customers_id INT( 11 ) DEFAULT NULL ,
				channel_id INT( 2 ) DEFAULT NULL ,
				severity INT(1),
				status INT(1),
				date_added DATETIME DEFAULT NULL,
				last_modified DATETIME DEFAULT NULL,
				PRIMARY KEY ( id ),
				INDEX ( ref, customers_id, iteration, module ) );");

        $this->update($this->version);
    }

    function remove()
    {
        $default_keys = $this->keys();
        $this->keys = array_merge($default_keys, array());
        parent::remove();
    }

    function update($installed_version = null)
    {

        mh_insert_config_value(array('configuration_title' => 'Panel effect',
            'configuration_key' => 'MAILBEEZ_INSIGHT_VIEW_MODE',
            'configuration_value' => 'simple',
            'configuration_description' => 'Simple for best compatibility, mega for a nice effect. Choose simple as soon as you get any issues on your admin pages.',
            'set_function' => 'mh_cfg_select_option(array(\'simple\', \'mega\'), '
        ));

        $sql = array();
        $sql[] = "ALTER TABLE " . DB_PREFIX . "mailbeez_notifications" . " ADD notification_summary  varchar(255) ;";
        mh_db_add_field(DB_PREFIX . "mailbeez_notifications", 'notification_summary', $sql);

        $sql = array();
        $sql[] = "ALTER TABLE " . DB_PREFIX . "mailbeez_notifications" . " ADD icon_style varchar(255) ;";
        mh_db_add_field(DB_PREFIX . "mailbeez_notifications", 'icon_style', $sql);

        $sql = array();
        $sql[] = "ALTER TABLE " . DB_PREFIX . "mailbeez_notifications" . " ADD link_type varchar(1) ;";
        mh_db_add_field(DB_PREFIX . "mailbeez_notifications", 'link_type', $sql);
        $sql = array();
        $sql[] = "ALTER TABLE " . DB_PREFIX . "mailbeez_notifications" . " ADD panel_click_action varchar(1) ;";
        mh_db_add_field(DB_PREFIX . "mailbeez_notifications", 'panel_click_action', $sql);

        $sql = array();
        $sql[] = "ALTER TABLE " . DB_PREFIX . "mailbeez_notifications" . " ADD notification_only varchar(1) ;";
        mh_db_add_field(DB_PREFIX . "mailbeez_notifications", 'notification_only', $sql);


        mh_insert_config_value(array('configuration_title' => 'Activate Notifications?',
            'configuration_key' => 'MAILBEEZ_INSIGHT_NOTIFICATION_STATUS',
            'configuration_value' => 'True',
            'configuration_description' => 'Do you want to activate Notifications?',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Exclude BeezDesk CRM Pad',
            'configuration_key' => 'MAILBEEZ_INSIGHT_EXCLUDE_PAGES',
            'configuration_value' => 'FILENAME_LOGIN;magnalister;attribute_manager',
            'configuration_description' => 'Exclude following pages (separated by ;)',
        ));


        mh_insert_config_value(array('configuration_title' => 'Tab Size',
            'configuration_key' => 'MAILBEEZ_INSIGHT_PANEL_TAB_SIZE',
            'configuration_value' => 'Normal',
            'configuration_description' => 'Configure the size of the BeezDesk CRM Pad tab',
            'set_function' => 'mh_cfg_select_option(array(\'Normal\', \'Mini\'), '

        ));

        mh_insert_config_value(array('configuration_title' => 'Tab Position',
            'configuration_key' => 'MAILBEEZ_INSIGHT_PANEL_TAB_POS_RELATIVE',
            'configuration_value' => 'top',
            'configuration_description' => 'Configure the position, e.g. measured from "top" or "bottom"',
            'set_function' => 'mh_cfg_select_option(array(\'top\', \'bottom\'), '

        ));

        mh_insert_config_value(array('configuration_title' => 'Tab Position value',
            'configuration_key' => 'MAILBEEZ_INSIGHT_PANEL_TAB_POS_VALUE',
            'configuration_value' => '75%',
            'configuration_description' => 'Configure the value e.g. "75%" or "20px"',
        ));

        parent::update($this->version);
    }


}

if (!function_exists('mh_datetime_short')) {
    function mh_datetime_short()
    {
        $args = func_get_args();
        switch (MH_PLATFORM) {
            case 'oscommerce':
            case 'creloaded':
            case 'digistore':
                return call_user_func_array('tep_datetime_short', makeValuesReferenced($args));
                break;
            case 'mercari':
                return call_user_func_array('datetime_short', makeValuesReferenced($args));
                break;
            case 'zencart':
                return call_user_func_array('zen_datetime_short', makeValuesReferenced($args));
                break;
            case 'xtc':
            case 'gambio':
                return call_user_func_array('xtc_datetime_short', makeValuesReferenced($args));
                break;
            default:
                echo 'platform not supported';
        }
    }
}

