<?php

Lib::loadClass('ProcesHelper');
Lib::loadClass('DebugExecutionTime');
Lib::loadClass('UI');

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

	UI::setTitleJsTag("⋋ Procesy (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_PROCES';

	$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['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]);
		}

		// 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_PROCES';

		Lib::loadClass('FilterFactory');
		$tree_procesy_filter = FilterFactory::build($tbl);
		$tree_procesy_filter->setArgs($_GET);
		$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);
		}
		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>';

	UI::startTag('ul', ['class' => "breadcrumb"]);
		UI::startTag('li');
			UI::tag('a', ['href'=>"index.php?_route=ViewTableAjax&namespace=default_db/CRM_PROCES"], "Tabela Procesy <i style=\"color:silver\">(CRM_PROCES)</i>");
		UI::endTag('li');
		UI::startTag('li');
			UI::tag('a', ['href'=>"index.php?_route=ViewTableAjax&namespace=default_db/CRM_PROCES#CREATE"], "<span class=\"glyphicon glyphicon-plus\"></span> Dodaj nowy rekord");
		UI::endTag('li');
	UI::endTag('ul');

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

	session_write_close();// End the current session and store session data. Below $_SESSION is read-only.
	$dbgExecTime->log('show...');

	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();
			{// 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>';
				}
			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);

		$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('ProcesTblId', ProcesHelper::getZasobTableID('CRM_PROCES'));
		$tree->set_param('ZasobTblId', ProcesHelper::getZasobTableID('CRM_LISTA_ZASOBOW'));
		$tree->set_param('WskaznikTblId', ProcesHelper::getZasobTableID('CRM_WSKAZNIK'));

		$tblPytaniaId = ProcesHelper::getZasobTableID('CRM_TESTY_PYTANIA');
		if ($tblPytaniaId > 0) {
			$userAcl = User::getAcl();
			$userAcl->fetchGroups();
			if ($userAcl->hasTableAcl($tblPytaniaId)) {
				$tblAcl = $userAcl->getTableAcl($tblPytaniaId);
				$tblAcl->init($forceTblAclInit = false);
				$tree->set_param('HasAclPytaniaTbl', true);
			}
			$tree->set_param('PytaniaTblId', $tblPytaniaId);
		}

		//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') );
			$dbgExecTime->log('done tree->showSubTree()');
		} else if ($tree_procesy_filter->get_arg('filtr_search_id') > 0) {
			$tree->showSearchNode( $tree_procesy_filter->get_arg('filtr_search_id') );
			$dbgExecTime->log('done tree->showSearchNode()');
		} else {
			$tree->show();
			$dbgExecTime->log('done 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){
		$dbgExecTime->log('end');
		$dbgExecTime->printDebug();
	}

}


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