<?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);


$act = isset($_GET['act']) ? trim($_GET['act']) : '';
$id = isset($_GET['id']) ? abs(intval($_GET['id'])) : 0;
$com = isset($_REQUEST) ? abs(intval($_REQUEST['com'])) : '';

 
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 = 'comment';


if (!$systemUser->isValid()) {
   require_once('../system/head.php');
   echo $tools->displayError('Login Before Write the Blogs!');
   require('../system/end.php');
   exit;
}


if($id) {
	$query = $db->query("SELECT * FROM `blogs` WHERE `id`='$id' LIMIT 1;");
	if ($query->rowCount()) {
		$res1 = $query->fetch();
		if(empty($_SESSION['error']))
		$_SESSION['error'] = '';
		$textl =  'Blogs | Comments Blogs "' . htmlentities($res1['name'], ENT_QUOTES, 'UTF-8') . '"';
		require_once('../system/head.php');
		echo '<div class="phdr"><h3>Comment on Blogs "<a href="'.$config['homeurl'].'/blogs/'.$tools->Rewrite($res1['name']) . '_' . $id . '.html">' . htmlentities($res1['name'], ENT_QUOTES, 'UTF-8') . '</a>"</h3></div>';
		
		
		
		switch($act) {
			case 'replay':
				if($systemUser->rights >= 7) {
					$q = $db->query("SELECT * FROM `blogs_comments` WHERE `id`='$com' LIMIT 1;");
					if ($q->rowCount()) {
						$r = $q->fetch();
						if(isset($_POST['submit'])) {
							$msg = isset($_POST['msg']) ? trim($_POST['msg']) : '';
							$error = [];
							if(!$msg) {
								$error[] = 'Comment empty!';
							} elseif (mb_strlen($msg) < 4 || mb_strlen($msg) > 5000) {
								$error[] =  'Comment verry short or long!';
                       }
                       $flood = $tools->antiflood();
                       if ($flood) {
                          $error[] = sprintf(_t('You cannot add the message so often. Please, wait %d seconds.'), $flood);
                       } 


						
							if(empty($error)) {

                $db->exec("UPDATE `blogs_comments` SET
                    `admin` = '" . $systemUser->name . "',
                    `reply` = " . $db->quote($msg) . ",
                    `otime` = '" . time() . "'
                    WHERE `id` = '$com'
                ");
								$db->exec("UPDATE `users` SET
									`lastpost` = '" . time() . "'
									WHERE `id` = '$systemUser->id'
								");
								$_SESSION['error'] = '';
							} else {
								$_SESSION['error'] = '<div class="rmenu">' . implode('<br />', $error) . '</div>';
							}
							header('Location: comments.php?id=' . $id);
							exit;
						}
						echo $_SESSION['error'] . '<div class="gmenu">
						<form action="comments.php?act=replay&amp;id=' . $id . '&amp;com=' . $com . '" method="post"  enctype="multipart/form-data" name="form"><div>
						<b>Reply:</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="Answare"/>
						</div></form>
						</div>';
					} else {
						echo $tools->displayError('Message not found!');
					}
				} else {
					header('Location: ../?err');
					exit;
				}
			break;
			
			case 'delete':
				if($systemUser->rights >= 7) {
					$q = $db->query("SELECT * FROM `blogs_comments` WHERE `id`='$com' LIMIT 1;");
					if ($q->rowCount()) {
						if(isset($_POST['submit'])) {
							$db->exec("DELETE FROM `blogs_comments` WHERE `id`='$com'");
							$_SESSION['error'] = '<div class="gmenu">The comment deleted!</div>';
							header('Location: comments.php?id=' . $id);
							exit;
						}
						echo $_SESSION['error'] . '<div class="rmenu">
						<form action="comments.php?act=delete&amp;id=' . $id . '&amp;com=' . $com . '" method="post"  enctype="multipart/form-data"><div>
						Remove this comment?<br />
						<input type="submit" name="submit" value="Delete"/>
						</div></form>
						</div>';
					} else {
						echo $tools->displayError('Comment not found maybe wass deleted!');
					}
				} else {
					header('Location: ../?err');
					exit;
				}
			break;
			
			default:
			if($systemUser->isValid() && empty($systemUser->ban[1]) ) {
				if(isset($_POST['submit'])) {
                $msg = isset($_POST['msg']) ? mb_substr(trim($_POST['msg']), 0, 5000) : '';
					//$text = isset($_POST['text']) ? trim($_POST['text']) : '';
					$error = [];
					if(!$msg) {
						$error[] = 'Comment empty!';
					} elseif (mb_strlen($msg) < 4 || mb_strlen($msg) > 5000) {
						$error[] = 'The comment verry short or long!';
                }
                $flood = $tools->antiflood();
                if ($flood) {
                  $error[] = sprintf(_t('You cannot add the message so often. Please, wait %d seconds.'), $flood);
                 } 
					
					if(empty($error)) {
                $db->prepare('
                 INSERT INTO `blogs_comments` SET
                 `refid` = ?,
                 `time` = ?,
                 `user_id` = ?,
                 `text` = ?
                ')->execute([
                 $id,        
                 time(),
                 $systemUser->id,
                 $msg,
                ]);


				  $db->exec("UPDATE `blogs` SET `hit_kom` = `hit_kom` + 1 WHERE `id` = '$id'");
				  $db->exec("UPDATE `users` SET
							`lastpost` = '" . time() . "'
							WHERE `id` = '$systemUser->id'
						");

						$_SESSION['error'] = '<div class="gmenu">Comment success</div>';
					} else {
						$_SESSION['error'] = '<div class="rmenu">' . implode('<br />', $error) . '</div>';
					}
					header('Location: view.php?id=' . $id);
					exit;
				}
				echo $_SESSION['error'] . '<div class="gmenu">
				<form action="comments.php?id=' . $id . '" method="post"  enctype="multipart/form-data" name="form"><div>
				<b>Message:</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>';
			}
			echo '<div class="phdr"><h3>Comments</h3></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);
             for ($i = 0; $row = $req->fetch(); ++$i) {
				//while (($row = $req->fetch()) !== false) {
					echo $i % 2 ? '<div class="list1">' : '<div class="list2">';
                 //echo $row['text'];
					$post = $row['text'];
					$post = $tools->checkout($post, 1, 1);
                 $post = $tools->smilies($post, $row['rights'] >= 1 ? 1 : 0);
                 //echo $post;					
				   //$post = $tools->smilies($post, 1);




                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($row['reply'])
						$post .= '<div class="reply">' . $tools->checkout($row['reply'], 1, 1) . '</div>';
*/
					if ($systemUser->rights >= 7) {
                    $subtext = '<a href="comments.php?act=replay&amp;id=' . $id . '&amp;com=' . $row['mid'] . '">Reply</a> | <a href="comments.php?act=delete&amp;id=' . $id . '&amp;com=' . $row['mid'] . '">Remove</a>';
                 } else {
                   $subtext = '';
                 }
					$texts = ' <span class="gray">(' . $tools->displayDate($row['mtime']) . ')</span>';
					$arg = [
						'header' => $texts,
						'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="comments.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 empty, be the first!</div>';
			}
		}
		echo '<div class="bmenu"><a href="'.$config['homeurl'].'/blogs/'.$tools->Rewrite($res1['name']) . '_' . $res1['id'] . '.html">Back</a></div>';
	} else {
		$textl = 'Blogs';
		require_once('../system/head.php');
		echo $tools->displayError('Blogs not found!');
	}
} else {
	$textl = 'Blogs';
	require_once('../system/head.php');
}
	require_once('../system/end.php');