<?php

class CommentsController extends Controller
{

	static function actionAdd()
	{
		if (!App::$user ||
				!isset($_POST['parentType']) ||
				!isset($_POST['parentId']) ||
				!isset($_POST['answerTo']) ||
				!isset($_POST['text'])) {
			App::error404();
		}

		if (trim($_POST['text']) == '') {
			App::redirect('/' . $_POST['parentType'] . '/' . $_POST['parentId']);
		}

		$text = str_replace(array('<', '>'), array('&lt;', '&gt;'), $_POST['text']);

		$html = strip_tags($_POST['text']);
		$html = str_replace(array('<', '>', "'"), array('&lt;', '&gt;', '&prime;'), $html);
		$html = Markdown::liteProcessing($html);
		$html = nl2br($html);

		$comment = new Comment(array(
			'userId' => App::$user->id,
			'parentType' => ($_POST['parentType'] == 'article') ? 'article' : 'point',
			'parentId' => (int) $_POST['parentId'],
			'answerTo' => (int) $_POST['answerTo'],
			'addDate' => time(),
			'text' => $text,
			'html' => $html,
		));
		$comment->save();

		if ($_POST['parentType'] == 'article') {
			$ownerId = Article::model()->getByPK((int) $_POST['parentId'])->author;
		} else {
			$ownerId = Point::model()->getByPK((int) $_POST['parentId'])->author;
		}

		// Оповещение автору статьи или точки
		if ($ownerId != App::$user->id) {
			Notifications::model()->add(array(
				'userId' => $ownerId,
				'fromUserId' => App::$user->id,
				'objectId' => $comment->id,
				'type' => ($_POST['parentType'] == 'article') ? Notifications::typeNewCommentArticle : Notifications::typeNewCommentPoint,
				'date' => time(),
			));
		}

		// Оповещение тому, на чей комментарий отвечают
		if (intval($_POST['answerTo']) > 0) {
			$parentComment = Comment::model()->getByPK(intval($_POST['answerTo']));
			if ($parentComment->userId != App::$user->id) {
				Notifications::model()->add(array(
					'userId' => $parentComment->userId,
					'fromUserId' => App::$user->id,
					'objectId' => $comment->id,
					'type' => Notifications::typeReply,
					'date' => time(),
				));
			}
		}

//		SMS::send('Новый комментарий от '.App::$user->nick, '79046106141');
		$url = '/' . $_POST['parentType'] . '/' . $_POST['parentId'] . '#comment' . $comment->id;
		Alarmer::send('Новый комментарий от ' . App::$user->nick . ' Прочитать: https://wikipoints.ru' . $url);

		App::redirect($url);
	}

	static function actionDel()
	{
		if (!App::$user || !(int)App::getParam('id')) {
			App::error404();
		}

		$id = (int)App::getParam('id');
		$comment = Comment::model()->getByPK($id);

		if($comment->id && $comment->userId == App::$user->id) {
			$comment->delete($id);
		}

		App::redirect('/'.$comment->parentType.'/'.$comment->parentId);
	}
}
