<?php
/*
 *   $Id$
 *
 *   AbanteCart, Ideal OpenSource Ecommerce Solution
 *   http://www.AbanteCart.com
 *
 *   Copyright © 2011-2025 Belavier Commerce LLC
 *
 *   This source file is subject to Open Software License (OSL 3.0)
 *   License details are bundled with this package in the file LICENSE.txt.
 *   It is also available at this URL:
 *   <http://www.opensource.org/licenses/OSL-3.0>
 *
 *  UPGRADE NOTE:
 *    Do not edit or add to this file if you wish to upgrade AbanteCart to newer
 *    versions in the future. If you wish to customize AbanteCart for your
 *    needs, please refer to http://www.AbanteCart.com for more information.
 */
if (!defined('DIR_CORE') || !IS_ADMIN) {
    header('Location: static_pages/');
}

/**
 * ANT
 * class for retrieving messages from remote ANT-server and insert it into a database of abantecart
 */
class ControllerCommonANT extends AController
{
    const EXPIRE_TIME = 86400;

    public function main()
    {
        // disable for login-logout pages
        if (in_array($this->request->get['rt'], ['index/logout', 'index/login'])) {
            unset($this->session->data['ant_messages']);
            return null;
        }

        if (!has_value($this->session->data['ant_messages']['date_modified'])) {
            unset($this->session->data['ant_messages']);
        }

        // prevent repeats of requests or if last update older then 24hours
        if (has_value($this->session->data['ant_messages'])
            && (time() - $this->session->data['ant_messages']['date_modified'] < self::EXPIRE_TIME)) {
            return null;
        }

        //init controller data
        $this->extensions->hk_InitData($this, __FUNCTION__);
        $httpQuery = (array)$this->data['ant_http_query'];
        $httpQuery['software_name'] = 'AbanteCart';
        $httpQuery['store_id'] = UNIQUE_ID;
        $httpQuery['store_ip'] = $_SERVER ['SERVER_ADDR'];
        $httpQuery['store_url'] = HTTP_SERVER;
        $httpQuery['store_version'] = VERSION;
        $httpQuery['language_code'] = $this->request->cookie['language'];

        //check if user login first time
        if (!$this->user->getLastLogin()) {
            $httpQuery['new_cart'] = 1;
        }

        //send extension info
        $extensions_list = $this->extensions->getExtensionsList();
        if ($extensions_list) {
            foreach ($extensions_list->rows as $ext) {
                $httpQuery['extension'][] = $ext['key'] . "~" . $ext['version'];
            }
        }

        //do connect without any http-redirects
        $connect = new AConnect (true);
        $result = $connect->getResponseSecure("/get_ant_messages/?".http_build_query($httpQuery));
        $this->session->data ['ant_messages'] = []; // prevent requests in future at this session
        // insert new messages in the database
        if ($result && is_array($result)) {
            //set array for check response
            $check_array = [
                'message_id',
                'type',
                'placeholder',
                'date_added',
                'date_modified',
                'start_date',
                'end_date',
                'priority',
                'title',
                'description',
                'version',
                'prior_version',
                'html',
                'url',
                'published',
                'language_code',
            ];
            $antIds = [];
            foreach ($result as $notify) {
                $tmp = [];
                if( (!in_array($notify['start_date'], ['0000-00-00 00:00:00','', null]) &&
                        dateISO2Int($notify['start_date'])>time())
                    ||
                    (!in_array($notify['end_date'], ['0000-00-00 00:00:00','', null]) &&
                        dateISO2Int($notify['end_date'])<time())
                ) {
                    continue;
                }
                foreach ($notify as $key => $value) {
                    if (!in_array($key, $check_array)) {
                        continue;
                    }
                    $tmp[$key] = $value;
                    $antIds[] = $tmp['message_id'];
                }

                // lets insert
                switch ($tmp ['type']) {
                    case 'W' :
                        $this->messages->saveWarning($tmp['title'], $tmp['description']);
                        break;
                    case 'E' :
                        $this->messages->saveError($tmp['title'], $tmp['description']);
                        break;
                    case 'B' :
                        $this->messages->saveANTMessage($tmp);
                        break;
                    default :
                        $this->messages->saveNotice($tmp['title'], $tmp['description']);
                        break;
                }
            }
            // purge messages except just saved
            $this->messages->purgeANTMessages($antIds);
        }
        // in case when answer from server is empty
        $this->session->data['ant_messages']['date_modified'] = time();

        // check for extension updates
        $this->loadModel('tool/updater');
        $this->model_tool_updater->check4updates(true);
    }
}
