<?php

Lib::loadClass('DB_Image');
Lib::loadClass('Http');

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

function ajax_get_alias_info() {
	header('Content-Type: text/html; charset=utf8');//utf8
	$idZasob = V::get('idZasob', 0, $_REQUEST, 'int');
	if (!$idZasob) die('Wrong param');
	$sql = <<<SQL
		select z.`ID`
			,	z.`ALIAS_ID`
			,	z.`ALIAS_MODE`
			,	za.`DESC` as `ALIAS_DESC`
			,	zap.`DESC` as `ALIAS_PARENT_DESC`
			,	zv.`CHILDS`
			,	zv.`PATH`
		from `CRM_LISTA_ZASOBOW` z
			join `CRM_LISTA_ZASOBOW_ALIASY_view` zv on(zv.`ID`=z.`ID`)
			left join `CRM_LISTA_ZASOBOW` za on(za.`ID`=z.`ALIAS_ID`)
			left join `CRM_LISTA_ZASOBOW` zap on(zap.`ID`=za.`PARENT_ID`)
		where z.`ID`='{$idZasob}'
SQL;
	$db = DB::getDB();
	$res = $db->query($sql);
	$info = $db->fetch($res);
	if (!$info) {
		echo 'Brak danych';
	} else {
		$outLines = array();
		if ($info->ALIAS_ID > 0) {
			$js = "return treeAddToFiltr(this, {$info->ALIAS_ID});";
			$outAliasedId = '<a href="#" onclick="' . $js . '" title="Dodaj do filtra ' . $info->ALIAS_ID . '">' . $info->ALIAS_ID . '</a>';
			$outAliasType = ('VIRTUAL' == $info->ALIAS_MODE)? "ALIAS WIRTUALNY" : "ALIAS";
			$outTitle = "{$outAliasType} DO [{$info->ALIAS_ID}] {$info->ALIAS_PARENT_DESC}/{$info->ALIAS_DESC}";
			$outLabel = "{$outAliasType} DO [{$outAliasedId}] " . V::strShortUtf8($info->ALIAS_PARENT_DESC, 16, '...') . '/' . V::strShortUtf8($info->ALIAS_DESC, 16, '...');
			$outLines[] = '<span title="'.$outTitle.'">'.$outLabel.'</span>';
		}
		if (!empty($info->PATH)) {
			$outPaths = array();
			$paths = explode(',', $info->PATH);
			foreach ($paths as $path) {
				$js = "return treeAddToFiltr(this, {$path});";
				$outPaths[] = '<a href="#" onclick="' . $js . '">' . $path . '</a>';
			}
			$outLines[] = 'Ścieżka: ' . implode(', ', $outPaths);
		}
		if (!empty($info->CHILDS)) {
			$outChilds = array();
			$childs = explode(',', $info->CHILDS);
			foreach ($childs as $child) {
				$js = "return treeAddToFiltr(this, {$child});";
				$outChilds[] = '<a href="#" onclick="' . $js . '">' . $child . '</a>';
			}
			$outLines[] = 'Aliasy: ' . implode(', ', $outChilds);
		}
	}
	if (empty($outLines)) {
		echo 'Brak danych';//Http::sendHeaderByCode(404);
	} else {
		echo implode('<br>', $outLines) . '<br/>';
	}
	exit;
}

function ajax_get_subtree() {
	header('Content-Type: text/html; charset=utf8');//utf8

	$id = V::get('id', '', $_GET);
	$tbl = V::get('tbl', '', $_GET);

	Lib::loadClass('FilterFactory');
	$tree_filter = FilterFactory::build($tbl);
	$tree_filter->setArgs($_GET);

	$clbk = 'tree_callback__show_item_from_'.$tbl;
	if (!function_exists($clbk)) {
		$clbk = null;
	}
	$tree = new Tree($tbl);
	if ($clbk) $tree->set_param('show_item_callback', $clbk);
// TODO: get all filters:
	$tree->set_param('rozwin', ($tree_filter->get_arg('filtr_drzewo') == 'ROZWIN'));
	$tree->set_param('rozwin_proces', ($tree_filter->get_arg('filtr_procesy') == 'ROZWIN'));
	$tree->set_param('rozwin_zasoby', ($tree_filter->get_arg('filtr_zasoby') == 'ROZWIN'));
	$tree->set_param('rozwin_opis', ($tree_filter->get_arg('filtr_opis') == 'ROZWIN'));
	$tree->set_param('filtr_sort_prio', ($tree_filter->get_arg('filtr_sort_prio') == 'SHOW'));
	$tree->set_param('filtr_img', ($tree_filter->get_arg('filtr_img') == 'SHOW'));
	$tree->set_param('filtr_ob', ($tree_filter->get_arg('filtr_ob') == 'SHOW'));
	$tree->set_param('filtr_ids', ($tree_filter->get_arg('filtr_ids') == 'SHOW'));

	$tree->set_param('style', $tree_filter->get_arg('filtr_view'));
	$tree->set_param('search_id', $tree_filter->get_arg('filtr_search_id'));
	//TODO: check perm to edit
	$tree->set_param('editable', ($tree_filter->get_arg('filtr_edit') == 'TAK'));
	$tree->_limit = 100;
	$tree->_deep_limit = 10;

	$open_rec = V::get('open_rec', '', $_REQUEST);
	if ($open_rec == '1') {
		$tree->show_rec_all($id);
	} else {
		$tree->show_rec($id);
	}

	exit;
}

function ajax_add_image() {
	//sleep(1);// TODO: TEST
	$tbl = V::get('tbl', '', $_REQUEST);
	$id = V::get('id', '', $_REQUEST);
	//echo $tbl;

	//fun_IMAGE_ADD();
	$remote_table = V::get('tbl', '', $_REQUEST);
	$remote_id = V::get('id', '', $_REQUEST, 'int');
	$task = V::get('task', '', $_REQUEST);

	$thiss = new stdClass();
	$thiss->DETECT_TABLE_NAME = $remote_table;
	$errors = array();
	$msgs = array();

	// check remote id
	if ($remote_id <= 0) {
		echo'<p>';
			echo "Error wrong ID";
			echo'<br />';
			//echo App::link();// TODO: link do ???
		echo'</p>';
		return;
	}

	// check remote table
	if (!DB_Image::tableIsAllowed($remote_table)) {
		$errors[] = "Error table not allowed to add image";
	}

	// task
	$task = V::get('task', '', $_REQUEST);
	if ($task == 'REMOVE') {// TODO: przerobic na funkcje, zwrocic msg, pokazac w body
		$req = array();
		$req['ID'] = V::get('ID', '', $_REQUEST, 'int');
		$req['REMOTE_ID'] = V::get('REMOTE_ID', '', $_REQUEST, 'int');
		$req['REMOTE_TABLE'] = V::get('REMOTE_TABLE', '', $_REQUEST);
		// validate
		if ($req['ID'] <= 0) {
			$errors[] = 'error ID';
		}

		if ($req['REMOTE_ID'] <= 0) {
			$errors[] = 'error REMOTE_ID';
		}

		if ($req['REMOTE_TABLE'] != $remote_table) {
			$errors[] = 'error REMOTE_TABLE';
		}

		if (empty($errors)) {
			$affected = DB_Image::deleteImage($req['ID'], $req['REMOTE_TABLE'], $req['REMOTE_ID']);
			if ($affected == 1) {
				$msgs[] = '<p>'."Usunieto zdjecie ID=".$req['ID'].'</p>';
			} else {
				$erros[] = '<p>'."Wystapil blad podczas usuwania zdjecia ID=".$req['ID'].'</p>';
			}
		}
	}

	// check if a file was submitted
	if (!isset($_FILES['userfile'])) {
		//echo '<p>Please select a file</p>';
	}
	else {
		$errors = DB_Image::uploadImage($remote_table, $remote_id, $_FILES['userfile']);
		// give praise and thanks to the php gods
		if (empty($errors)) {
			$msgs[] = '<p>Thank you for submitting</p>';
		} else {
			$msgs[] = '<p style="border:1px solid red;">' . "Sorry, could not upload file:" . '<br />' . implode('<br />', $errors) .'</p>';
		}
	}

	$title = 'Dodaj plik do rekordu ID='.$remote_id.' z tabeli '.$remote_table;

	echo'<h3>'.$title.'</h3>';

	// show masgs
	if (!empty($msgs)) {
		echo'<div class="box box-green">';
			echo implode('<br />', $msgs);
		echo'</div>';
	}

	// show errors
	if (!empty($errors)) {
		echo'<div class="box box-red">';
			echo implode('<br />', $errors);
		echo'</div>';
		return;
	}

	echo'<div class="box box-silver">';
	$js = "ajax_form(this, 'id', 'tip-popup-box');";
	$js = ' onsubmit="'.$js.'"';
	echo'<form enctype="multipart/form-data" action="" method="post"'.$js.'>';
		echo'<input type="hidden" name="function_init" value="'. __FUNCTION__ .'" />';
		echo'<input type="hidden" name="REMOTE_ID" value="'.$remote_id.'" />';
		echo'<input type="hidden" name="REMOTE_TABLE" value="'.$remote_table.'" />';
		//echo'<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />';

		echo"Rodzaj obrazka: ";
		echo'<input type="text" name="'."DEST".'" value="'."".'" />';
		$select_arr = array();
		$select_arr = DB_Image::conf_get_options($thiss->DETECT_TABLE_NAME);

		if (!empty($select_arr)) {
			echo' ';
			$js = "if(this.selectedIndex>0){this.form.DEST.value=this.value}";
			echo'<select onchange="'.$js.'">';
				echo'<option value="">'."Wybierz".'</option>';
			foreach ($select_arr as $key => $val) {
				echo'<option value="'.$key.'">'.$val.'</option>';
			}
			echo'</select>';
		}
		echo'<br />';
		echo'<input name="userfile" type="file" />';
		echo'<br />';
		echo'<input type="submit" value="'."Dodaj obrazek".'" />';
	echo'</form>';
	echo'</div>';// .box-silver


// TODO: show images, mv to function {
	$images = DB_Image::getImages($thiss->DETECT_TABLE_NAME, $remote_id);

	if (empty($images)) {
		echo'<p class="err">'."Brak obrazkow".'</p>';
	} else {
		echo'<h3>'."Wgrane pliki:".'</h3>';
		foreach ($images as $r) {
			$link_src = '?function_init=fun_SHOW_IMAGE&image_id='.$r->ID.'&HEADER_NOT_INIT=YES';
			$st = array();
			if ($r->WIDTH > 100 || $r->HEIGHT > 100) {
				if ($r->WIDTH > $r->HEIGHT) {
					$st[] = 'width:100px';
				} else {
					$st[] = 'height:100px';
				}
			}
			$st = (empty($st))? '' : ' style="'.implode(';', $st).'"';
			echo'<table style="float:left;border:1px solid silver;">';
			echo'<tr>';
				echo'<td>';
					echo''.$r->NAME.'<br />';
					echo''.$r->DEST.'<br />';
					echo''.$r->A_CREATE_DATE.'<br />';
					echo''.DB_Image::show_size($r->SIZE).' '.$r->WIDTH.'x'.$r->HEIGHT.'<br />';
					echo'<img src="'.$link_src.'" '.$st.'/>';
				echo'</td>';
			echo'</tr>';
			echo'<tr>';
				echo'<td style="text-align:center;">';

					echo'<form action="" method="post" style="display:inline">';
						echo'<input type="hidden" name="task" value="'."REMOVE".'" />';
						echo'<input type="hidden" name="ID" value="'.$r->ID.'" />';
						echo'<input type="hidden" name="REMOTE_ID" value="'.$remote_id.'" />';
						echo'<input type="hidden" name="REMOTE_TABLE" value="'.$remote_table.'" />';
						$js = "if(!confirm('Czy na pewno chcesz usunac obrazek?')) return false;";
						echo'<input type="submit" value="Usun" onclick="'.$js.'" />';
					echo'</form>';

					echo'<form action="" method="post" style="display:inline">';
						echo'<input type="hidden" name="task" value="'."EDIT".'" />';
						echo'<input type="hidden" name="ID" value="'.$r->ID.'" />';
						echo'<input type="hidden" name="REMOTE_ID" value="'.$remote_id.'" />';
						echo'<input type="hidden" name="REMOTE_TABLE" value="'.$remote_table.'" />';
						echo'<input type="submit" value="Edytuj" />';
					echo'</form>';

				echo'</td>';
			echo'</tr>';
			echo'</table>';
		}
	}
// } function show images

}

function ajax_zasob_search_external_ids() {
	header('Content-Type: text/html; charset=utf8');

	$zasob_id = V::get('zasob_id', '', $_REQUEST, 'int');
	if ($zasob_id <= 0) {
		echo'Error: Bad request';// TODO: header
		return;
	}
	$DBG = ('123' == V::get('DBG', '', $_REQUEST));

	$zasob = DB::get_by_id('CRM_LISTA_ZASOBOW', $zasob_id);
	if (!$zasob) {
		echo'Error: 404 not found';// TODO: header
		return;
	}
	$cnf = Config::getConfFile('external_ids');
	if (!$cnf) {
		echo'Config error (external_ids)';
		return;
	}

if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cnf (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cnf);echo'</pre>'; }

	if (!empty($cnf)) {
		$external_ids = array();
		foreach ($cnf 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', '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;
			$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}`='{$zasob->ID}'";
			}

			$sql = "select t.`ID`, {$sql_id_col} as id_col
				from `{$k_table_name}` as t
				where {$sql_where}
			";
if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>'; }
			$db = DB::getDB();
			$res = $db->query($sql);
			while ($r = $db->fetch($res)) {
				if ('ID' != $sql_id_col) {
					$external_ids[] = "{$r->ID}({$r->id_col})";
				} else {
					$external_ids[] = "{$r->id_col}";
				}
			}
		}
	}

	$out_link = '';
	if (empty($external_ids)) {
		$out_link = '<span class="not-found">'."Brak danych".'</span>';
	} else {
		$out_link = implode(', ', $external_ids);
	}

	echo '<span>';
	
	/*
		$cnf_ids_tabl_TODO_MOVE_TO_CONFIG=array('REWIR'=>'MK_Rewiry',
		'URZADZENIE'=>'DEVICES','DOSTEP-ZAMEK-ELEKTRONICZNY'=>'DEVICES', 'OZNACZENIE_LOKALIZACJI'=>'DEVICES', 'APLIKACJA'=>'DEVICES', 'SOFTWARE'=>'DEVICES', 'ALARM-SATEL'=>'DEVICES', 'SZAFA'=>'DEVICES', 'SEJF'=>'DEVICES', 'SEGREGATOR'=>'DEVICES', 'KUWETA'=>'DEVICES', 'NARZEDZIE'=>'DEVICES', 'DOSTEP-KLUCZ'=>'DEVICES', 'DOSTEP-KARTA'=>'DEVICES', 'DOSTEP-ZAMEK'=>'DEVICES', 'MATERIAL_REKLAMOWY'=>'DEVICES', 'SERWER'=>'DEVICES', 'MATERIAL_EKSPLOATACYJNY'=>'DEVICES', 'PIECZATKA'=>'DEVICES', 'PLYTA_CD'=>'DEVICES', 'KOMPUTER'=>'DEVICES', 'URZADZENIA_I_OZNACZENIA_BHP'=>'DEVICES',
		'LOKALIZACJA'=>'TELBOXES', 'OBSZAR'=>'TELBOXES', 'POLKA'=>'TELBOXES', 'MAGAZYN'=>'TELBOXES', 'POMIESZCZENIE'=>'TELBOXES', 'SZAFA'=>'TELBOXES',
		'DOKUMENTY'=>'IN7_DZIENNIK_KORESP',
		'DOSTEP-UPRAWNIENIA'=>'REMOTE_ACCESS_ACCOUNTS','SHARED_IMAP_MAILBOX'=>'REMOTE_ACCESS_ACCOUNTS',
		'PODMIOT'=>'BILLING_OWNER',
		'PROJEKT'=>'IN7_MK_BAZA_DYSTRYBUCJI','SPRAWA'=>'IN7_MK_BAZA_DYSTRYBUCJI',
		'SERVICE_POINT'=>'USERS2_MARKETING','LOKALIZACJA_USLUGI'=>'USERS2_MARKETING',
		'OFFER_GROUP'=>'USERS2_OFFERS_GROUPS',
		'OFFER'=>'USERS2_OFFERS',
		'OFFER_COSTS_GROUP'=>'USERS2_OFFERS_COSTS_GROUPS',
		'OFFER_COST'=>'USERS2_OFFERS_COSTS',
		'SES_PROCESY5_A'=>'SES_PROCESY5_A'
		);
		*/
		require_once 'php_classes_ajax_php__cnf_ids_tabl.php';

		echo $out_link;
		echo " ";
		if( $cnf_ids_tabl_TODO_MOVE_TO_CONFIG[$zasob->TYPE]) {
		echo App::link("dodaj", "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".ProcesHelper::getZasobTableID($cnf_ids_tabl_TODO_MOVE_TO_CONFIG[$zasob->TYPE])."&ff_A_STATUS=WAITING&ff_T_DEVICE_SERIAL=".date('Y-m-d')."-".$zasob->ID."&ff_T_DEVICE_INFO=".urlencode($zasob->OPIS)."&ff_T_DEVICE_TYPE=".urlencode($zasob->DESC)."&ff_CRM_LISTA_ZASOBOW_ID=".$zasob->ID."&ff_ID_ZASOB=".$zasob->ID."#CREATE", array('class'=>'btn-p5', 'title'=>'Dodaj zapotrzebowanie', 'onclick'=>null));
		echo App::link("szukaj", "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".ProcesHelper::getZasobTableID($cnf_ids_tabl_TODO_MOVE_TO_CONFIG[$zasob->TYPE])."&ff_CRM_LISTA_ZASOBOW_ID=".$zasob->ID, array('class'=>'btn-p5', 'title'=>'szukaj', 'onclick'=>null));
		}
		echo App::link_ajax("refresh", "ajax_zasob_search_external_ids", array('zasob_id'=>$zasob->ID), array('js_result_type'=>'override_parent', 'js_result'=>'', 'title'=>'refresh IDS', 'ico'=>"refresh.png"));
	echo '</span>';

	// TODO: add link to CRM_EXT_IDS - rysuj strukture
}

function ajax_zasob_stanowisko_search_kontakty() {
	header('Content-Type: text/html; charset=utf8');

	$zasob_id = V::get('zasob_id', '', $_REQUEST, 'int');
	if ($zasob_id <= 0) {
		echo'Error: Bad request';// TODO: header
		return;
	}
	$DBG = ('123' == V::get('DBG', '', $_REQUEST));

	$zasob = DB::get_by_id('CRM_LISTA_ZASOBOW', $zasob_id);
	if (!$zasob) {
		echo'Error: 404 not found';// TODO: header
		return;
	}

	$external_ids = array();
	$mailto_links = array();
	$db = DB::getDB();
	$sql = "select u.`ID`, u.`ADM_ACCOUNT`, u.`ADM_NAME`, u.`EMAIL`
		from `CRM_AUTH_PROFILE` as up
			left join `ADMIN_USERS` as u on (u.`ID`=up.`REMOTE_ID`)
		where
			up.`ID_ZASOB`='{$zasob->ID}'
			and up.`REMOTE_TABLE`='ADMIN_USERS'
			and up.`A_STATUS` in('WAITING', 'NORMAL')
			and u.`A_STATUS` in('WAITING', 'NORMAL')
		group by u.`ID`
	";
	if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>'; }
	$res = $db->query($sql);
	while ($r = $db->fetch($res)) {
		$external_ids[] = "{$r->ADM_ACCOUNT}({$r->ADM_NAME})";
		if (!empty($r->EMAIL)) {
			$mailto_links[$r->EMAIL] = true;
		}
	}

	if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">external_ids (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($external_ids);echo'</pre>'; }

	$out_link = '';
	if (empty($external_ids)) {
		$out_link = '<span class="not-found">'."Brak danych".'</span>';
	} else {
		$out_link = implode(', ', $external_ids);
	}

	echo '<span>';
		echo $out_link;
		echo " ";
		echo App::link_ajax("refresh", "ajax_zasob_stanowisko_search_kontakty", array('zasob_id'=>$zasob->ID), array('js_result_type'=>'override_parent', 'js_result'=>'', 'title'=>'refresh IDS', 'ico'=>"refresh.png"));
		echo " ";
		if (!empty($mailto_links)) {
			$mailto_links = array_keys($mailto_links);
			echo '<a href="' . "mailto:" . implode(', ', $mailto_links) . '"><img src="icon/mail_all.png" height="16" alt=" mail " /></a>';
			echo " ";
		}
		echo App::link(" więcej &raquo; ", array('task'=>"USERS", '_group'=>$zasob_id), array('target'=>"_blank"));
	echo '</span>';

	// TODO: add link to CRM_EXT_IDS - rysuj strukture
}

function ajax_zasob_get_obowiazki() {
	$zasob_id = V::get('zasob_id', '', $_REQUEST, 'int');
	if ($zasob_id <= 0) {
		echo'Error: Bad request';// TODO: header
		return;
	}

	$zasob = DB::get_by_id('CRM_LISTA_ZASOBOW', $zasob_id);
	if (!$zasob) {
		echo'Error: 404 not found';// TODO: header
		return;
	}

	$external_ids = array();

	$db = DB::getDB();
	$sql = "select t.`ID_PROCES` as ext_id
		from `CRM_WSKAZNIK` as t
			join `CRM_PROCES` as p on(p.`ID`=t.`ID_PROCES`)
		where
			t.`ID_ZASOB`='{$zasob->ID}'
			and t.`A_STATUS` in('WAITING','NORMAL')
			and p.`A_STATUS` in('WAITING','NORMAL')
	";
	$res = $db->query($sql);
	while ($r = $db->fetch($res)) {
		$external_ids[] = $r->ext_id;
	}

	$out_link_ids_limit = 5;
	$out_link = '';
	$out_link_add = '';
	if (empty($external_ids)) {
		$out_link = '<span class="not-found">'."Brak danych".'</span>';
	} else {
		$cnt = count($external_ids);
		if ($cnt > $out_link_ids_limit) {
			$external_ids_tmp = array();
			for ($i = 0; $i < $out_link_ids_limit; $i++) {
				$external_ids_tmp[] = $external_ids[$i];
			}
			$out_link_add .= implode(' ', $external_ids_tmp);
			$out_link_add .= ' ... ';
			$out_link_add .= App::link("({$cnt})", "?task=CRM_WYSWIETL_OBOWIAZKI&CLZ_ID={$zasob->ID}", array('target'=>'_blank', 'title'=>'Procesy powiazane z tym zasobem'));
		} else {
			$out_link_add .= implode(' ', $external_ids);
			$out_link_add .= ' ';
			$out_link_add .= App::link("(OB)", "?task=CRM_WYSWIETL_OBOWIAZKI&CLZ_ID={$zasob->ID}", array('target'=>'_blank', 'title'=>'Procesy powiazane z tym zasobem'));
		}
	}

	if ($out_link) {
		echo App::link_ajax($out_link, "ajax_zasob_get_obowiazki", array('zasob_id'=>$zasob->ID), array('js_result_type'=>'override', 'js_result'=>'', 'title'=>'refresh OB'));
	}

	if ($out_link_add) {
		echo $out_link_add;
	}

}

function ajax_show_images() {
	$remote_table = V::get('tbl', '', $_REQUEST);
	$remote_id = V::get('id', '', $_REQUEST, 'int');

	$thiss = new stdClass();
	$thiss->DETECT_TABLE_NAME = $remote_table;

	// check remote id
	if ($remote_id <= 0) {
		header('HTTP/1.1 400: Bad Request');
		header('Warning: wrong ID L.' . __LINE__);
		exit;
	}

	// check remote table
	$remote_tables = DB_Image::conf_get('remote_tables');
	if (!in_array($remote_table, $remote_tables)) {
		header('HTTP/1.1 400: Bad Request');
		header('Warning: table not allowed L.' . __LINE__);
		exit;
	}

	$images = DB_Image::getImages($remote_table, $remote_id);
	if (!$images) {
		header('HTTP/1.1 400: Bad Request');
		header('Warning: images not found in db L.' . __LINE__);
		exit;
	}

	echo'<p>'."Zdjecia dla rekordu <b>{$remote_id}</b> z tabeli {$remote_table}".'</p>';

	foreach ($images as $r) {
		$src = "?function_init=fun_SHOW_IMAGE&image_id={$r->ID}";
		echo'<img src="'.$src.'" alt="'.$r->TYPE.'" />';
	}

	exit;
}

function ajax_zasob_check_table() {
	$zasob_id = V::get('zasob_id', '', $_REQUEST, 'int');
	if ($zasob_id <= 0) {
		echo'Error: Bad request';// TODO: header
		return;
	}

	$zasob = DB::get_by_id('CRM_LISTA_ZASOBOW', $zasob_id);
	if (!$zasob) {
		echo'Error: 404 not found';// TODO: header
		return;
	}

	// TODO: get config from parent DATABASE%
	$cnf_id = $zasob->PARENT_ID;
	//$ext_db = DB::getDB( $r->PARENT_ID );
	$cnf = Config::getZasobConf($cnf_id);
	if (!$cnf) {
		echo'<span class="err">'."Brak konfiguracji dla zasobu <b>{$cnf_id}</b>".'</span>';
		return;
	} else {
		$db = DB::getDB($cnf_id);
		if ($db->get_errors()) {
			echo'<span class="err">'."Wystapily bledy podczas polaczenia z baza danych (zasob {$cnf_id}):";
				echo '<br />'.implode('<br />', $db->get_errors());
			echo'</span>';
			return;
		} else {
			//$db;
			echo'CONN OK;';// TODO: msg OK
			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($db);echo'</pre>';
		}
	}

	// conn ok, check if table exists
	$sql = "show tables like '{$zasob->DESC}' ; ";
	$res = $db->query($sql);
	if ($db->num_rows($res) == 1) {
		echo'TABLE NAME OK;';// TODO: msg OK
	} else {
		echo'<span class="err">'."Niepoprawna nazwa tabeli <b>{$zasob->DESC}</b>".'</span>';
		return;
	}

	// conn ok, table exists, check table fields
	$fields = array();
	$sql = "describe `{$zasob->DESC}` ; ";
	$res = $db->query($sql);
	// Field, Type, Null, Key, Default, Extra
	// ID, int(10), NO, PRI, NULL, auto_increment
	// A_RECORD_CREATE_DATE, varchar(30), NO
	while ($r = $db->fetch($res)) {
		$params = new stdClass();
		// TODO: analyze field parameters: Type,Length,Default,Null?
		$params->Type = $r->Type;
		if (substr($r->Type, 0, 3) == 'int') {
			$params->Type = 'int';
			$params->Length = substr(substr($r->Type, 3), 1, -1);
		} else if (substr($r->Type, 0, 7) == 'varchar') {
			$params->Type = 'varchar';
			$params->Length = substr(substr($r->Type, 7), 1, -1);
		} else if (substr($r->Type, 0, 4) == 'enum') {
			$params->Type = 'enum';
			$params->Values = substr(substr($r->Type, 4), 1, -1);// TODO: add DANE under KOMORKA
		} else if (substr($r->Type, 0, 4) == 'date') {
			$params->Type = 'date';
		} else if (substr($r->Type, 0, 4) == 'text') {
			$params->Type = 'text';
		} else {
			$params->Type = 'unknown';
		}
		// TODO: ...
		if ($r->Default) $params->Default = $r->Default;
		else if ($r->Null == 'YES') $params->Default = 'Null';
		$fields[$r->Field] = $params;
	}

	echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">fields=';
	foreach ($fields as $f_name => $f_params) {
		echo"\n".'['.$f_name.']='.json_encode($f_params);
	}
	echo'</pre>';

	$komorki = array();
	$db = DB::getDB();
	$sql = "select
			`ID`, `TYPE`, `DESC`
			-- TODO: , `PARAMS`
		from `CRM_LISTA_ZASOBOW`
		where `PARENT_ID`='{$zasob->ID}'
	";
	$res = $db->query($sql);
	// Field, Type, Null, Key, Default, Extra
	// ID, int(10), NO, PRI, NULL, auto_increment
	// A_RECORD_CREATE_DATE, varchar(30), NO
	while ($r = $db->fetch($res)) {
		$komorki[$r->DESC] = $r;
	}

	$errors = array();
	foreach ($komorki as $z_name => $z) {
		if ($z->TYPE != 'KOMORKA') {
			$errors[$z->ID] = "Wrong type ({$z->TYPE},{$z->DESC})";
		} else if (!array_key_exists($z->DESC, $fields)) {
			$errors[$z->ID] = "Not exists ({$z->DESC})";
		} else {
		}
	}

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

	$errors = array();
	foreach ($fields as $f_name => $f_params) {
		if (!array_key_exists($f_name, $komorki)) {
			$errors[$f_name] = 'Not exists ('.json_encode($f_params).')';
		} else {
		}
	}
	echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">2 ';print_r($errors);echo'</pre>';

}

function ajax_get_proces() {
	echo'<p>TODO: test ajax function L' . __LINE__ . '</p>';
}
