<?php

/**
 * @param $_GET['groupID'] - id grupy - zasob typu: 'STANOWISKO', 'PODMIOT', 'DZIAL'
 * 
 * example:
 *   index.php?MENU_INIT=GROUP_ADD_NESTEDGROUPS&groupID=13
 */
function GROUP_ADD_NESTEDGROUPS() {
	Lib::loadClass('UserStorage');
	$linkTypeIdNestedGroups = 5;

	$taskMsgs = array();
	$taskErrors = array();

	$task = V::get('_task', '', $_REQUEST);
	switch ($task) {
		case 'FRM_RM_PARENT_GROUP': {
			$groupID = V::get('groupID', 0, $_GET, 'int');
			$rmParentGroupID = V::get('rmParentGroupID', 0, $_POST, 'int');
			if (!$groupID || !$rmParentGroupID) {
				$taskErrors[] = 'Wrong param group id or remove group id!';
			}
			else {
				$usrStorageDB = UserStorage::getStorage('DB');
				$group = $usrStorageDB->getGroupWithoutNested($groupID);
				$parentGroup = $usrStorageDB->getGroupWithoutNested($rmParentGroupID);
				if ($group && $parentGroup) {
					$removed = $usrStorageDB->removeParentGroup($groupID, $parentGroup);
					if ($removed) {
						$taskMsgs[] = "Usunięto grupę nadrzędną [{$rmParentGroupID}] do grupy [{$groupID}]";
					} else {
						$taskErrors[] = "Nie udało się usunąć grupy nadrzędnej [{$rmParentGroupID}] do grupy [{$groupID}]";
					}
				}
			}
			break;
		}
		case 'FRM_RM_NESTED_GROUP': {
			$groupID = V::get('groupID', 0, $_GET, 'int');
			$rmNestedGroupID = V::get('rmNestedGroupID', 0, $_POST, 'int');
			if (!$groupID || !$rmNestedGroupID) {
				$taskErrors[] = 'Wrong param group id or remove group id!';
			}
			else {
				$usrStorageDB = UserStorage::getStorage('DB');
				$group = $usrStorageDB->getGroupWithoutNested($groupID);
				$nestedGroup = $usrStorageDB->getGroupWithoutNested($rmNestedGroupID);
				if ($group && $nestedGroup) {
					$removed = $usrStorageDB->removeNestedGroup($groupID, $nestedGroup);
					if ($removed) {
						$taskMsgs[] = "Usunięto grupę zagnieżdżoną [{$rmNestedGroupID}] z grupy [{$groupID}]";
					} else {
						$taskErrors[] = "Nie udało się usunąć grupy zagnieżdżonej [{$rmNestedGroupID}] z grupy [{$groupID}]";
					}
				}
			}
			break;
		}
		case 'FRM_ADD_GROUP': {
			if(V::get('DBG_NG', '', $_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">post (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($_POST);echo'</pre>';}
			// [addParentGroupID] => 372
			// [addNestedGroupID] => 372
			$groupID = V::get('groupID', 0, $_GET, 'int');
			if ($groupID > 0) {
				$usrStorageDB = UserStorage::getStorage('DB');
				$group = $usrStorageDB->getGroupWithoutNested($groupID);
				$addParentGroupID = V::get('addParentGroupID', 0, $_POST, 'int');
				$addNestedGroupID = V::get('addNestedGroupID', 0, $_POST, 'int');
				if ($addParentGroupID > 0) {
					$group = $usrStorageDB->getGroupWithoutNested($groupID);
					$parentGroup = $usrStorageDB->getGroupWithoutNested($addParentGroupID);
					if ($group && $parentGroup) {
						$added = $usrStorageDB->addParentGroup($groupID, $parentGroup);
						if ($added) {
							$taskMsgs[] = "Dodano grupę nadrzędną [{$addParentGroupID}] do grupy [{$groupID}]";
						} else {
							$taskErrors[] = "Nie udało się dodać grupy nadrzędnej [{$addParentGroupID}] do grupy [{$groupID}]";
						}
					}
				}
				else if ($addNestedGroupID > 0) {
					$group = $usrStorageDB->getGroupWithoutNested($groupID);
					$nestedGroup = $usrStorageDB->getGroupWithoutNested($addNestedGroupID);
					if ($group && $nestedGroup) {
						$added = $usrStorageDB->addNestedGroup($groupID, $nestedGroup);
						if ($added) {
							$taskMsgs[] = "Dodano grupę zagnieżdżoną [{$addNestedGroupID}] do grupy [{$groupID}]";
						} else {
							$taskErrors[] = "Nie udało się dodać grupy zagnieżdżonej [{$addNestedGroupID}] do grupy [{$groupID}]";
						}
					}
				}
			}
			break;
		}
		case 'TYPESPECIAL': {
			$DBG = ('1' == V::get('DBG', '', $_REQUEST));
			header("Content-type: application/json");

			$fld = V::get('fld', '', $_GET);
			switch ($fld) {
				case 'addParentGroupID':
				case 'addNestedGroupID': {
					Lib::loadClass('TypespecialVariable');
					$typeSpecialNestedGroups = TypespecialVariable::getInstance(-1, '__NESTED_GROUPS');

					$query = V::get('q', '', $_REQUEST);
					$rawRows = null;
					$rows = $typeSpecialNestedGroups->getValuesWithExports($query);
					if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">rows('.$query.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($rows);echo'</pre>';}
					foreach ($rows as $kID => $vItem) {
						$itemJson = new stdClass();
						$itemJson->id = $vItem->id;
						$itemJson->name = $vItem->param_out;
						if (!empty($vItem->exports)) {
							$itemJson->exports = $vItem->exports;
						}
						$jsonData[] = $itemJson;
					}
					echo json_encode($jsonData);
					break;
				}
			}
			exit;
		}
	}

	SE_Layout::menu();

	Lib::loadClass('UserActivity');

	Lib::loadClass('ProcesHelper');
	$zasobID = ProcesHelper::getZasobTableID('ITEM_LINKS');
	if ($zasobID <= 0) {
		echo UserActivity::showListInContainer();
		return;
	}

	$zasobObj = ProcesHelper::getZasobTableInfo($zasobID);
	if (!$zasobObj) {
		echo '<div class="alert alert-error">' . "Zasob TABELA ID={$zasobID} nie istnieje" . '</div>';
		echo UserActivity::showSimpleList();
		return;
	}

	$groupID = V::get('groupID', 0, $_GET, 'int');
	if (!$groupID) {
		echo '<div class="alert alert-error">Wrong param group id!</div>';
		return;
	}

	if (V::get('_testUsrGroupsLdapLvl0', '', $_GET)) {
		Lib::loadClass('UsersLdapHelper');
		$usrLogin = User::getLogin();
		$groups = array(); $groupsLvl3 = array();
		$groupsNetwork = UsersLdapHelper::getUserGroups($usrLogin, 0);
		foreach ($groupsNetwork as $vGroup) {
			$groups[$vGroup->cn] = $vGroup->appleUID;
		}
		echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;font-size:10px;">groups ldap lvl 0 (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($groups);echo'</pre>';
		$groupsNetwork = UsersLdapHelper::getUserGroups($usrLogin, 3);
		foreach ($groupsNetwork as $vGroup) {
			$groupsLvl3[$vGroup->cn] = $vGroup->appleUID;
		}
		echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;font-size:10px;">groups ldap lvl 3 (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($groupsLvl3);echo'</pre>';
	}


	Lib::loadClass('UserStorage');
	$usrStorageDB = UserStorage::getStorage('DB');

	if (!$usrStorageDB) {
		echo '<div class="alert alert-error">Error storage not exists!</div>';
		return;
	}

	$group = $usrStorageDB->getGroup($groupID);
	if (!$group) {
		echo '<div class="alert alert-error">' . "Grupa {$groupID} nie istnieje." . '</div>';
		return;
	}

	$group->parentGroups = $usrStorageDB->fetchParentGroups($groupID);

	if(V::get('DBG_NG', '', $_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$group (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($group);echo'</pre>';}

	UserActivity::add($zasobID);

	$userAcl = User::getAcl();
	$userAcl->fetchGroups();
	if (!$userAcl->hasTableAcl($zasobObj->ID)) {
		echo '<div class="alert alert-error">' . "Brak uprawnień do tabeli ID={$zasobObj->ID}" . '</div>';
		echo UserActivity::showSimpleList();
		return;
	}

	$tblAcl = $userAcl->getTableAcl($zasobObj->ID);

	$forceTblAclInit = ('1' == V::get('_force', '', $_GET));
	$tblAcl->init($forceTblAclInit);

	Lib::loadClass('TableAjax');

	$forceFilterInit = array();
	$filterInit = new stdClass();
	$filterInit->currSortCol = 'ID';
	$filterInit->currSortFlip = 'desc';
	foreach ($_GET as $k => $v) {
		if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && !empty($v)) {// filter prefix
			$filterInit->$k = $v;
		}
		else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && !empty($v)) {// special filter prefix
			$filterInit->$k = $v;
		}
		else if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
			$fldName = substr($k, 3);
			$forceFilterInit[$fldName] = $v;
		}
	}

	$tblZasobyID = ProcesHelper::getZasobTableID('CRM_LISTA_ZASOBOW');
	$forceFilterInit['TABLE_1_NAME'] = 'CRM_LISTA_ZASOBOW';
	$forceFilterInit['TABLE_1_ZASOB_ID'] = $tblZasobyID;
	$forceFilterInit['TABLE_1_ID'] = $group->zasobID;
	$forceFilterInit['TABLE_2_NAME'] = 'CRM_LISTA_ZASOBOW';
	$forceFilterInit['TABLE_2_ZASOB_ID'] = $tblZasobyID;
	$forceFilterInit['LINKS_TYPE_ID'] = $linkTypeIdNestedGroups;

	$tbl = new TableAjax($tblAcl);
	$tbl->setLabel($zasobObj->OPIS);
	$tbl->setFilterInit($filterInit);
	if (!empty($forceFilterInit)) $tbl->setForceFilterInit($forceFilterInit);
	$tbl->addRowFunction('edit');
	$tbl->addRowFunction('hist');
	$tbl->addRowFunction('files');
	$tbl->addRowFunction('cp');
	$tbl->showProcesInit(false);// hide Proces filter field

	Lib::loadClass('TypespecialVariable');
	$typeSpecialNestedGroups = TypespecialVariable::getInstance(-1, '__NESTED_GROUPS');

	$groupUsers = array();
	$groupNestedUsers = array();
	$tblUsrsZasobId = ProcesHelper::getZasobTableID('ADMIN_USERS');
	if ($group->zasobID > 0) {
		$groupUsers = UsersHelper::getUsersByGroupId($groupID);
		$groupNestedUsers = UsersHelper::getUsersByGroupsIds(array_keys($group->nestedGroups), array_keys($groupUsers));
	}

	?>
	<style type="text/css">
.frm-groups .selectize-control { float:left; }
.conn_groups {}
 .conn_groups .conn_groups-list {}
  .conn_groups .conn_groups-list .conn_groups-list_item { line-height:22px; }
  .conn_groups .conn_groups-list .conn_groups-list_item form { display:inline; margin:0; }
  .conn_groups .conn_groups-list_item-rmBtn {  display:inline; margin:0; padding:0 6px; border:none; opacity:0.4; }
  .conn_groups .conn_groups-list_item-editBtn {  margin:0 6px; padding:0; border:none; opacity:0.4; }
  .conn_groups .conn_groups-list_item:hover .conn_groups-list_item-rmBtn { display:inline; opacity:1; }
  .conn_groups .conn_groups-list_item:hover .conn_groups-list_item-editBtn { opacity:1; }
.users-with-perms {}
 .users-with-perms address { padding:0 6px; border:1px solid #eee; }
 .users-with-perms address:hover { border-color:#333; }
	</style>
	<div class="container conn_groups">
		<h3>Grupy uprawnień
			<!-- <em style="color:#ccc;">(Nested Groups)</em> -->
		</h3>
		<p>
			<b>Zasób [<?php echo $groupID; ?>]</b>: <?php echo $group->type; ?> <?php echo $group->zasobDESC; ?>
			<a class="btn btn-mini btn-primary" href="index.php?MENU_INIT=SYNC_LDAP_PERMS&syncGroup=<?php echo $groupID; ?>">synchronizuj do LDAP</a>
		</p>

		<br>

		<div class="row">
			<div class="span6">

				<?php if (!empty($taskErrors)) : ?>
					<div class="alert alert-error">
						<button type="button" class="close" data-dismiss="alert">×</button>
						<?php echo implode('<br>', $taskErrors); ?>
					</div>
				<?php endif; ?>
				<?php if (!empty($taskMsgs)) : ?>
					<div class="alert alert-success">
						<button type="button" class="close" data-dismiss="alert">×</button>
						<?php echo implode('<br>', $taskMsgs); ?>
					</div>
				<?php endif; ?>

<!--				<p><b>Grupy posiadające dostęp do rekordów grupy [<?php echo $group->zasobID; ?>] <?php echo $group->zasobDESC; ?></b> <em>(<?php echo (!empty($group->parentGroups))? count($group->parentGroups) : 0; ?>)</em>:
				</p> -->
				<blockquote>
<!--					<h5>Ustal grupy, które będą miały uprawnienia do rekordów dostępnych dla
						[<?php echo $group->zasobID; ?>] <?php echo $group->zasobDESC; ?>
					</h5>
					<small>np. grupy podrzędnych pracowników.</small> -->
					<h5>Udostępnij rekordy innym grupom</h5>
					<small>np. przełożonemu.</small>
				</blockquote>
				<ul class="conn_groups-list">
					<?php if (!empty($group->nestedGroups)) : ?>
						<?php foreach ($group->nestedGroups as $vNestedGroup) : ?>
							<li class="conn_groups-list_item">
								[<?php echo $vNestedGroup->zasobID; ?>]
								<?php echo $vNestedGroup->type; ?>
								<?php echo $vNestedGroup->zasobDESC; ?>
								<a href="index.php?MENU_INIT=GROUP_ADD_NESTEDGROUPS&groupID=<?php echo $vNestedGroup->zasobID; ?>" class="ico-pencil conn_groups-list_item-editBtn" title="Edytuj grupę"> </a>
								<form action="" method="POST" class="form-inline frm-groups">
									<input type="hidden" name="_task" value="FRM_RM_NESTED_GROUP">
									<button name="rmNestedGroupID" value="<?php echo $vNestedGroup->zasobID; ?>" class="btn-link btn-small conn_groups-list_item-rmBtn" title="usuń grupę"><i class="ico-remove"></i></button>
								</form>
							</li>
						<?php endforeach; ?>
					<?php endif; ?>
					<?php if ($typeSpecialNestedGroups) : ?>
						<li>
							<form action="" method="POST" class="form-inline frm-groups">
								<input type="hidden" name="_task" value="FRM_ADD_GROUP">
								<?php
									$fName = 'addNestedGroupID';
									$fldParams = array();
									$fldParams['allowCreate'] = false;
									$fldParams['ajaxDataUrlBase'] = "index.php?FUNCTION_INIT=" . __FUNCTION__ . "&HEADER_NOT_INIT=YES&_task=TYPESPECIAL&fld={$fName}";
									//$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
									echo $typeSpecialNestedGroups->showFormItem($tblID = -1, $fName, $selValue = '', $fldParams);
								?>
								<button class="btn">dodaj</button>
							</form>
						</li>
					<?php endif; ?>
				</ul>

<!--				<p><b>Grupy do rekordów, których posiada dostęp grupa [<?php echo $group->zasobID; ?>] <?php echo $group->zasobDESC; ?></b> <em>(<?php echo (!empty($group->parentGroups))? count($group->parentGroups) : 0; ?>)</em>:
				</p> -->
				<blockquote>
					<h5>Grupy, które udostępniają rekordy</h5>
					<small>np. grupy podrzędnych pracowników lub dział, podmiot.</small>
				</blockquote>
				<ul class="conn_groups-list">
					<?php if (!empty($group->parentGroups)) : ?>
						<?php foreach ($group->parentGroups as $vParentGroup) : ?>
							<li class="conn_groups-list_item">
								[<?php echo $vParentGroup->zasobID; ?>]
								<?php // if ('DZIAL' == $vParentGroup->type) : ?>
									<?php echo $vParentGroup->type; ?>
								<?php // endif; ?>
								<?php echo $vParentGroup->zasobDESC; ?>
								<a href="index.php?MENU_INIT=GROUP_ADD_NESTEDGROUPS&groupID=<?php echo $vParentGroup->zasobID; ?>" class="ico-pencil conn_groups-list_item-editBtn" title="Edytuj grupę"> </a>
								<form action="" method="POST" class="form-inline frm-groups">
									<input type="hidden" name="_task" value="FRM_RM_PARENT_GROUP">
									<button name="rmParentGroupID" value="<?php echo $vParentGroup->zasobID; ?>" class="btn-link btn-small conn_groups-list_item-rmBtn" title="usuń grupę"><i class="ico-remove"></i></button>
								</form>
							</li>
						<?php endforeach; ?>
					<?php endif; ?>

					<?php if ($typeSpecialNestedGroups) : ?>
						<li>
							<form action="" method="POST" class="form-inline frm-groups">
								<input type="hidden" name="_task" value="FRM_ADD_GROUP">
								<?php
									$fName = 'addParentGroupID';
									$fldParams = array();
									$fldParams['allowCreate'] = false;
									$fldParams['ajaxDataUrlBase'] = "index.php?FUNCTION_INIT=" . __FUNCTION__ . "&HEADER_NOT_INIT=YES&_task=TYPESPECIAL&fld={$fName}";
									//$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
									echo $typeSpecialNestedGroups->showFormItem($tblID = -1, $fName, $selValue = '', $fldParams);
								?>
								<button class="btn">dodaj</button>
							</form>
						</li>
					<?php endif; ?>
				</ul>

			</div>
			<div class="span6 users-with-perms">

				<h5>Użytkownicy:</h5>
				<?php if (empty($groupUsers)) : ?>
					<div class="alert">Brak użytkowników przypisanych bezpośrednio do grupy</div>
				<?php else : ?>
					<div class="row">
					<?php foreach ($groupUsers as $usr) : ?>
						<div class="span3">
							<address>
								<strong><?php echo $usr->ADM_NAME; ?></strong>
								<a href="index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $tblUsrsZasobId; ?>#EDIT/<?php echo $usr->ID; ?>" class="ico-pencil" title="Edytuj rekord"> </a>

								<br><em><?php echo $usr->EMPLOYEE_TYPE; ?></em>

								<?php if (!empty($usr->ADM_PHONE)) : ?>
									<br><abbr title="Telefon">Tel.:</abbr> <?php echo $usr->ADM_PHONE; ?>
								<?php endif; ?>

								<?php if (!empty($usr->EMAIL)) : ?>
									<br><a href="mailto:<?php echo $usr->EMAIL; ?>"><?php echo $usr->EMAIL; ?></a>
								<?php endif; ?>
							</address>
						</div>
					<?php endforeach; ?>
					</div>
				<?php endif; ?>

				<h5>Użytwkonicy z uprawnieniami do rekordów</h5>
				<?php if (empty($groupNestedUsers)) : ?>
					<div class="alert">Brak</div>
				<?php else : ?>
					<div class="row">
					<?php foreach ($groupNestedUsers as $usr) : ?>
						<div class="span3">
							<address>
								<strong><?php echo $usr->ADM_NAME; ?></strong>
								<a href="index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $tblUsrsZasobId; ?>#EDIT/<?php echo $usr->ID; ?>" class="ico-pencil" title="Edytuj rekord"> </a>

								<br><em><?php echo $usr->EMPLOYEE_TYPE; ?></em>

								<?php if (!empty($usr->ADM_PHONE)) : ?>
									<br><abbr title="Telefon">Tel.:</abbr> <?php echo $usr->ADM_PHONE; ?>
								<?php endif; ?>

								<?php if (!empty($usr->EMAIL)) : ?>
									<br><a href="mailto:<?php echo $usr->EMAIL; ?>"><?php echo $usr->EMAIL; ?></a>
								<?php endif; ?>
							</address>
						</div>
					<?php endforeach; ?>
					</div>
				<?php endif; ?>

			</div>
		</div>
	</div>
	<?php
	echo $tbl->render();

}
