<?php
session_start();
include('../permission/connect_sql.php');
$user_list = array();
$sql = "SELECT DISTINCT [User].[UserID],[Account],[UserName],[DepartmentID],[Group].[GroupID],[GroupName] FROM [User] 
LEFT JOIN [UserGroup] ON [User].[UserID] = [UserGroup].[UserID] 
LEFT JOIN [Group] ON [UserGroup].[GroupID] = [Group].[GroupID]
LEFT JOIN [GroupRight] ON [GroupRight].[GroupID] = [Group].[GroupID] 
LEFT JOIN [WebPage] ON [WebPage].[PgroupID] = [GroupRight].[PgroupID]
WHERE [DepartmentID] = (SELECT [DepartmentID] FROM [User] WHERE [UserID] = ?) ORDER BY [GroupName]";
$stmt = sqlsrv_query($conn, $sql, array($_SESSION['UserID']));
$users = array();
$permissions = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    if (in_array($row["UserID"], $user_list)) {
        $index = array_search($row["UserID"],$user_list);
        array_push($users[$index]["GroupID"],$row["GroupID"]);
        array_push($users[$index]["GroupName"],$row["GroupName"]);
    } else {
        $temp = array();
        $temp["UserID"] = $row["UserID"];
        $temp["Account"] = $row["Account"];
        $temp["UserName"] = $row["UserName"];
        $temp["DepartmentID"] = $row["DepartmentID"];
        $temp["GroupID"] = array($row["GroupID"]);
        $temp["GroupName"] = array($row["GroupName"]);
        array_push($users, $temp);
        array_push($user_list, $row["UserID"]);
    }
}

$sql = "SELECT [GroupID],[GroupName] FROM [Group] WHERE [GroupID] != 'Admin'";
$stmt = sqlsrv_query($conn, $sql, array($_SESSION['UserID']));
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    $temp = array();
    $temp["GroupID"] = $row["GroupID"];
    $temp["GroupName"] = $row["GroupName"];
    array_push($permissions, $temp);
}
$data["users"] = $users;
$data["permissions"] = $permissions;
echo json_encode($data);
