<?php


if (!class_exists('Lib')) die('404');


function tree_znajdz( $PARENT, $POZIOM, $LAST ) {
	global $TREE;

	$SQL2 = "select * from `CRM_PROCES`
		where
			`PARENT_ID` like '".$PARENT." %' or `PARENT_ID` like '% ".$PARENT." %' or `PARENT_ID` like '% ".$PARENT."' or `PARENT_ID` like '".$PARENT."'
		order by `SORT_PRIO` asc, `ID` asc
	";
	$result2 = DB::query($SQL2); $result2_numrows = DB::num_rows($result2);

	$lp = 0;
	while ($res2 = DB::fetch_array( $result2 )) {
		$lp++;
		if ($lp == $result2_numrows) $LLAST = 1; else $LLAST = 0;
		if ($LLAST) $TREE[$POZIOM]="   "; else $TREE[$POZIOM] = " | ";

		if (!$LLAST) {
			$cnt = 0;
			while ($cnt <= $POZIOM) {
				if ($cnt != $POZIOM) echo V::get("$cnt", '', $TREE); else {
					if ($TREE[$cnt]==" | ") echo " | ";
					else echo " | ";
				}
				$cnt++;
			}
			echo "\n"; 
		}

		$cnt = 0;
		while ($cnt <= $POZIOM) {
			//if($cnt<>$POZIOM) echo $TREE["$cnt"]; else {
			//	if($TREE[$cnt]==" | ") echo " +==";
			//	else echo " \\==";
			//}
			//$cnt++;
			if ($cnt != $POZIOM) echo V::get("$cnt", '', $TREE); else {
				if ($TREE[$cnt] == " | ") {
					if (!$_SESSION['ZWIN_DRZEWO']) echo " +-";
					else {
						echo' ';
						if (isset($_SESSION['TREE_OPEN_ARRAY'][$res2['ID']]) && $_SESSION['TREE_OPEN_ARRAY'][$res2['ID']]) {
							echo App::link("--", "?TREE_CLOSE=".$res2['ID']."#tree");
						} else {
							echo App::link("-+", "?TREE_OPEN=".$res2['ID']."#tree");
						}
						echo' ';
					}
				}
				else {
					if (!$_SESSION['ZWIN_DRZEWO']) echo " \\-";
					else {
						echo' ';
						if (isset($_SESSION['TREE_OPEN_ARRAY'][$res2['ID']]) && $_SESSION['TREE_OPEN_ARRAY'][$res2['ID']]) {
							echo App::link("\\-", "?TREE_CLOSE=".$res2['ID']."#tree");
						} else {
							echo App::link("\\+", "?TREE_OPEN=".$res2['ID']."#tree");
						}
						echo' ';
					}
				}
			}
			$cnt++;
		}
		echo '<span style="color:red">'."[ ";
			echo App::link("^", array('function_init'=>'SORT_PRIO_PROCES', 'arg1'=>$res2['ID'], 'arg1_val'=>'up'), array('class'=>"btn-clean", 'title'=>"w gore"));
			echo App::link("v", array('function_init'=>'SORT_PRIO_PROCES', 'arg1'=>$res2['ID'], 'arg1_val'=>'dw'), array('class'=>"btn-clean", 'title'=>"w dol"));
			echo "<b>";
				echo '<span id="TREE'.$res2['ID'].'"> '.$res2['ID'].'</span> ';
				echo App::link("E", "?EDIT=".$res2['ID']."&ID=".$res2['ID']."#".$res2['ID'], array('title'=>"Edytuj ".$res2['ID']));
				echo ' '.$res2['DESC'];
			echo '</b> ]</span> ';
			echo App::link("Z+", "?task=ADD_PROCES_ID&id=".$res2['ID'], array('target'=>'_blank'));
			if ($_SESSION['ROZWIN_OPIS']) echo ' <span style="color:#222;font-weight:normal;">'.$res2['OPIS'].'</span>';
			echo ' '."\n";
		if ($POZIOM > 200) die("problem petli L" . __LINE__);
		if ((!$_SESSION['ZWIN_DRZEWO'])||(isset($_SESSION['TREE_OPEN_ARRAY'][$res2['ID']]) && $_SESSION['TREE_OPEN_ARRAY'][$res2['ID']])) {
			tree_znajdz_zasoby2($res2['ID'], $POZIOM + 1, $LAST);
			tree_znajdz($res2['ID'], $POZIOM + 1, $LLAST);
		}
	}
}


function tree_znajdz_zasoby2( $PARENT, $POZIOM, $LAST ) {
	global $TREE;

	$SQL2 = "select
			clz.*
			, cw.`ID` as CW_ID, cw.`TYP` as CW_TYP, cw.`OPIS_ZASOB` as OPIS_ZASOB
			, cp.`PYTANIE` as CP_PYTANIE
		from `CRM_WSKAZNIK` as cw
			left join `CRM_LISTA_ZASOBOW` as clz on (clz.`ID`=cw.`ID_ZASOB`)
			left join `CRM_PRZYPADEK` as cp on (cp.`ID`=cw.`ID_PRZYPADEK`)
		where
			cw.`ID_PROCES`='".$PARENT."'
			and cw.`A_STATUS` in('WAITING','NORMAL','MONITOR')
		order by cw.`SORT_PRIO`, cw.`ID`
	";
	$result2 = DB::query( $SQL2 );
	if (!$result2) die("error query $SQL2");
	$result2_numrows = DB::num_rows( $result2 );

	$lp = 0;
	$slowa = array();
	while ($res2 = DB::fetch_array( $result2 )) {
		$lp++;
		if ($lp == $result2_numrows) $LLAST = 1; else $LLAST = 0;
		if ($LLAST) $TREE[$POZIOM] = "   "; else $TREE[$POZIOM] = " | ";
		$pyt = '';
		switch ($res2['CW_TYP']) {
			case "C": $pyt = "CO ROBI"; break;
			case "R": if ($res2['CP_PYTANIE']) $pyt = $res2['CP_PYTANIE']; break;
		}
		if ($_SESSION['ROZWIN_OPIS']) {
			$slowa[$pyt][] = "(".$res2['OPIS_ZASOB'].")"."[".$res2['ID']."]".$res2['DESC'];
		} else {
			$slowa[$pyt][] = $res2['DESC'];
		}

		if ($_SESSION['ROZWIN']) {
			$cnt = 0;
			while ($cnt <= $POZIOM) {
				if ($cnt != $POZIOM) {
					if (isset($TREE["$cnt"])) echo $TREE["$cnt"];
				} else {
					echo ' | ';
					echo App::link("^", "?function_init=SORT_PRIO_WSKAZNIK&arg1=".$res2['CW_ID']."&arg1_val=up", array('class'=>"btn-clean", 'title'=>"w gore"));
					echo App::link("v", "?function_init=SORT_PRIO_WSKAZNIK&arg1=".$res2['CW_ID']."&arg1_val=dw", array('class'=>"btn-clean", 'title'=>"w dol"));
					echo'-';
				}
				$cnt++;
			}
			echo '<font color="green">'."[ ";
				echo $res2['ID'];
				echo' ';
				echo App::link("E", "?task=CRM_EDIT_CRM_WSKAZNIK&EDIT=".$res2['CW_ID']."&ID=".$res2['CW_ID'], array('title'=>"Edytuj wskaznik ".$res2['CW_ID']));
				echo " [".$pyt."] ";
				echo '<b>'.$res2['TYPE'].'</b>';
				echo ' '.$res2['DESC'];
			echo " ]".'</font> ';
			echo App::link("Z-", "?task=CRM_DEL_CRM_WSKAZNIK&ID=".$res2['CW_ID']);
			if ($_SESSION['ROZWIN_OPIS']) {
				if ($res2['OPIS_ZASOB']) echo' <span style="color:#111;">'.$res2['OPIS_ZASOB'].'</span>';
				if ($res2['OPIS']) echo' <span style="color:#666;">'.$res2['OPIS'].'</span>';
			}
			echo' ';
			if ($_SESSION['ROZWIN_ZASOBY']) tree_trasuj_zasoby2($res2['PARENT_ID'], $POZIOM + 1, $LLAST);// zasoby rekurencyjnie w gore
			echo "\n";
		}
	}

 	$typy = Array("KTO CO","CO ROBI","KOGO CO","KOGO CZEGO","KOMU CZEMU","KIM CZYM","O KIM O CZYM");
	$zdanie = '';
	if (!empty($slowa)) {
		foreach ($typy as $typ) {
			if (!empty($slowa["$typ"])) foreach ($slowa["$typ"] as $slowo) {
				$zdanie .= "[".$typ."] ".$slowo." ";
			}
		}
	}
	if ($zdanie) {
		$cnt = 0;
		while ($cnt <= $POZIOM) {
			if ($cnt != $POZIOM) echo V::get("$cnt", '', $TREE); else {
				if ($TREE[$cnt] == " | ") echo " |<b> ^--</b>";
				else echo " \<b>====</b>";
			}
			$cnt++;
		}							
		echo $zdanie." \n";
	}
}


function tree_znajdz_zasoby($PARENT, $POZIOM, $LAST) {
  global $TREE;

  $SQL2 = "select
			CLZ.*
			, CW.ID as CW_ID
		from CRM_WSKAZNIK as CW
			left join CRM_LISTA_ZASOBOW as CLZ on (CLZ.ID=CW.ID_ZASOB)
		where
			CW.ID_PROCES='".$PARENT."'
			and CW.`A_STATUS` in('WAITING','NORMAL','MONITOR')
	";
	$result2 = DB::query( $SQL2 ); $result2_numrows = DB::num_rows( $result2 );

	$lp = 0;
	while ($res2 = DB::fetch_array( $result2 )) {
		$lp++;
		if ($lp == $result2_numrows) $LLAST = 1; else $LLAST = 0;
		if ($LLAST) $TREE[$POZIOM] = "   "; else $TREE[$POZIOM] = " | ";
		$cnt = 0;
		while ($cnt <= $POZIOM) {
			if ($cnt != $POZIOM) echo $TREE["$cnt"]; else {
				if ($TREE[$cnt] == " | ") echo " +==";
				else echo " \\==";
			}
			$cnt++;
		}
		echo '<font color="green">'."[ ".$res2['ID']." ".$res2['DESC']." ]".'</font> ';
		echo App::link("Z-", "?task=CRM_DEL_CRM_WSKAZNIK&ID=".$res2['CW_ID'], array('target'=>'_blank'));
		echo "\n";
		tree_trasuj_zasoby($res2['PARENT_ID'], $POZIOM + 1, $LLAST);
	}
}


function tree_trasuj_zasoby($PARENT, $POZIOM, $LAST) {
	global $TREE ;

	$SQL2 = "select CLZ.* from CRM_LISTA_ZASOBOW as CLZ where CLZ.ID='".$PARENT."'";
	$result2 = DB::query( $SQL2 );
	$result2_numrows = DB::num_rows( $result2 );

	$lp = 0;
	while ($res2 = DB::fetch_array( $result2 )) {
		$lp++;
		if ($lp == $result2_numrows) $LLAST = 1; else $LLAST = 0;
		if ($LLAST) $TREE[$POZIOM] = "   "; else $TREE[$POZIOM] = " | ";

		if (!$LLAST) {
			$cnt = 0;
			while ($cnt <= $POZIOM) {
				if ($cnt != $POZIOM) echo $TREE["$cnt"]; else {
					if ($TREE[$cnt] == " | ") echo " | ";
					else echo " | ";
				}
				$cnt++;
			}
			echo "\n"; 
		}

		$cnt = 0;
		while ($cnt <= $POZIOM) {
			if ($cnt != $POZIOM) echo $TREE["$cnt"]; else {
				if ($TREE[$cnt] == " | ") echo " +-";
				else echo " \\-";
			}
			$cnt++;
		}
		echo ""."<font color=magneta>[ $res2[0] $res2[3] $res2[4] ]</font> \n"; 
		tree_trasuj_zasoby($res2['PARENT_ID'], $POZIOM + 1, $LAST);
	}
}


function tree_trasuj_zasoby2($PARENT, $POZIOM, $LAST) {
	global $TREE ;

	$SQL2 = "select CLZ.* from CRM_LISTA_ZASOBOW as CLZ where CLZ.ID='".$PARENT."'";
	$result2 = DB::query( $SQL2 );
	$result2_numrows = DB::num_rows( $result2 );

	$lp = 0;
	while ($res2 = DB::fetch_array( $result2 )) {
		$lp++;
		$LLAST = ($lp == $result2_numrows);
		if ($LLAST) $TREE[$POZIOM] = "   "; else $TREE[$POZIOM] = " | ";
		echo ""."<font color=\"#aaa\">[ ".$res2['ID']." <b>".$res2['TYPE']."</b> ".$res2['DESC']." ]</font><b>/</b>";
		tree_trasuj_zasoby2($res2['PARENT_ID'], $POZIOM + 1, $LAST);
	}
}


function tree_listuj_zasoby($PARENT, $POZIOM, $LAST) {
	global $TREE;

	$sql = new stdClass();
	$sql->filter = array();
	$sql->filter[] = "(z.`PARENT_ID`='".$PARENT."')";
	if ($_SESSION['TREE_SHOW_P_ID2'] || $_SESSION['TREE_SHOW_P_ID3']) {
		if ($_SESSION['TREE_SHOW_P_ID2']) {
			$sql->filter[] = "(FIND_IN_SET('".$PARENT."', z.`PARENT_ID_ACCESS`) > 0)";
		}
		if ($_SESSION['TREE_SHOW_P_ID3']) {
			$sql->filter[] = "(FIND_IN_SET('".$PARENT."', z.`PARENT_ID_MAP`) > 0)";
		}
	}
	$sql->where = implode(" or ", $sql->filter);
	$sql->select_parent = "
		IF( z.`PARENT_ID`='".$PARENT."'
			, 'P_ID'
			, IF( (FIND_IN_SET('".$PARENT."', z.`PARENT_ID_ACCESS`) > 0)
				, 'P_ID_ACCESS'
				, IF( (FIND_IN_SET('".$PARENT."', z.`PARENT_ID_MAP`) > 0)
					, 'P_ID_MAP'
					, 'P_ID_UNKNOWN'
				)
			)
		) as PARENT_TYPE
	";

	$show_external_ids = V::get('EXTERNAL_IDS', 0, $_SESSION['TREE-ZASOBY']);

	$result_ext_ids_names = array();
	if (V::get('task', '', $_GET) == 'ADD_PROCES_ID' || !$show_external_ids) {
		$SQL2 = "select z.*
				, ".$sql->select_parent."
			from `CRM_LISTA_ZASOBOW` as z
			where ".$sql->where."
			order by z.`SORT_PRIO`, z.`ID`
		";
	} else {
		$sql->cols = array();
		$sql->add_left_join = array();
		$sql->cols[] = "z.*";
		$sql->cols[] = $sql->select_parent;

		$cnf = Config::getConfFile('external_ids');
		if ($cnf) {
			if (!empty($cnf)) {
				//$sql->cols[] = "group_concat(D.T_DEVICE_SERIAL) as DEVICES_IDS";
				//$sql->cols[] = "group_concat(T.T_TELBOX_NAME) as TELBOXES_IDS";

				//$sql->add_left_join[] = "left join DEVICES as D on D.CRM_LISTA_ZASOBOW_ID=z.ID";
				//$sql->add_left_join[] = "left join TELBOXES as T on T.CRM_LISTA_ZASOBOW_ID=z.ID";

				$external_tbls = array();
				foreach ($cnf as $k_table_name => $v_cnf) {
					$cur_cnf = new stdClass();
					$cur_cnf->table_name = $k_table_name;
					$cur_cnf->id_col = V::get('id_col', 'ID', $v_cnf);
					$cur_cnf->allowed_cols = V::get('allowed_cols', '', $v_cnf);
					$cur_cnf->search_col = V::get('search_col', 'CRM_LISTA_ZASOBOW_ID', $v_cnf);
					$cur_cnf->search_col_regex = V::get('search_col_regex', '', $v_cnf);
					$sql_id_col = $cur_cnf->id_col;
					$cur_cnf->sql = "";

					$result_ext_ids_name = $cur_cnf->table_name."_EXT_IDS";
					$result_ext_ids_names[] = $result_ext_ids_name;
					$sql->cols[] = "group_concat(`".$cur_cnf->table_name."`.`".$cur_cnf->id_col."`) as ".$result_ext_ids_name;

					$sql_left_join = "left join `".$cur_cnf->table_name."` on `".$cur_cnf->table_name."`.`".$cur_cnf->search_col."`";
					if ($cur_cnf->search_col_regex) {
						$sql_left_join .= " like '".str_replace('$ID', 'z.ID', $cur_cnf->search_col_regex)."'";
					} else {
						$sql_left_join .= "=z.ID";
					}
					$sql->add_left_join[] = $sql_left_join;
				}
			}
		}

		$SQL2 = "select
				".implode(",", $sql->cols)."
			from `CRM_LISTA_ZASOBOW` as z
				".implode("\n", $sql->add_left_join)."
			where ".$sql->where."
			group by z.ID
			order by z.`SORT_PRIO`, z.`ID`
		";
	}
	$res = DB::query( $SQL2 );
	if (!$res) die("sql: \n$SQL2");
	$numrows = DB::num_rows( $res );
	if (isset($_GET['DBG']) && $_GET['DBG']) {
		echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;display:none;">sql P_ID('.$PARENT.')';print_r($SQL2);echo'</pre>';
	}

	$lp = 0;
	while ($r = DB::fetch( $res )) {
		if (!empty($result_ext_ids_names)) {
			$r->external_IDS = array();
			foreach ($result_ext_ids_names as $v_ext_ids_name) {
				if (!empty($r->$v_ext_ids_name)) {
					$external_IDS = explode(',', $r->$v_ext_ids_name);
					foreach ($external_IDS as $v_ext_id) {
						if ($v_ext_id) $r->external_IDS[] = $v_ext_id;
					}
				}
			}
			$r->external_IDS = implode(',', $r->external_IDS);
		}
		$lp++;
		$LLAST = ($lp == $numrows)? 1 : 0;
		$TREE[$POZIOM] = ($LLAST)? "   " : " | ";

		$cnt = 0;
		while ($cnt <= $POZIOM) {
			if ($cnt != $POZIOM) {
				echo $TREE["$cnt"];
			} else {
				if ($TREE[$cnt] == " | ") {
					if (!$_SESSION['ZWIN_DRZEWO']) echo " +-";
					else {
						echo' ';
						if (!empty($_SESSION['TREE_OPEN_ARRAY'][$r->ID]) && $_SESSION['TREE_OPEN_ARRAY'][$r->ID]) {
							echo App::link("--", "?TREE_CLOSE=".$r->ID."#tree");
						} else {
							echo App::link("-+", "?TREE_OPEN=".$r->ID."#tree");
						}
						echo' ';
					}
				}
				else {
					if (!$_SESSION['ZWIN_DRZEWO']) echo " \\-";
					else {
						echo' ';
						if (!empty($_SESSION['TREE_OPEN_ARRAY'][$r->ID]) && $_SESSION['TREE_OPEN_ARRAY'][$r->ID]) {
							echo App::link("\\-", "?TREE_CLOSE=".$r->ID."#tree");
						} else {
							echo App::link("\\+", "?TREE_OPEN=".$r->ID."#tree");
						}
						echo' ';
					}
				}
			}
			$cnt++;
		}
		if (V::get('task', '', $_GET) == 'CRM_LISTA_ZASOBOW') {
			//echo'('.$r->SORT_PRIO.')';// TODO: DBG
			if ($r->PARENT_TYPE == 'P_ID') {
				echo App::link("^", array('function_init'=>'SORT_PRIO_ZASOB', 'arg1'=>$r->ID, 'arg1_val'=>'up'), array('class'=>"btn-clean", 'title'=>"w gore"));
				echo App::link("v", array('function_init'=>'SORT_PRIO_ZASOB', 'arg1'=>$r->ID, 'arg1_val'=>'dw'), array('class'=>"btn-clean", 'title'=>"w dol"));
			} else {
				echo'--';
			}
			if (V::get('SORT_PRIO', '', $_SESSION['TREE-ZASOBY'])) {
				echo'('.$r->SORT_PRIO.')';
			}
		} else if (V::get('task', '', $_GET) == 'ADD_PROCES_ID') {
			echo'<b>';
			echo App::link("(DODAJ do proc.# ".$_GET['id'].")", "?task=CRM_ADD_CRM_WSKAZNIK&ADD_ID_ZASOB=".$r->ID."&ADD_ID_PROCES=".$_GET['id']);
			echo'</b>';
		}
		
		echo '<span class="'.(($r->ALIAS_ID > 0)? 'ALIAS_ID' : $r->PARENT_TYPE).'">[ ';
			echo '<span'.(($r->PARENT_TYPE == 'P_ID')? ' id="TREE'.$r->ID.'"' : '').'>'.$r->ID.'</span>';
		echo ' <b>';
			echo App::link("E", "?task=CRM_LISTA_ZASOBOW&EDIT=".$r->ID."#".$r->ID);
			if ($r->ALIAS_ID > 0) echo ' <span class="P_ID">'."(ALIAS DO ".'<a href="#TREE'.$r->ALIAS_ID.'">'.$r->ALIAS_ID.'</a>'.")".'</span>';
			echo ' '.$r->TYPE;
		echo '</b>';
		echo ' '.$r->DESC;
		echo ' <span style="color:#333;">'.$r->OPIS.'</span>';
		echo ' ]';
		if (isset($r->external_IDS)) echo ' {<span style="color:green">'.$r->external_IDS.'</span>}';
		echo '</span>'."\n";

		if (!$_SESSION['ZWIN_DRZEWO'] || (!empty($_SESSION['TREE_OPEN_ARRAY'][$r->ID]) && $_SESSION['TREE_OPEN_ARRAY'][$r->ID])) {
			// drzewo tylko z glownego P_ID
			if ($r->PARENT_TYPE == 'P_ID') {
				tree_listuj_zasoby($r->ID, $POZIOM + 1, $LAST);
			}
		}
	}
}
