<?php

use Mnv\Core\Config;
use Mnv\Core\Utilities\Cookie\Session;

require_once '../includes/visitor.inc.php';

	$sectionId 	= (int) request()->get('sectionId');
	$page      	= (int) request()->get('page');
	$rewrite   	= request()->get('rewrite');

    $query      = request()->get('query');
    $min_price  = request()->get('min_price', '');
    $max_price  = request()->get('max_price', '');
    $sort       = request()->get('sort', null);
    $special    = (string)request()->get('special', null);


    if (!empty($SECTIONS[$sectionId])) {
		$section = prepareSection($SECTIONS[$sectionId]);
		$smarty->assign('section', $section);
	} else {
		header("HTTP/1.0 301 Moved Permanently");
		header("Location: ".SITE_URL."/");

		/* saving visit */
		writeErrorVisit(301);
		exit;
	}

	/* checking whether we in rewrite mode */
	if ($rewrite != Config::getValue('rewrite')) {
		header("HTTP/1.0 301 Moved Permanently");
        header("Location: $section[url]");

		/* saving visit */
		writeErrorVisit(301);
		exit;
	}

    $requestUri = $_SERVER["REQUEST_URI"];
    $countReplace = 0;
    $replaced_url = preg_replace('/\/\/+/', '/', $requestUri, -1, $countReplace);
    if ($countReplace > 0) {
        header("HTTP/1.0 301 Moved Permanently");
        header("Location: $section[url]");
        exit;
    }

	/* caching procedures */
	if ($section['isCached'] == 1) {
		$smarty->caching( 2, $section['cacheTime'] * $section['cachePeriod']);
	} elseif ($section['isCached'] != -1 && Config::getValue('cache_enabled_section') == 1) {
		$smarty->caching = 2;
        $smarty->caching( 2, Config::getValue('cache_time_section') * Config::getValue('cache_period_section'));
	}

	if ($page < 1) $page = 1;
    $smarty->assign('page', $page);

	/* for "you-are-here" navigation */
//	$sectionParents = getSectionParents($sectionId);
//	$section['parent'] = getSectionParent($section['parentId']);
//
//	$smarty->assign('sectionParents', $sectionParents);
//	$smarty->assign('activeSection', $SECTIONS[$sectionId]);


    $params = [];
    if (!empty($query)) $params['query'] = $query;
    if (!empty($min)) $params['min'] = $min;
    if (!empty($max)) $params['max'] = $max;
    if (!empty($sort)) $params['sort'] = $sort;

    $queryString = !empty($params) ? '&' . http_build_query(array_filter($params)) : '';
    $smarty->assign('queryString',  preg_replace( '/^.(.*)$/', '\1', $queryString ));

    $smarty->assign('query', $query);
    $smarty->assign('min_price', $min_price);
    $smarty->assign('max_price', $max_price);
    $smarty->assign('sort', Session::get('sort'));

	/* saving visit */
	writeSectionVisit($sectionId, $page);

    $templateName = empty($section['templateName']) ? ($section['type'] == 'tree' ? 'section.tpl' : 'page.tpl') : $section['templateName'];
	$smarty->display($templateName, "$sectionId-$page".SITE_LANG_POSTFIX);

	/* precise load time */
	updateLoadTime();

?>