<?php
require_once('../includes/visitor.inc.php');

use Mnv\Core\Config;

    $fileName  = request()->get('fileName');
    $page      	= (int) request()->get('page');
    $param      = request()->get('param');
	$rewrite   = request()->get('rewrite');
	$nocache   = (boolean) request()->get('nocache');

	if ($brand = connect('brands')->where('fileName',  $fileName)->get('array')) {
		if ($rewrite != Config::getValue('rewrite')) {
			header("HTTP/1.0 301 Moved Permanently");
			header("Location: $brand->url");

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


		$templateName = empty($param) ? 'brand.tpl' : 'collection.tpl';

		if (!$smarty->isCached($templateName, md5($fileName).SITE_LANG_POSTFIX)) {

            $brand = prepareBrand($brand);
			$smarty->assign('brand', $brand);
		}


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


		$smarty->display($templateName, md5($fileName).SITE_LANG_POSTFIX);

	}  else {

		/* article not found */
		header("HTTP/1.0 404 Not Found");

		/* finding URI part, that caused 404 error */
		$requestUri = strtolower(urldecode($_SERVER['REQUEST_URI']));
		$parsedUrl  = parse_url(strtolower(SITE_URL));
        $errorUrl   = isset($parsedUrl['path']) ? str_replace($parsedUrl['path'], '', $requestUri) : $requestUri;

		/* finding all words in the URL */
		if(preg_match_all("/[a-zA-Z0-9]+/", $errorUrl, $matches)) $query = implode(' ', $matches[0]);
		if(!empty($query)) $smarty->assign('query', $query);

		/* saving visit */
		writeErrorVisit(404);
		
		$smarty->display('error-404.tpl', md5($fileName).SITE_LANG_POSTFIX);
	}