<?php
 
include_once('../../../../core/includes/master.inc.php');
// set up the logs
log::setContext('plugin_comments_comment_rating');

$pluginConfig	= pluginHelper::pluginSpecificConfiguration('comments');
$pluginSettings = json_decode($pluginConfig['data']['plugin_settings'], true);
if ($pluginSettings)
{
    $commentRatings       = $pluginSettings['commentRatings'];
    $maxLikes             = $pluginSettings['maxLikes'];
}
$comId		  = (int)$_REQUEST['comId'];
$userId		  = (int)$Auth->id;
$ipAddress	  = coreFunctions::getUsersIPAddress();

// prepare result
$result = array();
$result['error'] = false;
$result['msg']   = '';

// validate submission
if (_CONFIG_DEMO_MODE == true)
{
    $result['error'] = true;
    $result['msg']   = 'Demo Mode';
}
if($commentRatings == 0)
{
    $result['error'] = true;
    $result['msg']   = '';
}
//check if the user has liked the comment already
$hasLiked = $db->getRow("SELECT id FROM plugin_comments_likes WHERE likedBy = ".(int)$userId." AND comId = ".(int)$comId." LIMIT 1");
if($hasLiked)
{
    $result['error'] = true;
    $result['msg']   = 'Already liked this comment.';
}
// Count the number of reports a user has made
$numLikes = $db->getValue("SELECT COUNT(id) FROM plugin_comments_likes WHERE likedBy = '".(int)$userId."' AND likeDate BETWEEN DATE_SUB(NOW(), INTERVAL 1 DAY) AND NOW()");
if($maxLikes != 0)
{
    if($numLikes > $maxLikes)
    {
        $result['error'] = true;
        $result['msg']   = 'Max Daily Limit Reached';
    }
}
if ($result['error'] == false)
{
	$db->query("INSERT INTO plugin_comments_likes (comId, likedBy, likeDate, ipAddress) VALUES ('".(int)$comId."', '".(int)$userId."', NOW(), ".$db->quote($ipAddress).")");
    $db->query("UPDATE plugin_comments SET rating = rating + 1 WHERE id = '".(int)$comId."'");
	$rating = $db->getValue("SELECT rating FROM plugin_comments WHERE id = '".(int)$comId."'");
	$result['error'] = false;
	$result['msg']   = $rating;  
}

echo json_encode($result);
exit;