<?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]) && $article = connect('articles')->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: $article[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($article['commentsEnabled'] == 1) {
        $article['commentsEnabled'] = 1;
    } elseif($article['commentsEnabled'] == -1) {
        $article['commentsEnabled'] = 0;
    } elseif($article['commentsEnabled'] == 0){
        $article['commentsEnabled'] = 0;
        if($SECTIONS[$sectionId]['commentsEnabled'] == 1) {
            $article['commentsEnabled'] = 1;
        } elseif($SECTIONS[$sectionId]['commentsEnabled'] != -1 && Config::getValue('comments_enabled') == 1){
            $article['commentsEnabled'] = 1;
        }
    }

    $article['section'] = $SECTIONS[$article['sectionId']];
    $templateName = empty($SECTIONS[$sectionId]['artTemplateName']) ? 'article.tpl' : $article['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($article['sectionId']);
        $smarty->assign('sectionParents', $sectionParents);

        $article = prepareArticle($article);
        $fields = getProperties($article['articleId']);
        if (!empty($fields)) {
            foreach ($fields as $fieldId => $field) {
                $article[$fieldId] = $field;
            }
        }

//        print_r($article);

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

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

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

    /** просмотры */
    articleViewCounter($article['articleId']);
    /** saving visit */
    writeArticleVisit($article['articleId']);

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

    /* precise load time */
    updateLoadTime();

} else if ($article = connect('articles')->select('articleId, 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: $article[url]");
    echo "<html><body>Moved to <a href=\"$article[url]\">$article[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();
}
?>