<?php
include_once "../../../inc/start.php";
include_once "../../../inc/protect.php";
include_once "../../../modules_extra/demoview/base/config.php";

if (empty($_POST['phpaction'])) {
	log_error("Прямой вызов actions.php");
	exit(json_encode(array('status' => '2')));
}
if($conf->token == 1 && ($_SESSION['token'] != clean($_POST['token'],null))) {
	log_error("Неверный токен");
	exit(json_encode(array('status' => '2')));
}

if (isset($_POST['add_demoview'])) {
	$server = check($_POST['server'],"int");
	$nick = check($_POST['nick'],null);
	$img = check($_POST['img'],"var");
	$demo = check($_POST['demo'],"var");


	if (empty($server)) {
		exit (json_encode(array('status' => '2', 'input' => 'server', 'reply' => 'Заполните')));
	}
	if (empty($nick)) {
		exit (json_encode(array('status' => '2', 'input' => 'nick', 'reply' => 'Заполните')));
	}
	if (empty($img)) {
		$img = 0;
	}
	if (empty($demo)) {
		exit (json_encode(array('status' => '2', 'input' => 'demo', 'reply' => 'Заполните')));
	}

	$date = date("Y-m-d H:i:s");
	$STH = $pdo->prepare("INSERT INTO demoview (server,nick,img,demo,date,author) values (:server, :nick, :img, :demo, :date, :author)");
	if ($STH->execute(array( 'server' => $server, 'nick' => $nick, 'img' => $img, 'demo' => $demo, 'date' => $date, 'author' => $_SESSION['id'])) == '1') {
		$STH = $pdo->query("SELECT id FROM demoview WHERE date='$date' LIMIT 1"); $STH->setFetchMode(PDO::FETCH_OBJ);
		$row = $STH->fetch();

		sendmail('none', "Оставлена новая демо запись", "На администрируемом вами сайте \"".$site_name."\" оставлена новая демо запись.", $pdo, 1);
		exit (json_encode(array('status' => '1', 'id' => $row->id)));
	}

	exit (json_encode(array('status' => '2')));
}

if (isset($_POST['dell_demoview']) and is_worthy("o")) {
	$id = checkJs($_POST['id'],"int");
	
	if (empty($id)){
		exit(json_encode(array('status' => '2')));
	}

	$STH = $pdo->query("SELECT `id`, `server` FROM `demoview` WHERE id='$id' LIMIT 1"); $STH->setFetchMode(PDO::FETCH_OBJ);
	$row = $STH->fetch();
	
	if (empty($row->id)){
		exit(json_encode(array('status' => '2')));
	}
	if(!is_worthy_specifically("o", $row->server)) {
		exit(json_encode(array('status' => '2')));
	}

	$pdo->exec("DELETE FROM demoview WHERE id='$id' LIMIT 1");
	$pdo->exec("DELETE FROM demoview__comments WHERE demoview_id='$id'");
	exit (json_encode(array('status' => '1')));
}

if (isset($_POST['close_demoview']) and is_worthy("i")) {
	$id = checkJs($_POST['id'],"int");
	$action_type = checkJs($_POST['type'],"int");

	if ($action_type != '1' and $action_type != '2'){
		exit(json_encode(array('status' => '2')));
	}
	if (empty($id)){
		exit(json_encode(array('status' => '2')));
	}

	$STH = $pdo->query("SELECT `server` FROM `demoview` WHERE id='$id' LIMIT 1"); $STH->setFetchMode(PDO::FETCH_OBJ);
	$row = $STH->fetch();
	if (empty($row->server)){
		exit(json_encode(array('status' => '2')));
	}

	if(!is_worthy_specifically("i", $row->server)) {
		exit(json_encode(array('status' => '2')));
	}

	$STH = $pdo->prepare("UPDATE `demoview` SET `status`=:status, `closed`=:closed WHERE `id`='$id' LIMIT 1");
	if ($STH->execute(array( 'status' => $action_type, 'closed' => $_SESSION['id'])) == '1') {
		$action_type++;
		$STH = $pdo->query("SELECT `demoview`.`author`, `users`.`email`, `users`.`email_notice` FROM `demoview` LEFT JOIN `users` ON `users`.`id`=`demoview`.`author` WHERE `demoview`.`id`='$id' LIMIT 1"); $STH->setFetchMode(PDO::FETCH_OBJ);
		$row = $STH->fetch();
		
		incNotifications();
		send_noty($pdo, "Ваша демо запись <a href='../demoview/demo?id=".$id."'>#".$id."</a> просмотрена", $row->author, $action_type);

		if($row->email_notice == 1) {
			sendmail($row->email, "Ваша демо запись просомтрена", "Ваша демо запись (".$full_site_host."demoview/demo?id=".$id.") просмотрена", $pdo);
		}

		exit (json_encode(array('status' => '1', 'closed' => $_SESSION['id'], 'closed_a' => $_SESSION['login'])));
	} else {
		exit(json_encode(array('status' => '2')));
	}
}

if (isset($_POST['load_demoview_comments'])) {
	$id = checkJs($_POST['id'],"int");
	$i = 0;

	$tpl = new Template;
	$tpl->dir = '../../../templates/'.$conf->template.'/tpl';
	$tpl->result['content'] = '';
	$STH = $pdo->query("SELECT `demoview__comments`.*, `demoview`.`server`, `users`.`login`, `users`.`avatar`, `users`.`rights` FROM `demoview__comments` 
		LEFT JOIN `users` ON `demoview__comments`.`user_id` = `users`.`id` 
		LEFT JOIN `demoview` ON `demoview__comments`.`demoview_id` = `demoview`.`id` 
		WHERE `demoview__comments`.`demoview_id` = '$id' ORDER BY `demoview__comments`.`id` DESC"); $STH->setFetchMode(PDO::FETCH_OBJ);
	while($row = $STH->fetch()) {
		$tpl->load_template('/elements/comment.tpl');

		$gp = $users_groups[$row->rights];
		$date = expand_date($row->date,8);
		if (is_worthy_specifically("o", $row->server)){
			$dell = '<span onclick="dell_demoview_comment('.$row->id.');" tooltip="yes" data-placement="left" title="Удалить" class="m-icon icon-trash dell_message"></span>';
		} else {
			$dell = '';
		}
		$i++;

		$tpl->set("{id}", $row->id);
		$tpl->set("{user_id}", $row->user_id);
		$tpl->set("{login}", $row->login);
		$tpl->set("{avatar}", $row->avatar);
		$tpl->set("{text}", $row->text);
		$tpl->set("{dell}", $dell);
		$tpl->set("{date_full}", $date['full']);
		$tpl->set("{date_short}", $date['short']);
		$tpl->set("{gp_color}", $gp['color']);
		$tpl->set("{gp_name}", $gp['name']);
		$tpl->compile( 'content' );
		$tpl->clear();
	}
	if ($i == 0){
		echo '<span class="empty-element">Комментариев нет</span>';
	} else {
		$tpl->show($tpl->result['content']);
		$tpl->global_clear();
	}
	exit();
}

if (isset($_POST['send_demoview_comment'])) {
	$id = checkJs($_POST['id'],"int");

	if (empty($id)) {
		exit(json_encode(array('status' => '2')));
	}

	$text = HTMLPurifier()->purify($_POST['text']);
	$text = find_img_mp3($text, $id, 1);

	if (empty($text)) {
		exit (json_encode(array('status' => '2', 'input' => 'text', 'reply' => 'Заполните!')));
	}

	if (mb_strlen($text, 'UTF-8') > 10000) {
		exit (json_encode(array('status' => '2', 'input' => 'text', 'reply' => 'Слишком длинный контент.')));
	}

	$date = date("Y-m-d H:i:s");

	$STH = $pdo->query("SELECT `demoview`.`author`, `demoview`.`closed`, `users`.`email`, `users`.`email_notice` FROM `demoview` LEFT JOIN `users` ON `users`.`id`=`demoview`.`author` WHERE `demoview`.`id`='$id' LIMIT 1"); $STH->setFetchMode(PDO::FETCH_OBJ);
	$row = $STH->fetch();

	$STH = $pdo->prepare("INSERT INTO `demoview__comments` (`user_id`, `demoview_id`, `text`, `date`) values (:user_id, :demoview_id, :text, :date)");
	$STH->execute(array( 'user_id' => $_SESSION['id'], 'demoview_id' => $id, 'text' => $text, 'date' => $date ));
	if ($row->author != $_SESSION['id']){
		
		$STH = $pdo->prepare("UPDATE `demoview` SET `have_answer`=:have_answer WHERE `id`='$id' LIMIT 1");
		$STH->execute(array( 'have_answer' => '1' ));

		incNotifications();

		send_noty($pdo, "На вашу демо запись <a href='../demoview/demo?id=".$id."'>#".$id."</a> оставлен ответ", $row->author, 1);

		if($row->email_notice == 1) {
			sendmail($row->email, "Оставлен ответ на вашу демо запись", "На вашу демо запись (".$full_site_host."demoview/demo?id=".$id.") оставлен ответ", $pdo);
		}
	} else {
		if($row->closed == 0) {
			$STH = $pdo->prepare("UPDATE `demoview` SET `have_answer`=:have_answer WHERE `id`='$id' LIMIT 1");
			$STH->execute(array( 'have_answer' => '0' ));
		}
	}
	exit (json_encode(array('status' => '1')));
}

if (isset($_POST['dell_demoview_comment']) and is_worthy("o")) {
	$id = check($_POST['id'],"int");

	if (empty($id)){
		exit(json_encode(array('status' => '2')));
	}

	$STH = $pdo->prepare("SELECT `demoview`.`server` FROM `demoview__comments` 
		LEFT JOIN `demoview` ON `demoview__comments`.`demoview_id` = `demoview`.`id` 
		WHERE `demoview__comments`.`id` = :id LIMIT 1"); $STH->setFetchMode(PDO::FETCH_OBJ);
	$STH->execute(array( ':id' => $id ));
	$row = $STH->fetch();

	if (!is_worthy_specifically("o", $row->server)) {
		exit(json_encode(array('status' => '2')));
	}

	$pdo->exec("DELETE FROM `demoview__comments` WHERE `id`='$id' LIMIT 1");
	exit(json_encode(array('status' => '1')));
}
if (isset($_POST['add_demo_img'])) {
	$counter = check($_POST['counter'],"int");
	if (empty($counter) and $counter != 0){
		exit('<script>setTimeout(show_error, 500);</script>');
	}
	if ($counter >= 5){
		exit('<p class="text-danger">Загружено максимальное количество изображений</p><script>setTimeout(show_error, 500);</script>');
	}
	if (empty($_FILES['demo_img']['name'])) {
		exit('<script>show_input_error("demo_img", "", null);setTimeout(show_error, 500);</script>');
	} else {
		$path = '../../modules_extra/demoview/files/';
		$date = time();

		if (if_img($_FILES['demo_img']['name'])) {
			$source = $_FILES['demo_img']['tmp_name'];
			$demo_img = $path . $date . ".jpg";
			$target = '../'. $demo_img;
			if (!move_uploaded_file($source, $target)) {
				exit('<p class="text-danger">Ошибка загрузки файла!</p>');
			}
		} else {
			exit('<p class="text-danger">Изображение должено быть в формате JPG,GIF,BMP или PNG</p><script>show_input_error("ban_img", "", null);setTimeout(show_error, 500);</script>');
		}
		?>
			<script>
				$("#imgs").append('<a class="thumbnail" data-lightbox="1" href="<?php echo $demo_img; ?>"><img class="thumbnail-img" src="<?php echo $demo_img; ?>"></img></a>');
				var screens = $('#screens').val();
				$('#screens').val(screens+'<?php echo $demo_img; ?>;');
				var counter = $('#counter').val();
				counter++;
				$('#counter').val(counter);
				setTimeout(show_ok, 500);
			</script>
		<?php
	}
	exit();
}
?>