<?php

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

  Copyright (c) 2010 MailBeez

  inspired and in parts based on
  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
 */

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

class mailbeez_check extends mailbeez
{

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

        // set some stuff:
        $this->code = 'mailbeez_check';
        $this->module = 'mailbeez_check';
        $this->version = '2.2'; // float value
        $this->required_mb_version = 2.7; // required mailbeez version
        $this->iteration = $this->_getCheckInterval();
        $this->title = mh_lng('MAILBEEZ_MAILBEEZ_CHECK_TEXT_TITLE');
        $this->description = mh_lng('MAILBEEZ_MAILBEEZ_CHECK_TEXT_DESCRIPTION');
        $this->description_image = 'icon_64.png';
        $this->icon = 'icon.png';
        $this->sort_order = 1010;
        $this->enabled = mh_cfg('MAILBEEZ_MAILBEEZ_CHECK_STATUS') == 'True';
        $this->sender = mh_cfg('MAILBEEZ_MAILBEEZ_CHECK_SENDER');
        $this->sender_name = mh_cfg('MAILBEEZ_MAILBEEZ_CHECK_SENDER_NAME');
        $this->status_key = 'MAILBEEZ_MAILBEEZ_CHECK_STATUS';
        $this->nochk = true;
        $this->allow_preview = false;
        $this->allow_reporting = false;
        $this->allow_filter_check = false;

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

        $this->htmlBodyTemplateResource = 'body_html.tpl'; // located in folder of this module
        $this->txtBodyTemplateResource = 'body_txt.tpl'; // located in folder of this module
        $this->subjectTemplateResource = 'subject.tpl'; // located in folder of this module


        $this->htmlUpdateListTemplateResource = 'updatelist_html.tpl'; // located in folder of this module
        $this->txtUpdateListResource = 'updatelist_txt.tpl'; // located in folder of this module

        $this->audience = array();
        $this->additionalFields = array('modules' => mh_cfg('MAILBEEZ_INSTALLED_VERSIONS'), 'iteration' => $this->iteration, 'check_result_html' => 'run module to see list', 'check_result_txt' => 'run module to see list'); // list of additional fields to show in listing with testvalues
        // list of additional fields to show in listing with testvalues used for Test-Mail

        $this->check_cloud();

    }


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


// class methods
    function getAudience()
    {

        // todo
        // adjust to new version API


        $id = -42; // the answer... ;-)
        // early check to avoid processing when email was already sent
        $mb_chk = new mailbeez_mailer($this);
//        $mb_chk->load_filter();
        $chk_result = $mb_chk->early_check($this->module, $this->iteration, $id);
        if ($chk_result != false) {
            // this iteration was already sent
            return false;
        }

        $query_sql = "select count(*) as count from " . TABLE_MAILBEEZ_TRACKING . " ";

        $count_query = mh_db_query($query_sql);
        $count = mh_db_fetch_array($count_query);

        $htmlListOut = '';
        $txtListOut = '';
        $check_result_content = $this->_getCurlContent(MAILBEEZ_VERSION_CHECK_URL . '&api=true');

        $check_result = json_decode($check_result_content, true);

        $check_result_md = $check_result['core']['changelog'];

        $Parsedown = new Parsedown();

        $check_result_html = $Parsedown->text($check_result_md);
        $check_result_html = str_replace('<a href="#new"></a>', 'NEW', $check_result_html);
        $check_result_html = str_replace('<a href="#improved"></a>', 'IMPROVED', $check_result_html);
        $check_result_html = str_replace('<a href="#bugfix"></a>', 'BUGFIX', $check_result_html);


        $this->audience[$id] = array('firstname' => mh_cfg('MAILBEEZ_MAILBEEZ_CHECK_SENDER_NAME'),
            'lastname' => ' - MailBeez Version Check',
            'email_address' => mh_cfg('MAILBEEZ_MAILBEEZ_CHECK_SENDER'),
            'customers_id' => $id,
            'iteration' => $this->iteration,
            'check_result_html' => $check_result_html,
            'check_result_txt' => '',
            'msg' => $check_result['notification'],
            'number_of_emails' => $count['count']
        );

        return $this->audience;
    }

    function _getCheckInterval()
    {
        switch (mh_cfg('MAILBEEZ_MAILBEEZ_CHECK_INTERVAL')) {
            case 'every day':
                return date('Yz');
                break;
            case 'every week':
                return date('YW');
                break;
            case 'every month':
                return date('Ym');
                break;
        }
    }

    function _getCurlContent($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_USERAGENT, $this->user_agent);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $content = curl_exec($ch);

        if (empty($content)) {
            print curl_error($ch);
        } else {
            $info = curl_getinfo($ch);
            //print_r($info);
        }

        if (is_resource($ch)) {
            curl_close($ch);
        }
        return $content;
    }

    // installation methods

    function keys()
    {
        return array('MAILBEEZ_MAILBEEZ_CHECK_STATUS', 'MAILBEEZ_MAILBEEZ_CHECK_SENDER', 'MAILBEEZ_MAILBEEZ_CHECK_SENDER_NAME', 'MAILBEEZ_MAILBEEZ_CHECK_INTERVAL');
    }

    function install()
    {

        mh_insert_config_value(array('configuration_title' => 'Send mailbeez_check reminder',
            'configuration_key' => 'MAILBEEZ_MAILBEEZ_CHECK_STATUS',
            'configuration_value' => 'True',
            'configuration_description' => 'Do you want to send  mailbeez_check emails?',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

        mh_insert_config_value(array('configuration_title' => 'Interval',
            'configuration_key' => 'MAILBEEZ_MAILBEEZ_CHECK_INTERVAL',
            'configuration_value' => 'every week',
            'configuration_description' => 'How often do yo want to receive an email with update information?',
            'set_function' => 'mh_cfg_select_option(array(\'every day\', \'every week\', \'every month\'), '
        ));


        mh_insert_config_value(array('configuration_title' => 'sender and receiver email',
            'configuration_key' => 'MAILBEEZ_MAILBEEZ_CHECK_SENDER',
            'configuration_value' => mh_cfg('STORE_OWNER_EMAIL_ADDRESS'),
            'configuration_description' => 'sender email',
            'set_function' => ''
        ));

        mh_insert_config_value(array('configuration_title' => 'sender and receiver name',
            'configuration_key' => 'MAILBEEZ_MAILBEEZ_CHECK_SENDER_NAME',
            'configuration_value' => mh_cfg('STORE_NAME'),
            'configuration_description' => 'sender email',
            'set_function' => ''
        ));
    }

}

?>
