<?php
if (session_status() == PHP_SESSION_NONE && !IS_CLI) {
    if(!isset($_SESSION)) session_start();
}

function getUserDetails($username=null)
{
	if (empty($username)&& array_key_exists('username', $_SESSION)){
          $username = $_SESSION['username'];   
        }
	global $userdetails;
	if (empty($userdetails) || !empty($username)){
		$userdetails = fetchUserDetails($username);
        }
	return $userdetails;
}

function getGroupsAuth(){
    $mysqli = sqlCreateConnection("getGroupsAuth");
    
    $sql = "SELECT * FROM `groups_table` ORDER BY group_id ASC";
    $res = sqlQuery($mysqli, $sql);
    while ($res && ($row = $res->fetch_object()))
    {
        $perm_arr = [];
        $perm = json_decode($row->permissions,true);
        foreach ($perm as $per){
            $perm_arr[constant($per)] = true;
        }
        $results[] = ["name"=> $row->name, "permissions"=>$perm_arr];
    }
    sqlClose($mysqli, "getGroupsAuth");
    return $results;
    
}

function getUserAuth($username=null)
{
    require_once 'demosettings.php';
// 	global $AUTH;
	global $userAuth;	
	global $noPrivileges;
	$AUTH = getGroupsAuth();
	
	$userdetails = getUserDetails($username);
	if (empty($userAuth) || !empty($username)){
		$userAuth = $AUTH[$userdetails['Group_ID']]["permissions"];
// 		$userAuth = array_merge($noPrivileges, $userAuth);
	}

	return $userAuth;

}

function getUserPermission($permission,$username=null)
{
	$userAuth = getUserAuth($username);
	return $userAuth[$permission] ?? false;
}

?>