<?php

// make path work from admin
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/mailbeez.php');

class service_newsletter2go_api extends mailbeez
{
    // class constructor
    function __construct()
    {
        // call constructor
        parent::__construct();

        // set some stuff:
        $this->code = 'service_newsletter2go_api';
        $this->module = 'service_newsletter2go_api';
        $this->version = '1.6'; // float value
        $this->required_mb_version = 2.8; // required mailbeez version
        $this->iteration = 1;
        $this->title = mh_lng('MAILBEEZ_N2GO_API_TITLE');
        $this->description = mh_lng('MAILBEEZ_N2GO_API_DESCRIPTION');
        $this->sort_order = -1;
        $this->enabled = preg_match('/Newsletter2Go/', mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE'));

        $this->documentation_root = 'https://www.mailbeez.com/documentation/configbeez/';
        $this->documentation_key = 'config_email_engine'; // leave empty if no documentation available
        $this->admin_action_plugins = 'process.php';

        $this->common_admin_action_plugins = '';
        $this->do_process = true; // a processable module
        $this->is_editable = false; // allow editor
        $this->is_configurable = false;
        $this->hidden = !preg_match('/Newsletter2Go/', mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE')) || (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_VERSION') == 'v2');
        //$this->hidden = true;
        $this->do_run = true; // run only when called explicit
        $this->removable = false;
        $this->allow_preview = false;
        $this->allow_reporting = false;
        $this->allow_timing = false;
        $this->allow_group_filter_check = false;

    }

    function service_newsletter2go_api()
    {
        self::__construct();
    }

// class methods
    function getAudience()
    {
        return false;
    }

    function process($audience = '', $mode = '')
    {
        $cnt = $this->external_syncBounces('False');
//        mh_exit();
        return -1;
    }

    function processApiCall($apiCall, $params = null)
    {
        // run synchronization tasks
        // work in background
        mailHive::clear_process_lock();
        // return print_r($_POST, true);
        require_once(MH_DIR_CONFIG . 'config_email_engine_n2g/classes/api_newsletter2go.class.php');
        $api = new api_newsletter2go();

        if ($api->checkApiKey($_POST['key'])) {
            echo $api->$apiCall($params);
        } else {
            echo json_encode(array('result' => 0, 'error' => 'unauthorized'));

        }
        mh_exit();
    }


    function external_testConnection()
    {
        echo $this->processApiCall('testConnection');
        mh_exit();
    }

    function external_getShopName()
    {
        echo $this->processApiCall('getShopName');
        mh_exit();
    }

    function external_getShopPrefix()
    {
        echo $this->processApiCall('getShopPrefix');
        mh_exit();
    }

    function external_getCustomers()
    {
        $params = array();
        $params['hours'] = $_POST['hours'];
        $params['newsletterSubscribersOnly'] = $_POST['newsletterSubscribersOnly'];
        echo $this->processApiCall('getCustomers', $params);
        mh_exit();
    }

    function external_getProductInfo()
    {
        $params = array();
        $params['identifier'] = $_POST['identifier'];
        $params['language'] = $_POST['language'];
        echo $this->processApiCall('getProductInfo', $params);
        mh_exit();
    }

    function external_setBounce()
    {
        $params = array();
        $params['email'] = $_POST['email'];
        echo $this->processApiCall('setBounce', $params);
        mh_exit();
    }

    function external_setUnsubscribe()
    {
        $params = array();
        $params['email'] = $_POST['email'];
        echo $this->processApiCall('setUnsubscribe', $params);
        mh_exit();
    }

    function external_syncBounces($external_call = 'True')
    {

        echo $external_call;

        require_once(MH_DIR_CONFIG . 'config_email_engine_n2g/classes/newsletter2go.class.php');

        if ($external_call == '' || $external_call == 'True') {
            echo $this->html_header();
        }

        echo '<h2>' . mh_lng('MAILBEEZ_N2GO_API_TITLE') . '</h2>';

        $nl2go = new newsletter2go(mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_KEY'));
        $return = $nl2go->getHardbounces();


        $cnt = 0;
        if (is_array($return) && $return['success']) {
            $bounces_array = $return['value'];

            foreach ($bounces_array as $bounce_email_add) {
                if ($this->trackBounce($bounce_email_add)) {
                    $cnt++;
                }
//                echo "$bounce_email_add<hr>";
            }


        } else {
            echo "API call getHardbounces() failed: " . $return['reason'];
        }

        echo "<hr>$cnt new Bounces from Newsletter2Go synchronized - done<hr>";

        if ($external_call == '' || $external_call == 'True') {
            echo $this->html_footer();
            mh_exit();
        }
        return $cnt;


    }


    function trackBounce($bounced_email_address)
    {

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

        $bounced_email_address = mh_db_input($bounced_email_address);

        // 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
            //echo "$bounced_email_address already processed <hr>";
            return false;
        }


        // 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' => 'H'
            );

            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 = 'H'
                                where autoemail_id = '" . $query['autoemail_id'] . "'");

            // echo "$bounced_email_address matched to mailbeez email <hr>";
            return true;

        } 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' => 'H'
                    );

                    mh_db_perform(TABLE_MAILBEEZ_BOUNCE, $sql_data_array);


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

                }
                //echo "$bounced_email_address matched to customer <hr>";
                return true;

            } 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' => 'H'
                );

                mh_db_perform(TABLE_MAILBEEZ_BOUNCE, $sql_data_array);
                //echo "$bounced_email_address unknown, tracked <hr>";
                return true;
            }
        }

        return false;

    }

    function get_do_run()
    {
        return (preg_match('/Newsletter2Go/', mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE')) && (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_API_VERSION') == 'v1'));
    }

    function check()
    {
        return true;
    }
    /*

        function remove()
        {
            return false;
        }

        function install()
        {

        }

        */

}
