<?php

class PageController extends Controller
{
	const elementsByPage = 30;
	const minElementsByPage = 10;

	static function actionPoints()
	{
		self::$layout = 'layouts/page.php';
		self::addStyle('/css/style.css?ver=' . App::getConfig('version'));
		self::addStyle('/css/pageStyle.css?ver=' . App::getConfig('version'));
		self::addScript('/js/jquery-2.1.0.min.js');
		self::addScript('/js/jquery-ui-1.10.4.custom.min.js');
		self::addScript('/js/bootstrap.min.js');
		self::addScript('/js/app.js');
		self::addStyle('/css/bootstrap.min.css');
		self::addStyle('/css/bootstrap-theme.min.css');

		$notModeratedPoints = $result = array();

		// On moderation
		if (App::$user && App::$user->isAdmin) {
			$param['order'] = 'id DESC';
			$param['where'] = '`status` = "moderation"';
			$points = Point::model()->getAll($param);
			$categories = Category::model()->getAll(array('order' => 'ord ASC'));

			foreach ($points as $point) {
				$id = $point->id;
				$result[$id]['id'] = $point->id;
				$result[$id]['name'] = $point->name;
				$result[$id]['lat'] = $point->lat;
				$result[$id]['lng'] = $point->lng;
				$result[$id]['author'] = $point->authorUser->nick;
				$result[$id]['categoryId'] = $point->categoryId;
				$result[$id]['categoryIcon'] = $categories[$point->categoryId]->icon;
			}
			$notModeratedPoints = $result;
		}
		// ------------------------------------------

		$param = array();
		$param['order'] = '`ord` ASC';

		if (App::getParam('category')) {
			$param['where'] = 'categoryId = ' . (int) App::getParam('category') . ' AND `status` = "published"';
		} else if (App::getParam('user')) {
			$param['where'] = '`author` = ' . (int) App::getParam('user') . ' AND `status` = "published"';
		} else {
			$param['where'] = '`status` = "published" AND `categoryId` NOT IN ('.  implode(',', Category::$paidIds).')';
		}

		$pointsCount = Point::model()->getCount($param);
		$pagesCount = intval(ceil($pointsCount/self::elementsByPage));
		$fullPagesCount = intval(floor($pointsCount/self::elementsByPage));
		$residue = $pointsCount - ($fullPagesCount * self::elementsByPage);

		if ($residue < self::minElementsByPage) {
			$pagesCount = $fullPagesCount;
		}

		$page = isset($_GET['page']) ? abs((int)$_GET['page']) : $pagesCount;

		$pages = array();

		// Заполняем страницы от большей к меньшей - добавляем 3 штуки
		for ($index = $pagesCount; (($index > $pagesCount-3) && ($index > 0)); $index--) {
			$pages[$index] = 1;
		}

		// Заполняем страницы от 3 к 1 - добавляем 3 штуки
		if ($pagesCount >= 3) {
			for ($index = 3; $index > 0; $index--) {
				$pages[$index] = 1;
			}
		}

		if ($page > $pagesCount) {
			$page = $pagesCount;
		} else if ($page < 1) {
			$page = 1;
		}

		// Заполняем страницы вокруг текущей. +/- 2 штуки.
		$topIndex = ($page+2 > $pagesCount) ? $pagesCount : $page+2;
		$bottomIndex = ($page-3 < 1) ? 1 : $page-3;
		for ($index = $topIndex; $index > $bottomIndex; $index--) {
			$pages[$index] = 1;
		}

		krsort($pages);

		if ($page == $pagesCount && $residue < self::minElementsByPage) {
			$param['limit'] = self::elementsByPage + $residue;
		} else {
			$param['limit'] = self::elementsByPage;
		}

		if($page) {
			$param['offset'] = self::elementsByPage * ($page - 1);
		}

		$points = Point::model()->getAll($param);
		$points = array_reverse($points);
		$categories = Category::model()->getAll(array('order' => 'ord ASC'));

		$result = array();

		foreach ($points as $point) {
			$id = $point->id;
			$result[$id]['id'] = $point->id;
			$result[$id]['name'] = $point->name;
			$result[$id]['lat'] = $point->lat;
			$result[$id]['lng'] = $point->lng;
			$result[$id]['img'] = $point->getImg('middle');
			$result[$id]['author'] = $point->authorUser->nick;
			$result[$id]['categoryId'] = $point->categoryId;
			$result[$id]['categoryIcon'] = $categories[$point->categoryId]->icon;
		}

		App::setConfig('title', App::$defaultTitle);

		self::render('page/points.php', array(
			'categories' => $categories,
			'points' => $result,
			'pointsCount' => $pointsCount,
			'page' => $page,
			'pagesCount' => $pagesCount,
			'pages' => $pages,
			'notModeratedPoints' => $notModeratedPoints,
			'randomPoint' => Point::model()->getRandom(),
		));
	}

	static function actionArticles()
	{
		self::$layout = 'layouts/page.php';
		self::addStyle('/css/style.css?ver=' . App::getConfig('version'));
		self::addStyle('/css/pageStyle.css?ver=' . App::getConfig('version'));
		self::addScript('/js/jquery-2.1.0.min.js');
		self::addScript('/js/jquery-ui-1.10.4.custom.min.js');
		self::addScript('/js/bootstrap.min.js');
		self::addScript('/js/app.js');
		self::addStyle('/css/bootstrap.min.css');
		self::addStyle('/css/bootstrap-theme.min.css');

		$param = array();
		$param['order'] = '`pubDate` ASC';
		$param['where'] = '`status` = "published"';

		$articlesCount = Article::model()->getCount($param);
		$pagesCount = intval(ceil($articlesCount/self::elementsByPage));
		$fullPagesCount = intval(floor($articlesCount/self::elementsByPage));
		$residue = $articlesCount - ($fullPagesCount * self::elementsByPage);

		if ($residue < self::minElementsByPage) {
			$pagesCount = $fullPagesCount;
		}

		$page = isset($_GET['page']) ? abs((int)$_GET['page']) : $pagesCount;

		$pages = array();

		// Заполняем страницы от большей к меньшей - добавляем 3 штуки
		for ($index = $pagesCount; (($index > $pagesCount-3) && ($index > 0)); $index--) {
			$pages[$index] = 1;
		}

		// Заполняем страницы от 3 к 1 - добавляем 3 штуки
		if ($pagesCount >= 3) {
			for ($index = 3; $index > 0; $index--) {
				$pages[$index] = 1;
			}
		}

		if ($page > $pagesCount) {
			$page = $pagesCount;
		} else if ($page < 1) {
			$page = 1;
		}

		// Заполняем страницы вокруг текущей. +/- 2 штуки.
		$topIndex = ($page+2 > $pagesCount) ? $pagesCount : $page+2;
		$bottomIndex = ($page-3 < 1) ? 1 : $page-3;
		for ($index = $topIndex; $index > $bottomIndex; $index--) {
			$pages[$index] = 1;
		}

		krsort($pages);

		if ($page == $pagesCount && $residue < self::minElementsByPage) {
			$param['limit'] = self::elementsByPage + $residue;
		} else {
			$param['limit'] = self::elementsByPage;
		}

		if($page) {
			$param['offset'] = self::elementsByPage * ($page - 1);
		}

		$articles = Article::model()->getAll($param);
		$articles = array_reverse($articles);

		$result = array();

		foreach ($articles as $article) {
			$id = $article->id;
			$result[$id]['id'] = $article->id;
			$result[$id]['title'] = $article->title;
			$result[$id]['text'] = mb_substr(Markdown::getClear($article->text), 0, 400, 'UTF-8');
			$result[$id]['photoId'] = $article->photoId;
			$result[$id]['img'] = $article->getImg('middle');
			$result[$id]['author'] = $article->authorUser->nick;
		}

		App::setConfig('title', App::$defaultTitle);

		self::render('page/articles.php', array(
			'articles' => $result,
			'articlesCount' => $articlesCount,
			'page' => $page,
			'pagesCount' => $pagesCount,
			'pages' => $pages,
			'randomPoint' => Point::model()->getRandom(),
		));
	}

	static function actionPoint()
	{
		$pointId = (int) App::getParam('id');
		if ($pointId) {
			App::redirect('/point/'.$pointId, 301);
		} else {
			App::error404();
		}
	}

	static function actionArticle()
	{
		$articleId = (int) App::getParam('id');
		if ($articleId) {
			App::redirect('/article/'.$articleId, 301);
		} else {
			App::error404();
		}
	}

	static function actionVkpoint()
	{
		$pointId = (int) App::getParam('id');
		if (App::$user && App::$user->isAdmin == 1 && $pointId) {
			$point = Point::model()->getByPK($pointId);

			if ($point->id == NULL) {
				App::error404();
			}

			$point->descriptionHtml = nl2br($point->description);
			$point->name = htmlspecialchars($point->name);

			$categories = Category::model()->getAll(array('order' => 'ord ASC', 'asArray' => true));

			$point->description = Helper::replaceLinks($point->description);

			self::renderPartial('page/vkPoint.php', array(
				'point' => $point,
				'photos' => $point->photos,
			));
		} else {
			App::error404();
		}
	}

	static function actionInstapoint()
	{
		$pointId = (int) App::getParam('id');
		if (App::$user && App::$user->isAdmin == 1 && $pointId) {
			$point = Point::model()->getByPK($pointId);

			if ($point->id == NULL) {
				App::error404();
			}

			$point->descriptionHtml = nl2br($point->description);
			$point->name = htmlspecialchars($point->name);

			$categories = Category::model()->getAll(array('order' => 'ord ASC', 'asArray' => true));

			$point->description = Helper::replaceLinks($point->description);

			self::renderPartial('page/instaPoint.php', array(
				'point' => $point,
				'photos' => $point->photos,
			));
		} else {
			App::error404();
		}
	}

	static function action404($message)
	{
		self::$layout = 'layouts/page.php';
		self::addStyle('/css/style.css?ver=' . App::getConfig('version'));
		self::addStyle('/css/pageStyle.css?ver=' . App::getConfig('version'));
		self::addStyle('/css/bootstrap.min.css');
		self::addScript('/js/jquery-2.1.0.min.js');
		self::addScript('/js/bootstrap.min.js');

		App::setConfig('title', App::$defaultTitle);
		self::render('error404.php', array(
			'randomPoint' => Point::model()->getRandom(),
		));
	}

	static function actionStatus()
	{
		if (App::$user && App::$user->isAdmin == 1) {
			self::$layout = 'layouts/page.php';
			self::addStyle('/css/style.css?ver=' . App::getConfig('version'));
			self::addStyle('/css/pageStyle.css?ver=' . App::getConfig('version'));
			self::addStyle('/css/bootstrap.min.css');
			self::addScript('/js/jquery-2.1.0.min.js');
			self::addScript('/js/bootstrap.min.js');

			App::setConfig('title', 'Сводка по проекту');

			$points = Point::model()->getCount(array(
				'where' => '`status` = "published" AND `categoryId` NOT IN ('.  implode(',', Category::$paidIds).')',
			));

			$paidPoints = Point::model()->getCount(array(
				'where' => '`status` = "published" AND `categoryId` IN ('.  implode(',', Category::$paidIds).')',
			));

			$notModeratedPoints = Point::model()->getCount(array(
				'where' => '`status` = "moderation"',
			));

			$articles = Article::model()->getCount(array(
				'where' => '`status` = "published"',
			));

			$comments = Comment::model()->getCount();

			$users = User::model()->getCount();

			self::render('page/status.php', array(
				'points' => $points,
				'paidPoints' => $paidPoints,
				'notModeratedPoints' => $notModeratedPoints,
				'articles' => $articles,
				'comments' => $comments,
				'users' => $users,
				'randomPoint' => Point::model()->getRandom(),
			));
		} else {
			App::error404();
		}
	}

}
