<?php

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

  Copyright (c) 2010 - 2012 MailBeez

  Released under the GNU General Public License
 */

///////////////////////////////////////////////////////////////////////////////
///																			 //
///                 MailBeez Core file - do not edit                         //
///                                                                          //
///////////////////////////////////////////////////////////////////////////////

require_once(MH_DIR_CONFIG . 'config_customer_insight/classes/viewbeez.php');


class view_news extends viewbeez
{

// class constructor
    function __construct($order_id = null)
    {
        parent::__construct();

        $this->code = 'view_news';
        $this->module = 'view_news';
        $this->version = '1.0';
        $this->title = mh_lng('MAILBEEZ_VIEW_NEWS_TITLE');
        $this->description = mh_lng('MAILBEEZ_VIEW_NEWS_DESCRIPTION');
        $this->hidden = true;

        $this->sort_order = 999;
        $this->enabled = true;
        $this->has_dashboard_view = true;


        $this->set_template();
//        $this->menu_cnt_default = $this->cnt_news();
    }

    function view_news()
    {
        return self::__construct();
    }

    function get_view_dashboard_content($template)
    {
        $smarty = $this->init_view_dashboard();

        $news_result = $this->get_news_feed();

//        print_r($news_result); exit();

        $smarty->assign('newsfeed', $news_result['rows']);

        return $this->parse_view_dashboard($smarty, $template);
    }

    function get_view_dashboard_widget()
    {
        $smarty = $this->init_view_dashboard_widget();

        $news_result = $this->get_news_feed(1);

        $smarty->assign('newsfeed', $news_result['rows']);

        $smarty->assign('news_cnt', $this->cnt_news());

        return $this->parse_view_dashboard_widget($smarty);
    }

    function get_news_feed($limit = null)
    {
        if (!class_exists('lastRSS')) {
            include(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/' . 'rss.php');
        }

        $rss = new lastRSS;
        $rss->items_limit = 30;
        $rss->cache_dir = MAILBEEZ_CONFIG_TEMPLATE_ENGINE_COMPILE_DIR;
        $rss->cache_time = 360; //86400;
        $rss->date_format = 'Y-m-d h:m:s';

        $feed_url_en = 'https://www.mailbeez.com/newsfeed.rss';
        $feed_url_de = 'https://www.mailbeez.de/newsfeed.rss';

        switch ($this->language) {
            case "german":
                $feed_url = $feed_url_de;
                break;
            default:
                $feed_url = $feed_url_en;
        }

        $result = array(
            'rows' => array()
        );

        $feed = $rss->get($feed_url);

        $cnt = 0;

        if (is_array($feed) && is_array($feed['items']) && sizeof($feed['items']) > 0) {
            foreach ($feed['items'] as $item) {
                $result['rows'][$cnt] = $item;
                $decoded_title = function_exists('utf8_decode') ? @utf8_decode($item['title'] ?? '') : mb_convert_encoding($item['title'] ?? '', 'ISO-8859-1', 'UTF-8');
                $result['rows'][$cnt]['title'] = $this->convert($decoded_title);
                $decoded_description = function_exists('utf8_decode') ? @utf8_decode($item['description'] ?? '') : mb_convert_encoding($item['description'] ?? '', 'ISO-8859-1', 'UTF-8');
                $result['rows'][$cnt]['description'] = $this->convert($decoded_description);
                $cnt++;
            }
        }

        if ($limit != null && isset($result['rows'])) {
            $result['rows'] = array_slice($result['rows'], 0, $limit);
        }

        return $result;
    }

    function convert($message)
    {
        // http://stackoverflow.com/questions/5362195/need-php-to-encode-special-characters-but-not-html-tags-for-inclusion-in-a-word


        // http://jonathonhill.net/2010-12-01/how-to-tell-if-your-are-running-php-5-3/
        if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
            // PHP 5.3+

            // syntax causes error on PHP5.2
            // $message = preg_replace_callback('/[\x80-\xFF]/', function ($matches) {
            //    return "&#x" . dechex(ord("$matches[0]")) . ";";
            // }, $message);

            $message = preg_replace_callback('/[\x80-\xFF]/', array($this, 'mh_convert_preg_callback'), $message);


        } else {
            $message = preg_replace('/[\x80-\xFF]/e', '"&#x".dechex(ord("$0")).";"', $message);
        }
        return $message;
    }


    function mh_convert_preg_callback($matches)
    {
        $a = $matches[0];
        return "&#x" . dechex(ord("$a")) . ";";
    }


    function get_number_of_news()
    {
        $this->set_cache_id('global', 'num_of_news');
        if ($cache = $this->read_cache()) {
            return $cache['value'];
        }

        $newsfeed = $this->get_news_feed();

        return $this->set_cache(sizeof($newsfeed['rows']), 'app');
    }


    function cnt_news()
    {
        return $this->get_number_of_news();
    }

    public function data_update()
    {

        $this->set_cache_id('global', 'num_of_news');
        $this->purge_cache('app');

        $this->notficationsObj = new notificationbeez();
        $newsfeed = $this->get_news_feed();

        mh_log("data_update: " . $this->code . " ", $newsfeed);

        if (is_array($newsfeed['rows'])) {
            foreach ($newsfeed['rows'] as $item) {

                // alternative approach
                // https://www.webmasterworld.com/php/4183291.htm
                // substr(base_convert(md5($item['link']), 16, 10) , -5);

                $uid = strtotime($item['pubDate']);
                $notification = array('title' => 'News',
                    'notification_summary' => $item['title'],
                    'notification' => $item['description'],
                    'module' => $this->code,
                    'ref_id' => $uid,
                    'iteration' => 1,
                    'customers_id' => null,
                    'severity' => 5,
                    'link' => $item['link'],
                    'link_type' => 'E', // E - external, I - internal, P - popup
                    'panel_click_action' => 'H', // H - hide
                    'channel_id' => 0,
                    'status' => '0',
                    'icon_style' => 'background-image: url(' . mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH') . 'configbeez/config_customer_insight/viewbeez/view_news/icon_panel.png); background-color: #c4e1fd');
                $this->notficationsObj->add($notification);
            }
        }
        echo "update news";
    }

}

