<?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.

 */

require_once(mh_cfg('MH_DIR_CONFIG') . 'config_customer_insight.php');
require_once(mh_cfg('MH_DIR_CONFIG') . 'config_customer_insight/classes/context_date.php');


// backwards compatibility
if ((mh_cfg('MAILBEEZ_LIVEAGENT_STATUS') == 'True') ||
    (mh_cfg('MAILBEEZ_BEEZDESK_STATUS') == 'True')
) {
    if (file_exists(mh_cfg('MH_DIR_CONFIG') . 'config_liveagent.php')) {
        include_once(mh_cfg('MH_DIR_CONFIG') . 'config_liveagent.php');
    }
    if (file_exists(MH_DIR_CONFIG . 'config_beezdesk.php')) {
        include_once(mh_cfg('MH_DIR_CONFIG') . 'config_beezdesk.php');
    }
}

mh_define('TABLE_MAILBEEZ_CUSTOMER_MAPPING', DB_PREFIX . 'mailbeez_beezdesk_customer_mapping');


class mh_insight_customer
{
    var $email;
    var $admin_language;
    var $language;

    var $id;
    var $cid;
    var $firstname;
    var $lastname;
    var $status;
    var $bounces;
    var $hasHardBounce;
    var $status_name;
    var $guest_account = false;
    var $birthdate;
    var $next_birthdate;
    var $telephone;
    var $fax;
    var $date_added;
    var $date_last_modiefied;
    var $vat_id;
    var $default_address_id;
    var $user_image;

    var $last_order_id;
    var $date_last_order;

    var $def_addr_gender;
    var $def_addr_company;
    var $def_addr_firstname;
    var $def_addr_lastname;
    var $def_addr_street_address;
    var $def_addr_suburb;
    var $def_addr_postcode;
    var $def_addr_city;
    var $def_addr_state;
    var $def_addr_country_id;
    var $def_addr_country_name;
    var $def_addr_country_code;
    var $def_addr_zone_id;

    var $is_prospect;

    function __construct($email = false, $admin_language = '', $language = '')
    {


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


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

        // basic test: is email?
        if (!stristr($email, '@')) {
            return false;
        }
        if ($this->loadCustomer($email)) {
            if ($this->default_address_id != '') {
                $this->loadCustomersDefaultAddress($this->default_address_id, $this->id);
            }
            $this->getLastOrder();
        } else {
            return false;
        }
    }


    function loadCustomer($email)
    {
        $customer_loaded = false;
        $this->id = null;
        $customers_status_query = '';
        $customers_status_query_join = '';
        $customers_status_where = '';

        //customers_status for xt:commerce
        if (config_customer_insight::db_field_exists('TABLE_CUSTOMERS', 'customers_status') && defined('TABLE_CUSTOMERS_STATUS')) {
            $customers_status_query = 'c.customers_status, cs.customers_status_name, ';
            $customers_status_query_join = " INNER JOIN " . TABLE_CUSTOMERS_STATUS . " cs ON c.customers_status = cs.customers_status_id ";
            $customers_status_where = " AND cs.language_id = '" . mh_db_input($this->admin_language) . "' ";

            $orders_customers_status_query = 'o.customers_status, cs.customers_status_name, ';
            $orders_customers_status_query_join = " INNER JOIN " . TABLE_CUSTOMERS_STATUS . " cs ON o.customers_status = cs.customers_status_id ";
            $orders_customers_status_where = " AND cs.language_id = '" . mh_db_input($this->admin_language) . "' ";
        }

        $beezdesk_installed = mh_cfg('MAILBEEZ_BEEZDESK_STATUS') == 'True';
        $beezdesk_customers_join = '';
        $beezdesk_customers_where = ')';


        if ($beezdesk_installed) {
            $beezdesk_customers_join = " LEFT JOIN " . TABLE_MAILBEEZ_CUSTOMER_MAPPING . " map
                                        ON c.customers_id = map.customers_id ";
            $beezdesk_customers_where = " OR map.beezdesk_email_address = '" . mh_db_input($email) . "') ";
        }

        $additional_customer_fields = '';
        $additional_order_fields = '';

        if (config_customer_insight::db_field_exists('TABLE_CUSTOMERS', 'customers_cid')) {
            $additional_customer_fields .= ", c.customers_cid";
        }
        if (config_customer_insight::db_field_exists('TABLE_CUSTOMERS', 'customers_date_added')) {
            $additional_customer_fields .= ", c.customers_date_added";
        }
        if (config_customer_insight::db_field_exists('TABLE_CUSTOMERS', 'customers_last_modified')) {
            $additional_customer_fields .= ", c.customers_last_modified";
        }
        if (config_customer_insight::db_field_exists('TABLE_CUSTOMERS', 'customers_vat_id')) {
            $additional_customer_fields .= ", c.customers_vat_id";
        }
        if (config_customer_insight::db_field_exists('TABLE_CUSTOMERS', 'customers_telephone')) {
            $additional_customer_fields .= ", c.customers_telephone";
        }
        if (config_customer_insight::db_field_exists('TABLE_CUSTOMERS', 'customers_fax')) {
            $additional_customer_fields .= ", c.customers_fax";
        }

        if (config_customer_insight::db_field_exists('TABLE_ORDERS', 'customers_cid')) {
            $additional_order_fields .= ", o.customers_cid";
        }
        if (config_customer_insight::db_field_exists('TABLE_ORDERS', 'customers_vat_id')) {
            $additional_order_fields .= ", o.customers_vat_id";
        }
        if (config_customer_insight::db_field_exists('TABLE_ORDERS', 'customers_firstname')) {
            $additional_order_fields .= ", o.customers_firstname";
        }
        if (config_customer_insight::db_field_exists('TABLE_ORDERS', 'customers_lastname')) {
            $additional_order_fields .= ", o.customers_lastname";
        }


        // Load customers data		
        $query_sql = "SELECT c.customers_id,  c.customers_firstname, c.customers_lastname, c.customers_email_address, " . $customers_status_query . " c.customers_dob, c.customers_default_address_id
            " . $additional_customer_fields . "
                        FROM " . TABLE_CUSTOMERS . " c " . $customers_status_query_join . '
                        ' . $beezdesk_customers_join . "
                      WHERE (c.customers_email_address = '" . mh_db_input($email) . "'
                        " . $beezdesk_customers_where . $customers_status_where . "
                        order by c.customers_id DESC
                        ";

        // get the latest customer id

        $query = mh_db_query($query_sql);

        if (mh_db_num_rows($query) > 0) {
            $customer = mh_db_fetch_array($query);

            // specific properties
            $this->birthdate = $customer['customers_dob'];
            $this->next_birthdate = context_date::nextBirthdate($customer['customers_dob']);
            $this->fax = $customer['customers_fax'];
            $this->date_added = isset($customer['customers_date_added']) ? $customer['customers_date_added'] : '';
            $this->date_last_modiefied = isset($customer['customers_last_modified']) ? $customer['customers_last_modified'] : '';

            $customer_loaded = true;
        } else {
            if ($beezdesk_installed) {
                $beezdesk_customers_join = " LEFT JOIN " . TABLE_MAILBEEZ_CUSTOMER_MAPPING . " map
                                            ON o.customers_id = map.customers_id ";
                $beezdesk_customers_where = " OR map.beezdesk_email_address = '" . mh_db_input($email) . "') ";
            }

            // Load customers data from orders if customers data is empty (guest account)
            $query_sql = "SELECT o.customers_id, o.customers_email_address, " . $orders_customers_status_query . " o.customers_company, o.customers_street_address, o.customers_suburb, o.customers_postcode, o.customers_city, o.customers_state, o.customers_country " . $additional_order_fields . "
                            FROM " . TABLE_ORDERS . " o " . $orders_customers_status_query_join . '
                        ' . $beezdesk_customers_join . "
                            WHERE (o.customers_email_address = '" . mh_db_input($email) . "'
                                " . $beezdesk_customers_where . $orders_customers_status_where;
            $query = mh_db_query($query_sql);
            if (mh_db_num_rows($query) > 0) {
                $customer = mh_db_fetch_array($query);

                // specific properties
                $this->def_addr_gender = '';
                $this->def_addr_company = $customer['customers_company'];
                $this->def_addr_firstname = $customer['customers_firstname'];
                $this->def_addr_lastname = $customer['customers_lastname'];
                $this->def_addr_street_address = $customer['customers_street_address'];
                $this->def_addr_suburb = $customer['customers_suburb'];
                $this->def_addr_postcode = $customer['customers_postcode'];
                $this->def_addr_city = $customer['customers_city'];
                $this->def_addr_state = $customer['customers_state'];
                $this->def_addr_country_id = $this->mh_getCountriesId($customer['customers_country']);
                $this->def_addr_country_name = $this->mh_getCountriesName($this->def_addr_country_id);
                $this->def_addr_country_code = $this->mh_getCountriesCode2($this->def_addr_country_id);
                $this->def_addr_zone_id = '';
                $this->guest_account = true;
                $customer_loaded = true;
            }
        }

        if ($customer_loaded) {
            // common properties
            $this->email = mh_arr_val($customer, 'customers_email_address');
            $this->id = mh_arr_val($customer, 'customers_id');
            $this->cid = mh_arr_val($customer, 'customers_cid');
            $this->firstname = mh_arr_val($customer, 'customers_firstname');
            $this->lastname = mh_arr_val($customer, 'customers_lastname');
            $this->status = mh_arr_val($customer, 'customers_status');
            $this->status_name = mh_arr_val($customer, 'customers_status_name');
            $this->telephone = mh_arr_val($customer, 'customers_telephone');
            $this->vat_id = mh_arr_val($customer, 'customers_vat_id');
            $this->default_address_id = mh_arr_val($customer, 'customers_default_address_id');

        }
        if ($this->status == 1) {
            $this->guest_account = true;
        }


        $this->set_user_image();

        $this->bounces = config_customer_insight::getBounces($this->id);
        $this->hasHardBounce = config_customer_insight::hasHardBounce($this->bounces);

        if ($customer_loaded) {
            return true;
        } else {
            return false;
        }
    }

    function loadCustomersDefaultAddress($address_book_id, $customers_id)
    {
        if ((int)$address_book_id == 0 || (int)$customers_id == 0) return false;

        $query_sql = "SELECT a.entry_gender, a.entry_company, a.entry_firstname, a.entry_lastname, a.entry_street_address, a.entry_suburb, a.entry_postcode, a.entry_city, a.entry_state, a.entry_country_id, a.entry_zone_id
                        FROM " . TABLE_ADDRESS_BOOK . " a
                        WHERE a.customers_id = '" . mh_db_input($customers_id) . "'
                            AND address_book_id = '" . mh_db_input($address_book_id) . "'";
        $query = mh_db_query($query_sql);
        if (mh_db_num_rows($query) > 0) {
            $address = mh_db_fetch_array($query);
            $this->def_addr_gender = $address['entry_gender'];
            $this->def_addr_company = $address['entry_company'];
            $this->def_addr_firstname = $address['entry_firstname'];
            $this->def_addr_lastname = $address['entry_lastname'];
            $this->def_addr_street_address = $address['entry_street_address'];
            $this->def_addr_suburb = $address['entry_suburb'];
            $this->def_addr_postcode = $address['entry_postcode'];
            $this->def_addr_city = $address['entry_city'];
            $this->def_addr_state = $address['entry_state'];
            $this->def_addr_country_id = $address['entry_country_id'];
            $this->def_addr_country_name = $this->mh_getCountriesName($address['entry_country_id']);
            $this->def_addr_country_code = $this->mh_getCountriesCode2($address['entry_country_id']);
            $this->def_addr_zone_id = $address['entry_zone_id'];
            return true;
        }

        return false;
    }

    function getLastOrder()
    {
        $query_sql = "SELECT o.orders_id, o.date_purchased
                        FROM " . TABLE_ORDERS . " o
                      WHERE o.customers_id = '" . mh_db_input($this->id) . "'
                        ORDER BY o.date_purchased DESC LIMIT 1";
        $query = mh_db_query($query_sql);
        if (mh_db_num_rows($query) > 0) {
            $order = mh_db_fetch_array($query);
            $this->last_order_id = $order['orders_id'];
            $this->date_last_order = $order['date_purchased'];
            return true;
        }
        return false;
    }

    function mh_getCountriesId($country)
    {
        if ($country == '') return false;
        $query_sql = "SELECT c.countries_id
                        FROM " . TABLE_COUNTRIES . " c
                      WHERE c.countries_name = '" . mh_db_input($country) . "'";
        $query = mh_db_query($query_sql);
        $countries = mh_db_fetch_array($query);
        return $countries['countries_id'];
    }

    function mh_getCountriesName($country_id)
    {
        if ($country_id == '') return false;
        $query_sql = "SELECT c.countries_name
                        FROM " . TABLE_COUNTRIES . " c
                      WHERE c.countries_id = '" . mh_db_input($country_id) . "'";
        $query = mh_db_query($query_sql);
        $countries = mh_db_fetch_array($query);
        return $countries['countries_name'];
    }

    function mh_getCountriesCode2($country_id)
    {
        if ($country_id == '') return false;
        $query_sql = "SELECT c.countries_iso_code_2
                        FROM " . TABLE_COUNTRIES . " c
                      WHERE c.countries_id = '" . mh_db_input($country_id) . "'";
        $query = mh_db_query($query_sql);
        $countries = mh_db_fetch_array($query);
        return $countries['countries_iso_code_2'];
    }

    function set_user_image()
    {
        $this->user_image = $this->get_gravatar($this->email, 80, 'identicon', 'g');

//        $this->user_image = MH_CATALOG_SERVER . MH_DIR_CONFIG . 'config_customer_insight/images/user.png';
    }

    /**
     * Get either a Gravatar URL or complete image tag for a specified email address.
     *
     * @param string $email The email address
     * @param string $s Size in pixels, defaults to 80px [ 1 - 2048 ]
     * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
     * @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
     * @param boole $img True to return a complete IMG tag False for just the URL
     * @param array $atts Optional, additional key/value attributes to include in the IMG tag
     * @return String containing either just a URL or a complete image tag
     * @source http://gravatar.com/site/implement/images/php/
     */
    function get_gravatar($email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array())
    {
        return false;
//        return "<div class='name'>Cord Rosted</div>";

        $url = '//www.gravatar.com/avatar/';
        $url .= md5(strtolower(trim($email)));
        $url .= "?s=$s&d=$d&r=$r";
        if ($img) {
            $url = '<img src="' . $url . '"';
            foreach ($atts as $key => $val)
                $url .= ' ' . $key . '="' . $val . '"';
            $url .= ' />';
        }
        return $url;
    }

}
