<?php
include '../db/db.php';
session_start();

if(isset($_SESSION['userID'])) {
	$log = htmlspecialchars(strip_tags(trim($_SESSION['userID'])), ENT_QUOTES, 'UTF-8');
} else {
	$log = '';
}

if (empty($log)) {     
	$redirectUrl = "../";
	echo "<script type=\"text/javascript\">";
	echo "window.location.href = '$redirectUrl'";
	echo "</script>";
	 
} else {
	$sqlu = "SELECT id FROM user_acc_tbl WHERE userID='$log' and access=1 and val=1";
	$stmtu = mysqli_query($conn, $sqlu);
	$countu = mysqli_num_rows($stmtu);
	
	if($countu == 1) {
		$rowu = mysqli_fetch_assoc($stmtu);
		$uid = $rowu['id'];
		
		/*************************** Reject ***************************/
		
	    if (array_key_exists('reject_review', $_POST)) {
			$id = htmlspecialchars(strip_tags(trim($_POST['id'])), ENT_QUOTES, 'UTF-8');
			$sql = "UPDATE cus_review SET accept=2 WHERE id = '$id'";
			$stmt_log = mysqli_query($conn, $sql);
			
			if( $stmt_log === false ) {
				echo json_encode(array("msgType" => 2, "msg" => "Error"));
			
			} else {
				echo json_encode(array("msgType" => 1, "msg" => "Success"));
			}
	    }
		
		/*************************** Accept ***************************/
		
	    if (array_key_exists('accept_review', $_POST)) {
			$id = htmlspecialchars(strip_tags(trim($_POST['id'])), ENT_QUOTES, 'UTF-8');
			$itm_id = htmlspecialchars(strip_tags(trim($_POST['bk_id'])), ENT_QUOTES, 'UTF-8');
			
			if(empty($id) || empty($itm_id)) {
				echo json_encode(array("msgType" => 3, "msg" => "Empty"));
				
			} else {
				$sql = "UPDATE cus_review SET accept=1 WHERE id = '$id'";
				$stmt_log = mysqli_query($conn, $sql);
				
				if( $stmt_log === false ) {
					echo json_encode(array("msgType" => 2, "msg" => "Error"));
				
				} else {
					$sql_ratings = mysqli_query($conn, "SELECT SUM(review) AS tot FROM cus_review WHERE item_id = '$itm_id' AND accept=1");
					$row_ratings = mysqli_fetch_array($sql_ratings);
					$sum = $row_ratings['tot'];
					
					if($sum == NULL) {
						$sum = 0;
					}

					if($sum > 0) {
						$sql_cont = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM cus_review WHERE item_id = '$itm_id' AND accept=1"));
						$avg = $sum / $sql_cont;
						$avg_rev = ceil($avg);
						
						$sql_avg = "UPDATE bookdetails SET reviews = '$avg_rev' WHERE id = '$itm_id'";
						$result_avg = mysqli_query($conn, $sql_avg);
					}
					
					echo json_encode(array("msgType" => 1, "msg" => "Success"));
				}
			}
	    }
		
		/***************************** // *****************************/
		
	} else {
		$redirectUrl = "../";
		echo "<script type=\"text/javascript\">";
		echo "window.location.href = '$redirectUrl'";
		echo "</script>";
	}
}
?>