<?php

/*
 * MailBeez Aps 2017
 *
 *
 * current limitations
 * ---------------------------
 *
 * getCustomers:
 *  - it is not possible to select changes to customers by "hours"
 *
 * getProductInfo:
 *  - only main image
 *
 * setUnsubscribe
 *  - not yet implemented
 *
 * setBounce
 *  - not yet implemented
 *
 * setUnsubscribe
 *  - not yet implemented
 *
 */

class api_newsletter2go_v2
{

    public function testConnection()
    {
        $data = array('result' => true);
        return $this->handleRequest($data);
    }

    public function getShopName()
    {
        $data = array('result' => 'MailBeez');
        return $this->handleRequest($data);
    }

    public function getShopPrefix()
    {
        $data = array('result' => 'mbz');
        return $this->handleRequest($data);
    }


    public function getCustomers($params)
    {
        // $hours = $params['hours']; // not implemented
        $newsletterSubscribersOnly = (isset($params['newsletterSubscribersOnly'])) ? $params['newsletterSubscribersOnly'] : false;

        $query_raw = "select c.customers_firstname, c.customers_lastname, c.customers_gender, c.customers_email_address, c.customers_dob, date_format(c.customers_dob, '%d.%m.%Y') as date_of_birth
                    from " . TABLE_CUSTOMERS . " c where true";

        $query_raw .= (($newsletterSubscribersOnly == 1) ? " and customers_newsletter = 1 " : '');

        $query = mh_module_query($this, $query_raw);

        $customer_data = array();
        while ($item = mh_db_fetch_array($query)) {
            $customer_data[] = array('firstname' => $item['customers_firstname'],
                'lastname' => $item['customers_lastname'],
                'gender' => $item['customers_gender'],
                'mail' => $item['customers_email_address'],
                'mobile' => null,
                'birthday' => $item['date_of_birth'],
            );
        }

        $data = array('result' => $customer_data,
            'info' => array(
                'count' => sizeof($customer_data)
            ));

        return $this->handleRequest($data);
    }

    public function setBounce($params)
    {
        $email = $params['email'];
        $result = $this->trackBounce($email);
        return $this->handleRequest($result);
    }


    public function setUnsubscribe($params)
    {
        $email = $params['email'];
        $result = $this->doUnsubscribe($email);
        return $this->handleRequest($result);
    }


    public function getProductInfo($params)
    {
        $identifier = $params['identifier'];
        $_filter_language_code = (isset($params['language'])) ? $params['language'] : null;

        if (!isset($lng) || (isset($lng) && !is_object($lng))) {
            if (!class_exists('language')) {
                include(DIR_WS_CLASSES . 'language.php');
            }
            $lng = new language;
        }

        $language_code_map = array();


        if ($_filter_language_code) {
            $lang_info = $lng->catalog_languages[$_filter_language_code];
            $language_id = $lang_info['id'];
            $language_code_map[$language_id] = $_filter_language_code;
        } else {
            foreach ($lng->catalog_languages as $lng_code => $lng_code_data) {
                $lang_info = $lng_code_data;
                $language_code_map[$lang_info['id']] = $lng_code;
            }
        }


        $query_products_raw = "select distinct p.products_model, p.products_image,  p.products_id, pd.language_id, pd.products_name, pd.products_description, p.products_price, p.products_tax_class_id, IF(s.status, s.specials_new_products_price, NULL) as specials_new_products_price, IF(s.status, s.specials_new_products_price, p.products_price) as final_price , IF(s.status, p.products_price, s.specials_new_products_price) as old_price
                                from " . TABLE_PRODUCTS . " p
                                    join " . TABLE_PRODUCTS_DESCRIPTION . " pd on (p.products_id = pd.products_id)
                                     left join " . TABLE_SPECIALS . " s on p.products_id = s.products_id
                                where p.products_status = '1'
                                    and p.products_id = " . (int)$identifier . " ";
        if ($_filter_language_code) {
            $query_products_raw .= " and pd.language_id = '" . (int)$language_id . "' limit 1";
        }

        //$data = array('result' => $query_products_raw);
        //return $this->handleRequest($data);


        $query_products = mh_db_query($query_products_raw);

        $products_data = array();

        while ($products_array = mh_db_fetch_array($query_products)) {
            $link = mh_href_email_link(FILENAME_PRODUCT_INFO, 'products_id=' . $products_array['products_id']);

            $image = '';
            if (mh_not_null($products_array['products_image'])) {
                $image = mh_product_image_src(mh_product_image($products_array));
                $image = str_replace('thumbnail', 'info', $image);
            }
            $image_array = array();
            $image_array[] = $image;
            $url_data = parse_url($link);
            $url = $url_data['scheme'] . '://' . $url_data['host']; // . $url_data['path'];

            $lng_code = (isset($language_code_map[$products_array['language_id']])) ? $language_code_map[$products_array['language_id']] : $products_array['language_id'];

            $products_data[$lng_code] = array(
                'itemId' => $products_array['products_id'],
                'name' => $products_array['products_name'],
                'oldPrice' => $products_array['old_price'],
                'newPrice' => $products_array['final_price'],
                'url' => $url,
                'link' => $link,
                'shortDescription' => $products_array['products_name'] . ' ' . $products_array['products_model'], // todo: limit
                'description' => $products_array['products_description'],
                'images' => $image_array
            );
        }
        if ($_filter_language_code) {
//            $products_data = $products_data[$_filter_language_code];

        }

        $data = array('result' => $products_data,
            'info' => array(
                'count' => (sizeof($products_data) > 0) ? 1 : 0
            ));

        return $this->handleRequest($data);
    }


    public function checkApiKey($secret)
    {
        return ($secret == mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_V2_SECRET'));
//        return ($auth_key == mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_V2_AUTH_KEY'));
    }


    function handleRequest($result)
    {
        $data = array(
            "success" => '1',
            "status" => ((isset($result['status'])) ? $result['status'] : '200'),
            "code" => ((isset($result['code'])) ? $result['code'] : '200'),
            "errorMessage" => $result['errorMessage'],
            "successMessage" => $result['successMessage'],
            "value" => $result['result'],
            "info" => $result['info']
        );

        foreach ($data as $k => $v) {
            if (is_null($v)) {
                unset($data[$k]);
            }
        }

        return $data;
    }

    private function doUnsubscribe($email_address)
    {
        if (!stristr($email_address, '@')) {
            $result = array(
                "status" => '400',
                "code" => '400',
                "errorMessage" => "invalid Email Address",
            );
            return $result;
        }


        require_once(MH_DIR_CONFIG . 'config_block.php');

        //get
        $customers_ids = self::getCustomerIdsByEmail($email_address);

        if ($customers_ids) {
            $cfg_block = new config_block();
            foreach ($customers_ids as $cid) {
                $result = $cfg_block->process_block('ALL', $cid, $email_address, 4, false, 'prod', 'Global', false);
            }
            $data = array(
                "status" => '200',
                "code" => '200',
                "errorMessage" => '',
                "info" => array('count' => sizeof($customers_ids))
            );
        } else {

            $data = array(
                "status" => '404',
                "code" => '404',
                "errorMessage" => 'no customer found for given Email Address',
            );
        }
        return $data;
    }

    private static function getCustomerIdsByEmail($email)
    {
        $customer_sql = "select distinct customers_id from " . TABLE_CUSTOMERS . " c
                                 where customers_email_address = '" . $email . "'";
        $query = mh_db_query($customer_sql);

        if (mh_db_num_rows($query) > 0) {
            $result = array();
            while ($result_array = mh_db_fetch_array($query)) {
                $result[] = $result_array['customers_id'];
            }
            return $result;
        } else {
            return false;
        }
    }


    private function trackBounce($bounced_email_address)
    {

        // prepare for email addresses like test'@gmail.com

        $bounced_email_address = mh_db_input($bounced_email_address);

        if (!stristr($bounced_email_address, '@')) {
            $result = array(
                "status" => '400',
                "code" => '400',
                "errorMessage" => "invalid Email Address",
            );
            return $result;
        }


        // check against written bounces
        $sql_query_raw = "select id from " . TABLE_MAILBEEZ_BOUNCE . " where customers_email = '" . $bounced_email_address . "'";
        $sql_query = mh_db_query($sql_query_raw);

        if (mh_db_num_rows($sql_query) > 0) {
            // already processed
            $result = array(
                "status" => '200',
                "code" => '200',
                "successMessage" => "$bounced_email_address already processed",
            );
            return $result;
        }


        // try to match email with mailbeez tracking data
        $sql_query_raw = "select autoemail_id, module, customers_email, customers_id, bounce_status
                                from " . TABLE_MAILBEEZ_TRACKING . "
                                where customers_email = '" . $bounced_email_address . "'
                                    and bounce_status = ''
                                order by autoemail_id DESC
                                limit 1";

        $sql_query = mh_db_query($sql_query_raw);

        // found matching entry
        if (mh_db_num_rows($sql_query) > 0) {
            $query = mh_db_fetch_array($sql_query);
            $sql_data_array = array('autoemail_id' => $query['autoemail_id'],
                'customers_email' => $query['customers_email'],
                'customers_id' => $query['customers_id'],
                'module' => $query['module'],
                'date_bounce' => 'now()',
                'bounce_type' => 'S'
            );

            mh_db_perform(TABLE_MAILBEEZ_BOUNCE, $sql_data_array);

            /*
            if (mh_get_conf('MAILBEEZ_BOUNCEHIVE_UNSUBSCRIBE') == 'True') {
                mailbeez_bounce_unsubscribe($query['customers_id'], 'H');
            }
            */

            if (mh_cfg('MAILBEEZ_BOUNCEHIVE_MSG_LOG') == 'True') {
                $sql_data_array = array('autoemail_id' => $query['autoemail_id'],
                    'bounce_msg' => 'Newsletter2Go Hard Bounce',
                );
                mh_db_perform(TABLE_MAILBEEZ_BOUNCE_MSG_LOG, $sql_data_array);
            }

            mh_db_query("update " . TABLE_MAILBEEZ_TRACKING . "
                                set bounce_status = 'S'
                                where autoemail_id = '" . $query['autoemail_id'] . "'");

            $result = array(
                "status" => '200',
                "code" => '200',
                "successMessage" => "$bounced_email_address matched to mailbeez email",
            );
            return $result;
        } else {
            // add bounce data for unknown mail

            //echo "handling bounced on unknown mail<hr>";
            $sql_query_raw = "select customers_id, customers_email_address
                                    from " . TABLE_CUSTOMERS . "
                                    where customers_email_address = '" . $bounced_email_address . "'";

            $sql_query = mh_db_query($sql_query_raw);

            if (mh_db_num_rows($sql_query) > 0) {

                // write for all matching customer ids
                while ($query = mh_db_fetch_array($sql_query)) {
                    $sql_data_array = array('autoemail_id' => -1,
                        'customers_email' => $query['customers_email_address'],
                        'customers_id' => $query['customers_id'],
                        'module' => 'n/a',
                        'date_bounce' => 'now()',
                        'bounce_type' => 'S'
                    );

                    mh_db_perform(TABLE_MAILBEEZ_BOUNCE, $sql_data_array);
                }

                $result = array(
                    "status" => '200',
                    "code" => '200',
                    "successMessage" => "$bounced_email_address matched to customer",
                );
                return $result;
            } else {
                // track all other email addresses as well
                $sql_data_array = array('autoemail_id' => -1,
                    'customers_email' => $bounced_email_address,
                    'customers_id' => -1,
                    'module' => 'n/a',
                    'date_bounce' => 'now()',
                    'bounce_type' => 'S'
                );

                mh_db_perform(TABLE_MAILBEEZ_BOUNCE, $sql_data_array);

                $result = array(
                    "status" => '200',
                    "code" => '200',
                    "successMessage" => "$bounced_email_address unknown, tracked",
                );
                return $result;
            }
        }
    }
}
