<?php

ini_set("url_rewriter.tags", "");
ini_set("session.use_trans_sid", false);
$sessionCookieDomain = !empty($_SERVER['HTTP_HOST'])
    ? preg_replace('/:\d+$/', '', $_SERVER['HTTP_HOST'])
    : $_SERVER['SERVER_NAME'];
ini_set('session.cookie_domain', $sessionCookieDomain);
ini_set('pcre.backtrack_limit',5000000000);
ini_set('pcre.recursion_limit',5000000000);

header("Content-Type: text/html; charset=utf-8");

// czasem potrzebne do pasazu wp zeby sie nie kopal - moze powodowac podwojne zamowienia.
Header('P3P: CP="NOI DSP COR NID OUR IND"');

if (isset($_GET['logout']) && $_GET['logout'] == true) {
    session_name('sessid');
    session_start();
    $reference_from = $_SESSION['reference'];
    session_unset();
    session_destroy();
}
//Active Cache
$db_cache_active = true;
$time_session = 60 * 60 * 24 * 14;
session_name('sessid');
session_cache_limiter('private, must-revalidate');
session_start([
    'cookie_lifetime' => 0,
    'gc_maxlifetime' => $time_session
]);
setcookie('sessid', session_id(), time() + $time_session);

// wymagane w kazdym pliku
require 'init_boot.php';
require_once BASE_DIR . 'include/functions.php';
$_SESSION['letTime'] = time();

GoogleAnalytics4::getInstance()->registerEvents();

if (isset($_GET['logout']) && $_GET['logout'] == true) {
    Event::run('client.logout');
}

if(file_exists(BASE_DIR.'front_en.csv')) {
    addLanguage($langISO = 'en_US', $shortIso = 'en', $midIso = 'en-us', $file = 'front_en.csv', $name = 'english', $pName = 'Angielski', $nameIso = 'english_us', $nameOrginal = 'Angielski (US)');
}
if(file_exists(BASE_DIR.'front_de.csv')) {
    addLanguage($langISO = 'de_DE', $shortIso = 'de', $midIso = 'de-de', $file = 'front_de.csv', $name = 'deutsch', $pName = 'Niemiecki', $nameIso = 'deutsch_de', $nameOrginal = 'Niemiecki (DE)');
}
if(file_exists(BASE_DIR.'front_it.csv')) {
    addLanguage($langISO = 'it_IT', $shortIso = 'it', $midIso = 'it-it', $file = 'front_it.csv', $name = 'italiano', $pName = 'Włoski', $nameIso = 'italiano_it', $nameOrginal = 'Włoski (IT)');
}
if(file_exists(BASE_DIR.'front_cs.csv')) {
    addLanguage($langISO = 'cs_CS', $shortIso = 'cs', $midIso = 'cs-cs', $file = 'front_cs.csv', $name = 'čeština', $pName = 'Czeski', $nameIso = 'cestina_cs', $nameOrginal = 'Czeski (CS)');
}

if(file_exists(BASE_DIR.'it_table_templates.csv')) {
    //addLanguageToTable('templates', $langISO = 'it_IT', BASE_DIR.'it_table_templates.csv');
}
if(file_exists(BASE_DIR.'it_table_statusy.csv')) {
    //addLanguageToTable('statusy', $langISO = 'it_IT', BASE_DIR.'it_table_statusy.csv');
}


$GLOBALS['IP'] = IP::getAddress();
$GLOBALS['javascript'] = $GLOBALS['query_catnon'] = $GLOBALS['arCatPosition'] = $GLOBALS['arCatNon'] = NULL;
$arCatNon = $arCatPosition = NULL;

$freeDelivery = false;

if ($b2bMode) {
    if (isset($b2bConfig['private_mode'])) {
        $GLOBALS['private_mode'] = $b2bConfig['private_mode'];
    }

    Event::run('system.b2bMode.init_plist', $eventData);

    if($eventData['assign']) {
        $_SESSION['plist'] = $eventData['plist'];
    }


    if (Config::get('shipment_type') == 0) {
        $weight = $_SESSION['shopcart']['total']['weight'] ?? 0;

        $res = $sql->query('SELECT 1 FROM wysylka WHERE koszt = 0 AND additional_info != 3 AND pozycja > 0 AND waga_do >= ' . $weight);

        if ($res) {
            $freeDelivery = 0;
        } else {
            $res = $sql->query($q = 'SELECT MIN(limit_kwoty / (1 + podatek / 100)) AS `min` FROM wysylka WHERE additional_info != 3 AND pozycja > 0 AND waga_do >= ' . $weight);

            if ($res) {
                $freeDelivery = $sql->getField(0, 'min') - $_SESSION['shopcart']['total']['netto'];

                $freeDelivery = $freeDelivery < 0 ? 0 : $freeDelivery;
            }
        }
    }
}

function curPageURL($ssl = NULL) {
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on" AND $ssl === NULL) {
        $pageURL .= "s";
    } else if ($ssl === TRUE) {
        $pageURL .= "s";
    }
    $pageURL .= "://";

    $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];

    return $pageURL;
}

if(!isset($_SESSION['reference']) || empty($_SESSION['reference'])) {
    $reference_from = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : NULL;
    
    if (empty($reference_from)) {
        $reference_from = 'direct';
    } else {
        $_SESSION['reference'] = $reference_from;
    }
    if (isset($_SESSION['reference']) && parse_url($_SESSION['reference'], PHP_URL_HOST) == parse_url(url::base(), PHP_URL_HOST)) {
        $_SESSION['reference'] = $reference_from = 'direct';
    }
} elseif (!empty($reference_from) && empty($_SESSION['reference'])) {
    $_SESSION['reference'] = $reference_from;
}

/**
 * Przekierowania
 * */
if (Valid::host(Config::get('redirect_domain')) AND $_SERVER['HTTP_HOST'] != Config::get('redirect_domain')) {
    $redirect = (($GLOBALS['ssl_mode']  == '1' || $ssl === true) ? 'https' : 'http'). "://" . Config::get('redirect_domain') . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header("Location: " . $redirect);
    die;
}

$host = $_SERVER['HTTP_HOST'];



if (Config::get('redirect_www') == 1 AND preg_match('/www.*/i', $host)) {
    if((empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off") &&
        (empty($_SERVER['HTTP_X_FORWARDED_PROTO']) || $_SERVER['HTTP_X_FORWARDED_PROTO'] != 'https') && $GLOBALS['ssl_mode'] == '1')
        $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    else $redirect = curPageURL();
    header('HTTP/1.1 301 Moved Permanently');
    header("Location: " . str_replace('://www.', '://', $redirect));
    die();
}

if (Config::get('redirect_www') == 2 AND ! preg_match('/www.*/i', $host)) {
    if((empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off") &&
        (empty($_SERVER['HTTP_X_FORWARDED_PROTO']) || $_SERVER['HTTP_X_FORWARDED_PROTO'] != 'https') && $GLOBALS['ssl_mode'] == '1')
        $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    else $redirect = curPageURL();
    header('HTTP/1.1 301 Moved Permanently');
    header("Location: " . str_replace('://', '://www.', $redirect));
    die();
}

if((empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off") &&
    (empty($_SERVER['HTTP_X_FORWARDED_PROTO']) || $_SERVER['HTTP_X_FORWARDED_PROTO'] != 'https') &&
    $GLOBALS['ssl_mode'] == '1' && $GLOBALS['ssl_mode_only_for_auth'] == 0){
    $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $redirect);
    exit();
}
        
function htmlentities_array($a) {
    if (!isset($a))
        return null;
    if (is_array($a))
        return array_map('htmlentities_array', $a);
    return htmlentities($a);
}

if ($_SERVER)
    array_walk_recursive($_SERVER, 'my_filter');
if ($_ENV)
    array_walk_recursive($_ENV, 'my_filter');
if ($_POST)
    array_walk_recursive($_POST, 'my_filter');
if ($_GET)
    array_walk_recursive($_GET, 'my_filter');
if ($_COOKIE)
    array_walk_recursive($_COOKIE, 'my_filter');
if (isset($_FILE))
    array_walk_recursive($_FILE, 'my_filter');
if ($_REQUEST)
    array_walk_recursive($_REQUEST, 'my_filter');

function addslashes_array($a) {
    if (!isset($a))
        return null;
    if (is_array($a))
        return array_map('addslashes_array', $a);
    return addslashes($a);
}

$_SERVER = addslashes_array($_SERVER);
$_GET = addslashes_array($_GET);
$_POST = addslashes_array($_POST);
$_COOKIE = addslashes_array($_COOKIE);
$_FILES = addslashes_array($_FILES);
$_ENV = addslashes_array($_ENV);
$_REQUEST = addslashes_array($_REQUEST);

Event::run('system.start');

$_theme_header = '';
$_mainId = '';
$_canonicalUrl = '';

if(Config::get('theme_version')<5) $GLOBALS['javascript'] .= '<script type="text/javascript" src="' . url::site('include/functions.js') . '"></script>';
Cron::doScript();

if(Config::get('recaptcha') == true) $GLOBALS['javascript'] .= '<script src="https://www.google.com/recaptcha/api.js?onload=initCRecaptcha&render=explicit" async defer></script>';

require $GLOBALS['server_path'] . '/include/globals.php';
require $GLOBALS['server_path'] . '/include/function.email.php';

require $GLOBALS['server_path'] . '/inpost/inpost.php';

if (!blacklist('admin/blacklist.txt', $IP))
    die();

//dodatkowy kod php
if (file_exists($GLOBALS['server_path'] . '/ext/extend.php')) {
    include $GLOBALS['server_path'] . '/ext/extend.php';
}

//dodatkowy kod php exclusixe dla templatek
if ( file_exists( $GLOBALS['server_path'] . '/themes/' . $GLOBALS['theme_path'] . '/ext/extra.php' ) ) {
    include $GLOBALS['server_path'] . '/themes/' . $GLOBALS['theme_path'] . '/ext/extra.php';
}

//zalogowanie goscia z linku aktywacyjnego
if (($userid > 0 && isset($_GET['mdkey'])) && (mb_strlen($_GET['mdkey']) == 32) && isset($_GET['sessid'])) {
    $res = $sql->Query("SELECT
            `id`,
            `aktywny`,
            `sess_id`
        FROM `klienci`
        WHERE `id` = '$userid'
            AND `kluczcmd` = '" . $_GET['mdkey'] . "'
        LIMIT 1");
    if ($res > 0) {
        $lnk_client_id = $sql->GetField(0, 'id');
        $lnk_client_aktywny = $sql->GetField(0, 'aktywny');
        $lnk_client_sess_id = $sql->GetField(0, 'sess_id');
        if ($lnk_client_id && $lnk_client_aktywny == 0) {
            $res2 = $sql->Query("UPDATE `klienci`
                SET
                    `aktywny` = '1',
                    `kluczcmd` = '',
                    `sess_id` = ''
                WHERE `id` = '$userid'");
            $sessid = $lnk_client_sess_id;
            $user_activation = true;
            if ($_GET['sessid'] != null)
                session_id($_GET['sessid']);
            $komunikaty->Set('main', __('Twoje konto zostało aktywowane'), 1);
        }
    }
}

if (Config::get('blocked_account')) {
    die(__('Sklep został zablokowany przez administratora.'));
}
// Potwerdzanie złożonego zamówienia
if( isset( $_GET['confCOD'] ) && strlen( $_GET['confCOD'] ) == 32 ) {
    $res = $sql->Query( "SELECT `id`, `platnosc`
        FROM `zamowienia`
        WHERE MD5( CONCAT( 'cod', `id` ) ) = '" . htmlspecialchars($_GET["confCOD"], ENT_QUOTES) . "'
        AND `stan` = 10 LIMIT 1" );

    if( $res > 0 ) {
        switch( (int)$sql->GetField( 0, 'platnosc' ) ){
            case 1:
                $stan = 3;
                break;
            case 18:
                $stan = 13;
                break;
            default:
                $stan = 1;
                break;
        }
        $sql->Query( "UPDATE `zamowienia` SET `stan` = {$stan}  WHERE `id` = '" . $sql->GetField(0, 'id') . "'" );
        $komunikaty->Set( 'main', __( 'Twoje zamówienie zostało potwierdzone.' ), 1 );
    }
    else {
        $komunikaty->Set( 'main', __( 'Link wygasł lub jest niepoprawny.' ) );
    }
}

if (isset($_SESSION['registerDone'])) {
    $successText = __('Dziękujemy za rejestrację. Twoje konto jest już aktywne i możesz się zalogować.');
    Event::run('register.success.text', $successText);
    $komunikaty->Set('main', $successText, 1);
    unset($_SESSION['registerDone']);
}

require $GLOBALS['server_path'] . '/admin/plugins.php';

if (is_numeric(fromgetpost('plist')) && fromgetpost('plist') > 0 && fromgetpost('plist') < 4){
    $_SESSION['plist'] = fromgetpost('plist');
}

if (!$_SESSION['plist']) {
    $_SESSION['plist'] = Config::get('product_list_default_view') ? Config::get('product_list_default_view') : 1;
}


if (Debug::check()) {
    if (!isset($_SESSION['debuger']))
        $_SESSION['debuger'] = 'on';
    require 'benchmark/Timer.php';
    $timer = new Benchmark_Timer();
    $timer->start();
}
//pasaze !!!
if (isset($_GET['pasaz'])) {
    $_SESSION['pasaz'] = $_GET['pasaz'];
    if ($_SESSION['pasaz'] == 'wp') {
        $adres = "http://zakupy.wp.pl/stat_view.html?sid=" . $wp['id'] . "";
        echo "<img src=\"$adres\" width=\"1\" height=\"1\" border=\"0\">";
    }
} else {
    $_SESSION['pasaz'] = '';
}

/** Catalogue Mode */
$privateMode = (bool)Config::get('private_mode') && empty($_SESSION['user']);
$catalogueMode = (bool)Config::get('catalogue');
$catalogueModeShowPrices = true;
$catalogueModeAllowLoginRegister = true;

if ($catalogueMode) {
    if (true === (bool)Config::get('catalogue_for_guests') && !empty($_SESSION['user'])) {
        $catalogueMode = false;
    }
}

if ($catalogueMode) {
    $catalogueModeShowPrices = (bool)Config::get('catalogue_prices');
    $catalogueModeAllowLoginRegister = (bool)Config::get('catalogue_allow_loginregister');
}

$GLOBALS['catalogue'] = $catalogueMode;
$GLOBALS['catalogue_prices'] = $catalogueModeShowPrices;

if ($GLOBALS['catalogue'] == 1) {
    unset($dodaj);
    unset($_GET['dodaj']);
    unset($_POST['dodaj']);
}

//  Cash4free.pl - Integracja Openrate
if( Config::get( 'Cash4Free' ) == 1 && isset( $_REQUEST['oTTUID'] ) && !empty( $_REQUEST['oTTUID'] ) ) {
	setcookie( 'MEDIAEFFECT', $_REQUEST['oTTUID'], time() + 2592000, '/', parse_url( url::base(), PHP_URL_HOST ) );
}

//narazie wylaczone cache-- moze wprowadzic jakas zmienna w ustawieniach czy cache-owac producentow i kategorie
real_global_extract(get_manufactures());

$stop = $onlyRawBody = false;
$onlyRawBody = fromgetpost('onlyRawBody');
if (isset($_POST['do']) || isset($_GET['do'])) {
    if (isset($_POST['do']))
        $do = $_POST['do'];
    else
        $do = $_GET['do'];

    header('Content-Type: text/html; charset=utf-8');

    if (is_ajax()) {
        $_POST = isset($_POST) ? $_POST : NULL;
        $_GET = isset($_GET) ? $_GET : NULL;
    }

    ob_start();

    $controller = '';

    switch ($do) {
        case 'api' : $controller = BASE_DIR . 'controller/api.php';
            break;
        case 'negotiate' : $controller = BASE_DIR . 'controller/popup/negotiate.php';
            break;
        case 'popup_article' : $controller = BASE_DIR . 'controller/popup/popup_article.php';
            break;
        case 'question' : $controller = BASE_DIR . 'controller/popup/question.php';
            break;
        case 'recommend' : $controller =  BASE_DIR . 'controller/popup/recommend.php';
            break;
        case 'comment' : $controller =  BASE_DIR . 'controller/popup/comment.php';
            break;
        case 'notify' : $controller =  BASE_DIR . 'controller/popup/notify.php';
            break;
        case 'googlemap' : $controller =  BASE_DIR . 'googlemap.php';
            break;
        case 'click' : $controller =  BASE_DIR . 'click.php';
            break;
        case 'komunikaty' : $controller =  BASE_DIR . 'komunikaty.php';
            break;
        case 'stale_cechy_ajax':$controller =  BASE_DIR . 'szukaj_stcechy_ajax.php';
            break;
        case 'captcha' : $controller =  BASE_DIR . 'captcha.php';
            break;
        case 'paczkawruchu_point' : $controller =  BASE_DIR . 'controller/delivery/paczkawruchu_point.php';
            break;
        case 'raty_lukas' : $controller =  BASE_DIR . 'raty_lukas.php';
            break;
        case 'checkDotPay' : $controller =  BASE_DIR . 'checkDotPay.php';
            break;
        case 'eCard' : $controller =  BASE_DIR . 'checkeCard.php';
            break;
        case 'paypal' : $controller = BASE_DIR . 'checkPayPal.php';
            break;
        default : break;
    }

    Event::run('system.do.routing', $controller);
    
    if (! empty($controller)) {
        require $controller;
    }

    $stop = true;

    $_theme_do = ob_get_contents();

    ob_end_clean();

    if (is_ajax() == TRUE || $onlyRawBody) {
        $_theme_header = $_theme_do;
    } else {

        $arrPopup = array(
            '[%content%]' => $_theme_do,
            '[%title%]' => $popup_title,
        );

        $_theme_header_do = load_template('popup/header.html');

        $_theme_header = str_replace(array_keys($arrPopup), $arrPopup, $_theme_header_do);

        unset($_theme_header_do);
    }
}

if (isset($_GET['menubox']) AND file_exists(BASE_DIR . 'menu/' . $_GET['menubox'] . '.inc.php')) {
    //POBIERA WSZYSTKLIE KATEGORIE DO TABLICY !I PRODUCENTOW ORAZ TWORZY TABELE DO GENEROWANIA HIERARCHI KATEGORII
    real_global_extract(get_categories());
    real_global_extract(get_query_catnon());

    // artykuly
    real_global_extract(get_categories_articles());
    real_global_extract(get_all_status());

    include BASE_DIR . 'menu/' . $_GET['menubox'] . '.inc.php';

    $_theme_header = $tmp;
    $stop = TRUE;
}

if (!$stop) {
    //POBIERA WSZYSTKLIE KATEGORIE DO TABLICY !I PRODUCENTOW ORAZ TWORZY TABELE DO GENEROWANIA HIERARCHI KATEGORII
    real_global_extract(get_categories());
    real_global_extract(get_query_catnon());

    // artykuly
    real_global_extract(get_categories_articles());
    real_global_extract(get_all_status());

    //stats
    $ip_mb_substr1 = explode(".", IP::getAddress());
    $ip_mb_substr = $ip_mb_substr1[0] . "." . $ip_mb_substr1[1] . "." . $ip_mb_substr1[2];
    $res_1 = $sql->Query("SELECT
            `ip`
        FROM `bots_ips`
        WHERE `ip` = '" . IP::getAddress() . "'
            OR `ip` = '" . $ip_mb_substr . "'");
    if (!$res_1 || $res_1 == 0) {
        $server_http_referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : NULL;

        $needBlock = Config::get('needBlockStats');

        if ($needBlock != '1') {
            $sql->Query("INSERT INTO `stats` (
					`sess_id`,
					`ip`,
					`from`,
					`time`
				) VALUES (
					'" . session_id() . "',
					'" . IP::getAddress() . "',
					'" . $sql->escape($server_http_referer) . "',
					'" . time() . "'
				)
				ON DUPLICATE KEY UPDATE
					`time` = '" . time() . "'");
        }
    }


    if (empty($_SESSION['reference']))
        $_SESSION['reference'] = $reference_from;
    
    $customErrorMessages = false;
    Event::run('shopcart.custom.error.messages', $customErrorMessages);
    if(!$customErrorMessages) {
        if( isset( $_SESSION['shopcart'] ) && $_SESSION['shopcart']['total']['stock_err'] == 1 )
            $komunikaty->Set( 'main', __( '<strong>UWAGA!</strong><br>Nie posiadamy podanej ilości sztuk wybranych pozycji!<br>W koszyku zaktualizowano towary zgodnie z ilością dostępnych towarów!' ), 2 );
        if( isset( $_SESSION['shopcart'] ) && $_SESSION['shopcart']['total']['stock_err'] == 2 )
            $komunikaty->Set( 'main', __( '<strong>UWAGA!</strong><br>Ten produkt może być sprzedawany tylko od podanej ilości.<br>W koszyku zaktualizowano towary zgodnie z minimalną ilością!' ), 2 );
        if( isset( $_SESSION['shopcart'] ) && $_SESSION['shopcart']['total']['stock_err'] == 3 )
            $komunikaty->Set( 'main', __( '<strong>UWAGA!</strong><br>Możesz kupić tylko ograniczoną ilość danego produktu<br>W koszyku zaktualizowano towary zgodnie z maksymalną ilością!' ), 2 );
        unset($_SESSION['shopcart']['total']['stock_err']);
    }
    //sprawy zwiazane z koszykiem
    include $GLOBALS['server_path'] . '/shop_cart.php';
    //Product::fc(0)->initWaiting() ; // sprawy związane z zapisaniem
    require $GLOBALS['server_path'] . '/checkandset.php';
    require $GLOBALS['server_path'] . '/payments.php';
    require $GLOBALS['server_path'] . '/switchpage.php';

    Event::run('system.ready');
    $deals_default_run = true;
    Event::run('system.default.deals.check', $deals_default_run);

    if($deals_default_run){
        $query = 'SELECT `deals_timer`.`prod_id`
                FROM `deals_timer`
                WHERE `deals_timer`.`on` = 1
                AND (`deals_timer`.`enddate` < CURDATE() OR (`deals_timer`.`enddate` = CURDATE() && `deals_timer`.`endtime` < NOW()))';
        if ($sql->query($query) > 0) {
            $prods = $sql->get_list('prod_id', 'prod_id');
            $sql->update2('produkty')
                ->set('cena_prom', 0)
                ->where('id', 'IN', $prods)
                ->execute();
            // zakonczenie samej promocji
            $sql->update2('deals_timer')
                ->set('on', 0)
                ->where('on', '=', 1)->where('enddate', '<=', date('Y-m-d'))->where('endtime', '<', date('H:i:s'))
                ->execute();
        }
        // uruchomienie nowej promocji
        $query = 'SELECT `deals_timer`.`prod_id` ,  `deals_timer`.`price`
                FROM `deals_timer`
                JOIN `produkty` ON  `produkty`.`id` =  `deals_timer`.`prod_id`
                WHERE `deals_timer`.`on` = 1
                AND `deals_timer`.`price` > 0
                AND (
                        `deals_timer`.`startdate` < CURDATE()
                        OR (
                            `deals_timer`.`startdate` = CURDATE()
                            AND `deals_timer`.`starttime` < NOW()
                        )
                    )
                AND `deals_timer`.`price` !=  `produkty`.`cena_prom`';
        if ($sql->query($query) > 0) {
            foreach ($sql->get_list('prod_id', 'price') as $id => $price) {
                $sql->update2('produkty')
                    ->set('cena_prom', $price)
                    ->where('id', '=', $id)
                    ->execute();
                $sql->update2('cechy_magazyn')
                    ->set('price_prom_final', $price)
                    ->where('prod_id', '=', $id)
                    ->execute();
            }
        }
    }
    if (Debug::check())
        $timer->setMarker('cStore Loading');

    require $GLOBALS['server_path'] . '/naglowek.php';
    if (Debug::check())
        $timer->setMarker('Header');

    require $GLOBALS['server_path'] . '/wnetrze.php';
    if (Debug::check())
        $timer->setMarker('Body');

    Event::run('system.ready.befor.footer');

    require $GLOBALS['server_path'] . '/footer.php';
    if (Debug::check())
        $timer->setMarker('Foot');


    //cStore-info
    if ($GLOBALS['csinfo'] == 1) {
        if (trim($GLOBALS['csinfo_sound']) != '')
            $GLOBALS['javascript'].='<script type="text/javascript" src="' . url::site('themes/js/sound.js') . '"></script>';
        $GLOBALS['javascript'].='<script type="text/javascript" src="' . url::site('/themes/js/cs_info.php') . '"></script>';

        $cs_info_divs = '<div style="position: fixed; bottom: 20px; right: 20px;" class="customCsInfo">
            <div id="kom" style="width: 250px; margin-top: 15px; background: #eee; font-size: 13px; color: #555; text-align: center; padding: 20px; border-radius: 3px; border: 1px solid #ccc; position: relative; display: none;"><div style="position: absolute; top: -10px; right: -10px; background: #fff; border-radius: 90px; padding: 2px 8px; border: 1px solid #bbb; font-size:12px; cursor: pointer;" class="kom_close">X</div><div class="kom_mid">1</div></div>
            <div id="kom2" style="width: 250px; margin-top: 15px; background: #eee; font-size: 13px; color: #555; text-align: center; padding: 20px; border-radius: 3px; border: 1px solid #ccc; position: relative; display: none;"><div style="position: absolute; top: -10px; right: -10px; background: #fff; border-radius: 90px; padding: 2px 8px; border: 1px solid #bbb; font-size:12px; cursor: pointer;" class="kom_close">X</div><div class="kom_mid">2</div></div>
            <div id="kom3" style="width: 250px; margin-top: 15px; background: #eee; font-size: 13px; color: #555; text-align: center; padding: 20px; border-radius: 3px; border: 1px solid #ccc; position: relative; display: none;"><div style="position: absolute; top: -10px; right: -10px; background: #fff; border-radius: 90px; padding: 2px 8px; border: 1px solid #bbb; font-size:12px; cursor: pointer;" class="kom_close">X</div><div class="kom_mid">3</div></div>
        </div>';
        $_theme_header = preg_replace('/\<\/body\>/Ui', $cs_info_divs . '</body>', $_theme_header, 1);
    }
    
    $_theme_header = str_replace('[%javascript%]', $GLOBALS['javascript'], $_theme_header, $count);
    if ($count == 0)
        $_theme_header = preg_replace('/\<\/head\>/Ui', $GLOBALS['javascript'] . '</head>', $_theme_header, 1);
}

/**
 *  breadcrumbs
 */
$breadcrumbs_html = '';

if (!empty($breadcrumbs)) {
    $tpl = load_template('dec/breadcrumbs.html');
    $tpl_content = template_regions($tpl, array('header', 'first', 'loop', 'last', 'footer'));
    $tpl_content_items = $tpl_content['loop'];

    $breadcrumbs_html = $tpl_content['header'];

    $i = 0;
    $template_count = count($breadcrumbs) - 1;

    $last_element = NULL;
    if (!empty($breadcrumbs) AND trim($tpl_content['last']) != '')
        $last_element = array_pop($breadcrumbs);

    $first_element = NULL;
    if (!empty($breadcrumbs) AND trim($tpl_content['first']) != '')
        $first_element = array_shift($breadcrumbs);

    if (!empty($first_element)) {
        $class = 'no-' . (int) $i . ( ($i % 2 == 1 ) ? ' nth-child-2' : '' ) . ( $i == $template_count ? ' last' : '' ) . ( $i == 0 ? ' first' : '' );
        $first_element['class'] = $class;
        $preg = array();
        $preg['no_url'] = !((bool) $first_element['url']);
        $preg['url'] = ((bool) $first_element['url']);

        $breadcrumbs_html .= template_decore_replace($tpl_content['first'], $first_element, $preg);
        $i++;
    }

    if (!empty($breadcrumbs)) {
        foreach ($breadcrumbs as $key => $value) {
            $class = 'no-' . (int) $i . ( ($i % 2 == 1 ) ? ' nth-child-2' : '' ) . ( $i == $template_count ? ' last' : '' ) . ( $i == 0 ? ' first' : '' );
            $value['class'] = $class;
            $tpl_item = $tpl_content_items;

            $preg = array();
            $preg['no_url'] = !((bool) $value['url']);
            $preg['url'] = ((bool) $value['url']);

            $breadcrumbs_html .= template_decore_replace($tpl_content['loop'], $value, $preg);
            $i++;
        }
    }

    if (!empty($last_element)) {
        $class = 'no-' . (int) $i . ( ($i % 2 == 1 ) ? ' nth-child-2' : '' ) . ( $i == $template_count ? ' last' : '' ) . ( $i == 0 ? ' first' : '' );
        $last_element['class'] = $class;

        $preg = array();
        $preg['no_url'] = !((bool) $last_element['url']);
        $preg['url'] = ((bool) $last_element['url']);
        $breadcrumbs_html .= template_decore_replace($tpl_content['last'], $last_element, $preg);
    }

    $breadcrumbs_html .= $tpl_content['footer'];
}

$msg = implode(' ', $komunikaty->text);
if (strpos($_theme_header, '[%msg%]') !== FALSE) {
    $msg = '';
}

// uwzględniamy sciezki do logotypów multistora
if(Config::get('multisklepOn') && $_multiConfArr['store_id']>0) $logo_path = '/images/logo/'.$_multiConfArr['store_id'].'/';
else $logo_path = '/images/logo/';
        
$arrShopVar = array(
    '[%breadcrumbs%]' => $breadcrumbs_html,
    '[%shop_path%]' => url::base(),
    '[%theme_path%]' => $GLOBALS['theme_path'],
    '[%base_url%]' => url::base(),
    '[%cat_link%]' => url::site("themes/" . $GLOBALS['theme_path']),
    '[%shop_name%]' => $GLOBALS['shop_name'],
    '[%email%]' => $GLOBALS['email_address'],
    '[%shop_logo%]' => $logo_path.Config::get('logo'),
    '[%msg_default%]' => $msg,
    '[%msg%]' => implode(' ', $komunikaty->text),
    '[%form_manufacturers%]' => form::dropdown('producent', array(0 => __('Wybierz producenta')) + $arProducers, $_REQUEST['producent']),
    '[%cookie_info%]' => Config::get('cookie_info_text')
);





if (isset($meta) AND is_array($meta)) {
    template_array_decore($meta);
    $arrShopVar += $meta;
}

$_theme_header = str_replace( array_keys( $arrShopVar ), $arrShopVar, $_theme_header );

$arrShopWar = array(
    template_preg_decore( 'rss' ) => ( (bool)Config::get( 'enable_rss' ) === TRUE ? '$1' : '' ),
    template_preg_decore( 'breadcrumbs' ) => ( (bool) $breadcrumbs_html === TRUE ? '$1' : '' ),
    template_no_preg_decore( 'breadcrumbs' ) => ( (bool) $breadcrumbs_html === FALSE ? '$1' : '' ),
    template_preg_decore( 'shop_logo' ) => ( Config::get('logo') != '' ? '$1' : '' ),
    template_no_preg_decore( 'shop_logo' ) => ( Config::get('logo') != '' ? '' : '$1' ),
    template_preg_decore( 'demo' ) => ( $GLOBALS['ust_demo_version'] == 1 ? '$1' : '' ),
    template_no_preg_decore( 'demo' ) => ( $GLOBALS['ust_demo_version'] == 0 ? '$1' : '' ),
    template_preg_decore( 'front_page' ) => ( $is_front_page ? '$1' : '' ),
    template_no_preg_decore( 'front_page' ) => ( !$is_front_page ? '$1' : '' ),
    template_preg_decore('b2b') => $b2bMode ? '$1' : '',
    template_no_preg_decore('b2b') => $b2bMode ? '' : '$1',
    template_preg_decore('b2b_outer') => $b2bMode ? '$1' : '',
    template_no_preg_decore('b2b_outer') => $b2bMode ? '' : '$1',
    template_preg_decore('b2b_demo_access') => $b2bMode && ($b2bConfig['demo_access'] ?? false) ? '$1' : '',
    template_preg_decore('private_mode_logged') => !$GLOBALS['private_mode'] || ($GLOBALS['private_mode'] && isset($_SESSION['user']) && $_SESSION['user'] > 0) ? '$1' : '',
    template_preg_decore('b2b_free_delivery') => $freeDelivery !== false ? '$1' : '',
    template_preg_decore('private_mode') => (true === $privateMode ? '$1' : ''),
    template_no_preg_decore('private_mode') => (false === $privateMode ? '$1' : ''),
    template_preg_decore('catalogue') => (true === $catalogueMode ? '$1' : ''),
    template_no_preg_decore('catalogue') => (false === $catalogueMode ? '$1' : ''),
    template_preg_decore('shop') => (false === $catalogueMode ? '$1' : ''),
    template_preg_decore('show_price') => (false === $catalogueMode || true === $catalogueModeShowPrices ? '$1' : ''),
    template_preg_decore('allow_loginregister') => (false === $catalogueMode || true === $catalogueModeAllowLoginRegister ? '$1' : ''),
);

$_theme_header = preg_replace( array_keys( $arrShopWar ), $arrShopWar, $_theme_header );

if ($b2bMode) {
    if ($freeDelivery !== false) {
        $_theme_header = str_replace('[%b2b_free_delivery%]', formatuj_cene($freeDelivery), $_theme_header);
    }

    if ($b2bConfig['demo_access'] ?? false) {
        $_theme_header = str_replace('[%username%]', 'demo@cstore.pl', $_theme_header);
        $_theme_header = str_replace('[%password%]', 'dJAGi129&@!(*', $_theme_header);
    }

    $hasTrader = isset($_SESSION['user_data']['trader_id'])
        && $_SESSION['user_data']['trader_id'] > 0
        && $sql->Query('SELECT * FROM uzytkownicy WHERE id = ' . $_SESSION['user_data']['trader_id']);

    if ($hasTrader) {
        $trader = $sql->GetRow(0);

        $src = 'modules/trader/admin-images/' . md5($_SESSION['user_data']['trader_id']) . '.png';

        if (! file_exists(BASE_DIR . $src)) {
            $src = url::site('themes/' . $GLOBALS['theme_path'] . '/img/nophoto.png');
        }

        $_theme_header = str_replace('[%trader_src%]', $src, $_theme_header);

        $_theme_header = str_replace('[%trader_name%]', $trader['name'], $_theme_header);
        $_theme_header = str_replace('[%trader_surname%]', $trader['surname'], $_theme_header);
        $_theme_header = str_replace('[%trader_phone%]', $trader['phone'], $_theme_header);
        $_theme_header = str_replace('[%trader_email%]', $trader['email'], $_theme_header);
    }

    if (isset($_SESSION['user']) && $_SESSION['user'] > 0) {
        $sql->Query('SELECT SUM(IF(oplacone = 1, 0, koszt_netto * -1)) AS saldo FROM subiekt2_zamowienia WHERE user_id = ' . $_SESSION['user']); // @TODO: uwzględnić saldo dodatnie (?)

        $saldo = $sql->getField(0, 'saldo');

        $_theme_header = str_replace('[%b2b_saldo%]', str_replace(',00', '', formatuj_cene(round($saldo))), $_theme_header);
        $_theme_header = str_replace('[%b2b_saldo_color%]', $saldo >= 0 ? 'black' : 'danger', $_theme_header);
    }

    $_theme_header = preg_replace(template_preg_decore('trader'), $hasTrader ? '$1' : '', $_theme_header);
}

$res = strpos($_theme_header, '<shopcart>');

if ($res !== FALSE) {
    $_theme_header = template_shopcart($_theme_header);
}

//dodatkowy kod php
if (file_exists($GLOBALS['server_path'] . '/ext/extend_end.php')) {
    include $GLOBALS['server_path'] . '/ext/extend_end.php';
}

//dodatkowy kod php exclusive dla templatek
if ( file_exists( $GLOBALS['server_path'] . '/themes/' . $GLOBALS['theme_path'] . '/ext/extra_end.php')) {
    include $GLOBALS['server_path'] . '/themes/' . $GLOBALS['theme_path'] . '/ext/extra_end.php';
}

for ($i= 0; $i<6; $i++) { 
	
	if ( ! ( 
	strpos($_theme_header, "<!--<cstore_legend>") !== false  
	&& strpos($_theme_header, "</cstore_legend>-->") !== false ))
	break; 
	
	$_theme_header = preg_replace("/(?:\<\!\-\-)+\<cstore_legend\>(?:(?!\<cstore_legend\>).)+<\/cstore_legend\>(?:\-\-\>)+/Us", '', $_theme_header);  
	
}
if (strpos($_SERVER["HTTP_HOST"], ".cstore") !== false) {
    $_theme_header = str_replace("index,follow", "noindex,follow", $_theme_header);
}

$_theme_header = str_replace('[%time%]', time(), $_theme_header);

$_theme_header = str_replace('http://"', '/"', $_theme_header);
$_theme_header = str_replace('https://"', '/"', $_theme_header);
\Prices::addBathPriceHistory();
Core::reader($_theme_header);


if (Debug::check()) {
    $timer->stop();
    if (!is_ajax())
        echo Debug::display();
}

$sql->done(1);
