<?php

/**
 * @param $_GET['procesID'] - id procesu
 * 
 * example:
 *   index.php?MENU_INIT=PROCES_ADD_ZASOB&procesID=3885
 */
function PROCES_ADD_ZASOB() {

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

	$task = V::get('_task', '', $_REQUEST);
	switch ($task) {
		case 'FRM_RM_ZASOB': {
			$procesID = V::get('procesID', 0, $_GET, 'int');
			$rmWskID = V::get('rmWskID', 0, $_POST, 'int');
			if (!$procesID || !$rmWskID) {
				$taskErrors[] = "Wrong param proces id or remove wskaźnik id!";
			}
			else {
				$db = DB::getDB();
				$sql_obj = new stdClass();
				$sql_obj->ID = $rmWskID;
				$sql_obj->A_STATUS = 'DELETED';

				$affected = $db->UPDATE_OBJ('CRM_WSKAZNIK', $sql_obj);
				if ($affected == 2) {
					$taskMsgs[] = "Usunieto wskaznik";
				} else if ($affected == 1) {
					$taskMsgs[] = "Usunieto wskaznik (nie zapisano historii)";
				} else if ($affected < 0) {
					$taskErrors[] = "Nie udało się usunąć zasobu - nic nie zmieniono";
				}
			}
			break;
		}
		case 'FRM_ADD_ZASOB': {
			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>';}
			$procesID = V::get('procesID', 0, $_GET, 'int');
			$addZasobID = V::get('addZasobID', 0, $_POST, 'int');
			$addPrzypadekID = V::get('addPrzypadekID', 0, $_POST, 'int');
			if ($procesID > 0 && $addZasobID > 0 && $addPrzypadekID > 0) {
				$addComment = V::get('addComment', '', $_POST);

				$db = DB::getDB();
				$sql_obj = new stdClass();
				$sql_obj->ID_PROCES = $procesID;
				$sql_obj->ID_ZASOB = $addZasobID;
				$sql_obj->ID_PRZYPADEK = $addPrzypadekID;
				$sql_obj->OPIS_ZASOB = $db->_($addComment);
				$sql_obj->SORT_PRIO = 0;
				// nowy wskaznik na koniec listy pod procesem
				$sql = "select max(cw.`SORT_PRIO`) as MAX_SORT_PRIO
					from `CRM_WSKAZNIK` as cw
					where
						cw.`ID_PROCES`='{$sql_obj->ID_PROCES}'
				";
				$res = $db->query($sql);
				while ($r = $db->fetch($res)) {
					$sql_obj->SORT_PRIO = $r->MAX_SORT_PRIO + 1;
				}

				$new_id = $db->ADD_NEW_OBJ('CRM_WSKAZNIK', $sql_obj);
				if ($new_id > 0) {
					$taskMsgs[] = "Dodano zasób [{$addZasobID}] do procesu [{$procesID}]";
				} else {
					$taskErrors[] = "Nie udało się dodać zasobu";
				}
			}
			else if (!$addPrzypadekID) {
				$taskErrors[] = "Brak okreśłonego uprawnienia";
			}
			else if (!$addZasobID) {
				$taskErrors[] = "Brak numeru zasobu";
			}
			break;
		}
		case 'TYPESPECIAL': {
			$DBG = ('1' == V::get('DBG', '', $_REQUEST));
			header("Content-type: application/json");

			$fld = V::get('fld', '', $_GET);
			switch ($fld) {
				case 'editZasobID':
				case 'addZasobID': {
					Lib::loadClass('TypespecialVariable');
					$typeSpecialZasob = TypespecialVariable::getInstance(-1, '__ZASOB');

					$query = V::get('q', '', $_REQUEST);
					$rawRows = null;
					$jsonData = array();
					$rows = $typeSpecialZasob->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;
		}
		case 'EDIT_WSKAZNIK_SAVE': {
			$procesID = V::get('procesID', 0, $_GET, 'int');
			$cw_id = V::get('cw_id', 0, $_GET, 'int');
			$editZasobID = V::get('editZasobID', 0, $_POST, 'int');
			$editPrzypadekID = V::get('editPrzypadekID', 0, $_POST, 'int');
			$editComment = V::get('editComment', '', $_POST);
			if (!$procesID || !$cw_id || !$editZasobID) {
				header('HTTP/1.0 406 Not Acceptable');
				echo "Wrong param proces ID or Wskaznik ID or Zasob ID!";
				exit;
			}
			$db = DB::getDB();
			if (!$db) {
				header('HTTP/1.0 406 Not Acceptable');
				echo "No DB!";
				exit;
			}

			$proces = $db->get_by_id('CRM_PROCES', $procesID);
			if (!$proces) {
				header('HTTP/1.0 406 Not Acceptable');
				echo "Proces not exists!";
				exit;
			}
			Lib::loadClass('ProcesHelper');
			$proces->_zasoby = ProcesHelper::get_wskazniki($proces->ID);

			if (!isset($proces->_zasoby[$cw_id])) {
				header('HTTP/1.0 406 Not Acceptable');
				echo "Wskaznik not exists!";
				exit;
			}
			$wskaznik = $proces->_zasoby[$cw_id];

			$sqlObj = new stdClass();
			$sqlObj->ID = $wskaznik->CW_ID;
			$toChange = false;
			if ($wskaznik->ID != $editZasobID) {
				$sqlObj->ID_ZASOB = $editZasobID;
				$toChange = true;
			}
			if ($wskaznik->ID_PRZYPADEK != $editPrzypadekID) {
				$sqlObj->ID_PRZYPADEK = $editPrzypadekID;
				$toChange = true;
			}
			if ($wskaznik->OPIS_ZASOB != $editComment) {
				$sqlObj->OPIS_ZASOB = $editComment;
				$toChange = true;
			}

			if (!$toChange) {
				echo 'Nie wprowadzono żadnych zmian.';
			}
			else {
				$ret = $db->UPDATE_OBJ('CRM_WSKAZNIK', $sqlObj);
				if ($ret < 0) {
					header('HTTP/1.0 406 Not Acceptable');
					echo "Wystąpiły błędy podczas zapisu zmian w bazie danych!";
					exit;
				}
				else if ($ret > 0) {
					//echo 'OK';
				}
				else {
					//echo 'Nie wprowadzono żadnych zmian.';
				}
			}
			// TODO: return json object wskaznik to fix layout without page reload
			header("Content-type: application/json");
			$data = new stdClass();
			$data->msg = "Zmiany wprowadzono pomyślnie";
			$data->wskaznik = $db->get_by_id('CRM_WSKAZNIK', $cw_id);
			if ($data->wskaznik->ID_ZASOB > 0) {
				$data->wskaznik->_zasob = $db->get_by_id('CRM_LISTA_ZASOBOW', $data->wskaznik->ID_ZASOB);
			}
			if ($data->wskaznik->ID_PRZYPADEK > 0) {
				$data->wskaznik->_przypadek = $db->get_by_id('CRM_PRZYPADEK', $data->wskaznik->ID_PRZYPADEK);
			}
			echo json_encode($data);

			exit;
		}
		case 'EDIT_WSKAZNIK': {
			$procesID = V::get('procesID', 0, $_GET, 'int');
			$cw_id = V::get('cw_id', 0, $_GET, 'int');
			if (!$procesID || !$cw_id) {
				header('HTTP/1.0 406 Not Acceptable');
				echo "Wrong param proces ID or Wskaznik ID!";
				exit;
			}
			$db = DB::getDB();
			if (!$db) {
				header('HTTP/1.0 406 Not Acceptable');
				echo "No DB!";
				exit;
			}
			$proces = $db->get_by_id('CRM_PROCES', $procesID);
			if (!$proces) {
				header('HTTP/1.0 406 Not Acceptable');
				echo "Proces not exists!";
				exit;
			}
			Lib::loadClass('ProcesHelper');
			$proces->_zasoby = ProcesHelper::get_wskazniki($proces->ID);

			if (!isset($proces->_zasoby[$cw_id])) {
				header('HTTP/1.0 406 Not Acceptable');
				echo "Wskaznik not exists!";
				exit;
			}
			$wskaznik = $proces->_zasoby[$cw_id];

			Lib::loadClass('TypespecialVariable');
			$typeSpecialZasob = TypespecialVariable::getInstance(-1, '__ZASOB');
			if (!$typeSpecialZasob) {
				header('HTTP/1.0 406 Not Acceptable');
				echo "TypeSpecial Zasob not exists!";
				exit;
			}

			?>
			<form action="" method="POST" class="form conn_wsk-frm">
				<div class="control-group">
					<label class="control-label" for="editZasobID">Zasób</label>
					<div class="controls">
						<?php
							$fName = 'editZasobID';
							$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";
							$tsValues = $typeSpecialZasob->getEditSelectedValuesByIds($tblId = null, $id = null, $fieldName = '', $fieldValue = $wskaznik->ID);
							$fldParams['typespecialValue'] = (!empty($tsValues))? reset($tsValues) : '';
							echo $typeSpecialZasob->showFormItem($tblID = -1, $fName, $selValue = $wskaznik->ID, $fldParams);
						?>
					</div>
				</div>
				<div class="control-group">
					<label class="control-label" for="editPrzypadekID">Uprawnienia</label>
					<div class="controls">
						<?php
							$uprawnienia = array();
							$db = DB::getDB();
							$sql = "select p.* from `CRM_PRZYPADEK` as p ";
							$res = $db->query($sql);
							while ($r = $db->fetch($res)) {
								$uprawnienia[$r->ID] = "{$r->FORM_TREAT}: {$r->OPIS}";// {$r->NAZWA} | {$r->PYTANIE} | 
							}
						?>
						<select name="editPrzypadekID" style="width:366px;" size="6">
							<?php foreach($uprawnienia as $kId => $vPermLabel) : ?>
								<?php $sel = ($wskaznik->CW_ID_PRZYPADEK == $kId)? ' selected="selected"' : ''; ?>
								<option value="<?php echo $kId; ?>"<?php echo $sel; ?>><?php echo $vPermLabel; ?></option>
							<?php endforeach; ?>
						</select>
					</div>
				</div>
				<div class="control-group">
					<label class="control-label" for="editComment">Komentarz</label>
					<div class="controls">
						<textarea name="editComment" cols="80" rows="6" style="width:354px;"><?php echo $wskaznik->OPIS_ZASOB; ?></textarea>
					</div>
				</div>
				<div class="control-group">
					<div class="controls">
						<button type="submit" class="btn btn-primary">Zapisz</button>
					</div>
				</div>
			</form>
			<?php
			exit;
		}
	}

	SE_Layout::menu();

	Lib::loadClass('UserActivity');

	Lib::loadClass('ProcesHelper');
/* TODO: permy do pokazania tej funkcji
	$zasobID = ProcesHelper::getZasobTableID('CRM_WSKAZNIK');
	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;
	}
*/

	$procesID = V::get('procesID', '', $_GET);
	if (!$procesID) {
		echo '<div class="alert alert-error">' . "Wrong param proces ID!" . '</div>';
		return;
	}
	$db = DB::getDB();
	$proces = $db->get_by_id('CRM_PROCES', $procesID);
	Lib::loadClass('ProcesHelper');
	$proces->_zasoby = ProcesHelper::get_wskazniki($proces->ID);


	Lib::loadClass('TypespecialVariable');
	$typeSpecialZasob = TypespecialVariable::getInstance(-1, '__ZASOB');

	?>
	<style type="text/css">
.conn_wsk {}
 .conn_wsk .conn_wsk-list {}
  .conn_wsk .conn_wsk-list .conn_wsk-list_item { line-height:22px; }
  .conn_wsk .conn_wsk-list .conn_wsk-list_item form { display:inline; margin:0; }
  .conn_wsk .conn_wsk-list_item-rmBtn,
  .conn_wsk .conn_wsk-list_item-editBtn { /*display:none;*/ opacity:0.3; margin:0; padding:0; border:none; }
  .conn_wsk .conn_wsk-list_item-rmBtn   { margin:0 0 0 10px; }
  .conn_wsk .conn_wsk-list_item-editBtn { margin:0 0 0 10px; }
  .conn_wsk .conn_wsk-list_item:hover .conn_wsk-list_item-rmBtn,
  .conn_wsk .conn_wsk-list_item:hover .conn_wsk-list_item-editBtn { /*display:inline;*/ opacity:0.6; }
  .conn_wsk .conn_wsk-list_item .conn_wsk-list_item-rmBtn:hover,
  .conn_wsk .conn_wsk-list_item .conn_wsk-list_item-editBtn:hover { /*display:inline;*/ opacity:1; }
.conn_wsk-frm {}

 .conn_wsk .conn_wsk-opisyShowBtn { padding:0 0 0 10px; font-size:12px; font-weight:normal; color:#08C; cursor:pointer; }
.conn_wsk-list_item-desc,
.conn_wsk-list_item-longDesc { display:none; }
.opisyShow .conn_wsk-list_item-desc,
.opisyShow .conn_wsk-list_item-longDesc { display:block; }

.editWskModal-loading .modal-body { padding-left:40px; background:url(./icon/loading.gif) no-repeat left top; background-position:20px 20px; }

	</style>
	<div class="container conn_wsk">
		<h3>Edycja procesu</h3>
		<blockquote>
			<b>Proces [<?php echo $proces->ID; ?>]</b>: <?php echo $proces->TYPE; ?> <?php echo $proces->DESC; ?>
			<p><?php echo $proces->OPIS; ?></p>
		</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; ?>
		<h5>Przypisane zasoby <em>(<?php echo (!empty($proces->_zasoby))? count($proces->_zasoby) : 0; ?>)</em>: <span class="conn_wsk-opisyShowBtn" onclick="jQuery(this).parent().parent().toggleClass('opisyShow')">+/- opisy</span></h5>
		<ul class="conn_wsk-list">
			<?php if (!empty($proces->_zasoby)) : ?>
				<?php foreach ($proces->_zasoby as $vZasob) : ?>
					<li class="conn_wsk-list_item conn_wsk-list_item-<?php echo $vZasob->CW_ID; ?>">
						<span class="conn_wsk-list_item-title"><?php echo $vZasob->CP_FORM_TREAT; ?> [<?php echo $vZasob->ID; ?>] <?php echo $vZasob->TYPE; ?> <b><?php echo $vZasob->DESC; ?></b></span>
						<form action="" method="POST" class="form-inline conn_wsk-list_item-frm-rm">
							<input type="hidden" name="_task" value="FRM_RM_ZASOB">
							<button name="rmWskID" value="<?php echo $vZasob->CW_ID; ?>" class="btn-link btn-small conn_wsk-list_item-rmBtn" title="usuń zasób"><i class="icon icon-remove"></i></button>
						</form>
						<p class="conn_wsk-list_item-desc">
							<?php if (!empty($vZasob->OPIS)) : ?>
								<?php echo $vZasob->OPIS; ?>
							<?php endif; ?>
						</p>
						<p class="conn_wsk-list_item-longDesc">
							<?php if (!empty($vZasob->OPIS_ZASOB)) : ?>
								<?php echo $vZasob->OPIS_ZASOB; ?>
							<?php endif; ?>
						</p>
					</li>
				<?php endforeach; ?>
			<?php endif; ?>
		</ul>
		<?php if ($typeSpecialZasob) : ?>
			<h5>Dodaj zasób:</h5>
			<form action="" method="POST" class="form-horizontal conn_wsk-frm">
				<input type="hidden" name="_task" value="FRM_ADD_ZASOB">
				<div class="control-group">
					<label class="control-label" for="addZasobID">Zasób</label>
					<div class="controls">
						<?php
							$fName = 'addZasobID';
							$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 $typeSpecialZasob->showFormItem($tblID = -1, $fName, $selValue = '', $fldParams);
						?>
					</div>
				</div>
				<div class="control-group">
					<label class="control-label" for="addPrzypadekID">Uprawnienia</label>
					<div class="controls">
						<?php
							$uprawnienia = array();
							$db = DB::getDB();
							$sql = "select p.* from `CRM_PRZYPADEK` as p ";
							$res = $db->query($sql);
							while ($r = $db->fetch($res)) {
								$uprawnienia[$r->ID] = "{$r->FORM_TREAT}: {$r->OPIS}";// {$r->NAZWA} | {$r->PYTANIE} | 
							}
						?>
						<select name="addPrzypadekID" style="width:366px;" size="6">
							<?php foreach($uprawnienia as $kId => $vPermLabel) : ?>
								<option value="<?php echo $kId; ?>"><?php echo $vPermLabel; ?></option>
							<?php endforeach; ?>
						</select>
					</div>
				</div>
				<div class="control-group">
					<label class="control-label" for="addComment">Komentarz</label>
					<div class="controls">
						<textarea name="addComment" cols="80" rows="6" style="width:354px;"></textarea>
					</div>
				</div>
				<div class="control-group">
					<div class="controls">
						<button type="submit" class="btn">dodaj</button>
					</div>
				</div>
			</form>
		<?php endif; ?>
	</div>

	<!-- Modal -->
	<div id="editWskModal" class="modal hide fade editWskModal-loading" tabindex="-1" role="dialog" aria-labelledby="editWskModalLabel" aria-hidden="true">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			<h3 id="editWskModalLabel">Edycja wskaźnika</h3>
		</div>
		<div class="modal-body">
			<p>One fine body...</p>
		</div>
<!--
		<div class="modal-footer">
			<button class="btn" data-dismiss="modal" aria-hidden="true">Anuluj</button>
			<button class="btn btn-primary">Zapisz</button>
		</div>
-->
	</div>

<script>
jQuery(document).ready(function() {
	jQuery('.conn_wsk-list_item-rmBtn').each(function(ind, n) {
		var btn = jQuery('<button class="btn-link btn-small conn_wsk-list_item-editBtn" title="edytuj wskaźnik"><i class="icon icon-edit"></i></button>');
		btn.data('cw_id', n.value);
		btn.on('click', function(e) {
			e.preventDefault();
			e.stopPropagation();
			var trg = jQuery(event.currentTarget),
				cw_id = trg.data('cw_id');
			if (cw_id > 0) {
				var modal = jQuery('#editWskModal');
				modal.addClass('editWskModal-loading');
				modal.modal();
				jQuery.ajax({
					data: null,
					type: "GET",
					url: 'index.php?FUNCTION_INIT=<?php echo __FUNCTION__; ?>&HEADER_NOT_INIT=YES&_task=EDIT_WSKAZNIK&procesID=<?php echo $proces->ID; ?>&cw_id=' + cw_id,
				})
				.done(function(data, textStatus, jqXHR){
					modal.find('.modal-body').html(data);
					modal.find('.modal-body').find('form').on('submit', function() {
						var frm = jQuery(this);
						jQuery.ajax({
							data: frm.serialize(),
							type: "POST",
							dataType: 'json',
							url: 'index.php?FUNCTION_INIT=<?php echo __FUNCTION__; ?>&HEADER_NOT_INIT=YES&_task=EDIT_WSKAZNIK_SAVE&procesID=<?php echo $proces->ID; ?>&cw_id=' + cw_id
						})
						.done(function(data, textStatus, jqXHR){
							if (data.msg) {
								modal.find('.modal-body').html('<div class="alert alert-success">' + data.msg + '</div>');
							} else {
								modal.find('.modal-body').html(data);
							}
							if (data.wskaznik) {
								var trgWrap = jQuery('.conn_wsk-list_item-' + cw_id),
										trgTitle = trgWrap.find('.conn_wsk-list_item-title'),
										trgDesc = trgWrap.find('.conn_wsk-list_item-desc'),
										trgZasobDesc = trgWrap.find('.conn_wsk-list_item-longDesc')
									;
								if (trgTitle && trgTitle.length > 0) {
									var outTrgTitle = '';
									if (undefined !== data.wskaznik._przypadek) {
										if (undefined !== data.wskaznik._przypadek.FORM_TREAT) {
											outTrgTitle += data.wskaznik._przypadek.FORM_TREAT + ' ';
										}
									}
									if (undefined !== data.wskaznik._zasob) {
										if (undefined !== data.wskaznik._zasob.ID) outTrgTitle += '[' + data.wskaznik._zasob.ID + '] ';
										if (undefined !== data.wskaznik._zasob.TYPE) outTrgTitle += data.wskaznik._zasob.TYPE + ' ';
										if (undefined !== data.wskaznik._zasob.DESC) outTrgTitle += '<b>' + data.wskaznik._zasob.DESC + '</b>';
									}
									trgTitle.html(outTrgTitle);
								}
								if (trgDesc && trgDesc.length > 0) {
									if (undefined !== data.wskaznik._zasob) {
										if (undefined !== data.wskaznik._zasob.OPIS) {
											trgDesc.html(data.wskaznik._zasob.OPIS);
										}
									}
								}
								if (trgZasobDesc && trgZasobDesc.length > 0) {
									if (undefined !== data.wskaznik.OPIS_ZASOB) {
										trgZasobDesc.html(data.wskaznik.OPIS_ZASOB);
									}
								}
							}
						})
						.fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
							var txt = jqXHR.responseText || 'Error';
							modal.find('.modal-body').html('<div class="alert alert-error">' + txt + '</div>');
						})
						return false;
					});
				})
				.fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
					var txt = jqXHR.responseText || 'Error';
					modal.find('.modal-body').html('<div class="alert alert-error">' + txt + '</div>');
				})
				.always(function(data, textStatus, jqXHR) {
					modal.removeClass('editWskModal-loading');
				});
			}
		});
		btn.insertBefore(n);
	});
});
</script>
	<?php

}
