<?php

Lib::loadClass('UI');

/**
 * @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();

	UI::setTitleJsTag("⋋ Zasoby (drzewo)");
	$_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';

	$DBG_TIME = ('1' == V::get('DBG_TIME', '', $_GET));
	$dbgExecTime = new DebugExecutionTime();
	if ($DBG_TIME) $dbgExecTime->activate();
	$dbgExecTime->log('start');

	// 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]);
		}

		// 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];
			}
		}

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

		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;
		}
		echo'</div>';
	}// TABLE - Filter

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

		Lib::loadClass('FilterFactory');
		$tree_zasoby_filter = FilterFactory::build($tbl);
		$tree_zasoby_filter->setArgs($_GET);
		$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);
		}
		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 && $tblAcl->hasFieldPerm($tblAcl->getFieldIdByName('ID'),'R')) {
		UI::startTag('ul', ['class' => "breadcrumb"]);
			UI::startTag('li');
				UI::tag('a', ['href'=>"index.php?_route=ViewTableAjax&namespace=default_db/CRM_LISTA_ZASOBOW"], "Tabela Zasoby <i style=\"color:silver\">(CRM_LISTA_ZASOBOW)</i>");
			UI::endTag('li');
			UI::startTag('li');
				UI::tag('a', ['href'=>"index.php?_route=ViewTableAjax&namespace=default_db/CRM_LISTA_ZASOBOW#CREATE"], "<span class=\"glyphicon glyphicon-plus\"></span> Dodaj nowy rekord");
			UI::endTag('li');
		UI::endTag('ul');
	}

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

	$dbgExecTime->log('show...');

	//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>';
				}
			echo'</select>';
			echo'</form>';
		}

		$tree = new Tree( $tbl );
		$tree->setProfiler($dbgExecTime);
		$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 && $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>';
		}
		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>';

	}

	if($DBG_TIME){
		$dbgExecTime->log('end');
		$dbgExecTime->printDebug();
	}

}


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