<?php 
require_once 'inc/mysqli.php';

$check = $db->query("SELECT * FROM `rating` WHERE `ip` = ?s and `file_id` = ?i", md5($_SERVER['REMOTE_ADDR']), $_POST['id']);
if($db->numRows($check) > 0){
	$data['msg'] = 'Вы уже голосовали.';
	$data['status'] = 'ERR';
}else{
	
	if($_POST['val'] > 5 or $_POST['val'] < 0.1){
		$data['msg'] = 'Ошибка.';
		$data['status'] = 'ERR';
	}else{
		$check_file = $db->query("SELECT * FROM `files` WHERE `id` = ?i", $_POST['id']);
		if($db->numRows($check_file) == 0){
			$data['msg'] = 'Ошибка.';
			$data['status'] = 'ERR';
		}else{
			$file  = $db->getRow("SELECT `rating`,`golos` FROM `files` WHERE `id` = ?i", $_POST['id']);
			
			$rating = (($file['rating']*$file['golos']+floatval($_POST['score']))/($file['golos']+1));
			
			if($rating > 5){
				$rating = 5;
			}
			
			$db->query("INSERT INTO `rating` SET `ip` = ?s, `file_id` = ?i, `time` = ?i", md5($_SERVER['REMOTE_ADDR']), $_POST['id'], time());
			$db->query("UPDATE `files` SET `rating` = ?s, `golos` = `golos` +1 WHERE `id` = ?i", $rating, $_POST['id']);
			$data['msg'] = 'Голос учтен.';
			$data['status'] = 'OK';	
		}
	}
	
}

echo json_encode($data);
?>