<?php


function TREEJS() {
global $result,$thiss;

$zasobID = V::get('ZASOB_ID', 0, $_GET, 'int');
if ($zasobID <= 0) {
	echo 'Wrong param ZASOB_ID';
	return;
}

echo "&lt;&lt;".'<a href="' . "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$zasobID}" . '" title="Powrot">Powrot do tabeli</a>';

$conf = null;

$tblName = '';
Lib::loadClass('ProcesHelper');
$zasobObj = ProcesHelper::getZasobTableInfo($zasobID);
if (!$zasobObj) {
	echo "Zasob TABELA ID={$zasobID} nie istnieje";
	return;
}
$tblName = $zasobObj->DESC;

$allowed_tables_conf = array();
$allowed_tables_conf ['IN7_MK_BAZA_DYSTRYBUCJI'] = array('set_parent_id_col'=>'P_ID');
$allowed_tables_conf ['IN7_MK_BAZA_DYSTRYBUCJI']['params'] = array();
$allowed_tables_conf ['IN7_MK_BAZA_DYSTRYBUCJI']['params']['show_item_callback']='tree_callback__show_item_from_IN7_MK_BAZA_DYSTRYBUCJI';
$allowed_tables_conf ['IN7_MK_BAZA_DYSTRYBUCJI']['params']['ajax']='NIE';

if (!array_key_exists($tblName, $allowed_tables_conf)) {
	echo'<p>'."Brak dostepu".'</p>';
}
$conf = $allowed_tables_conf[$tblName];

require_once dirname(__FILE__) . '/' . 'se-lib' . '/' . 'Lib.php';
Lib::loadClass('V');
Lib::loadClass('DB');
Lib::loadClass('Tree');
Lib::loadClass('TreeHelper');

Lib::loadClass('App');
echo'<style type="text/css">'."
.btn-box{margin:0 2px 0 0;padding:0 3px;background:#bbb;color:#fff;text-decoration:none;border:0;font-weight:bold;}
.btn-box-blue{background:#3A3AFF;color:#fff;}
.btn-box-green{background:#008A00;color:#fff;}
.btn-box-lgreen{background:#97CF97;color:#fff;}
.btn-box-red{background:#FF4646;color:#fff;}
.btn-box-group1{background-color:#9F9FCB;color:#fff;}
.btn-box-group2{background-color:#B8B879;color:#fff;}
/*.tree-wrap .btn{border-radius:3px;-webkit-border-radius:3px;-moz-border-radius:3px;}*/
/*.btn-box{border-radius:3px;-webkit-border-radius:3px;-moz-border-radius:3px;}*/

.filters{margin:0;padding:2px;background:#F0F0F0 url(./stuff/flexigrid/css/images/bg.gif) repeat-x top;border:1px solid #ccc;border-style:solid solid none solid;clear:both;overflow:hidden;}
.filters .btnseparator{float:left;height:22px;border-left:1px solid #CCC;border-right:1px solid #fff;margin:1px;}
.filters form{margin:0;padding:0;}
.filters nobr{display:block;float:left;margin:0;padding:2px;font-weight:normal;font-size:13px;}
.filters nobr:hover{text-decoration:underline;}
.filters nobr.active{color:#f00;font-weight:normal;}
.filters nobr input,
.filters nobr select,
.filters nobr button{margin:0 1px;padding:0 2px;font-size:13px;}

".'</style>'."\n";
App::show_head_css();
App::show_head_js();


function tree_callback__show_item_from_IN7_MK_BAZA_DYSTRYBUCJI( &$r, &$tree ) {
	$zasobID = V::get('ZASOB_ID', 0, $_GET, 'int');
	// TODO: btn-box zasob type from PARENT_ID
	$cls = array();
	if (($search_id = $tree->get_param('search_id')) > 0 && $search_id == $r->ID) {
		$cls []= 'search_id';
	}
	$cls = (!empty($cls))? ' class="'.implode(' ', $cls).'"' : '';

	{// $wsk == ids
		$wsk = array();
		if ($tree->get_param('filtr_ids')) {
			/*
[DEVICES]
id_col="T_DEVICE_SERIAL"
allowed_cols="ID,CRM_LISTA_ZASOBOW_ID:CLZ_ID,T_TELBOX_NEIGHBOUR_IN,T_DEVICE_SERIAL,T_DEVICE_INFO,A_STATUS_EV,S_OTHER_INFO"

[TELBOXES]
id_col="T_TELBOX_NAME"
allowed_cols="ID,CRM_LISTA_ZASOBOW_ID:CLZ_ID,T_TELBOX_NEIGHBOUR_IN,T_TELBOX_NEIGHBOUR_OUT,T_TELBOX_NAME,A_STATUS,S_OTHER_INFO"
			*/
			$ids_conf_arr = array();
			$ids_conf_arr ['DEVICES']= array('id_col'=>"T_DEVICE_SERIAL",'allowed_cols'=>"ID,CRM_LISTA_ZASOBOW_ID:CLZ_ID,T_TELBOX_NEIGHBOUR_IN,T_DEVICE_SERIAL,T_DEVICE_INFO,A_STATUS,S_OTHER_INFO");
			$ids_conf_arr ['TELBOXES']= array('id_col'=>"T_TELBOX_NAME",'allowed_cols'=>"ID,CRM_LISTA_ZASOBOW_ID:CLZ_ID,T_TELBOX_NEIGHBOUR_IN,T_TELBOX_NEIGHBOUR_OUT,T_TELBOX_NAME,A_STATUS,S_OTHER_INFO");
			if (!empty($ids_conf_arr)) {
				$external_ids = array();
				foreach ($ids_conf_arr as $k_table_name => $v_cnf) {
					$cur_cnf = new stdClass();
					$cur_cnf->id_col = V::get('id_col', 'ID', $v_cnf);
					$cur_cnf->search_col = V::get('search_col', 'ID_PROJECT', $v_cnf);
					$cur_cnf->search_col_regex = V::get('search_col_regex', '', $v_cnf);
					$sql_id_col = $cur_cnf->id_col;
					$sql_where = "";
					if ($cur_cnf->search_col_regex) {
						$sql_where = "`".$cur_cnf->search_col."` like '".str_replace('$ID', $zasob->ID, $cur_cnf->search_col_regex)."'";
					} else {
						$sql_where = "`".$cur_cnf->search_col."`='".$r->ID."'";
					}

					$sql = "select t.`".$sql_id_col."`
						from `".$k_table_name."` as t
						where ".$sql_where."
					";
					$res = DB::query( $sql );
					while ($r_wsk = DB::fetch( $res )) {
						$wsk []= (object)array('name'=>$r_wsk->$sql_id_col, 'table'=>$k_table_name);
					}
				}//end foreach
			}
		}
	}

	echo'<dl'.$cls.'>';
	echo'<dt>';

	$out_id = ($r->ID < 10)? '&nbsp;'.$r->ID.'' : $r->ID;
	echo'<a href="'."index.php?MENU_INIT=TREEJS&ZASOB_ID={$zasobID}&filtr_id=".$r->ID."#TREE".$r->ID.'" class="item_id btn-box">'.$out_id.'</a>';

	echo'<a href="'."index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$zasobID}#EDIT/{$r->ID}".'" class="btn" title="'."Edit".'">'."E".'</a>';

	//if ($r->has_childrens) {
	//	if (!$tree->get_param('rozwin')) {
	//		$js = "return " . $tree->js_tree_open_rec_fun . "(this," . $r->ID . ");";
	//		echo'<a href="'."#".'" title="'."Rozwin wszystko".'" onclick="'.$js.'" class="btn open-rec">'."L".'</a>';
	//	}
	//}

	// TODO: edycja nie działa - bierze ostatni edytowany rekord
	//echo' <a href="'."?FUNCTION_INIT=IN7_MK_BAZA_DYSTRYBUCJI_EDIT&ARG1=EDIT&ARG1_VAL=".$r->ID.'" class="btn-box">'."E".'</a>';

	$st_status_bg = '';
	if ($r->A_STATUS == 'NORMAL') {
		$st_status_bg = '#8F8;';
	} else if ($r->A_STATUS == 'WAITING') {
		$st_status_bg = '#F8F;';
	} else if ($r->A_STATUS == 'DELETED') {
		$st_status_bg = '#ccc;';
	} else if ($r->A_STATUS == 'OFF_SOFT') {
		$st_status_bg = '#F99;';
	} else if ($r->A_STATUS == 'OFF_HARD') {
		$st_status_bg = '#eee;';
	}
	$st_status_bg = ($st_status_bg)? 'background-color:'.$st_status_bg : '';

	echo'<span class="desc">';
		echo'<span class="btn-box" style="'.$st_status_bg.'">'.$r->A_STATUS.'</span>';
		echo' <em style="color:#666;" title="'.$r->M_DIST_TYPE.'">'.((strlen($r->M_DIST_TYPE) > 5)? substr($r->M_DIST_TYPE, 0, 5).'...' : $r->M_DIST_TYPE).'</em>';
		echo' <i style="color:red">'.$r->M_DIST_DESC.'</i>';
		echo' <span>'.$r->M_DISTRIBUTOR.'</span>';
		echo' <font size="-1">'.$r->M_DIST_INVENTOR.'</font>';
	echo'</span>';

	echo'</dt>';
	if (!empty($wsk)) {
		echo'<dd>';
		echo'<ul>';
		$wsk_cnt = count( $wsk );
		foreach ($wsk as $w) {
			echo'<li'.((--$wsk_cnt)? '' : ' class="last"').'>';
				echo'<p>';
				//TODO: test: echo ' <span class="btn-box btn-box-silver">'.".".$w->CW_ID.".".'</span>';
				echo ' <span class="silver">'.$w->table.'</span>';
				echo' <b>'.$w->name.'</b>';
				echo'</p>';
			echo'</li>';
		}
		echo'</dd>';
	}
	echo'</dl>'."\n";
}


{// tree filter
	$tbl = $tblName;
	Lib::loadClass('Filter');
	$tree_filter = new Filter( $_GET, $tbl, 'session' );

	if ($tbl == 'IN7_MK_BAZA_DYSTRYBUCJI') {
		{ // filtr_status
			$filtr = array();
			$filtr['WSZYSTKIE'] = 'WSZYSTKIE';
			$filtr['WAITING'] = 'WAITING';
			$filtr['NORMAL'] = 'NORMAL';
			// TODO: add js search without page reload, add #TREE{ID}
			$tree_filter->add_filter( 'filtr_status', $filtr, 'WSZYSTKIE', 'Status' );
		}
		{// filtr_id
			$filtr = array('search');
			$tree_filter->add_filter( 'filtr_id', $filtr, '', 'Filtruj ID' );
		}
		{ // filtr_search_id
			$filtr = array('search');
			// TODO: add js search without page reload, add #TREE{ID}
			$tree_filter->add_filter( 'filtr_search_id', $filtr, '', 'Wyszukaj ID' );
		}
		{ // filtr_ids
			$filtr = array();
			$filtr['SHOW'] = '0';
			$filtr['HIDE'] = '1';
			$tree_filter->add_filter( 'filtr_ids', $filtr, 'HIDE', 'IDS' );
		}
	}
}// tree filter

$tree_filter->_save_args();


	echo'<div class="filters">';
		echo'<form action="'."".'" method="get" style="margin:0;padding:0;">';
		//echo'<input type="hidden" name="'."FUNCTION_INIT".'" value="'."TREEJS".'" />';
		echo'<input type="hidden" name="'."MENU_INIT".'" value="'."TREEJS".'" />';
		echo'<input type="hidden" name="'."ZASOB_ID".'" value="'."{$zasobID}".'" />';
		$tree_filter->show_filters();
if(0){
		{// 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>';

if(0){// test-tree-js
	$items = array();
	$sql = "select p.ID, p.P_ID
			, p.`A_STATUS`
			, p.`M_DIST_TYPE`
			, p.`M_DIST_DESC`
			, p.`M_DISTRIBUTOR`
			, p.`M_DIST_INVENTOR`
		from `".$tblName."` as p
		where
			p.P_ID!='-1' and p.P_ID!=''
	";
	$res = DB::query( $sql );
	while ($r = DB::fetch( $res )) {
		$r->sub = array();
		$r->P_ID = trim($r->P_ID);
		$r->P_ID = str_replace(' ', ',', $r->P_ID);
		$v_parents = array();
		$v_parents_test = explode(',', $r->P_ID);
		foreach ($v_parents_test as $v_id) {
			$v_id = intval(trim($v_id));
			if ($v_id > 0) {
				$v_parents []= $v_id;
			}
		}//end foreach
		if (empty($v_parents)) {
			$r->P_ID = 0;
		} else {
			$r->P_ID = $v_parents;
		}
		$items[$r->ID] = $r;
	}

	// set root for tree $pro_tree
	$pro_tree = array();
	foreach ($items as $k_id => $r) {
		if ($r->P_ID == 0) {
			$pro_tree [ $r->ID ] = array();
			$v_id = $r->P_ID;
			if (array_key_exists($v_id, $items)) {
				$items[$v_id]->sub [$r->ID] = true;
			}
		} else {// array
			foreach ($r->P_ID as $v_id) {
				if (array_key_exists($v_id, $items)) {
					$items[$v_id]->sub [$r->ID] = true;
				}
			}//end foreach
		}
	}//end foreach
	ksort($pro_tree);

	// set up has_childrens
	foreach ($items as $k_id => $r) {
		$items[$k_id]->has_childrens = !empty($r->sub);
	}//end foreach
	

	// build tree by P_ID - array or 0
	function TREEJS_create_project_tree_rec( $p_id, &$items ) {
		static $rec_ind;
		$rec_ind++;
		$ret = array();
		if (!array_key_exists($p_id, $items)) {
			return false;
		} else {
			$r = $items[$p_id];
			if (empty($r->sub)) {
				return false;
			}
			foreach ($r->sub as $k_id => $v) {
				$ret [$k_id] = TREEJS_create_project_tree_rec( $k_id, $items );
			}//end foreach
			return $ret;
		}
	}
	//$pro_tree = TREEJS_create_project_tree_rec( $pro_tree, $items );
	foreach ($pro_tree as $k_id => $v_childrens) {
		if (array_key_exists($k_id, $items)) {
			$pro_tree[$k_id] = TREEJS_create_project_tree_rec( $k_id, $items );
		}
	}
}// test-tree-js

$tree = new Tree( $tblName );
if (($p_id_col = V::get('set_parent_id_col', '', $conf)) != '') {
	$tree->set_parent_id_col( $p_id_col );
}
if (!empty($conf['params'])) {
	foreach ($conf['params'] as $k_param => $v_param) {
		$tree->set_param($k_param, $v_param);
	}//end foreach
}
$tree->set_param('filtr_status', $tree_filter->get_arg('filtr_status'));
$tree->set_param('filtr_ids', ($tree_filter->get_arg('filtr_ids') == 'SHOW'));

if(0){// test-tree-js
$tree->show_css();
$tree->show_js();
echo "\n".'<div class="tree-wrap">'."\n";
$tree->show_rec_by_tree($pro_tree, $items);
echo '</div>'."\n";

return;
echo'<br /><hr /><br />';

// TODO: rm
}// test-tree-js
if ($tree_filter->get_arg('filtr_id') != 0) {
	$tree->showSubTree( $tree_filter->get_arg('filtr_id') );
} else if ($tree_filter->get_arg('filtr_search_id') > 0) {
	$tree->showSearchNode( $tree_filter->get_arg('filtr_search_id') );
} else {
	$tree->show();
}


}
