<?php

/**
 * @param $_GET['usrLogin'] - user login
 * 
 * example:
 *   index.php?MENU_INIT=USER_ADD_GROUP&usrLogin=test13
 */
function USER_ADD_GROUP() {
	Lib::loadClass('UserStorageFactory');

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

	$task = V::get('_task', '', $_REQUEST);
	switch ($task) {
		case 'FRM_RM_GROUP': {
			$rmProfileID = V::get('rmProfileID', 0, $_POST, 'int');
			$usrLogin = V::get('usrLogin', '', $_GET);
			if (!$usrLogin || !$rmProfileID) {
				$taskErrors[] = 'Wrong param user login or remove group id!';
			}
			else {
				$usrStorageDB = UserStorageFactory::getStorage('DB');
				if (!$usrStorageDB) {
					$taskErrors[] =  'Error storage not exists!';
				} else {
					$profile = $usrStorageDB->getProfileById($rmProfileID);
					if (!$profile) {
						$taskErrors[] =  'Error profile not exists!';
					} else {
						$usrStorageDB->removeUserGroupByProfileId($usrLogin, $profile->group, $rmProfileID);
						$taskMsgs[] = 'Profil został usunięty';
					}
				}
			}
			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>';}
			$usrLogin = V::get('usrLogin', '', $_GET);
			if (!$usrLogin) {
				$taskErrors[] = 'Wrong param user login!';
			}
			else {
				Lib::loadClass('UserStorageFactory');
				$usrStorageDB = UserStorageFactory::getStorage('DB');
				if (!$usrStorageDB) {
					$taskErrors[] =  'Error storage not exists!';
				}
				else {
					$usr = $usrStorageDB->getUser($usrLogin);
					if (!$usr) {
						$taskErrors[] = "Użytkownik {$usrLogin} nie istnieje.";
					}
					else {
						$addUsrGroupID = V::get('addUsrGroupID', 0, $_POST, 'int');
						$addTelboxesID = V::get('addTelboxesID', 0, $_POST, 'int');
						if ($addUsrGroupID > 0) {
							$groupToAdd = $usrStorageDB->getGroupWithoutNested($addUsrGroupID);
							if (!$groupToAdd) {
								$taskErrors[] = "Grupa [{$addUsrGroupID}] nie istnieje";
							}
							else {
								$added = $usrStorageDB->addUserGroup($usrLogin, $groupToAdd, $addTelboxesID);
								if ($added) {
									$taskMsgs[] = "Dodano grupę [{$addUsrGroupID}] do użytkownika [{$usrLogin}]";
								} else {
									$taskErrors[] = "Nie udało się dodać grupy [{$addUsrGroupID}] do użytkownika [{$usrLogin}]";
								}
							}
						}
					}
				}
			}
			break;
		}
		case 'TYPESPECIAL': {
			header("Content-type: application/json");

			$fld = V::get('fld', '', $_GET);
			switch ($fld) {
				case 'addUsrGroupID': {
					Lib::loadClass('TypespecialVariable');
					$typeSpecialUserGroups = TypespecialVariable::getInstance(-1, '__USER_GROUPS');

					$query = V::get('q', '', $_REQUEST);
					$rawRows = null;
					$rows = $typeSpecialUserGroups->getValuesWithExports($query);
					if(V::get('DBG', '', $_REQUEST)){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;
				}
				case 'addTelboxesID': {
					Lib::loadClass('TypespecialVariable');
					$typeSpecialTelboxes = TypespecialVariable::getInstance(-1, '__TELBOXES');

					$query = V::get('q', '', $_REQUEST);
					$rawRows = null;
					$rows = $typeSpecialTelboxes->getValuesWithExports($query);
					if(V::get('DBG', '', $_REQUEST)){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('CRM_AUTH_PROFILE');
	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;
	}

	$usrLogin = V::get('usrLogin', '', $_GET);
	if (!$usrLogin) {
		echo '<div class="alert alert-error">Wrong param user login!</div>';
		return;
	}

	$usrStorageDB = UserStorageFactory::getStorage('DB');

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

	$usr = $usrStorageDB->getUser($usrLogin);
	if (!$usr) {
		echo '<div class="alert alert-error">' . "Użytkownik {$usrLogin} nie istnieje." . '</div>';
		return;
	}

	$stanowiska = array();
	$stanowiska = $usrStorageDB->getUserProfiles($usrLogin, $fetchNested = false);
	function this__sort_stanowiska_by_type($a, $b) {
		if ($a->group->type != $a->group->type) {
			if ($a->group->type == 'network') {
				return 1;
			}
			else if ($a->group->type == 'local') {
				return -1;
			}
		}
		return 0;
	}
	uasort($stanowiska, 'this__sort_stanowiska_by_type');

	Lib::loadClass('UsersHelper');
	$groups = UsersHelper::getGroupByUser($usr->primaryKey);
	if(V::get('DBG', '', $_REQUEST)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">groups (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($groups);echo'</pre>';}

	Lib::loadClass('UsersLdapHelper');
	$groupsNetwork = UsersLdapHelper::getUserGroups($usrLogin, 3);
	if(V::get('DBG', '', $_REQUEST)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">groupsNetwork (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($groupsNetwork);echo'</pre>';}

	UserActivity::add($zasobID);

	//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">zasobObj (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($zasobObj);echo'</pre>';

	$userAcl = User::getAcl();
	$userAcl->fetchGroups();
	//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none;">$userAcl (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($userAcl);echo'</pre>';

	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);
	//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">tblAcl (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($tblAcl);echo'</pre>';

	$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;
		}
	}

	$forceFilterInit['REMOTE_ID'] = $usr->primaryKey;
	$forceFilterInit['REMOTE_TABLE'] = 'ADMIN_USERS';

	$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');
	$typeSpecialUserGroups = TypespecialVariable::getInstance(-1, '__USER_GROUPS');
	$typeSpecialTelboxes   = TypespecialVariable::getInstance(-1, '__TELBOXES');

	?>
	<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:none;*/ opacity:0.4; margin:0; padding:0 10px; border:none; }
  .conn_groups .conn_groups-list_item:hover .conn_groups-list_item-rmBtn { /*display:inline;*/ opacity:1; }
	</style>
	<div class="container conn_groups">
		<h3>Przypisane grupy</h3>
		<blockquote>
			<b>Użytkownik [<?php echo $usr->primaryKey; ?>]</b>: <?php echo $usr->name; ?> <em>(<?php echo $usr->login; ?>)</em>
			<a class="btn btn-mini btn-primary" href="index.php?MENU_INIT=SYNC_LDAP_PERMS&syncUsr=<?php echo $usr->login; ?>">synchronizuj do LDAP</a>
		</blockquote>
			<?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; ?>
			<b>Przypisane grupy (<?php echo (!empty($stanowiska))? count($stanowiska) : 0; ?>):</b>
			<?php if (!empty($stanowiska)) : ?>
				<ul class="conn_groups-list">
					<?php foreach ($stanowiska as $vProfile) : ?>
						<li class="conn_groups-list_item">
							<?php echo $vProfile->group->realName; ?>
							<?php if ($vProfile->localisationId > 0) : ?>
								(lokalizacja [<?php echo $vProfile->localisationId; ?>])
							<?php endif; ?>
							<form action="" method="POST" class="form-inline frm-groups">
								<input type="hidden" name="_task" value="FRM_RM_GROUP">
								<button name="rmProfileID" value="<?php echo $vProfile->profileId; ?>" class="btn-link btn-small conn_groups-list_item-rmBtn" title="usuń grupę" onclick="return confirm('Czy jesteś pewien że chcesz usunąć przypisanie do grupy <?php echo $vProfile->group->realName; ?>?');"><i class="icon icon-remove"></i></button>
							</form>
						</li>
					<?php endforeach; ?>
				</ul>
			<?php endif; ?>
			<?php if ($typeSpecialUserGroups && $typeSpecialTelboxes) : ?>
			<p><b>Dodaj grupę:</b></p>
				<form class="form-horizontal" action="" method="POST">
					<input type="hidden" name="_task" value="FRM_ADD_GROUP">
					<div class="control-group">
						<label class="control-label" for="addUsrGroupID">Grupa</label>
						<div class="controls">
							<?php
								$fName = 'addUsrGroupID';
								$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 $typeSpecialUserGroups->showFormItem($tblID = -1, $fName, $selValue = '', $fldParams);
							?>
						</div>
					</div>
					<div class="control-group">
						<label class="control-label" for="addTelboxesID">Lokalizacja</label>
						<div class="controls">
							<?php
								$fName = 'addTelboxesID';
								$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 $typeSpecialTelboxes->showFormItem($tblID = -1, $fName, $selValue = '', $fldParams);
							?>
						</div>
					</div>
					<div class="control-group">
						<div class="controls">
							<button type="submit" class="btn">dodaj grupę</button>
						</div>
					</div>
				</form>
			<?php endif; ?>
	</div>
	<?php
	echo $tbl->render();

}
