<?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.js');

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

		self::addScript('/js/api-maps-yandex-2.0.js');
		self::addScript('/js/tile/Yandex.js');

		self::addScript('/js/app.js?ver=' . App::getConfig('version'));
		self::addScript('/js/jquery.cookie.js');
		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/suggest.js?ver=' . App::getConfig('version'));
		self::addScript('/js/navigation.js?ver=' . App::getConfig('version'));
		self::addScript('/js/map.js?ver=' . App::getConfig('version'));
		self::addScript('/js/fotorama.js');
		self::addScript('/js/tracks.js?ver=' . App::getConfig('version'));

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

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

		$routes = $favorites = $tracks = array();
		if (App::$user && App::$user->id) {
			self::addVar('user', App::$user->id);
			$routes = Route::model()->getByAuthor(App::$user->id);
			$favorites = Favorite::model()->getAllMy();
			$tracks = Trips::model()->getAll(array('where' => '`owner` = ?'), array(App::$user->id));
		} else {
			self::addVar('user', '0');
		}

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

		self::addVar('isAdmin', (int) (App::$user && App::$user->isAdmin == 1));
		self::addVar('pointLat', (isset($_GET['lat'])?floatval($_GET['lat']):0));
		self::addVar('pointLng', (isset($_GET['lng'])?floatval($_GET['lng']):0));

		if (isset($_COOKIE['userLat']) && isset($_COOKIE['userLng'])) {
			self::addVar('userLat', $_COOKIE['userLat']);
			self::addVar('userLng', $_COOKIE['userLng']);
		} else {
			self::addVar('userLat', App::$userGeo['lat']);
			self::addVar('userLng', App::$userGeo['lng']);
		}

		$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 .= ' Посмотреть на карте: https://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'] = 'Случайная точка на карте — это лучший способ узнать что-то новое! – wikipoints.ru';
			$og['site_name'] = App::$defaultTitle;
			$og['type'] = 'article';
			$og['url'] = 'https://wikipoints.ru/?point=random';
			$og['image'] = 'https://wikipoints.ru/img/logo.png';
		}

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

	static function actionLogout()
	{
		$referrer = (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'wikipoints.ru') !== FALSE) ? $_SERVER['HTTP_REFERER'] : '/';
		App::userLogout();
		App::redirect($referrer);
	}

	static function actionLogin()
	{
		$source = file_get_contents('https://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;
			}
		}

		$target = App::getBasedir().'public/img/avatars/'.$user->id.'.jpg';
		Image::createAvatar($uLoginUser['photo_big'], $target);

		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"/>');

		$url = $xml->addChild('url');
		$url->addChild('loc', 'https://wikipoints.ru/');
		$url->addChild('lastmod', date("Y-m-d"));
		$url->addChild('changefreq', "daily");
		$url->addChild('priority', "0.9");

		$articles = Article::model()->getAll(array('where'=>'`author` != 0 AND (`status` = "published" OR `status` = "system") ', 'order' => 'ID DESC', 'asArray' => true));
		foreach ($articles as $article) {
			$url = $xml->addChild('url');
			$url->addChild('loc', 'https://wikipoints.ru/article/' . $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', 'https://wikipoints.ru/point/' . $point['id']);
			$url->addChild('lastmod', date("Y-m-d", $point['dateEdit']));
			$url->addChild('changefreq', "weekly");
			$url->addChild('priority', "0.8");
		}

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

	static function actionRoute()
	{
		self::$layout = 'layouts/print.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,
		));
	}

	function actionShorturlroute()
	{
		if (!isset($_GET['elements']) || empty($_GET['elements'])) {
			App::error404();
		}

		$elements = (array)$_GET['elements'];

		$url = '/?route=[';
		foreach ($elements AS $key => $element) {
			if ($key != 0) {
				$url .= ',';
			}

			if (isset($element['id'])) {
				$url .= '"'.$element['id'].'"';
			}

			if (isset($element['latLng'])) {
				$url .= '"['.$element['latLng']['lat'].','.$element['latLng']['lng'].']"';
			}
		}
		$url .= ']';

		$shortUrl = ShortUrl::model()->getAll(array('where' => '`url` LIKE :url', 'limit' => 1), array('url' => $url));

		if (!$shortUrl || $shortUrl->isEmpty()) {
			$shortUrl = ShortUrl::addNew($url);
		}

		print 'https://wikipoints.ru/s/'.x62::encode($shortUrl->id);
	}
}
