<?php

class IndexController extends Controller
{

	/**
	 * 	Действие по умолчанию
	 */
	static function actionIndex()
	{
//		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/leaflet-0.7.3.js');

		self::addScript('http://maps.google.com/maps/api/js?v=3&sensor=false');
		self::addScript('/js/tile/Google.js');

		self::addScript('http://api-maps.yandex.ru/2.0/?load=package.map&lang=ru-RU');
		self::addScript('/js/tile/Yandex.js');

		self::addScript('/js/app.js?ver=' . App::getConfig('version'));
		self::addScript('/js/jquery.cookie.js');
		self::addScript('/js/map.js?ver=' . App::getConfig('version'));
		self::addScript('/js/leaflet-routing-machine.js');
		self::addScript('/js/route.js?ver=' . App::getConfig('version'));
		self::addScript('/js/leaflet.markercluster.js');
		self::addScript('/js/fotorama.js');
		self::addScript('/js/suggest.js?ver=' . App::getConfig('version'));
		self::addScript('/js/navigation.js?ver=' . App::getConfig('version'));

//		self::addStyle('/css/style.css?ver=' . App::getConfig('version'));
		self::addStyle('/css/leaflet-0.7.3.css');
		self::addStyle('/css/bootstrap.min.css');
		self::addStyle('/css/bootstrap-theme.min.css');
		self::addStyle('/css/leaflet-routing-machine.css');
		self::addStyle('/css/MarkerCluster.css');
		self::addStyle('/css/MarkerCluster.Default.css');
		self::addStyle('/css/fotorama.css');

		if (!App::$user)
			self::addScript('//ulogin.ru/js/ulogin.js');

		$category = Category::model()->getAll(array('order' => 'ord ASC'));

		$routes = array();
		if (App::$user && App::$user->id) {
			$routes = Route::model()->getByAuthor(App::$user->id);
			self::addVar('user', App::$user->id);
		} else {
			self::addVar('user', '0');
		}

		$favorites = array();
		if (App::$user && App::$user->id) {
			$favorites = Favorite::model()->getAllMy();
		}

		self::addVar('isAdmin', (int) (App::$user && App::$user->isAdmin == 1));

		$res = App::DB()->query("SELECT COUNT(`id`) pointsCount FROM `points` where `moderate` = 1")->fetch(PDO::FETCH_ASSOC);
		App::setConfig('title', $res['pointsCount'] . ' или даже больше поводов не сидеть дома');
		self::addVar('pointsCount', $res['pointsCount']);

		self::addVar('pointLat', 0);
		self::addVar('pointLng', 0);

		$categoryArray = array();
		foreach ($category as $cat) {
			$categoryArray[] = $cat->getValues();
		}

		$og = array();
		if (isset($_GET['point']) && $_GET['point'] && is_numeric($_GET['point'])) {
			$id = (int) $_GET['point'];

			$point = Point::model()->getByPK($id);
			$point->name = htmlspecialchars($point->name);
			$point->descriptionHtml = htmlspecialchars($point->description);
			$point->descriptionHtml .= ' Посмотреть на карте: http://wikipoints.ru/?point=' . $id;
			$point->descriptionHtml .= ' #wikipoints';

			$og = Helper::buildOG($point);

			self::addVar('pointLat', $point->lat);
			self::addVar('pointLng', $point->lng);
		} else if (isset($_GET['point']) && $_GET['point'] && strtolower($_GET['point']) == 'random') {
			$og['title'] = 'Случайная точка на wikipoints.ru';
			$og['description'] = 'Загляните сюда: http://vk.com/wikipoints Случайная точка на карте - лучший способ узнать что-то новое!';
			$og['site_name'] = 'WikiPoints - ' . $res['pointsCount'] . ' или даже больше поводов не сидеть дома';
			$og['type'] = 'article';
			$og['url'] = 'http://wikipoints.ru/?point=random';
			$og['image'] = 'http://wikipoints.ru/img/compas.jpg';
		}

		self::render('indexTemplate.php', array(
			'categories' => $category,
			'categoryArray' => $categoryArray,
			'user' => App::$user,
			'routes' => $routes,
			'favorites' => $favorites,
			'og' => $og,
		));
	}

	static function actionUser()
	{
		App::error404();
		$routes = Route::model()->getByAuthor(App::$user->id);

		var_dump($routes);
	}

	static function actionLogout()
	{
		App::userLogout();
		App::redirect('/');
	}

	static function actionLogin()
	{
		$source = file_get_contents('http://ulogin.ru/token.php?token=' . $_POST['token'] . '&host=' . $_SERVER['HTTP_HOST']);
		$uLoginUser = json_decode($source, true);
		$uLoginUser['identity'] = md5($uLoginUser['uid'] . $uLoginUser['network'] . '=P');

		$user = User::model()->getByUID($uLoginUser['identity']);

		if (!$user->id) {
			$user = $user->add(array(
				'uid' => $uLoginUser['identity'],
				'nick' => $uLoginUser['nickname'],
				'name' => $uLoginUser['first_name'],
				'profile' => $uLoginUser['profile'],
				'network' => $uLoginUser['network'],
				'photo' => $uLoginUser['photo_big'],
			));

			if (!$user) {
				return false;
			}
		}

		App::userLogin($user);
		App::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '/');
	}

	static function actionSitemap()
	{
		$xml = new SimpleXMLElement('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>');

		$articles = Article::model()->getAll(array('order' => 'ID DESC', 'asArray' => true));
		foreach ($articles as $article) {
			$url = $xml->addChild('url');
			$url->addChild('loc', 'http://wikipoints.ru/page/article/id/' . $article['id']);
			$url->addChild('lastmod', date("Y-m-d", strtotime('- 5 days')));
			$url->addChild('changefreq', "weekly");
			$url->addChild('priority', "0.8");
		}

		$points = Point::model()->getAll(array('order' => 'ID DESC', 'asArray' => true));
		foreach ($points as $point) {
			$url = $xml->addChild('url');
			$url->addChild('loc', 'http://wikipoints.ru/page/point/id/' . $point['id']);
			$url->addChild('lastmod', date("Y-m-d", $point['date']));
			$url->addChild('changefreq', "weekly");
			$url->addChild('priority', "0.8");
		}

		Header('Content-type: text/xml');
		print($xml->asXML());
	}

	static function actionRoute()
	{
		self::$layout = 'layoutPrint.php';
		self::addStyle('/css/print.css?ver=' . App::getConfig('version'));

		if (!isset($_GET['route']) || !$_GET['route']) {
			App::error404('Нет данных для построения маршрута!');
		}

		$route = json_decode($_GET['route']);

		if (!$route || !is_array($route)) {
			App::error404();
		}

		$points = array();
		foreach ($route as $pointId) {
			if ((int) $pointId) {
				$points[] = Point::model()->getByPK($pointId);
			}
		}

		self::render('route.php', array(
			'points' => $points,
		));
	}

}
