<?php
include '../db/db.php';
session_start();
$log = htmlspecialchars(trim($_SESSION['user']), ENT_QUOTES, 'UTF-8');
$log_lang = htmlspecialchars(trim($_SESSION['lang']), ENT_QUOTES, 'UTF-8');

$menu = htmlspecialchars(trim($_SESSION['menu']), ENT_QUOTES, 'UTF-8');
$emp_id = htmlspecialchars(trim($_SESSION['emp_id']), ENT_QUOTES, 'UTF-8');

if (empty($log)) {
	$redirectUrl = "index.php";
	echo "<script type=\"text/javascript\">";
	echo "window.location.href = '$redirectUrl'";
	echo "</script>";

} else {

	$sqlu = "SELECT * FROM user_priv_q WHERE emp_id='$emp_id' AND user='$log' AND menu_id='$menu'";
	$resultu = mysqli_query($conn, $sqlu);
	$countu = mysqli_num_rows($resultu);

	if($countu == 1){
  
		$gid = htmlspecialchars(strip_tags(trim($_GET['gid'])), ENT_QUOTES, 'UTF-8');
		$menu = htmlspecialchars(strip_tags(trim($_GET['menu'])), ENT_QUOTES, 'UTF-8');
		$flag = htmlspecialchars(strip_tags(trim($_GET['flag'])), ENT_QUOTES, 'UTF-8');

		if(!empty($gid) && !empty($menu)) {
			if($flag == 1) { // Add	
				$query = mysqli_query($conn, "SELECT * FROM user_privileges WHERE group_id='$gid' and menu_id='$menu'");

				if (mysqli_num_rows($query) == 0){
					if($log_lang == 1) {
						mysqli_query($conn, "INSERT INTO user_privileges SET group_id='$gid' , menu_id='$menu'");
					}
				}
			}
			
			if($flag == 2) { // Remove		
				if($log_lang == 1) {
					mysqli_query($conn, "DELETE FROM user_privileges WHERE group_id='$gid' and menu_id='$menu'");
				}
			}
		}	

	} else{
		$redirectUrl = "index.php";
		echo "<script type=\"text/javascript\">";
		echo "window.location.href = '$redirectUrl'";
		echo "</script>";	
	}
}
?>