<?php

use Mnv\Core\Config;

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

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

$caching = false;

$fileName = strtolower($fileName);

if (!empty($SECTIONS[$sectionId])
    && $product = connect('products')->where('sectionId', $sectionId)->where('fileName', strtolower($fileName))->get('array')) {
    /* checking whether we in rewrite mode */
    if ($rewrite != Config::getValue('rewrite')) {
        header("HTTP/1.0 301 Moved Permanently");
        header("Location: $product[url]");

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

    /* caching procedures */
    if ($nocache) {
        $smarty->caching(0, null);
    } elseif($SECTIONS[$sectionId]['artIsCached'] == 1){
        $smarty->caching(2, $SECTIONS[$sectionId]['artCacheTime'] * $SECTIONS[$sectionId]['artCachePeriod']);
    } elseif($SECTIONS[$sectionId]['artIsCached'] != -1 && Config::getValue('cache_enabled_article') == 1) {
        $smarty->caching(2, Config::getValue('cache_time_article') * Config::getValue('cache_period_article'));
    }

    /* commenting procedures */
    if($product['commentsEnabled'] == 1){
        $product['commentsEnabled'] = 1;
    } elseif($product['commentsEnabled'] == -1){
        $product['commentsEnabled'] = 0;
    } elseif($product['commentsEnabled'] == 0){
        $product['commentsEnabled'] = 0;
        if($SECTIONS[$sectionId]['commentsEnabled'] == 1){
            $product['commentsEnabled'] = 1;
        } elseif($SECTIONS[$sectionId]['commentsEnabled'] != -1 && Config::getValue('comments_enabled') == 1){
            $product['commentsEnabled'] = 1;
        }
    }

    $product['section'] = $SECTIONS[$product['sectionId']];
    $templateName = empty($SECTIONS[$sectionId]['artTemplateName']) ? 'product.tpl' : $product['section']['artTemplateName'];

    try {
        $caching = $smarty->isCached($templateName, md5($fileName).SITE_LANG_POSTFIX);
    } catch (SmartyException|Exception $e) {
        print_r($e->getMessage());
    }

    if (!$caching) {
        /* for "you-are-here" navigation */
        $sectionParents = getSectionParents($product['sectionId']);
        $smarty->assign('sectionParents', $sectionParents);

        $product = prepareProduct($product);
        $product['brand']    = getProductBrand($product['brand']);
        $product['options']  = getProductOptions($product['productId']);
        $product['features'] = getAllProductFeatures($product['productId'], $product['sectionId']);
//        $product['features'] = getProductFeatureValues($product['productId']);

        /* displaying product */
//        print_r($product);
        $smarty->assign('product', $product);

        /* saving fetched article for SKIP ability */
        if (empty($fetchedArticles['primaryArticle'])) {
            $fetchedArticles['primaryArticle'] = array();
        }
        $fetchedArticles['primaryArticle'][] = $product['productId'];

        $smarty->assign('activeSection', $SECTIONS[$sectionId]);
    }

    /** просмотры */
//    articleViewCounter($product['productId']);
    /** saving visit */
    writeProductVisit($product['productId']);

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

    /* precise load time */
    updateLoadTime();

} else if ($product = connect('products')->select('productId, url')->where('LOWER(fileName)', strtolower($fileName))->get('array')) {

    /* wrong section or filename character case - redirecting browser to the correct address */
    header("HTTP/1.0 301 Moved Permanently");
    header("Location: $product[url]");
    echo "<html><body>Moved to <a href=\"$product[url]\">$product[url]</a></body></html>";

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

} else if ($section = connect('sections')->select('sectionId, url')->where('LOWER(fileName)', strtolower($fileName))->get('array')) {

    /* user wanted to open section, but not an article - redirecting browser to the correct address */
    header("HTTP/1.0 301 Moved Permanently");
    header("Location: $section[url]");
    echo "<html><body>Moved to <a href=\"$section[url]\">$section[url]</a></body></html>";

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

} 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);
    }

    /* finding all words in the URL and find all sections equal to the words */
    if (preg_match_all("/[0-9a-zA-Z]+/", $errorUrl, $matches)) {
        $query = implode(' ', $matches[0]);
        $sectionIDs = connect('sections')->select('sectionId')->whereAgainst('name',  $query)->where('status', 'V')->valueKey('sectionId')->getAllIndexes();
        if (!empty($sectionIDs)) {
            foreach ($sectionIDs as $sectionId) {
                $section = $SECTIONS[$sectionId];
                if ($section['parents']) {
                    foreach ($section['parents'] as $parentId) {
                        $section['codeName'][] = ucfirst($SECTIONS[$parentId]['name']);
                    }
                }
                $section['codeName'][] = ucfirst($section['name']);
                $section['codeName'] = implode(' :: ', $section['codeName']);
                $sections[] = $section;
                if (count($sections) >= 5) break;
            }
        }
        if (!empty($sections)) {
            $smarty->assign('sections', $sections);
        }
    }

    /* saving visit */
    writeErrorVisit(404);

    $smarty->display('error-404.tpl', md5($fileName).SITE_LANG_POSTFIX);

    /* precise load time */
    updateLoadTime();
}
?>