<?php


function task_CRM_LISTA_ZASOBOW_test() {
	User_procesy5_check_access();

	$tbl = 'CRM_LISTA_ZASOBOW';

	//Column::init($tbl, true);// $tbl, force = true

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

	Lib::loadClass('Data_Source');
	Lib::loadClass('Table_View');

	$data_source = new Data_Source();// object cols, types, perms?; TODO: Data_Source, Data_Source_Proces, Data_Source_Zasob
	$data_source->set_table('CRM_LISTA_ZASOBOW');
	$data_source->set_cols($visible_cols);
	// set types and perms
	foreach ($visible_cols as $field_name) {
		$data_source->set_field_sql_type($field_name, $tbl_conf->type($field_name));
		$data_source->set_field_perm($field_name, $tbl_conf->perm($field_name));
	}
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">tbl_source: ';print_r($tbl_source);echo'</pre>';

	$tbl_view = new Table_View('tblView' . 'CRM_LISTA_ZASOBOW', $data_source);

	$tbl_view->set_base_url_params(array('task'=>App::get_task()));
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">tbl_view: ';print_r($tbl_view);echo'</pre>';

	$tbl_view->set_param('show_search', true);
	$tbl_view->set_param('url_param_source', $_GET);

	echo $tbl_view->to_html();
}


/**
 * @param $_GET['EDIT'] - ID rekordu do edycji (inline)
 * @param $_GET['EDIT_ID'] - ID rekordu do edycji (inline)
 */
function task_CRM_LISTA_ZASOBOW() {
	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_LISTA_ZASOBOW';

	//Column::init($tbl, true);// $tbl, force = true

	$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['PARENT_ID_ACCESS'] = 'P_ID2';
	$tbl_search_params['PARENT_ID_MAP'] = 'P_ID3';
	$tbl_search_params['ALIAS_ID'] = 'ALIAS_ID';
	$tbl_search_params['TYPE'] = 'TYPE';
	$tbl_search_params['DESC'] = 'DESC';
	$tbl_search_params['DESC_PL'] = 'DESC_PL';
	$tbl_search_params['OPIS'] = 'OPIS';
	$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['LOCALIZATION_INCLUDE'] = 'LOCALIZATION_INCLUDE';
	$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';
	$tbl_search_params['EXPORT_PARAM'] = 'EXPORT_PARAM';

	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_LISTA_ZASOBOW';
		$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_LISTA_ZASOBOW';

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

		{// zapisz stan - ajax function to save filters stan and opened tree nodes, etc.
			$filtr_ses_key = $tree_zasoby_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_zasoby_filter->_read_args( true );// force load args from session
			}
		}// zapisz stan - ajax function to save filters stan and opened tree nodes, etc.

		$tree_zasoby_filter->_save_args();// force save_args (executet at the end of show_filters)

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

	echo'<h1>';
		echo App::link("Zasoby", array('task'=>App::get_task(), 'filtr_id'=>''));
		if ($tree_zasoby_filter->is_trash()) {//$_GET['filtr_id'] == -1) {
			echo ' &raquo; '."Kosz";
			echo " " . App::link("czyść", array('task'=>App::get_task(), 'function_init'=>"fun_CRM_LISTA_ZASOBOW_clean_trash"), array('title'=>"Ustaw status rekord￳w w koszu na DELETED", 'class'=>'btn-p5', 'style'=>'font-size:13px;'));
		} else if ($tree_zasoby_filter->get_arg('filtr_id') > 0) {//$_GET['filtr_id'] > 0) {
			echo ' &raquo; '."Zasob [".$tree_zasoby_filter->get_arg('filtr_id')."]";
		}
	echo'</h1>';
		$userAcl = User::getAcl();
		$tblAcl = $userAcl->getTableAcl(ProcesHelper::getZasobTableID('CRM_LISTA_ZASOBOW'));
		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_LISTA_ZASOBOW'));
		echo "<br>".App::link("Dodaj nowy rekord", "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".ProcesHelper::getZasobTableID('CRM_LISTA_ZASOBOW')."#CREATE");

		
	} else {
	
			
	
			if (!$_SESSION['HIDE_ZASOBY']) {
				echo App::link("Ukryj Tabele", "?task=CRM_LISTA_ZASOBOW&HIDE_ZASOBY=1");
			} else {
				echo App::link("Pokaz Tabele", "?task=CRM_LISTA_ZASOBOW&UNHIDE_ZASOBY=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']['PARENT_ID_ACCESS'] = "P_ID2";
		$table_view['labels']['PARENT_ID_MAP'] = "P_ID3";
		$table_view['labels']['ALIAS_ID'] = "ALIAS_ID";
		$table_view['labels']['TYPE'] = "TYPE";
		$table_view['labels']['DESC'] = "DESC";
		$table_view['labels']['DESC_PL'] = "DESC_PL";
		$table_view['labels']['OPIS'] = "OPIS";
		$table_view['labels']['SORT_PRIO'] = "Sort Prio";
		$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']['EXPORT_PARAM'] = "EXPORT_PARAM";
		
		$table_view['head']['ID']= 'ID';
		$table_view['head']['PARENT_ID']= '<span class="P_ID">'."P_ID".'</span>';
		$table_view['head']['PARENT_ID_ACCESS']= '<nobr>';
		$table_view['head']['PARENT_ID_ACCESS'] .= '<span title="Elektryczne" class="P_ID_ACCESS">P_ID2</span>';
		if ($_SESSION['TREE_SHOW_P_ID2']) {
			$table_view['head']['PARENT_ID_ACCESS'] .= App::link("-", "?TREE_HIDE_P_ID2=1", array('title'=>"Ukryj na drzewie", 'class'=>"btn-p5 btn-small"));
		} else {
			$table_view['head']['PARENT_ID_ACCESS'] .= App::link("+", "?TREE_SHOW_P_ID2=1", array('title'=>"Pokaz na drzewie", 'class'=>"btn-p5 btn-small"));
		}
		$table_view['head']['PARENT_ID_ACCESS'] .= '</nobr>';
		$table_view['head']['PARENT_ID_MAP']= '<nobr>';
		$table_view['head']['PARENT_ID_MAP'] .= '<span title="Lokalizacyjne" class="P_ID_MAP">P_ID3 </span>';
		if ($_SESSION['TREE_SHOW_P_ID3']) {
			$table_view['head']['PARENT_ID_MAP'] .= App::link("-", "?TREE_HIDE_P_ID3=1", array('title'=>"Ukryj na drzewie", 'class'=>"btn-p5 btn-small"));
		} else {
			$table_view['head']['PARENT_ID_MAP'] .= App::link("+", "?TREE_SHOW_P_ID3=1", array('title'=>"Pokaz na drzewie", 'class'=>"btn-p5 btn-small"));
		}
		$table_view['head']['PARENT_ID_MAP'] .= '</nobr>';
		$table_view['head']['ALIAS_ID']= '<span title="ALIAS ID" class="'."ALIAS_ID".'">ALIAS</span>';
		$table_view['head']['TYPE']= 'TYPE';
		$table_view['head']['DESC']= 'DESC';
		$table_view['head']['DESC_PL']= 'DESC_PL';
		$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']['SORT_PRIO']= 'Sort Prio';
		$table_view['head']['EXPORT_PARAM']= 'Export?';
		
		$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']['PARENT_ID_ACCESS']= App::field_search( 'P_ID2', "varchar(255)", $_GET['P_ID2'], array('class'=>'i', 'size'=>5) );
		$table_view['find']['PARENT_ID_MAP']= App::field_search( 'P_ID3', "varchar(255)", $_GET['P_ID3'], array('class'=>'i', 'size'=>5) );
		$table_view['find']['ALIAS_ID']= App::field_search( 'ALIAS_ID', "varchar(255)", $_GET['ALIAS_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']['DESC_PL']= App::field_search( 'DESC_PL', "varchar(255)", $_GET['DESC_PL'], 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']['SORT_PRIO']= '&nbsp;';
		$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']['LOCALIZATION_INCLUDE'] = App::field_search( 'LOCALIZATION_INCLUDE', $tbl_conf->type('LOCALIZATION_INCLUDE'), $_GET['LOCALIZATION_INCLUDE'], 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']['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['find']['EXPORT_PARAM']= App::field_search( 'EXPORT_PARAM', $tbl_conf->type('EXPORT_PARAM'), $_GET['EXPORT_PARAM'], 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']['PARENT_ID_ACCESS'] = App::field( 'ADD_'.'PARENT_ID_ACCESS', "varchar(255)", V::get('ADD_'.'PARENT_ID_ACCESS', '', $_POST), array('class'=>'i', 'size'=>4) );
		$table_view['foot']['PARENT_ID_MAP'] = App::field( 'ADD_'.'PARENT_ID_MAP', "varchar(255)", V::get('ADD_'.'PARENT_ID_MAP', '', $_POST), array('class'=>'i', 'size'=>4) );
		$table_view['foot']['ALIAS_ID'] = App::field( 'ADD_'.'ALIAS_ID', "varchar(255)", V::get('ADD_'.'ALIAS_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', "varchar(255)", V::get('ADD_'.'DESC_PL', '', $_POST), array('class'=>'i', 'size'=>14) );
		$table_view['foot']['OPIS'] = App::field( 'ADD_'.'OPIS', "varchar(255)", V::get('ADD_'.'OPIS', '', $_POST), array('class'=>'i', 'size'=>20) );
		$table_view['foot']['EXPORT_PARAM'] = App::field( 'ADD_'.'EXPORT_PARAM', $tbl_conf->type('EXPORT_PARAM'), V::get('ADD_'.'EXPORT_PARAM', '', $_POST), array('class'=>'i', 'size'=>1) );
		//$table_view['foot']['SORT_PRIO'] = '<input type="text" name="ADD_SORT_PRIO" size=5 class="i" title="'."SORT PRIO".'" />';
		
		$ses_col_name = 'CRM_LISTA_ZASOBOW';
		
		echo'<table width="100%" 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_ZASOBY']) $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_LISTA_ZASOBOW` 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_LISTA_ZASOBOW'."&id=".$r->ID, array('target'=>'_blank', 'title'=>"Dodaj zdjecia"));
				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 ' '.App::link("OB", "?task=CRM_WYSWIETL_OBOWIAZKI&CLZ_ID=".$r->ID, array('target'=>'_blank', 'title'=>"Powiazania z procesami"));
							echo'<input type="hidden" name="function_init" value="'."fun_CRM_LISTA_ZASOBOW_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 {// not EDIT
				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 if ($field_name == 'PARENT_ID') {
						echo'<td>';
							if (User_is_admin()) {
								echo App::link(' '.$r->PARENT_ID, "?EDIT=".$r->PARENT_ID."#".$r->PARENT_ID, array('title'=>'Edytuj'));
							} else {
								echo $r->PARENT_ID;
							}
						echo'</td>';
					} else if ($field_name == 'PARENT_ID_ACCESS') {
						echo'<td>';
							$p_id2_links = array();
							$p_id2 = explode(',', $r->PARENT_ID_ACCESS);
							foreach ($p_id2 as $p_id) {
								$p_id2_links []= App::link($p_id, "?EDIT=".$p_id."#".$p_id);
							}//end foreach
							if (!empty($p_id2_links)) echo implode(', ', $p_id2_links);
						echo'</td>';
					} else if ($field_name == 'PARENT_ID_MAP') {
						echo'<td>';
							$p_id3_links = array();
							$p_id3 = explode(',', $r->PARENT_ID_MAP);
							foreach ($p_id3 as $p_id) {
								$p_id3_links []= App::link($p_id, "?EDIT=".$p_id."#".$p_id);
							}//end foreach
							if (!empty($p_id3_links)) echo implode(', ', $p_id3_links);
						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_LISTA_ZASOBOW_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 />';

// test ajax load table content
//TEST://	Lib::loadClass( 'AjaxReq' );
// load content from ajax function on load
//TEST://	$generate_uniq_ajax_req_id = AjaxReq::generate_id( 'CRM_LISTA_ZASOBOW', 'CRM_LISTA_ZASOBOW' );
//TEST: lub //	echo App::link_ajax_load_on_ready('flexigrid table zasoby', 'ajax_table', array('_ajax_req_id'=>$generate_uniq_ajax_req_id));


//if (V::get('EDIT', '', $_GET) > 0) {
//	echo'edycja - hide tree...';
//	return;
//}

echo'<br />';

	echo'<div id="tree"></div>';

	//if (isset($_SESSION['USER_PARAMS']['ZASOBY_TREE_TYPE_HTML']) && $_SESSION['USER_PARAMS']['ZASOBY_TREE_TYPE_HTML']) {
	if ($tree_zasoby_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_zasoby_filter->show_filters();
			// TODO: another form ? function_init ?
			{// save profile - btn-p5
				echo'<nobr>';
					echo'<input type="submit" name="save_profile" value="'."Save".'" title="'."Save profile".'" />';
				echo'</nobr>';
			}
			{// load profile - btn-p5
				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_zasoby_filter
		$tree->set_param('rozwin', ($tree_zasoby_filter->get_arg('filtr_drzewo') == 'ROZWIN'));
		$tree->set_param('filtr_ob', ($tree_zasoby_filter->get_arg('filtr_ob') == '+'));
		$tree->set_param('filtr_img', ($tree_zasoby_filter->get_arg('filtr_img') == '+'));
		$tree->set_param('rozwin_opis', ($tree_zasoby_filter->get_arg('filtr_opis') == '+'));
		$tree->set_param('filtr_ids', ($tree_zasoby_filter->get_arg('filtr_ids') == '+'));
		$tree->set_param('search_id', $tree_zasoby_filter->get_arg('filtr_search_id'));
		//TODO: editable tylko dla userow ktorzy maja uprawnienia
		$tree->set_param('getZasobTableID', ProcesHelper::getZasobTableID('CRM_LISTA_ZASOBOW'));

		$tree->set_param('editable', ($tree_zasoby_filter->get_arg('filtr_edit') == 'TAK'));
		
		//wykrywamy czy ma dostepny proces do jakiejs komorki w tej tabeli
		$userAcl = User::getAcl();
		$tblAcl = $userAcl->getTableAcl(ProcesHelper::getZasobTableID('CRM_LISTA_ZASOBOW'));
		if($tblAcl)
		if($tblAcl->hasFieldPerm($tblAcl->getFieldIdByName('ID'),'R')) $tree->set_param('hasFieldPerm__ID', true);
		
		if ($tree_zasoby_filter->is_trash()) $tree->set_param('is_trash', true);
		if ($tree_zasoby_filter->get_arg('filtr_ajax') == 'TAK') {
			$tree->_limit = 300;
			$tree->_deep_limit = 2;
		}
		if ($tree_zasoby_filter->get_arg('filtr_id') != 0) {
			$tree->showSubTree( $tree_zasoby_filter->get_arg('filtr_id') );
		} else if ($tree_zasoby_filter->get_arg('filtr_search_id') > 0) {
			$tree->showSearchNode( $tree_zasoby_filter->get_arg('filtr_search_id') );
		} else {
			$tree->show();
		}
	}
	else {

echo'<pre>';
	echo "DRZEWO ";
	if ($_SESSION['ZWIN_DRZEWO']) {
		echo App::link("ROZWIN", "?ROZWIN_DRZEWO=1#tree");
	} else {
		echo App::link("ZWIN", "?ZWIN_DRZEWO=1#tree");
	}
	echo " / ";

	if ($filter_show_sort_prio = V::get('TREE_ZASOBY_SORT_PRIO', '', $_REQUEST)) {
		if ($filter_show_sort_prio == 'SHOW') {
			$_SESSION['TREE-ZASOBY']['SORT_PRIO'] = 1;
		} else if ($filter_show_sort_prio == 'HIDE') {
			$_SESSION['TREE-ZASOBY']['SORT_PRIO'] = 0;
		}
	}
	echo "SORT PRIO ";
	if (V::get('SORT_PRIO', '', $_SESSION['TREE-ZASOBY'])) {
		echo App::link("UKRYJ", "?TREE_ZASOBY_SORT_PRIO=HIDE#tree");
	} else {
		echo App::link("POKAZ", "?TREE_ZASOBY_SORT_PRIO=SHOW#tree");
	}
	echo " / ";

	if ($filter_show_ids = V::get('TREE_ZASOBY_EXTERNAL_IDS', '', $_REQUEST)) {
		if ($filter_show_ids == 'SHOW') {
			$_SESSION['TREE-ZASOBY']['EXTERNAL_IDS'] = 1;
		} else if ($filter_show_ids == 'HIDE') {
			$_SESSION['TREE-ZASOBY']['EXTERNAL_IDS'] = 0;
		}
	}
	echo "IDS ";
	if (V::get('EXTERNAL_IDS', '', $_SESSION['TREE-ZASOBY'])) {
		echo App::link("UKRYJ", "?TREE_ZASOBY_EXTERNAL_IDS=HIDE#tree");
	} else {
		echo App::link("POKAZ", "?TREE_ZASOBY_EXTERNAL_IDS=SHOW#tree");
	}
	echo " / ";

	$show_filter_type = 0;
	if ($show_filter_type) {
		$selected_type = V::get('TREE_ZASOBY_FILTER_TYPE', V::get('FILTER_TYPE', '', $_SESSION['TREE-ZASOBY']), $_REQUEST);
		$_SESSION['TREE-ZASOBY']['FILTER_TYPE'] = $selected_type;

		$types = $_SESSION['CRM_LISTA_ZASOBOW_COLUMN']['TYPE']['TYPE'];
		$types = explode(',', str_replace(array("enum(",")","'"), '', $types));
		sort($types);
		array_unshift($types, '%');
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($types);echo'</pre>';
		echo"TYP: ";
		echo'<form action="" method="GET" style="display:inline">';
		echo'<input type="hidden" name="task" value="CRM_LISTA_ZASOBOW" />';
		echo'<select name="TREE_ZASOBY_FILTER_TYPE" onchange="this.form.submit();">';
		foreach ($types as $v) {
			$sel = ($selected_type == $v)? ' selected=selected"' : '';
			echo'<option value="'.$v.'"'.$sel.'>'.$v.'</option>';
		}//end foreach
		echo'</select>';
		echo'</form>';
		echo " / ";
	}

	$js = "window.location.href='#TREE'+this.form.id.value;return false;";
	echo '<form style="display:inline" action="#" method="GET">';
		echo "Zasob ID: ";
		echo'<input type="text" name="id" value="" />';
		echo'<button onclick="'.$js.'">'."Wyszukaj ID".'</button>';
	echo'</form>';

	echo " / ";

	echo'Widok ';
	echo App::link("NOWY", "?filtr_view=NOWY");

	{
		echo " / ";
		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 "\n";

	tree_listuj_zasoby(0,0,0);
echo'</pre>';

	}

}


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

	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_LISTA_ZASOBOW` 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_LISTA_ZASOBOW', $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'] - ID rekordu
 * function_init - params in $_POST, ends with redirect to task
 */
function fun_CRM_LISTA_ZASOBOW_EDIT() {
	$redirect = "?task=".App::get_task();
	$msg = '';
	$sql_obj = new stdClass();
	$tbl_name = 'CRM_LISTA_ZASOBOW';

	$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? EDIT_ALIAS_ID must be INT
				$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_LISTA_ZASOBOW', $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);
}


/**
 * @param $_GET['EDIT_ID'] - ID rekordu
 */
function task_CRM_LISTA_ZASOBOW_EDIT() {
	User_procesy5_check_access();

	global $error;

	$id = V::get('EDIT_ID', '', $_GET, 'int');
	if ($id <= 0) {
		echo'<p class="err">'."Wrong ID".'</p>';
		return;
	}

	$r = DB::get_by_id( 'CRM_LISTA_ZASOBOW', $id );
	if (!$r) {
		echo'<p class="err">'."Wrong ID - not exists".'</p>';
		return;
	}

//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($r);echo'</pre>';

	echo'<h1>';
		echo App::link("LISTA ZASOBOW", "?task=CRM_LISTA_ZASOBOW");
		echo' - ';
		echo "Edycja zasobu [".$r->ID."]";
	echo'</h1>';

	echo App::link("IMG", "?function_init=fun_IMAGE_ADD&tbl=".'CRM_LISTA_ZASOBOW'."&id=".$r->ID, array('target'=>'_blank', 'title'=>"Dodaj zdjecia"));
	echo ' '.App::link("OB", "?task=CRM_WYSWIETL_OBOWIAZKI&CLZ_ID=".$r->ID, array('target'=>'_blank', 'title'=>"Powiazania z procesami"));
	echo '<br /><br />';

	echo'<form action="" method="POST">';
		echo'<input type="hidden" name="function_init" value="'."fun_CRM_LISTA_ZASOBOW_EDIT".'">';
		echo'<input type="hidden" name="task" value="'.App::get_task().'">';
		echo'<input type="hidden" name="EDIT_ID" value="'.$r->ID.'">';
		//echo ' '.App::link("L", "#TREE".$r->PARENT_ID);
	echo'<table width="100%" border="1" cellspacing="0" cellpadding="0" class="tbl-view">';
	echo'<tbody>';
	$t = 0;
	echo'<tr class="row-'.($t = 1 - $t).'">';
		echo'<th>'."P_ID".'</th>';
		echo'<td>';
			echo App::field( 'EDIT_PARENT_ID', $_SESSION['CRM_LISTA_ZASOBOW_COLUMN']['TYPE']['PARENT_ID'], $r->PARENT_ID, array('class'=>'i') );
		echo'</td>';
	echo'</tr>';
	echo'<tr class="row-'.($t = 1 - $t).'">';
		echo'<th>'."P_ID2".'</th>';
		echo'<td>';
			echo App::field( 'EDIT_PARENT_ID_ACCESS', $_SESSION['CRM_LISTA_ZASOBOW_COLUMN']['TYPE']['PARENT_ID_ACCESS'], $r->PARENT_ID_ACCESS, array('class'=>'i') );
		echo'</td>';
	echo'</tr>';
	echo'<tr class="row-'.($t = 1 - $t).'">';
		echo'<th>'."P_ID3".'</th>';
		echo'<td>';
			echo App::field( 'EDIT_PARENT_ID_MAP', $_SESSION['CRM_LISTA_ZASOBOW_COLUMN']['TYPE']['PARENT_ID_MAP'], $r->PARENT_ID_MAP, array('class'=>'i') );
		echo'</td>';
	echo'</tr>';
	echo'<tr class="row-'.($t = 1 - $t).'">';
		echo'<th>'."ALIAS_ID".'</th>';
		echo'<td>';
			echo App::field( 'EDIT_ALIAS_ID', $_SESSION['CRM_LISTA_ZASOBOW_COLUMN']['TYPE']['ALIAS_ID'], $r->ALIAS_ID, array('class'=>'i') );
		echo'</td>';
	echo'</tr>';
	echo'<tr class="row-'.($t = 1 - $t).'">';
		echo'<th>'."TYPE".'</th>';
		echo'<td>';
			echo App::field( 'EDIT_TYPE', $_SESSION['CRM_LISTA_ZASOBOW_COLUMN']['TYPE']['TYPE'], $r->TYPE, array('class'=>'i') );
		echo'</td>';
	echo'</tr>';
	echo'<tr class="row-'.($t = 1 - $t).'">';
		echo'<th>'."DESC".'</th>';
		echo'<td>';
			echo App::field( 'EDIT_DESC', $_SESSION['CRM_LISTA_ZASOBOW_COLUMN']['TYPE']['DESC'], $r->DESC, array('class'=>'i') );
		echo'</td>';
	echo'</tr>';
	echo'<tr class="row-'.($t = 1 - $t).'">';
		echo'<th>'."OPIS".'</th>';
		echo'<td>';
			echo App::field( 'EDIT_OPIS', $_SESSION['CRM_LISTA_ZASOBOW_COLUMN']['TYPE']['OPIS'], $r->OPIS, array('class'=>'i') );
		echo'</td>';
	echo'</tr>';
	echo'<tr class="row-'.($t = 1 - $t).'">';
		echo'<th>'."SORT_PRIO".'</th>';
		echo'<td>';
			echo App::field( 'EDIT_SORT_PRIO', $_SESSION['CRM_LISTA_ZASOBOW_COLUMN']['TYPE']['SORT_PRIO'], $r->SORT_PRIO, array('class'=>'i') );
		echo'</td>';
	echo'</tr>';
	echo'<tr class="row-'.($t = 1 - $t).'">';
		echo'<th>'."IP_ADDRESS".'</th>';
		echo'<td>';
			echo App::field( 'EDIT_IP_ADDRESS', $_SESSION['CRM_LISTA_ZASOBOW_COLUMN']['TYPE']['IP_ADDRESS'], $r->IP_ADDRESS, array('class'=>'i') );
		echo'</td>';
	echo'</tr>';
	echo'<tr class="row-'.($t = 1 - $t).'">';
		echo'<th>'."DNS_ADDRESS".'</th>';
		echo'<td>';
			echo App::field( 'EDIT_DNS_ADDRESS', $_SESSION['CRM_LISTA_ZASOBOW_COLUMN']['TYPE']['DNS_ADDRESS'], $r->DNS_ADDRESS, array('class'=>'i') );
		echo'</td>';
	echo'</tr>';
	echo'</tbody>';
	echo'</table>';

	echo'<input type="submit" name="EDIT_SUBMIT" value="'."Zapisz".'" title="'."Zapisz".'">';

	echo'</form>';

}


function fun_CRM_LISTA_ZASOBOW_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_LISTA_ZASOBOW` as z
		set z.`A_STATUS`='DELETED', z.`A_RECORD_UPDATE_AUTHOR`='TrashRemoveRec', z.`A_RECORD_UPDATE_DATE`=NOW()
		where z.`PARENT_ID`=-1 and z.`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_LISTA_ZASOBOW` as z, `CRM_LISTA_ZASOBOW` as zz
			set z.`A_STATUS`='DELETED', z.`A_RECORD_UPDATE_AUTHOR`='TrashRemoveRec', z.`A_RECORD_UPDATE_DATE`=NOW()
			where z.`PARENT_ID`=zz.`ID` and (zz.`PARENT_ID`=-1 or zz.`A_STATUS`='DELETED') and z.`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>';
}
