<?php

$file 			= $params['file'];
$Auth 			= Auth::getAuth();
$db   			= Database::getDatabase();
$pluginConfig	= pluginHelper::pluginSpecificConfiguration('comments');
$pluginSettings = json_decode($pluginConfig['data']['plugin_settings'], true);
if ($pluginSettings)
{
	$plugin_enabled	      = $pluginConfig['data']['plugin_enabled'];
	$plugin_folder	      = $pluginConfig['data']['folder_name'];
	$commentsPerPage      = $pluginSettings['commentsPerPage'];
    $autoApprove          = $pluginSettings['autoApprove'];
    $enableCaptcha        = $pluginSettings['enableCaptcha'];
    $disableExternalLinks = $pluginSettings['disableExternalLinks'];
    $commentRatings       = $pluginSettings['commentRatings'];
    $maxReports           = $pluginSettings['maxReports'];
    $maxLikes             = $pluginSettings['maxLikes'];
}
$pluginObj  = pluginHelper::getInstance('comments');

// Pagination
$rows       = $db->getValue("SELECT COUNT(id) FROM plugin_comments WHERE status = 'active' AND fileId = ".(int)$file->id);
$totalpages = ceil($rows / $commentsPerPage);
$startPage  = 1;
$limit      = 'LIMIT '.($startPage - 1) * (int)$commentsPerPage .', '. (int)$commentsPerPage;

// only logged in users can like comments
$ratingComArr = array();
if($Auth->id >= 1)
{
    $ratings  = $db->getRows("SELECT comId FROM plugin_comments_likes WHERE likedBy = ".(int)$Auth->id);
    foreach($ratings AS $rating)
    {
        $ratingComArr[] = $rating['comId'];
    }
}

// only logged in users can report
$reportComArr = array();
if($Auth->id >= 1)
{
    $reports  = $db->getRows("SELECT comId FROM plugin_comments_reports WHERE reportedBy = ".(int)$Auth->id);
    foreach($reports AS $report)
    {
        $reportComArr[] = $report['comId'];
    }
}
$comments = $db->getRows("SELECT plugin_comments.*, users.username FROM plugin_comments LEFT OUTER JOIN users ON plugin_comments.userId = users.id WHERE plugin_comments.fileId = ".(int)$file->id." AND plugin_comments.status = 'active' ORDER BY plugin_comments.id ".$limit);
$pageTotal = COUNT($comments);

$userAllowed = false;
if(($Auth->level_id == 0) && ($pluginSettings['enabled_non_user'] == 1))
{
	$userAllowed = true;
}
elseif(($Auth->level_id == 1) && ($pluginSettings['enabled_free_user'] == 1))
{
	$userAllowed   = true;
}
elseif(($Auth->level_id >= 2) && ($pluginSettings['enabled_paid_user'] == 1))
{
	$userAllowed   = true;
}
if($userAllowed === true)
{
	$canReply = true;
}

?>
<style type="text/css">
.notification {display: block; padding: 1.3em 35px; margin-bottom: 1em}
.notification.undone {border: 1px solid #c88383; background: url(../images/notifications/cross.png) no-repeat 10px center #fabbbb; color: #882626}
.notification.done {border: 1px solid #90b96b; background: url(../images/notifications/tick.png) no-repeat 10px center #c2ee9b; color: #345f0e}
.notification.information {border: 1px solid #7ea2bf; background: url(../images/notifications/information-balloon.png) no-repeat 10px center #b6d9f4; color: #1e4f74}
.notification.setting {border: 1px solid #b7b7b7; background: url(../images/notifications/gear.png) no-repeat 10px center #e2e2e2; color: #454545}
.notification.warning {border: 1px solid #c2c193; background: url(../images/notifications/exclamation.png) no-repeat 10px center #f1efb1; color: #6c6913}
</style>
<script>
function reportComment(comId)
{
	$.ajax({
		type: "POST",
		url: "<?php echo PLUGIN_WEB_ROOT; ?>/comments/includes/ajax/_report_comment.ajax.php",
		data: { comId: comId, maxReports: <?php echo $maxReports; ?> },
		dataType: 'json',
		success: function(json) {
			if(json.error == false)
			{
				$('.reported' + comId).show();
				$('.report' + comId).hide();
                alert('<?php echo t('plugin_comments_comment_reported_popup', 'Comment successfully reported.'); ?>');
			}
            else
            {
                alert(json.msg);
            }
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			showError(XMLHttpRequest.responseText);
		}
	});
}

function likeComment(comId)
{
	$.ajax({
		type: "POST",
		url: "<?php echo PLUGIN_WEB_ROOT; ?>/comments/includes/ajax/_like_comment.ajax.php",
		data: { comId: comId },
		dataType: 'json',
		success: function(json) {
			if(json.error == false)
			{
				$('#totalLikes' + comId).html('('+json.msg+')');       
			}
            else
            {
                alert(json.msg);
            }
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			showError(XMLHttpRequest.responseText);
		}
	});
}

function postNewComment()
{
	commentVal = $('#comment').val();
	captchaVal = null;
	if($('#g-recaptcha-response').length != 0)
	{
		captchaVal = $('#g-recaptcha-response').val();
	}
	$.ajax({
		type: "POST",
		url: "<?php echo PLUGIN_WEB_ROOT; ?>/comments/includes/ajax/_post_comment.ajax.php",
		data: { comment: commentVal, captcha: captchaVal, fileId: <?php echo (int)$file->id; ?> },
		dataType: 'json',
		success: function(json) {
			if(json.error == true)
			{
			   commentError(json.msg);                   
			}
			else
			{
				commentSuccess(json.msg);
				$('#postComment').hide();
				$('.submitComment').hide();
				$("#comment").val('');
				loadComments(<?php echo (int)$file->id; ?>, 1);
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			showError(XMLHttpRequest.responseText);
		}
	});
}

function loadComments(startPage, isAdd)
{
	if(typeof(isAdd) == 'undefined')
	{
		isAdd = 0;
	}
	
	$.ajax({
		type: "POST",
		url: "<?php echo PLUGIN_WEB_ROOT; ?>/comments/includes/ajax/_comments.ajax.php",
		data: { fileId: <?php echo (int)$file->id; ?>, startPage: startPage, isAdd: isAdd },
		dataType: 'json',
		success: function(json) {
			if(json.error == false)
			{
				$('.comments-container').html(json.html);
				if(json.is_add == 1)
				{
					$(".comments-container .last-comment").hide().fadeIn();
					$('html, body').animate({
						scrollTop: $(".comments-container .last-comment").offset().top
					}, 500);
				}
				else
				{
					$('#notificationHeader').hide();
					$(".comments-container").hide().fadeIn();
					scrollToComments();
				}
			}
            else
            {
                alert(json.msg);
            }
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			showError(XMLHttpRequest.responseText);
		}
	});
}

function scrollToComments()
{
	$('html, body').animate({
		scrollTop: $(".comments-title").offset().top
	}, 500);
}

function commentError(msg, containerId)
{
	$('#notificationHeader').hide().html('<ul class="alert alert-danger"><li>'+msg+'</li></ul>').show();
	commentNotificationEvents();
	$('html, body').animate({
		scrollTop: $("#notificationHeader").offset().top
	}, 500);
}

function commentSuccess(msg, containerId)
{
	$('#notificationHeader').hide().html('<ul class="alert alert-success"><li>'+msg+'</li></ul>').show();
	commentNotificationEvents();
	$('html, body').animate({
		scrollTop: $("#notificationHeader").offset().top
	}, 500);
}

function commentNotificationEvents()
{
	$(".notification").click(function() {
		$(this).fadeOut("slow");
	});
}

function respondComment(original)
{
	original = original.replace(/<blockquote>/gi, "");
	original = original.replace(/<\/blockquote>/gi, "");
	$('#comment').val($('#comment').val()+'[quote]'+original+'[/quote]'+"\n");
	$('#comment').focus();
	$('html, body').animate({
        scrollTop: $("#comment").offset().top
    }, 500);
}
</script>


<div class="image-section-title comments-title">
	<?php echo t("plugin_comments_comments_title_total", "Comments ([[[TOTAL_COMMENTS]]])", array('TOTAL_COMMENTS' => (int)$rows)); ?>
</div>

<ul class="comments">
	<div class="comments-container">
		<?php
		foreach ($comments AS $k=>$com)
		{
			echo $pluginObj->outputCommentBootstrap($com, $Auth, $reportComArr, $ratingComArr, ($pageTotal==($k+1)));
		}
		
		if($rows > 0)
		{
			?>
			<div class="paging-wrapper">
				<?php echo $pluginObj->outputAjaxPaging($startPage, $totalpages); ?>
			</div>
			<?php
		}
		?>
	</div>
	
	<?php
	if($canReply == true)
	{
	?>
    <li class="comment-form">
        <div class="user-comment-thumb"> <img src="<?php echo WEB_ROOT; ?>/page/view_avatar.php?id=<?php echo (int)$Auth->id; ?>&width=40&height=40" alt="" class="img-circle" width="40"> </div>
        <div class="user-comment-content"> <textarea name="comment" id="comment" class="form-control autogrow" placeholder="Write a comment..." style="overflow: hidden; word-wrap: break-word; resize: horizontal; height: 72px; margin-left: 0px; margin-right: 0px;"></textarea> <button class="btn" onClick="postNewComment(); return false;"><i class="entypo-chat"></i></button>
		<?php if($enableCaptcha == 1 && $Auth->level_id == 0): ?>
			<div style="margin-top: 8px;"><?php echo coreFunctions::outputCaptcha(); ?></div>
		<?php endif; ?>
		</div>
    </li>
	<?php
	}
	elseif($canReply == false)
	{
		echo $pluginObj->userErrorReporting($pluginSettings['enabled_non_user'], $pluginSettings['enabled_free_user'], $pluginSettings['enabled_paid_user']);
	}
	?>
	<div class="notificationHeader alert" id="notificationHeader" style="display: none;"></div>
</ul>
