<?php
/*
 * JohnCMS NEXT Mobile Content Management System (http://johncms.com)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://johncms.com JohnCMS Project
 * @copyright   Copyright (C) JohnCMS Community
 * @license     GPL-3
 * Blogs By Aan Gabriel
 */

define('_IN_JOHNCMS', 1);

//$id = isset($_REQUEST['id']) ? abs(intval($_REQUEST['id'])) : 0;
//$act = isset($_GET['act']) ? trim($_GET['act']) : '';
//$mod = isset($_GET['mod']) ? trim($_GET['mod']) : '';
//$do = isset($_REQUEST['do']) ? trim($_REQUEST['do']) : false;


require('../system/bootstrap.php');
/** @var Psr\Container\ContainerInterface $container */
$container = App::getContainer();

/** @var PDO $db */
$db = $container->get(PDO::class);

/** @var Johncms\Api\UserInterface $systemUser */
$systemUser = $container->get(Johncms\Api\UserInterface::class);

/** @var Johncms\Api\ToolsInterface $tools */
$tools = $container->get(Johncms\Api\ToolsInterface::class);

/** @var Johncms\Api\ConfigInterface $config */
$config = $container->get(Johncms\Api\ConfigInterface::class);

 /** @var Johncms\Api\BbcodeInterface $bbcode */
$bbcode = $container->get(Johncms\Api\BbcodeInterface::class);


$headmod = 'view_blogs';


if(empty($_SESSION['error']))
	$_SESSION['error'] = '';
//Функция отображения рейтинга
function rating($id, $type = 0) {
	if(!$ids)
		return '<img class="ico" src="stars/stars_5.gif" alt="0" />';
	$total = $db->query("SELECT COUNT(*) FROM `blogs_rating` WHERE `news`='$id'")->fetchColumn(); 
	if($total) {
		$query = $db->query("SELECT `golos`, COUNT(*) as `count` FROM `blogs_rating` WHERE `news`='$id' GROUP BY `golos`");
		$array['plus'] = 0;
		$array['minus'] = 0;
		while (($row = $query->fetch()) !== false) {
			if(isset($row['golos']) && $row['golos'] == 1) $array['plus'] = $row['count'];
			else if(isset($row['golos']) && $row['golos'] == 2) $array['minus'] = $row['count'];
			else {
				$array['plus'] = 0;
				$array['minus'] = 0;
			}
		}
		if($array['plus'] > $array['minus']) {
			if($array['minus'] == 0) {
				if($array['plus'] == 1) $count = 60;
				else if($array['plus'] == 2) $count = 60;
				else if($array['plus'] == 3) $count = 60;
				else if($array['plus'] == 4) $count = 70;
				else if($array['plus'] == 5) $count = 70;
				else if($array['plus'] == 6) $count = 80;
				else if($array['plus'] == 7) $count = 80;
				else if($array['plus'] == 8) $count = 90;
				else if($array['plus'] == 9) $count = 90;
				else if($array['plus'] >= 10) $count = 100;
			} else {
				$count = round($array['minus'] / $array['plus'], 1) * 100;
				if($count == 0)	$count = 100;
				else $count = (100 - $count);
			}
		} else if($array['plus'] < $array['minus']) {
			if($array['plus'] == 0) {
				if($array['minus'] == 1) $count = 40;
				else if($array['minus'] == 2) $count = 40;
				else if($array['minus'] == 3) $count = 40;
				else if($array['minus'] == 4) $count = 30;
				else if($array['minus'] == 5) $count = 30;
				else if($array['minus'] == 6) $count = 20;
				else if($array['minus'] == 7) $count = 20;
				else if($array['minus'] == 8) $count = 10;
				else if($array['minus'] == 9) $count = 10;
				else if($array['minus'] >= 10) $count = 0;
			} else {
				$pr = (round($array['plus'] / $array['minus'], 1) * 100);
				$count = $pr;
			}
		} else
			$count = 50;
		$percent = $count;
		if($percent == 100)	$stars = 10;
		else if($percent < 100 && $percent >= 90) $stars = 9;
		else if($percent < 100 && $percent >= 90) $stars = 9;
		else if($percent < 90 && $percent >= 80) $stars = 8;
		else if($percent < 80 && $percent >= 70) $stars = 7;
		else if($percent < 70 && $percent >= 60) $stars = 6;
		else if($percent < 60 && $percent >= 50) $stars = 5;
		else if($percent < 50 && $percent >= 40) $stars = 4;
		else if($percent < 40 && $percent >= 30) $stars = 3;
		else if($percent < 30 && $percent >= 20) $stars = 2;
		else if($percent < 20 && $percent >= 10) $stars = 2;
		else if($percent < 10 && $percent > 0) $stars = 1;
		else if($percent == 0) $stars = 0;
		if($type == 0) return '<img class="ico" src="stars/stars_'.$stars.'.gif" alt="&bull;" />';
		else return $percent;
	} else return '<img class="ico" src="stars/stars_5.gif" alt="&bull;" />';
}


$id = intval($_GET['id']);
if($id) {
	$query = $db->query("SELECT `blogs`.*, `blogs_cat`.`name` as `catname`, `blogs_cat`.`id` as `catid` FROM `blogs` LEFT JOIN `blogs_cat` ON `blogs`.`refid`=`blogs_cat`.`id` WHERE `blogs`.`id`='$id'".($systemUser->rights < 7 ? " AND `blogs`.`time`<='" . time() . "'":"")." LIMIT 1;");
	if ($query->rowCount()) {
		//Показываем новость
		$res1 = $query->fetch();
		$textl =  'Blogs | ' . htmlentities($res1['name'], ENT_QUOTES, 'UTF-8');
		require_once('../system/head.php');
		include('bookmarking.php');
		echo '<div class="phdr">'.facebook().' '.twitter().'<h3><center>' . htmlentities($res1['name'], ENT_QUOTES, 'UTF-8') . '</center></h3></div>';
		echo '<div class="list1">';
		if (file_exists(ROOT_PATH . 'blogs/icon/news_' . $id . '.jpg'))
			echo '<img style="float: left; margin: 5px 6px 2px 2px; border: 0px;" src="icon/news_' . $id . '.jpg" alt=""/>  ';
		$text = $tools->checkout($res1['text'], 1, 1);

		$text = $tools->smilies($text);
		echo $text;
		echo '<div style="clear:both;"></div></div>';
		//Обрабатываем голосование
		if(isset($_POST['plus_x']) || isset($_POST['plus_y'])) {


			if($res1['user_id'] == $systemUser->id) {
				$_SESSION['error'] = '<div class="list1 red">You can not rate your own blog!</div>';
			} else {
				$plus = $db->query("SELECT COUNT(*) FROM `blogs_rating` WHERE `news`='$id' AND `user_id`='$systemUser->id' LIMIT 1;")->fetchColumn();
				if($plus) {
					$_SESSION['error'] = '<div class="list1 red">Rating wass accepted!</div>';
				} else {
					$db->exec("INSERT INTO `blogs_rating` SET
					`news`='$id',
					`user_id`='$systemUser->id', `golos`='1';");
					$_SESSION['error'] = '<div class="list1 green">Rating accepted!</div>';
				}
			}
			header('Location: view.php?id=' . $id);
			exit;
		} else if(isset($_POST['minus_x']) || isset($_POST['minus_y'])) {
			if($res1['user_id'] == $systemUser->id) {
				$_SESSION['error'] = '<div class="list1 red">You can not rate your own blog!</div>';
			} else {
				$plus = $db->query("SELECT COUNT(*) FROM `blogs_rating` WHERE `news`='$id' AND `user_id`='$systemUser->id' LIMIT 1;")->fetchColumn();
				if($plus) {
					$_SESSION['error'] = '<div class="list1 red">Rating wass accepted!</div>';
				} else {
					$db->exec("INSERT INTO `blogs_rating` SET
					`news`='$id',
					`user_id`='$systemUser->id', `golos`='2';");
					$_SESSION['error'] = '<div class="list1 green">Rating accepted!</div>';
				}
			}
			header('Location: view.php?id=' . $id);
			exit;
		}
		//Сообщение об оставленном голосе
		echo $_SESSION['error'];
		//Выводим автора новости
		$us = $db->query("SELECT `id`, `name` FROM `users` WHERE `id` = '{$res1['user_id']}'");
		if ($us->rowCount()) {
			$rowuse = $us->fetch();
			$name_use = $systemUser->id ? '<a href="../profile/?id=' . $rowuse['id'] . '">' . $rowuse['name'] . '</a>' : $rowuse['name'];
		} else {
			$name_use = 'Guest';
		}
		//
		$db->exec("UPDATE `blogs` SET  `count` = (`count`+1) WHERE `id` = '$id'");
	
		echo '<div class="list2"><table width="100%" cellpadding="0" cellspacing="0"><tr>' .
'<td width="auto"><span class="underline">Rating:</span> ' . rating($id) . '</td><td width="auto" align="right">
		'.($systemUser->id ? '<form action="view.php?id=' . $id . '" method="post"><div>
		<input style="width: 32; height: 32; cursor:none; border: 0px; padding: 0;padding-top: 2px; margin: 0;" type="image" name="plus" value="15" src="img/like.gif" alt="like"/><input class="rate" style="cursor:none; border: 0px; margin: 0; padding: 0;padding-top: 2px;" type="image" src="img/unlike.gif" name="minus" alt="-"/>
		</div></form>':'<img class="ico" src="img/like.gif" style="width: 32; height: 32;" alt="+" /><img class="ico" src="img/unlike.gif" style="width: 32; height: 32;" alt="-" /><br />').'
		</td></tr></table></div><div class="gmenu">
		Writed By: ' . $name_use . '<br />
		Showed: '.$res1['count'].'<br />
		On: ' . date('d.m.o / H:i', $res1['time'] + $sdvigclock * 3600) . '<br />
		'.($res1['time'] > time()?'<div class="func">Time left to show: ' . timer($res1['time'] - time()) . '</div>':'').'
		<a href="comments.php?id=' . $id . '">Comments</a> (' . $db->query("SELECT COUNT(*) FROM `blogs_comments` WHERE `refid`='$id'")->fetchColumn() . ')
		</div>
		' . ($systemUser->rights >= 7 ? '<div class="menu"><div class="func">
		<a href="manage.php?act=newsedit&id='.$id.'">Edit</a><br />
		<a href="manage.php?act=delnews&id=' . $id . '">Delete</a><br />
		</div></div>':'') . '
		<div class="bmenu">Category: <a href="index.php?id=' . $res1['catid'] . '">' . htmlentities($res1['catname'], ENT_QUOTES, 'UTF-8') . '</a></div>';
       if ($systemUser->isValid()) {
	    echo $_SESSION['error'] . '<div class="gmenu">
				<form action="comments.php?id=' . $id . '" method="post"  enctype="multipart/form-data" name="form"><div>
				<b>Comment:</b><br/>';
            echo $bbcode->buttons('form', 'msg');
            echo '<textarea rows="' . $systemUser->getConfig()->fieldHeight . '" name="msg"></textarea>
				<br /><span style="font-size: x-small;">Min 2. Max 5000 character</span><br />
				<input type="submit" name="submit" value="Send"/>
				</div></form>
				</div>';
       }
	} else {
		$textl = 'Blogs';
		require_once('../system/head.php');
		echo $tools->displayError('Blogs Not Founds!');
	}
} else {
	$textl = 'Blogs';
	require_once('../system/head.php');
	 echo $tools->displayError('Blogs Not Founds!');
}
echo '<div class="phdr"><a href="comments.php?id=' . $id . '">Comment:</a></div>';
			$total = $db->query("SELECT COUNT(*) FROM `blogs_comments` WHERE `refid`='$id';")->fetchColumn();
			if($total) {
				if ($total > $kmess)
					echo '<div class="topmenu">' . $tools->displayPagination('comments.php?id=' . $id . '&amp;', $start, $total, $kmess) . '</div>';
				$i = 1;
				$req = $db->query("SELECT `blogs_comments`.*, `blogs_comments`.`time` as `mtime`, `blogs_comments`.`id` as `mid`, `users`.* FROM `blogs_comments` LEFT JOIN `users` ON `blogs_comments`.`user_id`=`users`.`id` WHERE `blogs_comments`.`refid`='$id' ORDER BY `blogs_comments`.`time` DESC LIMIT "
						. $start . "," . $kmess);
				while (($row = $req->fetch()) !== false) {
					echo $i % 2 ? '<div class="list1">' : '<div class="list2">';
					$post = $row['text'];
					$post = $tools->checkout($post, 1, 1);
					$post = $tools->smilies($post, $row['rights'] >= 1 ? 1 : 0);
                if (!empty($row['reply'])) {
                    // Ответ Администрации
                    $otvet = $tools->checkout($row['reply'], 1, 1);
                    $otvet = $tools->smilies($otvet, 1);
                    $post .= '<div class="reply"><b>' . $row['admin'] . '</b>: (' . $tools->displayDate($row['otime']) . ')<br>' . $otvet . '</div>';
                }
					if($systemUser->rights >= 7) $subtext = '<a href="comments.php?act=replay&amp;id=' . $id . '&amp;com=' . $row['mid'] . '">Replay</a> | <a href="comments.php?act=delete&amp;id=' . $id . '&amp;com=' . $row['mid'] . '">Delete</a>';
					else $subtext = '';
					$text = ' <span class="gray">(' . $tools->displayDate($row['mtime']) . ')</span>';
					$arg = array(
						'header' => $text,
						'body' => $post,
						'sub' => $subtext
					);
					echo $tools->displayUser($row, $arg);
					echo '</div>';
					++$i;
				}
				echo '<div class="phdr">Total: ' . $total . '</div>';
				if ($total > $kmess) {
					echo '<div class="topmenu">' . $tools->displayPagination('comments.php?id=' . $id . '&amp;', $start, $total, $kmess) . '</div>';
					echo '<p><form action="index.php" method="get">
					<input type="hidden" name="act" value="comments"/>
					<input type="hidden" name="id" value="' . $id . '"/>
					<input type="text" name="page" size="2"/>
					<input type="submit" value="To page &gt;&gt;"/></form></p>';
				}
				}
				else {
				echo '<div class="rmenu">Comment its empty!</div>';
			}
				echo '<div class="bmenu"><a href="index.php">Back to Blogs</a></div>';
unset($_SESSION['error']);
require('../system/end.php');