<?php


/**
 * @param $_GET['EDIT'] - ID rekordu do edycji (inline)
 * @param $_GET['EDIT_ID'] - ID rekordu do edycji (inline)
 */
function task_CRM_PROCES() {
	User_procesy5_check_access();

	$_GET['ADM_AREA'] = V::get('ADM_AREA', "BN%", $_GET);
	$_GET['EDIT'] = V::get('EDIT', 0, $_GET, 'int');
	if (($edit_id = V::get('EDIT_ID', 0, $_GET, 'int')) > 0) {
		$_GET['EDIT'] = $edit_id;
	}
	$tbl = 'CRM_PROCES';

	$tbl_conf = Column::getInstance($tbl);
	if (!$tbl_conf) {
		echo'<p class="red">'."Brak konfiguracji dla ".$tbl."!".'</p>';
		return;
	}
	$visible_cols = $tbl_conf->getVisibleFieldList();

	// form decorators:

	$tbl_search_params = array();
	$tbl_search_params['ID'] = 'ID';
	$tbl_search_params['PARENT_ID'] = 'P_ID';
	$tbl_search_params['TYPE'] = 'TYPE';
	$tbl_search_params['DESC'] = 'DESC';
	$tbl_search_params['OPIS'] = 'OPIS';
	$tbl_search_params['DESC_PL'] = 'DESC_PL';
	$tbl_search_params['TAGS'] = 'TAGS';
	$tbl_search_params['A_STATUS'] = 'A_STATUS';
	$tbl_search_params['L_APPOITMENT_USER'] = 'L_APPOITMENT_USER';
	$tbl_search_params['L_APPOITMENT_DATE'] = 'L_APPOITMENT_DATE';
	$tbl_search_params['L_APPOITMENT_INFO'] = 'L_APPOITMENT_INFO';
	$tbl_search_params['A_ADM_COMPANY'] = 'A_ADM_COMPANY';
	$tbl_search_params['IF_TRUE_GOTO'] = 'IF_TRUE_GOTO';
	$tbl_search_params['IF_TRUE_GOTO_FLAG'] = 'IF_TRUE_GOTO_FLAG';
	$tbl_search_params['A_RECORD_CREATE_AUTHOR'] = 'A_RECORD_CREATE_AUTHOR';
	$tbl_search_params['A_RECORD_CREATE_DATE'] = 'A_RECORD_CREATE_DATE';
	$tbl_search_params['A_RECORD_UPDATE_AUTHOR'] = 'A_RECORD_UPDATE_AUTHOR';
	$tbl_search_params['A_RECORD_UPDATE_DATE'] = 'A_RECORD_UPDATE_DATE';

	Lib::loadClass('FilterLast');
	$filter_last = new FilterLast( $_REQUEST, $tbl, 'session');
	$filter_last->add_filter( 'last_id', array('filtr_id','filtr_search_id','ID','EDIT'), "Ostatnio uzywane ID", 'int' );
	$filter_last->_save_args();// save args from request

	{// TABLE - Filter
		$tbl = 'CRM_PROCES';
		$tbl_filter = new stdClass();
		$tbl_filter->key = 'tbl-'.$tbl;
		$tbl_filter->filters = array();
		// TODO: stronicowanie $tbl_filter->filters: _page_nr, _limit, _total (need sql - only after change params)

		// read args from session, or get dafault values
		foreach ($tbl_search_params as $k => $req_field_name) {
			$tbl_filter->filters[$req_field_name] = V::get($req_field_name, '%', $_SESSION[$tbl_filter->key]);
		}//end foreach

		// read args from $_GET if isset
		foreach ($tbl_search_params as $k => $req_field_name) {
			if (isset($_GET[$req_field_name])) {
				$tbl_filter->filters[$req_field_name] = $_GET[$req_field_name];
			}
		}//end foreach

		// save args in session and $_GET
		foreach ($tbl_filter->filters as $req_field_name => $v) {
			$_SESSION[$tbl_filter->key][$req_field_name] = $v;
			$_GET[$req_field_name] = $v;
		}//end foreach

		echo'<div style="border:1px solid red; display:none;">';
		foreach ($tbl_filter->filters as $req_field_name => $v) {
			echo'<br />arg['.$req_field_name.'] = '.$v;
		}//end foreach
		echo'</div>';
	}// TABLE - Filter

	{// TREE - Filter
		$tbl = 'CRM_PROCES';

		$tree_procesy_filter = get_filter_for_table( $tbl );
		$tree_procesy_filter->set_trash( 'filtr_id', -1 );

		{// zapisz stan - ajax function to save filters stan and opened tree nodes, etc.
			$filtr_ses_key = $tree_procesy_filter->_key;
			$cookie_key = 'TREE_'.$tbl;
			$profile_key = 'Filtr_'.$filtr_ses_key;
			if (V::get('save_profile', '', $_REQUEST)) {
				$profile_val = array();
				$profile_val['filtr'] = $_SESSION[$filtr_ses_key];
				$profile_val['tree'] = $_COOKIE[$cookie_key];// cookie key from Tree class - 'TREE_'. $tbl @see __construct
				User::setProfile($profile_key, $profile_val);
				$ret = User::saveProfile();
			}
			else if (V::get('load_profile', '', $_REQUEST)) {
				//User::loadProfile();// proile is loaded in USERS_COLUMN_INIT after login
				$profile_val = User::getProfile($profile_key);
				$_COOKIE[$cookie_key] = $profile_val['tree'];
				echo'<script type="text/javascript">'."
jQuery(document).ready(function(){
	jQuery.cookie('".$cookie_key."','" . $_COOKIE[$cookie_key] . "');
});
				".'</script>';
				$_SESSION[$filtr_ses_key] = $profile_val['filtr'];
				$tree_procesy_filter->_read_args( true );// force load args from session
			}
		}// zapisz stan - ajax function to save filters stan and opened tree nodes, etc.

		$tree_procesy_filter->_save_args();// force save_args (execute at the end of show_filters)

		echo'<div style="border:1px solid red; display:none;">';
		foreach ($tree_procesy_filter->filters as $arg => $v) {
			echo'<br />arg['.$arg.'] = '.$tree_procesy_filter->get_arg($arg);
		}//end foreach
		echo'</div>';
	}// TREE - Filter

	echo'<h1>';
		echo App::link("Procesy", array('task'=>App::get_task(), 'filtr_id'=>''));
		if ($tree_procesy_filter->is_trash()) {//$_GET['filtr_id'] == -1) {
			echo ' &raquo; '."Kosz";
			echo " " . App::link("czyść", array('task'=>App::get_task(), 'function_init'=>"fun_CRM_PROCES_clean_trash"), array('title'=>"Ustaw status rekordów w koszu na DELETED", 'class'=>'btn-p5', 'style'=>'font-size:13px;'));
		} else if ($tree_procesy_filter->get_arg('filtr_id') > 0) {//$_GET['filtr_id'] > 0) {
			echo ' &raquo; '."Proces [".$tree_procesy_filter->get_arg('filtr_id')."]";
		}

		echo '<span class="pull-right">'.App::link("Mapa procesów", array('task'=>'VIEW_PROCES_MAP')).'</span>';
	echo'</h1>';

//wykrywamy czy ma dostepny proces do jakiejs komorki w tej tabeli
		$userAcl = User::getAcl();
		$tblAcl = $userAcl->getTableAcl(ProcesHelper::getZasobTableID('CRM_PROCES'));
	if($tblAcl)
	if($tblAcl->hasFieldPerm($tblAcl->getFieldIdByName('ID'),'R')) {
		echo App::link("Pokaz Tabele", "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".ProcesHelper::getZasobTableID('CRM_PROCES'));
		echo "<br>".App::link("Dodaj nowy rekord", "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".ProcesHelper::getZasobTableID('CRM_PROCES')."#CREATE");

		
	} else {


			
		
		if (!$_SESSION['HIDE_PROCESY']) {
		echo App::link("Ukryj Tabele", "?task=CRM_PROCES&HIDE_PROCESY=1");
		} else {
		echo App::link("Pokaz Tabele", "?task=CRM_PROCES&UNHIDE_PROCESY=1");
		}

		$table_view = array();
		$table_view['labels'] = array();
		$table_view['head'] = array();
		$table_view['find'] = array();
		$table_view['foot'] = array();
		
		$table_view['labels']['ID'] = "ID";
		$table_view['labels']['PARENT_ID'] = "P_ID";
		$table_view['labels']['TYPE'] = "TYPE";
		$table_view['labels']['DESC'] = "DESC";
		$table_view['labels']['OPIS'] = "OPIS";
		$table_view['labels']['DESC_PL'] = "DESC_PL";
		$table_view['labels']['TAGS'] = "TAGS";
		$table_view['labels']['A_STATUS'] = "A_STATUS";
		$table_view['labels']['L_APPOITMENT_USER'] = "L_APPOITMENT_USER";
		$table_view['labels']['L_APPOITMENT_DATE'] = "L_APPOITMENT_DATE";
		$table_view['labels']['L_APPOITMENT_INFO'] = "L_APPOITMENT_INFO";
		$table_view['labels']['A_ADM_COMPANY'] = "A_ADM_COMPANY";
		
		$table_view['head']['ID']= 'ID';
		$table_view['head']['PARENT_ID']= '<span class="P_ID">'."P_ID".'</span>';
		$table_view['head']['TYPE']= 'TYPE';
		$table_view['head']['DESC']= 'DESC';
		$table_view['head']['DESC_PL']= 'DESC_PL';
		$table_view['head']['TAGS']= 'TAGS';
		$table_view['head']['OPIS']= 'OPIS';
		$table_view['head']['A_STATUS'] = 'A_STATUS';
		$table_view['head']['L_APPOITMENT_USER'] = 'L_APP_USER';
		$table_view['head']['L_APPOITMENT_DATE'] = 'L_APP_DATE';
		$table_view['head']['L_APPOITMENT_INFO'] = 'L_APP_INFO';
		$table_view['head']['A_ADM_COMPANY'] = 'A_ADM_COMPANY';
		
		$table_view['find']['ID']= App::field_search( 'ID', "varchar(255)", $_GET['ID'], array('class'=>'i', 'size'=>5) );
		$table_view['find']['PARENT_ID']= App::field_search( 'P_ID', "varchar(255)", $_GET['P_ID'], array('class'=>'i', 'size'=>5) );
		$table_view['find']['TYPE']= App::field_search( 'TYPE', $tbl_conf->type('TYPE'), $_GET['TYPE'], array('class'=>'i') );
		$table_view['find']['DESC']= App::field_search( 'DESC', "varchar(255)", $_GET['DESC'], array('class'=>'i', 'size'=>5) );
		$table_view['find']['OPIS']= App::field_search( 'OPIS', "varchar(255)", $_GET['OPIS'], array('class'=>'i', 'size'=>5) );
		$table_view['find']['TAGS']= App::field_search( 'TAGS', "varchar(100)", $_GET['TAGS'], array('class'=>'i', 'size'=>5) );
		$table_view['find']['A_STATUS'] =  App::field_search( 'A_STATUS', $tbl_conf->type('A_STATUS'), $_GET['A_STATUS'], array('class'=>'i') );
		$table_view['find']['L_APPOITMENT_USER'] = App::field_search( 'L_APPOITMENT_USER', $tbl_conf->type('L_APPOITMENT_USER'), $_GET['L_APPOITMENT_USER'], array('class'=>'i', 'size'=>5) );
		$table_view['find']['L_APPOITMENT_DATE'] = App::field_search( 'L_APPOITMENT_DATE', $tbl_conf->type('L_APPOITMENT_DATE'), $_GET['L_APPOITMENT_DATE'], array('class'=>'i', 'size'=>5) );
		$table_view['find']['L_APPOITMENT_INFO'] = App::field_search( 'L_APPOITMENT_INFO', $tbl_conf->type('L_APPOITMENT_INFO'), $_GET['L_APPOITMENT_INFO'], array('class'=>'i', 'size'=>5) );
		$table_view['find']['A_ADM_COMPANY'] = App::field_search( 'A_ADM_COMPANY', $tbl_conf->type('A_ADM_COMPANY'), $_GET['A_ADM_COMPANY'], array('class'=>'i', 'size'=>5) );
		$table_view['find']['IF_TRUE_GOTO']= App::field_search( 'IF_TRUE_GOTO', "varchar(11)", $_GET['IF_TRUE_GOTO'], array('class'=>'i', 'size'=>5) );
		$table_view['find']['IF_TRUE_GOTO_FLAG']= App::field_search( 'IF_TRUE_GOTO_FLAG', $tbl_conf->type('IF_TRUE_GOTO_FLAG'), $_GET['IF_TRUE_GOTO_FLAG'], array('class'=>'i') );
		$table_view['find']['A_RECORD_CREATE_AUTHOR']= App::field_search( 'A_RECORD_CREATE_AUTHOR', $tbl_conf->type('A_RECORD_CREATE_AUTHOR'), $_GET['A_RECORD_CREATE_AUTHOR'], array('class'=>'i') );
		$table_view['find']['A_RECORD_CREATE_DATE']= App::field_search( 'A_RECORD_CREATE_DATE', $tbl_conf->type('A_RECORD_CREATE_DATE'), $_GET['A_RECORD_CREATE_DATE'], array('class'=>'i') );
		$table_view['find']['A_RECORD_UPDATE_AUTHOR']= App::field_search( 'A_RECORD_UPDATE_AUTHOR', $tbl_conf->type('A_RECORD_UPDATE_AUTHOR'), $_GET['A_RECORD_UPDATE_AUTHOR'], array('class'=>'i') );
		$table_view['find']['A_RECORD_UPDATE_DATE']= App::field_search( 'A_RECORD_UPDATE_DATE', $tbl_conf->type('A_RECORD_UPDATE_DATE'), $_GET['A_RECORD_UPDATE_DATE'], array('class'=>'i') );
		
		$table_view['foot']['PARENT_ID'] = App::field( 'ADD_'.'PARENT_ID', "varchar(255)", V::get('ADD_'.'PARENT_ID', '', $_POST), array('class'=>'i', 'size'=>4) );
		$table_view['foot']['TYPE'] = App::field( 'ADD_'.'TYPE', $tbl_conf->type('TYPE'), V::get('ADD_'.'TYPE', '', $_POST), array('class'=>'i') );
		$table_view['foot']['DESC'] = App::field( 'ADD_'.'DESC', "varchar(255)", V::get('ADD_'.'DESC', '', $_POST), array('class'=>'i', 'size'=>14) );
		$table_view['foot']['DESC_PL'] = App::field( 'ADD_'.'DESC_PL', $tbl_conf->type('DESC_PL'), V::get('ADD_'.'DESC_PL', '', $_POST), array('class'=>'i','size'=>10) );
		$table_view['foot']['OPIS'] = App::field( 'ADD_'.'OPIS', "varchar(255)", V::get('ADD_'.'OPIS', '', $_POST), array('class'=>'i', 'size'=>20) );
		$table_view['foot']['IF_TRUE_GOTO'] = App::field( 'ADD_'.'IF_TRUE_GOTO', $tbl_conf->type('IF_TRUE_GOTO'), V::get('ADD_'.'IF_TRUE_GOTO', '', $_POST), array('class'=>'i','size'=>10) );
		$table_view['foot']['IF_TRUE_GOTO_FLAG'] = App::field( 'ADD_'.'IF_TRUE_GOTO_FLAG', $tbl_conf->type('IF_TRUE_GOTO_FLAG'), V::get('ADD_'.'IF_TRUE_GOTO_FLAG', '', $_POST), array('class'=>'i','size'=>1) );
		
		$ses_col_name = 'CRM_PROCES';
		
		echo'<table border="1" cellspacing="0" cellpadding="0" class="tbl-view">';
		echo'<thead>';
		echo'<tr>'."\n";
			echo'<th>';
				echo App::link("C", array('function_init'=>"fun_USERS_COLUMN", 'arg'=>"edit"), array('title'=>"Ustawienia", 'ico'=>'excel.gif', 'ico_height'=>'12'));
			echo'</th>';
			foreach ($visible_cols as $field_id => $field_name) {
				$v = V::get($field_name, str_replace('_', ' ', $field_name), $table_view['head']);
				echo'<td>';
					echo $v;
					if ($field_name != 'ID') {
						echo ' ';
						echo App::link("X", array('function_init'=>"fun_USERS_COLUMN", 'arg'=>"hide", 'col_id'=>$field_id), array('title'=>"Ukryj kolumne", 'ico'=>'shutdown.gif', 'ico_height'=>11));
					}
				echo'</td>'."\n";
			}//end foreach
		echo'</tr>'."\n";
		echo'<tr class="find">'."\n";
			echo'<form action="" method="GET">';
			echo'<input type="hidden" name="task" value="'.App::get_task().'" />';
			echo'<th style="text-align:center;">';
				echo'<input type="image" value="'."Szukaj".'" src="'."icon/search.png".'" title="'."Szukaj".'" />';
			echo'</th>';
			foreach ($visible_cols as $field_id => $field_name) {
				$v = V::get($field_name, '', $table_view['find']);
				$cls = array();
				$v_label = V::get($field_name, '', $table_view['labels']);
				if ($v_label && isset($tbl_filter->filters[$v_label])) {
					if ($tbl_filter->filters[$v_label] != '%') {
						$cls []= 'selected';
					}
				}
				$cls = (!empty($cls))? ' class="'.implode(' ', $cls).'"' : '';
				echo'<td'.$cls.'>'.$v.'</td>'."\n";
			}//end foreach
			echo'</form>';
		echo'</tr>'."\n";
		echo'</thead>';
		echo'<tbody>';
		
		
		{// fetch data
			$sql_limit = 1500;// TODO: stronicowanie
			if ($_SESSION['HIDE_PROCESY']) $sql_limit = "3";
		
			$sql_where = array();
			if ($_GET['EDIT']) {
				$sql_where []= "CP.`ID`='".$_GET['EDIT']."'";
			} else {
				foreach ($tbl_search_params as $k => $req_field_name) {
					// TODO: FILTER_SEARCH <, >, <=, >=, !
					$sql_where []= "CP.`".$k."` like '".$_GET[$req_field_name]."'";
				}
			}
			$sql_where = implode(" and ", $sql_where);
		
			$query = "SELECT
					CP.*
				FROM `CRM_PROCES` as CP
				where
					".$sql_where."
				order by CP.`ID` desc, CP.`PARENT_ID`, CP.`TYPE`, CP.`DESC`
				limit ".$sql_limit."
			";
			$res = DB::query( $query );
		}
		
		
		$t = 0;
		while ($r = DB::fetch( $res )) {
			if ($_GET['EDIT'] == $r->ID) {
				echo'<form action="'.App::build_http_query("?EDIT=".$r->ID."#".$r->ID).'" method="POST">';
				echo'<tr class="edit row-'.($t = 1 - $t).'">';
				echo'<th>';
					echo'<input type="image" src="'."icon/save.png".'" name="EDIT_SUBMIT" value="'."E ".$r->ID.'" title="'."Zapisz".'">';
					echo '<br />'.App::link("IMG", "?function_init=fun_IMAGE_ADD&tbl=".'CRM_PROCES'."&id=".$r->ID, array('target'=>'_blank', 'title'=>"Dodaj zdjecia"));
					echo '<br />'.App::link("P+", array('task'=>"CRM_TESTY_ADD_PYTANIA", 'id_proces'=>$r->ID), array('title'=>'Dodaj pytanie do testow', 'class'=>'btn-p5 btn-red'));
				echo'</th>';
				foreach ($visible_cols as $field_id => $field_name) {
					if ($field_name == 'ID') {
						echo'<td>';
							echo'<a id="'.$r->ID.'">'.$r->ID.'</a>';
							echo ' '.App::link("L", "#TREE".$r->PARENT_ID);
							echo'<input type="hidden" name="function_init" value="'."fun_CRM_PROCES_EDIT".'">';
							echo'<input type="hidden" name="task" value="'.App::get_task().'">';
							echo'<input type="hidden" name="EDIT_ID" value="'.$r->ID.'">';
						echo '</td>';
					} else {
						echo'<td>';
							if ($tbl_conf->allowWrite($field_name)) {
								echo App::field( 'EDIT_' . $field_name, $tbl_conf->type($field_name), $r->$field_name, array('class'=>'i') );
							} else {
								echo $r->$field_name;
							}
						echo'</td>';
					}
				}
				echo '</tr>';
				echo'</form>';
			}
			else {
				echo "\n".'<tr class="edit row-'.($t = 1 - $t).'">';
				echo'<th>';
					if (User_is_admin()) {
						echo App::link("Edit", "?EDIT=".$r->ID, array('id'=>$r->ID, 'title'=>"Edytuj", 'ico'=>'edit.png'));
					}
				echo'</th>';
				foreach ($visible_cols as $field_id => $field_name) {
					if ($field_name == 'ID') {
						echo'<td>';
						if (User_is_admin()) {
							echo App::link($r->ID, "?EDIT=".$r->ID."#".$r->ID, array('id'=>$r->ID, 'title'=>'Edytuj'));
						} else {
							echo $r->ID;
						}
						echo '</td>';
					} else {
						echo'<td> '.$r->$field_name.'</td>';
					}
				}
				echo'</tr>';
			}
		}
		echo'</tbody>';
		
		
		
		if (User_is_admin()) {
			echo'<tfoot>';
			echo'<form action="" method="POST">';
			echo'<tr class="add">';
				echo'<th colspan=2>';
					echo'<input type="hidden" name="task" value="'.App::get_task().'" />';
					echo'<input type="hidden" name="function_init" value="'."fun_CRM_PROCES_ADD".'" />';
					echo'<input type="image" alt="'."Dodaj".'" src="'."icon/add.gif".'" title="'."Dodaj nowy".'">';
				echo'</th>';
				foreach ($visible_cols as $field_id => $field_name) {
					if ($field_name == 'ID') continue;
		
					$v = V::get($field_name, ' ', $table_view['foot']);
					echo'<td>'.$v.'</td>';
				}//end foreach
			echo'</tr>';
			echo'</form>';
			echo'</tfoot>';
		}
		echo'</table>';
		
		
	}

echo'<br />';

$TREE = array();
echo'<div id="tree"></div>';


$DBG_TIME = 0;
if($DBG_TIME) $time_arr = array();// [ [time, desc], [time, desc], ... ]
if($DBG_TIME) $time_arr []= array(microtime(true), 'before Tree');

	if ($tree_procesy_filter->get_arg('filtr_view') == 'NOWY') {
		$filter_last->show_filters();

		echo'<div class="filters">';
		echo'<form action="'."".'" method="get" style="margin:0;padding:0;">';
			echo'<input type="hidden" name="task" value="'.App::get_task().'" />';
			$tree_procesy_filter->show_filters();
			// TODO: another form ? function_init ?
			{// save profile - btn
				echo'<nobr>';
					echo'<input type="submit" name="save_profile" value="'."Save".'" title="'."Save profile".'" />';
				echo'</nobr>';
			}
			{// load profile - btn
				echo'<nobr>';
					echo'<input type="submit" name="load_profile" value="'."Load".'" title="'."Load profile".'" />';
				echo'</nobr>';
			}
		echo'</form>';
		echo'</div>';// .filters

		$filter_hist = (isset($_SESSION['TREE-PROCESY']['filter_hist']))? $_SESSION['TREE-PROCESY']['filter_hist'] : array();
		if (!empty($filter_hist)) {
			echo'<form style="display:inline" action="" method="GET">';
			echo'<input type="hidden" name="task" value="'.App::get_task().'">';
			echo'<select name="filter_hist_id">';
				foreach ($filter_hist as $k => $v) {
					echo'<option value="'.$k.'">'.$v.'</option>';
				}//end foreach
			echo'</select>';
			echo'</form>';
		}

		$tree = new Tree( $tbl );
		$clbk = 'tree_callback__show_item_from_'.$tbl;
		$tree->set_param('show_item_callback', $clbk);
//TODO: add all filters from Filter - $tree_procesy_filter
		$tree->set_param('rozwin', ($tree_procesy_filter->get_arg('filtr_drzewo') == 'ROZWIN'));
		$tree->set_param('rozwin_proces', ($tree_procesy_filter->get_arg('filtr_procesy') == '+'));
		$tree->set_param('rozwin_zasoby', ($tree_procesy_filter->get_arg('filtr_zasoby') == '+'));
		$tree->set_param('rozwin_opis', ($tree_procesy_filter->get_arg('filtr_opis') == '+'));
		$tree->set_param('filtr_img', ($tree_procesy_filter->get_arg('filtr_img') == '+'));
		$tree->set_param('style', $tree_procesy_filter->get_arg('filtr_view'));
		$tree->set_param('search_id', $tree_procesy_filter->get_arg('filtr_search_id'));
		$tree->set_param('getZasobTableID', ProcesHelper::getZasobTableID('CRM_PROCES'));
		$tree->set_param('getZasobTableID_CRM_LISTA_ZASOBOW', ProcesHelper::getZasobTableID('CRM_LISTA_ZASOBOW'));
		$userAcl = User::getAcl();
		if($userAcl)
			$tblAcl = $userAcl->getTableAcl(ProcesHelper::getZasobTableID('CRM_PROCES'));
			if($tblAcl)
				if($tblAcl->hasFieldPerm($tblAcl->getFieldIdByName('ID'),'R')) $tree->set_param('hasFieldPerm__ID',1);


		//TODO: check perm to edit


		if ($tree_procesy_filter->is_trash()) $tree->set_param('is_trash', true);
		$tree->set_param('editable', ($tree_procesy_filter->get_arg('filtr_edit') == 'TAK'));
		if ($tree_procesy_filter->get_arg('filtr_ajax') == 'TAK') {
			$tree->_limit = 300;
			$tree->_deep_limit = 1;
		}
		if ($tree_procesy_filter->get_arg('filtr_id') != 0) {
			$tree->showSubTree( $tree_procesy_filter->get_arg('filtr_id') );
		} else if ($tree_procesy_filter->get_arg('filtr_search_id') > 0) {
			$tree->showSearchNode( $tree_procesy_filter->get_arg('filtr_search_id') );
		} else {
			$tree->show();
		}
	}
	else {
		echo'<pre>';
{

	echo'<table cellspacing="0" cellpadding="1">';
	echo'<tr>';
		echo'<td>';
			echo "DRZEWO ";
			if ($_SESSION['ZWIN_DRZEWO']) {
				echo App::link("ROZWIN", "?ROZWIN_DRZEWO=1#tree");
			} else {
				echo App::link("ZWIN", "?ZWIN_DRZEWO=1#tree");
			}
		echo'</td>';
		echo'<td>';
			echo "&nbsp;/&nbsp;";
		echo'</td>';
		echo'<td>';
			echo "PROCESY ";
			if ($_SESSION['ROZWIN']) {
				echo App::link("ZWIN", "?TREE_ZWIN=1#tree");
			} else {
				echo App::link("ROZWIN", "?TREE_ROZWIN=1#tree");
			}
		echo'</td>';
		echo'<td>';
			echo "&nbsp;/&nbsp;";
		echo'</td>';
		echo'<td>';
			echo "ZASOBY ";
			if ($_SESSION['ROZWIN_ZASOBY']) {
				echo App::link("ZWIN", "?TREE_ZASOBY_ZWIN=1#tree");
			} else {
				echo App::link("ROZWIN", "?TREE_ZASOBY_ROZWIN=1#tree");
			}
		echo'</td>';
		echo'<td>';
			echo "&nbsp;/&nbsp;";
		echo'</td>';
		echo'<td>';
			echo "OPISY ";
			if ($_SESSION['ROZWIN_OPIS']) {
				echo App::link("ZWIN", "?TREE_OPISY_ZWIN=1#tree");
			} else {
				echo App::link("ROZWIN", "?TREE_OPISY_ROZWIN=1#tree");
			}
		echo'</td>';
		echo'<td>';
			echo "&nbsp;/&nbsp;";
		echo'</td>';
		echo'<td>';
			$js = "window.location.href='#TREE'+this.form.id.value;return false;";
			echo '<form style="display:inline" action="#" method="GET">';
				echo "Proces ID: ";
				echo'<input type="text" name="id" value="" size="5" />';
				echo'<button onclick="'.$js.'">'."Wyszukaj ID".'</button>';
			echo'</form>'."\n";
		echo'</td>';
		echo'<td>';
			echo "&nbsp;/&nbsp;";
		echo'</td>';
		echo'<td>';
			echo'Widok ';
			echo App::link("NOWY", "?filtr_view=NOWY");
		echo'</td>';

	{
		echo'<td>';
			echo "&nbsp;/&nbsp;";
		echo'</td>';
		echo'<td>';

		echo'<form action="" method="GET" style="display:inline">';
			echo'<input type="hidden" name="'."task".'" value="'.App::get_task().'" />';
			echo'<nobr>';
				echo'<input type="submit" name="load_profile" value="'."Load".'" title="'."Load profile".'" />';
			echo'</nobr>';
		echo'</form>';

		echo'</td>';
	}
	echo'</tr>';
	echo'</table>';// btns
}

		tree_znajdz(0, 1, 0);
		echo'</pre>';
	}

if($DBG_TIME) $time_arr []= array(microtime(true), 'after Tree...');
if($DBG_TIME){
	$time_arr []= array(microtime(true), 'end');
	$last_time = 0;
	echo'<table style="color:#e0e0e0; text-align:left;">';
	foreach ($time_arr as $t) {
		echo'<tr>';
			echo'<td> </td>';
			echo'<td> </td>';
			echo'<td style="text-align:left;">'.number_format(($t[0] - $last_time), 6).'</td>';
		echo'</tr>';
		echo'<tr>';
			echo'<td>'.$t[0].'</td>';
			echo'<td>'.$t[1].'</td>';
			echo'<td> </td>';
		echo'</tr>';
		$last_time = $t[0];
	}//end foreach
	echo'</table>';
	//echo'<pre style="text-align:left;">';print_r($db);echo'</pre>';
	//echo'<pre style="text-align:left;">';print_r($_SERVER);echo'</pre>';
}

}


function fun_CRM_PROCES_ADD() {
	$redirect = "?task=".App::get_task();
	$msg = '';
	$sql_obj = new stdClass();
	$tbl_name = 'CRM_PROCES';

	Lib::loadClass('Column');
	$tbl_conf = Column::getInstance($tbl_name);
	if (!$tbl_conf) {
		return;
	}

	foreach ($tbl_conf->getFieldList() as $field_id => $field_name) {
		if ($tbl_conf->allowCreate($field_name)) {
			$post_arg_name = 'ADD_' . $field_name;
			if (isset($_POST[$post_arg_name])) {
				$sql_obj->$field_name = $_POST[$post_arg_name];
			}
		}
	}//end foreach

	// nowy na koniec listy
	$sql = "select max(t.`SORT_PRIO`) as MAX_SORT_PRIO
		from `CRM_PROCES` as t
		where
			t.`PARENT_ID`='".$sql_obj->PARENT_ID."'
	";
	$res = DB::query( $sql );
	while ($r = DB::fetch( $res )) {
		$sql_obj->SORT_PRIO = $r->MAX_SORT_PRIO + 1;
	}

	//TODO: post verify

	$new_id = DB::ADD_NEW_OBJ('CRM_PROCES', $sql_obj);

	if (V::get('DEBUG', '', $_SESSION)) App::add_msg("PASSED(1) NEW RECORD ID($new_id)");
	if ($new_id > 0) {
		App::add_msg("Dodano nowy rekord (ID ".$new_id.")");
		$redirect .= "&EDIT=".$new_id;
	}
	else {
		App::add_error("Error przy dodawaniu rekordu!");
	}
	App::redirect($redirect, $msg);
}


/**
 * @param $_POST['EDIT'] - ID rekordu
 */
function fun_CRM_PROCES_EDIT() {
	$redirect = "?task=".App::get_task();
	$msg = '';
	$sql_obj = new stdClass();
	$tbl_name = 'CRM_PROCES';

	$sql_obj->ID = V::get('EDIT_ID', '', $_POST, 'int');
	// TODO: fields can be hidden
	Lib::loadClass('Column');
	$tbl_conf = Column::getInstance($tbl_name);
	if (!$tbl_conf) {
		return;
	}

	foreach ($tbl_conf->getFieldList() as $field_id => $field_name) {
		if ($tbl_conf->allowWrite($field_name)) {
			$post_arg_name = 'EDIT_' . $field_name;
			if (isset($_POST[$post_arg_name])) {
				// TODO: convert field types?
				$sql_obj->$field_name = $_POST[$post_arg_name];
			}
		}
	}//end foreach

	$redirect .= "&EDIT=".$sql_obj->ID;

	//TODO: post verify

	$id = $sql_obj->ID;
	$affected = DB::UPDATE_OBJ( 'CRM_PROCES', $sql_obj );
	if (V::get('DEBUG', '', $_SESSION)) App::add_msg("PASSED($affected)");
	if ($affected == 2) {
		App::add_msg("Zmieniono rekord (ID ".$id.")");
	}
	else if ($affected == 1) {
		App::add_msg("Zmieniono rekord (ID ".$id.") (Error: nie zapisano hostorii)");
	}
	else if ($affected < 0) {
		App::add_error("Blad podczas edytowania rekordu - nic nie zmieniono");
	}

	App::redirect($redirect, $msg);
}


function fun_CRM_PROCES_clean_trash() {
	$db = DB::getDB();
	if (!$db) {
		echo '<p class="red">' . "No DB!" . '</p>';
		return;
	} else if ($db->has_errors()) {
		echo '<p>' . "Error DB: " . implode('<br />', $db->get_errors()) . '</p>';
		return;
	}
	$affected_total = 0;
	// remove all root trash items
	$sql = "update `CRM_PROCES` as p
		set p.`A_STATUS`='DELETED', p.`A_RECORD_UPDATE_AUTHOR`='TrashRemoveRec', p.`A_RECORD_UPDATE_DATE`=NOW()
		where p.`PARENT_ID`=-1 and p.`A_STATUS`!='DELETED'
	";
	$db->query($sql);
	$affected = $db->affected_rows();
	if ($affected) {
		$affected_total += $affected;
	}

	// remove all child trash items - run X times
	$loop_limit = 50;
	do {
		$sql = "update `CRM_PROCES` as p, `CRM_PROCES` as pp
			set p.`A_STATUS`='DELETED', p.`A_RECORD_UPDATE_AUTHOR`='TrashRemoveRec', p.`A_RECORD_UPDATE_DATE`=NOW()
			where p.`PARENT_ID`=pp.`ID` and (pp.`PARENT_ID`=-1 or pp.`A_STATUS`='DELETED') and p.`A_STATUS`!='DELETED'
		";
		$db->query($sql);
		$affected = $db->affected_rows();
		if ($affected) {
			$affected_total += $affected;
		}
	} while ($affected > 0 && --$loop_limit >= 0);

	echo '<p>' . "Usunięto " . $affected_total . " rekordów." . '</p>';
}
