<?php

require_once 'intro.php';

// Получаем массив ARGV
// 26.01.17: правильно ли получать его таким образом? и вообще нужно ли?
$argvs = explode('/', $doc['path'], -1);
$doc['argv'] = [];
foreach ($argvs as $argv) {
	if (!empty($argv)) {
		array_push($doc['argv'], $argv);
	}
}
unset($argvs);

// заполняем UTM метки для форм
if (empty($_SESSION['utm'])) {
	$_SESSION['utm'] = [];
}
if (empty($_SESSION['utm']['source']) && !empty($_GET['utm_source'])) {
	$_SESSION['utm']['source'] = $_GET['utm_source'];
}
if (empty($_SESSION['utm']['source']) && !empty($_SERVER['HTTP_REFERER'])) {
   // если источник пустой, тогда запишем домен откуда мы пришли
   $domain_parsed = parse_url($_SERVER['HTTP_REFERER']);
    $domain_self = parse_url($doc['host']);
    if(!empty($domain_parsed['host']) && $domain_self['host'] != $domain_parsed['host'] ) {
      $_SESSION['utm']['source'] = $domain_parsed['host'];
   }
   if (!empty($_SESSION['utm']['source'])) {
      // преобразовываем источник
      if (strpos($_SESSION['utm']['source'], "yandex") !== false) {
         $_SESSION['utm']['source'] = "yandex";
      } else if (strpos($_SESSION['utm']['source'], "google") !== false) {
         $_SESSION['utm']['source'] = "google";
      }
   }
}
if (empty($_SESSION['utm']['campaign']) && !empty($_GET['utm_campaign'])) {
	$_SESSION['utm']['campaign'] = $_GET['utm_campaign'];
}
if (empty($_SESSION['utm']['medium']) && !empty($_GET['utm_medium'])) {
	$_SESSION['utm']['medium'] = $_GET['utm_medium'];
}
if (empty($_SESSION['utm']['referer']) && !empty($_SERVER['HTTP_REFERER'])) {
	$_SESSION['utm']['referer'] = $_SERVER['HTTP_REFERER'];
}

if (!isset($doc['settings']['use_pages']) || $doc['settings']['use_pages'] == 1) {
	if (!file_exists($doc['root'].$doc['path']) || is_dir($doc['root'].$doc['path'])) {
		$id = getidfrompath($doc['path']);
		if ($id['code'] == 301) {
			redirect_page($id['page'], 301);
		}

    if($id['code'] == 404 || !in_array(hp2("view_page",$doc['path']), [1,""])) {
        header('HTTP/1.1 404 Not Found');
        $id['page'] = getVal("SELECT `id` FROM `pages` WHERE `name` = '404' ");
        $doc['path'] = '404/';
    }
		$redir = getVal("SELECT `redirect` FROM `pages` WHERE `id`= '".adds($id['page'])."' LIMIT 1");
		if (!empty($redir) && $doc['logeduser']['group'] != '1') {
			redirect_page($redir);
		}

		$doc['page'] = diadm_page('info', $id['page']);
		$doc['url'] = $doc['page']['url'];
		if (empty($doc['page']['outtemplate'])) {
			$doc['page']['outtemplate'] = $doc['settings']['template_name'];
		}
		if ($doc['request']['method'] == 'get') {
			if ($id['code'] != 404) {
				if (isset($_SESSION['cur_page']) && (!isset($_SESSION['prev_page']) || $_SESSION['cur_page'] != $doc['page']['id'])) {
					$_SESSION['prev_page'] = $_SESSION['cur_page'];
				}
				if (isset($doc['page']['id']) && $doc['page']['id'] != 8) // Вай! Нехорошее условие!
				{
					$_SESSION['cur_page'] = $doc['page']['id'];
				}

                $_SESSION['prev_get'] = !empty($_SESSION['cur_get']) ? $_SESSION['cur_get'] : ""; // Странный набор условий был. Баг с очисткой старого гета пропал, но может что-то другое сломалось?
				$_SESSION['cur_get'] = http_build_query($_GET);
			}

			/* РЕДИРЕКТИМ НА СТРАНИЦУ ЛОГИН ЛИБО ДЕЛАЕМ EXIT В СЛУЧАЕ ЕСЛИ НЕ НАДО */
			if ($doc['settings']['login_required'] == 1) {
				$loginpage = 4;  //id страницы логина
				if (!isset($doc['logeduser']) && $doc['page']['id'] != $loginpage) {
					header("Location: ".$doc['host'].getpagepath($loginpage));
					die();
				} elseif ($doc['settings']['login_redirect'] == 1 && isset($doc['logeduser']) && $doc['page']['id'] == $loginpage) {
					if ($_SESSION['prev_page'] != $loginpage) {
						header("Location: ".$doc['host'].getpagepath($_SESSION['prev_page']));
					} else {
						header("Location: ".$doc['host']);
					}
					die();
				}
			}
		}
	}
}


/* css */
$out = ((empty($doc['page']['outtemplate'])) ? ($doc['settings']['template_name']) : ($doc['page']['outtemplate'])); //верно
$tpl = ((empty($doc['page']['template'])) ? ($out) : ($doc['page']['template'])); //добавить проверку админа через HP2
$doc['template']['name'] = $out;
$doc['template']['path'] = $doc['host']."site/templates/".$out."/";

/* Определяем переменную прав доступа. Заменить на HP2! */
$hp = hp();
//$hp = hp2("view_page");

/* 1. Цепляем файл с кодом для конкретного сайта */
if (file_exists("core/includes/preprocessor.php")) {
	include_once("core/includes/preprocessor.php");
}
if (file_exists("site/includes/site_preprocessor.php")) {
	include_once("site/includes/site_preprocessor.php");
}

/**
 * Определяем, используем мы контроллеры или работаем по обычным страницам
 */
$useController = false;
$uri = !empty($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : "";
if(substr($uri, -1)=="/")
{
	$uri = substr($uri, 0, strlen($uri)-1);
}
$path = explode("/", $uri);
$path = array_values(array_filter($path));


if(!empty($path[0]))
{
    $controllerName = $path[0]."Controller";
    $controllerFile = $doc['root'].'App/Controllers/'.$controllerName.".php";

    $action = @array_pop(array_slice($path, -1));

    $path= array_slice($path, 1);
    $path= array_slice($path, 0, count($path)-1);
    if(file_exists($controllerFile))
    {
        require_once $controllerFile;
        $method = "action".ucfirst($action);

        // execute;
        if(method_exists($controllerName, $method))
        {
            $doc['path'] = $path;
            $useController = true;
        }
    }
}
/**
 * Определяем, используем мы контроллеры или работаем по обычным страницам
 */



$outtemplate = $doc['settings']['template_name']
    ?: 'default';

$siteTemplatePath = $doc['page']['template']
    ?: 'default';

$siteTemplate = explode('/', $siteTemplatePath)[0] ?: $outtemplate;
$subTemplate = explode('/', $siteTemplatePath)[1] ?? null;
$componentName = $doc['page']['component_name'];

$coreComponentFolder = $doc['root'].'core/components/'.$componentName;
$templateFolder = $doc['root']."site/templates/".$siteTemplate."/components/".$componentName;
$subTemplateFolder = $templateFolder . ($subTemplate ? "/" . $subTemplate : "");

/* подключаем файл функций компонента */
if (file_exists($coreComponentFolder."/functions.php")) {
    include_once $coreComponentFolder."/functions.php";
}

/* 2. ПОДКЛЮЧАЕМ ФАЙЛЫ СТРАНИЦЫ */
switch ($doc['request']['method']) {
	case "get":
		if ( $useController == true ) {
			(new $controllerName)->$method();
//			call_user_func(array(new $controllerName, $method));
		}
		else if (!isset($doc['settings']['use_pages']) || $doc['settings']['use_pages'] == 1) {
			$tdir = $doc['root']."site/templates/".$out."/";
			if (!isset($_GET['di-noheader']) && file_exists($tdir."/header.php")) {
				require_once ($tdir."header.php");
			}
			$par = [];
			if (isset($_GET['di-template'])) {
				$par['page']['template'] = $_GET['di-template'];
			}
			includepage($doc['page']['id'], $par);
			if (!isset($_GET['di-nofooter']) && file_exists($tdir."/footer.php")) {
				include($tdir."footer.php");
			}
		}

		break;

	case "ajax":
		/* подключаем корневой ajax. в нем прописаны общие ajax функции админки */
		include_once $doc['root']."core/includes/ajax.php";
        $from_ajax = 1;
		if ( $useController == true ) {
			(new $controllerName)->$method();
			//call_user_func(array(new $controllerName, $method));
		}
		else if (!isset($doc['settings']['use_pages']) || $doc['settings']['use_pages'] == 1) {
            /* если используются страницы */
            loadComponentFiles([$subTemplateFolder, $templateFolder], $componentName);

            /* подключаем ajax файл компонента */
            if (file_exists($coreComponentFolder."/ajax.php")) {
                include_once $coreComponentFolder."/ajax.php";
            } else {
                include_once $coreComponentFolder."/index.php";
            }
		}
		break;

	case "post":
		/* подключаем корневой post */
		include($doc['root']."core/includes/post.php");
        $from_post = 1;
		if ( $useController == true ) {
			(new $controllerName)->$method();
			//call_user_func(array(new $controllerName, $method));
		}
        else if (!isset($doc['settings']['use_pages']) || $doc['settings']['use_pages'] == 1) {
            /* если используются страницы */
            loadComponentFiles([$subTemplateFolder, $templateFolder], $componentName);

			/* подключаем файл post компонента нашей страницы */
			if (file_exists($coreComponentFolder."/post.php")) {
				include_once($coreComponentFolder."/post.php");
			} else {
				include_once $coreComponentFolder."/index.php";
			}
		}

		/* определяем, какой адрес открыть после выполнения всего кода из post */
		if (isset($_SESSION['post_redirect'])) {
			$re = $doc['host'].getpagepath($_SESSION['post_redirect']).((!empty($_SESSION['post_redirect_get'])) ? ("?") : ("")).$_SESSION['post_redirect_get'];
			unset($_SESSION['post_redirect']);
			unset($_SESSION['post_redirect_get']);
		}
		if (isset($_POST['re'])) {
			$re = adds($_POST['re']);
		}
		if (isset($_GET['re'])) {
			$re = addslashes($_GET['re']);
		}
		if (isset($re) ) {
		    if( is_numeric($re) )
            {
                $re = $doc['host'].getpagepath($re);
            }
		    if( strpos($re, "http://") != 0 )
            {
			$re = $doc['host'].$re;
		}
		}
		if (empty($re)) {
			$re = $doc['host'].getpagepath($doc['page']['id']);
		}
//		hr($re);
		header("Location: ".$re);
		exit();
		break;

	default :
		break;
}

// Заносим весь вывод в переменную
$html = ob_get_contents();

// Очищаем память
ob_end_clean();


/* 3. Цепляем файл с кодом для конкретного сайта */
if (file_exists("core/includes/afterprocessor.php")) {
	include_once("core/includes/afterprocessor.php");
}
if (file_exists("site/includes/site_afterprocessor.php")) {
    include_once("site/includes/site_afterprocessor.php");
}

/* 4. Цепляем управляющий выводом содержимого страницы */
if (file_exists("core/includes/echo.php")) {
	include_once("core/includes/echo.php");
}
