<?php

/**
 * TODO: S_TECHNOLOGY - przepisywanie do SES_USERS2_A
 * TODO: dla aneks w GPON zostawiać stary jak jest, nie wyłączać i tworzyć nowy na waitingu
 */

error_reporting(E_ALL & ~E_NOTICE);

if (!defined('DS')) define('DS', DIRECTORY_SEPARATOR);
if (!defined('APP_PATH_ROOT')) define('APP_PATH_ROOT', dirname(__FILE__));
if (!defined('APP_PATH_WWW')) define('APP_PATH_WWW', dirname(__FILE__));
if (!defined('APP_PATH_CONFIG')) define('APP_PATH_CONFIG', APP_PATH_ROOT . DS . 'config');


function POKAZ_OFERTY_AKTUALNE_FUNC() {

if (file_exists(".config.php")) include(".config.php");

SEF('DEBUG_S');
require_once dirname(__FILE__) . '/' . 'se-lib' . '/' . 'Lib.php';
Lib::loadClass('V');
Lib::loadClass('User');
Lib::loadClass('Config');
Lib::loadClass('DB');

Lib::loadClass('PokazOfertyView');


$_GET['S_ADDRESS_STREET'] = V::get('S_ADDRESS_STREET', '', $_GET);
$_GET['print'] = V::get('print', '', $_GET);
$_GET['task'] = V::get('task', '', $_GET);
$_GET['user_id'] = V::get('user_id', '', $_GET, 'int');

switch ($_GET['task']) {
	case 'dodaj_aneks':
		POKAZ_OFERTY_AKTUALNE_FUNC__dodaj_aneks();
		return;
		break;
	case 'ajax_search_user':
		POKAZ_OFERTY_AKTUALNE_FUNC__ajax_search_user(V::get('q', '', $_REQUEST));
		return;
		break;
	case 'ajax_search_street':
		POKAZ_OFERTY_AKTUALNE_FUNC__ajax_search_street(V::get('S_ADDRESS_STREET', '', $_REQUEST));
		return;
		break;
	case 'activate_deal':// &task=activate_deal&id_deal=11253 @from DEALS_TABLE and DEALS_TABLE_EDIT @require Zasob KOMORKA
		POKAZ_OFERTY_AKTUALNE_FUNC__activate_deal(V::get('id_deal', '', $_REQUEST));
		return;
		break;
	case 'verify_deal':// &task=verify_deal&id_deal=11253 @from DEALS_TABLE_EDIT @require Zasob KOMORKA
		POKAZ_OFERTY_AKTUALNE_FUNC__verify_deal(V::get('id_deal', '', $_REQUEST));
		return;
		break;
	case 'verify_deals':// &task=verify_deals
		POKAZ_OFERTY_AKTUALNE_FUNC__verify_deals();
		return;
		break;
	case 'klient_umowy':// &task=klient_umowy&id_user
		POKAZ_OFERTY_AKTUALNE_FUNC__klient_umowy(V::get('id_user', '', $_REQUEST));
		return;
		break;
	case 'umowa_add_options':// &task=umowa_add_options&id_user &id_deal
		POKAZ_OFERTY_AKTUALNE_FUNC__umowa_add_options(V::get('id_user', '', $_REQUEST), V::get('id_deal', '', $_REQUEST));
		return;
		break;
	case 'umowa_rm_options':// &task=umowa_rm_options&id_user &id_deal
		POKAZ_OFERTY_AKTUALNE_FUNC__umowa_rm_options(V::get('id_user', '', $_REQUEST), V::get('id_deal', '', $_REQUEST));
		return;
		break;
	case 'rozlicz_month':// &task=rozlicz_month&month=
		POKAZ_OFERTY_AKTUALNE_FUNC__rozlicz_month(V::get('month', '', $_REQUEST));
		return;
		break;
	case 'activate_services_tv':// &task=activate_services_tv&id_services={ID_SERVICES}&id_ses_tv_a={ID}
		POKAZ_OFERTY_AKTUALNE_FUNC__activate_services_tv();
		return;
		break;
	case 'activate_services_net':// &task=activate_services_net&id_services={ID_SERVICES}&id_ses_tv_a={ID}
		POKAZ_OFERTY_AKTUALNE_FUNC__activate_services_net();
		return;
		break;
	case 'activate_services_voip':// &task=activate_services_voip&id_services={ID_SERVICES}&id_ses_tv_a={ID}
		POKAZ_OFERTY_AKTUALNE_FUNC__activate_services_voip();
		return;
		break;
	case 'ajaxUmowaZysk':
		POKAZ_OFERTY_AKTUALNE_FUNC__ajaxUmowaZysk();
		return;
		break;
	default:
		
}

if (!$_GET['print']) {
	MENU();
}


echo '<style type="text/css">'."
body{font-family:arial; font-size:12px;}

.tbl {margin:0 5px;font-size:small;}
/*
.tbl-hover:hover{background:#F3FFF3;}
*/
.tbl td,
.tbl th{padding:0 2px;border-style:solid;border-width:1px;}
.tbl th{font-weight:normal;color:#333;}
.tbl thead th{background:#F3F3F3;}
.tbl-offers th{padding:0 6px;text-align:right;font-weight:normal}
code{padding:0 2px;color:#666;}
code:hover{color:#000;background:#FF9494;}
.red{color:red;}
.green{color:green;}
.box{margin:5px;padding:3px 10px;border:1px solid silver;}
p{margin:3px 5px;}

.cell-A_STATUS-WAITING{background-color:#FF88FF;}
.cell-A_STATUS-NORMAL{background-color:#88FF88;}
.cell-A_STATUS-DELETED{background-color:#CCCCCC;}
.cell-A_STATUS-WARNING{background-color:#FFCCCC;}
.cell-A_STATUS-MONITOR{background-color:#fff;}
.cell-T_INSTALACJA_W_CIAGU_DNI{background-color:#E1E1E1;}

".'</style>';

$view = new PokazOfertyView();
echo $view->print_jquery_ui();

function get_rewir_info( $rewir ) {
	$ret = array('TV'=>false, 'SPD'=>0);// budynek has TV, SPD - max lan speed
	if (!$rewir) {
		return $ret;
	}

	echo "\n".'<!-- L.' . __LINE__ . "\n";
	$rewir_arr = explode('.', $rewir);
	foreach ($rewir_arr as $rewir_part) {
		if (strpos($rewir_part, 'TV') !== false) {
			if (false !== strpos($rewir_part, '?')) {
				$ret['TV_NOTE'] = "Rewir zawiera znak \"?\", więc instalacja telewizji jest możliwa po dłuższym okresie czasu (dokładny termin instalacji określa dział techniczny, z którym należy tą kwestię skonsultować).";// @from CRM_WSKAZNIK.3174 krok 1130 (2012-08-01)
			}
			$rewir_part_ok = str_replace(array('?','!'), '', $rewir_part);
			echo "part TV: (".$rewir_part."/".$rewir_part_ok.")\n";
			if ($rewir_part_ok == 'TV') {
				$ret['TV'] = true;
			}
		}
		if (strpos($rewir_part, 'GPON') !== false) {
			if (false !== strpos($rewir_part, '?')) {
			//	$ret['TV_NOTE'] = "Rewir zawiera znak \"?\", więc instalacja telewizji jest możliwa po dłuższym okresie czasu (dokładny termin instalacji określa dział techniczny, z którym należy tą kwestię skonsultować).";// @from CRM_WSKAZNIK.3174 krok 1130 (2012-08-01)
			}
			$rewir_part_ok = str_replace(array('?','!'), '', $rewir_part);
			//echo "part TV: (".$rewir_part."/".$rewir_part_ok.")\n";
			if ($rewir_part_ok == 'GPON') {
				$ret['GPON'] = true;
			}
		}
		if (substr($rewir_part, 0, 4) == 'SPDX') {
			$rewir_part_ok = substr($rewir_part, 3);
			if (str_replace('X', '', $rewir_part_ok) == '') {
				$ret['SPD'] = pow(2, strlen($rewir_part_ok));
			}
			echo "part SPD: (".$rewir_part."/".$rewir_part_ok.") = [".$ret['SPD']."]\n";
		}
	}//end foreach
	echo "\n".' -->'."\n";
	return $ret;
}

function get_building_a_status_info( $status ) {
	$building_a_status_info = '';
	switch ($status) {
		/* SELECT COUNT( * ) AS  `Rekordów` ,  `A_STATUS`  FROM  `BUILDINGS`  GROUP BY  `A_STATUS`  ORDER BY  `A_STATUS` ;
				337		NORMAL
				13		WARNING
				2			
				139		WAITING
				596		MONITOR
				2			TO_OFF
				35		DELETED
		*/
		case 'NORMAL':
			$building_a_status_info .= " - oznacza to, że zasób jest dostępny do podpisywania umów.";
			break;
		case 'WARNING':
			$building_a_status_info .= "Uwaga! budynek podłączony do naszej sieci, ale z powodów technicznych część lub cały budynek nie spełnia standardów podłączenia (np. dłuższy termin podłączenia z powodu braku pionu). W takim wypadku należy zastosować się do informacji wprowadzonych w polu T INSTALACJA W CIAGU DNI i powiadomić o tym klienta";
			break;
		case 'WAITING':
			$building_a_status_info .= "Uwaga! Budynek, który prawdopodobnie zostanie podłączony, zgodnie z informacjami z T INSTALACJA W CIAGU DNI. W razie wątpliwości należy zweryfikować w tabeli budynków";
			break;
		case 'MONITOR':
			$building_a_status_info .= "Uwaga! Budynek nie znajduje się w zasięgu sieci. Firma prowadzi analizę zainteresowania podłączeniem i jego opłacalności. Należy wykonać badanie!";
			break;
		default:
			$building_a_status_info .= " - Status rekordu powinien wynosić \"NORMAL\" - oznacza to, że zasób jest dostępny do podpisywania umów. Jeżeli zasób ma status np. \"WAITING\" - oznacza to, że jest aktualnie budowany przez dział inwestycji i należy sprawdzić dokładnie dalsze właściwości zasobu w celu odpowiedniego poinformowania klienta o terminie instalacji oraz zakresie możliwych usług do sprzedaży. Status \"MONITOR\" oznacza, że zasób jest brany pod uwagę do inwestycji - należy prowadzić akcje marketingowe. Kwestia podpisywania umów jest zależna od cech danego rekordu (budynku).";
	}
	return $building_a_status_info;
}


if (!$_GET['print']) {
	echo '<h1>'."POKAZ_OFERTY_AKTUALNE".'</h1>';
	echo '<script type="text/javascript">' . "

function ajax_search_req_street() {
	console.log('ajax_search_req_street()...');
	if (window.ajax_req_queue) window.ajax_req_queue.ajax_search_req('street');
}

function ajax_search_req_user() {
	console.log('ajax_search_req_user()...');
	if (window.ajax_req_queue) window.ajax_req_queue.ajax_search_req('user');
}

function ajax_street_select(n) {
	jQuery('#frm_S_ADDRESS_STREET').val(n.value);
	return false;
}

function ajax_user_select(n) {
	jQuery('#frm_Q').val(n.value);
	return false;
}

jQuery(document).ready(function(){

	window.ajax_req_queue = {
		cnf: new Array(),
		current_req: 0,
		queue_id: 0,
		queue_on: 0,
		add: function(cnf_name, ajax_fun, ajax_fun_arg, search_fld_id, frm_result_id){
			this.cnf[cnf_name] = {'ajax_fun': ajax_fun, 'ajax_fun_arg': ajax_fun_arg, 'search_fld': jQuery(search_fld_id), 'res_id': frm_result_id}

			this.cnf[cnf_name]['search_fld'].keyup(function(e){
				var n=e.target,c,code,regex;
				console.log(e);
				console.log(n.value);
				code=e.keyCode? e.keyCode : e.charCode;
				c=String.fromCharCode(code);
				regex=/^[0-9A-Za-z ]+$/; //^[a-zA-z;%]+$/
				if(regex.test(c)||code==8||code==46){//8=Backspace,46=Delete
					window.ajax_req_queue.search(cnf_name);
				}
				else if(code == 40){// 40 = key DOWN
					var res_sel=jQuery(window.ajax_req_queue.cnf[cnf_name]['res_id'] + ' select');
					if (res_sel.length > 0) {
						res_sel.focus();
					}
				}
				else {
					//console.log('NO');
				}
				return false;
			});
		},
		search: function(cnf_name){
			console.log('this.search('+cnf_name+') ' + this.cnf);
			if (undefined !== this.cnf[cnf_name]) {
				console.log('setTimeout(ajax_search_req_'+cnf_name+'())');
				queue_id=setTimeout('ajax_search_req_'+cnf_name+'()',250);
			}
			//jQuery('#wyniki #search-form').addClass('loading');
			window.ajax_req_queue.abort_current();
			console.log('ajax_search()...');
			if(window.ajax_req_queue.queue_on){
				console.log('clearTimeout('+window.ajax_req_queue.queue_id+')');
				clearTimeout(window.ajax_req_queue.queue_id);//anuluj poprzedni timer
			}
			console.log('setTimeout('+window.ajax_req_queue.queue_id+')');
			queue_on=1;
		},
		abort_current: function(){
			if(window.ajax_req_queue.current_req) window.ajax_req_queue.current_req.abort();
		},
		ajax_search_req: function(cnf_name){
			var result_node=jQuery(this.cnf[cnf_name].res_id),h,b;
			window.ajax_req_queue.abort_current();
			//console.log('ajax_search init ...');
			var arg_value=this.cnf[cnf_name].search_fld.val();
			console.log('ajax_search ' + cnf_name + ': ' + arg_value);

			if ('' == arg_value) {
				// TODO: clear select
				return;
			}

			//prepare post values:
			var url_params = new Array();
			url_params.push('FUNCTION_INIT=' + 'POKAZ_OFERTY_AKTUALNE_FUNC');
			url_params.push('HEADER_NOT_INIT=' + 'YES');
			url_params.push('MENU_INIT=' + 'DOL');
			url_params.push('HTML_HEADER_NOT_INIT=' + 'yes');
			url_params.push('task=' + this.cnf[cnf_name].ajax_fun);
			url_params.push(this.cnf[cnf_name].ajax_fun_arg + '=' + arg_value);
			url_params=url_params.join('&');

			window.ajax_req_queue.current_req = jQuery.post('index.php?' + url_params, '', function(data){
				console.log('XX data: ' + data + ' search(' + data.search('Brak Danych') + ')')
				//queue_req-=1;//zdejmij z kolejki
				if(data.length < 100 && -1 !== data.search('Brak Danych')){
					result_node.html('Brak Danych');
				}
				else{
					result_node.html(data);
				}
				//t.find('#search-form').removeClass('loading');
			});
		}
	};

	window.ajax_req_queue.add('street', 'ajax_search_street', 'S_ADDRESS_STREET', '#frm_S_ADDRESS_STREET', '#frm_S_ADDRESS_STREET_values');
	window.ajax_req_queue.add('user', 'ajax_search_user', 'q', '#frm_Q', '#frm_Q_values');
/*
	jQuery('#frm_S_ADDRESS_STREET').keyup(function(e){
		var n=e.target,c,code,regex;
		console.log(e);
		console.log(n.value);
		code=e.keyCode? e.keyCode : e.charCode;
		c=String.fromCharCode(code);
		regex=/^[0-9A-Za-z ]+$/; //^[a-zA-z;%]+$/
		if(regex.test(c)||code==8||code==46){//8=Backspace,46=Delete
			window.ajax_req_queue.search('street');
		}
		else {
			//console.log('NO');
		}
		return false;
	});
	jQuery('#frm_Q').keyup(function(e){
		var n=e.target,c,code,regex;
		console.log(e);
		console.log(n.value);
		code=e.keyCode? e.keyCode : e.charCode;
		c=String.fromCharCode(code);
		regex=/^[0-9A-Za-z ]+$/; //^[a-zA-z;%]+$/
		if(regex.test(c)||code==8||code==46){//8=Backspace,46=Delete
			window.ajax_req_queue.search('user');
		}
		else{
			//console.log('NO');
		}
		return false;
	});
*/
});
	" . '</script>';
	echo '<form action="' . "index.php" . '" method="GET">';
	echo '<input type="hidden" name="MENU_INIT" value="POKAZ_OFERTY_AKTUALNE_FUNC">';
	echo '<input type="hidden" name="ADD" value="ADD">';
	echo '<table cellspacing="0" cellpadding="0" border="0" style="margin:8px;">';
	echo '<tr>';
		echo '<th style="vertical-align:top;font-size:16px;">' . "Podaj skrót ulicy, dla jakiej chcesz wyszukać dostępne oferty" . '</th>';
		echo '<td style="padding:0 3px;vertical-align:top;">';
			echo '<input type="text" name="S_ADDRESS_STREET" size="10" id="' . "frm_S_ADDRESS_STREET" . '" value="' . $_GET['S_ADDRESS_STREET'] . '">';
		echo '</td>';
		echo '<td style="vertical-align:top;">';
			echo '<div id="frm_S_ADDRESS_STREET_values"></div>';
		echo '</td>';
		echo '<td style="vertical-align:top;">' . '<input type="submit" value="' . "Wybierz mieszkanie" . '">' . '</td>';
	echo '</tr></table>';
	echo '</form>';
}

if (!$_GET['S_ADDRESS_STREET']) {
	echo $view->print_ui_widget_errors("Podaj skrót adresu");
	return;
}

$building = 0;// wybrany budynek
$buildings = PokazOfertyHelper::get_buildings_by_mieszk($_GET['S_ADDRESS_STREET']);
if (empty($buildings)) {
	echo $view->print_ui_widget_errors("Brak danych");
	return;
}

{// budynki i mieszkanie info
	$buildings_sql_cols = PokazOfertyHelper::get_buildings_cols();

	if (count($buildings) == 1) {
		$building = reset($buildings);
		$marketing_sql_cols = PokazOfertyHelper::get_marketing_cols();
		echo '<table border="0" cellspacing="0" cellpadding="0">';
		echo '<thead>' . '<tr>' . '<th>' . "Budynek" . '</th>' . '<th>' . "Mieszkanie" . '</th>' . '</tr>' . '</thead>';
		echo '<tbody>' . '<tr>';
			echo '<td style="vertical-align:top;width:50%">';
				echo '<table border="1" cellspacing="0" cellpadding="0" class="tbl">';
				echo '<tbody>';
				if ($building->ID <= 0) {
					echo '<tr><td colspan="2">';
						echo '<p style="color:red">' . "Bledne dane:";
						if (empty($building->m__T_TELBOX_BUILDING_IN)) {
							echo '<br />' . "Brak wypełnionego pola T_TELBOX_BUILDING_IN w mieszkaniach.";
						} else if ($building->ID <= 0) {
							echo '<br />' . "Brak przypisanego mieszkania (T_TELBOX_BUILDING_IN={$building->m__T_TELBOX_BUILDING_IN}).";
						}
						echo '</p>';
					echo '</td></tr>';
				}
				else {
					foreach ($buildings_sql_cols as $k_sql_field => $v_label) {
						echo '<tr>';
						if ($k_sql_field == 'A_STATUS') {
							$building_title = '';
							switch ($building->A_STATUS) {
								case 'NORMAL':
									$building_title = " - oznacza to, że zasób jest dostępny do podpisywania umów.";
									break;
								case 'WARNING':
									$building_title = "Uwaga! budynek podłączony do naszej sieci, ale z powodów technicznych część lub cały budynek nie spełnia standardów podłączenia (np. dłuższy termin podłączenia z powodu braku pionu). W takim wypadku należy zastosować się do informacji wprowadzonych w polu T INSTALACJA W CIAGU DNI i powiadomić o tym klienta";
									break;
								case 'WAITING':
									$building_title = "Uwaga! Budynek, który prawdopodobnie zostanie podłączony, zgodnie z informacjami z T INSTALACJA W CIAGU DNI. W razie wątpliwości należy zweryfikować w tabeli budynków";
									break;
								case 'MONITOR':
									$building_title = "Uwaga! Budynek nie znajduje się w zasięgu sieci. Firma prowadzi analizę zainteresowania podłączeniem i jego opłacalności. Należy wykonać badanie!";
									break;
								default:
									$building_title = " - Status rekordu powinien wynosić \"NORMAL\" - oznacza to, że zasób jest dostępny do podpisywania umów. Jeżeli zasób ma status np. \"WAITING\" - oznacza to, że jest aktualnie budowany przez dział inwestycji i należy sprawdzić dokładnie dalsze właściwości zasobu w celu odpowiedniego poinformowania klienta o terminie instalacji oraz zakresie możliwych usług do sprzedaży. Status \"MONITOR\" oznacza, że zasób jest brany pod uwagę do inwestycji - należy prowadzić akcje marketingowe. Kwestia podpisywania umów jest zależna od cech danego rekordu (budynku).";
							}
							echo '<th><b>' . $v_label . '<b></th>' . '<td class="cell-A_STATUS-' . $building->A_STATUS . '" title="' . $building_title . '">';
							echo '<b>' . $building->A_STATUS . ' </b>';
							echo '</td>';
						} else if ($k_sql_field == 'T_INSTALACJA_W_CIAGU_DNI') {
							echo '<th class="cell-T_INSTALACJA_W_CIAGU_DNI">' . $v_label . '</th>' . '<td class="cell-T_INSTALACJA_W_CIAGU_DNI">' . $building->$k_sql_field . '</td>';
						} else {
							echo '<th>' . $v_label . '</th>' . '<td>' . $building->$k_sql_field . '</td>';
						}
						echo '</tr>';
					}
				}
				echo '</tbody>';
				echo '</table>';
			echo '</td>';
			echo '<td style="vertical-align:top">';
				echo '<table border="1" cellspacing="0" cellpadding="0" class="tbl">';
				echo '<tbody>';
				foreach ($marketing_sql_cols as $k_sql_field => $v_label) {
					echo '<tr>';
					$k_sql_field = 'm__' . $k_sql_field;
					echo '<th>' . $v_label . '</th>' . '<td>' . $building->$k_sql_field . '</td>';
					echo '</tr>';
				}
				echo '</tbody>';
				echo '</table>';
			echo '</td>';
		echo '</tr>' . '</tbody>';
		echo '</table>';
	}
	else {// old way - should be only one
		echo '<table border="1" cellspacing="0" cellpadding="0" class="tbl">';
		echo'<thead>';
			echo'<tr>';
				foreach ($buildings_sql_cols as $k => $v) {
					if ($k == 'ID') {
						echo'<th>'."&nbsp;".'</th>';
					} else {
						echo'<th>'.$v.'</th>';
					}
					if ($k == 'M_REWIR') {
						echo'<th>'."TV".'</th>';
						echo'<th>'."SPD (Mbit/sek)".'</th>';
					}
				}//end foreach
			echo'</tr>';
		echo'</thead>';
		foreach ($buildings as $r) {
			echo'<tr>';
				foreach ($buildings_sql_cols as $k => $v) {
					$cls = '';
					if ($k == 'A_STATUS') {
						$cls = ' class="cell-A_STATUS-'.$r->$k.'"';
					}
					echo'<td'.$cls.'>';
					if ($k == 'ID') {
						echo'<a href="'."?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&S_ADDRESS_STREET=".$r->S_ADDRESS_STREET.'">'."Wybierz".'</a>';
					} else {
						echo $r->$k;
					}
					echo'</td>';
					if ($k == 'M_REWIR') {
						$rewir_info = get_rewir_info( $r->M_REWIR );
						echo'<td>'.(($rewir_info['TV'])? '<b class="green">'."TAK".'</b>' : '<b class="red">'."NIE".'</b>').'</td>';
						echo'<td>'.(($rewir_info['SPD'] > 0)? $rewir_info['SPD'] : '<b class="red">'."NIE".'</b>').'</td>';
					}
				}
			echo'</tr>';
		}
		echo'</table>';
	}
}// budynki info

// jesli tylko 1 to szukaj ofert (S_ADDRESS_STREET uniq)
if (count($buildings) == 1) {
	$building = reset($buildings);
}

if (!$building) {
	echo $view->print_ui_widget_errors("Wybierz budynek");
	return;
}
if ($building->ID <= 0) {
	echo $view->print_ui_widget_errors("Brak budynku lub błędne dane.");
	return;
}

$building_status_info = get_building_a_status_info($building->A_STATUS);
$building_status_title = "A_STATUS: " . '<b style="padding:0 4px;" class="cell-A_STATUS-' . $building->A_STATUS . '">' . $building->A_STATUS . '</b>';
if (in_array($building->A_STATUS, array('WAITING', 'MONITOR'))) {
	echo '<br />' . $view->print_ui_widget_errors($building_status_title . '<br>' . $building_status_info);
} else {
	echo $view->print_ui_widget_info($building_status_title, $building_status_info);
}

if (!in_array($building->A_STATUS, array('NORMAL', 'WARNING', 'WAITING', 'MONITOR'))) {
	$info = "W przypadku gdy klient jest zainteresowany ofertą na adresie, na którym nie możemy jeszcze świadczyć naszych usług proszę wyszukać i przedstawić oferty standardowe dla adresu: ";
	$info .= '<a href="' . "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&ADD=ADD&S_ADDRESS_STREET=CI50%2F1" . '">' . "CI50/1" . '</a>';
	$info .= " Przedstawiamy ofertę tylko informacyjnie, nie podpisujemy umowy ze względu na brak możliwości podłączenia klienta!";
	echo '<br />' . $view->print_ui_widget_errors($info);
	return;
}

$rewir_info = get_rewir_info( $building->M_REWIR );
{// M_REWIR
	$rewir_msg = '';
	if ($rewir_info['TV']) {
		$rewir_msg .= " Można oferować TV.";
	} else if($rewir_info['GPON']) {
		$rewir_msg .= " <b>Można oferować TV w technologii GPON</b>";
	} else {
		$rewir_msg .= ' <b class="red">'."Nie można oferować TV.".'</b>';
	}
	if ($rewir_info['SPD'] > 0) {
		$rewir_msg .= " Można ofertować Internet max <b>".$rewir_info['SPD']."</b> Mbit/sek.";
	} else {
		$rewir_msg .= ' <b class="red">'."Nie można oferować Internetu.".'</b>';
	}
	if (!empty($rewir_info['TV_NOTE'])) {
		$rewir_msg .= '<br />' . '<b style="color:red">' . "Uwaga: " . $rewir_info['TV_NOTE'] . '</b>';
	}
	if (!empty($rewir_msg)) {
		echo $view->print_ui_widget_info($rewir_msg);
	}
}// M_REWIR

	// search oferty:
	$DBG = V::get('DBG', 0, $_GET, 'int');

$oferty_group_cols = array();
$oferty_group_cols ['0_1380']= array('label'=>"", 'title'=>"", 'field'=>"ID");
//$oferty_group_cols ['0_COMPANY']= array('label'=>"nazwa firmy", 'title'=>, 'field'=>"P_SERVICE_COMPANY");
$oferty_group_cols ['0_451']= array('label'=>"nazwa promocji", 'title'=>"", 'field'=>'P_PROMOTION_NAME');
$oferty_group_cols ['0_456']= array('label'=>"okres umowy", 'title'=>"", 'field'=>'P_DEALTERM_MONTHS');
$oferty_group_cols ['0_1579']= array('label'=>"ważna od", 'title'=>"", 'field'=>'P_OFFER_TERM_BEGIN');
$oferty_group_cols ['0_464']= array('label'=>"ważna do", 'title'=>"", 'field'=>'P_OFFER_TERM');
$oferty_group_cols ['0_1743_ID_NET']= array('label'=>"", 'title'=>"Jakiej dotyczy oferty na Internet", 'field'=>'ID_NET');
$oferty_group_cols ['0_1744_ID_TV']= array('label'=>"", 'title'=>"Jakiej dotyczy oferty na Telewizję", 'field'=>'ID_TV');
$oferty_group_cols ['0_1745_ID_TVC']= array('label'=>"", 'title'=>"Jakiej dotyczy oferty na TV Cyfrową", 'field'=>'ID_TVC');
//$oferty_group_cols ['0_1746_ID_TVCP']= array('label'=>"", 'title'=>"Jakie są dostępne w tej ofercie pakiety cyfrowe (ile kosztuja)", 'field'=>'ID_TVCP');
$oferty_group_cols ['0_1747_ID_TEL']= array('label'=>"", 'title'=>"Jakiej dotyczy oferty na Telefon", 'field'=>'ID_TEL');
$oferty_group_cols ['0_2621_ID_TVCP_1']= array('label'=>"", 'title'=>"Jakiej dotyczy oferty na pakiet TV Cyfrowej", 'field'=>'ID_TVCP_1');
$oferty_group_cols ['0_2622_ID_TVCP_2']= array('label'=>"", 'title'=>"Jakiej dotyczy oferty na pakiet TV Cyfrowej", 'field'=>'ID_TVCP_2');
$oferty_group_cols ['0_2623_ID_TVCP_3']= array('label'=>"", 'title'=>"Jakiej dotyczy oferty na pakiet TV Cyfrowej", 'field'=>'ID_TVCP_3');
//$oferty_group_cols ['0_2624_ID_TVCP_4']= array('label'=>"", 'title'=>"Jakiej dotyczy oferty na pakiet TV Cyfrowej", 'field'=>'ID_TVCP_4');
$oferty_group_cols ['0_1627']= array('label'=>"", 'title'=>"", 'field'=>'M_REWIR');

	$oferty_cols = array();
	$oferty_cols_desc = array();
	$oferty_cols_desc['0_1743_ID_NET'] = 'NET';
	$oferty_cols_desc['0_1744_ID_TV'] = 'TV';
	$oferty_cols_desc['0_1745_ID_TVC'] = 'TVC';
	$oferty_cols_desc['0_2621_ID_TVCP_1'] = 'TVCP';
	$oferty_cols_desc['0_2622_ID_TVCP_2'] = 'TVCP';
	$oferty_cols_desc['0_2623_ID_TVCP_3'] = 'TVCP';
	$oferty_cols_desc['0_1747_ID_TEL'] = 'TEL';
	$oferty_cols ['0_1743_ID_NET'] = array();
	$oferty_cols ['0_1743_ID_NET']['1_1385']= array('label'=>"ID oferty", 'field'=>'ID');
//	$oferty_cols ['0_1743_ID_NET']['1_449']= array('label'=>"Typ usługi", 'field'=>'P_SERVICE');
	$oferty_cols ['0_1743_ID_NET']['1_450']= array('label'=>"Nazwa oferty", 'field'=>'P_SERVICE_NAME');
	$oferty_cols ['0_1743_ID_NET']['1_458']= array('label'=>"Promocyjna cena instalacji/aktywacji (brutto)", 'field'=>'P_INSTALL_QUOTE');
//	$oferty_cols ['0_1743_ID_NET']['t1_1578']= array('label'=>"Nominalna cena opłaty instalacyjnej (brutto)", 'field'=>'P_INSTALL_QUOTE_NORMAL');
	$oferty_cols ['0_1743_ID_NET']['1_459']= array('label'=>"Cena abonamentu po promocji (brutto)", 'field'=>'P_CONTRACT_PRICE');
	$oferty_cols ['0_1743_ID_NET']['1_460']= array('label'=>"Wartość abonamentu w promocyjnych miesiącach (brutto)", 'field'=>'P_PROMO_MONTH_PRICE');
	$oferty_cols ['0_1743_ID_NET']['1_461']= array('label'=>"Nominalna wartość abonamentu (brutto)", 'field'=>'P_NORMAL_PRICE');
	$oferty_cols ['0_1743_ID_NET']['1_457']= array('label'=>"Ilość promocyjnych miesięcy", 'field'=>'P_DEAL_PROMO_MONTHS');
	$oferty_cols ['0_1743_ID_NET']['t1_srednia']= array('label'=>"srednia (brutto)", 'field'=>'srednia');
	$oferty_cols ['0_1743_ID_NET']['t1_srednia_netto']= array('field'=>'srednia_netto');
	$oferty_cols ['0_1743_ID_NET']['t1_1580']= array('label'=>"Upust od ceny normalnej do wyliczeń kary (brutto)", 'field'=>'P_DISCOUNT_TOTAL');
	$oferty_cols ['0_1743_ID_NET']['[1_452]']= array('label'=>"DOWNLOAD", 'field'=>'P_S_PARAM1');
	$oferty_cols ['0_1743_ID_NET']['[1_453]']= array('label'=>"UPLOAD", 'field'=>'P_S_PARAM2');
	$oferty_cols ['0_1743_ID_NET']['[1_454]']= array('label'=>"Limit ściągania danych", 'field'=>'P_S_LIMIT');
	$oferty_cols ['0_1743_ID_NET']['[1_462]']= array('label'=>"Wielkość w MegaBajtach konta pocztowego", 'field'=>'P_S_MAILBOX_SIZE');
	$oferty_cols ['0_1743_ID_NET']['[1_463]']= array('label'=>"Pojemność strony: (MB)", 'field'=>'P_S_WWW_SIZE');
	$oferty_cols ['0_1744_ID_TV'] = array();
	$oferty_cols ['0_1744_ID_TV']['2_1385']= array('label'=>"ID oferty", 'field'=>'ID');
//	$oferty_cols ['0_1744_ID_TV']['2_449']= array('label'=>"Typ usługi", 'field'=>'P_SERVICE');
	$oferty_cols ['0_1744_ID_TV']['2_450']= array('label'=>"Nazwa oferty", 'field'=>'P_SERVICE_NAME');
	$oferty_cols ['0_1744_ID_TV']['2_458']= array('label'=>"Promocyjna cena instalacji (brutto)", 'field'=>'P_INSTALL_QUOTE');
//	$oferty_cols ['0_1744_ID_TV']['t2_1578']= array('label'=>"Nominalna cena opłaty instalacyjnej (brutto)", 'field'=>'P_INSTALL_QUOTE_NORMAL');
	$oferty_cols ['0_1744_ID_TV']['2_459']= array('label'=>"Cena abonamentu po promocji (brutto)", 'field'=>'P_CONTRACT_PRICE');
	$oferty_cols ['0_1744_ID_TV']['2_460']= array('label'=>"Wartość abonamentu w promocyjnych miesiącach (brutto)", 'field'=>'P_PROMO_MONTH_PRICE');
	$oferty_cols ['0_1744_ID_TV']['2_461']= array('label'=>"Nominalna wartość abonamentu (brutto)", 'field'=>'P_NORMAL_PRICE');
	$oferty_cols ['0_1744_ID_TV']['2_457']= array('label'=>"Ilość promocyjnych miesięcy", 'field'=>'P_DEAL_PROMO_MONTHS');
	$oferty_cols ['0_1744_ID_TV']['t2_srednia']= array('label'=>"srednia (brutto)", 'field'=>'srednia');
	$oferty_cols ['0_1744_ID_TV']['t2_srednia_netto']= array('field'=>'srednia_netto');
	$oferty_cols ['0_1744_ID_TV']['t2_1580']= array('label'=>"Upust od ceny normalnej do wyliczeń kary (brutto)", 'field'=>'P_DISCOUNT_TOTAL');
	$oferty_cols ['0_1745_ID_TVC'] = array();
	$oferty_cols ['0_1745_ID_TVC']['3_1385']= array('label'=>"ID oferty", 'field'=>'ID');
//	$oferty_cols ['0_1745_ID_TVC']['3_449']= array('label'=>"Typ usługi", 'field'=>'P_SERVICE');
	$oferty_cols ['0_1745_ID_TVC']['3_450']= array('label'=>"Nazwa oferty", 'field'=>'P_SERVICE_NAME');
	$oferty_cols ['0_1745_ID_TVC']['3_458']= array('label'=>"Promocyjna cena instalacji (brutto)", 'field'=>'P_INSTALL_QUOTE');
//	$oferty_cols ['0_1745_ID_TVC']['t3_1578']= array('label'=>"Nominalna cena opłaty instalacyjnej (brutto)", 'field'=>'P_INSTALL_QUOTE_NORMAL');
	$oferty_cols ['0_1745_ID_TVC']['3_459']= array('label'=>"Cena abonamentu po promocji (brutto)", 'field'=>'P_CONTRACT_PRICE');
	$oferty_cols ['0_1745_ID_TVC']['3_460']= array('label'=>"Wartość abonamentu w promocyjnych miesiącach (brutto)", 'field'=>'P_PROMO_MONTH_PRICE');
	$oferty_cols ['0_1745_ID_TVC']['3_461']= array('label'=>"Nominalna wartość abonamentu (brutto)", 'field'=>'P_NORMAL_PRICE');
	$oferty_cols ['0_1745_ID_TVC']['3_457']= array('label'=>"Ilość promocyjnych miesięcy", 'field'=>'P_DEAL_PROMO_MONTHS');
	$oferty_cols ['0_1745_ID_TVC']['t3_srednia']= array('label'=>"srednia (brutto)", 'field'=>'srednia');
	$oferty_cols ['0_1745_ID_TVC']['t3_srednia_netto']= array('field'=>'srednia_netto');
	$oferty_cols ['0_1745_ID_TVC']['t3_1580']= array('label'=>"Upust od ceny normalnej do wyliczeń kary (brutto)", 'field'=>'P_DISCOUNT_TOTAL');
	$oferty_cols ['0_2621_ID_TVCP_1'] = array();
	$oferty_cols ['0_2621_ID_TVCP_1']['4_1385']= array('label'=>"ID oferty", 'field'=>'ID');
//	$oferty_cols ['0_2621_ID_TVCP_1']['4_449']= array('label'=>"Typ usługi", 'field'=>'P_SERVICE');
	$oferty_cols ['0_2621_ID_TVCP_1']['4_450']= array('label'=>"Nazwa oferty", 'field'=>'P_SERVICE_NAME');
	$oferty_cols ['0_2621_ID_TVCP_1']['4_458']= array('label'=>"Promocyjna cena instalacji (brutto)", 'field'=>'P_INSTALL_QUOTE');
//	$oferty_cols ['0_2621_ID_TVCP_1']['t4_1578']= array('label'=>"Nominalna cena opłaty instalacyjnej (brutto)", 'field'=>'P_INSTALL_QUOTE_NORMAL');
	$oferty_cols ['0_2621_ID_TVCP_1']['4_459']= array('label'=>"Cena abonamentu po promocji (brutto)", 'field'=>'P_CONTRACT_PRICE');
	$oferty_cols ['0_2621_ID_TVCP_1']['4_460']= array('label'=>"Wartość abonamentu w promocyjnych miesiącach (brutto)", 'field'=>'P_PROMO_MONTH_PRICE');
	$oferty_cols ['0_2621_ID_TVCP_1']['4_461']= array('label'=>"Nominalna wartość abonamentu (brutto)", 'field'=>'P_NORMAL_PRICE');
	$oferty_cols ['0_2621_ID_TVCP_1']['4_457']= array('label'=>"Ilość promocyjnych miesięcy", 'field'=>'P_DEAL_PROMO_MONTHS');
	$oferty_cols ['0_2621_ID_TVCP_1']['t4_srednia']= array('label'=>"srednia (brutto)", 'field'=>'srednia');
	$oferty_cols ['0_2621_ID_TVCP_1']['t4_srednia_netto']= array('field'=>'srednia_netto');
	$oferty_cols ['0_2621_ID_TVCP_1']['t4_1580']= array('label'=>"Upust od ceny normalnej do wyliczeń kary (brutto)", 'field'=>'P_DISCOUNT_TOTAL');
	$oferty_cols ['0_2622_ID_TVCP_2'] = array();
	$oferty_cols ['0_2622_ID_TVCP_2']['6_1385']= array('label'=>"ID oferty", 'field'=>'ID');
//	$oferty_cols ['0_2622_ID_TVCP_2']['6_449']= array('label'=>"Typ usługi", 'field'=>'P_SERVICE');
	$oferty_cols ['0_2622_ID_TVCP_2']['6_450']= array('label'=>"Nazwa oferty", 'field'=>'P_SERVICE_NAME');
	$oferty_cols ['0_2622_ID_TVCP_2']['6_458']= array('label'=>"Promocyjna cena instalacji (brutto)", 'field'=>'P_INSTALL_QUOTE');
//	$oferty_cols ['0_2622_ID_TVCP_2']['t6_1578']= array('label'=>"Nominalna cena opłaty instalacyjnej (brutto)", 'field'=>'P_INSTALL_QUOTE_NORMAL');
	$oferty_cols ['0_2622_ID_TVCP_2']['6_459']= array('label'=>"Cena abonamentu po promocji (brutto)", 'field'=>'P_CONTRACT_PRICE');
	$oferty_cols ['0_2622_ID_TVCP_2']['6_460']= array('label'=>"Wartość abonamentu w promocyjnych miesiącach (brutto)", 'field'=>'P_PROMO_MONTH_PRICE');
	$oferty_cols ['0_2622_ID_TVCP_2']['6_461']= array('label'=>"Nominalna wartość abonamentu (brutto)", 'field'=>'P_NORMAL_PRICE');
	$oferty_cols ['0_2622_ID_TVCP_2']['6_457']= array('label'=>"Ilość promocyjnych miesięcy", 'field'=>'P_DEAL_PROMO_MONTHS');
	$oferty_cols ['0_2622_ID_TVCP_2']['t6_srednia']= array('label'=>"srednia (brutto)", 'field'=>'srednia');
	$oferty_cols ['0_2622_ID_TVCP_2']['t6_srednia_netto']= array('field'=>'srednia_netto');
	$oferty_cols ['0_2622_ID_TVCP_2']['t6_1580']= array('label'=>"Upust od ceny normalnej do wyliczeń kary (brutto)", 'field'=>'P_DISCOUNT_TOTAL');
	$oferty_cols ['0_2623_ID_TVCP_3'] = array();
	$oferty_cols ['0_2623_ID_TVCP_3']['7_1385']= array('label'=>"ID oferty", 'field'=>'ID');
//	$oferty_cols ['0_2623_ID_TVCP_3']['7_449']= array('label'=>"Typ usługi", 'field'=>'P_SERVICE');
	$oferty_cols ['0_2623_ID_TVCP_3']['7_450']= array('label'=>"Nazwa oferty", 'field'=>'P_SERVICE_NAME');
	$oferty_cols ['0_2623_ID_TVCP_3']['7_458']= array('label'=>"Promocyjna cena instalacji (brutto)", 'field'=>'P_INSTALL_QUOTE');
//	$oferty_cols ['0_2623_ID_TVCP_3']['t7_1578']= array('label'=>"Nominalna cena opłaty instalacyjnej (brutto)", 'field'=>'P_INSTALL_QUOTE_NORMAL');
	$oferty_cols ['0_2623_ID_TVCP_3']['7_459']= array('label'=>"Cena abonamentu po promocji (brutto)", 'field'=>'P_CONTRACT_PRICE');
	$oferty_cols ['0_2623_ID_TVCP_3']['7_460']= array('label'=>"Wartość abonamentu w promocyjnych miesiącach (brutto)", 'field'=>'P_PROMO_MONTH_PRICE');
	$oferty_cols ['0_2623_ID_TVCP_3']['7_461']= array('label'=>"Nominalna wartość abonamentu (brutto)", 'field'=>'P_NORMAL_PRICE');
	$oferty_cols ['0_2623_ID_TVCP_3']['7_457']= array('label'=>"Ilość promocyjnych miesięcy", 'field'=>'P_DEAL_PROMO_MONTHS');
	$oferty_cols ['0_2623_ID_TVCP_3']['t7_srednia']= array('label'=>"srednia (brutto)", 'field'=>'srednia');
	$oferty_cols ['0_2623_ID_TVCP_3']['t7_srednia_netto']= array('field'=>'srednia_netto');
	$oferty_cols ['0_2623_ID_TVCP_3']['t7_1580']= array('label'=>"Upust od ceny normalnej do wyliczeń kary (brutto)", 'field'=>'P_DISCOUNT_TOTAL');
	$oferty_cols ['0_1747_ID_TEL'] = array();
	$oferty_cols ['0_1747_ID_TEL']['5_1385']= array('label'=>"ID oferty", 'field'=>'ID');
//	$oferty_cols ['0_1747_ID_TEL']['5_449']= array('label'=>"Typ usługi", 'field'=>'P_SERVICE');
	$oferty_cols ['0_1747_ID_TEL']['5_450']= array('label'=>"Nazwa oferty", 'field'=>'P_SERVICE_NAME');
	$oferty_cols ['0_1747_ID_TEL']['5_458']= array('label'=>"Promocyjna cena instalacji (brutto)", 'field'=>'P_INSTALL_QUOTE');
//	$oferty_cols ['0_1747_ID_TEL']['t5_1578']= array('label'=>"Nominalna cena opłaty instalacyjnej (brutto)", 'field'=>'P_INSTALL_QUOTE_NORMAL');
	$oferty_cols ['0_1747_ID_TEL']['5_459']= array('label'=>"Cena abonamentu po promocji (brutto)", 'field'=>'P_CONTRACT_PRICE');
	$oferty_cols ['0_1747_ID_TEL']['5_460']= array('label'=>"Wartość abonamentu w promocyjnych miesiącach (brutto)", 'field'=>'P_PROMO_MONTH_PRICE');
	$oferty_cols ['0_1747_ID_TEL']['5_461']= array('label'=>"Nominalna wartość abonamentu (brutto)", 'field'=>'P_NORMAL_PRICE');
	$oferty_cols ['0_1747_ID_TEL']['5_457']= array('label'=>"Ilość promocyjnych miesięcy", 'field'=>'P_DEAL_PROMO_MONTHS');
	$oferty_cols ['0_1747_ID_TEL']['t5_srednia']= array('label'=>"srednia (brutto)", 'field'=>'srednia');
	$oferty_cols ['0_1747_ID_TEL']['t5_srednia_netto']= array('field'=>'srednia_netto');
	$oferty_cols ['0_1747_ID_TEL']['t5_1580']= array('label'=>"Upust od ceny normalnej do wyliczeń kary (brutto)", 'field'=>'P_DISCOUNT_TOTAL');

	$oferty_filters = array();
	$oferty_filters ['f_COM'] = array('label'=>"COMPANY", 'values'=>array('BIALL-NET'=>"t0.`P_SERVICE_COMPANY`='BN'", 'NETDAY'=>"t0.`P_SERVICE_COMPANY`='NETDAY'"), 'default'=>"BIALL-NET");
	$oferty_filters ['f_A_STATUS'] = array('label'=>"Oferty A_STATUS", 'default'=>"NORMAL");
	$oferty_filters ['f_A_STATUS']['values'] = array();
	$oferty_filters ['f_A_STATUS']['values']['NORMAL'] = "t0.`A_STATUS`='NORMAL'";
	$oferty_filters ['f_A_STATUS']['values']['WSZYSTKIE'] = "t0.`A_STATUS`in('WAITING','NORMAL')";
	$oferty_filters ['f_A_STATUS']['values']['TEST'] = "t0.`A_STATUS`in('WAITING','NORMAL','MONITOR')";
	$oferty_filters ['f_ID_NET'] = array('label'=>"Internet", 'values'=>array('MOZE'=>"", 'TAK'=>"t0.`ID_NET`>0", 'NIE'=>"t0.`ID_NET`=0"), 'default'=>"MOZE");
	$oferty_filters ['f_ID_TV'] = array('label'=>"TV", 'values'=>array('MOZE'=>"", 'TAK'=>"t0.`ID_TV`>0", 'NIE'=>"t0.`ID_TV`=0"), 'default'=>"MOZE");
	$oferty_filters ['f_ID_TVC'] = array('label'=>"TVC", 'values'=>array('MOZE'=>"", 'TAK'=>"t0.`ID_TVC`>0", 'NIE'=>"t0.`ID_TVC`=0"), 'default'=>"MOZE");
	$oferty_filters ['f_ID_TVCP'] = array('label'=>"TVCP", 'values'=>array('MOZE'=>"", 'TAK'=>"(t0.`ID_TVCP_1`>0 or t0.`ID_TVCP_2`>0 or t0.`ID_TVCP_3`>0)", 'NIE'=>"(t0.`ID_TVCP_1`=0 and t0.`ID_TVCP_2`=0 and t0.`ID_TVCP_3`=0)"), 'default'=>"MOZE");
	$oferty_filters ['f_ID_TEL'] = array('label'=>"TEL", 'values'=>array('MOZE'=>"", 'TAK'=>"t0.`ID_TEL`>0", 'NIE'=>"t0.`ID_TEL`=0"), 'default'=>"MOZE");
	$oferty_filters ['f_P_DEALTERM_MONTHS'] = array('label'=>"okres umowy", 'values'=>array(
			'WSZYSTKIE'=>""
			, '24'=>"t0.`P_DEALTERM_MONTHS`='24'"
			, '18'=>"t0.`P_DEALTERM_MONTHS`='18'"
			, '12'=>"t0.`P_DEALTERM_MONTHS`='12'"
//			, 'INNE'=>"t0.`P_DEALTERM_MONTHS` not in ('24','18','12')"
		), 'default'=>"WSZYSTKIE");
	$oferty_filters ['f_P_OFFER_TARGET'] = array('label'=>"OFFER TARGET", 'values'=>array('WSZYSTKIE'=>""), 'help'=>array(), 'default'=>"WSZYSTKIE");
	SEF('P_OFFER_TARGET');
	$target_params = P_OFFER_TARGET('', '', array('task' => 'get_all_params'));
	if (!empty($target_params)) {
		foreach ($target_params['targets'] as $k_name => $v_opis) {
			$oferty_filters['f_P_OFFER_TARGET']['values'][$k_name] = "t0.`P_OFFER_TARGET`='{$k_name}'";
			$oferty_filters['f_P_OFFER_TARGET']['help'][$k_name] = $v_opis;
		}
		foreach ($target_params['colors'] as $k_name => $v_color) {
			$oferty_filters['f_P_OFFER_TARGET']['color'][$k_name] = $v_color;
		}
	}

	$oferty_filters_pomin = array();
	foreach ($oferty_filters as $k_filter => $v_params) {
		$oferty_filters[$k_filter]['value'] = V::get($k_filter, $v_params['default'], $_GET);
	}//end foreach

$sql_where_filter_add = "";
{// prepare sql
	$sql_where_filter_add_arr = array();
	{// oferty_filters_pomin
		foreach ($oferty_filters as $k_field => $v_params) {
			if (substr($k_field, 0, 5) == 'f_ID_') {
				$curr_service = substr($k_field, 5);
				//if (!in_array($curr_service, $services)) {
				//	$oferty_filters_pomin []= $k_field;
				//	continue;
				//}
			}
			if ($v_params['values'][ $v_params['value'] ]) {
				$sql_where_filter_add_arr []= $v_params['values'][ $v_params['value'] ];
			}
		}
	}// oferty_filters_pomin
	$sql_where_filter_add = (!empty($sql_where_filter_add_arr))? " and ".implode(" and ", $sql_where_filter_add_arr) : "";

	//$sql_P_SERVICE_COMPANY = 'BN';
}// prepare sql

//$sql_where_rewir_add = "'".$building->M_REWIR."' like t0.`M_REWIR`";
$sql_where_rewir_add_company = '';
	{
		if ($oferty_filters['f_COM']['value'] == 'BIALL-NET') {
			$sql_where_rewir_add_company = " and sub_g.`P_SERVICE_COMPANY`='BN' ";
		} else if ($oferty_filters['f_COM']['value'] == 'NETDAY') {
			$sql_where_rewir_add_company = " and sub_g.`P_SERVICE_COMPANY`='NETDAY' ";
		}
	}
$sql_where_rewir_add = "IF( (
		select count(1)
		from `USERS2_OFFERS_GROUPS` as sub_g
		where sub_g.`M_REWIR`='".$building->M_REWIR."' and sub_g.`A_STATUS`='NORMAL'
			{$sql_where_rewir_add_company}
		limit 1
	) > 0
	, '".$building->M_REWIR."'=t0.`M_REWIR`
	, '".$building->M_REWIR."' like t0.`M_REWIR`
)";

$sql = "
SELECT
 t0.`ID` as `0_1380` ,
 t0.`P_SERVICE_COMPANY` as `0_COMPANY`,
 t0.`P_PROMOTION_NAME` as `0_451` ,
 t0.`S_ALIAS` as `0_S_ALIAS` ,
 t0.`P_DEALTERM_MONTHS` as `0_456` ,
 t0.`P_OFFER_TERM_BEGIN` as `0_1579`, t0.P_OFFER_TERM as `0_464` ,
 t0.`M_REWIR` as `0_447`  ,
-- concat('|',(select group_concat(S_ADDRESS_STREET, '|') from BUILDINGS where M_REWIR like concat(t0.M_REWIR,'%') limit 1),'|') as `x_410`,
 t0.`ID_NET`  as `0_1743_ID_NET` ,
 t0.`ID_TV`   as `0_1744_ID_TV` ,
 t0.`ID_TVC`  as `0_1745_ID_TVC` ,
 t0.`ID_TVCP` as `0_1746_ID_TVCP` ,
 t0.`ID_TVCP_1` as `0_2621_ID_TVCP_1` ,
 t0.`ID_TVCP_2` as `0_2622_ID_TVCP_2` ,
 t0.`ID_TVCP_3` as `0_2623_ID_TVCP_3` ,
 t0.`ID_TVCP_4` as `0_2624_ID_TVCP_4` ,
 t0.`ID_TEL`  as `0_1747_ID_TEL` ,
 t0.`M_REWIR` as `0_1627` ,
 t0.`P_OFFER_TARGET` as `P_OFFER_TARGET` ,

-- internet: 
 t1.ID as `1_1385` ,
 t1.P_SERVICE as `1_449` ,
 t1.P_SERVICE_NAME as `1_450` ,
 t1.P_INSTALL_QUOTE as `1_458` , t1.P_INSTALL_QUOTE_NORMAL as `t1_1578`,
 t1.P_CONTRACT_PRICE as `1_459` ,
 t1.P_PROMO_MONTH_PRICE as `1_460` ,
 t1.P_NORMAL_PRICE as `1_461` ,
 t1.P_DEAL_PROMO_MONTHS as `1_457` ,
-- (t1.P_NORMAL_PRICE-t1.P_PROMO_MONTH_PRICE)*t0.P_DEALTERM_MONTHS+(t1.P_INSTALL_QUOTE_NORMAL-t1.P_INSTALL_QUOTE) as `t1_1580`,
-- (t1.P_NORMAL_PRICE-t1.P_CONTRACT_PRICE)*t0.P_DEALTERM_MONTHS+(t1.P_INSTALL_QUOTE_NORMAL-t1.P_INSTALL_QUOTE) as `t1_1580`,
 t1.P_NORMAL_PRICE*t0.P_DEALTERM_MONTHS - t1.P_DEAL_PROMO_MONTHS*t1.P_PROMO_MONTH_PRICE - (t0.P_DEALTERM_MONTHS-t1.P_DEAL_PROMO_MONTHS)*t1.P_CONTRACT_PRICE + (t1.P_INSTALL_QUOTE_NORMAL-t1.P_INSTALL_QUOTE) as `t1_1580`,
 ROUND(( ((t0.P_DEALTERM_MONTHS-t1.P_DEAL_PROMO_MONTHS)*t1.P_CONTRACT_PRICE) + (t1.P_DEAL_PROMO_MONTHS*t1.P_PROMO_MONTH_PRICE) + (t1.P_INSTALL_QUOTE))/t0.P_DEALTERM_MONTHS, 2) as `t1_srednia`,
 ROUND(( ((t0.P_DEALTERM_MONTHS-t1.P_DEAL_PROMO_MONTHS)*t1.P_CONTRACT_PRICE_NETTO) + (t1.P_DEAL_PROMO_MONTHS*t1.P_PROMO_MONTH_PRICE_NETTO) + (t1.P_INSTALL_QUOTE/1.23))/t0.P_DEALTERM_MONTHS, 2) as `t1_srednia_netto`,
 t1.P_S_PARAM1 as `[1_452]` , t1.P_S_PARAM2 as `[1_453]` , t1.P_S_LIMIT as `[1_454]`, t1.P_S_MAILBOX_SIZE as `[1_462]`, t1.P_S_WWW_SIZE as `[1_463]` , 
 if(t1.ID,t0.P_PROMOTION_NAME,'') as `1_451` , 

-- telewizja analogowa
 t2.ID as `2_1385` ,
 t2.P_SERVICE as `2_449` ,
 t2.P_SERVICE_NAME as `2_450` ,
 t2.P_INSTALL_QUOTE as `2_458` , t2.P_INSTALL_QUOTE_NORMAL as `t2_1578`,
 t2.P_CONTRACT_PRICE as `2_459` ,
 t2.P_PROMO_MONTH_PRICE as `2_460` ,
 t2.P_NORMAL_PRICE as `2_461` ,
 t2.P_DEAL_PROMO_MONTHS as `2_457` ,
-- (t2.P_NORMAL_PRICE-t2.P_PROMO_MONTH_PRICE)*t0.P_DEALTERM_MONTHS+(t2.P_INSTALL_QUOTE_NORMAL-t2.P_INSTALL_QUOTE) as `t2_1580`,
-- (t2.P_NORMAL_PRICE-t2.P_CONTRACT_PRICE)*t0.P_DEALTERM_MONTHS+(t2.P_INSTALL_QUOTE_NORMAL-t2.P_INSTALL_QUOTE) as `t2_1580`,
 t2.P_NORMAL_PRICE*t0.P_DEALTERM_MONTHS - t2.P_DEAL_PROMO_MONTHS*t2.P_PROMO_MONTH_PRICE - (t0.P_DEALTERM_MONTHS-t2.P_DEAL_PROMO_MONTHS)*t2.P_CONTRACT_PRICE + (t2.P_INSTALL_QUOTE_NORMAL-t2.P_INSTALL_QUOTE) as `t2_1580`,
 ROUND(( (t0.P_DEALTERM_MONTHS-t2.P_DEAL_PROMO_MONTHS)*t2.P_CONTRACT_PRICE + t2.P_DEAL_PROMO_MONTHS*t2.P_PROMO_MONTH_PRICE + t2.P_INSTALL_QUOTE)/t0.P_DEALTERM_MONTHS, 2) as `t2_srednia`,
 ROUND(( (t0.P_DEALTERM_MONTHS-t2.P_DEAL_PROMO_MONTHS)*t2.P_CONTRACT_PRICE_NETTO + t2.P_DEAL_PROMO_MONTHS*t2.P_PROMO_MONTH_PRICE_NETTO + t2.P_INSTALL_QUOTE/1.23)/t0.P_DEALTERM_MONTHS, 2) as `t2_srednia_netto`,
 if(t0.ID='1','',if(t2.ID,'TAK','NIE')) as `2_IF` ,
 if(t2.ID,t0.P_PROMOTION_NAME,'') as `2_451` ,  

-- telewizja cyfrowa
 t3.ID as `3_1385` ,
 t3.P_SERVICE as `3_449` ,
 t3.P_SERVICE_NAME as `3_450` ,
 t3.P_INSTALL_QUOTE as `3_458` , t3.P_INSTALL_QUOTE_NORMAL as `3_1578`,
 t3.P_CONTRACT_PRICE as `3_459` ,
 t3.P_PROMO_MONTH_PRICE as `3_460` ,
 t3.P_NORMAL_PRICE as `3_461` ,
 t3.P_DEAL_PROMO_MONTHS as `3_457` ,
-- (t3.P_NORMAL_PRICE-t3.P_PROMO_MONTH_PRICE)*t0.P_DEALTERM_MONTHS+(t3.P_INSTALL_QUOTE_NORMAL-t3.P_INSTALL_QUOTE) as `t3_1580`,
-- (t3.P_NORMAL_PRICE-t3.P_CONTRACT_PRICE)*t0.P_DEALTERM_MONTHS+(t3.P_INSTALL_QUOTE_NORMAL-t3.P_INSTALL_QUOTE) as `t3_1580`,
 t3.P_NORMAL_PRICE*t0.P_DEALTERM_MONTHS - t3.P_DEAL_PROMO_MONTHS*t3.P_PROMO_MONTH_PRICE - (t0.P_DEALTERM_MONTHS-t3.P_DEAL_PROMO_MONTHS)*t3.P_CONTRACT_PRICE + (t3.P_INSTALL_QUOTE_NORMAL-t3.P_INSTALL_QUOTE) as `t3_1580`,
 ROUND(( (t0.P_DEALTERM_MONTHS-t3.P_DEAL_PROMO_MONTHS)*t3.P_CONTRACT_PRICE + t3.P_DEAL_PROMO_MONTHS*t3.P_PROMO_MONTH_PRICE + t3.P_INSTALL_QUOTE)/t0.P_DEALTERM_MONTHS, 2) as `t3_srednia`,
 ROUND(( (t0.P_DEALTERM_MONTHS-t3.P_DEAL_PROMO_MONTHS)*t3.P_CONTRACT_PRICE_NETTO + t3.P_DEAL_PROMO_MONTHS*t3.P_PROMO_MONTH_PRICE_NETTO + t3.P_INSTALL_QUOTE/1.23)/t0.P_DEALTERM_MONTHS, 2) as `t3_srednia_netto`,
 if(t0.ID='1','',if(t3.ID,'TAK','NIE')) as `3_IF` ,
 if(t3.ID,t0.P_PROMOTION_NAME,'') as `3_451` ,  
-- 2169 S_DEKODER_SD_OPTION
-- 2170 S_MODUL_PCMCIA_OPTION
-- 2171 S_DEKODER_HD_OPTION
	if(t2.S_DEKODER_SD_OPTION='TAK','X','') as `1_2169_TAK` ,
	if(t2.S_DEKODER_SD_OPTION='NIE','X','') as `1_2169_NIE` ,
	if(t2.S_MODUL_PCMCIA_OPTION='TAK','X','') as `1_2170_TAK` ,
	if(t2.S_MODUL_PCMCIA_OPTION='NIE','X','') as `1_2170_NIE` ,
	if(t2.S_DEKODER_HD_OPTION='TAK','X','') as `1_2171_TAK` ,
	if(t2.S_DEKODER_HD_OPTION='NIE','X','') as `1_2171_NIE` ,

-- telewizja cyfrowa pakiety 
 t4.ID as `4_1385` ,
 t4.P_SERVICE as `4_449` ,
 t4.P_SERVICE_NAME as `4_450` ,
 t4.P_INSTALL_QUOTE as `4_458` , t4.P_INSTALL_QUOTE_NORMAL as `t4_1578`,
 t4.P_CONTRACT_PRICE as `4_459` ,
 t4.P_PROMO_MONTH_PRICE as `4_460` ,
 t4.P_NORMAL_PRICE as `4_461` ,
 t4.P_DEAL_PROMO_MONTHS as `4_457` ,
-- (t4.P_NORMAL_PRICE-t4.P_PROMO_MONTH_PRICE)*t0.P_DEALTERM_MONTHS+(t4.P_INSTALL_QUOTE_NORMAL-t4.P_INSTALL_QUOTE) as `t4_1580`,
-- (t4.P_NORMAL_PRICE-t4.P_CONTRACT_PRICE)*t0.P_DEALTERM_MONTHS+(t4.P_INSTALL_QUOTE_NORMAL-t4.P_INSTALL_QUOTE) as `t4_1580`,
 t4.P_NORMAL_PRICE*t0.P_DEALTERM_MONTHS - t4.P_DEAL_PROMO_MONTHS*t4.P_PROMO_MONTH_PRICE - (t0.P_DEALTERM_MONTHS-t4.P_DEAL_PROMO_MONTHS)*t4.P_CONTRACT_PRICE + (t4.P_INSTALL_QUOTE_NORMAL-t4.P_INSTALL_QUOTE) as `t4_1580`,
 ROUND(( (t0.P_DEALTERM_MONTHS-t4.P_DEAL_PROMO_MONTHS)*t4.P_CONTRACT_PRICE + t4.P_DEAL_PROMO_MONTHS*t4.P_PROMO_MONTH_PRICE + t4.P_INSTALL_QUOTE)/t0.P_DEALTERM_MONTHS, 2) as `t4_srednia`,
 ROUND(( (t0.P_DEALTERM_MONTHS-t4.P_DEAL_PROMO_MONTHS)*t4.P_CONTRACT_PRICE_NETTO + t4.P_DEAL_PROMO_MONTHS*t4.P_PROMO_MONTH_PRICE_NETTO + t4.P_INSTALL_QUOTE/1.23)/t0.P_DEALTERM_MONTHS, 2) as `t4_srednia_netto`,
 if(t0.ID='1','',if(t4.ID,'TAK','NIE')) as `4_IF` ,
 if(t4.ID,t0.P_PROMOTION_NAME,'') as `4_451` ,  

-- telefon
 t5.ID as `5_1385` ,
 t5.P_SERVICE as `5_449` ,
 t5.P_SERVICE_NAME as `5_450` ,
 t5.P_INSTALL_QUOTE as `5_458` , t5.P_INSTALL_QUOTE_NORMAL as `t5_1578`,
 t5.P_CONTRACT_PRICE as `5_459` ,
 t5.P_PROMO_MONTH_PRICE as `5_460` ,
 t5.P_NORMAL_PRICE as `5_461` ,
 t5.P_DEAL_PROMO_MONTHS as `5_457` ,
-- (t5.P_NORMAL_PRICE-t5.P_PROMO_MONTH_PRICE)*t0.P_DEALTERM_MONTHS+(t5.P_INSTALL_QUOTE_NORMAL-t5.P_INSTALL_QUOTE) as `t5_1580`,
-- (t5.P_NORMAL_PRICE-t5.P_CONTRACT_PRICE)*t0.P_DEALTERM_MONTHS+(t5.P_INSTALL_QUOTE_NORMAL-t5.P_INSTALL_QUOTE) as `t5_1580`,
 t5.P_NORMAL_PRICE*t0.P_DEALTERM_MONTHS - t5.P_DEAL_PROMO_MONTHS*t5.P_PROMO_MONTH_PRICE - (t0.P_DEALTERM_MONTHS-t5.P_DEAL_PROMO_MONTHS)*t5.P_CONTRACT_PRICE + (t5.P_INSTALL_QUOTE_NORMAL-t5.P_INSTALL_QUOTE) as `t5_1580`,
 ROUND(( (t0.P_DEALTERM_MONTHS-t5.P_DEAL_PROMO_MONTHS)*t5.P_CONTRACT_PRICE + t5.P_DEAL_PROMO_MONTHS*t5.P_PROMO_MONTH_PRICE + t5.P_INSTALL_QUOTE)/t0.P_DEALTERM_MONTHS, 2) as `t5_srednia`,
 ROUND(( (t0.P_DEALTERM_MONTHS-t5.P_DEAL_PROMO_MONTHS)*t5.P_CONTRACT_PRICE_NETTO + t5.P_DEAL_PROMO_MONTHS*t5.P_PROMO_MONTH_PRICE_NETTO + t5.P_INSTALL_QUOTE/1.23)/t0.P_DEALTERM_MONTHS, 2) as `t5_srednia_netto`,
 if(t0.ID='1','',if(t5.ID,'TAK','NIE')) as `5_IF` ,
 if(t5.ID,t0.P_PROMOTION_NAME,'') as `5_451`,

 t5.ID_DOMAINS_PACKET_ID as `5_3898` ,

-- telewizja cyfrowa pakiety 2
 t6.ID as `6_1385` ,
 t6.P_SERVICE as `6_449` ,
 t6.P_SERVICE_NAME as `6_450` ,
 t6.P_INSTALL_QUOTE as `6_458` , t6.P_INSTALL_QUOTE_NORMAL as `t6_1578`,
 t6.P_CONTRACT_PRICE as `6_459` ,
 t6.P_PROMO_MONTH_PRICE as `6_460` ,
 t6.P_NORMAL_PRICE as `6_461` ,
 t6.P_DEAL_PROMO_MONTHS as `6_457` ,
 t6.P_NORMAL_PRICE*t0.P_DEALTERM_MONTHS - t6.P_DEAL_PROMO_MONTHS*t6.P_PROMO_MONTH_PRICE - (t0.P_DEALTERM_MONTHS-t6.P_DEAL_PROMO_MONTHS)*t6.P_CONTRACT_PRICE + (t6.P_INSTALL_QUOTE_NORMAL-t6.P_INSTALL_QUOTE) as `t6_1580`,
 ROUND(( (t0.P_DEALTERM_MONTHS-t6.P_DEAL_PROMO_MONTHS)*t6.P_CONTRACT_PRICE + t6.P_DEAL_PROMO_MONTHS*t6.P_PROMO_MONTH_PRICE + t6.P_INSTALL_QUOTE)/t0.P_DEALTERM_MONTHS, 2) as `t6_srednia`,
 ROUND(( (t0.P_DEALTERM_MONTHS-t6.P_DEAL_PROMO_MONTHS)*t6.P_CONTRACT_PRICE_NETTO + t6.P_DEAL_PROMO_MONTHS*t6.P_PROMO_MONTH_PRICE_NETTO + t6.P_INSTALL_QUOTE/1.23)/t0.P_DEALTERM_MONTHS, 2) as `t6_srednia_netto`,
 if(t0.ID='1','',if(t6.ID,'TAK','NIE')) as `6_IF` ,
 if(t6.ID,t0.P_PROMOTION_NAME,'') as `6_451` ,  

-- telewizja cyfrowa pakiety 3
 t7.ID as `7_1385` ,
 t7.P_SERVICE as `7_449` ,
 t7.P_SERVICE_NAME as `7_450` ,
 t7.P_INSTALL_QUOTE as `7_458` , t7.P_INSTALL_QUOTE_NORMAL as `t7_1578`,
 t7.P_CONTRACT_PRICE as `7_459` ,
 t7.P_PROMO_MONTH_PRICE as `7_460` ,
 t7.P_NORMAL_PRICE as `7_461` ,
 t7.P_DEAL_PROMO_MONTHS as `7_457` ,
 t7.P_NORMAL_PRICE*t0.P_DEALTERM_MONTHS - t7.P_DEAL_PROMO_MONTHS*t7.P_PROMO_MONTH_PRICE - (t0.P_DEALTERM_MONTHS-t7.P_DEAL_PROMO_MONTHS)*t7.P_CONTRACT_PRICE + (t7.P_INSTALL_QUOTE_NORMAL-t7.P_INSTALL_QUOTE) as `t7_1580`,
 ROUND(( (t0.P_DEALTERM_MONTHS-t7.P_DEAL_PROMO_MONTHS)*t7.P_CONTRACT_PRICE + t7.P_DEAL_PROMO_MONTHS*t7.P_PROMO_MONTH_PRICE + t7.P_INSTALL_QUOTE)/t0.P_DEALTERM_MONTHS, 2) as `t7_srednia`,
 ROUND(( (t0.P_DEALTERM_MONTHS-t7.P_DEAL_PROMO_MONTHS)*t7.P_CONTRACT_PRICE_NETTO + t7.P_DEAL_PROMO_MONTHS*t7.P_PROMO_MONTH_PRICE_NETTO + t7.P_INSTALL_QUOTE/1.23)/t0.P_DEALTERM_MONTHS, 2) as `t7_srednia_netto`,
 if(t0.ID='1','',if(t7.ID,'TAK','NIE')) as `7_IF` ,
 if(t7.ID,t0.P_PROMOTION_NAME,'') as `7_451`,
 if(t0.A_STATUS='NORMAL','1','') as t0_STATUS_NORMAL , 
 if(t0.A_STATUS='WAITING','1','') as t0_STATUS_WAITING 

-- TV - dane z ID_TV lub ID_TVC jesli nie ma ID_TV
, if (t0.`ID_TV`>0, t0.`ID_TV`, IF(t0.`ID_TVC`>0, t0.`ID_TVC`, null)) as TV_ID
, if (t0.`ID_TV`>0, 'X', IF(t0.`ID_TVC`>0, 'X', '')) as TV_JEST
, if (t2.`ID`>0, t2.`P_SERVICE_NAME`, IF(t3.`ID`>0, t3.`P_SERVICE_NAME`, null)) as TV_P_SERVICE_NAME

-- ID COSTS

-- ID PROCES
, t0.`ID_PROCES` as t0_ID_PROCES
, t1.`ID_PROCES` as t1_ID_PROCES
, t2.`ID_PROCES` as t2_ID_PROCES
, t3.`ID_PROCES` as t3_ID_PROCES
, t4.`ID_PROCES` as t4_ID_PROCES
, t5.`ID_PROCES` as t5_ID_PROCES
, t6.`ID_PROCES` as t6_ID_PROCES
, t7.`ID_PROCES` as t7_ID_PROCES

FROM `USERS2_OFFERS_GROUPS` as t0
 left join `USERS2_OFFERS` as t1 on (t0.ID_NET!=0 and t1.ID=t0.ID_NET and t1.A_STATUS!='DELETED' and t1.P_SERVICE='NET'  )
 left join `USERS2_OFFERS` as t2 on (t0.ID_TV!=0  and t2.ID=t0.ID_TV  and t2.A_STATUS!='DELETED' and t2.P_SERVICE='TV'   )
 left join `USERS2_OFFERS` as t5 on (t0.ID_TEL!=0 and t5.ID=t0.ID_TEL and t5.A_STATUS!='DELETED' and t5.P_SERVICE in('TEL','OPCJA_TEL')  )
 left join `USERS2_OFFERS` as t3 on (t0.ID_TVC!=0 and t3.ID=t0.ID_TVC and t3.A_STATUS!='DELETED' and t3.P_SERVICE in('TVC','OPCJA_TVC')  )
 left join `USERS2_OFFERS` as t4 on (t0.ID_TVCP_1!=0 and t4.ID=t0.ID_TVCP_1 and t4.A_STATUS!='DELETED' and t4.P_SERVICE='TVCP' )
 left join `USERS2_OFFERS` as t6 on (t0.ID_TVCP_2!=0 and t6.ID=t0.ID_TVCP_2 and t6.A_STATUS!='DELETED' and t6.P_SERVICE='TVCP' )
 left join `USERS2_OFFERS` as t7 on (t0.ID_TVCP_3!=0 and t7.ID=t0.ID_TVCP_3 and t7.A_STATUS!='DELETED' and t7.P_SERVICE='TVCP' )

WHERE
	".$sql_where_rewir_add."
	-- and t0.`P_SERVICE_COMPANY`='BN'
	".$sql_where_filter_add."
GROUP BY t0.ID
order by t0.ID desc
";
//-- having  x_410 like '%|".addslashes($_GET['S_ADDRESS_STREET'])."|%'
if ($DBG) {echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">sql: ';print_r($sql);echo'</pre>';}
	$oferty = array();
	$oferty_costs_ids = array();
	$db = DB::getDB();
	$res = $db->query($sql);
	while ($row = $db->fetch_array($res)) {
		$row['_cls'] = '';
		$oferty[] = $row;
		// add oferty costs
		if ($row['1_1385'] > 0) $oferty_costs_ids[ $row['1_1385'] ] = true;
		if ($row['2_1385'] > 0) $oferty_costs_ids[ $row['2_1385'] ] = true;
		if ($row['3_1385'] > 0) $oferty_costs_ids[ $row['3_1385'] ] = true;
		if ($row['4_1385'] > 0) $oferty_costs_ids[ $row['4_1385'] ] = true;
		if ($row['5_1385'] > 0) $oferty_costs_ids[ $row['5_1385'] ] = true;
		if ($row['6_1385'] > 0) $oferty_costs_ids[ $row['6_1385'] ] = true;
		if ($row['7_1385'] > 0) $oferty_costs_ids[ $row['7_1385'] ] = true;

		if ($row['5_449'] == 'OPCJA_TEL') $row['5_449'] = 'TEL';
		if ($row['3_449'] == 'OPCJA_TVC') $row['5_449'] = 'TVC';
	}

	$oferty_costs = PokazOfertyHelper::get_offers_costs_by_offer_ids(array_keys($oferty_costs_ids));
	$oferty_costs_start = PokazOfertyHelper::get_offers_costs_start_by_offer_ids(array_keys($oferty_costs_ids));


	echo '<div class="oferty-print-user-search">';
	echo " <b>Oferty</b>";
	if (!$_GET['print']) {
		$link_href .= "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC";
		$link_href .= "&S_ADDRESS_STREET=".$_GET['S_ADDRESS_STREET']."&print=1";
		foreach ($oferty_filters as $k_filter => $v_params) {
			//if (in_array($k_filter, $oferty_filters_pomin)) continue;
			$link_href .= "&".$k_filter."=".$v_params['value'];
		}
		echo' - <a href="'.$link_href.'" target="_blank">' . " drukuj " . '<img src="icon/print.gif" height="24">' . '</a>';

		$user = null;
		if ($_GET['user_id'] > 0) {
			$user = PokazOfertyHelper::get_user_info($_GET['user_id']);
		}
		//if (!$user) {
			echo " " . '<form style="display:inline; margin:0 0 0 50px;" id="frm_user_id">' . "<b>Wyszukaj klienta (ID, imie lub nazwisko):</b> ";
				echo '<input type="hidden" name="' . "MENU_INIT" . '" value="' . "POKAZ_OFERTY_AKTUALNE_FUNC" . '" />';
				echo '<input type="hidden" name="' . "S_ADDRESS_STREET" . '" value="' . $_GET['S_ADDRESS_STREET'] . '" />';
				foreach ($oferty_filters as $k_filter => $v_params) {
					echo '<input type="hidden" name="' . $k_filter . '" value="' . $v_params['value'] . '" />';
				}
				echo '<input type="text" name="user_id" id="frm_Q" value="' . $_GET['user_id'] . '" size="20" />';
				echo " ";
				echo '<input type="submit" value="' . "Wybierz klienta" . '" />';
			echo '</form>';
			echo '<div id="frm_Q_values"></div>';
			if (!empty($_GET['S_ADDRESS_STREET'])) {
				$active_deals_street = PokazOfertyHelper::get_deals_active_by_street($_GET['S_ADDRESS_STREET']);
				if (!empty($active_deals_street)) {
					echo '<div style="border:1px solid red;background:#FFCCCC;padding:0 10px;">' . "<b>Uwaga na wybranym adresie są aktywne umowy:</b>";
					$link_base = "";
					$link_base .= "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC";
					$link_base .= "&S_ADDRESS_STREET=".$_GET['S_ADDRESS_STREET'];
					foreach ($oferty_filters as $k_filter => $v_params) {
						$link_base .= "&".$k_filter."=".$v_params['value'];
					}
					$out_user_deals = array();
					foreach ($active_deals_street as $k_id_user => $v_usr_arr) {
						foreach ($v_usr_arr as $v_usr) {
							if (!array_key_exists($v_usr->ID_BILLING_USERS, $out_user_deals)) {
								$out_user_deals [$v_usr->ID_BILLING_USERS] = (object)array('P_NAME'=>$v_usr->P_NAME, 'deals_id_arr'=>array($v_usr->ID_DEALS));
							} else {
								$out_user_deals [$v_usr->ID_BILLING_USERS]->deals_id_arr []= $v_usr->ID_DEALS;
							}
						}
					}
					foreach ($out_user_deals as $v_usr_id => $v_usr_info) {
						echo '<p>' . $v_usr_info->P_NAME . " umowy nr: " . implode(", ", $v_usr_info->deals_id_arr);
						echo " - " . '<a href="' . $link_base . "&user_id=" . $v_usr_id . '">' . "Wybierz klienta " . $v_usr_id . '</a>';
						echo '</p>';
					}
					echo '</div>';
				}
			}
		//} else {
		if ($user) {
			$active_deals_by_id = PokazOfertyHelper::get_deals_active_with_info($_GET['S_ADDRESS_STREET'], $user->ID_BILLING_USERS);

			PokazOfertyView::user_with_services($user, $active_deals_by_id);
		}
	}
	echo '</div>';// .oferty-print-user-search

	echo '<hr />';

	if (!$_GET['print']) {
		echo'<form action="" method="GET">';
			echo'<input type="hidden" name="'."MENU_INIT".'" value="'."POKAZ_OFERTY_AKTUALNE_FUNC".'" />';
			echo'<input type="hidden" name="'."S_ADDRESS_STREET".'" value="'.$_GET['S_ADDRESS_STREET'].'" />';
			echo'<input type="hidden" name="'."user_id".'" value="'.$_GET['user_id'].'" />';
		echo'<table cellspacing="0" cellpadding="0" class="tbl tbl-hover" style="margin-top:5px;" border="1">';
		echo'<tr>';
		foreach ($oferty_filters as $k_field => $v_params) {
			//if (in_array($k_field, $oferty_filters_pomin)) continue;
			echo'<th>'.$v_params['label'].'</th>';
		}//end foreach
			echo'<td rowspan="2">'.'<input type="submit" value="'."Szukaj".'" />'.'</td>';
		echo'</tr>';
		echo'<tr>';
		foreach ($oferty_filters as $k_field => $v_params) {
			//if (in_array($k_field, $oferty_filters_pomin)) continue;
			$st = ($v_params['value'] != $v_params['default'])? ' style="border-bottom:4px solid red;"' : '';
			echo'<td'.$st.'>';
			$js = '';//' onchange="this.form.submit();"';
			echo'<select name="'.$k_field.'"'.$js.' size="4" style="width:100%">';
			foreach ($v_params['values'] as $key => $val) {
				$st = '';
				if (isset($v_params['color'][$key])) {
					$st = 'style="background-color:'.$v_params['color'][$key].';"';
				}

				$sel = ($v_params['value'] == $key)? ' selected="selected"' : '';
				echo'<option value="'.$key.'"'.$sel.$st.'>'.$key.'</option>';
			}//end foreach
			echo'</select>';
			echo'</td>';
		}//end foreach
		echo'</tr>';
		echo'</table>';
		echo'</form>';
		if (!empty($oferty)) {
			echo '<p>' . "Znaleziono <b>" . count($oferty) . "</b> ofert." . '</p>';
		}
	}

	if (empty($oferty)) {
		echo'<p class="red">'."Brak ofert".'</p>';
		return;
	}

$pokaz_oferty_view = new PokazOfertyView();
echo $pokaz_oferty_view->print_css();
echo '<script type="text/javascript">' . "
jQuery(document).ready(function(){
	jQuery('#tbl-oferty').on('click', '.tbl-row', function(event){
		jQuery(this).toggleClass('active');
		jQuery(this).next('tr').toggle();
	});

	jQuery('#tbl-oferty-rowin-all').on('click', function(event){
		jQuery('#tbl-oferty .tbl-row').addClass('active');
		jQuery('#tbl-oferty .sub').show();
	});
	jQuery('#tbl-oferty-zwin-all').on('click', function(event){
		jQuery('#tbl-oferty .tbl-row').removeClass('active');
		jQuery('#tbl-oferty .sub').hide();
	});

});
" . '</script>';

$oferty_group_cols_new = array();
$oferty_group_cols_new ['0_1380']= '';
$oferty_group_cols_new ['0_451']= '';
$oferty_group_cols_new ['ID_PROCES']= '';
$oferty_group_cols_new ['0_456']= '';
//$oferty_group_cols_new []= '1_457';// 	$oferty_cols ['0_1743_ID_NET']['1_457']= array('label'=>"Ilość promocyjnych miesięcy", 'field'=>'P_DEAL_PROMO_MONTHS');
$oferty_group_cols_new ['suma_1']= "suma opłat instalacyjnych (brutto)";// Suma opłat instalacyjnych
$oferty_group_cols_new ['suma_2']= "suma abonamentów w promocyjnych miesiącach / po promocji (brutto)";// suma abonamentów w promocyjnych miesiącach
$oferty_group_cols_new ['srednia']= "średnia kwota (brutto)";
$oferty_group_cols_new ['cost']= "suma kosztów (netto)";
$oferty_group_cols_new ['zysk']= "zysk (netto)";


$oferty_p_services = array('1_1385'=>'NET', '5_1385'=>'TEL', '2_1385'=>'TV', '3_1385'=>'TVC', '4_1385'=>'TVCP_1', '6_1385'=>'TVCP_2', '7_1385'=>'TVCP_3');
$oferty_group_add_info ['labels']['1385'] = 'ID oferty';
$oferty_group_add_info ['labels']['ID_PROCES'] = '';
$oferty_group_add_info ['labels']['450' ] = 'Nazwa oferty';
$oferty_group_add_info ['labels']['458' ] = 'Promocyjna cena instalacji (brutto)';
$oferty_group_add_info ['labels']['460' ] = 'Wartość abonamentu w promocyjnych miesiącach (brutto)';
$oferty_group_add_info ['labels']['459' ] = 'Wartość abonamentu po promocji (brutto)';
$oferty_group_add_info ['labels']['457' ] = 'Ilość promocyjnych miesięcy';
$oferty_group_add_info ['labels']['461' ] = 'Nominalna wartość abonamentu (brutto)';
$oferty_group_add_info ['labels']['srednia'] = 'Średnia (brutto)';
$oferty_group_add_info ['labels']['1580'] = 'Upust od ceny normalnej do wyliczeń kary (brutto)';

$oferty_group_add_info ['NET'   ]['1385'] = '1_1385';
$oferty_group_add_info ['TEL'   ]['1385'] = '5_1385';
$oferty_group_add_info ['TV'    ]['1385'] = '2_1385';
$oferty_group_add_info ['TVC'   ]['1385'] = '3_1385';
$oferty_group_add_info ['TVCP_1']['1385'] = '4_1385';
$oferty_group_add_info ['TVCP_2']['1385'] = '6_1385';
$oferty_group_add_info ['TVCP_3']['1385'] = '7_1385';
$oferty_group_add_info ['NET'   ]['ID_PROCES'] = 't1_ID_PROCES';
$oferty_group_add_info ['TEL'   ]['ID_PROCES'] = 't5_ID_PROCES';
$oferty_group_add_info ['TV'    ]['ID_PROCES'] = 't2_ID_PROCES';
$oferty_group_add_info ['TVC'   ]['ID_PROCES'] = 't3_ID_PROCES';
$oferty_group_add_info ['TVCP_1']['ID_PROCES'] = 't4_ID_PROCES';
$oferty_group_add_info ['TVCP_2']['ID_PROCES'] = 't6_ID_PROCES';
$oferty_group_add_info ['TVCP_3']['ID_PROCES'] = 't7_ID_PROCES';
$oferty_group_add_info ['NET'   ]['450'] = '1_450';
$oferty_group_add_info ['TEL'   ]['450'] = '5_450';
$oferty_group_add_info ['TV'    ]['450'] = '2_450';
$oferty_group_add_info ['TVC'   ]['450'] = '3_450';
$oferty_group_add_info ['TVCP_1']['450'] = '4_450';
$oferty_group_add_info ['TVCP_2']['450'] = '6_450';
$oferty_group_add_info ['TVCP_3']['450'] = '7_450';
$oferty_group_add_info ['NET'   ]['458'] = '1_458';
$oferty_group_add_info ['TEL'   ]['458'] = '5_458';
$oferty_group_add_info ['TV'    ]['458'] = '2_458';
$oferty_group_add_info ['TVC'   ]['458'] = '3_458';
$oferty_group_add_info ['TVCP_1']['458'] = '4_458';
$oferty_group_add_info ['TVCP_2']['458'] = '6_458';
$oferty_group_add_info ['TVCP_3']['458'] = '7_458';
$oferty_group_add_info ['NET'   ]['459'] = '1_459';
$oferty_group_add_info ['TEL'   ]['459'] = '5_459';
$oferty_group_add_info ['TV'    ]['459'] = '2_459';
$oferty_group_add_info ['TVC'   ]['459'] = '3_459';
$oferty_group_add_info ['TVCP_1']['459'] = '4_459';
$oferty_group_add_info ['TVCP_2']['459'] = '6_459';
$oferty_group_add_info ['TVCP_3']['459'] = '7_459';
$oferty_group_add_info ['NET'   ]['460'] = '1_460';
$oferty_group_add_info ['TEL'   ]['460'] = '5_460';
$oferty_group_add_info ['TV'    ]['460'] = '2_460';
$oferty_group_add_info ['TVC'   ]['460'] = '3_460';
$oferty_group_add_info ['TVCP_1']['460'] = '4_460';
$oferty_group_add_info ['TVCP_2']['460'] = '6_460';
$oferty_group_add_info ['TVCP_3']['460'] = '7_460';
$oferty_group_add_info ['NET'   ]['461'] = '1_461';
$oferty_group_add_info ['TEL'   ]['461'] = '5_461';
$oferty_group_add_info ['TV'    ]['461'] = '2_461';
$oferty_group_add_info ['TVC'   ]['461'] = '3_461';
$oferty_group_add_info ['TVCP_1']['461'] = '4_461';
$oferty_group_add_info ['TVCP_2']['461'] = '6_461';
$oferty_group_add_info ['TVCP_3']['461'] = '7_461';
$oferty_group_add_info ['NET'   ]['457'] = '1_457';
$oferty_group_add_info ['TEL'   ]['457'] = '5_457';
$oferty_group_add_info ['TV'    ]['457'] = '2_457';
$oferty_group_add_info ['TVC'   ]['457'] = '3_457';
$oferty_group_add_info ['TVCP_1']['457'] = '4_457';
$oferty_group_add_info ['TVCP_2']['457'] = '6_457';
$oferty_group_add_info ['TVCP_3']['457'] = '7_457';
$oferty_group_add_info ['NET'   ]['1580'] = 't1_1580';
$oferty_group_add_info ['TEL'   ]['1580'] = 't5_1580';
$oferty_group_add_info ['TV'    ]['1580'] = 't2_1580';
$oferty_group_add_info ['TVC'   ]['1580'] = 't3_1580';
$oferty_group_add_info ['TVCP_1']['1580'] = 't4_1580';
$oferty_group_add_info ['TVCP_2']['1580'] = 't6_1580';
$oferty_group_add_info ['TVCP_3']['1580'] = 't7_1580';
$oferty_group_add_info ['NET'   ]['srednia'] = 't1_srednia';
$oferty_group_add_info ['TEL'   ]['srednia'] = 't5_srednia';
$oferty_group_add_info ['TV'    ]['srednia'] = 't2_srednia';
$oferty_group_add_info ['TVC'   ]['srednia'] = 't3_srednia';
$oferty_group_add_info ['TVCP_1']['srednia'] = 't4_srednia';
$oferty_group_add_info ['TVCP_2']['srednia'] = 't6_srednia';
$oferty_group_add_info ['TVCP_3']['srednia'] = 't7_srednia';
$oferty_group_add_info ['NET'   ]['srednia_netto'] = 't1_srednia_netto';
$oferty_group_add_info ['TEL'   ]['srednia_netto'] = 't5_srednia_netto';
$oferty_group_add_info ['TV'    ]['srednia_netto'] = 't2_srednia_netto';
$oferty_group_add_info ['TVC'   ]['srednia_netto'] = 't3_srednia_netto';
$oferty_group_add_info ['TVCP_1']['srednia_netto'] = 't4_srednia_netto';
$oferty_group_add_info ['TVCP_2']['srednia_netto'] = 't6_srednia_netto';
$oferty_group_add_info ['TVCP_3']['srednia_netto'] = 't7_srednia_netto';

$specialFltrs = array();
{// specialFltrs
	$specialFltrs['net_speed'] = (object)array('values'=>array(), 'label'=>"NET speed", 'lastInd'=>0);
	$specialFltrs['tv_name'] = (object)array('values'=>array(), 'label'=>"TV", 'lastInd'=>0);
	$specialFltrs['tel_name'] = (object)array('values'=>array(), 'label'=>"TEL", 'lastInd'=>0);
	$specialFltrs['promo_name'] = (object)array('values'=>array(), 'label'=>"Promocja", 'lastInd'=>0);
	echo '<script type="text/javascript">' . "
	function runSpecialFltrs() {
		jQuery('#tbl-oferty tbody tr.sub').hide();

		var fltrs = [];
		jQuery('#tbl-oferty-specialFltrs').find('select').each(function(ind, el){
			var fltr='',n=jQuery(el);
			if (n.val() != '') {
				fltr = n.attr('name') + '-' + n.val();
				fltrs.push(fltr)
			}
		});
		jQuery('#tbl-oferty tbody tr.tbl-row').each(function(ind, el){
			var show=true, n=jQuery(el);
			if (fltrs.length > 0) {
				jQuery.each(fltrs, function(i, fltr){
					if (!n.hasClass(fltr)) {
						show = false;
					}
				});
			}
			if (show) {
				n.show();
			} else {
				n.hide();
			}
		});
	}
	jQuery(document).ready(function(){
		jQuery('#tbl-oferty-specialFltrs').find('select').on('change', function(e) {
			runSpecialFltrs();
		});
	});
	" .'</script>';
	foreach ($oferty as $ind => $row) {// $row = array('[1_452]'=>'P_S_PARAM1', 'TV_P_SERVICE_NAME'=>TV lub TVC name, '5_450' => TV name)
		if (!empty($row['[1_452]'])) {// NET.P_S_PARAM1
			if (!array_key_exists($row['[1_452]'], $specialFltrs['net_speed']->values)) {
				$specialFltrs['net_speed']->lastInd += 1;
				$specialFltrs['net_speed']->values[$row['[1_452]']] = $specialFltrs['net_speed']->lastInd;
			}
			$oferty[$ind]['_cls'] .= ' net_speed-fltr-' . $specialFltrs['net_speed']->values[$row['[1_452]']];
		}
		if (!empty($row['TV_P_SERVICE_NAME'])) {// TV lub TVC name
			if (!array_key_exists($row['TV_P_SERVICE_NAME'], $specialFltrs['tv_name']->values)) {
				$specialFltrs['tv_name']->lastInd += 1;
				$specialFltrs['tv_name']->values[$row['TV_P_SERVICE_NAME']] = $specialFltrs['tv_name']->lastInd;
			}
			$oferty[$ind]['_cls'] .= ' tv_name-fltr-' . $specialFltrs['tv_name']->values[$row['TV_P_SERVICE_NAME']];
		}
		if (!empty($row['5_450'])) {// TV name
			if (!array_key_exists($row['5_450'], $specialFltrs['tel_name']->values)) {
				$specialFltrs['tel_name']->lastInd += 1;
				$specialFltrs['tel_name']->values[$row['5_450']] = $specialFltrs['tel_name']->lastInd;
			}
			$oferty[$ind]['_cls'] .= ' tel_name-fltr-' . $specialFltrs['tel_name']->values[$row['5_450']];
		}
		if (!empty($row['0_451'])) {// [0_451] => Witaminowa bomba
			if (!array_key_exists($row['0_451'], $specialFltrs['promo_name']->values)) {
				$specialFltrs['promo_name']->lastInd += 1;
				$specialFltrs['promo_name']->values[$row['0_451']] = $specialFltrs['promo_name']->lastInd;
			}
			$oferty[$ind]['_cls'] .= ' promo_name-fltr-' . $specialFltrs['promo_name']->values[$row['0_451']];
		}
	}
}

//if (!$_GET['print']) {
	echo '<div style="margin:3px;">';
		echo '<button id="tbl-oferty-rowin-all">' . "Rozwin wszystkie" . '</button>';
		echo '<button id="tbl-oferty-zwin-all">' . "Zwin wszystkie" . '</button>';
		echo '<form action="#" method="post" style="display:inline" id="tbl-oferty-specialFltrs">';
		echo ' Filtry: ';
		foreach ($specialFltrs as $kFltr => $vFltr) {
			if (!empty($vFltr->values)) {
				echo '<select name="' . $kFltr . '">';
					echo '<option value=""> [' . $vFltr->label . '] </option>';
				foreach ($vFltr->values as $kLabel => $vVal) {
					echo '<option value="fltr-' . $vVal . '">' . $kLabel .'</option>';
				}
				echo '</select>';
			}
		}
		echo '</form>';
	echo '</div>';
//}

$oferty_opcje_all = PokazOfertyHelper::get_oferty_opcje_all();
$oferty_opcje_cols = PokazOfertyHelper::get_oferty_opcje_visible_cols();
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">$oferty_opcje: ';print_r($oferty_opcje);echo'</pre>';
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($oferty_group_add_info ['labels']);echo'</pre>';
echo '<table cellspacing="0" cellpadding="0" border="1" id="tbl-oferty-opcje" style="display:none;">';
echo '<caption>' . "Oferty dodatkowe" . '</caption>';
foreach ($oferty_opcje_all as $k_service => $v_oferty) {
	$isOpcjaService = in_array($k_service, array('OPCJA_TVC','OPCJA_TEL'));

	echo '<tbody id="oferty-opcje-service-'.$k_service.'">';
	foreach ($v_oferty as $k_id => $v_oferta) {
		echo '<tr class="row-oferty-opcje' . (($isOpcjaService)? ' row-oferty-opcje-srv' : '') . '">';
			echo '<td>';
				if ($isOpcjaService) {
					echo substr($k_service, 6) . '<br>';
				}
				$option_name = 'id_options_' . $k_service . '[]';
				echo '<input type="checkbox" name="'.$option_name.'" value="' . $k_id . '" data-p_service="' . $k_service . '" onclick="return select_option(this);" />';
			echo '</td>';
			foreach ($oferty_opcje_cols as $k_field => $v_type_label) {
				if ($k_field == 'koszt') {
					$koszt = (double)$v_oferta->$k_field;
					echo '<td>' . number_format($koszt, 2, ',', ' ') . '</td>';
				} else {
					echo '<td>' . $v_oferta->$k_field . '</td>';
				}
			}
		echo '</tr>';
	}
	echo '</tbody>';
}
echo '</table>';

echo PokazOfertyView::print_js_umowa(count($oferty_group_cols_new) + 3);

echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl tbl-hover" id="tbl-oferty">';
echo '<thead>';
echo '<tr>';
foreach ($oferty_group_cols_new as $k_field => $v_value) {
	$cls = '';
	if ($k_field == '0_1380') $cls = ' class="cell-id"';
	if (array_key_exists($k_field, $oferty_group_cols)) {
		$v_params = $oferty_group_cols[ $k_field ];
		$field_header = '<code>'.$k_field.'</code>';
		if ($v_params['label']) $field_header = $v_params['label']." ".$field_header;
		else $field_header = str_replace('_', ' ', $v_params['field'])." ".$field_header;
		echo'<th'.$cls.'>'.$field_header.'</th>';
	} else {
		echo'<th'.$cls.'>'.$v_value.'</th>';
	}
}
echo '</tr>';
echo '</thead>';
echo '<tbody>';

$t = 0;
$pakiet_lp = 0;
foreach ($oferty as $row) {
	$pakiet_lp += 1;

	$suma_P_PROMO_MONTH_PRICE = 0;
	$suma_P_CONTRACT_PRICE = 0;
	$suma_P_PROMO_INSTALL_PRICE = 0;
	$suma_P_OFFER_SREDNIA = 0;
	$suma_P_OFFER_SREDNIA_NETTO = 0;
	$suma_P_OFFER_COSTS = 0;
	$suma_P_OFFER_COSTS_START = 0;
	$curr_oferty_costs = array();
	foreach ($oferty_cols as $k_service => $v_oferty_cols) {
		if ($row[$k_service] <= 0) {
			continue;
		}
//		foreach ($oferty_cols[$k_service] as $k_field => $v_params) {
//			$field_header = ($v_params['label'])? $v_params['label'] : str_replace('_', ' ', $v_params['field']);
//			if ($v_params['title']) $field_header = '<span title="'.$v_params['title'].'">'.$field_header.'</span>';
//			$field_header .= " ".'<code>'.$k_field.'</code>';
//		}//end foreach
		foreach ($oferty_cols[$k_service] as $k_field => $v_params) {
			$st = '';
			if ($v_params['field'] == 'ID') $st .= 'font-weight:bold;';
			if ($v_params['field'] == 'P_PROMO_MONTH_PRICE') $st .= 'background-color:#FDFD74;';
			if ($v_params['field'] == 'P_INSTALL_QUOTE') $st .= 'background-color:#84FD74;';
			$st = ($st)? ' style="'.$st.'"' : '';

			if ($v_params['field'] == 'P_PROMO_MONTH_PRICE') {
				$suma_P_PROMO_MONTH_PRICE += $row[$k_field];
			}
			else if ($v_params['field'] == 'P_CONTRACT_PRICE') {
				$suma_P_CONTRACT_PRICE += $row[$k_field];
			}
			else if ($v_params['field'] == 'P_INSTALL_QUOTE') {
				$suma_P_PROMO_INSTALL_PRICE += $row[$k_field];
			}
			else if ($v_params['field'] == 'ID') {// add cost
				if (array_key_exists($row[$k_field], $oferty_costs)) {
					$curr_oferty_costs[$k_service] = $oferty_costs[ $row[$k_field] ];
					$suma_P_OFFER_COSTS += $oferty_costs[ $row[$k_field] ];
				}
				if (array_key_exists($row[$k_field], $oferty_costs_start)) {
					$suma_P_OFFER_COSTS_START += $oferty_costs_start[ $row[$k_field] ];
				}
			}
			else if ($v_params['field'] == 'srednia') {// add srednia
				$suma_P_OFFER_SREDNIA += $row[$k_field];
			}
			else if ($v_params['field'] == 'srednia_netto') {
				$suma_P_OFFER_SREDNIA_NETTO += $row[$k_field];
			}
		}
	}

	echo '<tr class="tbl-row tbl-row-' . ($t = 1 - $t) . ' ' . $row['_cls'] . '">';
		$st = '';
		$help = '';
		if ($row['P_OFFER_TARGET']) {
			if (isset($oferty_filters['f_P_OFFER_TARGET']['color'][ $row['P_OFFER_TARGET'] ])) {
				$st = ' style="background-color:'.$oferty_filters['f_P_OFFER_TARGET']['color'][ $row['P_OFFER_TARGET'] ].';"';
			}
			$help = $row['P_OFFER_TARGET'];
			if (isset($oferty_filters['f_P_OFFER_TARGET']['help'][ $row['P_OFFER_TARGET'] ])) {
				$help .= ' - ' . $oferty_filters['f_P_OFFER_TARGET']['help'][ $row['P_OFFER_TARGET'] ];
			}
			$help = ' title="' . $help . '"';
		}
		echo '<td class="cell-id"'.$st.$help.'>' . $row['0_1380'] . '</td>';
		echo '<td>' . $row['0_S_ALIAS'] . " " . '<em style="color:#555;">' . "(" . $row['0_451'] . ")</em>" . '</td>';
		echo '<td>';
			if ($row['t0_ID_PROCES'] > 0) {
				echo ' <a href="' . "procesy5.php?task=PROCES_VIEW&id_proces={$row['t0_ID_PROCES']}" . '" target="_blank" style="color:#00f;font-weight:bold;text-decoration:none;" title="' . "Proces {$row['t0_ID_PROCES']}" . '">' . "(?)" . '</a>';
			}
		echo '</td>';
		echo '<td>' . $row['0_456'] . '</td>';
		echo '<td class="cell-suma_1">' . number_format($suma_P_PROMO_INSTALL_PRICE, 2, ',', ' ') . " zł" . '</td>';
		echo '<td class="cell-suma_2">' . "<b>" . number_format($suma_P_PROMO_MONTH_PRICE, 2, ',', ' ') . "</b> zł" . " / " . number_format($suma_P_CONTRACT_PRICE, 2, ',', ' ') . " zł" . '</td>';
		echo '<td class="cell-srednia">' . "" . number_format($suma_P_OFFER_SREDNIA, 2, ',', ' ') . " zł" . '</td>';
//		echo '<td class="cell-srednia">' . "" . number_format($suma_P_OFFER_SREDNIA, 2, ',', ' ') . " zł / " . number_format($suma_P_OFFER_SREDNIA_NETTO, 2, ',', ' ') . " zł" . '</td>';
		echo '<td class="cell-cost">' . "" . number_format($suma_P_OFFER_COSTS, 2, ',', ' ') . " zł" . '</td>';
		echo '<td class="cell-zysk">' . "" . number_format($suma_P_OFFER_SREDNIA_NETTO - $suma_P_OFFER_COSTS - ($suma_P_OFFER_COSTS_START / $row['0_456']), 2, ',', ' ') . " zł" . '</td>';
	echo '</tr>';
	echo '<tr class="sub sub-' . $t . '" style="display:none;">';
		echo '<td colspan="' . count($oferty_group_cols_new) . '" class="sub-oferty-wrap">';
			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($row);echo'</pre>';
			echo '<table class="sub-oferty" cellspacing="0" cellpadding="0" border="1">';
				echo '<thead>';
					echo '<tr>';
						echo '<th>';
							$link_href = "./odt2xhtml/1379.umowa.php";
							$link_href .= "?id_group=" . $row['0_1380'];
							if (($user_id = V::get('user_id', 0, $_GET, 'int')) > 0) {
								$link_href .= "&id_user={$user_id}";
							}
							$js = "return print_umowa(this);";
							echo '<a href="' . $link_href . '" href_base="' . $link_href . '" title="' . "Drukuj umowę [1379]" . '" target="_blank" onclick="' . $js . '">' . '<img src="icon/print.gif" height="24" />' . '</a>';
						echo '</th>';
						foreach ($oferty_group_add_info ['labels'] as $k_zasob_id => $v_label) {
							echo '<th>' . $v_label . '</th>';
						}
						echo '<th>' . "Koszt (netto)" . '</th>';
					echo '</tr>';
				echo '</thead>';
				echo '<tfoot>';
					echo '<tr>';
						echo '<th colspan="'.(count($oferty_group_add_info['labels']) + 2).'" style="text-align:left">';
							$link_href = "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC";
							//"S_ADDRESS_STREET=&ADD=SZUKAJ";
							$link_href .= "&task=dodaj_aneks";
							$link_href .= "&S_ADDRESS_STREET=" . $_GET['S_ADDRESS_STREET'];
							$link_href .= "&id_group=" . $row['0_1380'];
							$link_href .= "&user_id=" . $_GET['user_id'];
							$js = "return print_umowa(this);";
							echo '<a href="' . $link_href . '" href_base="' . $link_href . '" title="' . "Dodaj aneks lub nową umowę" . '" onclick="' . $js . '">' . '<img src="icon/add.gif" alt="+" />' . " Dodaj aneks lub nową umowę" . '</a>';

							$js = "return umowaZysk_click(this); return false;";
							?>
								<a class="btn btn-mini pull-right" href="#" data-id_group="<?php echo $row['0_1380']; ?>" title="Oblicz zysk" onclick="<?php echo $js; ?>">Oblicz zysk</a>
							<?php
						echo '</th>';
					echo '</tr>';
				echo '</tfoot>';
					foreach ($oferty_p_services as $k_field_id => $v_p_service) {
						if ($row[$k_field_id] > 0) {
							$html_cell_id = $row['0_1380'] . '-' . $row[$k_field_id];
							echo '<tbody id="' . $html_cell_id . '">';
							echo '<tr>';
								echo '<td>';
									$outPService = explode('_', $v_p_service);
									echo reset($outPService);
									echo '<br />';
									$js = "return show_opcje('" . $html_cell_id . "', '" . $v_p_service . "');";
									echo '<a href="' . "#" . '" onclick="' . $js . '">' . "opcje" . '</a>';
								echo '</td>';// clean numbers from TVCP_1
								foreach ($oferty_group_add_info ['labels'] as $k_zasob_id => $v_type_label) {
									$k_field_name = $oferty_group_add_info [$v_p_service][$k_zasob_id];
									echo '<td>';
									if ($k_zasob_id == 'ID_PROCES') {
										if ($row[$k_field_name] > 0) {
											echo ' <a href="' . "procesy5.php?task=PROCES_VIEW&id_proces={$row[$k_field_name]}" . '" target="_blank" style="color:#00f;font-weight:bold;text-decoration:none;" title="' . "Proces {$row[$k_field_name]}" . '">' . "(?)" . '</a>';
										}
									} else {
										echo $row[$k_field_name];
									}
									echo '</td>';
								}
								echo '<td>';
									foreach ($curr_oferty_costs as $k_service => $v_cost) {
										if (substr($k_service, -1 * (strlen($v_p_service))) == $v_p_service) {
											echo number_format($v_cost, 2, ',', ' ');
										}
									}
								echo '</td>';
							echo '</tr>';
						}
						echo '</tbody>';
					}
			echo '</table>';
		echo '</td>';
	echo '</tr>';
}

echo '</tbody>';
echo '</table>';
}

function POKAZ_OFERTY_AKTUALNE_FUNC__ajax_search_user($q) {
	header('Content-Type: text/plain; charset=utf8');
	$users = array();
	$users_rows = PokazOfertyHelper::get_users_by_query($q);
	//die(V::json_encode_latin2($streets));
	if (empty($users_rows)) {
		die('Brak danych');
	}
	foreach ($users_rows as $r) {
		$v_user = '' . $r->P_NAME . ' ' . $r->P_NAME_SECOND . ' ';
		if ($r->is_firma) $v_user = '(Firma) ' . $v_user;
		$v_user_add = array();
		if (!empty($r->P_PESEL)) $v_user_add []= 'PESEL: ' . $r->P_PESEL;
		if (!empty($r->P_NIP)) $v_user_add []= 'NIP: ' . $r->P_NIP;
		if (!empty($v_user_add)) {
			$v_user .= ' (' . implode(', ', $v_user_add) . ')';
		}
		$users [$r->ID]= $v_user;
	}
	if (empty($users)) {
		die('Brak danych');
	}
	$size = count($users_rows);
	if ($size > 10) $size = 10;
	else if ($size < 2) $size = 2;
	echo '<select size="' . $size . '" id="frm_Q_select">';
	foreach ($users as $k_user => $v_user) {
		echo '<option value="' . $k_user . '">' . $v_user . "  " . '</a>';
	}
	echo '</select>';
	echo '<script type="text/javascript">' . "
(function(){
//	jQuery('#frm_Q_select option').click(function(e){
//		ajax_street_select(e.target);
//	});
	jQuery('#frm_Q_select').change(function(e){
		jQuery('#frm_Q').val(jQuery(e.target).val());
	});
})();
	" . '</script>';
	exit;
}

function POKAZ_OFERTY_AKTUALNE_FUNC__ajax_search_street($street) {
	header('Content-Type: text/plain; charset=utf8');
	$streets = array();
	if (empty($street)) {
		die('Brak danych');
	}
	$db = DB::getDB();
	$sql = "select m.`ID`, m.`S_ADDRESS_STREET`, m.`T_TELBOX_BUILDING_IN`
		from `USERS2_MARKETING` as m
		where m.`A_STATUS` in('WAITING','NORMAL','MONITOR','WARNING','OFF_SOFT','OFF_HARD')
			and m.`S_ADDRESS_STREET` like  '" . $db->_($street) . "%'
	";
	$res = $db->query($sql);
	while ($r = $db->fetch($res)) {
		$r->T_TELBOX_BUILDING_IN = strtoupper($r->T_TELBOX_BUILDING_IN);
		$r->S_ADDRESS_STREET = strtoupper($r->S_ADDRESS_STREET);
		$s_address_street = explode('/', $r->S_ADDRESS_STREET, 2);
		$r->dom = intval( preg_replace('/[^0-9]/', '', reset($s_address_street)) );// reset($s_address_street);
		$r->nr_domu = end($s_address_street);
		$streets_rows []= $r;
	}
	if (empty($streets_rows)) {
		die('Brak danych');
	}
	function sort_streets_callback($a, $b) {
		if ($a->dom < $b->dom) {
			return -1;
		} else if ($a->dom > $b->dom) {
			return 1;
		} else if ($a->nr_domu < $b->nr_domu) {
			return -1;
		} else if ($a->nr_domu > $b->nr_domu) {
			return 1;
		} else {
			return 0;
		}
	}
	uasort($streets_rows, 'sort_streets_callback');

	foreach ($streets_rows as $v_street) {
		$streets []= $v_street->S_ADDRESS_STREET;
	}

	//die(V::json_encode_latin2($streets));
	if (empty($streets)) {
		die('Brak danych');
	}
	$size = count($streets);
	if ($size > 5) $size = 5;
	else if ($size < 2) $size = 2;
	echo '<select size="' . $size . '" id="frm_S_ADDRESS_STREET_select">';
	foreach ($streets as $v_street) {
		//echo '<option onclick="return ajax_street_select(this);" value="' . $v_street . '">' . $v_street . "  " . '</a>';
		echo '<option value="' . $v_street . '">' . $v_street . "  " . '</a>';
	}
	echo '</select>';
	echo '<script type="text/javascript">' . "
(function(){
//	jQuery('#frm_S_ADDRESS_STREET_select option').click(function(e){
//		ajax_street_select(e.target);
//	});
	jQuery('#frm_S_ADDRESS_STREET_select').change(function(e){
		jQuery('#frm_S_ADDRESS_STREET').val(jQuery(e.target).val());
	});
})();
	" . '</script>';
	exit;
}

function POKAZ_OFERTY_AKTUALNE_FUNC__dodaj_aneks() {
	/*
	 * 1. wybierz budynek - S_ADDRESS_STREET
	 * 2. wybierz ofertę - id_group, wraz z opcjami (id_options_NET, id_options_TV, id_options_TEL)
	 * 3. wybierz klienta - na podstawie aktywnych umów na wybranym budynku
	 * 4. wybierz aktywne umowy
	 * 5. utwórz rekord w DEALS_TABLE
	 * 6. utwórz rekordy w USERS2_DEALS wg. wybranych usług i zaznaczonych opcji
	 */

/*
    [MENU_INIT] => POKAZ_OFERTY_AKTUALNE_FUNC
    [task] => dodaj_aneks
    [S_ADDRESS_STREET] => ci50%
    [id_group] => 1474
    [id_options_NET] => Array
            [0] => 445
            [1] => 1247
    [id_options_TV] => Array
            [0] => 598
    [print] => 
 */

	$view = new PokazOfertyView();
	echo $view->print_css();

	$con = new PokazOfertyController();
	$con->set_params_from_request();
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none">con: (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($con);echo'</pre>';
	if ($con->hasOptionsToServices()) {
		?>
		<div class="alert alert-warning">
			<strong>Uwaga wersja testowa!</strong> wymagane utworzenie specjalengo pakietu na podstawie wybranych opcji.
		</div>
		<?php if (!$con->convertOptionsToSrv()) : ?>
			<div class="alert alert-error">
				<strong>Bład!</strong> nie udało się utworzyć nowej grupy na podstawie wybranych parametrów.
			</div>
		<?php else : ?>
			<div class="alert alert-success">
				Nowy numer oferty to <?php echo $con->get_param('id_group'); ?>.
			</div>
		<?php endif; ?>
		<?php
	}

	echo '<h1>';
		echo '<a href="' . $con->url(array('task'=>'')) . '">' . "POKAZ OFERTY AKTUALNE" . '</a>';
		echo " &raquo; ";
		echo '<a href="' . $con->url(array('user_id'=>'')) . '">' . " Oferta " . $con->get_param('id_group') . " " . '</a>';
		if ($con->get_param('user_id') > 0) {
			echo " &raquo; ";
			echo '<a href="' . $con->url() . '">' . " Klient " . $con->get_param('user_id') . " " . '</a>';
		}
	echo '</h1>';

	$group = $con->get_group();
	if (!$group) {
		echo '<p>' . "Errro: bledny numer pakietu '" . $con->get_param('id_group') . "'" . '</p>';
		return;
	}

	$con->fetch_group_data();

	$view->print_group_info($group, array('user_id'=>$con->get_param('user_id')));

	// TODO: user_id is required? or ajax search for user_id
	if ($con->get_param('user_id') <= 0) {
		echo '<p style="color:red">' . "Nie wybrano klienta!" . '</p>';
		return;

		$active_deals = PokazOfertyHelper::get_deals_active_by_street($con->get_param('S_ADDRESS_STREET'));

		if (empty($active_deals)) {
			echo '<p>' . "Brak aktywnych umów na danym adresie '" . $con->get_param('S_ADDRESS_STREET') . "'" . '</p>';
			// TODO: wybierz innego klienta?
			return;
		}
		echo '<h4>' . "Wybierz klienta z aktualną umową na adresie '" . $con->get_param('S_ADDRESS_STREET') . "'" . '</h4>';
		$tbl_cells = array();// field_name => label
		$tbl_cells['ID_BILLING_USERS'] = 'ID klienta';
		$tbl_cells['P_NAME'] = 'Imię i nazwisko';
		$tbl_cells['ID_DEALS'] = 'ID umowy';
		$tbl_cells['SERVICES_S_ADDRESS_STREET'] = 'adres instalacji usług';
		echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
		echo '<thead>';
		echo '<tr>';
			echo '<th>' . "&nbsp;" . '</th>';
			foreach ($tbl_cells as $k_field => $v_label) {
				echo '<th>' . $v_label . '</th>';
			}
		echo '</tr>';
		echo '</thead>';
		echo '<tbody>';
		$t = 0;
		foreach ($active_deals as $v_usr_arr) {
			$v_cell = array();
			foreach ($v_usr_arr as $v_usr) {
				foreach ($v_usr as $k_field => $v_value) {
					if (array_key_exists($k_field, $v_cell)) {
						if ($v_cell[$k_field] != $v_value) {
							$v_cell[$k_field] .= ', ' . $v_value;
						}
					} else {
						$v_cell[$k_field] = $v_value;
					}
				}
			}
			echo '<tr class="tbl-row-'.($t = 1 - $t).'">';
				echo '<td>' . '<a href="' . $con->url(array('user_id'=>$v_cell['ID_BILLING_USERS'])) . '">' . " Wybierz " . '</a>' . '</td>';
				foreach ($tbl_cells as $k_field => $v_label) {
					echo '<td>' . $v_cell[$k_field] . '</td>';
				}
			echo '</tr>';
		}
		echo '</tbody>';
		echo '</table>';

		return;
	}

	// dodaj aneks dla klienta, numeru pakietu i opcji dodatkowych
	$user = PokazOfertyHelper::get_user_info($con->get_param('user_id'));
	if (!$user) {
		echo '<p>' . "Error: brak informacji o kleincie '" . $con->get_param('user_id') . "'" . '</p>';
		return;
	}

	// aktywne umowy klienta na danym adresie
	$active_deals_by_id = $con->get_deals_active_with_info();

	$view->user_with_services($user, $active_deals_by_id);

	/* $user = stdClass Object
			[ID_BILLING_USERS] => 2138// [id_users] => 2138
			[is_firma] => 0
			[P_NAME] => Agnieszka
			[P_NAME_SECOND] => Katka
			[P_NIP] => AIX286269
			[P_PESEL] => 
			[P_PHONE] => 303-38-75; 507-093-885
			[P_ADDRESS_REGION] => 11
			[P_ADDRESS_CITY] => Gdańsk
			[P_ADDRESS_POST_CODE] => 80-809
			[P_ADDRESS_STREET] => Cieszyńskiego
			[P_ADDRESS_HOME] => 38
			[P_ADDRESS_HOUSE] => 50
			[user_mail_contact] => sole@chelmnet.pl
	 * 
	 * kwerenda ODBC
		, '' as KLIENT_ID
		, '' as KLIENT_IS_FIRMA		-- X or ''
		, '' as KLIENT_IS_OSOBA_FIZYCZNA		-- X or ''
		, '' as KLIENT_P_NAME
		, '' as KLIENT_P_NAME_SECOND
		, '' as KLIENT_P_NIP
		, '' as KLIENT_P_PESEL
		, '' as KLIENT_P_PHONE
		, '' as KLIENT_P_ADDRESS_REGION
		, '' as KLIENT_P_ADDRESS_CITY
		, '' as KLIENT_P_ADDRESS_POST_CODE
		, '' as KLIENT_P_ADDRESS_STREET
		, '' as KLIENT_P_ADDRESS_HOME
		, '' as KLIENT_P_ADDRESS_HOUSE
		, '' as KLIENT_user_mail_contact
		, '' as NR_UMOWY
		, '' as NR_ANEKSU
	 */

	if (empty($active_deals_by_id)) {
		//echo '<p>' . "Error: brak aktywnych umów klienta " . $con->get_param('user_id') . '</p>';
		//return;
	}

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

	$con->_deals_table = PokazOfertyHelper::get_deals_table_empty_object();
	$con->_deals_table->set_new_deal_data($group);
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$user (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($user);echo'</pre>';
	$con->_deals_table->set_s_address_street($con->get_param('S_ADDRESS_STREET'));
	$con->_deals_table->set_user_data($user);
	$con->_deals_table->generate_P_DEALNUMBER();

	$users2_deals = PokazOfertyHelper::get_users2_deals_empty_object();
	$users2_deals->set_deal_table($con->_deals_table);
	$users2_deals->set_s_address_street($con->get_param('S_ADDRESS_STREET'));
	//$users2_deals->set_new_deal_data($group);
	$users2_deals->set_old_deals_data($active_deals_by_id);
	$users2_deals->generate_srv_map();

	echo '<script type="text/javascript">' . "
jQuery(document).ready(function (){
	window.deal_frm = {};
	window.deal_frm.html_frm = document.forms.deal_form;
	window.deal_frm.html_frm_users2_deals = document.forms.deal_form_users2_deals;
	window.deal_frm.html_frm_deals_table = document.forms.deal_form_deals_table;
	window.deal_frm.deals = " . V::json_encode_latin2($users2_deals->get_old_deal_data(), true) . ";
	window.deal_frm.srv_map = " . V::json_encode_latin2($users2_deals->get_srv_map(), true) . ";
	window.deal_frm.cols = " . V::json_encode_latin2($users2_deals->get_cols(), true) . ";
	window.deal_frm.offer_ids = " . V::json_encode_latin2($con->_deals_table->get_offers_ids(), true) . ";

	window.deal_frm.clear_preview = function(){
		var p_cell='';
		jQuery('#' + 'DEALS_TABLE' + '-' + 'P_DEALNUMBER_OLD').val('');
		for(var offer_ind in window.deal_frm.offer_ids){
			for(var col_ind in window.deal_frm.cols){
				// name / id = 'NEW_OFFER-598-P_OFFER_ID_OLD'
				p_cell = 'NEW_OFFER-' + window.deal_frm.offer_ids[offer_ind] + '-' + window.deal_frm.cols[col_ind];
				if(undefined != window.deal_frm.html_frm_users2_deals[p_cell]){
					window.deal_frm.html_frm_users2_deals[p_cell].value='';
					jQuery('#' + p_cell).text(' ');
				}
			}
		}
		jQuery(window.deal_frm.html_frm_users2_deals).find('.old-deal').hide();
	}

	console.log(window.deal_frm)
});


function deal_select_deal(n){
	window.deal_frm.clear_preview();
	if(undefined != deal_frm.deals[n.value]){
		var deal=deal_frm.deals[n.value],
			srv_map=deal_frm.srv_map[n.value];
		jQuery('#' + 'DEALS_TABLE' + '-' + 'P_DEALNUMBER_OLD').val(deal.ID_DEALS);

		var srv,out_offer_id=0;
		for(var srv_id in srv_map){
			out_offer_id=srv_map[srv_id];
			if (out_offer_id > 0) {
				srv=deal.services_by_id[srv_id];

				jQuery('#NEW_OFFER-' + out_offer_id + '-' + 'ID_BILLING_USERS_OLD').text(deal.ID_BILLING_USERS);
				jQuery('#NEW_OFFER-' + out_offer_id + '-' + 'P_DEALNUMBER_OLD').text(deal.ID_DEALS);
				jQuery('#NEW_OFFER-' + out_offer_id + '-' + 'P_DEAL_DATE_OLD').text(deal.P_DEALDATE);
				jQuery('#NEW_OFFER-' + out_offer_id + '-' + 'P_DEALTERM_OLD').text(deal.P_DEALDATE_TERM);

				jQuery('#NEW_OFFER-' + out_offer_id + '-' + 'ID_SERVICES_OLD').text(srv.ID);
				jQuery('#NEW_OFFER-' + out_offer_id + '-' + 'P_OFFER_ID_OLD').text(srv.ID_OFFERS);
				jQuery('#NEW_OFFER-' + out_offer_id + '-' + 'MONTH_COST_OLD').text(srv.ABONAMENT_VALUE);
			}
		}
		jQuery(window.deal_frm.html_frm_users2_deals).find('#OLD_DEAL-' + n.value).show();
	}
}
	" . '</script>';

	$con->_show_deal_form = true;
	if ('' != V::get('save_deal_form', '', $_POST)) {
		$con->save_deal_form(V::get('active_deal_id', 0, $_POST, 'int'), $users2_deals);
	}
	if ($con->_show_deal_form) {
		echo '<h4 style="margin-bottom:6px;">' . "Wybierz umowy do aneksu lub nową umowę" . '</h4>';
		echo '<form action="#" method="post" id="deal_form" name="deal_form">';
			echo '<input type="radio" name="' . "active_deal_id" . '" value="' . "-1" . '" onclick="return deal_select_deal(this)" />';
			echo " Nowa umowa";
			echo '<br />';
			if (!empty($active_deals_by_id)) {
				foreach ($active_deals_by_id as $k_deal_id => $v_deal) {
					echo '<input type="radio" name="' . "active_deal_id" . '" value="' . $k_deal_id . '" onclick="return deal_select_deal(this)" />';
					echo " Umowa ID " . $v_deal->ID_DEALS . " (P_DEALNUMBER: " . $v_deal->P_DEALNUMBER . ", " . $v_deal->P_DEALDATE . " - " . $v_deal->P_DEALDATE_TERM . ")";
					echo " usługi: " . implode(", ", array_keys($v_deal->services));
					foreach ($v_deal->services as $k_pservice => $v_value) {
						echo '<input type="hidden" name="' . $k_deal_id . "-" . $k_pservice . '" value="' . $k_pservice . '" />';
					}
					echo '<br />';
				}
			}
			echo '<input type="submit" name="' . "save_deal_form" . '" value="' . "Dodaj rekordy do tabeli DEALS_TABLE i USERS2_DEALS" . '" />';
		echo '</form>';// #deal_form
	} else {
		// OK utworzono umowę - pokaz dodane rekordy? link do edycji rekordu?
		
		return;
	}

	echo '<br />';

	echo '<h3>' . "Podgląd rekordów do utworzenia:" . '</h3>';
	$con->_deals_table->view_table();
	echo '<br />';
	$users2_deals->view_table();
}

class PokazOfertyController {

	var $params;
	var $allowed_options;
	var $id_options;
	var $active_deals_by_id;

	/*
			[MENU_INIT] => POKAZ_OFERTY_AKTUALNE_FUNC
			[task] => dodaj_aneks
			[S_ADDRESS_STREET] => ci50%
			[id_group] => 1474
			[id_options_NET] => Array
							[0] => 445
							[1] => 1247
			[id_options_TV] => Array
							[0] => 598
			[id_deals] => Array -- active deals do zastapienia
							[0] => 1234
							[1] => 5678
			[print] => 
	 */

	function __construct() {
		$this->params = array();
		$this->allowed_options = array('NET', 'TEL', 'TV', 'TVC');
		$this->id_options = array();
		$this->active_deals_by_id = array();
		$this->group = null;
		$this->allowed_options_to_srv = array('TVC'=>'OPCJA_TVC', 'TEL'=>'OPCJA_TEL');
		$this->options_to_srv = array();// special options to convert to services
	}

	/**
	 * Set params values from request.
	 */
	function set_params_from_request() {
		$this->params['MENU_INIT'] = V::get('MENU_INIT', 'POKAZ_OFERTY_AKTUALNE_FUNC', $_GET);
		$this->params['task'] = V::get('task', 'dodaj_aneks', $_GET);
		if (isset($_GET['S_ADDRESS_STREET'])) {
			$this->params['S_ADDRESS_STREET'] = $_GET['S_ADDRESS_STREET'];
			//$this->params['S_ADDRESS_STREET'] = (substr($_GET['S_ADDRESS_STREET'], -1) != '%')? $_GET['S_ADDRESS_STREET'] . '%' : $_GET['S_ADDRESS_STREET'];
		}
		if (isset($_GET['user_id'])) {
			$this->params['user_id'] = V::get('user_id', 0, $_GET, 'int');
		}
		if (isset($_GET['id_group'])) {
			$this->params['id_group'] = V::get('id_group', 0, $_GET, 'int');
		}
		$this->params['id_deals'] = V::get('id_deals', array(), $_GET, 'array');

		// fetch id options
		foreach ($this->allowed_options as $v_option) {
			$this->params['id_options_' . $v_option] = V::get('id_options_' . $v_option . '', array(), $_GET, 'array');
			$this->id_options[$v_option] = V::get('id_options_' . $v_option . '', array(), $_GET, 'array');
		}

		// fetch id options to services
		foreach ($this->allowed_options_to_srv as $kSrv => $vOption) {
			$this->id_options_to_srv[$kSrv]['id_options_' . $vOption] = V::get('id_options_' . $vOption, array(), $_GET, 'array');
		}
		// filter options - remove empty and not numeric values
		foreach ($this->allowed_options_to_srv as $kSrv => $vOption) {
			if (is_array($vOption) && !empty($vOption)) foreach ($vOption as $kOption => $vValue) {
				$this->id_options_to_srv[$kSrv][$kOption] = array_filter($this->id_options_to_srv[$kSrv][$kOption], function($value) {
					return !empty($value) && is_numeric($value);
				});
			}
			$this->id_options_to_srv[$kSrv] = array_filter($this->id_options_to_srv[$kSrv], function($value) {
				return !empty($value);
			});
		}
		$this->id_options_to_srv = array_map(function($value) {
			if (count($value) == 1) {
				$vOptions = reset($value);
				if (count($vOptions) == 1) {
					return reset($vOptions);
				}
			}
			return null;
		}, $this->id_options_to_srv);
		$this->id_options_to_srv = array_filter($this->id_options_to_srv, function($value) {
			return !empty($value);
		});
	}

	public function hasOptionsToServices() {
		return !empty($this->id_options_to_srv);
	}

	public function convertOptionsToSrv() {
		$DBG = ('123' == V::get('DBG', '', $_GET));
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->id_options_to_srv);echo'</pre>';}

		$db = DB::getDB();
		if (!$db) return false;

		$group = $this->get_group();
		if (!$group) return false;

		/*
		 * 'TVC' => ID_TVC in USERS2_OFFERS_GROUPS
		 * 'TEL' => ID_TEL in USERS2_OFFERS_GROUPS
		 */
		$sqlSearch = array();
		foreach ($this->id_options_to_srv as $kService => $vOfferId) {
			switch ($kService) {
				case 'TVC': $sqlSearch[] = "g.`ID_TVC`='{$vOfferId}'"; break;
				case 'TEL': $sqlSearch[] = "g.`ID_TEL`='{$vOfferId}'"; break;
				default:
			}
		}
		if (count($sqlSearch) <= 0) return false;
		$sqlSearch = implode(" and ", $sqlSearch);

		$offersIds = array_values($this->id_options_to_srv);
		if ($this->group->_data['ID_NET'] > 0) $offersIds[] = $this->group->_data['ID_NET'];
		$offersByIds = PokazOfertyHelper::get_offers_by_id($offersIds);
		foreach ($this->id_options_to_srv as $kService => $vOfferId) {
			if (empty($offersByIds[$vOfferId])) {
				return false;
			}
		}

		$sqlIdGroup = $this->params['id_group'];
		$sql = "select g.`ID`
			from `USERS2_OFFERS_GROUPS` as g
			where g.`A_STATUS` in('WAITING','NORMAL','MONITOR')
				and {$sqlSearch}
				and g.`PARENT_ID`='{$sqlIdGroup}'
		";
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
		$groupsFound = array();
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$groupsFound[] = $r->ID;
		}

		if (empty($groupsFound)) {
			$sqlObj = (object)array_map(function($v) { return $v; }, $this->group->_data);
			$sqlObj->PARENT_ID = $sqlObj->ID;
			unset($sqlObj->ID);
			/* $sqlObj:
					[S_ALIAS] => ADRENALINET#7
					[P_PROMOTION_NAME] => TESTOWA OFERTA BIALL-NET#1
					[ID_TVC] => 0
					[ID_TEL] => 0
					[RABAT_IF_OPCJA_TVC] => 10
					[RABAT_IF_OPCJA_TEL] => 10
			 */
			/* $offersByIds[$vOfferId]:
            [S_ALIAS] => PAKIET CYFROWY - PLATYNOWY
            [P_SERVICE_NAME] => PAKIET CYFROWY - PLATYNOWY
            [P_PROMOTION_NAME] => OFERTA TESTOWA
			*/
			$rabat = 0;
			foreach ($this->id_options_to_srv as $kService => $vOfferId) {
				switch ($kService) {
					case 'TVC':
						$sqlObj->ID_TVC = $vOfferId;
						$sqlObj->S_ALIAS .= " + {$offersByIds[$vOfferId]->S_ALIAS}"; 
						$sqlObj->P_PROMOTION_NAME .= " + {$offersByIds[$vOfferId]->P_SERVICE_NAME}"; 
						if ($sqlObj->RABAT_IF_OPCJA_TVC > 0) {
							$rabat += $sqlObj->RABAT_IF_OPCJA_TVC;
						}
						break;
					case 'TEL':
						$sqlObj->ID_TEL = $vOfferId;
						$sqlObj->S_ALIAS .= " + {$offersByIds[$vOfferId]->S_ALIAS}"; 
						$sqlObj->P_PROMOTION_NAME .= " + {$offersByIds[$vOfferId]->P_SERVICE_NAME}"; 
						if ($sqlObj->RABAT_IF_OPCJA_TEL > 0) {
							$rabat += $sqlObj->RABAT_IF_OPCJA_TEL;
						}
						break;
					default:
				}
			}

			if ($rabat > 0) {
				$offerNet = $db->get_by_id('USERS2_OFFERS', $sqlObj->ID_NET);
				$newOfferNet = new stdClass();
				$rabatPr = 1 - $rabat/100;
				$newOfferNet->P_CONTRACT_PRICE    = round($rabatPr * $offerNet->P_CONTRACT_PRICE, 2);
				$newOfferNet->P_PROMO_MONTH_PRICE = round($rabatPr * $offerNet->P_PROMO_MONTH_PRICE, 2);

				$sql = "select o.`ID`
					from `USERS2_OFFERS` as o
					where o.`A_STATUS` in('WAITING','NORMAL','MONITOR')
						and o.`PARENT_ID`={$sqlObj->ID_NET}
						and o.`P_CONTRACT_PRICE`='{$newOfferNet->P_CONTRACT_PRICE}'
						and o.`P_PROMO_MONTH_PRICE`='{$newOfferNet->P_PROMO_MONTH_PRICE}'
				";
				$foundOfferNet = null;
				$res = $db->query($sql);
				while ($r = $db->fetch($res)) {
					$foundOfferNet = $r;
				}

				if (!$foundOfferNet) {
					foreach ($offerNet as $kFld => $vFld) {
						if (!isset($newOfferNet->$kFld)) {
							if ('ID' == $kFld) continue;
							if ('_NETTO' == substr($kFld, -6)) continue;
							if ('A_' == substr($kFld, 0, 2)) continue;
							$newOfferNet->$kFld = $offerNet->$kFld;
						}
					}
					$newOfferNet->S_ALIAS .= " (rabat {$rabat}%)";
					$newOfferNet->P_SERVICE_NAME .= " (rabat {$rabat}%)";
					$newOfferNet->P_PROMOTION_NAME .= " (rabat {$rabat}%)";
					$newOfferNet->PARENT_ID = $offerNet->ID;
					$newOfferNetId = $db->ADD_NEW_OBJ('USERS2_OFFERS', $newOfferNet);
					if ($newOfferNetId <= 0) {
						return false;
					}
				}
				else {
					$newOfferNetId = $foundOfferNet->ID;
				}
				if ($newOfferNetId <= 0) return false;
				$sqlObj->ID_NET = $newOfferNetId;
			}

			$sqlObj->A_STATUS = 'WAITING';
			if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sqlObj (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sqlObj);echo'</pre>';}
			$newGroupId = $db->ADD_NEW_OBJ('USERS2_OFFERS_GROUPS', $sqlObj);
			if ($newGroupId <= 0) return false;
		} else {
			$newGroupId = reset($groupsFound);
			if ($newGroupId <= 0) return false;
		}

		$this->params['id_group'] = $newGroupId;
		unset($this->group);
		$group = $this->get_group();
		$group->fetch_offers();
		return true;
	}

	/**
	 * Set param.
	 */
	function set_param($key, $value) {
		$this->params [$key] = $value;
	}

	/**
	 * Get user selected options id.
	 * 
	 * @returns Array(P_SERVICE => Array of offers ID)
	 */
	function get_id_options() {
		return $this->id_options;
	}

	/**
	 * Create url based on current params and given $params_add.
	 * 
	 * @returns String - url
	 */
	function url($params_add = array()) {
		$params = array();
		$params = array_merge_recursive($params, $this->params);// copy array
		if (!empty($params_add)) {
			//$params = array_merge_recursive($params, $params_add);
			foreach ($params_add as $k => $v) {
				$params[$k] = $v;
			}
		}
		$url_params_flat = array();
		if (!empty($params)) {
			foreach ($params as $k1 => $v1) {
				if (is_array($v1)) {
					foreach ($v1 as $k2 => $v2) {
						$url_params_flat []= '' . $k1 . '[]=' . $v2;
					}
				} else {
					$url_params_flat []= '' . $k1 . '=' . $v1;
				}
			}
		}
		return '?' . implode('&', $url_params_flat);
	}

	/**
	 * Get param.
	 * 
	 * @returns String or Array - param value
	 */
	function get_param($key) {
		$param = V::get($key, '', $this->params);
		// if array? - return array
		return $param;
	}

	/**
	 * Get group defined in params.
	 * 
	 * @return Column_users2_offers_groups - group with offers and options
	 */
	function get_group() {
		if (empty($this->group)) {
			if ($this->get_param('id_group') > 0) {
				$this->group = PokazOfertyHelper::get_group($this->get_param('id_group'));
				$this->group->set_id_options($this->get_id_options());
			}
		}
		return $this->group;
	}

	/**
	 * Get user deals active on selected street.
	 */
	function get_deals_active_with_info() {
		if (empty($this->active_deals_by_id)) {
			$this->active_deals_by_id = PokazOfertyHelper::get_deals_active_with_info($this->get_param('S_ADDRESS_STREET'), $this->get_param('user_id'));
		}
		return $this->active_deals_by_id;
	}

	/**
	 * Get deal with services.
	 * 
	 * @param $deal_id - deal ID
	 * 
	 * @returns deal info with connected services.
	 */
	function get_deal_with_services($deal_id) {
		$old_deal = null;
		$deals_active_arr = $this->get_deals_active_with_info();
		if (array_key_exists($deal_id, $deals_active_arr)) {
			$old_deal = $deals_active_arr[$deal_id];
		}
		return $old_deal;
	}

	/**
	 * Fetch group offers data.
	 */
	function fetch_group_data() {
		$this->group->fetch_offers();
	}

	/**
	 * Save deal form.
	 * 
	 * @param int $active_deal_id - 0 not set, -1 nowa umowa, > 0 nr umowy
	 * @param $users2_deals - Column_users2_deals to create rows in USERS2_DEALS
	 */
	function save_deal_form($active_deal_id, $users2_deals) {
		if ($active_deal_id == 0) {
			$this->_show_deal_form = true;
			echo '<p style="color:red">' . "Wybierz jedną z podanych opcji" . '</p>';
		}
		else if ($active_deal_id == -1) {// nowa umowa
			$new_deal_id = $this->_deals_table->create();
			if ($new_deal_id <= 0) {
				echo '<p style="color:red">' . "Error: wystąpił błąd podczas dodawania rekordu DEALS_TABLE" . '</p>';
			} else {
				// OK save USERS2_DEALS
				echo '<p style="color:green">' . "Utworzono umowę - rekord w tabeli DEALS_TABLE (ID=" . $new_deal_id . ")" . '</p>';

				$new_deal_row = PokazOfertyHelper::get_deal($new_deal_id);
				if ($new_deal_row) {
					$cols = array('ID', 'ID_BILLING_USERS', 'P_DEALNUMBER', 'P_DEALNUMBER_OLD', 'P_DEALDATE', 'P_DEALDATE_TERM', 'S_ADDRESS_STREET');
					PokazOfertyView::print_simple_tbl($new_deal_row, $cols, "Nowa umowa");
				}

				// create records in USERS2_DEALS
				$users2_deals->set_p_dealnumber_new($new_deal_id);

				if (!$users2_deals->create_rows()) {
					echo '<p style="color:red">' . "Error: wystąpił błąd podczas dodawania rekordów do USERS2_DEALS" . '</p>';
					$this->_show_deal_form = true;
				} else {
					echo '<p style="color:green">' . "Utworzono rekordy w tabeli USERS2_DEALS dla nowej umowy (ID=" . $new_deal_id . ")" . '</p>';
					$this->_show_deal_form = false;
				}

				echo '<a href="' . "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=895#EDIT/{$new_deal_id}" . '">' . "Przejdź do edycji umowy (DEALS_TABLE)" . '</a>';// TODO: 895 ID Zasobu DEALS_TABLE
			}
		}
		else if (false) {// aneks test
			echo '<div style="border:2px solid red;background:#FFE8E8;">';// TODO: TEST
			$this->_deals_table->set('P_DEALNUMBER_OLD', $active_deal_id);
			$old_deal = $this->get_deal_with_services($active_deal_id);
			$users2_deals->set_old_deal($old_deal);
			$this->_deals_table->set_old_offers_ids($users2_deals->get_old_offers_ids());

			$new_deal_id = 'X-test-X';
			$users2_deals->set_p_dealnumber_new($new_deal_id);
			$ret = $users2_deals->create_rows_try();
			if ($ret == -1) {
				
			}
			echo '</div>';
		}
		else {// aneks
			$old_deal = $this->get_deal_with_services($active_deal_id);
			$users2_deals->set_old_deal($old_deal);

			$this->_deals_table->set('P_DEALNUMBER_OLD', $active_deal_id);
			$this->_deals_table->set_old_offers_ids($users2_deals->get_old_offers_ids());

			$new_deal_id = $this->_deals_table->create();
			if ($new_deal_id <= 0) {
				echo '<p style="color:red">' . "Error: wystąpił błąd podczas dodawania rekordu DEALS_TABLE" . '</p>';
			} else {
				// OK save USERS2_DEALS
				echo '<p style="color:green">' . "Utworzono umowę - rekord w tabeli DEALS_TABLE (ID=" . $new_deal_id . ")" . '</p>';

				$new_deal_row = PokazOfertyHelper::get_deal($new_deal_id);
				if ($new_deal_row) {
					$cols = array('ID', 'ID_BILLING_USERS', 'P_DEALNUMBER', 'P_DEALNUMBER_OLD', 'P_DEALDATE', 'P_DEALDATE_TERM', 'S_ADDRESS_STREET');
					PokazOfertyView::print_simple_tbl($new_deal_row, $cols, "Nowa umowa");
				}

				// create records in USERS2_DEALS
				$users2_deals->set_p_dealnumber_new($new_deal_id);

				if (!$users2_deals->create_rows()) {
					echo '<p style="color:red">' . "Error: wystąpił błąd podczas dodawania rekordów do USERS2_DEALS" . '</p>';
					$this->_show_deal_form = true;
				} else {
					echo '<p style="color:green">' . "Utworzono rekordy w tabeli USERS2_DEALS dla nowej umowy (ID=" . $new_deal_id . ")" . '</p>';
					$this->_show_deal_form = false;
				}

				echo '<a href="' . "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=895#EDIT/{$new_deal_id}" . '">' . "Przejdź do edycji umowy (DEALS_TABLE)" . '</a>';
			}
		}
	}

}

class PokazOfertyHelper {

	/**
	 * @param string $S_ADDRESS_STREET - tylko umowy na danym adresie
	 * @return array or null
	 *   [ID_BILLING_USERS => array of object deal]
	 */
	public static function get_deals_active_by_street($S_ADDRESS_STREET) {
		return self::get_deals_active(array('S_ADDRESS_STREET'=>$S_ADDRESS_STREET));
	}

	/**
	 * @param string $S_ADDRESS_STREET - tylko umowy na danym adresie
	 * @param int $ID_BILLING_USERS - tylko umowy danego klienta
	 * @return array or null
	 *   [ID_DEALS => deal]
	 */
	public static function get_deals_active_with_info($S_ADDRESS_STREET, $ID_BILLING_USERS, $only_active = true) {
		$active_deals_by_id = self::get_deals_active(array('S_ADDRESS_STREET'=>$S_ADDRESS_STREET, 'ID_BILLING_USERS'=>$ID_BILLING_USERS, 'return_by'=>'ID', 'P_DEALNUMBER'=>true));
		self::deals_active_add_info($active_deals_by_id, $ID_BILLING_USERS, $only_active);
		return $active_deals_by_id;
	}

	public static function get_deals_active_by_user($ID_BILLING_USERS, $only_active = true) {
		$active_deals_by_id = self::get_deals_active(array('ID_BILLING_USERS'=>$ID_BILLING_USERS, 'return_by'=>'ID', 'P_DEALNUMBER'=>true));
		self::deals_active_add_info($active_deals_by_id, $ID_BILLING_USERS, $only_active);
		return $active_deals_by_id;
	}

	public static function deals_active_add_info(&$active_deals_by_id, $ID_BILLING_USERS, $only_active = false) {
		if (empty($active_deals_by_id)) {
			return;
		}
		$uslugi = self::get_services_by_user_deals($ID_BILLING_USERS, array_keys($active_deals_by_id), $only_active);
		foreach ($active_deals_by_id as $k_deal_id => $v_deal) {
			if (array_key_exists($k_deal_id, $uslugi)) {
				$active_deals_by_id[$k_deal_id]->services = $uslugi[$k_deal_id];
				$active_deals_by_id[$k_deal_id]->services_by_id = array();
				foreach ($uslugi[$k_deal_id] as $k_p_service => $v_srv_arr) {
					foreach ($v_srv_arr as $k_srv_id => $v_srv) {
						$active_deals_by_id[$k_deal_id]->services_by_id[$k_srv_id] = $v_srv;
					}
				}
			}
		}

		// add $v_deal->ses_x_a
		$out_id_count = array();
		$uslugi_params = self::get_services_params($uslugi);
		foreach ($active_deals_by_id as $k_deal_id => $v_deal) {
			$active_deals_by_id[$k_deal_id]->ses_x_a = array();
			foreach ($v_deal->services as $k_p_service => $v_srv_arr) {
				foreach ($v_srv_arr as $k_srv_id => $v_srv) {
					$v_deal->services[$k_p_service][$k_srv_id]->offer_p_service = $k_p_service;

					// add SERVICE params if exists
					if (array_key_exists($k_srv_id, $uslugi_params)) {
						$active_deals_by_id[$k_deal_id]->ses_x_a[$k_srv_id] = $uslugi_params[$k_srv_id];
						if ($v_srv->NAME_LIST_SERVICES == 'TV' && $uslugi_params[$k_srv_id]->P_SERVICE_CLASS != '') {
							$v_deal->services[$k_p_service][$k_srv_id]->offer_p_service = $uslugi_params[$k_srv_id]->P_SERVICE_CLASS;
						}
					}

					// add out_id - @used in JavaScript overview
					if (!in_array($v_srv->offer_p_service, $out_id_count)) {
						$out_id_count[$v_srv->offer_p_service] = 1;
					} else {
						$out_id_count[$v_srv->offer_p_service] += 1;
					}
					$v_deal->services[$k_p_service][$k_srv_id]->out_id = $v_srv->offer_p_service . '_' . $out_id_count[$v_srv->offer_p_service];
				}
			}
		}
	}

	/**
	 * @param array $params
	 *   $params['S_ADDRESS_STREET'] - tylko umowy na danym adresie
	 *   $params['ID_BILLING_USERS'] - tylko umowy danego klienta
	 *   $params['P_DEALNUMBER'] - pobierz numer umowy
	 *   $params['return_by'] - return by
	 *     'ID' - @return [ID_DEALS => deal]
	 * @return array or null
	 *   [ID_BILLING_USERS => array of object deal]
	 */
	public static function get_deals_active($params = array()) {

		$forceUpdate = false;
		Lib::loadClass('ColumnDealsStatus');
		ColumnDealsStatus::run_update($forceUpdate, $dbg_msgs);

		$active_deals = array();
		$return_by = V::get('return_by', '', $params);
		$sql_left_join = "";
		$sql_select_arr = array();
		$sql_select_arr []= "ds.`ID_DEALS`";
		$sql_select_arr []= "ds.`ID_BILLING_USERS`";
		$sql_select_arr []= "ds.`SERVICES_S_ADDRESS_STREET`";
		$sql_select_arr []= "concat(bua.`P_NAME`, ' ', bua.`P_NAME_SECOND`) as P_NAME";
		if ('' != V::get('ID_BILLING_USERS', '', $params)) {
			$sql_left_join .= "\n left join `DEALS_TABLE` as d on (d.`ID`=ds.`ID_DEALS`)";
			$sql_select_arr []= "d.`P_DEALNUMBER`";
			$sql_select_arr []= "d.`P_DEALDATE`";
			$sql_select_arr []= "d.`P_DEALDATE_TERM`";
			$sql_select_arr []= "d.`ID_OFFERS_GROUP`";
			$sql_select_arr []= "d.`ID_OFFERS_ON`";
			$sql_select_arr []= "d.`ID_OFFERS_OFF`";
			$sql_select_arr []= "d.`S_ADDRESS_STREET`";
		}
		$sql_where_arr = array();
		$sql_where_arr []= "ds.`DEALS_ACTIVE`=1";
		if ('' != ($user_id = V::get('ID_BILLING_USERS', '', $params))) {
			$sql_where_arr []= "ds.`ID_BILLING_USERS`='" . $user_id . "'";
		}
		if ('' != ($street = V::get('S_ADDRESS_STREET', '', $params))) {
			$sql_where_arr []= "(ds.`SERVICES_S_ADDRESS_STREET`='{$street}' or concat(',', ds.`SERVICES_S_ADDRESS_STREET`, ',') like '%,{$street},%')";
		}
		$sql = "select " . implode("\n, ", $sql_select_arr) . "
			from `temp_DEALS_STATUS` as ds
				left join `BILLING_USERS_ADD` as bua on (bua.`id_users`=ds.`ID_BILLING_USERS`)
				" . $sql_left_join . "
			where " . implode("\n and ", $sql_where_arr) . "
			order by ds.`ID_DEALS` DESC
		";
		if(V::get('DBG_SQL', 0, $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
		DEBUG_S(6, "dbg sql:", $sql, __FILE__, __FUNCTION__, __LINE__);
		$res = DB::query($sql);
		while ($r = DB::fetch($res)) {
			if ($return_by == 'ID') {
				$active_deals [$r->ID_DEALS]= $r;
			} else {
				$active_deals [$r->ID_BILLING_USERS] []= $r;
			}
		}
		DEBUG_S(6, "dbg active_deals:", $active_deals, __FILE__, __FUNCTION__, __LINE__);
		return $active_deals;
	}

	public static function get_l2_list_status_name($status) {
		static $l2_list_status;
		if (!is_array($l2_list_status)) {
			$l2_list_status = array();
			$db = DB::getDB();
			$sql = "select lst.`ses_users2`, lst.`name`, lst.`description`
				from `LIST_status` as lst
				where lst.`ID`>2
			";
			$res = $db->query($sql);
			while ($r = $db->fetch($res)) {
				$l2_list_status[$r->ses_users2] = $r->name;
			}
		}
		if (array_key_exists($status, $l2_list_status)) {
			return $l2_list_status[$status];
		}
		return null;
	}

	public static function get_services_by_user_deals($user_id, $deals_ids = array(), $only_active = false) {
		$deals = array();
		if (empty($deals_ids)) {
			return $deals;
		}
		$db = DB::getDB();
		$sql = "select
				s.`ID`, s.`NAME_LIST_SERVICES`, s.`A_STATUS`
				, s.`ID_OFFERS`
				, s.`ID_DEALS_TABLE`
				, s.`P_ID_SERVICES`
				, s.`ABONAMENT_VALUE` as ABONAMENT_VALUE
				, s.`P_ID_SERVICES` as P_ID
				, s.`HANGUP_STATUS`
				, s.`HANGUP_FROM`
				, s.`HANGUP_TILL`
				, s.`VAT`
				, ls.`description` as description
		--		, lst.`name` as A_STATUS_DESC
				, '' as A_STATUS_DESC
			from `SERVICES` as s
				left join `LIST_SERVICES` as ls on(ls.`name`=s.`NAME_LIST_SERVICES`)
		--		left join `LIST_status` as lst on(lst.`ses_users2`=s.`A_STATUS`)
		--		left join `LIST_status` as lst on(lst.`ses_users2`=s.`HANGUP_STATUS` and lst.`ID`>2)
			where `ID_BILLING_USERS`='" . $user_id . "'
				and `ID_DEALS_TABLE` in(" . implode(",", $deals_ids) . ")
		--		and s.`A_STATUS`='NORMAL'
		";
		if(V::get('DBG_SQL', 0, $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {

			// TODO: only active services - @from $A_STATUS_L2_SQL
			// $r->HANGUP_STATUS = ('NORMAL', 'OFF_SOFT', 'OFF_HARD')
			$r->HANGUP_TILL = (!$r->HANGUP_TILL || $r->HANGUP_TILL == '0000-00-00')? null : $r->HANGUP_TILL;
			$r->HANGUP_FROM = (!$r->HANGUP_FROM || $r->HANGUP_FROM == '0000-00-00')? null : $r->HANGUP_FROM;
			$r->_status = null;
			$today = date("Y-m-d");
			if ($r->HANGUP_STATUS == $r->A_STATUS) {
				$r->_status = $r->A_STATUS;
			} else if (!$r->HANGUP_TILL && $r->HANGUP_FROM > '' && $today > $r->HANGUP_FROM) {
				$r->_status = $r->HANGUP_STATUS;
			} else if (!$r->HANGUP_TILL && $r->HANGUP_FROM > '' && $today < $r->HANGUP_FROM) {
				$r->_status = $r->A_STATUS;
			} else if ($r->HANGUP_TILL > '' && $r->HANGUP_FROM > '' && $today > $r->HANGUP_FROM && $today < $r->HANGUP_TILL) {
				$r->_status = $r->HANGUP_STATUS;
			} else if ($r->HANGUP_TILL > '' && $r->HANGUP_FROM > '' && $today < $r->HANGUP_FROM && $today < $r->HANGUP_TILL) {
				$r->_status = $r->A_STATUS;
			} else if (!$r->HANGUP_TILL && !$r->HANGUP_FROM) {
				$r->_status = $r->A_STATUS;
			} else if ($r->HANGUP_TILL > '' && $r->HANGUP_FROM > '' && $today > $r->HANGUP_FROM && $today > $r->HANGUP_TILL) {
				$r->_status = $r->A_STATUS;
			} else if ($r->HANGUP_TILL > '' && $r->HANGUP_FROM > '' && $today > $r->HANGUP_FROM && $today > $r->HANGUP_TILL && $r->HANGUP_FROM < $r->HANGUP_TILL) {
				$r->_status = 'ERROR1';
			} else {
				$r->_status = 'ERROR2';
			}

			$r->A_STATUS_DESC = self::get_l2_list_status_name($r->_status);

			if ($only_active && !in_array($r->_status, array('NORMAL'))) {
				continue;
			}

			// TODO: P_SERVICE used?
			$r->P_SERVICE = $r->NAME_LIST_SERVICES;
			if ($r->P_SERVICE == 'USERS2') $r->P_SERVICE = 'NET';
			else if ($r->P_SERVICE == 'VOIP') $r->P_SERVICE = 'TEL';

			$deals[$r->ID_DEALS_TABLE][$r->P_SERVICE][$r->ID] = $r;
		}
		return $deals;
	}

	public static function get_services_params($uslugi) {
		$ses_x_a = array();
		if (empty($uslugi)) return $ses_x_a;

		$allowed_name_list_srv = array('USERS2', 'TV', 'VOIP');

		$load_ses_x_a_ids = array();
		foreach ($uslugi as $k_deal_id => $v_deal_arr) {
			foreach ($v_deal_arr as $k_p_service => $v_srv_arr) {
				if (empty($v_srv_arr)) continue;
				foreach ($v_srv_arr as $k_srv_id => $v_srv) {
					$load_ses_x_a_ids [$v_srv->NAME_LIST_SERVICES] []= $v_srv->ID;
				}
			}
		}
		// load from DB
		$db = DB::getDB();
		foreach ($load_ses_x_a_ids as $k_name_list_srv => $v_srv_ids) {
			if (!in_array($k_name_list_srv, $allowed_name_list_srv)) continue;
			$sql = "select * from `SES_" . $k_name_list_srv . "_A` where `ID_SERVICES` in (" . implode(", ", $v_srv_ids) . ")";
			$res = $db->query($sql);
			while ($r = $db->fetch($res)) {
				$ses_x_a [$r->ID_SERVICES] = $r;
			}
		}
		return $ses_x_a;
	}

	public static function get_users_by_query($q) {
		$users_rows = array();
		$db = DB::getDB();
		$sql_order_by = 'order by a.`P_NAME` asc';
		$sql_limit = 'limit 500';
		$sql_where = '1=1';
		$sql_where_and_arr = array();
		if (!empty($q)) {
			$q = trim($q);
			if (is_numeric($q)) {// billing number
				$sql_where_and_arr []= "a.`id_users`='".$db->_($q)."'";
			}
			else {// string - name, second name
				$q_arr_values = array();
				$q_exp = explode(' ', $q);
				foreach ($q_exp as $v_q) {
					$v_q = trim($v_q);
					if (strlen($v_q) > 2) {// min. 3 znaki
						$q_arr_values []= strtolower($v_q);
					}
				}

				foreach ($q_arr_values as $q_value) {
					$sql_filter_q = array();
					$q_arr = array();// uniq array
					$q_arr_pl = array();// loop array

					$pl_letters = array('ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ź', 'ż');
					$en_letters = array('a', 'c', 'e', 'l', 'n', 'o', 's', 'z', 'z');

					$sql_filter_q []= "a.`P_NAME` like '".$db->_($q_value)."%'";
					$sql_filter_q []= "a.`P_NAME_SECOND` like '".$db->_($q_value)."%'";

					$q_value_clean_en = str_replace($pl_letters, $en_letters, $q_value);
					$q_value_clean_pl = str_replace($en_letters, $pl_letters, $q_value_clean_en);
					$q_value_clean_pr = str_replace($en_letters, '_', $q_value_clean_en);
					if ($q_value_clean_en != $q_value) $q_arr[ $q_value_clean_en ] = true;
					if ($q_value_clean_pl != $q_value) $q_arr[ $q_value_clean_pl ] = true;
					if ($q_value_clean_pr != $q_value) $q_arr[ $q_value_clean_pr ] = true;

					foreach ($q_arr as $v_q => $v_val) {
						$sql_filter_q []= "a.`P_NAME` like '".$db->_($v_q)."'";
						$sql_filter_q []= "a.`P_NAME_SECOND` like '".$db->_($v_q)."'";
						// $sql_filter_q []= "a.`P_ADDRESS_STREET` like '".DB::_($q)."'";
					}

					$sql_field_1 = "a.`P_NAME`";
					$sql_field_2 = "a.`P_NAME_SECOND`";
					foreach ($pl_letters as $k_ind => $v_char_pl) {
						$sql_field_1 = "REPLACE(" . $sql_field_1 . ", '" . $v_char_pl . "', '" . $en_letters[$k_ind] . "')";
						$sql_field_2 = "REPLACE(" . $sql_field_2 . ", '" . $v_char_pl . "', '" . $en_letters[$k_ind] . "')";
					}//end foreach
					$sql_filter_q []= $sql_field_1 . " like '%" . $db->_($q_value_clean_en) . "%'";
					$sql_filter_q []= $sql_field_2 . " like '%" . $db->_($q_value_clean_en) . "%'";

					$sql_where_and_arr []= "(" . implode(" or ", $sql_filter_q) . ")";
				}
			}
		}
		$sql_where = (empty($sql_where_and_arr))? "1=1" : implode(" and ", $sql_where_and_arr);

		$sql = "select a.`id_users` as ID
				, a.`id_users`
				, a.`P_NAME`
				, a.`P_NAME_SECOND`
				, a.`P_ADDRESS_STREET`
				, a.`P_ADDRESS_HOME`
				, a.`P_ADDRESS_HOUSE`
				, a.`P_ADDRESS_CITY`
				, a.`P_ADDRESS_POST_CODE`
				, a.`P_ADDRESS_REGION`
				, a.`P_NIP`
				, a.`P_PESEL`
				, a.`P_PHONE`
				, a.`P_OTHER_DOC`
				, a.`user_mail_contact`
				, a.`is_firma`
			from `BILLING_USERS_ADD` as a
			where ".$sql_where."
			".$sql_order_by."
			".$sql_limit."
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$users_rows[$r->id_users] = $r;
		}
		return $users_rows;
	}

	public static function get_user_info($user_id) {
		$user = null;
		$user_id = (int)$user_id;
		if ($user_id <= 0) {
			return $user_id;
		}
		$db = DB::getDB();
		$sql = "select bua.`id_users`
				, bua.`id_users` as ID_BILLING_USERS
				, bua.`is_firma`
				, bua.`P_NAME`
				, bua.`P_NAME_SECOND`
				, bua.`P_NIP`
				, bua.`P_PESEL`
				, bua.`P_PHONE`
				, bua.`P_ADDRESS_REGION`
				, bua.`P_ADDRESS_CITY`
				, bua.`P_ADDRESS_POST_CODE`
				, bua.`P_ADDRESS_STREET`
				, bua.`P_ADDRESS_HOME`
				, bua.`P_ADDRESS_HOUSE`
				, bua.`user_mail_contact`
				, bu.`BILLING_OWNER`
			from `BILLING_USERS_ADD` as bua
				left join `BILLING_USERS` as bu on(bu.`ID`=bua.`id_users`)
			where bua.`id_users`='{$user_id}'
		";
		$res = $db->query($sql);
		if ($r = $db->fetch($res)) {
			$user = $r;
		}
		return $user;
	}

	public static function get_users2_deals_empty_object() {
		return new Column_users2_deals();
	}

	public static function get_deals_table_empty_object() {
		return new Column_deals_table();
	}

	public static function get_buildings_cols() {
		$buildings_sql_cols = array();
		$buildings_sql_cols ['ID']= "ID";
		$buildings_sql_cols ['S_ADDRESS_STREET']= "S ADDRESS STREET";
		$buildings_sql_cols ['P_ADDRESS_STREET']= "P ADDRESS STREET";
		$buildings_sql_cols ['A_STATUS']= "A STATUS";
		$buildings_sql_cols ['T_INSTALACJA_W_CIAGU_DNI']= '<span title="'."informacje o terminach instalacji moze byc data lub daty na kazdy z rodzai uslug. Moga byc inforamcje na indywidualne klatki".'">'."T INSTALACJA W CIAGU DNI".'</span>';
		$buildings_sql_cols ['T_BUILDING_TYPE']= "T BUILDING TYPE";
		$buildings_sql_cols ['M_REWIR']= "M REWIR";
		$buildings_sql_cols ['M_PARAMETRY']= "M PARAMETRY";
		$buildings_sql_cols ['M_DIRECT_MARKETING_DATE']= "M DIRECT MARKETING DATE";
		$buildings_sql_cols ['M_DATA_ZASIEDLENIA']= "M DATA ZASIEDLENIA";
		return $buildings_sql_cols;
	}

	public static function get_marketing_cols() {
		$marketing_sql_cols = array();
		$marketing_sql_cols ['ID']= "ID";
		$marketing_sql_cols ['S_ADDRESS_STREET']= "S ADDRESS STREET";
		$marketing_sql_cols ['A_RECORD_UPDATE_DATE']= "A RECORD UPDATE DATE";
		$marketing_sql_cols ['A_RECORD_UPDATE_AUTHOR']= "A RECORD UPDATE AUTHOR";
		$marketing_sql_cols ['L_APPOITMENT_DATE']= "L APPOITMENT DATE";
		$marketing_sql_cols ['L_APPOITMENT_USER']= "L APPOITMENT USER";
		$marketing_sql_cols ['L_APPOITMENT_INFO']= "L APPOITMENT INFO";
		return $marketing_sql_cols;
	}

	public static function get_buildings_by_mieszk($street) {
		$buildings = array();
		if (empty($street)) {
			//return self::get_buildings($street);
			return $buildings;
		}
		$db = DB::getDB();
		$sql_cols_alias = array();
		$buildings_sql_cols = self::get_buildings_cols();
		foreach ($buildings_sql_cols as $k => $v) {
			$sql_cols_alias []= 'b.' . $k;
		}

		$marketing_sql_cols = self::get_marketing_cols();
		foreach ($marketing_sql_cols as $k => $v) {
			$sql_cols_alias []= 'm.' . $k . ' as m__' . $k;
		}
		$sql_cols_alias []= 'm.`T_TELBOX_BUILDING_IN` as m__T_TELBOX_BUILDING_IN';

		$sql_where_and = array();
		$sql_where_and []= "1=1";
		$sql_where_and []= "m.`A_STATUS` in('WAITING','NORMAL','MONITOR','WARNING','OFF_SOFT','OFF_HARD')";
		$sql_where_and []= "m.`S_ADDRESS_STREET`='" . $db->_($street) . "'";
		$sql_where = implode(" and ", $sql_where_and);
		$sql = "select " . implode(", ", $sql_cols_alias) . "
			from `USERS2_MARKETING` as m
				left join `BUILDINGS` as b on(b.`S_ADDRESS_STREET`=m.`T_TELBOX_BUILDING_IN`)
			where " . $sql_where . "
			group by b.`ID`
			order by b.`S_ADDRESS_STREET`
		";
		DEBUG_S(6, "dbg sql:", $sql, __FILE__, __FUNCTION__, __LINE__);
		$res = $db->query( $sql );
		while ($r = $db->fetch( $res )) {
			$buildings [$r->ID]= $r;
		}
		return $buildings;
	}

	public static function get_buildings($street) {
		$buildings = array();
		$db = DB::getDB();
		$buildings_sql_cols = self::get_buildings_cols();

		$sql_where_and = array();
		$sql_where_and []= "1=1";
		if (!empty($street)) {
			$sql_where_and []= "
				(
					`S_ADDRESS_STREET` like '" . $db->_($street) . "'
					or `P_ADDRESS_STREET` like '" . $db->_($street) . "'
				)
			";
		}
		$sql_where = implode(" and ", $sql_where_and);
		$sql = "select ".implode(", ", array_keys($buildings_sql_cols))."
			from `BUILDINGS`
			where
				" . $sql_where . "
			order by `S_ADDRESS_STREET`
		";
		DEBUG_S(6, "dbg sql:", $sql, __FILE__, __FUNCTION__, __LINE__);
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$buildings [$r->ID]= $r;
		}
		return $buildings;
	}

	public static function get_deal($id_deal) {
		$deal = null;
		if ($id_deal <= 0) {
			return $deal;
		}
		$sql = "select d.`ID`
				, d.`ID_BILLING_USERS`
				, d.`P_DEALPREFIX`
				, d.`P_DEALNUMBER`
				, d.`P_DEALNUMBER_OLD`
				, d.`P_DEALDATE`
				, d.`P_DEALDATE_TERM`
				, d.`ANEX_NEEDED`
				, d.`ANEX_CONFIRM_DATE`
				, d.`DEALDESC`
				, d.`A_STATUS`
				, d.`ID_OFFERS_GROUP`
				, d.`S_ADDRESS_STREET`
				, d.`ID_OFFERS_ON`
				, d.`ID_OFFERS_OFF`
				, d.`P_ID`
				, d.`L2_HANGUP_FROM`
			from `DEALS_TABLE` as d
			where d.`ID`='" . $id_deal . "'
		";
		$res = DB::query($sql);
		if ($r = DB::fetch($res)) {
			$deal = $r;
		}
		return $deal;
	}

	public static function get_group($id_group) {
		$group = null;
		if ($id_group <= 0) {
			return $group;
		}
		$sql = "select
				t0.`ID` ,
				t0.`S_ALIAS` ,
				t0.`P_SERVICE_COMPANY` ,
				t0.`P_PROMOTION_NAME` ,
				t0.`P_DEALTERM_MONTHS` ,
				t0.`P_OFFER_TERM_BEGIN` ,
				t0.`P_OFFER_TERM` ,
				t0.`M_REWIR` ,
				t0.`ID_NET` ,
				t0.`ID_TV` ,
				t0.`ID_TVC` ,
				t0.`ID_TVCP_1` ,
				t0.`ID_TVCP_2` ,
				t0.`ID_TVCP_3` ,
				t0.`ID_TVCP_4` ,
				t0.`ID_TEL`,
				t0.`RABAT_IF_OPCJA_TVC`,
				t0.`RABAT_IF_OPCJA_TEL`
			from `USERS2_OFFERS_GROUPS` as t0
			where t0.`ID`='" . $id_group . "'
			group by t0.ID
			order by t0.ID desc
		";
		$res = DB::query($sql);
		if ($r = DB::fetch($res)) {
			$group = new Column_users2_offers_groups();
			$group->set_from_raw_data($r);
		}
		return $group;
	}

	public static function get_offers_by_id($offers_ids, $params = array()) {
		$offers = array();
		$db = DB::getDB();
		$sql_select = array();
		if (($dealterm = V::get('P_DEALTERM_MONTHS', 0, $params, 'int')) > 0) {
			$sql_select []= "ROUND(( ((" . $dealterm . " - o.P_DEAL_PROMO_MONTHS)*o.P_CONTRACT_PRICE) + (o.P_DEAL_PROMO_MONTHS*o.P_PROMO_MONTH_PRICE) + (o.P_INSTALL_QUOTE))/" . $dealterm . ", 2) as srednia";
			$sql_select []= "ROUND(( ((" . $dealterm . " - o.P_DEAL_PROMO_MONTHS)*o.P_CONTRACT_PRICE_NETTO) + (o.P_DEAL_PROMO_MONTHS*o.P_PROMO_MONTH_PRICE_NETTO) + (o.P_INSTALL_QUOTE/1.23))/" . $dealterm . ", 2) as srednia_netto";
			$sql_select []= "o.P_NORMAL_PRICE*" . $dealterm . " - o.P_DEAL_PROMO_MONTHS*o.P_PROMO_MONTH_PRICE - (" . $dealterm . " - o.P_DEAL_PROMO_MONTHS)*o.P_CONTRACT_PRICE + (o.P_INSTALL_QUOTE_NORMAL - o.P_INSTALL_QUOTE) as `upust`";
		}
		//$sql_select []= "'' as out_id";
		$sql_select []= "o.`ID`";
		$sql_select []= "o.`S_ALIAS`, o.`P_SERVICE_NAME`, o.`P_PROMOTION_NAME`, o.`P_S_PARAM1`";
		$sql_select []= "o.`P_INSTALL_QUOTE`, o.`P_INSTALL_QUOTE_NORMAL`, round(o.`P_INSTALL_QUOTE`/1.23, 2) as P_INSTALL_QUOTE_NETTO";
		$sql_select []= "o.`P_CONTRACT_PRICE`, o.`P_CONTRACT_PRICE_NETTO`";
		$sql_select []= "o.`P_PROMO_MONTH_PRICE`, o.`P_PROMO_MONTH_PRICE_NETTO`";
		$sql_select []= "o.`P_NORMAL_PRICE`, o.`P_NORMAL_PRICE_NETTO`";
		$sql_select []= "o.`P_DEAL_PROMO_MONTHS`";
		$sql_select []= "o.`P_SERVICE`, o.`P_SERVICE_PARENT`";

		$sql_select []= "o.`A_STATUS`";
		$sql_select []= "o.`P_SERVICE_COMPANY`";
		// 		$sql_select []= "o.`S_OTHER_INFO`";
		// 		$sql_select []= "o.`USERS2_OFFERS_GROUPS_ID`";
		$sql_select []= "o.`P_S_PARAM2`";
		// 		$sql_select []= "o.`P_S_LIMIT`";
		// 		$sql_select []= "o.`P_S_LAN`";
		$sql_select []= "o.`P_DEALTERM_MONTHS`";
		$sql_select []= "o.`STAWKA_VAT`";
		// 		$sql_select []= "o.`P_S_MAILBOX_SIZE`";
		// 		$sql_select []= "o.`P_S_WWW_SIZE`";
		// 		$sql_select []= "o.`P_OFFER_TERM_BEGIN`";
		// 		$sql_select []= "o.`P_OFFER_TERM`";
		//			$sql_select []= "o.`S_DEKODER_SD_OPTION`";
		//			$sql_select []= "o.`S_MODUL_PCMCIA_OPTION`";
		//			$sql_select []= "o.`S_DEKODER_HD_OPTION`";
		// 		$sql_select []= "o.`ID_PRODUKT`";
		$sql_select []= "o.`LAN_DOWNLOAD`";
		$sql_select []= "o.`S_PUBLIC_IP`";
		$sql_select []= "o.`S_SOHO_WIFI_ROUTER_1292`";
		$sql_select []= "o.`S_E_PORT_1293`";
		$sql_select []= "o.`P_DEVICE`";
		$sql_select []= "o.`P_SERVICE_CLASS`";
		$sql_select []= "o.`P_SERVICE_SOCKETS_AMMOUNT_1298`";
		$sql_select []= "o.`ID_DOMAINS`";
		$sql_select []= "o.`ID_DOMAINS_PACKET_ID`";
		$sql_select []= "o.`VOIP_FAX2EMAIL`";
		$sql_select []= "o.`CONN_DIV`";
		$sql_select []= "o.`P_SERVICE_QUOTA`";
		$sql_select []= "o.`P_SERVICE_QUOTA_PROFILE`";
		$sql_select []= "o.`P_SERVICE_UPLOAD_RATIO`";
		$sql_select []= "o.`S_TECHNOLOGY`";
		$sql_select []= "o.`P_MULTIROOM_ADD_CARDS`";
		$sql_select []= "o.`P_MULTIROOM_ADD_DEKODER_SD`";
		$sql_select []= "o.`P_MULTIROOM_ADD_DEKODER_HD`";
		$sql_select []= "o.`P_MULTIROOM_ADD_MODUL_CAM`";

		$sql = "select " . implode(", ", $sql_select) . "
			from `USERS2_OFFERS` as o
			where o.`ID` in(" . implode(', ', $offers_ids) . ")
		";
		$res = $db->query($sql);
		if ($db->has_errors()) {
			echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">DB Errors (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($db->get_errors());echo'</pre>';
			echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
		}
		while ($r = $db->fetch($res)) {
			if ($r->P_SERVICE == 'OPCJA_TVC') $r->P_SERVICE = 'TVC';
			else if ($r->P_SERVICE == 'OPCJA_TEL') $r->P_SERVICE = 'TEL';
			$offers[$r->ID] = $r;
		}
		return $offers;
	}

	public static function get_users2_deals_by_deal_id($deal_id, $params = array()) {
		$users2_deals = array();
		$db = DB::getDB();
		$sql_status = "";
		$status = V::get('A_STATUS', '', $params);
		if (!empty($status)) {
			$allowed_status = array('WAITING', 'NORMAL');
			if (!is_array($status)) {
				$status = array($status);
			}
			$sql_status_arr = array();
			foreach ($status as $v_status) {
				if (in_array($v_status, $allowed_status)) {
					$sql_status_arr []= "'{$v_status}'";
				}
			}
			if (!empty($sql_status_arr)) {
				$sql_status = "and d.`A_STATUS` in (" . implode(',', $sql_status_arr) . ")";
			}
		}
		$sql = "select d.*
			from `USERS2_DEALS` as d
			where d.`P_DEALNUMBER_NEW`='{$deal_id}'
				{$sql_status}
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$users2_deals []= $r;
		}
		return $users2_deals;
	}

	/**
	 * @param array $offer_ids
	 * @returns array $oferty_costs
	 */
	public static function get_offers_costs_by_offer_ids($offer_ids = array()) {
		$oferty_costs = array();
		$db = DB::getDB();
		$sql_where = "";
		if (!empty($offer_ids)) {
			$sql_where = "where o.`ID` in (" . implode(",", $offer_ids) . ")";
		}
		$sql = "select
				o.`ID` as ID_OFERTY
				, c.`P_OFFER_COSTS`
			from `USERS2_OFFERS` as o
				join `USERS2_OFFERS_COSTS_GROUPS` as c on (c.`ID`=o.`ID_COSTS_GROUPS`)
			{$sql_where}
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$oferty_costs[$r->ID_OFERTY] = (double)$r->P_OFFER_COSTS;
		}
		return $oferty_costs;
	}

	/**
	 * @param array $offer_ids
	 * @returns array $oferty_costs_start
	 */
	public static function get_offers_costs_start_by_offer_ids($offer_ids = array()) {
		$oferty_costs_start = array();
		$db = DB::getDB();
		$sql_where = "";
		if (!empty($offer_ids)) {
			$sql_where = "where o.`ID` in (" . implode(",", $offer_ids) . ")";
		}
		$sql = "select
				o.`ID` as ID_OFERTY
				, c.`P_OFFER_COSTS_START`
			from `USERS2_OFFERS` as o
				join `USERS2_OFFERS_COSTS_GROUPS` as c on (c.`ID`=o.`ID_COSTS_GROUPS`)
			{$sql_where}
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$oferty_costs_start[$r->ID_OFERTY] = $r->P_OFFER_COSTS_START;
		}
		return $oferty_costs_start;
	}

	public static function get_oferty_opcje_visible_cols() {
		$cols = array();
		$cols ['ID'] = 'ID oferty';
		//$cols ['ID_PROCES' ] = '';
		$cols ['S_OTHER_INFO' ] = '<b title="' . "Uwagi" . '">&nbsp;!&nbsp;</b>';
		$cols ['P_SERVICE_NAME' ] = 'Nazwa oferty';
		$cols ['P_INSTALL_QUOTE' ] = 'Promocyjna cena instalacji (brutto)';
		$cols ['P_PROMO_MONTH_PRICE' ] = 'Wartość abonamentu w promocyjnych miesiącach (brutto)';
		$cols ['P_CONTRACT_PRICE' ] = 'Wartość abonamentu po promocji (brutto)';
		$cols ['P_DEAL_PROMO_MONTHS' ] = 'Ilość promocyjnych miesięcy';
		//$cols ['P_DEALTERM_MONTHS' ] = '';
		$cols ['P_NORMAL_PRICE' ] = 'Nominalna wartość abonamentu (brutto)';
		$cols ['srednia'] = 'Średnia (brutto)';
		$cols ['upust'] = 'Upust od ceny normalnej do wyliczeń kary (brutto)';
		$cols ['koszt'] = 'Koszt (netto)';
		return $cols;
	}

	public static function get_oferty_opcje() {
		$oferty_opcje = array();// [ service ] => array(ID => {oferta})
		$oferty_costs = self::get_offers_costs_by_offer_ids();
		// TODO: use [P_OFFER_TERM_BEGIN] => 0000-00-00, [P_OFFER_TERM] => 2011-12-31, [M_REWIR] => gd
		$sql = "select
				o.`ID`
				, o.`P_SERVICE`
				, o.`P_SERVICE_PARENT`
				, o.`P_SERVICE_NAME`
				, o.`P_INSTALL_QUOTE`
				, o.`P_INSTALL_QUOTE_NORMAL`
				, o.`P_CONTRACT_PRICE`
				, o.`P_PROMO_MONTH_PRICE`
				, o.`P_NORMAL_PRICE`
				, o.`P_DEAL_PROMO_MONTHS`
				, o.`P_DEALTERM_MONTHS`
				, o.`ID_PRODUKT` as `ID_PRODUKT`
				, '' as `upust`
				, '' as `koszt`
				, IF(o.`ID_PROCES`>0, o.`ID_PROCES`, '') as `ID_PROCES`
				, o.`S_OTHER_INFO`
				, o.`S_TECHNOLOGY`
				, o.`P_MULTIROOM_ADD_CARDS`
				, o.`P_MULTIROOM_ADD_DEKODER_SD`
				, o.`P_MULTIROOM_ADD_DEKODER_HD`
				, o.`P_MULTIROOM_ADD_MODUL_CAM`
			from `USERS2_OFFERS` as o
			where o.`P_SERVICE`='OPCJE' 
				and o.`A_STATUS`='NORMAL'
				and o.`P_SERVICE_COMPANY`='BN'
			order by o.`ID_PRODUKT` desc, o.`P_CONTRACT_PRICE` desc
		";
		$res = DB::query($sql);
		while ($r = DB::fetch($res)) {
			$r->srednia = '';
			if (array_key_exists($r->ID, $oferty_costs)) {
				$r->koszt = $oferty_costs[ $r->ID ];
			}
			$oferty_opcje[ $r->P_SERVICE_PARENT ][ $r->ID ] = $r;
		}
		return $oferty_opcje;
	}

	public static function get_oferty_opcje_all() {
		$oferty_opcje = array();// [ service ] => array(ID => {oferta})
		$oferty_costs = self::get_offers_costs_by_offer_ids();
		// TODO: use [P_OFFER_TERM_BEGIN] => 0000-00-00, [P_OFFER_TERM] => 2011-12-31, [M_REWIR] => gd
		$sqlStatus = array('NORMAL');
		if (V::get('TEST_MONITOR', '', $_GET)) $sqlStatus[] = 'MONITOR';
		$sqlStatus = "and o.`A_STATUS` in('" . implode("','", $sqlStatus) . "')";
		$sql = "select
				o.`ID`
				, o.`P_SERVICE`
				, o.`P_SERVICE_PARENT`
				, o.`P_SERVICE_NAME`
				, o.`P_INSTALL_QUOTE`
				, o.`P_INSTALL_QUOTE_NORMAL`
				, o.`P_CONTRACT_PRICE`
				, o.`P_PROMO_MONTH_PRICE`
				, o.`P_NORMAL_PRICE`
				, o.`P_DEAL_PROMO_MONTHS`
				, o.`P_DEALTERM_MONTHS`
				, o.`ID_PRODUKT` as `ID_PRODUKT`
				, '' as `upust`
				, '' as `koszt`
				, IF(o.`ID_PROCES`>0, o.`ID_PROCES`, '') as `ID_PROCES`
				, o.`S_OTHER_INFO`
				, o.`S_TECHNOLOGY`
				, o.`P_MULTIROOM_ADD_CARDS`
				, o.`P_MULTIROOM_ADD_DEKODER_SD`
				, o.`P_MULTIROOM_ADD_DEKODER_HD`
				, o.`P_MULTIROOM_ADD_MODUL_CAM`
			from `USERS2_OFFERS` as o
			where o.`P_SERVICE` in('OPCJE', 'OPCJA_TVC', 'OPCJA_TEL')
				{$sqlStatus}
				and o.`P_SERVICE_COMPANY`='BN'
			order by o.`ID_PRODUKT` desc, o.`P_CONTRACT_PRICE` desc
		";
		$res = DB::query($sql);
		while ($r = DB::fetch($res)) {
			$r->srednia = '';
			if (array_key_exists($r->ID, $oferty_costs)) {
				$r->koszt = $oferty_costs[ $r->ID ];
			}
			if (in_array($r->P_SERVICE, array('OPCJA_TVC', 'OPCJA_TEL'))) {
				$oferty_opcje[ $r->P_SERVICE ][ $r->ID ] = $r;
			} else {
				$oferty_opcje[ $r->P_SERVICE_PARENT ][ $r->ID ] = $r;
			}
		}
		return $oferty_opcje;
	}

	public static function find_groups_by_offers($oferty, $todo_test_deal_id = 0) {
		$db = DB::getDB();
		$groups = array();
		$sql_where_arr = array();
		foreach ($oferty as $v_offer) {
			if ($v_offer->P_SERVICE == 'NET') {
				$sql_where_arr []= " `ID_NET`='{$v_offer->ID}' ";
			}
			else if ($v_offer->P_SERVICE == 'TEL') {
				$sql_where_arr []= " `ID_TEL`='{$v_offer->ID}' ";
			}
			else if ($v_offer->P_SERVICE == 'TV') {
				$sql_where_arr []= " (`ID_TV`='{$v_offer->ID}' or `ID_TVC`='{$v_offer->ID}')";
			}
		}
		if (empty($sql_where_arr)) {
			echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none;">Cant find groups for offers ('.$todo_test_deal_id.') (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($oferty);echo'</pre>';
			return $groups;
		}
		$sql_where = implode(" and ", $sql_where_arr);
		$sql = "SELECT *
			FROM  `USERS2_OFFERS_GROUPS`
			where $sql_where
		";
		$res = $db->query($sql);
		if ($db->has_errors()) {
			echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">DB Errors (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($db->get_errors());echo'</pre>';
			echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
		}
		while ($r = $db->fetch($res)) {
			$groups []= $r;
		}
		return $groups;
	}

	public static function date_diff_days($d1, $d2) {
		$d1_sec = strtotime($d1);
		$d2_sec = strtotime($d2);
		$diff_sec = $d1_sec - $d2_sec;
		$diff_days = floor($diff_sec / 3600 / 24);
		return $diff_days;
	}

	public static function date_diff_months($d1, $d2) {
		$d1_sec = strtotime($d1);
		$d2_sec = strtotime($d2);
		$diff_sec = $d1_sec - $d2_sec;
		$diff_months = floor($diff_sec / 3600 / 24 / 30);
		return $diff_months;
	}

	public static function get_aneks_loss($offers_ids, $diff_months, $deal_month, &$loss_log) {
		if (empty($offers_ids) || $diff_months <= 0) {
			return 0;
		}
		$loss = 0;
		$offers = self::get_offers_by_id($offers_ids, array('P_DEALTERM_MONTHS'=>$deal_month));
		$offers_costs = self::get_offers_costs_by_offer_ids($offers_ids);
		foreach ($offers as $v_offer) {
			if (array_key_exists($v_offer->ID, $offers_costs)) {
				$loss_log []= "oferta {$v_offer->ID} srednia netto: {$v_offer->srednia_netto} koszt: {$offers_costs[$v_offer->ID]}";
				$loss += $v_offer->srednia_netto - $offers_costs[$v_offer->ID];
			} else {
				$loss_log []= "brak kosztów dla ofety {$v_offer->ID}";
			}
		}
		$loss_log []= "sredni zysk miesięczny {$loss}";
		$loss = $loss * $diff_months;
		return $loss;
	}

	public static function get_aneks_loss_abonament_netto($offers_ids, $diff_months, $deal_month, &$loss_log) {
		if (empty($offers_ids) || $diff_months <= 0) {
			return 0;
		}
		$loss = 0;
		$offers = self::get_offers_by_id($offers_ids, array('P_DEALTERM_MONTHS'=>$deal_month));
		foreach ($offers as $v_offer) {
			$loss += $v_offer->srednia_netto;
		}
		$loss_log []= "sredni abonament miesięczny {$loss}";
		$loss = $loss * $diff_months;
		return $loss;
	}

	public static function get_deals_by_month($month, $params = array()) {
		$deals = array();

		$sql_status = "";
		$status = V::get('A_STATUS', '', $params);
		if (!empty($status)) {
			$allowed_status = array('WAITING', 'NORMAL');
			if (!is_array($status)) {
				$status = array($status);
			}
			$sql_status_arr = array();
			foreach ($status as $v_status) {
				if (in_array($v_status, $allowed_status)) {
					$sql_status_arr []= "'{$v_status}'";
				}
			}
			if (!empty($sql_status_arr)) {
				$sql_status = "and d.`A_STATUS` in (" . implode(',', $sql_status_arr) . ")";
			}
		}

		$db = DB::getDB();
		$sql = "select d.*
			from `DEALS_TABLE` as d
			where
				d.`P_DEALDATE` like '{$month}-%'
				{$sql_status}
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$deals[$r->ID] = $r;
		}
		return $deals;
	}

	public static function get_deals_created_in_month($month, $params = array()) {
		$deals = array();

		$sql_status = "";
		$sql_pominId = "";

		$status = V::get('A_STATUS', '', $params);
		if (!empty($status)) {
			$allowed_status = array('WAITING', 'NORMAL');
			if (!is_array($status)) {
				$status = array($status);
			}
			$sql_status_arr = array();
			foreach ($status as $v_status) {
				if (in_array($v_status, $allowed_status)) {
					$sql_status_arr []= "'{$v_status}'";
				}
			}
			if (!empty($sql_status_arr)) {
				$sql_status = "and d.`A_STATUS` in (" . implode(',', $sql_status_arr) . ")";
			}
		}
		$pominId = V::get('pominId', '', $params);
		if (!empty($pominId)) {
			$sql_pominId = "and `ID` not in(" . implode(",", $pominId) . ")";
		}

		$db = DB::getDB();
		$sql = "select d.*
			from `DEALS_TABLE` as d
			where
				d.`A_RECORD_CREATE_DATE` like '{$month}-%'
				{$sql_status}
				{$sql_pominId}
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$deals[$r->ID] = $r;
		}
		return $deals;
	}

}

class Column_Base {

	var $_data;
	var $_errors;

	function __construct() {
		$this->_errors = array();
		$this->_data = array();
	}

	function get($field) {
		return (array_key_exists($field, $this->_data))? $this->_data[$field] : '';
	}

	function set($field, $value) {
		if (array_key_exists($field, $this->_data)) {
			$this->_data[$field] = $value;
		}
	}

	function setForce($field, $value) {
		$this->_data[$field] = $value;
	}

	function get_cols() {
		return array_keys($this->_data);
	}

	function get_data() {
		return $this->_data;
	}

	function add_error($msg) {
		$this->_errors []= $msg;
	}

	function get_errors() {
		return $this->_errors;
	}

	function has_errors() {
		return !empty($this->_errors);
	}

}

class Services_Converter {

	var $_deal;// Column_deal_table
	var $_group;// Column_users2_offers_groups
	var $_services;
	var $_old_deals_data;// user current active deals with services info
	var $_old_deal;// current choosen old deal
	var $_old_srv_data;// 
	var $_new_srv_data;// 
	var $_srv_map;// 
	var $_srv_to_create;
	var $_srv_to_off;
	var $_errors;

	function __construct() {
		$this->_deal = null;
		$this->_group = null;
		$this->_services = array();
		$this->_old_deals_data = array();
		$this->_old_deal = null;
		$this->_old_srv_data = array();
		$this->_new_srv_data = array();
		$this->_srv_map = array();
		$this->_srv_to_create = array();
		$this->_srv_to_off = array();
		$this->_errors = array();
	}

	function set_deal($deal) {
		$this->_deal = $deal;
	}

	function fetch_group() {
		if (!$this->_deal || $this->_deal->get('ID') <= 0) {
			return false;
		}
		$db = DB::getDB();
		$group_id = (int)$this->_deal->get('ID_OFFERS_GROUP');
		if ($group_id <= 0) {
			return false;
		}
		$this->_group = PokazOfertyHelper::get_group($group_id);
		if ($this->_group) {
			return true;
		}
		return false;
	}

	/**
	 * Fetch offers rows by ID_OFFERS_ON or USERS2_DEALS.
	 */
	function fetch_offers() {
		if (!$this->_deal || $this->_deal->get('ID') <= 0) {
			return;
		}
		$id_offers_on = $this->_deal->get('ID_OFFERS_ON');
		if (!empty($id_offers_on)) {
			$offers_ids = explode(',', $id_offers_on);
		} else {
			$offers_ids = array();
			$db = DB::getDB();
			$sql = "select d.`P_OFFER_ID_NEW`
				from `USERS2_DEALS` as d
				where d.`P_DEALNUMBER_NEW`='" . $this->_deal->get('ID') . "'
					and d.`A_STATUS`='WAITING'
					and d.`P_OFFER_ID_NEW`>0
			";
			$res = $db->query($sql);
			while ($r = $db->fetch($res)) {
				$offers_ids []= $r->P_OFFER_ID_NEW;
			}
		}
		if (empty($offers_ids)) {
			return;
		}
		$this->_group->set_offers(PokazOfertyHelper::get_offers_by_id($offers_ids));
	}

	function fetch_old_deal() {
		if ($this->_deal->get('P_DEALNUMBER_OLD') > 0) {
			$this->_old_deals_data = PokazOfertyHelper::get_deals_active_with_info($this->_deal->get('S_ADDRESS_STREET'), $this->_deal->get('ID_BILLING_USERS'));
			if (array_key_exists($this->_deal->get('P_DEALNUMBER_OLD'), $this->_old_deals_data)) {
				$this->_old_deal = $this->_old_deals_data[$this->_deal->get('P_DEALNUMBER_OLD')];
			}
		}
	}

	function generate_srv_map() {
		if (empty($this->_old_deals_data)) return;

		foreach ($this->_old_deals_data as $k_deal_id => $v_deal) {
			foreach ($v_deal->services_by_id as $k_p_service => $v_srv) {
				$v_srv->ses_x_a = V::get($v_srv->ID, null, $v_deal->ses_x_a);
				$this->_old_srv_data [$v_deal->ID_DEALS] [$v_srv->ID] = $v_srv;
			}

			foreach ($this->_group->get_offers_by_id() as $v_offer) {
				if ($v_offer->P_SERVICE_PARENT != '') {// opcja
					if ($v_offer->ID_DOMAINS == '' && $v_offer->ID_DOMAINS_PACKET_ID == '') {
						// pomin - ta oferta jest tylko opcją i nie wchodzi jako osobny SERVICES
						continue;
					}
				}
				$this->_new_srv_data [$v_offer->ID]= $v_offer;
			}

			$this->_srv_map[$v_deal->ID_DEALS] = array();
			$used_offer_ids = array();// id offers => id srv

			// decide what to do with old services
			foreach ($this->_old_srv_data[$v_deal->ID_DEALS] as $k_srv_id => $v_srv) {
				$new_offer_id = 0;

				// pomin NET pod VOIP
				if ($v_srv->NAME_LIST_SERVICES == 'USERS2') {
					if ($v_srv->P_ID_SERVICES > 0) {
						?>
						<div class="container">
							<div class="alert alert-info">
								Usługa internet ID=<?php echo $v_srv->ID; ?> pozostanie bez zmian ponieważ ma ustawione P_ID_SERVICES.
							</div>
						</div>
						<?php
						continue;
					}
				}

				foreach ($this->_new_srv_data as $k_offer_id => $v_offer) {
					if (in_array($k_offer_id, $used_offer_ids) || $new_offer_id > 0) {
						continue;
					}
					// try if new offer match old service
					if ($v_srv->NAME_LIST_SERVICES == 'USERS2') {
						if ($v_offer->P_SERVICE == 'NET') {
							if ($v_offer->S_TECHNOLOGY == $v_srv->ses_x_a->S_TECHNOLOGY) {
								$new_offer_id = $k_offer_id;
								$used_offer_ids []= $k_offer_id;
							} else {
								?>
								<div class="container">
									<div class="alert alert-error">
										TODO: Oferta na internet ma S_TECHNOLOGY='<?php echo $v_offer->S_TECHNOLOGY; ?>', a aktualna usługa ma '<?php echo $v_srv->ses_x_a->S_TECHNOLOGY; ?>'
										<?php if ($v_offer->S_TECHNOLOGY == 'GPON') : ?>
											<br>Propozycja: utworzyć nową umowę zamiast aneksu, a stare usługi wyłączyć po instalacji nowych usług.
										<?php else : ?>
											<br>Stare usugi zostaną wyłączone automtycznie, ale powinny działać do czasu włączenia nowej umowy
										<?php endif; ?>
									</div>
								</div>
								<?php
								//exit;
							}
						}
					} else if ($v_srv->NAME_LIST_SERVICES == 'VOIP') {
						if ($v_offer->P_SERVICE == 'TEL') {
							if ($v_offer->ID_DOMAINS != '') {
								if ($v_offer->ID_DOMAINS == $v_srv->ses_x_a->ID_DOMAINS) {
									$new_offer_id = $k_offer_id;
									$used_offer_ids []= $k_offer_id;
								}
							}
						}
					} else if ($v_srv->NAME_LIST_SERVICES == 'TV') {
						if ( ($v_offer->P_SERVICE == $v_srv->ses_x_a->P_SERVICE_CLASS)
								|| ($v_offer->P_SERVICE == 'OPCJE' && $v_offer->P_SERVICE_PARENT == 'TV')
						) {// TV, TVC, TVCP
							if ($v_offer->ID_DOMAINS != '' && $v_offer->ID_DOMAINS_PACKET_ID > 0) {
								if ($v_offer->ID_DOMAINS == $v_srv->ses_x_a->ID_DOMAINS && $v_offer->ID_DOMAINS_PACKET_ID == $v_srv->ses_x_a->ID_DOMAINS_PACKET_ID) {
									$new_offer_id = $k_offer_id;
									$used_offer_ids []= $k_offer_id;
								}
							} else {
								$new_offer_id = $k_offer_id;
								$used_offer_ids []= $k_offer_id;
							}
						}
					}
				}
				$this->_srv_map[$v_deal->ID_DEALS][$v_srv->ID] = $new_offer_id;
			}
		}
	}

	function get_srv_map() {
		return $this->_srv_map;
	}

	function get_srv_map_by_deal($deal_id) {
		return (array_key_exists($deal_id, $this->_srv_map))? $this->_srv_map[$deal_id] : null;
	}

	function get_old_srv_data($deal_id) {
		return (array_key_exists($deal_id, $this->_old_srv_data))? $this->_old_srv_data[$deal_id] : array();
	}

	function add_error($msg) {
		$this->_errors []= $msg;
	}

	function get_errors() {
		return $this->_errors;
	}

	function has_errors() {
		return !empty($this->_errors);
	}

	function validate_edit() {
		if ($this->_deal->get('ID') <= 0) {
			$this->add_error("Błędny numer ID rekordu");
		}

		if ('WAITING' != $this->_deal->get('A_STATUS')) {
			$verify_link = "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&task=verify_deal&id_deal=" . $this->_deal->get('ID');
			$verify_link = " - " . '<a href="' . $verify_link . '">' . " Zweryfikuj " . $this->_deal->get('ID') . '</a>';
			$this->add_error("Błędny status umowy (A_STATUS), aktywować można tylko WAITING {$verify_link}");
		}

		if (intval($this->_deal->get('ID_OFFERS_GROUP')) <= 0) {
			$this->add_error("Błędny numer pakietu ID_OFFERS_GROUP");
		} else {
			if (!$this->_group) {
				$this->add_error("Brak grupy ofert ID " . $this->_data['ID_OFFERS_GROUP'] . " (USERS2_OFFERS_GROUPS)");
			} else if (!$this->_group->has_offers()) {
				$this->add_error("Brak ofert (USERS2_OFFERS)");
			}
		}

		if (intval($this->_deal->get('ID_BILLING_USERS')) <= 0) {
			$this->add_error("Błędny numer klienta ID_BILLING_USERS");
		}

		if ('' == $this->_deal->get('P_DEALPREFIX')) {
			$this->add_error("Pole P_DEALPREFIX musi być wypełnione");
		}

		if (intval($this->_deal->get('P_DEALNUMBER')) <= 0) {
			$this->add_error("Błędny numer umowy P_DEALNUMBER");
		}

		$deal_date = $this->_deal->get('P_DEALDATE');
		if (strlen($deal_date) != 10) {
			$this->add_error("Błędna data umowy P_DEALDATE");
		} else {
			// TODO: data aktywacji nie moze byc wczesniej nie TODAY
		}

		$deal_term = $this->_deal->get('P_DEALDATE_TERM');
		if (strlen($deal_term) != 10) {
			$this->add_error("Błędny termin umowy P_DEALDATE_TERM");
		}

		$old_deal_id = intval($this->_deal->get('P_DEALNUMBER_OLD'));
		if ($old_deal_id > 0) {

			// check if all old SERVICES has ID_OFFER
			$old_srv_data = $this->get_old_srv_data($old_deal_id);
			foreach ($old_srv_data as $k_srv_id => $v_srv) {
				if ($v_srv->ID_OFFERS <= 0) {
					$this->add_error("Brak numeru oferty przy usłudze ID=" . $v_srv->ID . ": " . $v_srv->NAME_LIST_SERVICES);
				}
			}

			$srv_map = $this->get_srv_map_by_deal($old_deal_id);
			if (empty($srv_map)) {
				$this->add_error("Brak srv_map dla old_deal_id = $old_deal_id!");
				echo'<pre style="display:none;max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this);echo'</pre>';
			}
		}

		if (!$this->has_errors()) {
			$activated_services = array();
			$db = DB::getDB();
			$sql = "select * from `SERVICES` where `ID_DEALS_TABLE`='" . $this->_deal->get('ID') . "'";
			$res = $db->query($sql);
			while ($r = $db->fetch($res)) {
				$activated_services[$r->ID] = $r;
			}
			if (!empty($activated_services)) {
				//echo '<p style="color:red">' . "UWAGA: Uslugi już zostały wprowadzone! (SERVICES ID: " . implode(", ", array_keys($activated_services)) . ")" . '</p>';
				$this->add_error("Uslugi dla tej umowy (ID: " . $this->_deal->get('ID') . ") już zostały wprowadzone! (SERVICES ID: " . implode(", ", array_keys($activated_services)) . ")");
			}
		}

		return true;
	}

	function print_html_data() {

		PokazOfertyView::print_simple_tbl((object)$this->_deal->get_data(), $this->_deal->get_cols(), 'DEALS_TABLE');

		if ($this->_group) {
			PokazOfertyView::print_simple_tbl((object)$this->_group->get_data(), $this->_group->get_cols(), 'USERS2_OFFERS_GROUPS');

			$cols = array_keys(get_object_vars(reset($this->_group->get_offers_by_id())));
			// hide P_SERVICE_QUOTA_PROFILE
			if (in_array('P_SERVICE_QUOTA_PROFILE', $cols)) {
				$new_cols = array();
				foreach ($cols as $v_col) {
					if ($v_col == 'P_SERVICE_QUOTA_PROFILE') {
						continue;
					}
					$new_cols []= $v_col;
				}
				$cols = $new_cols;
			}
			echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
			PokazOfertyView::print_simple_tbl_header($cols, 'USERS2_OFFERS');
			echo '<tbody>';
			$t = 0;
			foreach ($this->_group->get_offers_by_id() as $k_id => $v_offer) {
				PokazOfertyView::print_simple_tbl_body_row($v_offer, $cols, array('class'=>'row-' . ($t = 1 - $t)));
			}
			echo '</tbody>';
			echo '</table>';
		}

/*
		$cols = array_keys(reset($this->_users2_deals_rows)->get_data());
		echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
		PokazOfertyView::print_simple_tbl_header($cols, 'USERS2_DEALS');
		echo '<tbody>';
		$t = 0;
		foreach ($this->_users2_deals_rows as $k_id => $v_obj) {
			PokazOfertyView::print_simple_tbl_body_row((object)$v_obj->get_data(), $cols, array('class'=>'row-' . ($t = 1 - $t)));
		}
		echo '</tbody>';
		echo '</table>';
*/
	}

	function get_service_type_map() {
/* fields map:
 * SERVICES
 * 		ID_BILLING_USERS						$this->_user->ID_BILLING_USERS
 * 		ID_DEALS_TABLE							$this->get('ID')
 * 		ID_OFFERS										$this->_offers_rows[ID]->ID
 * 		NAME_LIST_SERVICES					USERS2, TV, VOIP
 * 		A_STATUS										WAITING
 * 		active											1
 * 		SERVICE_TYPE								ABONAMENT
 * 		ID_BILLING_NUMBERS_TYPE			1
 * 		ABONAMENT_PERIOD						1
 * 		ABONAMENT_VALUE							$this->_offers_rows[ID]->P_PROMO_MONTH_PRICE_NETTO - netto w promocyjnych miesiącach
 * 				lub P_CONTRACT_PRICE_NETTO + rekordy w SES_X_C po P_DEALTERM_MONTHS (VALUE1), TYP 17, róznice NETTO z ceną P_PROMO_MONTH_PRICE_NETTO (VALUE2)
 * 		VAT													$this->_offers_rows[ID]->STAWKA_VAT - vat (int)
 * 		ID_CURRENCY									0
 * 		ABONAMENT_PAYMENT						UP
 * 		ABONAMENT_START							1
 * 		MINIMUM_BILLING_VALUE				0.00
 * 		BILLED_TILL									NULL
 * 		HANGUP_FROM									NULL
 * 		HANGUP_TILL									NULL
 * 		HANGUP_STATUS								NULL
 * 		HANGUP_RATIO								1.00
 * 		P_ID_SERVICES								0 lub parent services ID
 * 		uwagi												''
 * 		VAT_NAME										'ZW',8,23
 * 		id_list_sww									(int) ??
 * 		SERV_ID_BILLING_PREFIXES		0
 * TODO: VAT czasem jest 0 i VAT_NAME na ZW
 * 
 * SES_USERS2_A
 * 		ID_BILLING_USERS					user.ID
 * 		ID_SERVICES								SERVICES.ID
 * 		P_SERVICE_QUOTA_PROFILE		$this->_offers_rows[ID]->P_SERVICE_QUOTA_PROFILE
 * 		LAN_DOWNLOAD							$this->_offers_rows[ID]->LAN_DOWNLOAD
 * 		S_PUBLIC_IP								$this->_offers_rows[ID]->S_PUBLIC_IP
 * 		S_SOHO_WIFI_ROUTER_1292		$this->_offers_rows[ID]->S_SOHO_WIFI_ROUTER_1292
 * 		S_E_PORT_1293							$this->_offers_rows[ID]->S_E_PORT_1293
 * 		CONN_DIV									$this->_offers_rows[ID]->CONN_DIV
 * SES_TV_A
 * 		P_DEVICE													$this->_offers_rows[ID]->P_DEVICE
 * 		P_SERVICE_CLASS										$this->_offers_rows[ID]->P_SERVICE_CLASS
 * 		P_SERVICE_SOCKETS_AMMOUNT_1298		$this->_offers_rows[ID]->P_SERVICE_SOCKETS_AMMOUNT_1298
 * 		ID_DOMAINS_PACKET_ID	$this->_offers_rows[ID]->ID_DOMAINS_PACKET_ID
 * 		ID_DOMAINS						$this->_offers_rows[ID]->ID_DOMAINS
 * SES_VOIP_A
 * 		ID_DOMAINS_PACKET_ID	$this->_offers_rows[ID]->ID_DOMAINS_PACKET_ID
 * 		VOIP_FAX2EMAIL				$this->_offers_rows[ID]->VOIP_FAX2EMAIL
 * 		ID_DOMAINS						$this->_offers_rows[ID]->ID_DOMAINS
 */

/*
 * SES_TV_A
 * SES_USERS2_A
 * SES_VOIP_A
 * 
 * SES_DOMAINS_A
 * SES_EMAIL_A
 * SES_E_WLAN_A
 * SES_INSTALL_A
 * SES_SERWIS_A
 * SES_WWW_A
 * SES_WWW_MASS_A
 */
		$name_list_services_map = array();
		$name_list_services_map['NET'] = 'USERS2';
		$name_list_services_map['TEL'] = 'VOIP';// TOOD: wymaga SES_USERS2_A jako podrzedna do VOIP
		$name_list_services_map['TV'] = 'TV';
		$name_list_services_map['TVC'] = 'TV';
		$name_list_services_map['TVCP'] = 'TV';

		$map = array();
		$map['TV'] = 'TV';
		$map['TVC'] = 'TV';
		$map['TVCP'] = 'TV';
		$map['NET'] = 'USERS2';
		$map['TEL'] = 'VOIP';// TOOD: wymaga SES_USERS2_A jako podrzedna do VOIP
		//$map['OPCJE-NET'] = 'NET';
		//$map['OPCJE-TV'] = 'TV';
		//$map['OPCJE-TVC'] = 'TV';
		//$map['OPCJE-TVCP'] = 'TV';
		//$map['OPCJE-TEL'] = 'TEL';
		return $map;
	}

	/**
	 * Create array of services to create ($this->_srv_to_create).
	 * $this->_srv_to_create [ID=>P_SERVICE_CLASS]
	 */
	function generate_preview() {
		$srv_map = array();

		$old_deal_id = intval($this->_deal->get('P_DEALNUMBER_OLD'));
		if ($old_deal_id > 0) {
			$srv_map = $this->get_srv_map_by_deal($old_deal_id);
		}

		echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none">_srv_map (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($srv_map);echo'</pre>';

	// TODO: add $this->_srv_todo = array('create', 'update', 'off')
	//   'create' - create new records in SERVICES, SES_X_A, SES_X_C
	//   'update' - create new records in SERVICES, mv SES_X_C from old srv to new srv using $srv_map
	//   'off' - turn off services

// $this->_srv_to_off today - TODO: HANGUP_FROM / HANGUP_TILL, HANGUP_STATUS, HANGUP_RATIO
/*
        <p align="center">Podaj okres zawieszenia usługi:</td>
    </tr>
        <td align="left">Wybierz status jaki ma mieć płatnik na czas zawieszenia:<br>
 <b>U</b>stalenie HANGUP_STATUS na ODLACZONY,ZABLOKOWANY itp pozwala na: od DATA1 do DATA2 , od (nieustalone) do DATA2, od DATA1 do (nieustalone)<br>
 <b>U</b>stalenie HANGUP_STATUS na NORMAL np od 2004-10-01 do 2004-11-01 spowoduje zawieszenie przed 2004-10-01 oraz po 2004-11-01.<br>
 <b>U</b>stalenie HANGUP_STATUS na NORMAL np od 2004-10-01 do (nieustalone) spowoduje zawieszenie uslugi do 2004-10-01<br>
 <b>W</b> każdym z przypadków należy pamiętać o ustaleniu WSPÓŁCZYNNIKU ZAWIESZENIA, gdyż on wpływa na wysokość zawieszenia w trakcie jego trwania<br>
	<select size="1" name="Hstatus">
        <option selected value="">---- Status ---</option>
<?php
//    $sqll = "SELECT HANGUP_FROM,HANGUP_TILL,HANGUP_STATUS FROM SERVICES WHERE ID='$uid'";
    $sqll = "SELECT HANGUP_FROM,HANGUP_TILL,HANGUP_STATUS,HANGUP_RATIO  FROM SERVICES WHERE ID='$posid' AND NAME_LIST_SERVICES='$uservice' ";    
echo "  ***** $sqll ***** ";
    $resultl = $vdb->sql_query($sqll);
    list($ffrom,$fto,$fstat,$fHANGUP_RATIO)=$vdb->sql_fetchrow($resultl);
 * 
 * save
 * 
        $sqlsh="INSERT INTO SERVICES_HIST ( ID_SERVICES , ID_BILLING_USERS , A_RECORD_UPDATE_AUTHOR,HANGUP_FROM,HANGUP_TILL,HANGUP_STATUS,HANGUP_RATIO
        ) values ( '$SERVICES_ID','$uID', '".$_SESSION['u_id']."' ,'$data_start','$data_end','$Hstatus','$fHANGUP_RATIO'
        )" ;

    $sql = "UPDATE SERVICES SET HANGUP_FROM='$data_start', HANGUP_TILL='$data_end', HANGUP_STATUS='$Hstatus' , HANGUP_RATIO='$fHANGUP_RATIO' WHERE ID_BILLING_USERS='$uID' AND NAME_LIST_SERVICES='$uservice' and ID='$SERVICES_ID' ";
 */
		$offers = $this->_group->get_offers_by_id();

		$this->_srv_to_create = array();
		$group_external_offers_id = array('ID_NET'=>'NET','ID_TV'=>'TV','ID_TVC'=>'TVC','ID_TVCP_1'=>'TVC','ID_TVCP_2'=>'TVC','ID_TVCP_3'=>'TVC','ID_TVCP_4'=>'TVC','ID_TEL'=>'TEL');
		foreach ($group_external_offers_id as $k_external_id => $v_p_service) {
			$offer_id = $this->_group->get($k_external_id);
			if ($offer_id > 0) {

				$find_old_srv_id = 0;
				if (!empty($srv_map)) {
					foreach ($srv_map as $k_srv_id => $v_offer_id) {
						if ($offer_id == $v_offer_id) {
							$find_old_srv_id = $k_srv_id;
						}
					}
				}

				$this->_srv_to_create[$offer_id] = array('P_SERVICE'=>$v_p_service, 'old_srv_id'=>$find_old_srv_id);
			}
		}

		$offers_option_to_add = array();
		foreach ($offers as $k_id => $v_offer) {
			if (array_key_exists($k_id, $this->_srv_to_create)) {
				continue;
			}
			$offers_option_to_add [$k_id] = $v_offer->P_SERVICE_PARENT;
		}
		if (!empty($offers_option_to_add)) {
			foreach ($offers_option_to_add as $k_option_id => $v_p_service_parent) {
				$v_option = $offers[$k_option_id];
				foreach ($offers as $k_id => $v_offer) {// find option parent (first offer)
					if ($v_offer->P_SERVICE == $v_p_service_parent) {
						// add option to parent offer service or create new service
						// przetestowac dla OPCJE do TVC np. 'Canal+', 'Canal+ HD'
						if (!empty($v_option->ID_DOMAINS)	&& $v_option->ID_DOMAINS_PACKET_ID > 0) {
							$this->_srv_to_create[$v_option->ID] = array('P_SERVICE'=>$v_option->P_SERVICE, 'old_srv_id'=>0);
						} else {
							$offers[$k_id]->_options[$k_option_id] = $offers[$k_option_id];
						}
						break;
					}
				}
			}
		}

		// create new _services objects
		foreach ($this->_srv_to_create as $k_offer_id => $v_params) {
			$offer = $offers[$k_offer_id];
			$srv = new Column_services();
			$srv->set_id_deals_table($this->_deal->get('ID'));
			$srv->set_id_billing_users($this->_deal->get('ID_BILLING_USERS'));
			$srv->set_s_address_street($this->_deal->get('S_ADDRESS_STREET'));
			$srv->set_services_map($this->get_service_type_map());
			$srv->set_data_from_oferta_row($offer);

			if (($old_srv_id = V::get('old_srv_id', 0, $v_params)) > 0) {
				$srv->set_old_srv_id($old_srv_id);
				$srv->set_old_srv($this->get_old_srv_by_id($old_deal_id, $old_srv_id));
				$srv->set('A_STATUS', 'NORMAL');
				// TODO: HANGUP_FROM i inne parametry wymagane do uruchomienia usługi
				
				// _srv_to_off
				$this->_srv_to_off [$old_srv_id] = true;
			}

			$this->_services []= $srv;
		}

		// set _srv_to_off from $srv_map where => 0
		if (!empty($srv_map)) {
			foreach ($srv_map as $k_srv_id => $v_offer_id) {
				if ($v_offer_id == 0) {
					$this->_srv_to_off [$k_srv_id] = true;
				}
			}
		}
	}

	function get_old_srv_by_id($old_deal_id, $srv_id) {
		/*
			[11361] => Array(
            [20495] => stdClass Object(
                    [ID] => 20495
                    ...
                    [ses_x_a] => stdClass Object
		 */
		if (isset($this->_old_srv_data[$old_deal_id][$srv_id])) {
			return $this->_old_srv_data[$old_deal_id][$srv_id];
		}
		return null;
	}

	function edit_preview() {
		echo '<h3>' . "Podgląd rekordów do utworzenia" . '</h3>';

		$old_deal_id = intval($this->_deal->get('P_DEALNUMBER_OLD'));
		if (!empty($this->_srv_to_off) && $old_deal_id > 0) {
			$srv_data = array();
			if (!empty($this->_old_srv_data[$old_deal_id])) {
				foreach ($this->_srv_to_off as $k_srv_id => $v_bool) {
					$srv_data[$k_srv_id] = $this->_old_srv_data[$old_deal_id][$k_srv_id];
				}
			}
			$cols = array('ID','NAME_LIST_SERVICES','A_STATUS','ID_OFFERS','ID_DEALS_TABLE','P_ID_SERVICES','ABONAMENT_VALUE','P_ID','description','A_STATUS_DESC','P_SERVICE');
			echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
			PokazOfertyView::print_simple_tbl_header($cols, 'SERVICES - do wyłączenia');
			echo '<tbody>';
			$t = 0;
			foreach ($srv_data as $k_srv_id => $v_obj) {
				PokazOfertyView::print_simple_tbl_body_row($v_obj, $cols, array('class'=>'row-' . ($t = 1 - $t)));
			}
			echo '</tbody>';
			echo '</table>';
		}

		$cols = array_keys(reset($this->_services)->get_data());
		echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
		PokazOfertyView::print_simple_tbl_header($cols, 'SERVICES - nowe rekordy');
		echo '<tbody>';
		$t = 0;
		foreach ($this->_services as $k_id => $v_obj) {
			PokazOfertyView::print_simple_tbl_body_row((object)$v_obj->get_data(), $cols, array('class'=>'row-' . ($t = 1 - $t)));
		}
		echo '</tbody>';
		echo '</table>';

		// show SES_X_A and SES_X_C records
		foreach ($this->_services as $k_id => $v_srv) {
			$v_obj = $v_srv->get_ses_x_a();

			if ($old_deal_id > 0 && $v_srv->get_old_srv_id() > 0) {
				echo '<div style="background:#ddd;padding:3px;">';
				$old_srv_obj = $v_srv->get_old_srv();
				if ($old_srv_obj) {
					$cols = array_keys((array)$old_srv_obj->ses_x_a);
					echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
					PokazOfertyView::print_simple_tbl_header($cols, 'SES_' . $old_srv_obj->NAME_LIST_SERVICES . '_A - stary rekord');
					echo '<tbody>';
					PokazOfertyView::print_simple_tbl_body_row($old_srv_obj->ses_x_a, $cols, array('class'=>'row-1'));
					echo '</tbody>';
					echo '</table>';

					$update_fields = $v_obj->get_update_fields_from_old_ses_x_a('TODO', $old_srv_obj->ses_x_a);
					if (!empty($update_fields)) {
						$cols = array_keys($update_fields);
						echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
						PokazOfertyView::print_simple_tbl_header($cols, 'SES_' . $old_srv_obj->NAME_LIST_SERVICES . '_A - zaktualizowany rekord');
						echo '<tbody>';
						$t = 0;
						PokazOfertyView::print_simple_tbl_body_row((object)$update_fields, $cols, array('class'=>'row-' . ($t = 1 - $t)));
						echo '</tbody>';
						echo '</table>';
					} else {
						echo '<p>'."Nie udało się utworzyć zaktualizowanego rekordu".'</p>';
					}
				}
				if (0) {// if ($v_obj) {
					$cols = array_keys($v_obj->get_data());
					echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
					PokazOfertyView::print_simple_tbl_header($cols, $v_obj->get_name() . ' - nowy rekord w przypadku nowej usługi - tylko dla testu');
					echo '<tbody>';
					$t = 0;
					PokazOfertyView::print_simple_tbl_body_row((object)$v_obj->get_data(), $cols, array('class'=>'row-' . ($t = 1 - $t)));
					echo '</tbody>';
					echo '</table>';
				}

				if (!empty($v_obj->_extra_services)) {
					foreach ($v_obj->_extra_services as $v_esrv) {
						$rows = $v_esrv->get_old_rows($v_srv->get_old_srv_id());
						if (!empty($rows)) {
							$r = reset($rows);
							$cols = array_keys((array)$r);
							echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
							PokazOfertyView::print_simple_tbl_header($cols, 'EXTRA_SERVICES - zmiany');
							echo '<tbody>';
							$t = 0;
							foreach ($rows as $r) {
								PokazOfertyView::print_simple_tbl_body_row($r, $cols, array('class'=>'row-' . ($t = 1 - $t)));
								$r->ID_SERVICES = 'NOWY ID';
								PokazOfertyView::print_simple_tbl_body_row($r, $cols, array('class'=>'row-' . ($t = 1 - $t)));
							}
							echo '</tbody>';
							echo '</table>';
						}
					}
				}
				echo '</div>';
			}
			else {
				if ($v_obj) {
					$cols = array_keys($v_obj->get_data());
					echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
					PokazOfertyView::print_simple_tbl_header($cols, $v_obj->get_name());
					echo '<tbody>';
					$t = 0;
					PokazOfertyView::print_simple_tbl_body_row((object)$v_obj->get_data(), $cols, array('class'=>'row-' . ($t = 1 - $t)));
					echo '</tbody>';
					echo '</table>';
				}
			}

			$v_obj_arr = $v_srv->get_ses_x_b();
			if (!empty($v_obj_arr)) {
				$v_obj = reset($v_obj_arr);
				$cols = array_keys($v_obj->get_data());
				echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
				PokazOfertyView::print_simple_tbl_header($cols, $v_obj->get_name());
				echo '<tbody>';
				$t = 0;
				foreach ($v_obj_arr as $v_obj) {
					PokazOfertyView::print_simple_tbl_body_row((object)$v_obj->get_data(), $cols, array('class'=>'row-' . ($t = 1 - $t)));
				}
				echo '</tbody>';
				echo '</table>';
			}

			$v_obj_arr = $v_srv->get_ses_x_c();
			if (!empty($v_obj_arr)) {
				$v_obj = reset($v_obj_arr);
				$cols = array_keys($v_obj->get_data());
				echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
				PokazOfertyView::print_simple_tbl_header($cols, $v_obj->get_name());
				echo '<tbody>';
				$t = 0;
				foreach ($v_obj_arr as $v_obj) {
					PokazOfertyView::print_simple_tbl_body_row((object)$v_obj->get_data(), $cols, array('class'=>'row-' . ($t = 1 - $t)));
				}
				echo '</tbody>';
				echo '</table>';
			}
		}
	}

	function verify_preview() {
		echo '<h3>' . "Podgląd rekordów do utworzenia" . '</h3>';

		$old_deal_id = intval($this->_deal->get('P_DEALNUMBER_OLD'));
		if (!empty($this->_srv_to_off) && $old_deal_id > 0) {
			$srv_data = array();
			if (!empty($this->_old_srv_data[$old_deal_id])) {
				foreach ($this->_srv_to_off as $k_srv_id => $v_bool) {
					$srv_data[$k_srv_id] = $this->_old_srv_data[$old_deal_id][$k_srv_id];
				}
			}
			$cols = array('ID','NAME_LIST_SERVICES','A_STATUS','ID_OFFERS','ID_DEALS_TABLE','P_ID_SERVICES','ABONAMENT_VALUE','P_ID','description','A_STATUS_DESC','P_SERVICE');
			echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
			PokazOfertyView::print_simple_tbl_header($cols, 'SERVICES - do wyłączenia');
			echo '<tbody>';
			$t = 0;
			foreach ($srv_data as $k_srv_id => $v_obj) {
				PokazOfertyView::print_simple_tbl_body_row($v_obj, $cols, array('class'=>'row-' . ($t = 1 - $t)));
			}
			echo '</tbody>';
			echo '</table>';
		}

		$cols = array_keys(reset($this->_services)->get_data());
		echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
		PokazOfertyView::print_simple_tbl_header($cols, 'SERVICES - nowe rekordy');
		echo '<tbody>';
		$t = 0;
		foreach ($this->_services as $k_id => $v_obj) {
			PokazOfertyView::print_simple_tbl_body_row((object)$v_obj->get_data(), $cols, array('class'=>'row-' . ($t = 1 - $t)));
		}
		echo '</tbody>';
		echo '</table>';

		// show SES_X_A and SES_X_C records
		foreach ($this->_services as $k_id => $v_srv) {
			$v_obj = $v_srv->get_ses_x_a();

			if ($old_deal_id > 0 && $v_srv->get_old_srv_id() > 0) {
				echo '<div style="background:#ddd;padding:3px;">';
				$old_srv_obj = $v_srv->get_old_srv();
				if ($old_srv_obj && $old_srv_obj->ses_x_a) {
					$cols = array_keys((array)$old_srv_obj->ses_x_a);
					echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
					PokazOfertyView::print_simple_tbl_header($cols, 'SES_' . $old_srv_obj->NAME_LIST_SERVICES . '_A - stary rekord');
					echo '<tbody>';
					PokazOfertyView::print_simple_tbl_body_row($old_srv_obj->ses_x_a, $cols, array('class'=>'row-1'));
					echo '</tbody>';
					echo '</table>';
				}
				if ($v_obj) {
					$cols = array_keys($v_obj->get_data());
					echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
					PokazOfertyView::print_simple_tbl_header($cols, $v_obj->get_name() . ' - nowy rekord');
					echo '<tbody>';
					$t = 0;
					PokazOfertyView::print_simple_tbl_body_row((object)$v_obj->get_data(), $cols, array('class'=>'row-' . ($t = 1 - $t)));
					echo '</tbody>';
					echo '</table>';
				}
				echo '</div>';
			}
			else {
				if ($v_obj) {
					$cols = array_keys($v_obj->get_data());
					echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
					PokazOfertyView::print_simple_tbl_header($cols, $v_obj->get_name());
					echo '<tbody>';
					$t = 0;
					PokazOfertyView::print_simple_tbl_body_row((object)$v_obj->get_data(), $cols, array('class'=>'row-' . ($t = 1 - $t)));
					echo '</tbody>';
					echo '</table>';
				}
			}

			$v_obj_arr = $v_srv->get_ses_x_c();
			if (!empty($v_obj_arr)) {
				$v_obj = reset($v_obj_arr);
				$cols = array_keys($v_obj->get_data());
				echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
				PokazOfertyView::print_simple_tbl_header($cols, $v_obj->get_name());
				echo '<tbody>';
				$t = 0;
				foreach ($v_obj_arr as $v_obj) {
					PokazOfertyView::print_simple_tbl_body_row((object)$v_obj->get_data(), $cols, array('class'=>'row-' . ($t = 1 - $t)));
				}
				echo '</tbody>';
				echo '</table>';
			}
		}
	}

	function edit_update(&$err_msgs, &$log_arr, $simulate_db = null) {
		// Create new services and set 'ID_SERVICES_NEW' in USERS2_DEALS rows

		$old_deal_id = intval($this->_deal->get('P_DEALNUMBER_OLD'));

		$db = DB::getDB();
		//$db->query('SET autocommit=0');
		//$db->query('START TRANSACTION');
		// wyłącz stare usługi
		if (!empty($this->_srv_to_off) && $old_deal_id > 0) {
			$srv_data = array();
			if (!empty($this->_old_srv_data[$old_deal_id])) {
				foreach ($this->_srv_to_off as $k_srv_id => $v_bool) {
					$srv_data[$k_srv_id] = $this->_old_srv_data[$old_deal_id][$k_srv_id];
				}
			}
			if (!empty($srv_data)) {
				foreach ($srv_data as $k_srv_id => $v_srv) {
					if ($v_srv->NAME_LIST_SERVICES == 'EMAIL') {// TODO: tylko przepisz do nowej umowy
						$sql_obj = new stdClass();
						$sql_obj->ID = $v_srv->ID;
						$sql_obj->ID_DEALS_TABLE = $this->_deal->get('ID');
						if ($simulate_db) {
							$simulate_db->add('UPDATE_OBJ', 'SERVICES', $sql_obj);
						} else {
							if ($db->UPDATE_OBJ('SERVICES', $sql_obj) <= 0) {
								//$db->query('ROLLBACK');
								$err_msgs []= "nie udało się przenieść usługi {$v_srv->ID}";
							} else {
								$log_arr []= "przeniesiono usługę {$v_srv->ID}";
							}
						}
					} else {
						$sql_obj = new stdClass();
						$sql_obj->ID = $v_srv->ID;
						$sql_obj->HANGUP_STATUS = 'OFF_HARD';
						$sql_obj->HANGUP_FROM = date('Y-m-d');
						$sql_obj->HANGUP_RATIO = 1;
						if ($simulate_db) {
							$simulate_db->add('UPDATE_OBJ', 'SERVICES', $sql_obj);
						} else {
							if ($db->UPDATE_OBJ('SERVICES', $sql_obj) <= 0) {
								//$db->query('ROLLBACK');
								$err_msgs []= "nie udało się wyłączyć usługi " . $v_srv->ID;
							} else {
								$log_arr []= "wyłączono usługę " . $v_srv->ID . " (HANGUP_STATUS na OFF_HARD, HANGUP_FROM: " . date('Y-m-d') . ")";
							}
						}
					}
				}
			}
		}

		foreach ($this->_services as $k_id => $v_srv) {
			if (!$v_srv->save($simulate_db)) {
				//$db->query('ROLLBACK');
				$err_msgs []= "nie udało się dodać usługi dla oferty " . $v_srv->get('ID_OFFERS');
				return false;
			} else {
				if ($simulate_db) {
					$log_arr []= "dodano nowe zadanie " . $v_srv->_saved_id . " dla oferty " . $v_srv->get('ID_OFFERS');
				} else {
					$log_arr []= "dodano nową usługę " . $v_srv->_saved_id . " dla oferty " . $v_srv->get('ID_OFFERS');
				}
			}
		}
		// update DEALS_TABLE.A_STATUS to NORMAL
		$sql_obj= new stdClass();
		$sql_obj->ID = $this->_deal->get('ID');
		$sql_obj->A_STATUS = 'NORMAL';
		if ($simulate_db) {
			$simulate_db->add('UPDATE_OBJ', 'DEALS_TABLE', $sql_obj);
		} else {
			if ($db->UPDATE_OBJ('DEALS_TABLE', $sql_obj) <= 0) {
				//$db->query('ROLLBACK');
				$err_msgs []= "nie udało się aktywować umowy " . $this->_deal->get('ID');
				return false;
			} else {
				$log_arr []= "aktywowano umowę " . $this->_deal->get('ID') . " (status na NORMAL)";
			}
		}

		// update USERS2_DEALS.A_STATUS to NORMAL
		$users2_deals_rows = PokazOfertyHelper::get_users2_deals_by_deal_id($this->_deal->get('ID'), array('A_STATUS'=>'WAITING'));
		foreach ($users2_deals_rows as $v_users2_deal) {
			if ($v_users2_deal->P_OFFER_ID_NEW <= 0) {
				continue;
			}
			if (empty($this->_group->_offers_by_id[$v_users2_deal->P_OFFER_ID_NEW])) {
				continue;
			}
			$v_offer = $this->_group->_offers_by_id[$v_users2_deal->P_OFFER_ID_NEW];
			// find services with offer id
			foreach ($this->_services as $v_srv) {
				if ($v_srv->_saved_id <= 0) {
					continue;
				}
				if ($v_srv->get('ID_OFFERS') == $v_users2_deal->P_OFFER_ID_NEW) {
					$sql_obj = new stdClass();
					$sql_obj->ID = $v_users2_deal->ID;
					$sql_obj->ID_SERVICES_NEW = $v_srv->_saved_id;
					$sql_obj->A_STATUS = 'NORMAL';
					if (empty($v_users2_deal->INICJALY_HANDLOWCA)) {
						$sql_obj->INICJALY_HANDLOWCA = $this->_deal->get('P_DEALPREFIX');
					}
					if (empty($v_users2_deal->S_OTHER_INFO)) {
						$sql_obj->S_OTHER_INFO = $this->_deal->get('DEALDESC');
					}
					if ($simulate_db) {
						$simulate_db->add('UPDATE_OBJ', 'USERS2_DEALS', $sql_obj, array('ID_SERVICES_NEW'=>$v_srv->_saved_id));
					} else {
						if ($db->UPDATE_OBJ('USERS2_DEALS', $sql_obj) <= 0) {
							//$db->query('ROLLBACK');
						} else {
							$log_arr []= "zmieniono rekord w USERS2_DEALS " . $v_users2_deal->ID . " (status na NORMAL oraz ID_SERVICES_NEW na " . $v_srv->_saved_id . ")";
						}
					}
				}
			}
		}

		//$db->query('COMMIT');
		return true;
	}

}

class Column_deals_table extends Column_Base {

	var $_user;
	var $_group;
	var $_users2_deals_rows;
	var $_offers_rows;
	var $_srv_to_create;// [ID_OFFER => P_SERVICE('NET', 'TV', 'TEL')]
	var $_services;
	var $_old_offers_ids;

	function __construct() {
		parent::__construct();

		$this->_data['ID_BILLING_USERS'] = '';// 
		$this->_data['P_DEALPREFIX'] = '';// 
		$this->_data['P_DEALNUMBER'] = '';// 
		$this->_data['P_DEALNUMBER_OLD'] = '';// 
		$this->_data['P_DEALDATE'] = '';// 
		$this->_data['P_DEALDATE_TERM'] = '';// 
		$this->_data['ANEX_NEEDED'] = '';// 
		$this->_data['ANEX_CONFIRM_DATE'] = '';// 
		$this->_data['DEALDESC'] = '';// 
		$this->_data['A_STATUS'] = 'WAITING';// 
		$this->_data['ID_OFFERS_GROUP'] = '';// 
		$this->_data['S_ADDRESS_STREET'] = '';// 
		$this->_data['P_ID'] = 0;

		$this->_group = null;
		$this->_users2_deals_rows = array();
		$this->_offers_rows = array();
		$this->_old_offers_ids = array();
	}

	function get_type() {
		$type = '';
		$types = array();
		$types []= 'ACTIVATE_OPTIONS';
		$types []= 'DEACTIVATE_OPTIONS';
		$types []= 'NEW_DEAL';
		$types []= 'ANEKS';
		$types []= 'REZYGNACJA';
		//$types []= 'UNKNOWN';// error unknown type
		if ($this->get('P_ID') > 0) {
			// dotyczy aktywacji nowych ofert lub deaktywacji opcji
			$id_offers_on = $this->get('ID_OFFERS_ON');
			$id_offers_off = $this->get('ID_OFFERS_OFF');
			if (!empty($id_offers_on)) {
				$type = 'ACTIVATE_OPTIONS';
			}
			else if (!empty($id_offers_off)) {
				$type = 'DEACTIVATE_OPTIONS';
			}
		}
		else {// P_ID == 0 - nowa umowa, aneks, rezygnacja
			if ($this->get('P_DEALNUMBER_OLD') > 0) {
				if ($this->get('P_DEALNUMBER') > 0) {
					$type = 'ANEKS';
				}
				else {
					$type = 'REZYGNACJA';
				}
			}
			else {
				$type = 'NEW_DEAL';
			}
		}
		return $type;
	}

	function set_user_data($user) {
		$this->_user = $user;

		$this->_data['ID_BILLING_USERS'] = $this->_user->ID_BILLING_USERS;
	}

	function set_new_deal_data($group) {
		$this->_group = $group;
		$this->_data['ID_OFFERS_GROUP'] = $this->_group->get('ID');
		$this->_data['P_DEALDATE'] = date("Y-m-d");
		$this->_data['P_DEALDATE_TERM'] = date("Y-m-d", mktime(0,0,0, date('m') + $this->_group->get('P_DEALTERM_MONTHS'), date('d') - 1, date('Y')));
	}

	function set_s_address_street($street) {
		$this->_data['S_ADDRESS_STREET'] = $street;
	}

	function generate_P_DEALNUMBER() {
		$db = DB::getDB();
		// sql from l2: ./modules/webone/form/edit_user_status.php
		// $sql="select  ifnull(max(DEALS_TABLE.ID),1)+1 as NEXTID, ifnull(MAX(DEALS_TABLE.P_DEALNUMBER),1)+1 as NEXTNUMBER , now() as TERAZ from DEALS_TABLE ";
		$sql = "select ifnull(MAX(DEALS_TABLE.P_DEALNUMBER),1)+1 as NEXTNUMBER from `DEALS_TABLE` ";
		$res = $db->query($sql);
		if ($r = $db->fetch($res)) {
			$this->_data['P_DEALNUMBER'] = $r->NEXTNUMBER;
		}
	}

	function view_table() {
		echo '<form action="#" method="post" id="deal_form_deals_table" name="deal_form_deals_table">';
		echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
		echo '<thead><tr>';
		foreach ($this->_data as $k_field_name => $v_value) {
			echo '<th>' . str_replace('_', ' ', $k_field_name) . '</th>';
		}
		echo '</tr></thead>';
		echo '<tbody>';
		echo '<tr>';
		foreach ($this->_data as $k_field_name => $v_value) {
			if (!empty($v_value)) {
				echo '<td>' . $v_value . '</td>';
			} else {
				$html_field_id = 'DEALS_TABLE-' . $k_field_name;
				echo '<td>' . '<input type="text" name="' . $html_field_id . '"  id="' . $html_field_id . '" readonly="reaonly" value="" style="width:100%;border:none" />' . '</td>';
			}
		}
		echo '</tr>';
		echo '</tbody>';
		echo '</table>';
		echo '</form>';
	}

	function set_from_raw_data($deal_row) {
		foreach ($deal_row as $k_field_name => $v_value) {
			$this->_data[$k_field_name] = $v_value;
		}
	}

	function fetch_users2_deals_rows() {
		$db = DB::getDB();
		$deal_id = $this->get('ID');
		if ($deal_id <= 0) {
			return;
		}
		$sql = "select d.`ID`
				, d.`DATA_DOK`
				, d.`S_ADDRESS_STREET`
				-- , d.`S_OTHER_INFO`
				-- , d.`T_WORKPOINTS_PROCES`
				-- , d.`T_PENALTIES_TYPE`
				, d.`ID_BILLING_USERS_OLD`
				, d.`ID_BILLING_USERS_NEW`
				, d.`ID_SERVICES_OLD`
				, d.`ID_SERVICES_NEW`
				, d.`P_SERVICE`
				-- , d.`P_SERVICE_COMPANY`
				, d.`P_SERVICE_NAME`
				, d.`P_OFFER_ID_OLD`
				, d.`P_OFFER_ID_NEW`
				, d.`P_DEAL_DATE_OLD`
				, d.`P_DEAL_DATE_NEW`
				, d.`P_DEALNUMBER_OLD`
				, d.`P_DEALNUMBER_NEW`
				, d.`P_DEALTERM_OLD`
				, d.`P_DEALTERM_NEW`
				, d.`MONTH_COST_OLD`
				, d.`MONTH_COST_NEW`
				, d.`INICJALY_HANDLOWCA`
				, d.`RODZAJ_DZIALANIA_HANDLOWEGO`
				-- , d.`OLD_L2_HANGUP_STATUS`
				-- , d.`OLD_L2_HANGUP_FROM`
				, d.`P_ACCOUNT`
			from `USERS2_DEALS` as d
			where d.`P_DEALNUMBER_NEW`='" . $deal_id . "'
				and d.`A_STATUS`='WAITING'
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$users2_deal = new Column_users2_deals();
			$users2_deal->set_from_raw_data($r);
			$this->_users2_deals_rows [$r->ID]= $users2_deal;
		}
	}

	function fetch_offers_rows() {
		$db = DB::getDB();
		$deal_id = $this->get('ID');
		if ($deal_id <= 0) {
			return;
		}
		$offers_ids = array();
		if (!empty($this->_users2_deals_rows)) {
			foreach ($this->_users2_deals_rows as $v_users2_deal) {
				if ($v_users2_deal->get('P_OFFER_ID_NEW') > 0) {
					$offers_ids []= $v_users2_deal->get('P_OFFER_ID_NEW');
				}
			}
		}
		if (empty($offers_ids)) {
			return;
		}
		$this->_offers_rows = PokazOfertyHelper::get_offers_by_id($offers_ids);
	}

	function get_offers_by_id() {
		if ($this->_group) {
			return $this->_group->get_offers_by_id();
		} else {
			return $this->_offers_rows;
		}
	}

	function get_offers_ids() {
		if ($this->_group) {
			return $this->_group->get_offers_ids();
		} else {
			$offers_ids = array();
			return $offers_ids;
		}
	}

	function set_old_offers_ids($old_offers_ids) {
		$this->_old_offers_ids = $old_offers_ids;
	}

	function fetch_group_row() {
		$db = DB::getDB();
		if ($this->get('ID') <= 0) {
			return;
		}
		$group_id = (int)$this->get('ID_OFFERS_GROUP');
		if ($group_id <= 0) {
			return;
		}
		$this->_group = PokazOfertyHelper::get_group($group_id);
		$this->_group->set_offers($this->_offers_rows);
	}

	function get_services_map() {
/* fields map:
 * SERVICES
 * 		ID_BILLING_USERS						$this->_user->ID_BILLING_USERS
 * 		ID_DEALS_TABLE							$this->get('ID')
 * 		ID_OFFERS										$this->_offers_rows[ID]->ID
 * 		NAME_LIST_SERVICES					USERS2, TV, VOIP
 * 		A_STATUS										WAITING
 * 		active											1
 * 		SERVICE_TYPE								ABONAMENT
 * 		ID_BILLING_NUMBERS_TYPE			1
 * 		ABONAMENT_PERIOD						1
 * 		ABONAMENT_VALUE							$this->_offers_rows[ID]->P_PROMO_MONTH_PRICE_NETTO - netto w promocyjnych miesiącach
 * 				lub P_CONTRACT_PRICE_NETTO + rekordy w SES_X_C po P_DEALTERM_MONTHS (VALUE1), TYP 17, róznice NETTO z ceną P_PROMO_MONTH_PRICE_NETTO (VALUE2)
 * 		VAT													$this->_offers_rows[ID]->STAWKA_VAT - vat (int)
 * 		ID_CURRENCY									0
 * 		ABONAMENT_PAYMENT						UP
 * 		ABONAMENT_START							1
 * 		MINIMUM_BILLING_VALUE				0.00
 * 		BILLED_TILL									NULL
 * 		HANGUP_FROM									NULL
 * 		HANGUP_TILL									NULL
 * 		HANGUP_STATUS								NULL
 * 		HANGUP_RATIO								1.00
 * 		P_ID_SERVICES								0 lub parent services ID
 * 		uwagi												''
 * 		VAT_NAME										'ZW',8,23
 * 		id_list_sww									(int) ??
 * 		SERV_ID_BILLING_PREFIXES		0
 * TODO: VAT czasem jest 0 i VAT_NAME na ZW
 * 
 * SES_USERS2_A
 * 		ID_BILLING_USERS					user.ID
 * 		ID_SERVICES								SERVICES.ID
 * 		P_SERVICE_QUOTA_PROFILE		$this->_offers_rows[ID]->P_SERVICE_QUOTA_PROFILE
 * 		LAN_DOWNLOAD							$this->_offers_rows[ID]->LAN_DOWNLOAD
 * 		S_PUBLIC_IP								$this->_offers_rows[ID]->S_PUBLIC_IP
 * 		S_SOHO_WIFI_ROUTER_1292		$this->_offers_rows[ID]->S_SOHO_WIFI_ROUTER_1292
 * 		S_E_PORT_1293							$this->_offers_rows[ID]->S_E_PORT_1293
 * 		CONN_DIV									$this->_offers_rows[ID]->CONN_DIV
 * SES_TV_A
 * 		P_DEVICE													$this->_offers_rows[ID]->P_DEVICE
 * 		P_SERVICE_CLASS										$this->_offers_rows[ID]->P_SERVICE_CLASS
 * 		P_SERVICE_SOCKETS_AMMOUNT_1298		$this->_offers_rows[ID]->P_SERVICE_SOCKETS_AMMOUNT_1298
 * 		ID_DOMAINS_PACKET_ID	$this->_offers_rows[ID]->ID_DOMAINS_PACKET_ID
 * 		ID_DOMAINS						$this->_offers_rows[ID]->ID_DOMAINS
 * SES_VOIP_A
 * 		ID_DOMAINS_PACKET_ID	$this->_offers_rows[ID]->ID_DOMAINS_PACKET_ID
 * 		VOIP_FAX2EMAIL				$this->_offers_rows[ID]->VOIP_FAX2EMAIL
 * 		ID_DOMAINS						$this->_offers_rows[ID]->ID_DOMAINS
 */

/*
 * SES_TV_A
 * SES_USERS2_A
 * SES_VOIP_A
 * 
 * SES_DOMAINS_A
 * SES_EMAIL_A
 * SES_E_WLAN_A
 * SES_INSTALL_A
 * SES_SERWIS_A
 * SES_WWW_A
 * SES_WWW_MASS_A
 */
		$name_list_services_map = array();
		$name_list_services_map['NET'] = 'USERS2';
		$name_list_services_map['TEL'] = 'VOIP';// TOOD: wymaga SES_USERS2_A jako podrzedna do VOIP
		$name_list_services_map['TV'] = 'TV';
		$name_list_services_map['TVC'] = 'TV';
		$name_list_services_map['TVCP'] = 'TV';

		$map = array();
		$map['TV'] = 'TV';
		$map['TVC'] = 'TV';
		$map['TVCP'] = 'TV';
		$map['NET'] = 'USERS2';
		$map['TEL'] = 'VOIP';// TOOD: wymaga SES_USERS2_A jako podrzedna do VOIP
		//$map['OPCJE-NET'] = 'NET';
		//$map['OPCJE-TV'] = 'TV';
		//$map['OPCJE-TVC'] = 'TV';
		//$map['OPCJE-TVCP'] = 'TV';
		//$map['OPCJE-TEL'] = 'TEL';
		return $map;
	}

	function print_html_data() {

		$cols = array_keys($this->_data);
		PokazOfertyView::print_simple_tbl((object)$this->_data, $cols, 'DEALS_TABLE');

		PokazOfertyView::print_simple_tbl((object)$this->_group->get_data(), $this->_group->get_cols(), 'USERS2_OFFERS_GROUPS');

		$cols = array_keys(get_object_vars(reset($this->_offers_rows)));
		// hide P_SERVICE_QUOTA_PROFILE
		if (in_array('P_SERVICE_QUOTA_PROFILE', $cols)) {
			$new_cols = array();
			foreach ($cols as $v_col) {
				if ($v_col == 'P_SERVICE_QUOTA_PROFILE') {
					continue;
				}
				$new_cols []= $v_col;
			}
			$cols = $new_cols;
		}
		echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
		PokazOfertyView::print_simple_tbl_header($cols, 'USERS2_OFFERS');
		echo '<tbody>';
		$t = 0;
		foreach ($this->_offers_rows as $k_id => $v_offer) {
			PokazOfertyView::print_simple_tbl_body_row($v_offer, $cols, array('class'=>'row-' . ($t = 1 - $t)));
		}
		echo '</tbody>';
		echo '</table>';

		$cols = array_keys(reset($this->_users2_deals_rows)->get_data());
		echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
		PokazOfertyView::print_simple_tbl_header($cols, 'USERS2_DEALS');
		echo '<tbody>';
		$t = 0;
		foreach ($this->_users2_deals_rows as $k_id => $v_obj) {
			PokazOfertyView::print_simple_tbl_body_row((object)$v_obj->get_data(), $cols, array('class'=>'row-' . ($t = 1 - $t)));
		}
		echo '</tbody>';
		echo '</table>';
	}

	/**
	 * @return int created record id
	 */
	function create() {
		// aneks i nowa umowa - tak samo jak nowa umowa
		$sql_data = array();
		foreach ($this->_data as $k => $v) {
			if ($k == 'P_DEALNUMBER') {
				continue;
			}
			if (!empty($v)) {
				$sql_data["`" . $k . "`"] = "'" . $v . "'";
			}
		}
		// insert query
		$db = DB::getDB();
		$sql_data["`P_DEALNUMBER`"] = "(ifnull(MAX(DEALS_TABLE.P_DEALNUMBER),1)+1)";
		$sql_data["`A_RECORD_CREATE_DATE`"] = "'" . date('Y-m-d-H:i') . "'";
		$sql_data["`A_RECORD_CREATE_AUTHOR`"] = "'" . User::getName() . "'";

		$offers_ids = $this->get_offers_ids();
		if (!empty($offers_ids)) {
			$sql_data["`ID_OFFERS_ON`"] = "'" . implode(",", $offers_ids) . "'";
		}
		if (!empty($this->_old_offers_ids)) {
			$sql_data["`ID_OFFERS_OFF`"] = "'" . implode(",", $this->_old_offers_ids) . "'";
		}
		$sql = "insert into `DEALS_TABLE` (" . implode(", ", array_keys($sql_data)) . ") select " . implode(", ", array_values($sql_data)) . " from `DEALS_TABLE`; ";
//insert into `DEALS_TABLE` (`ID_BILLING_USERS`, `P_DEALDATE`, `P_DEALDATE_TERM`, `A_STATUS`, `ID_OFFERS_GROUP`, `S_ADDRESS_STREET`, `P_DEALNUMBER`) select '5861', '2013-01-28', '2015-01-27', 'WAITING', '2044', 'MWZ24A/22', (ifnull(MAX(DEALS_TABLE.P_DEALNUMBER),1)+1) from `DEALS_TABLE`; 
		if (!$db->query($sql)) {
			return false;
		}
		return $db->insert_id();
	}

	function create_opcje_aktywacja() {
		$db = DB::getDB();
		$sql_data["`A_RECORD_CREATE_DATE`"] = "'" . date('Y-m-d-H:i') . "'";
		$sql_data["`A_RECORD_CREATE_AUTHOR`"] = "'" . User::getName() . "'";
		$sql_data["`P_ID`"] = "'" . $this->get('P_ID') . "'";
		$sql_data["`ID_BILLING_USERS`"] = "'" . $this->get('ID_BILLING_USERS') . "'";
		$sql_data["`DEALDESC`"] = "'" . $this->get('DEALDESC') . "'";
		$sql_data["`S_ADDRESS_STREET`"] = "'" . $this->get('S_ADDRESS_STREET') . "'";

		$offers_ids = array_keys($this->_offers_rows);
		if (!empty($offers_ids)) {
			$sql_data["`ID_OFFERS_ON`"] = "'" . implode(",", $offers_ids) . "'";
		}
		$sql = "insert into `DEALS_TABLE` (" . implode(", ", array_keys($sql_data)) . ") values (" . implode(", ", array_values($sql_data)) . ") ; ";
		if (!$db->query($sql)) {
			return false;
		}
		return $db->insert_id();
	}

	function create_opcje_deaktywacja() {
		$db = DB::getDB();
		$sql_data["`A_RECORD_CREATE_DATE`"] = "'" . date('Y-m-d-H:i') . "'";
		$sql_data["`A_RECORD_CREATE_AUTHOR`"] = "'" . User::getName() . "'";
		$sql_data["`P_ID`"] = "'" . $this->get('P_ID') . "'";
		$sql_data["`ID_BILLING_USERS`"] = "'" . $this->get('ID_BILLING_USERS') . "'";
		$sql_data["`DEALDESC`"] = "'" . $this->get('DEALDESC') . "'";
		$sql_data["`S_ADDRESS_STREET`"] = "'" . $this->get('S_ADDRESS_STREET') . "'";

		$offers_ids = array_keys($this->_offers_rows);
		if (!empty($offers_ids)) {
			$sql_data["`ID_OFFERS_OFF`"] = "'" . implode(",", $offers_ids) . "'";
		}
		$sql = "insert into `DEALS_TABLE` (" . implode(", ", array_keys($sql_data)) . ") values (" . implode(", ", array_values($sql_data)) . ") ; ";
		if (!$db->query($sql)) {
			return false;
		}
		return $db->insert_id();
	}

}

class Column_users2_deals extends Column_Base {

	var $_new_deal;
	var $_old_fields;
	var $_offer_values_map;// TODO: tylko dla nowych ofert - pola *_NEW
	var $_deal_table;// @see set_deal_table
	var $_old_deal;
	var $_old_deals_data;
	var $_old_srv_data;
	var $_new_srv_data;// @from _group->offers

	/**
	 * Mapa starych uslug do ID z nowych ofert wg ID umowy
	 * Array [deal_ID][srv_ID] = offer_ID;
	 * @used in generate_srv_map()
	 */
	var $_old_srv_map;

	function __construct() {
		parent::__construct();
		$this->_data['DATA_DOK'] = '';// now()
		$this->_data['S_ADDRESS_STREET'] = '';// Ulica na ktorej swiadczona jest usluga
		$this->_data['S_OTHER_INFO'] = '';// Dodatkowe informacje do rejestru rozmow
		//$this->_data['T_WORKPOINTS_PROCES'] = '';
		//$this->_data['T_PENALTIES_TYPE'] = '';
		$this->_data['ID_BILLING_USERS_OLD'] = '';// Poprzedni numer klienta wg bazy L1/L2 (numer billingowy)
		$this->_data['ID_BILLING_USERS_NEW'] = '';// Nowy numer klienta wg bazy L1/L2 (numer billingowy)
		$this->_data['ID_SERVICES_OLD'] = '';// Poprzedni numer uslugi wg bazy l1/l2 (numer ID_SERVICES)
		$this->_data['ID_SERVICES_NEW'] = '';// Nowy numer uslugi wg bazy l1/l2 (numer ID_SERVICES)
		$this->_data['P_SERVICE'] = '';// Wybierz jakiego rodzaju uslugi dotyczy wpisywany rekord
		//$this->_data['P_SERVICE_COMPANY'] = '';// TODO: from $this->_deal_table->_group->get('P_SERVICE_COMPANY') - Firma swiadczaca usluge (enum('BN', 'NETDAY'))
		$this->_data['P_SERVICE_NAME'] = '';// Nazwa zwyczajna uslugi ktorej dotyczy rekord
		$this->_data['P_OFFER_ID_OLD'] = '';// Numer oferty/uslugi poprzedniej uslugi
		$this->_data['P_OFFER_ID_NEW'] = '';// Numer oferty/uslugi aktualnie podpisywanej uslugi
		$this->_data['P_DEAL_DATE_OLD'] = '';// Data ostatniego dokumentu/aneksu wg ktorego jest dokonywany wpis
		$this->_data['P_DEAL_DATE_NEW'] = '';// Aktualna data umowy / nowej umowy/ aneksu
		$this->_data['P_DEALNUMBER_OLD'] = '';// Numer umowy ostatnio obowiazujacej
		$this->_data['P_DEALNUMBER_NEW'] = '';// Numer umowy aktualnie obowiazujacej
		$this->_data['P_DEALTERM_OLD'] = '';// Termin w RRRR-MM-DD do ktorego byla wazna ostatnia umowa
		$this->_data['P_DEALTERM_NEW'] = '';// Nowy termin w formacie RRRR-MM-DD do ktorego jest wazny aktualny rekord
		$this->_data['MONTH_COST_OLD'] = '';// Poprzednia wartosc miesieczna kompletu uslug ktore opisywala umowa/aneks
		$this->_data['MONTH_COST_NEW'] = '';// Aktualna wartosc miesieczna kompletu uslug, ktore opisuje dana umowa/aneks
		$this->_data['INICJALY_HANDLOWCA'] = '';// Inicjaly handlowca i Jak klient do nas trafil (U-ulotka,R-plakat),L-List_intencyjny,Z-rywka-plakat)np DM/U
		$this->_data['RODZAJ_DZIALANIA_HANDLOWEGO'] = '';// Rodzaj dzialania w wyniku ktorego doszlo do podpisania niniejszej umowy/aneksu';
		//$this->_data['OLD_L2_HANGUP_STATUS'] = '';
		//$this->_data['OLD_L2_HANGUP_FROM'] = '';
		$this->_data['P_ACCOUNT'] = '';

		$this->_old_fields = array();
		$this->_old_fields['ID_BILLING_USERS_OLD'] = 'ID_BILLING_USERS';
		$this->_old_fields['ID_SERVICES_OLD'] = 'ID_SERVICES';
		$this->_old_fields['P_OFFER_ID_OLD'] = 'OFFER_ID';
		$this->_old_fields['P_DEAL_DATE_OLD'] = 'P_DEAL_DATE';
		$this->_old_fields['P_DEALNUMBER_OLD'] = 'P_DEALNUMBER';
		$this->_old_fields['MONTH_COST_OLD'] = 'MONTH_COST';

		$this->_offer_values_map = array();
		$this->_offer_values_map['P_OFFER_ID_NEW'] = 'ID';
		$this->_offer_values_map['P_SERVICE'] = 'P_SERVICE';
		$this->_offer_values_map['P_SERVICE_NAME'] = 'P_SERVICE_NAME';
		$this->_offer_values_map['MONTH_COST_NEW'] = 'srednia_netto';// TODO: sprawdzic czy zgodnie z zalozeniami - uzywane do rozliczen

		$this->_deal_table = null;
		$this->_old_services = array();
		$this->_old_srv_map = array();// [DEAL_ID][SRV_ID] = [OFFER_ID]
		$this->_old_srv_data = array();// [DEAL_ID][SRV_ID] = {srv}
		$this->_new_srv_data = array();// [] = [srv data]
	}

	function set_s_address_street($street) {
		$this->_data['S_ADDRESS_STREET'] = $street;
	}

	function set_p_dealnumber_new($deal_nr) {
		$this->_data['P_DEALNUMBER_NEW'] = $deal_nr;
	}

	function set_deal_table($deals_table) {
		$this->_deal_table = $deals_table;
		$this->_data['ID_BILLING_USERS_NEW'] = $this->_deal_table->get('ID_BILLING_USERS');
		$this->_data['P_DEALNUMBER_NEW'] = 'TODO';// TODO: created ID in deals_table
		$this->_data['DATA_DOK'] = $this->_deal_table->get('P_DEALDATE');
		$this->_data['P_DEAL_DATE_NEW'] = $this->_deal_table->get('P_DEALDATE');
		$this->_data['P_DEALTERM_NEW'] = $this->_deal_table->get('P_DEALDATE_TERM');
		$this->_data['INICJALY_HANDLOWCA'] = $this->_deal_table->get('P_DEALPREFIX');
		$this->_data['S_OTHER_INFO'] = $this->_deal_table->get('DEALDESC');

		if ($this->_deal_table->_group) {
			$this->_data['P_SERVICE_COMPANY'] = $this->_deal_table->_group->get('P_SERVICE_COMPANY');
		}
	}

	function set_from_raw_data($users2_deal_row) {
		foreach ($users2_deal_row as $k_field_name => $v_value) {
			$this->_data[$k_field_name] = $v_value;
		}
	}

	function view_table() {
		echo '<form action="#" method="post" id="deal_form_users2_deals" name="deal_form_users2_deals">';
		echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view podglad-users2_deals">';
		echo '<thead><tr>';
		foreach ($this->_data as $k_field_name => $v_value) {
			echo '<th>' . str_replace('_', ' ', $k_field_name) . '</th>';
		}
		echo '</tr></thead>';
		echo '<tbody>';
		// $group->_offers [$v_p_service] [$v_offer->ID] = $v_offer;
		foreach ($this->_deal_table->_group->get_offers_by_id() as $k_offer_id => $v_offer) {
			echo '<tr>';
			foreach ($this->_data as $k_field_name => $v_value) {
				$out_value = '';
				if (array_key_exists($k_field_name, $this->_offer_values_map)) {
					$offer_field_name = $this->_offer_values_map[$k_field_name];
					$out_value .= $v_offer->$offer_field_name;
					if (strlen($out_value) > 20) {
						$out_value = '<span title="' . htmlspecialchars($out_value) . '">' . substr($out_value, 0, 20) . "..." . '</span>';
					}
				} else if (!empty($v_value)) {
					$out_value .= $v_value;
					if (strlen($out_value) > 20) {
						$out_value = '<span title="' . htmlspecialchars($out_value) . '">' . substr($out_value, 0, 20) . "..." . '</span>';
					}
				} else {
					$html_field_id = 'NEW_OFFER-' . $v_offer->ID . '-' . $k_field_name;
					$out_value .= '<input type="hidden" name="' . $html_field_id . '" readonly="reaonly" value="" style="width:100%;border:none;" />';
					$out_value .= '<span id="' . $html_field_id . '">' . "&nbsp;" . '</span>';
				}
				echo '<td class="' . $k_field_name . '">' . $out_value . '</td>';
			}
			echo '</tr>';
		}

		// $this->_old_srv_map[$v_deal->ID_DEALS][$v_srv->ID] = $new_offer_id;
		foreach ($this->_old_srv_map as $k_id_deal => $v_map_arr) {
			foreach ($v_map_arr as $k_srv_id => $v_offer_id) {
				if ($v_offer_id > 0) continue;
				$out_tr_id = 'OLD_DEAL-' . $k_id_deal;
				echo '<tr id="' . $out_tr_id . '" class="old-deal">';
				foreach ($this->_data as $k_field_name => $v_value) {
					$out_value = '';

					$v_srv = $this->_old_srv_data[$k_id_deal][$k_srv_id];
					switch ($k_field_name) {
						case 'ID_SERVICES_OLD':
							$out_value = $v_srv->ID;
							break;
						case 'P_SERVICE':
							$out_value = $v_srv->offer_p_service;
							break;
						case 'P_OFFER_ID_OLD':
							$out_value = $v_srv->ID_OFFERS;
							break;
						case 'P_OFFER_ID_NEW':
						case 'ID_SERVICES_NEW':
						case 'MONTH_COST_NEW':
							$out_value = 0;
							break;
						case 'P_DEALNUMBER_NEW':
							$out_value = 0;
							$v_value = '';
							break;
						case 'P_DEAL_DATE_OLD':
							$out_value = $this->_old_deals_data[$k_id_deal]->P_DEALDATE;
							break;
						case 'P_DEALTERM_OLD':
							$out_value = $this->_old_deals_data[$k_id_deal]->P_DEALDATE_TERM;
							break;
						case 'P_DEALNUMBER_OLD':
							$out_value = $this->_old_deals_data[$k_id_deal]->ID_DEALS;
							break;
						case 'MONTH_COST_OLD':
							$out_value = $v_srv->ABONAMENT_VALUE;
							break;
						default:
							
					}

					if (!empty($v_value)) {
						$out_value .= $v_value;
						if (strlen($out_value) > 20) {
							$out_value = '<span title="' . htmlspecialchars($out_value) . '">' . substr($out_value, 0, 20) . "..." . '</span>';
						}
					}
					echo '<td class="' . $k_field_name . '">' . $out_value . '</td>';
				}
				echo '</tr>';// .old-deal
			}
		}
		echo '</tbody>';
		echo '</table>';
		echo '</form>';
	}

	function get_old_deal_data() {
		return $this->_old_deals_data;
	}

	function get_old_srv_data($old_deal_id) {
		return (array_key_exists($old_deal_id, $this->_old_srv_data))? $this->_old_srv_data[$old_deal_id] : array();
	}

	function set_old_deals_data($old_deals_by_id) {
		$this->_old_deals_data = $old_deals_by_id;
	}

	function get_srv_map() {
		return $this->_old_srv_map;
	}

	/**
	 * Numery ofert do wyłączenia zgodnie z numerem starej umowy 
	 * (P_DEALNUMBER_OLD) oraz wygenerowaną mapą (srv_map)
	 */
	function get_old_offers_ids() {
		$old_offers_ids = array();
		if (!empty($this->_old_srv_map) && !empty($this->_old_deal)) {
			$p_dealnumber_old = $this->get('P_DEALNUMBER_OLD');
			if (array_key_exists($p_dealnumber_old, $this->_old_srv_map)) {
				$srv_map = $this->_old_srv_map[$p_dealnumber_old];
				if (!empty($srv_map)) {
					foreach ($srv_map as $srv_id => $new_offer_id) {
						//if ($new_offer_id > 0) {// TODO: sprawdzić warunek
							$old_srv_row = $this->_old_deal->services_by_id[$srv_id];
							if ($old_srv_row->ID_OFFERS > 0) {
								$old_offers_ids []= $old_srv_row->ID_OFFERS;
							} else {
								echo '<p style="color:red">' . "Error: brak numeru oferty w SERVICES ID=" . $srv_id . '</p>';
							}
						//}
					}
				}
			}
		}
		return $old_offers_ids;
	}

	/**
	 * Generate $this->_old_srv_map - [deals_ID][srv_ID] = offer_ID;
	 */
	function generate_srv_map() {
		if (empty($this->_old_deals_data)) return;
		// TODO: map old deals to new deals
		foreach ($this->_old_deals_data as $k_deal_id => $v_deal) {
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none">v_deal (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($v_deal);echo'</pre>';
			// $this->services[TV][20495]->out_id = TVCP_1
			// $this->services[TV][20495]->offer_p_service = NET, TV, TVC, TVCP
			foreach ($v_deal->services as $k_p_service => $v_srv_arr) {
				foreach ($v_srv_arr as $k_srv_id => $v_srv) {
					$v_srv->ses_x_a = $v_deal->ses_x_a[$v_srv->ID];
					$this->_old_srv_data [$v_deal->ID_DEALS] [$v_srv->ID] = $v_srv;
				}
			}
echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;display:none">_old_srv_data (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_old_srv_data);echo'</pre>';
			// $this->_deal_table->_group->_offers[NET_1][1383]->out_id = NET_1, OPCJA_NET_1, OPCJA_NET_2, TV_1, OPCJA_TV_1, OPCJA_TV_2, TVC_1, TEL_1, OPCJA_TEL_1
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none"> (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_deal_table->_group);echo'</pre>';
			foreach ($this->_deal_table->_group->get_offers_by_id() as $v_offer) {
				if ($v_offer->P_SERVICE_PARENT != '') {// opcja
					if ($v_offer->ID_DOMAINS == '' && $v_offer->ID_DOMAINS_PACKET_ID == '') {
						// pomin - ta oferta jest tylko opcją i nie wchodzi jako osobny SERVICES
						continue;
					}
				}
				$this->_new_srv_data [$v_offer->ID]= $v_offer;
			}
echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;display:none">_new_srv_data ['.count($this->_new_srv_data).'] (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_new_srv_data);echo'</pre>';
			// set up $this->_old_srv_map
			$this->_old_srv_map[$v_deal->ID_DEALS] = array();
			$used_offer_ids = array();// id offers => id srv
			foreach ($this->_old_srv_data[$v_deal->ID_DEALS] as $k_srv_id => $v_srv) {
				$new_offer_id = 0;
				foreach ($this->_new_srv_data as $k_offer_id => $v_offer) {
					if (in_array($k_offer_id, $used_offer_ids) || $new_offer_id > 0) {
						continue;
					}
					// try if new offer match old service
					if ($v_srv->NAME_LIST_SERVICES == 'USERS2') {
						if ($v_offer->P_SERVICE == 'NET') {
							$new_offer_id = $k_offer_id;
							$used_offer_ids []= $k_offer_id;
						}
					} else if ($v_srv->NAME_LIST_SERVICES == 'VOIP') {
						if ($v_offer->P_SERVICE == 'TEL') {
							$new_offer_id = $k_offer_id;
							$used_offer_ids []= $k_offer_id;
						}
					} else if ($v_srv->NAME_LIST_SERVICES == 'TV') {
						if ($v_offer->P_SERVICE == $v_srv->ses_x_a->P_SERVICE_CLASS
								|| ($v_offer->P_SERVICE == 'OPCJE' && $v_offer->P_SERVICE_PARENT == 'TV')
						) {// TV, TVC, TVCP
							if ($v_offer->ID_DOMAINS != '' && $v_offer->ID_DOMAINS_PACKET_ID > 0) {
								//echo '{'.$v_offer->ID_DOMAINS.' == '.$v_srv->ses_x_a->ID_DOMAINS.' && '.$v_offer->ID_DOMAINS_PACKET_ID.' == '.$v_srv->ses_x_a->ID_DOMAINS_PACKET_ID.'}<br />';
								if ($v_offer->ID_DOMAINS == $v_srv->ses_x_a->ID_DOMAINS && $v_offer->ID_DOMAINS_PACKET_ID == $v_srv->ses_x_a->ID_DOMAINS_PACKET_ID) {
									$new_offer_id = $k_offer_id;
									$used_offer_ids []= $k_offer_id;
								}
							} else {
								$new_offer_id = $k_offer_id;
								$used_offer_ids []= $k_offer_id;
							}
						}
					}
				}
				$this->_old_srv_map[$v_deal->ID_DEALS][$v_srv->ID] = $new_offer_id;
			}
echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;display:none">_old_srv_map['.$v_deal->ID_DEALS.']['.count($this->_old_srv_map[$v_deal->ID_DEALS]).'] (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_old_srv_map[$v_deal->ID_DEALS]);echo'</pre>';
		}
	}

	function set_old_deal($old_deal) {
		$this->_old_deal = $old_deal;

		$this->set('ID_BILLING_USERS_OLD', $this->_old_deal->ID_BILLING_USERS);
		$this->set('P_DEALNUMBER_OLD', $this->_old_deal->ID_DEALS);
		$this->set('P_DEAL_DATE_OLD', $this->_old_deal->P_DEALDATE);
		$this->set('P_DEALTERM_OLD', $this->_old_deal->P_DEALDATE_TERM);
	}

	/**
	 * Create rows test
	 * @use $this->_old_deal for aneks
	 * 
	 * @use $this->_old_srv_map[desl_ID][srv_ID] = offer_ID
	 */
	function create_rows_try() {
		$db = DB::getDB();
		$sql_cols = array();
		$sql_insert = array();
		$old_service_all = array();// pola dla starych uslug jesli aneks
		$srv_map = array();// @used if aneks

		$p_dealnumber_old = $this->get('P_DEALNUMBER_OLD');

echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Proba dodania aneksu do umowy ID=' . $this->get('P_DEALNUMBER_OLD') . ' (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this);echo'</pre>';
		// validate
		if ($p_dealnumber_old > 0) {// aneks
			if (empty($this->_old_deal)) {
				echo '<p>' . "Error: Brak danych dotyczących starej umowy P_DEALNUMBER_OLD = " . $p_dealnumber_old . '</p>';
				return -1;
			}
			if (!array_key_exists($p_dealnumber_old, $this->_old_srv_map)) {
				echo '<p>' . "Error: Brak services map dla P_DEALNUMBER_OLD = " . $p_dealnumber_old . '</p>';
				return -1;
			}
			$srv_map = $this->_old_srv_map[$p_dealnumber_old];
		}

		$this->_data['A_RECORD_CREATE_DATE'] = date('Y-m-d-H:i');
		$this->_data['A_RECORD_CREATE_AUTHOR'] = User::getName();
		$this->_data['A_STATUS_INFO'] = 'Wprowadzono automatycznie za pomoca POKAZ_OFERTY_AKTUALNE';

		// dodatkowe dane dla aneksu
		if ($p_dealnumber_old > 0) {// aneks
			$srv_map = $this->_old_srv_map[$p_dealnumber_old];
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">srv_map (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($srv_map);echo'</pre>';
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_old_deal);echo'</pre>';
			if (!empty($srv_map)) {
				foreach ($srv_map as $srv_id => $offer_id) {
echo '<p>{TODO: srv_id = '.$srv_id.'; offer_id = '.$offer_id.'}</p>';
					$old_srv_row = $this->_old_deal->services_by_id[$srv_id];
					$old_srv_data = array();
					$old_srv_data['P_SERVICE'] = V::get('offer_p_service', '', $old_srv_row);
					$old_srv_data['ID_SERVICES_OLD'] = V::get('ID', '', $old_srv_row);
					$old_srv_data['P_OFFER_ID_OLD'] = V::get('ID_OFFERS', '', $old_srv_row);
					$old_srv_data['MONTH_COST_OLD'] = V::get('ABONAMENT_VALUE', '', $old_srv_row);
					$old_service_all[$offer_id] = $old_srv_data;
				}
			}
		}

		// wspolne rekordy dla nowej umowy i aneksu
		foreach ($this->_data as $k_field_name => $v_value) {
			$sql_cols []= "`" . $k_field_name . "`";
		}
		foreach ($this->_deal_table->_group->get_offers() as $k_p_service => $v_offers_arr) {
			$insert_values = array();
			foreach ($v_offers_arr as $k_offer_id => $v_offer) {
				$old_service_data = array();// fields like in $this->_old_fields
				if (array_key_exists($k_offer_id, $old_service_all)) {
					$old_service_data = $old_service_all[$k_offer_id];
				}
				foreach ($this->_data as $k_field_name => $v_value) {
					$out_value = '';
					if (array_key_exists($k_field_name, $this->_offer_values_map)) {
						$offer_field_name = $this->_offer_values_map[$k_field_name];
						$out_value .= $v_offer->$offer_field_name;
					} else if (array_key_exists($k_field_name, $old_service_data)) {
						$out_value .= $old_service_data[$k_field_name];
					} else if (!empty($v_value)) {
						$out_value .= $v_value;
					} else {
						// pozostaw puste
					}
					$insert_values []= "'" . $out_value . "'";
				}
				break;// only one offer by service
			}
			$sql_insert []= "(" . implode(", ", $insert_values) . ")";
		}

		if ($p_dealnumber_old > 0) {// aneks
			if (!empty($srv_map)) {
				foreach ($srv_map as $srv_id => $offer_id) {
					if ($offer_id == 0) {
						if (!array_key_exists($srv_id, $this->_old_deal->services_by_id)) {
							echo '<p style="color:red">' . "Error: brak SERVICES ID=$srv_id w starej umowie" . '</p>';
							continue;
						}

						$old_srv_data = array();
						$old_srv_data['ID_SERVICES_OLD'] = V::get('ID', '', $old_srv_row);
						$old_srv_data['P_OFFER_ID_OLD'] = V::get('ID_OFFERS', '', $old_srv_row);
						$old_srv_data['MONTH_COST_OLD'] = V::get('ABONAMENT_VALUE', '', $old_srv_row);
						$old_srv_data['P_SERVICE'] = V::get('offer_p_service', '', $old_srv_row);

						$insert_values = array();
						foreach ($this->_data as $k_field_name => $v_value) {
							$out_value = '';
							if (array_key_exists($k_field_name, $old_srv_data)) {
								$out_value = $old_srv_data[$k_field_name];
							} else {
								$out_value = $v_value;
							}
							$insert_values []= "'" . $out_value . "'";
						}
						$sql_insert []= "(" . implode(", ", $insert_values) . ")";
					}
				}
			}
		}

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

		if (empty($sql_insert)) {
			return false;
		}
		$sql = "insert into `USERS2_DEALS` (" . implode(", ", $sql_cols) . ") values " . implode("\n\t ,", $sql_insert);
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
		if (!$db->query($sql)) {
			return false;
		}
		return true;
	}

	function create_rows() {
		$db = DB::getDB();
		$sql_cols = array();
		$sql_insert = array();
		$old_service_all = array();// pola dla starych uslug jesli aneks
		$srv_map = array();// @used if aneks

		$p_dealnumber_old = $this->get('P_DEALNUMBER_OLD');

		// validate
		if ($p_dealnumber_old > 0) {// aneks
			if (empty($this->_old_deal)) {
				echo '<p>' . "Error: Brak danych dotyczących starej umowy P_DEALNUMBER_OLD = " . $p_dealnumber_old . '</p>';
				return -1;
			}
			if (!array_key_exists($p_dealnumber_old, $this->_old_srv_map)) {
				echo '<p>' . "Error: Brak services map dla P_DEALNUMBER_OLD = " . $p_dealnumber_old . '</p>';
				return -1;
			}
			$srv_map = $this->_old_srv_map[$p_dealnumber_old];
		}

		$this->_data['A_RECORD_CREATE_DATE'] = date('Y-m-d-H:i');
		$this->_data['A_RECORD_CREATE_AUTHOR'] = User::getName();
		$this->_data['A_STATUS_INFO'] = 'Wprowadzono automatycznie za pomoca POKAZ_OFERTY_AKTUALNE';

		// dodatkowe dane dla aneksu
		if ($p_dealnumber_old > 0) {// aneks
			$srv_map = $this->_old_srv_map[$p_dealnumber_old];
			if (!empty($srv_map)) {
				foreach ($srv_map as $srv_id => $offer_id) {
					if ($offer_id > 0) {
						$old_srv_row = $this->_old_deal->services_by_id[$srv_id];
						$old_srv_data = array();
						$old_srv_data['P_SERVICE'] = V::get('offer_p_service', '', $old_srv_row);
						$old_srv_data['ID_SERVICES_OLD'] = V::get('ID', '', $old_srv_row);
						$old_srv_data['P_OFFER_ID_OLD'] = V::get('ID_OFFERS', '', $old_srv_row);
						$old_srv_data['MONTH_COST_OLD'] = V::get('ABONAMENT_VALUE', '', $old_srv_row);
						$old_service_all[$offer_id] = $old_srv_data;
					}
				}
			}
		}

		// wspolne rekordy dla nowej umowy i aneksu
		foreach ($this->_data as $k_field_name => $v_value) {
			$sql_cols []= "`" . $k_field_name . "`";
		}

		// utworzenie rekordów na podstawie ofert
		foreach ($this->_deal_table->get_offers_by_id() as $k_offer_id => $v_offer) {
			$insert_values = array();
			$old_service_data = array();// fields like in $this->_old_fields
			if (array_key_exists($k_offer_id, $old_service_all)) {
				$old_service_data = $old_service_all[$k_offer_id];
			}
			foreach ($this->_data as $k_field_name => $v_value) {
				$out_value = '';
				if (array_key_exists($k_field_name, $this->_offer_values_map)) {
					$offer_field_name = $this->_offer_values_map[$k_field_name];
					$out_value .= $v_offer->$offer_field_name;// Undefined property: stdClass::$srednia_netto
				} else if (array_key_exists($k_field_name, $old_service_data)) {
					$out_value .= $old_service_data[$k_field_name];
				} else if (!empty($v_value)) {
					$out_value .= $v_value;
				} else {
					// pozostaw puste
				}

				// fix $this->_offer_values_map only for *_NEW fields
				if ($this->_deal_table->get_type() == 'DEACTIVATE_OPTIONS') {
					switch ($k_field_name) {
						case 'P_OFFER_ID_OLD':	$out_value = $v_offer->ID;	break;
						case 'P_OFFER_ID_NEW':	$out_value = '';	break;
						case 'MONTH_COST_OLD':	$out_value = $v_offer->srednia_netto;	break;// Undefined property: stdClass::$srednia_netto
						case 'MONTH_COST_NEW':	$out_value = '';	break;
					}
				}

				$insert_values []= "'" . $out_value . "'";
			}
			if (!empty($insert_values)) {
				$sql_insert []= "(" . implode(", ", $insert_values) . ")";
			}
		}

		if ($p_dealnumber_old > 0) {// aneks
			if (!empty($srv_map)) {
				foreach ($srv_map as $srv_id => $offer_id) {
					if ($offer_id == 0) {
						if (!array_key_exists($srv_id, $this->_old_deal->services_by_id)) {
							echo '<p style="color:red">' . "Error: brak SERVICES ID=$srv_id w starej umowie" . '</p>';
							continue;
						}

						$old_srv_row = $this->_old_deal->services_by_id[$srv_id];
						$old_srv_data = array();
						$old_srv_data['ID_SERVICES_OLD'] = V::get('ID', '', $old_srv_row);
						$old_srv_data['P_OFFER_ID_OLD'] = V::get('ID_OFFERS', '', $old_srv_row);
						$old_srv_data['MONTH_COST_OLD'] = V::get('ABONAMENT_VALUE', '', $old_srv_row);
						$old_srv_data['P_SERVICE'] = V::get('offer_p_service', '', $old_srv_row);

						$insert_values = array();
						foreach ($this->_data as $k_field_name => $v_value) {
							$out_value = '';
							if (array_key_exists($k_field_name, $old_srv_data)) {
								$out_value = $old_srv_data[$k_field_name];
							} else {
								$out_value = $v_value;
							}
							$insert_values []= "'" . $out_value . "'";
						}
						$sql_insert []= "(" . implode(", ", $insert_values) . ")";
					}
				}
			}
		}

		if (empty($sql_insert)) {
			return false;
		}
		$sql = "insert into `USERS2_DEALS` (" . implode(", ", $sql_cols) . ") values \n\t " . implode("\n\t ,", $sql_insert);
		if (!$db->query($sql)) {
			return false;
		}
		return true;
	}

	function create_rows_old_rmme() {
		// TODO: use $this->_old_srv_map[$v_deal->ID_DEALS][$v_srv->ID] = $new_offer_id;
		$db = DB::getDB();
		$sql_insert = array();

		/*
	$this->_old_deal :
			[ID_DEALS] => 8841
			[ID_BILLING_USERS] => 11181
			[SERVICES_S_ADDRESS_STREET] => SZP7/19
			[P_NAME] => Tomasz Bachora
			[P_DEALNUMBER] => 9106
			[P_DEALDATE] => 2011-10-24
			[P_DEALDATE_TERM] => 2013-04-23
			[ID_OFFERS_GROUP] => 
			[services] => Array
				(
					[NET] => Array
						(
							[18090] => stdClass Object
								(
									[ID] => 18090
									[NAME_LIST_SERVICES] => USERS2
									[A_STATUS] => NORMAL
									[ID_OFFERS] => 737
									[ID_DEALS_TABLE] => 8841
									[P_ID_SERVICES] => 0
									[ABONAMENT_VALUE] => 41.46
									[P_ID] => 0
									[description] => Dost.do INTERNET
									[A_STATUS_DESC] => NORMALNY
									[P_SERVICE] => NET
									[out_id] => NET_1
	* 
	$this->_old_fields['ID_BILLING_USERS_OLD'] = 'ID_BILLING_USERS';
	$this->_old_fields['ID_SERVICES_OLD'] = 'ID_SERVICES';
	$this->_old_fields['P_OFFER_ID_OLD'] = 'OFFER_ID';
	$this->_old_fields['P_DEAL_DATE_OLD'] = 'P_DEAL_DATE';
	$this->_old_fields['P_DEALNUMBER_OLD'] = 'P_DEALNUMBER';
	$this->_old_fields['MONTH_COST_OLD'] = 'MONTH_COST';
	* 
		for(var srv_id in srv_map){
			out_offer_id=srv_map[srv_id];
			if (out_offer_id > 0) {
				srv=deal.services_by_id[srv_id];

				jQuery('#NEW_OFFER-' + out_offer_id + '-' + 'ID_BILLING_USERS_OLD').text(deal.ID_BILLING_USERS);
				jQuery('#NEW_OFFER-' + out_offer_id + '-' + 'P_DEALNUMBER_OLD').text(deal.P_DEALNUMBER);
				jQuery('#NEW_OFFER-' + out_offer_id + '-' + 'P_DEAL_DATE_OLD').text(deal.P_DEALDATE);
				jQuery('#NEW_OFFER-' + out_offer_id + '-' + 'P_DEALTERM_OLD').text(deal.P_DEALDATE_TERM);

				jQuery('#NEW_OFFER-' + out_offer_id + '-' + 'ID_SERVICES_OLD').text(srv.ID);
				jQuery('#NEW_OFFER-' + out_offer_id + '-' + 'P_OFFER_ID_OLD').text(srv.ID_OFFERS);
				jQuery('#NEW_OFFER-' + out_offer_id + '-' + 'MONTH_COST_OLD').text(srv.ABONAMENT_VALUE);
	*/

		$old_service_all = array();
		$old_services_todo = array();
		// $this->_deal_table->_group->_offers[$k_p_service][$k_offer_id][$k_field_name] => $v_value
		// $old_service_all[$k_p_service . '-' . $k_offer_id][$k_field_name] => $v_value
		if (!empty($this->_old_deal)) {
			foreach ($this->_old_deal->services as $k_p_service => $v_services_arr) {
				foreach ($v_services_arr as $k_service_id => $v_service) {
					$old_services_todo[$v_service->offer_p_service] []= $k_service_id;
				}
			}
			foreach ($this->_deal_table->_group->get_offers() as $k_p_service => $v_offers_arr) {
				foreach ($v_offers_arr as $k_offer_id => $v_offer) {
					if (empty($old_services_todo[$v_offer->P_SERVICE])) {
						continue;
					}
					$old_service_id = array_shift($old_services_todo[$v_offer->P_SERVICE]);
					$old_service_row = $this->_old_deal->services[$v_offer->P_SERVICE][$old_service_id];
					$old_srv_data = array();
					$old_srv_data['P_SERVICE'] = V::get('offer_p_service', '', $old_service_row);
					$old_srv_data['ID_SERVICES_OLD'] = V::get('ID', '', $old_service_row);
					$old_srv_data['P_OFFER_ID_OLD'] = V::get('ID_OFFERS', '', $old_service_row);
					$old_srv_data['MONTH_COST_OLD'] = V::get('ABONAMENT_VALUE', '', $old_service_row);
					$old_service_all[$v_offer->P_SERVICE . '-' . $k_offer_id] = $old_srv_data;
				}
			}
		}

		$sql_cols = array();
		$this->_data['A_RECORD_CREATE_DATE'] = date('Y-m-d-H:i');
		$this->_data['A_RECORD_CREATE_AUTHOR'] = User::getName();
		$this->_data['A_STATUS_INFO'] = 'Wprowadzono automatycznie za pomoca POKAZ_OFERTY_AKTUALNE';
		foreach ($this->_data as $k_field_name => $v_value) {
			$sql_cols []= "`" . $k_field_name . "`";
		}
		foreach ($this->_deal_table->_group->get_offers() as $k_p_service => $v_offers_arr) {
			$insert_values = array();
			foreach ($v_offers_arr as $k_offer_id => $v_offer) {
				$old_service_data = array();// fields like in $this->_old_fields
				if (array_key_exists($v_offer->P_SERVICE . '-' . $k_offer_id, $old_service_all)) {
					$old_service_data = $old_service_all[$v_offer->P_SERVICE . '-' . $k_offer_id];
				}
				foreach ($this->_data as $k_field_name => $v_value) {
					$out_value = '';
					if (array_key_exists($k_field_name, $this->_offer_values_map)) {
						$offer_field_name = $this->_offer_values_map[$k_field_name];
						$out_value .= $v_offer->$offer_field_name;
					} else if (array_key_exists($k_field_name, $old_service_data)) {
						$out_value .= $old_service_data[$k_field_name];
					} else if (!empty($v_value)) {
						$out_value .= $v_value;
					} else {
						// pozostaw puste
					}
					$insert_values []= "'" . $out_value . "'";
				}
				break;// only one offer by service
			}
			$sql_insert []= "(" . implode(", ", $insert_values) . ")";
		}
		// TODO: utworzyc rekordy wylaczenia dla uslug w old_deal ktorych nie ma w nowym
		if (!empty($old_services_todo)) {
			foreach ($old_services_todo as $k_p_service => $v_service_ids) {
				if (empty($v_service_ids)) {
					continue;
				}
				foreach ($v_service_ids as $v_service_id) {
					$old_srv_row = null;
					foreach ($this->_old_deal->services as $k_srv_p_service => $v_srv_arr) {
						if (array_key_exists($v_service_id, $v_srv_arr)) {
							$old_srv_row = $v_srv_arr[$v_service_id];
						}
					}
					if (!$old_srv_row) {
						// TODO: err brak services
						continue;
					}

					$old_srv_data = array();
					$old_srv_data['ID_SERVICES_OLD'] = V::get('ID', '', $old_srv_row);
					$old_srv_data['P_OFFER_ID_OLD'] = V::get('ID_OFFERS', '', $old_srv_row);
					$old_srv_data['MONTH_COST_OLD'] = V::get('ABONAMENT_VALUE', '', $old_srv_row);
					$old_srv_data['P_SERVICE'] = V::get('offer_p_service', '', $old_srv_row);

					$insert_values = array();
					foreach ($this->_data as $k_field_name => $v_value) {
						$out_value = '';
						if (array_key_exists($k_field_name, $old_srv_data)) {
							$out_value = $old_srv_data[$k_field_name];
						} else {
							$out_value = $v_value;
						}
						$insert_values []= "'" . $out_value . "'";
					}
					$sql_insert []= "(" . implode(", ", $insert_values) . ")";
				}
			}
		}

		if (empty($sql_insert)) {
			return false;
		}
		$sql = "insert into `USERS2_DEALS` (" . implode(", ", $sql_cols) . ") values " . implode("\n\t ,", $sql_insert);
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
		if (!$db->query($sql)) {
			return false;
		}
		return true;
	}

}

class Column_services extends Column_Base {

	var $_defaults = array();
	var $_remote_data = array();
	var $_offer = null;
	var $_ses_x_a = null;
	var $_ses_x_b = array();
	var $_ses_x_c = array();
	var $_srv_map = null;
	var $_install_price_netto = 0;
	var $_upust_months = 0;
	var $_upust_months_netto = 0;
	var $_old_srv_id = 0;
	var $_old_srv = null;
	var $_saved_id = 0;

	function __construct() {
		parent::__construct();
		//$this->_data['ID'] = '';
		$this->_data['ID_BILLING_USERS'] = '';
		$this->_data['NAME_LIST_SERVICES'] = '';// TODO: `LIST_SERVICES`.`name`
		$this->_data['A_STATUS'] = '';
		$this->_data['active'] = '';
		$this->_data['SERVICE_TYPE'] = '';
		$this->_data['ID_BILLING_NUMBERS_TYPE'] = '';
		$this->_data['ABONAMENT_PERIOD'] = '';
		$this->_data['ABONAMENT_VALUE'] = '';
		$this->_data['VAT'] = '';
		$this->_data['ID_CURRENCY'] = '';
		$this->_data['ABONAMENT_PAYMENT'] = '';
		$this->_data['ABONAMENT_START'] = '';
		$this->_data['MINIMUM_BILLING_VALUE'] = '';
		$this->_data['BILLED_TILL'] = '';
		$this->_data['HANGUP_FROM'] = '';
		$this->_data['HANGUP_TILL'] = '';
		$this->_data['HANGUP_STATUS'] = '';
		$this->_data['HANGUP_RATIO'] = '';
		$this->_data['TIMESTAMP'] = '';
		$this->_data['P_ID_SERVICES'] = '';
		$this->_data['uwagi'] = '';
		$this->_data['ID_DEALS_TABLE'] = '';
		$this->_data['VAT_NAME'] = '';
		$this->_data['id_list_sww'] = '';// TODO: `list_sww`.`ID`
		$this->_data['SERV_ID_BILLING_PREFIXES'] = '';
		$this->_data['ID_OFFERS'] = '';
		$this->_data['OLD_ID_SERVICES'] = '';
		//$this->_data['P_ACCOUNT'] = '';
		// BILLED_TILL ???

		$this->_defaults['A_STATUS'] = 'WAITING';
		$this->_defaults['active'] = 1;
		$this->_defaults['SERVICE_TYPE'] = 'ABONAMENT';
		$this->_defaults['ID_BILLING_NUMBERS_TYPE'] = 1;
		$this->_defaults['ABONAMENT_PERIOD'] = 1;
		$this->_defaults['ID_CURRENCY'] = 0;
		$this->_defaults['ABONAMENT_PAYMENT'] = 'UP';
		$this->_defaults['ABONAMENT_START'] = 1;
		$this->_defaults['MINIMUM_BILLING_VALUE'] = 0;
		$this->_defaults['HANGUP_FROM'] = null;
		$this->_defaults['HANGUP_TILL'] = null;
		$this->_defaults['HANGUP_STATUS'] = null;
		$this->_defaults['HANGUP_RATIO'] = 1;
		$this->_defaults['SERV_ID_BILLING_PREFIXES'] = '0';
		$this->_defaults['OLD_ID_SERVICES'] = '0';

		$this->_remote_data['S_ADDRESS_STREET'] = '';
	}

	function set_services_map($srv_map) {
		$this->_srv_map = $srv_map;
	}

	function set_old_srv_id($old_srv_id) {
		$this->_old_srv_id = $old_srv_id;
		$this->_data['OLD_ID_SERVICES'] = $this->_old_srv_id;
	}

	function get_old_srv_id() {
		return $this->_old_srv_id;
	}

	function set_old_srv($old_srv) {
		$this->_old_srv = $old_srv;

		if ($this->_old_srv) {
			$service_name = $this->get('NAME_LIST_SERVICES');// $this->_data['NAME_LIST_SERVICES']
			if (!$service_name) {
				echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Unknown service_name (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($service_name);echo'</pre>';
				return;
			}

			$srv_b = new Column_ses_x_b();
			$srv_b->set_name('SES_' . $service_name . '_B');
			$srv_b->set_id_services('TODO ID');
			$srv_b->set_id_user($this->get('ID_BILLING_USERS'));
			$srv_b->set_type(4);// ABONAMENT_START - Poczatek liczenia abonamentu
			$srv_b->set_value1(date('Y-m-d'));
			$this->_ses_x_b []= $srv_b;

			if (empty($this->_data['BILLED_TILL'])) {
				$this->_data['BILLED_TILL'] = date('Y-m-d H:i:s');
			}
		}
	}

	function get_old_srv() {
		return $this->_old_srv;
	}

	function get_services_map() {
		return $this->_srv_map;
	}

	function get_ses_x_a() {
		return $this->_ses_x_a;
	}

	function get_ses_x_c() {
		return $this->_ses_x_c;
	}

	function get_ses_x_b() {
		return $this->_ses_x_b;
	}

	function set_data_from_oferta_row($offer) {
		// TODO: BUG no $offer!
		$this->_offer = $offer;
		$this->set_defaults();
		$this->_data['ID_OFFERS'] = $offer->ID;
		$this->set_name_list_services($offer->P_SERVICE, $offer->P_SERVICE_PARENT);
		$this->set_vat($offer->STAWKA_VAT);
		$this->set_abonament_value($offer->P_CONTRACT_PRICE_NETTO);
		$this->add_install_price_netto($offer->P_INSTALL_QUOTE_NETTO);

		// nadpisanie z opcji oferty jesli zdefiniowano
		if (isset($offer->_options) && !empty($offer->_options)) {
			foreach ($offer->_options as $v_option) {
				if ($v_option->P_CONTRACT_PRICE_NETTO > 0) {
					$this->add_abonament_value($v_option->P_CONTRACT_PRICE_NETTO);
				}
				// sumuj oplaty instalacyjne / aktywacyjne
				if ($v_option->P_INSTALL_QUOTE_NETTO > 0) {
					$this->add_install_price_netto($v_option->P_INSTALL_QUOTE_NETTO);
				}
			}
		}

		// upust zwiazany z promocyjnymi miesiacami
		// 17	PROMOCYJNE_MIESIACE_DO_ODJECIA_ROZNICA_CENY	0	1	0	Jezeli w tabeli SES_C znajdzie sie taki rekord, to billing : w VALUE1 jest ilosc miesiecy do odjecia, w VALUE2 jest kwota netto bonifikatu za pojedynczy miesiac. System powinien ja rozliczac wstawiajac nowe rekordy i pomniejszajace stare.
		if ($offer->P_DEAL_PROMO_MONTHS) {// Ilość promocyjnych miesięcy
			$this->_upust_months = $offer->P_DEAL_PROMO_MONTHS;
			// P_PROMO_MONTH_PRICE_NETTO - Wartość abonamentu w promocyjnych miesiącach
			$this->_upust_months_netto = $this->_data['ABONAMENT_VALUE'] - $offer->P_PROMO_MONTH_PRICE_NETTO;
			if (isset($offer->_options) && !empty($offer->_options)) {
				foreach ($offer->_options as $v_option) {
					// odejmij cene abonamentu z opcji - opcje powinny meic P_PROMO_MONTH_PRICE == P_CONTRACT_PRICE
					if ($v_option->P_CONTRACT_PRICE_NETTO > 0) {
						$this->_upust_months_netto -= $v_option->P_CONTRACT_PRICE_NETTO;
					}
				}
			}
		}

		$map = $this->get_services_map();
		$service_name = $this->get('NAME_LIST_SERVICES');// $this->_data['NAME_LIST_SERVICES']
		if (!$service_name) {
			echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Unknown service_name (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($service_name);echo'</pre>';
			return;
		}
		$ses_x_class_name = 'Column_ses_' . strtolower($service_name) . '_a';
		$this->_ses_x_a = new $ses_x_class_name();
		$this->_ses_x_a->set_id_services('TODO ID');
		$this->_ses_x_a->set_id_billing_users($this->_data['ID_BILLING_USERS']);
		$this->_ses_x_a->set_data_from_oferta_row($this->_offer);
		// add S_ADDRESS_STREET for SES_USERS2_A
		$this->_ses_x_a->set_s_address_street($this->get_s_address_street());

		// create SES_X_C object with oplata instalacyjna / aktywacyjna - TYPE 18
		if ($this->_install_price_netto > 0) {
			$srv_c = new Column_ses_x_c();
			$srv_c->set_name('SES_' . $service_name . '_C');
			$srv_c->set_id_services('TODO ID');
			$srv_c->set_id_user($this->_data['ID_BILLING_USERS']);
			$srv_c->set_type(18);// 18	OPLATA_AKTYWACYJNA	0	1	0	Wprowadzenie rekordu tego typu oznaczac bedzie kon...
			$srv_c->set_value1('Oplata aktywacyjna');
			$srv_c->set_value2($this->_install_price_netto);
			$this->_ses_x_c []= $srv_c;
		}
		if ($this->_upust_months > 0 && $this->_upust_months_netto > 0) {
			$srv_c = new Column_ses_x_c();
			$srv_c->set_name('SES_' . $service_name . '_C');
			$srv_c->set_id_services('TODO ID');
			$srv_c->set_id_user($this->_data['ID_BILLING_USERS']);
			$srv_c->set_type(17);// 17	PROMOCYJNE_MIESIACE_DO_ODJECIA_ROZNICA_CENY	0	1	0	Jezeli w tabeli SES_C znajdzie sie taki rekord, to billing : w VALUE1 jest ilosc miesiecy do odjecia, w VALUE2 jest kwota netto bonifikatu za pojedynczy miesiac. System powinien ja rozliczac wstawiajac nowe rekordy i pomniejszajace stare.
			$srv_c->set_value1($this->_upust_months);
			$srv_c->set_value2($this->_upust_months_netto);
			$this->_ses_x_c []= $srv_c;
		}
	}

	function set_defaults() {
		foreach ($this->_defaults as $k_id => $v_val) {
			$this->_data[$k_id] = $v_val;
		}
	}

	function set_id_billing_users($id_user) {
		$this->_data['ID_BILLING_USERS'] = $id_user;
	}

	function set_name_list_services($p_service, $p_service_parent) {
		$service_name = '';
		$map = $this->get_services_map();
		if (array_key_exists($p_service, $map)) {
			$service_name = $p_service;
		} else if (array_key_exists($p_service_parent, $map)) {
			$service_name = $p_service_parent;
		}
		if (!$service_name) {
			echo'<p style="color:red">Error unknown p_service = ' . $p_service . ' [' . $this->_offer->ID . ' / P_SERVICE_PARENT: ' . $p_service_parent . ']' . ' (F.' . __FUNCTION__ . ':' . __LINE__ . ')</p>';
			echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">map: (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($map);echo'</pre>';
			return;
		}
		$this->_data['NAME_LIST_SERVICES'] = $map[$service_name];

		if ($map[$service_name] == 'TV') {
			$this->_data['id_list_sww'] = 3;// PKUiW na wartość 61.10.52
		}
	}

	function get_s_address_street() {
		return $this->_remote_data['S_ADDRESS_STREET'];
	}

	function set_s_address_street($street) {
		$this->_remote_data['S_ADDRESS_STREET'] = $street;
	}

	function set_abonament_value($abonament_value) {
		$this->_data['ABONAMENT_VALUE'] = $abonament_value;
	}

	function add_abonament_value($price_add) {
		$this->_data['ABONAMENT_VALUE'] += $price_add;
	}

	function add_install_price_netto($price_add) {
		$this->_install_price_netto += $price_add;
	}

	function set_p_id_services($p_id_services) {
		$this->_data['P_ID_SERVICES'] = $p_id_services;
	}

	function set_id_deals_table($id_deals) {
		$this->_data['ID_DEALS_TABLE'] = $id_deals;
	}

	function set_vat($vat) {
		$this->_data['VAT'] = $vat;
		$this->_data['VAT_NAME'] = $vat;// TODO: VAT_NAME 'ZW',8,23
	}

	function set_id_list_sww() {
		// TODO: set_id_list_sww ?
	}

	/**
	 * return inserted_id or false
	 */
	function save($simulate_db = null) {
		$db = DB::getDB();
		$sql_obj = (object)$this->_data;

		// if aneks and should run update_old_ses_x_a then set BILLED_TILL for aneks activation date - today
		if ($this->_old_srv_id > 0 && $this->_old_srv && $this->_old_srv->ID > 0) {
			if (empty($sql_obj->BILLED_TILL)) {
				$sql_obj->BILLED_TILL = date('Y-m-d H:i:s');
			}
		}

		if ($simulate_db) {
			$this->_saved_id = $simulate_db->add('ADD_NEW_OBJ', 'SERVICES', $sql_obj);
		} else {
			$this->_saved_id = $db->ADD_NEW_OBJ('SERVICES', $sql_obj);
		}
		if ($this->_saved_id <= 0) {
			$this->_saved_id = 0;
			return false;
		}

		if ($this->_old_srv_id > 0 && $this->_old_srv && $this->_old_srv->ID > 0) {// aneks, update $this->_old_srv
			if (!$this->_ses_x_a->update_old_ses_x_a($this->_saved_id, $this->_old_srv->ses_x_a, $simulate_db)) {
				return false;
			}
		}
		else {
			if (!$this->_ses_x_a->save($this->_saved_id, $simulate_db)) {
				return false;
			}
		}

		if (!empty($this->_ses_x_c)) {
			foreach ($this->_ses_x_c as $v_ses_c) {
				if (!$v_ses_c->save($this->_saved_id, $simulate_db)) {
					return false;
				}
			}
		}

		if (!empty($this->_ses_x_b)) {
			foreach ($this->_ses_x_b as $v_ses_b) {
				if (!$v_ses_b->save($this->_saved_id, $simulate_db)) {
					return false;
				}
			}
		}

		return $this->_saved_id;
	}

}

class Column_ses_x_a extends Column_Base {

	var $_data_from_offer = array();
	var $_data_from_offer_add = array();
	var $_defaults = array();
	var $_extra_services = array();

	function __construct() {
		parent::__construct();
		$this->_data['ID_SERVICES'] = '';
		$this->_data['ID_BILLING_USERS'] = '';
		$this->_data['A_STATUS'] = 'WAITING';
	}

	function set_defaults() {
		foreach ($this->_data_from_offer as $v_field) {
			if (array_key_exists($v_field, $this->_defaults)) {
				$this->_data[$v_field] = $this->_defaults[$v_field];
			}
		}
	}

	function set_id_services($id_services) {
		$this->_data['ID_SERVICES'] = $id_services;
	}

	function set_id_billing_users($id_user) {
		$this->_data['ID_BILLING_USERS'] = $id_user;
	}

	function set_s_address_street($street) {
		if (array_key_exists('S_ADDRESS_STREET', $this->_data)) {
			$this->_data['S_ADDRESS_STREET'] = $street;
		}
	}

	/**
	 * Override data from offer and options.
	 */
	function set_data_from_oferta_row($offer) {
		$this->set_defaults();
		foreach ($this->_data_from_offer as $v_field_name) {
			if (!empty($offer->$v_field_name)) {
				$this->_data[$v_field_name] = $offer->$v_field_name;
			}
		}
		foreach ($this->_data_from_offer_add as $v_field_name) {
			if (!empty($offer->$v_field_name)) {
				$this->_data[$v_field_name] += $offer->$v_field_name;
			}
		}

		// nadpisanie z opcji oferty jesli zdefiniowano
		if (isset($offer->_options) && !empty($offer->_options)) {
			foreach ($offer->_options as $v_option) {
				foreach ($this->_data_from_offer as $v_field_name) {
					if ($v_field_name == 'P_SERVICE_UPLOAD_RATIO') continue;
					if (!empty($v_option->$v_field_name)) {
						$this->_data[$v_field_name] = $v_option->$v_field_name;
					}
				}

				foreach ($this->_data_from_offer_add as $v_field_name) {
					if (!empty($v_option->$v_field_name)) {
						$this->_data[$v_field_name] += $v_option->$v_field_name;
					}
				}
			}
		}

		$this->generate_extra_services_from_offer($offer);
	}

	function generate_extra_services_from_offer($offer) {
	}

	function get_name() {
		return 'SES_X_A';
	}

	function save($services_id, $simulate_db = null) {
		if ($this->get_name() == 'SES_X_A') {
			echo '<p style="color:red">' . "Error: tabela SES_X_A nie istnieje" . '</p>';
			return false;
		}
		$db = DB::getDB();
		$this->set_id_services($services_id);
		$sql_obj = (object)$this->_data;
		if ($simulate_db) {
			$simulate_db->add('ADD_NEW_OBJ', $this->get_name(), $sql_obj, array('ID_SERVICES'=>$services_id));
			return true;
		} else {
			$ret_id = $db->ADD_NEW_OBJ($this->get_name(), $sql_obj);
			if ($db->has_errors()) {
				echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">DB Errors: (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($db->get_errors());echo "\n";print_r($sql);echo "\n";print_r($this);echo'</pre>';
				return false;
			}
			return $ret_id;
		}
	}

	/**
	 * Generates record object to update in database.
	 * @returns Array $sql_arr - array of fields to update
	 */
	function get_update_fields_from_old_ses_x_a($srv_id, $old_ses_x_a) {
		$sql_update_fields = array();

		$old_field_values = array();
		$sql_update_fields['ID'] = $old_ses_x_a->ID;
		$sql_update_fields['A_STATUS'] = 'NORMAL';
		$sql_update_fields['ID_SERVICES'] = $srv_id;
		//$sql_update_fields['T_WHEN_CONNECTED'] = date('Y-m-d');// 2013-06-10 wystarczy wpis w SES_X_B
		foreach ($old_ses_x_a as $k_field_name => $v_value) {
			if (array_key_exists($k_field_name, $sql_update_fields)) {
				continue;
			}
			$value = V::get($k_field_name, '', $this->_defaults);
			if (array_key_exists($k_field_name, $this->_data) && !empty($this->_data[$k_field_name])) {
				$value = $this->_data[$k_field_name];
			}
			if ($value != '' && $v_value != $value) {
				$sql_update_fields[$k_field_name] = $value;
				if ($k_field_name == 'P_SERVICE_QUOTA_PROFILE') {
					$old_field_values []= "{$k_field_name}=...";
				} else {
					$old_field_values []= "{$k_field_name}={$old_ses_x_a->$k_field_name}";
				}
			}
		}
		if (!empty($old_field_values)) {
			$sql_update_fields['A_PROBLEM'] = 'UNVERIFIED';
			$sql_update_fields['A_PROBLEM_DATE'] = date('Y-m-d-H:i');
			$sql_update_fields['A_PROBLEM_DESC'] = 'ANEKS - Stare dane: ID_SERVICES=' . $old_ses_x_a->ID_SERVICES . ', ' . implode(', ', $old_field_values);
			if (!empty($old_ses_x_a->A_PROBLEM) && !empty($old_ses_x_a->A_PROBLEM_DESC)) {
				$sql_update_fields['A_PROBLEM_DESC'] .= "\n" . $old_ses_x_a->A_PROBLEM_DESC;
			}
		}

		return $sql_update_fields;
	}

	/**
	 * Aneks - change ID_SERVICES for new created record
	 */
	function update_old_ses_x_a($srv_id, $old_ses_x_a, $simulate_db = null) {
		$retValue = 0;
		$db = DB::getDB();

		$sql_update_fields = $this->get_update_fields_from_old_ses_x_a($srv_id, $old_ses_x_a);

		$sql_obj = new stdClass();
		if (!empty($sql_update_fields)) {
			foreach ($sql_update_fields as $k_field_name => $v_value) {
				$sql_obj->$k_field_name = $v_value;
			}
			if ($simulate_db) {
				$simulate_db->add('UPDATE_OBJ', $this->get_name(), $sql_obj, array('ID_SERVICES'=>$srv_id));
				$retValue = true;
			} else {
				$ret = $db->UPDATE_OBJ($this->get_name(), $sql_obj);
				$retValue = ($ret > 0);
			}
		} else {
			$retValue = true;
		}
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$this (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this);echo'</pre>';
		if (!empty($this->_extra_services)) {
			foreach ($this->_extra_services as $v_extra_srv) {
				$v_extra_srv->update_old($srv_id, $this, $old_ses_x_a, $simulate_db);
			}
		}
		return $retValue;
	}

}

class Column_ses_users2_a extends Column_ses_x_a {

	function __construct() {
		parent::__construct();
		//$this->_data['S_ADDRESS_CITY'] = '';
		//$this->_data['S_ADDRESS_POST_CODE'] = '';
		$this->_data['S_ADDRESS_STREET'] = '';
		//$this->_data['S_ADDRESS_HOUSE'] = '';
		//$this->_data['S_ADDRESS_HOME'] = '';
		//$this->_data['S_HOST'] = '';
		//$this->_data['S_DOMAIN'] = '';
		//$this->_data['S_PASSWD'] = '';
		//$this->_data['T_NETWORK_SERVER'] = '';
		//$this->_data['P_SERVICE_QUOTA'] = '';
		$this->_data['S_OTHER_INFO'] = '';
		$this->_data['LAN_DOWNLOAD'] = '';
		$this->_data['CONN_DIV'] = '';
		$this->_data['S_PUBLIC_IP'] = '';
		$this->_data['S_SOHO_WIFI_ROUTER_1292'] = '';
		$this->_data['S_E_PORT_1293'] = '';
		$this->_data['P_SERVICE_QUOTA'] = '';
		$this->_data['P_SERVICE_QUOTA_PROFILE'] = '';
		$this->_data['P_SERVICE_UPLOAD_RATIO'] = '';
		$this->_data['S_TECHNOLOGY'] = '';

		$this->_defaults['LAN_DOWNLOAD'] = 'DOWN_LAN_ENABLED';
		$this->_defaults['CONN_DIV'] = 'NO';
		$this->_defaults['S_PUBLIC_IP'] = 'NO';
		$this->_defaults['S_SOHO_WIFI_ROUTER_1292'] = 'NO';
		$this->_defaults['S_E_PORT_1293'] = 'NO';

		$this->_data_from_offer = array();
		$this->_data_from_offer []= 'CONN_DIV';
		$this->_data_from_offer []= 'P_SERVICE_QUOTA';
		$this->_data_from_offer []= 'P_SERVICE_QUOTA_PROFILE';
		$this->_data_from_offer []= 'P_SERVICE_UPLOAD_RATIO';
		$this->_data_from_offer []= 'LAN_DOWNLOAD';
		$this->_data_from_offer []= 'S_PUBLIC_IP';
		$this->_data_from_offer []= 'S_SOHO_WIFI_ROUTER_1292';
		$this->_data_from_offer []= 'S_E_PORT_1293';
		$this->_data_from_offer []= 'S_TECHNOLOGY';
	}

	/**
	 * Run after set_data_from_oferta_row($offer)
	 */
	function generate_extra_services_from_offer($offer) {
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($offer);echo'</pre>';
		if (!empty($offer->P_S_PARAM1)) {
			/* sql to check if P_SERVICE_QUOTA and P_SERVICE_QUOTA_PROFILE in offers is correct
				SELECT o.ID, o.`P_S_PARAM1` , o.`P_SERVICE_QUOTA` , p.`P_SERVICE_QUOTA` , o.`P_SERVICE_QUOTA_PROFILE` , p.`P_SERVICE_QUOTA_PROFILE` , o.P_SERVICE_COMPANY
				FROM  `USERS2_OFFERS` AS o,  `LIST_USERS2_PROFILES` AS p
				WHERE o.`P_SERVICE`='NET' AND o.A_STATUS IN('WAITING','NORMAL') AND o.P_SERVICE_COMPANY IN('BN','NETDAY')
				AND p.P_S_PARAM1=o.`P_S_PARAM1` AND (o.`P_SERVICE_QUOTA` != p.`P_SERVICE_QUOTA` OR o.`P_SERVICE_QUOTA_PROFILE` != p.`P_SERVICE_QUOTA_PROFILE`)
				ORDER BY o.`ID` DESC
				LIMIT 100
			 */
			$db = DB::getDB();
			$sql = "select `P_SERVICE_QUOTA`,`P_SERVICE_QUOTA_PROFILE`
				from `LIST_USERS2_PROFILES`
				where `P_S_PARAM1`='{$offer->P_S_PARAM1}'
			";
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
			$res = $db->query($sql);
			//if ($db->num_rows() == 1) {
				if ($r = $db->fetch($res)) {
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($r);echo'</pre>';
					$this->_data['P_SERVICE_QUOTA'] = $r->P_SERVICE_QUOTA;
					$this->_data['P_SERVICE_QUOTA_PROFILE'] = $r->P_SERVICE_QUOTA_PROFILE;
				}
			//}
		}

		// nadpisanie z opcji oferty jesli zdefiniowano
		if (!empty($offer->_options)) {
			foreach ($offer->_options as $v_option) {
				foreach ($this->_data_from_offer as $v_field_name) {
					if ($v_field_name == 'P_SERVICE_UPLOAD_RATIO') continue;
					if (!empty($v_option->$v_field_name)) {
						$this->_data[$v_field_name] = $v_option->$v_field_name;

						if ($v_field_name == 'S_PUBLIC_IP') {
							if ($this->_data[$v_field_name] == 'YES') {
								$extras_srv = new Column_extra_services();
								$extras_srv->set_type_from_offer('S_PUBLIC_IP');
								$this->_extra_services []= $extras_srv;
							}
						}
					}
				}
			}
		}
	}

	function get_name() {
		return 'SES_USERS2_A';
	}

}

class Column_ses_voip_a extends Column_ses_x_a {

	function __construct() {
		parent::__construct();
		$this->_data['VOIP_FAX2EMAIL'] = '';
		$this->_data['ID_DOMAINS'] = '';// nazwa zewnetrzenego systemu
		$this->_data['ID_DOMAINS_PACKET_ID'] = '';// ID z zewnetrzenego systemu
		$this->_data['S_TECHNOLOGY'] = '';

		$this->_data_from_offer = array();
		$this->_data_from_offer []= 'VOIP_FAX2EMAIL';
		$this->_data_from_offer []= 'ID_DOMAINS';
		$this->_data_from_offer []= 'ID_DOMAINS_PACKET_ID';
		$this->_data_from_offer []= 'S_TECHNOLOGY';
	}

	function get_name() {
		return 'SES_VOIP_A';
	}

}

class Column_ses_tv_a extends Column_ses_x_a {

	function __construct() {
		parent::__construct();
		$this->_data['P_DEVICE'] = '';
		$this->_data['P_SERVICE_CLASS'] = '';
		$this->_data['P_SERVICE_SOCKETS_AMMOUNT_1298'] = '';
		$this->_data['ID_DOMAINS'] = '';// nazwa zewnetrzenego systemu
		$this->_data['ID_DOMAINS_PACKET_ID'] = '';// ID z zewnetrzenego systemu
		$this->_data['S_ADDRESS_STREET'] = '';
		$this->_data['P_MULTIROOM_ADD_CARDS'] = '0';
		$this->_data['P_MULTIROOM_ADD_DEKODER_SD'] = '0';
		$this->_data['P_MULTIROOM_ADD_DEKODER_HD'] = '0';
		$this->_data['P_MULTIROOM_ADD_MODUL_CAM'] = '0';
		$this->_data['S_TECHNOLOGY'] = '';

		$this->_defaults['P_SERVICE_CLASS'] = 'TV';

		$this->_data_from_offer = array();
		$this->_data_from_offer []= 'P_DEVICE';
		$this->_data_from_offer []= 'P_SERVICE_CLASS';
		$this->_data_from_offer []= 'P_SERVICE_SOCKETS_AMMOUNT_1298';
		$this->_data_from_offer []= 'ID_DOMAINS';
		$this->_data_from_offer []= 'ID_DOMAINS_PACKET_ID';
		$this->_data_from_offer []= 'S_TECHNOLOGY';

		$this->_data_from_offer_add []= 'P_MULTIROOM_ADD_CARDS';
		$this->_data_from_offer_add []= 'P_MULTIROOM_ADD_DEKODER_SD';
		$this->_data_from_offer_add []= 'P_MULTIROOM_ADD_DEKODER_HD';
		$this->_data_from_offer_add []= 'P_MULTIROOM_ADD_MODUL_CAM';
	}

	function get_name() {
		return 'SES_TV_A';
	}

}

class Column_ses_x_c extends Column_Base {

	var $_name;

	function __construct() {
		parent::__construct();
		$this->_name = 'SES_X_C';

		/* @from superedit-UPDATEDB.php after POST from superedit-A_PROBLEM.php
		 * insert into SES_X_C (ID,ID_SERVICES,ID_BILLING_USERS,TYPE,VALUE1,VALUE2)
		 * 
		 * A_PROBLEM dodaje TYPE 14 i 15:
		 *    14	PROBLEM_START_STOP	Poczatek i koniec problemu uniemozliwiajacy korzys...
		 *    15	CZYNNOSCI_SERWISOWE_USLUGI	Data i kwota czynnosci serwisowych, do rozliczenia...
		 */
		$this->_data['ID_SERVICES'] = '';
		$this->_data['ID_BILLING_USERS'] = '';
		$this->_data['TYPE'] = '';
		$this->_data['VALUE1'] = '';
		$this->_data['VALUE2'] = '';
	}

	function set_name($name) {
		$this->_name = $name;
	}

	function get_name() {
		return $this->_name;
	}

	function set_id_services($id_services) {
		$this->_data['ID_SERVICES'] = $id_services;
	}

	function set_id_user($id_user) {
		$this->_data['ID_BILLING_USERS'] = $id_user;
	}

	function set_type($type) {
		$this->_data['TYPE'] = $type;
	}

	function set_value1($val) {
		$this->_data['VALUE1'] = $val;
	}

	function set_value2($val) {
		$this->_data['VALUE2'] = $val;
	}

	function save($services_id, $simulate_db = null) {
		if ($this->get_name() == 'SES_X_C') {
			echo '<p style="color:red">' . "Error: tabela SES_X_C nie istnieje" . '</p>';
			return;
		}
		$db = DB::getDB();
		$this->set_id_services($services_id);
		//$sql_obj = (object)$this->_data;
		//$ret_id = $db->ADD_NEW_OBJ($this->get_name(), $sql_obj);
		$sql_arr = array();
		foreach ($this->_data as $k => $v) {
			$sql_arr ["`" . $k . "`"] = "'" . $v . "'";
		}
		if ($simulate_db) {
			$simulate_db->add('INSERT', $this->get_name(), $this->_data, array('ID_SERVICES'=>$services_id));
			return true;
		} else {
			$sql = "insert into `" . $this->get_name() . "` (" . implode(", ", array_keys($sql_arr)) . ") values (" . implode(", ", array_values($sql_arr)) . ");";
			$db->query($sql);
			if ($db->has_errors()) {
				echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">DB Errors: (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($db->get_errors());echo "\n";print_r($sql);echo "\n";print_r($this);echo'</pre>';
				return false;
			}
			return $db->insert_id();
		}
	}

}

class Column_ses_x_b extends Column_Base {

	var $_name;

	function __construct() {
		parent::__construct();
		$this->_name = 'SES_X_B';

		/* @from superedit-UPDATEDB.php after POST from superedit-A_PROBLEM.php
		 * insert into SES_X_C (ID,ID_SERVICES,ID_BILLING_USERS,TYPE,VALUE1,VALUE2)
		 * 
		 * A_PROBLEM dodaje TYPE 14 i 15:
		 *    14	PROBLEM_START_STOP	Poczatek i koniec problemu uniemozliwiajacy korzys...
		 *    15	CZYNNOSCI_SERWISOWE_USLUGI	Data i kwota czynnosci serwisowych, do rozliczenia...
		 */
		$this->_data['TIMESTAMP'] = date('Y-m-d H:i:s');
		$this->_data['ID_SERVICES'] = '';
		$this->_data['ID_BILLING_USERS'] = '';
		$this->_data['TYPE'] = '';
		$this->_data['VALUE1'] = '';
		$this->_data['VALUE2'] = '';
	}

	function set_name($name) {
		$this->_name = $name;
	}

	function get_name() {
		return $this->_name;
	}

	function set_id_services($id_services) {
		$this->_data['ID_SERVICES'] = $id_services;
	}

	function set_id_user($id_user) {
		$this->_data['ID_BILLING_USERS'] = $id_user;
	}

	function set_type($type) {
		$this->_data['TYPE'] = $type;
	}

	function set_value1($val) {
		$this->_data['VALUE1'] = $val;
	}

	function set_value2($val) {
		$this->_data['VALUE2'] = $val;
	}

	function save($services_id, $simulate_db = null) {
		if ($this->get_name() == 'SES_X_B') {
			echo '<p style="color:red">' . "Error: tabela SES_X_C nie istnieje" . '</p>';
			return;
		}
		$db = DB::getDB();
		$this->set_id_services($services_id);
		//$sql_obj = (object)$this->_data;
		//$ret_id = $db->ADD_NEW_OBJ($this->get_name(), $sql_obj);
		$sql_arr = array();
		foreach ($this->_data as $k => $v) {
			$sql_arr ["`" . $k . "`"] = "'" . $v . "'";
		}
		if ($simulate_db) {
			$simulate_db->add('INSERT', $this->get_name(), $this->_data, array('ID_SERVICES'=>$services_id));
			return true;
		} else {
			$sql = "insert into `" . $this->get_name() . "` (" . implode(", ", array_keys($sql_arr)) . ") values (" . implode(", ", array_values($sql_arr)) . ");";
			$db->query($sql);
			if ($db->has_errors()) {
				echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">DB Errors: (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($db->get_errors());echo "\n";print_r($sql);echo "\n";print_r($this);echo'</pre>';
				return false;
			}
			return $db->insert_id();
		}
	}

}

class Column_users2_offers_groups extends Column_Base {

	var $_offers;
	var $_offers_by_id;
	var $_id_options;
	var $_group_external_offers_id;
	var $suma_P_PROMO_INSTALL_PRICE = 0;
	var $suma_P_PROMO_MONTH_PRICE = 0;
	var $suma_P_CONTRACT_PRICE = 0;
	var $suma_P_OFFER_SREDNIA = 0;
	var $suma_P_OFFER_SREDNIA_NETTO = 0;
	var $suma_P_OFFER_COSTS = 0;
	var $suma_P_OFFER_COSTS_START = 0;

	function __construct() {
		parent::__construct();

		$this->_offers = array();
		$this->_offers_by_id = array();
		$this->_id_options = array();
		$this->_group_external_offers_id = array('ID_NET'=>'NET','ID_TV'=>'TV','ID_TVC'=>'TVC','ID_TVCP_1'=>'TVC','ID_TVCP_2'=>'TVC','ID_TVCP_3'=>'TVC','ID_TVCP_4'=>'TVC','ID_TEL'=>'TEL');

		$this->suma_P_PROMO_INSTALL_PRICE = 0;
		$this->suma_P_PROMO_MONTH_PRICE = 0;
		$this->suma_P_CONTRACT_PRICE = 0;
		$this->suma_P_OFFER_SREDNIA = 0;
		$this->suma_P_OFFER_SREDNIA_NETTO = 0;
		$this->suma_P_OFFER_COSTS = 0;
		$this->suma_P_OFFER_COSTS_START = 0;
	}

	function set_from_raw_data($db_row) {
		foreach ($db_row as $k_field => $v_value) {
			$this->_data[$k_field] = $v_value;
		}
	}

	function has_offers() {
		return !empty($this->_offers_by_id);
	}

	function get_offers() {
		return $this->_offers;
	}

	function get_offers_by_id() {
		return $this->_offers_by_id;
	}

	function set_offers($offers) {
		$this->_offers_by_id = $offers;
		$this->recount_costs();
		$this->_convert_offers();
	}

	function set_id_options($id_options) {
		$this->_id_options = $id_options;
	}

	function get_offers_ids() {
		return array_keys($this->_offers_by_id);
	}

	function fetch_offers() {
		$offers = array();
		foreach ($this->_group_external_offers_id as $k_external_id => $v_p_service) {
			if ($this->get($k_external_id) > 0) {
				$offers[$this->get($k_external_id)] = null;
			}
		}
		foreach ($this->_id_options as $k_service => $v_options) {
			if (empty($v_options)) continue;
			foreach ($v_options as $v_option_id) {
				if ($v_option_id > 0) {
					$offers[$v_option_id] = null;
				}
			}
		}
		//$offers = PokazOfertyHelper::get_offers_by_id(array_keys($offers), array('P_DEALTERM_MONTHS'=>$this->get('P_DEALTERM_MONTHS')));
		$this->_offers_by_id = PokazOfertyHelper::get_offers_by_id(array_keys($offers), array('P_DEALTERM_MONTHS'=>$this->get('P_DEALTERM_MONTHS')));

		$this->recount_costs();

		$this->_convert_offers();
	}

	/**
	 * Fetch offers by given ids and set _id_options.
	 * @param array $ids_offers - array of int - offers id
	 */
	function fetch_offers_by_ids($ids_offers) {
		$offers = array();
		$options = array();
		foreach ($this->_group_external_offers_id as $k_external_id => $v_p_service) {
			if ($this->get($k_external_id) > 0) {
				$offers[$this->get($k_external_id)] = null;
			}
		}

		foreach ($ids_offers as $v_offer_id) {
			if (!array_key_exists($v_offer_id, $offers)) {
				$offers[$v_offer_id] = null;
				$options []= $v_offer_id;
			}
		}

		$this->_offers_by_id = PokazOfertyHelper::get_offers_by_id(array_keys($offers), array('P_DEALTERM_MONTHS'=>$this->get('P_DEALTERM_MONTHS')));

		$this->recount_costs();

		foreach ($this->_offers_by_id as $v_offer) {
			if (in_array($v_offer->ID, $options)) {
				$this->_id_options[$v_offer->P_SERVICE_PARENT] []= $v_offer->ID;
			}
		}

		$this->_convert_offers();
	}

	function get_options_by_service($p_service) {
		if (array_key_exists($p_service, $this->_id_options)) {
			$options = array();
			foreach ($this->_id_options[$p_service] as $v_id_option) {
				$option = V::get($v_id_option, '', $this->_offers_by_id);
				if ($option) {
					$options [$v_id_option] = $option;
				}
			}
			return $options;
		}
		return null;
	}

	/**
	 * Convert $this->_offers_by_id to $this->_offers.
	 * Note: first run fetch_offers() or set_offers($offers) to set up $this->_offers;
	 */
	function _convert_offers() {
		$tmp_srv_id = array();// 'NET'=>1, 'TV'=>0, 'TEL'=>0, 'OPCJA_NET'=>2, 'OPCJA_TV'=>2
		foreach ($this->_group_external_offers_id as $k_external_id => $v_p_service) {
			if ($this->get($k_external_id) > 0) {
				$v_offer = $this->_offers_by_id[$this->get($k_external_id)];
				if ($v_offer) {

					$v_offer->out_id = $v_p_service;
					// wiele uslug tego samego typu np. TVC
					$tmp_srv_id[$v_offer->out_id] = (!array_key_exists($v_offer->out_id, $tmp_srv_id))? 1 : $tmp_srv_id[$v_offer->out_id] + 1;
					$v_offer->out_id = $v_offer->out_id . '_' . $tmp_srv_id[$v_offer->out_id];
					$this->_offers [$v_offer->out_id] [$v_offer->ID] = $v_offer;

					if (!empty($this->_id_options[$v_p_service])) {
						foreach ($this->_id_options[$v_p_service] as $v_option_id) {
							if ($v_option_id > 0) {
								$v_option = V::get($v_option_id, null, $this->_offers);
								if ($v_option) {
									$v_option->out_id = 'OPCJA_' . $v_option->P_SERVICE_PARENT;
									$tmp_srv_id[$v_option->out_id] = (!array_key_exists($v_option->out_id, $tmp_srv_id))? 1 : $tmp_srv_id[$v_option->out_id] + 1;
									$v_option->out_id = $v_option->out_id . '_' . $tmp_srv_id[$v_option->out_id];
									$this->_offers [$v_option->out_id] [$v_option->ID] = $v_option;
								}
							}
						}
					}
				}
			}
		}
		unset($tmp_srv_id);
	}

	function recount_costs() {
		$this->suma_P_PROMO_INSTALL_PRICE = 0;
		$this->suma_P_PROMO_MONTH_PRICE = 0;
		$this->suma_P_CONTRACT_PRICE = 0;
		$this->suma_P_OFFER_SREDNIA = 0;
		$this->suma_P_OFFER_SREDNIA_NETTO = 0;
		$this->suma_P_OFFER_COSTS = 0;
		$this->suma_P_OFFER_COSTS_START = 0;

		$oferty_costs = PokazOfertyHelper::get_offers_costs_by_offer_ids(array_keys($this->_offers_by_id));
		$oferty_costs_start = PokazOfertyHelper::get_offers_costs_start_by_offer_ids(array_keys($this->_offers_by_id));

		foreach ($this->_offers_by_id as $v_offer) {
			$this->suma_P_PROMO_INSTALL_PRICE += $v_offer->P_INSTALL_QUOTE;
			$this->suma_P_PROMO_MONTH_PRICE += $v_offer->P_PROMO_MONTH_PRICE;
			$this->suma_P_CONTRACT_PRICE += $v_offer->P_CONTRACT_PRICE;

			if (!isset($v_offer->srednia)) {
				$v_offer->srednia = round(( (($this->get('P_DEALTERM_MONTHS') - $v_offer->P_DEAL_PROMO_MONTHS) * $v_offer->P_CONTRACT_PRICE) + ($v_offer->P_DEAL_PROMO_MONTHS * $v_offer->P_PROMO_MONTH_PRICE) + ($v_offer->P_INSTALL_QUOTE)) / $this->get('P_DEALTERM_MONTHS'), 2);
			}
			$this->suma_P_OFFER_SREDNIA += $v_offer->srednia;

			if (!isset($v_offer->srednia_netto)) {
				$v_offer->srednia_netto = round(( (($this->get('P_DEALTERM_MONTHS') - $v_offer->P_DEAL_PROMO_MONTHS) * $v_offer->P_CONTRACT_PRICE_NETTO) + ($v_offer->P_DEAL_PROMO_MONTHS * $v_offer->P_PROMO_MONTH_PRICE_NETTO) + ($v_offer->P_INSTALL_QUOTE/1.23)) / $this->get('P_DEALTERM_MONTHS'), 2);
			}
			$this->suma_P_OFFER_SREDNIA_NETTO += $v_offer->srednia_netto;

			if (isset($oferty_costs[$v_offer->ID])) {
				$this->suma_P_OFFER_COSTS += $oferty_costs[$v_offer->ID];
			}
			if (isset($oferty_costs_start[$v_offer->ID])) {
				$this->suma_P_OFFER_COSTS_START += $oferty_costs_start[$v_offer->ID];
			}
		}

	}

	/**
	 * Zysk netto tylko z abonamentu - pomijając koszta aktywacji/instalacji (tylko typ MONTHLY pomijając START)
	 */
	function get_zysk_netto() {
		$this->recount_costs();
		return $this->suma_P_OFFER_SREDNIA_NETTO - $this->suma_P_OFFER_COSTS;
	}

	function get_zysk_netto_by_months($months) {
		//$this->recount_costs();
		$zysk = $this->get_zysk_netto();
		return $zysk * $months - $this->suma_P_OFFER_COSTS_START;
	}

	function get_srednia_netto() {
		$this->recount_costs();
		return $this->suma_P_OFFER_SREDNIA_NETTO;
	}

	function has_service($p_service) {
		foreach ($this->_group_external_offers_id as $k_external_id => $v_p_service) {
			if ($v_p_service == $p_service) {
				if ($this->get($k_external_id) > 0) {
					return true;
				}
			}
		}
		return false;
	}

}

class Column_extra_services extends Column_Base {

	var $_type = '';
	var $_old_esrv_rows = array();

	function set_type_from_offer($type) {
		// EXTRA_SERVICES.E_SERVICE : enum('','E_PORT','E_MAIL_ACCOUNT','E_MAIL_ALIAS','E_MAIL_CARBON','E_WWW_SITE','E_DB','E_TIMER_ON_OFF','E_NAT_IP')
		$this->_type = $type;
		// S_PUBLIC_IP -> E_NAT_IP @from proces 187 Elektroniczne aktywacje usług Proces zwiazany z elektronicznymi aktywacjami uslug
	}

	function get_old_rows($old_ses_x_a_id) {
		if ($this->_type == 'S_PUBLIC_IP') {
			$sql_e_type = 'E_NAT_IP';

			$db = DB::getDB();
			$sql = "select e.`ID`, e.`ID_SERVICES`, e.`E_SERVICE`, e.`E_S_V`
				from `EXTRA_SERVICES` as e
				where e.`ID_SERVICES`='{$old_ses_x_a_id}'
					and e.`E_SERVICE`='{$sql_e_type}'
			";
			$res = $db->query($sql);
			while ($r = $db->fetch($res)) {
				$this->_old_esrv_rows[$r->ID] = $r;
			}
		}
		return $this->_old_esrv_rows;
	}

	/**
	 * @param int $srv_id - SERVICES.ID or simulate ID
	 * @param Column_ses_x_a $srv - new ses_x_a data
	 * @param object $old_ses_x_a - old ses_x_a data ($k_field_name => $v_value)
	 * @param $simulate_db
	 */
	function update_old($srv_id, $srv, $old_ses_x_a, $simulate_db = null) {
		$extra_srv_rows = $this->get_old_rows($old_ses_x_a->ID_SERVICES);
		if (!empty($extra_srv_rows)) {
			foreach ($extra_srv_rows as $v_extra_srv) {
				$sql_obj = new stdClass();
				$sql_obj->ID = $v_extra_srv->ID;
				$sql_obj->ID_SERVICES = $srv_id;
				if ($simulate_db) {
					$simulate_db->add('UPDATE_OBJ', 'EXTRA_SERVICES', $sql_obj, array('ID_SERVICES'=>$srv_id));
				} else {
					$db->UPDATE_OBJ('EXTRA_SERVICES', $sql_obj);
				}
			}
		}
	}

}

function POKAZ_OFERTY_AKTUALNE_FUNC__activate_deal($id_deal) {
	$deal_row = PokazOfertyHelper::get_deal($id_deal);
	if (!$deal_row) {
		echo '<p class="err">' . "Error: Brak danych." . '</p>';
		return;
	}

	$deal = new Column_deals_table();
	$deal->set_from_raw_data($deal_row);

	$deal_type = $deal->get_type();
	if ($deal_type == 'ACTIVATE_OPTIONS') {
		$deal_form = new DealActivateOptionsForm();
		$deal_form->set_deal($deal);
		$deal_form->run();
		return;
	}
	else if ($deal_type == 'REZYGNACJA') {
		$deal_form = new DealActivateRezygnacja();
		$deal_form->set_deal($deal);
		$deal_form->run();
		return;
	}

	$conv = new Services_Converter();
	$conv->set_deal($deal);
	if (!$conv->fetch_group()) {
		echo '<p>' . "Error: brak grupy ofert (ID_OFFERS_GROUP)" . '</p>';
		return;
	}
	$conv->fetch_offers();
	$conv->fetch_old_deal();
	$conv->generate_srv_map();

	//$deal->fetch_users2_deals_rows();// TODO: TO REMOVE IN FUTURE - not needed - use field ID_OFFERS_ON, ID_OFFERS_OFF in DEALS_TABLE
	//$deal->fetch_offers_rows();// by users2_deals.P_OFFER_ID_NEW - TODO: use field ID_OFFERS_ON, ID_OFFERS_OFF in DEALS_TABLE
	//$deal->fetch_group_row();// use data from fetch_offers_rows
echo'<pre style="max-height:400px;overflow:auto;border:1px solid red;text-align:left;display:none;">deal (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($deal);echo'</pre>';

	echo '<style type="text/css">' . "
.tbl-view {margin:6px;}
 .tbl-view caption {background-color:#fff; text-align:left;}
 .tbl-view thead th {background-color:#eee;}
 .tbl-view th {font-size:11px;}
 .tbl-view td {font-size:12px;}
	" . '</style>';

	$conv->validate_edit();
echo'<pre style="max-height:200px;overflow:auto;border:1px solid green;text-align:left;display:none">conv (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($conv);echo'</pre>';

	if ($conv->has_errors()) {
		echo '<p>' . "Wróć do " . '<a href="' . "?MENU_INIT=DEALS_TABLE" . '">' . " DEALS_TABLE " . '</a>' . '</p>';
		echo '<p>' . "Rekord zawiera następujące błędy: " . '<br />' . implode('<br />', $conv->get_errors()) . '</p>';
		echo'<pre style="max-height:200px;overflow:auto;border:1px solid green;text-align:left;display:none">conv->get_errors (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($conv->get_errors());echo'</pre>';
		return;
	}
	echo 'OK';

	$conv->generate_preview();
echo'<pre style="max-height:200px;overflow:auto;border:1px solid green;text-align:left;display:none">conv (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($conv);echo'</pre>';

	if (1 == V::get('activate', '', $_POST)) {
		Lib::loadClass('SimulateDBTask');
		$simulate_db = null;
		if (true) {// if (V::get('_sim', 0, $_GET, 'int') > 0) {
			$db = DB::getDB();
			$simulate_db = new SimulateDBTask($db, "DEALS_TABLE-{$id_deal}");
			if ($simulate_db->has_todo()) {
				echo '<div style="border:1px solid #333; background:#eee; display:none;">';
				echo '<p>' . "Istnieją nieskończone zadania w kolejce dla tego rekordu!" . '</p>';
				// TODO: skontaktuj się z administratorem?
				$simulate_db->run();
				echo '</div>';
			}
		}

		$err_msgs = array();
		$log_arr = array();
		if ($conv->edit_update($err_msgs, $log_arr, $simulate_db)) {
			echo '<p style="color:green">' . "Umowa aktywowana" . '</p>';
		} else {
			echo '<p style="color:red">' . "Podczas aktywowania umowy wystąpiły następujące błędy:" . '<br />' . implode('<br />', $err_msgs) . '</p>';
		}
		if (!empty($log_arr)) {
			echo '<p style="color:silver">' . "Log: " . '<br />' . implode('<br />', $log_arr) . '</p>';
		}
		echo '<p>' . "Wróć do " . '<a href="' . "?MENU_INIT=DEALS_TABLE" . '">' . " DEALS_TABLE " . '</a>' . '</p>';

		if ($simulate_db) {
			echo '<div style="border:1px solid #333; background:#eee; display:none;">';
			echo '<p>' . "Run database tasks:" . '</p>';
			$simulate_db->run();
			echo '<p>' . "database tasks end." . '</p>';
			echo '</div>';

			{// update created SES_USERS2_A
				$ses_users2_a_update = array();
				$tasks = $simulate_db->get_tasks();
				foreach ($tasks as $v_task) {
					if ($v_task->TASK == 'ADD_NEW_OBJ' && $v_task->DB_TABLE == 'SES_USERS2_A' && $v_task->TASK_DONE == 1) {
						$ses_users2_a_update []= $v_task->RESULT_ID;
					}
				}
				if (!empty($ses_users2_a_update)) {
					echo '<p>' . "Aktualizacja SES_USERS2_A: " . implode(',', $ses_users2_a_update) . " - pola: S_HOST, S_DOMAIN, T_NETWORK_SERVER ..." . '</p>';
					$sql = "update `SES_USERS2_A` u, `USERS2_MARKETING` m, `BUILDINGS` b
						set
							u.`S_HOST`=concat('komp-', u.`ID_SERVICES`)
							, u.`S_DOMAIN`=b.`T_NETWORK_SERVER`
							, u.`T_NETWORK_SERVER`=b.`T_NETWORK_SERVER`
						where
							u.`ID` in(" . implode(',', $ses_users2_a_update) . ")
							and m.`S_ADDRESS_STREET`=u.`S_ADDRESS_STREET`
							and b.`S_ADDRESS_STREET`=m.`T_TELBOX_BUILDING_IN`
							and m.`ID` is not null
							and b.`ID` is not null
							and u.`S_HOST` is null
							and u.`S_DOMAIN` is null
							and u.`T_NETWORK_SERVER`=''
					";
					$db = DB::getDB();
					$db->query($sql);
					$affected = $db->affected_rows();
					echo '<p>' . "Zaktualizowano {$affected} rekordów w SES_USERS2_A." . '</p>';
				}
			}
		}

	}
	else {

		$conv->print_html_data();

		echo '<hr />';

		$conv->edit_preview();

		echo '<form action="" method="POST">';
			echo '<input type="hidden" name="' . "MENU_INIT" . '" value="' . "POKAZ_OFERTY_AKTUALNE_FUNC" . '" />';
			echo '<input type="hidden" name="' . "task" . '" value="' . "activate_deal" . '" />';
			//echo '<input type="hidden" name="' . "id_deal" . '" value="' . $deal->get('ID') . '" />';
			echo '<input type="hidden" name="' . "activate" . '" value="' . "1" . '" />';
			echo '<input type="submit" value="' . "Aktywuj umowę" . '" />';
		echo '</form>';
	}
}


function POKAZ_OFERTY_AKTUALNE_FUNC__verify_deals() {
echo '<style type="text/css">' . "
body {font:11px helvetica, arial;}
.tbl-view td {padding:0 2px;vertical-align:top;}
" . '</style>';

	$forceUpdate = false;
	Lib::loadClass('ColumnDealsStatus');
	ColumnDealsStatus::run_update($forceUpdate, $dbg_msgs);

	$db = DB::getDB();
	$sql_limit = 'limit 100';
	$limit = V::get('l', '', $_GET, 'int');
	if ($limit > 0) {
		$sql_limit = 'limit ' . $limit;
	}
	$offset = V::get('o', '', $_GET, 'int');
	if ($offset > 0) {
		$sql_limit .= 'offset ' . $offset;
	}
	$sql = "SELECT ds.`SERVICES_S_ADDRESS_STREET`, d.*
		FROM `temp_DEALS_STATUS` as ds
			LEFT JOIN `DEALS_TABLE` as d on(d.`ID`=ds.`ID_DEALS`)
		WHERE ds.`DEALS_ACTIVE`=1
			AND (`ID_OFFERS_GROUP`='' or `ID_OFFERS_GROUP` IS NULL)
		order by d.`ID` desc
		$sql_limit
	";
	$res = $db->query($sql);
	echo '<table border="1" cellspacing="0" cellpadding="0" class="tbl-view">';
	echo '<thead>';
		echo '<tr>';
			echo '<td>' . "ID" . '</td>';
			echo '<td>' . "SERVICES_S_ADDRESS_STREET" . '</td>';
			echo '<td>' . "ID_BILLING_USERS" . '</td>';
			echo '<td>' . "ID_OFFERS_GROUP" . '</td>';
			echo '<td>' . "ID_OFFERS_ON" . '</td>';
			echo '<td>' . "ID_OFFERS_OFF" . '</td>';
			echo '<td>' . "S_ADDRESS_STREET" . '</td>';
			echo '<td>' . "M_DIST_FILES" . '</td>';
		echo '</tr>';
	echo '</thead>';
	$ile = 0;
	while ($r = $db->fetch($res)) {
		$streets = explode(',', $r->SERVICES_S_ADDRESS_STREET);

		$user = PokazOfertyHelper::get_user_info($r->ID_BILLING_USERS);
		$active_deals_by_id = PokazOfertyHelper::get_deals_active_by_user($user->ID_BILLING_USERS);

		$srv_other_info = array();
		$offers_ids = array();
		foreach ($active_deals_by_id as $k_id_deal => $v_deal) {
			if (!empty($v_deal->services)) {
				foreach ($v_deal->services as $k_p_service => $v_srv_arr) {
					foreach ($v_srv_arr as $k_srv_id => $v_srv) {
						$v_srv->ses_x_a = null;
						if (array_key_exists($k_srv_id, $v_deal->ses_x_a)) {
							$v_srv->ses_x_a = $v_deal->ses_x_a[$k_srv_id];
							$srv_other_info[$v_srv->ID] = $v_srv->ses_x_a->S_OTHER_INFO;
						}

						$offers_ids [$v_srv->ID_OFFERS] = $v_srv;
					}
				}
			}
		}

		$groups = array();
		if (!empty($offers_ids)) {
			$oferty = PokazOfertyHelper::get_offers_by_id(array_keys($offers_ids));
			$groups = PokazOfertyHelper::find_groups_by_offers($oferty, $r->ID);
		}

		echo '<tr>';
			echo '<td>' . $r->ID . '</td>';
			echo '<td>' . $r->SERVICES_S_ADDRESS_STREET . '</td>';
			echo '<td>' . $r->ID_BILLING_USERS . '</td>';
			echo '<td>';
				if ($r->ID_OFFERS_GROUP > 0) {
					echo $r->ID_OFFERS_GROUP;
				} else {
					echo '<b style="color:red">Brak</b>';
				}
			echo '</td>';
			echo '<td>' . $r->ID_OFFERS_ON . '</td>';
			echo '<td>' . $r->ID_OFFERS_OFF . '</td>';
			echo '<td>' . $r->S_ADDRESS_STREET . '</td>';
			echo '<td>' . $r->M_DIST_FILES . '</td>';
			echo '<td>';
				foreach ($streets as $v_street) {
					echo ' <a href="' . "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&ADD=ADD&S_ADDRESS_STREET={$v_street}" . '" target="_blank">' . "Oferty({$v_street})"  .'</a>';
				}
				echo ' <a href="' . "?MENU_INIT=USERS2_WINDYKACJA_STATUS&_user_id={$r->ID_BILLING_USERS}" . '" target="_blank">' . "user" . '</a>';
				echo ' <a href="' . "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&task=verify_deal&id_deal={$r->ID}" . '" target="_blank">' . "deal" . '</a>';
				echo '<br /><a href="' . "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=895#EDIT/{$r->ID}" . '" target="_blank">' . "Edit deal" . '</a>';
			echo '</td>';
			echo '<td>';
				PokazOfertyView::user_with_services($user, $active_deals_by_id);

				echo '<table border="1" cellspacing="0" cellpadding="0" class="tbl-view">';
				foreach ($srv_other_info as $k_id => $v_info) {
					echo '<tr>';
						echo '<td>' . $k_id . '</td>';
						echo '<td>' . $v_info . '</td>';
					echo '</tr>';
				}
				echo '</table>';
			echo '</td>';
			echo '<td>';
				if (!empty($groups)) {
					echo '<p>'. "Znaleziono " . count($groups) . " pasujących grup" .'</p>';
					echo '<table border="1" cellspacing="0" cellpadding="0" class="tbl-view">';
					echo '<thead>';
						echo '<tr>';
							echo '<td>' . "ID" . '</td>';
							echo '<td>' . "COM" . '</td>';
							echo '<td>' . "ID_NET" . '</td>';
							echo '<td>' . "ID_TEL" . '</td>';
							echo '<td>' . "ID_TV" . '</td>';
							echo '<td>' . "ID_TVC" . '</td>';
							echo '<td>' . "ID_TVCP" . '</td>';
							echo '<td>' . "ID_TVCP_1" . '</td>';
							echo '<td>' . "P_DEALTERM_MONTHS" . '</td>';
						echo '</tr>';
					echo '</thead>';
					foreach ($groups as $v_group) {
						echo '<tr>';
							echo '<td title="' . "{$v_group->S_ALIAS} ({$v_group->P_PROMOTION_NAME})" . '">' . $v_group->ID . '</td>';
							echo '<td>' . $v_group->P_SERVICE_COMPANY . '</td>';
							echo '<td>';
								echo $v_group->ID_NET . '<br />';
								if (isset($oferty[$v_group->ID_NET])) {
									echo '<nobr>' . $oferty[$v_group->ID_NET]->P_CONTRACT_PRICE_NETTO . ' / ' . $oferty[$v_group->ID_NET]->P_PROMO_MONTH_PRICE_NETTO . '</nobr>';
								} else {
									echo '?';
								}
							echo '</td>';
							echo '<td>';
								echo $v_group->ID_TEL . '<br />';
								if (isset($oferty[$v_group->ID_TEL])) {
									echo '<nobr>' . $oferty[$v_group->ID_TEL]->P_CONTRACT_PRICE_NETTO . ' / ' . $oferty[$v_group->ID_TEL]->P_PROMO_MONTH_PRICE_NETTO . '</nobr>';
								} else {
									echo '?';
								}
							echo '</td>';
							echo '<td>';
								echo $v_group->ID_TV . '<br />';
								if (isset($oferty[$v_group->ID_TV])) {
									echo '<nobr>' . $oferty[$v_group->ID_TV]->P_CONTRACT_PRICE_NETTO . ' / ' . $oferty[$v_group->ID_TV]->P_PROMO_MONTH_PRICE_NETTO . '</nobr>';
								} else {
									echo '?';
								}
							echo '</td>';
							echo '<td>';
								echo $v_group->ID_TVC . '<br />';
								if (isset($oferty[$v_group->ID_TVC])) {
									echo '<nobr>' . $oferty[$v_group->ID_TVC]->P_CONTRACT_PRICE_NETTO . ' / ' . $oferty[$v_group->ID_TVC]->P_PROMO_MONTH_PRICE_NETTO . '</nobr>';
								} else {
									echo '?';
								}
							echo '</td>';
							echo '<td>';
								echo $v_group->ID_TVCP . '<br />';
								if (isset($oferty[$v_group->ID_TVCP])) {
									echo '<nobr>' . $oferty[$v_group->ID_TVCP]->P_CONTRACT_PRICE_NETTO . ' / ' . $oferty[$v_group->ID_TVCP]->P_PROMO_MONTH_PRICE_NETTO . '</nobr>';
								} else {
									echo '?';
								}
							echo '</td>';
							echo '<td>';
								if ($v_group->ID_TVCP_1 > 0) echo '<span' . ((isset($oferty[$v_group->ID_TVCP_1]))? ' title="' . "Price: {$oferty[$v_group->ID_TVCP_1]->P_CONTRACT_PRICE_NETTO} / Promo {$oferty[$v_group->ID_TVCP_1]->P_PROMO_MONTH_PRICE_NETTO}" . '"' : '') . '>'.$v_group->ID_TVCP_1.', </span>';
								if ($v_group->ID_TVCP_2 > 0) echo '<span' . ((isset($oferty[$v_group->ID_TVCP_2]))? ' title="' . "Price: {$oferty[$v_group->ID_TVCP_2]->P_CONTRACT_PRICE_NETTO} / Promo {$oferty[$v_group->ID_TVCP_2]->P_PROMO_MONTH_PRICE_NETTO}" . '"' : '') . '>'.$v_group->ID_TVCP_2.', </span>';
								if ($v_group->ID_TVCP_3 > 0) echo '<span' . ((isset($oferty[$v_group->ID_TVCP_3]))? ' title="' . "Price: {$oferty[$v_group->ID_TVCP_3]->P_CONTRACT_PRICE_NETTO} / Promo {$oferty[$v_group->ID_TVCP_3]->P_PROMO_MONTH_PRICE_NETTO}" . '"' : '') . '>'.$v_group->ID_TVCP_3.', </span>';
								if ($v_group->ID_TVCP_4 > 0) echo '<span' . ((isset($oferty[$v_group->ID_TVCP_4]))? ' title="' . "Price: {$oferty[$v_group->ID_TVCP_4]->P_CONTRACT_PRICE_NETTO} / Promo {$oferty[$v_group->ID_TVCP_4]->P_PROMO_MONTH_PRICE_NETTO}" . '"' : '') . '>'.$v_group->ID_TVCP_4.', </span>';
							echo '</td>';
							echo '<td>' . $v_group->P_DEALTERM_MONTHS . '</td>';
						echo '</tr>';
					}
					echo '</table>';
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">oferty (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($oferty);echo'</pre>';
				} else {
					echo '<p style="color:red">' . "Nie znaleziono pasujących grup" . '</p>';
				}
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none">$offers_ids (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($offers_ids);echo'</pre>';
			echo '</td>';
		echo '</tr>';
		$ile++;
	}
	//echo '<ftoot><tr><td colspan="8">' . "Ilość: " . $ile . '</td></tr></ftoot>';
	echo '</table>';
}

function POKAZ_OFERTY_AKTUALNE_FUNC__verify_deal($id_deal) {
	$deal_row = PokazOfertyHelper::get_deal($id_deal);
	if (!$deal_row) {
		echo '<p class="err">' . "Error: Brak danych." . '</p>';
		return;
	}

	$deal = new Column_deals_table();
	$deal->set_from_raw_data($deal_row);

	echo '<div style="margin:0 10px; padding:3px; border:1px solid #333; background:#efefee;">';
	echo '<h3>' . "Umowa ID " . $deal->get('ID') . ". Data umowy: " . $deal->get('P_DEALDATE') . '</h3>';
	$deal_type = $deal->get_type();
	echo "Wykryty rodzaj dokumentu: " . ((!$deal_type)? '<b style="color:red">' . "NIEZNANY" . '</b>' : '<b>' . $deal_type . '</b>') . '<br />';
	if ($deal_type) {
		//$deal->_group->get_zysk_netto();
		$id_offers_group = $deal->get('ID_OFFERS_GROUP');
		if ($id_offers_group <= 0) {
			echo '<b style="color:red">' . "Brak numeru grupy ofert!" . '</b>';
		} else {
			echo "Numer grupy ofert: <b>{$id_offers_group}</b> ";
			$group = PokazOfertyHelper::get_group($id_offers_group);
			if (!$group) {
				echo '<b style="color:red">' . "Brak grupy ofert!" . '</b>';
			} else {
				$group->fetch_offers();
				echo " Zysk netto: " . '<b style="color:green">' . number_format($group->get_zysk_netto(), 2, ',', ' ') . " zł" . '</b>';
				echo " Okres trwania umowy: <b>" . $group->get('P_DEALTERM_MONTHS') . "</b> miesięcy";
			}
		}
		echo '<br />';

		if ($deal_type == 'ANEKS') {
			$deal_old_id = $deal->get('P_DEALNUMBER_OLD');

			$old_offers_ids = array();
			if ($deal->get('ID_OFFERS_OFF') != '') {
				$old_offers_ids = explode(',', $deal->get('ID_OFFERS_OFF'));
			} else {
				echo '<p style="color:red">' . "Error: ANEKS - powinno być uzupełnione pole ID_OFFERS_OFF - numery ofert do wyłączenia" . '</p>';
			}

			echo '<h4>' . "Umowa old: <b>{$deal_old_id}</b>" . '</h4>';
			$deal_old_row = PokazOfertyHelper::get_deal($deal_old_id);
			if (!$deal_old_row) {
				echo '<b style="color:red">' . "Error: umowa nie istnieje - prawdopodobnie błędny numer ID umowy w polu P_DEALNUMBER_OLD." . '</b>';
			} else {
				$deal_old = new Column_deals_table();
				$deal_old->set_from_raw_data($deal_old_row);
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none">$deal_old (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($deal_old);echo'</pre>';
				$deal_old_type = $deal_old->get_type();
				echo "Od " . $deal_old->get('P_DEALDATE') . " do " . $deal_old->get('P_DEALDATE_TERM') . '<br />';
				if ($deal_old->get('P_DEALDATE_TERM') > $deal->get('P_DEALDATE')) {
					echo "Data zakończenia poprzedniej umowy: " . '<b>' . $deal_old->get('P_DEALDATE_TERM') . '</b>' . " - należy od zysku z nowej umowy odjąć zysk z pozostałej części starej umowy." . '<br />';

					$diff_days = PokazOfertyHelper::date_diff_days($deal_old->get('P_DEALDATE_TERM'), $deal->get('P_DEALDATE'));
					$diff_months = PokazOfertyHelper::date_diff_months($deal_old->get('P_DEALDATE_TERM'), $deal->get('P_DEALDATE'));

					echo '<p>'."Roznica dni: $diff_days, miesiecy: $diff_months".'</p>';

					if (empty($old_offers_ids)) {
						$users2_deals_rows = PokazOfertyHelper::get_users2_deals_by_deal_id($deal_old->get('ID'), array('WAITING','NORMAL'));
	echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none">users2_deals_rows (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users2_deals_rows);echo'</pre>';
						foreach ($users2_deals_rows as $v_users2_deal) {
							if ($v_users2_deal->P_OFFER_ID_NEW > 0) {
								$old_offers_ids []= $v_users2_deal->P_OFFER_ID_NEW;
							}
						}
						if (!empty($old_offers_ids)) {
							echo '<p>' . "Na podstawie wpisów w USERS2_DEALS dla umowy ID " . $deal_old->get('ID') . " udało się wykryć numery ofert: " . implode(',', $old_offers_ids) . '</p>';
						} else {
							echo '<p style="color:red">' . "Nie udało się wykryć numerów ofert dla umowy ID " . $deal_old->get('ID') . " na podstawie wpisów w USERS2_DEALS." . '</p>';
						}
					}

					if (!empty($old_offers_ids)) {
						if ($diff_months > 0) {
							$loss_log = array();
							$old_deal_months = PokazOfertyHelper::date_diff_months($deal_old->get('P_DEALDATE_TERM'), $deal_old->get('P_DEALDATE'));
							$loss = PokazOfertyHelper::get_aneks_loss($old_offers_ids, $diff_months, $old_deal_months, $loss_log);
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none">loss('.$loss.') (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($loss_log);echo'</pre>';
							foreach ($loss_log as $k_offer_id => $v_loss) {
								
							}
						}
					}

				} else {
					echo "Poprzednia umowa przeszła na czas nieokreślony." . '<br />';
				}
				//echo "Wykryty rodzaj dokumentu: " . ((!$deal_old_type)? '<b style="color:red">' . "NIEZNANY" . '</b>' : '<b>' . $deal_old_type . '</b>') . '<br />';

				$old_id_group = $deal_old->get('ID_OFFERS_GROUP');
				if ($old_id_group <= 0) {
					echo '<b style="color:red">' . "Brak numeru grupy ofert!" . '</b>';
				} else {
					echo "Numer grupy ofert: <b>{$old_id_group}</b> ";
					$group_old = PokazOfertyHelper::get_group($old_id_group);
					if (!$group_old) {
						echo '<b style="color:red">' . "Brak grupy ofert!" . '</b>';
					} else {
						$group_old->fetch_offers();
						echo " Zysk netto: " . '<b style="color:green">' . number_format($group_old->get_zysk_netto(), 2, ',', ' ') . " zł" . '</b>';
						echo " Okres trwania umowy: <b>" . $group_old->get('P_DEALTERM_MONTHS') . "</b> miesięcy";
					}
				}

			}
			echo '<br />';
		}
	}
	echo '</div>';
/*
$_SESSION['USERS2_DEALS_COLUMN']['RELATIVEDB']['TRG_COLUMN']['CHECK_NEW_BONUS']="(
	(
		(OF_NEW.P_PROMO_MONTH_PRICE_NETTO * OF_NEW.P_DEAL_PROMO_MONTHS)
		+ (OF_NEW.P_CONTRACT_PRICE_NETTO * (OF_NEW.P_DEALTERM_MONTHS - OF_NEW.P_DEAL_PROMO_MONTHS))
	) * 1
	-- tutaj odejmiemy utracony zysk, czyli ilosc od daty umowy do konca  * (zysk - koszt starych ofert)
	- 
	if (PERIOD_DIFF(date_format(USERS2_DEALS.P_DEALTERM_OLD, '%Y%m'), date_format(USERS2_DEALS.DATA_DOK, '%Y%m')) * OF_OLD.P_CONTRACT_PRICE_NETTO > 0
		, PERIOD_DIFF(date_format(USERS2_DEALS.P_DEALTERM_OLD,'%Y%m'), date_format(USERS2_DEALS.DATA_DOK,'%Y%m')) * (OF_OLD.P_CONTRACT_PRICE_NETTO - COSTS_GROUPS.P_OFFER_COSTS)
	,0) * 1
	-- tutaj okreslamy koszt biezacej oferty NEW 
	-
	(UOCG2_B.P_OFFER_COSTS * OF_NEW.P_DEALTERM_MONTHS) * 1
)
-- dajemy warunek jezeli nie jest to wypowiedzenie 
*
if(USERS2_DEALS.RODZAJ_DZIALANIA_HANDLOWEGO='UMOWA_BEZPOSREDNIA',
	0.15,
	if(USERS2_DEALS.RODZAJ_DZIALANIA_HANDLOWEGO in ('UMOWA_POSREDNIA','TELEMARKETING','UMOWA W BOK ZWYCZAJNA','REZYGNACJA CESJA'),
		0.05,
		0
	)
)

LEFT JOIN USERS2_OFFERS as OF_OLD on OF_OLD.ID=USERS2_DEALS.P_OFFER_ID_OLD 
left join USERS2_OFFERS_GROUPS as UOG_B on UOG_B.ID=OF_OLD.ID_COSTS_GROUPS
left join USERS2_OFFERS_COSTS_GROUPS as COSTS_GROUPS on ( COSTS_GROUPS.ID=UOG_B.ID  ) 
LEFT JOIN USERS2_OFFERS as OF_NEW on OF_NEW.ID=USERS2_DEALS.P_OFFER_ID_NEW 
left join USERS2_OFFERS_GROUPS as UOG2_B on UOG2_B.ID=OF_NEW.ID_COSTS_GROUPS
left join USERS2_OFFERS_COSTS_GROUPS as UOCG2_B on ( UOCG2_B.ID=UOG2_B.ID  ) 
 */

	$conv = new Services_Converter();
	$conv->set_deal($deal);
	$conv->fetch_group();
	$conv->fetch_offers();
	$conv->fetch_old_deal();
	$conv->generate_srv_map();

	//$deal->fetch_users2_deals_rows();// TODO: TO REMOVE IN FUTURE - not needed - use field ID_OFFERS_ON, ID_OFFERS_OFF in DEALS_TABLE
	//$deal->fetch_offers_rows();// by users2_deals.P_OFFER_ID_NEW - TODO: use field ID_OFFERS_ON, ID_OFFERS_OFF in DEALS_TABLE
	//$deal->fetch_group_row();// use data from fetch_offers_rows
echo'<pre style="max-height:400px;overflow:auto;border:1px solid red;text-align:left;display:none;">deal (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($deal);echo'</pre>';

	echo '<style type="text/css">' . "
.tbl-view {margin:6px;}
 .tbl-view caption {background-color:#fff; text-align:left;}
 .tbl-view thead th {background-color:#eee;}
 .tbl-view th {font-size:11px;}
 .tbl-view td {font-size:12px;}
	" . '</style>';

echo'<pre style="max-height:200px;overflow:auto;border:1px solid green;text-align:left;display:none">conv (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($conv);echo'</pre>';

	$conv->print_html_data();

	echo '<hr />';

	$conv->generate_preview();

echo'<pre style="max-height:200px;overflow:auto;border:1px solid green;text-align:left;display:none">conv (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($conv);echo'</pre>';
	$conv->verify_preview();

	echo '<hr />';

	$force_run_task = V::get('force_run_task', 0, $_GET, 'int');

	Lib::loadClass('SimulateDBTask');
	$db = DB::getDB();
	$simulate_db = new SimulateDBTask($db, "DEALS_TABLE-{$id_deal}");
	if ($simulate_db->has_tasks()) {
		$tasks = $simulate_db->get_tasks();
		echo '<div>';
		echo '<p>' . "Zadania dla rekordu umowy" . '</p>';
		echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view">';
		echo '<thead>';
			echo '<tr>';
				echo '<th>' . "ID" . '</th>';
				echo '<th>' . "A_RECORD_CREATE_DATE" . '</th>';
				echo '<th>' . "A_RECORD_CREATE_AUTHOR" . '</th>';
				echo '<th>' . "A_RECORD_UPDATE_DATE" . '</th>';
				echo '<th>' . "A_RECORD_UPDATE_AUTHOR" . '</th>';
				echo '<th>' . "TRANSACTION_ID" . '</th>';
				echo '<th>' . "TASK" . '</th>';
				echo '<th>' . "DB_TABLE" . '</th>';
				echo '<th>' . "DB_OBJ" . '</th>';
				echo '<th>' . "PARAMS" . '</th>';
				echo '<th>' . "RESULT_ID" . '</th>';
				echo '<th>' . "TASK_DONE" . '</th>';
			echo '</tr>';
		echo '</thead>';
		echo '<tbody>';
		$t = 0;
		foreach ($tasks as $v_task) {
			echo '<tr class="tbl-row-' . ($t = 1 - $t) . '">';
				echo '<td>' . $v_task->ID . '</td>';
				echo '<td>' . $v_task->A_RECORD_CREATE_DATE . '</td>';
				echo '<td>' . $v_task->A_RECORD_CREATE_AUTHOR . '</td>';
				echo '<td>' . $v_task->A_RECORD_UPDATE_DATE . '</td>';
				echo '<td>' . $v_task->A_RECORD_UPDATE_AUTHOR . '</td>';
				echo '<td>' . $v_task->TRANSACTION_ID . '</td>';
				echo '<td>' . $v_task->TASK . '</td>';
				echo '<td>' . $v_task->DB_TABLE . '</td>';
				echo '<td>' . str_replace("\n", '<br />', $v_task->DB_OBJ) . '</td>';
				echo '<td>' . $v_task->PARAMS . '</td>';
				echo '<td>' . $v_task->RESULT_ID . '</td>';
				echo '<td>' . $v_task->TASK_DONE;
					echo ' <a href="' . "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&task=verify_deal&id_deal={$id_deal}&force_run_task={$v_task->ID}" . '">Run</a>';
				echo '</td>';
			echo '</tr>';
		}
		echo '</tbody>';
		echo '</table>';
		echo '</div>';

		if ($force_run_task) {
			$simulate_db->force_run_task($force_run_task);
		}
	} else {
		echo '<p>' . "Brak zadań" . '</p>';
	}

}


function POKAZ_OFERTY_AKTUALNE_FUNC__rozlicz_month($month) {
	$months = array();
	$cur_y = date('Y');
	$cur_m = date('m');
	$DBG = ('rozlicz' == V::get('DBG', '', $_GET));

	for ($i = $cur_m; $i > 0; $i--) {
		$months []= sprintf("%d-%02d", $cur_y, $i);
	}
	for ($i = 12; $i > 0; $i--) {
		$months []= sprintf("%d-%02d", $cur_y - 1, $i);
	}

	if (!empty($month)) {
		if (!in_array($month, $months)) {
			$month = null;
			echo '<p style="color:red">'."Error - bad month".'</p>';
		}
	}
	echo '<form action="" method="get">';
		echo '<input type="hidden" name="MENU_INIT" value="POKAZ_OFERTY_AKTUALNE_FUNC" />';
		echo '<input type="hidden" name="task" value="rozlicz_month" />';
		echo '<p>' . "Wybierz miesiąc: ";
			echo '<select name="' . "month" . '">';
			foreach ($months as $v_month) {
				$sel = ($month == $v_month)? ' selected="selected"' : '';
				echo '<option value="' . $v_month . '" ' . $sel . '>' . $v_month . '</option>';
			}
			echo '</select>';
			echo '<input type="submit" value="' . "Wybierz" . '" />';
		echo '</p>';
	echo '</form>';

	if (!$month) {
		return;
	}

	$deals = PokazOfertyHelper::get_deals_by_month($month, array('A_STATUS'=>'NORMAL'));

	if (empty($deals)) {
		echo '<p>' . "Brak umów w wybranym miesiącu" . '</p>';
		return;
	}

	echo '<style type="text/css">' . "
.tbl-view {}
.tbl-view-small {font-size:small}
.tbl-view-small th {font-size:small}
.tbl-view thead th {background-color:#eee;}
.tbl-view tfoot td {background-color:#eee;}
.tbl-view tr:nth-child(even) td {background-color:#eee;}
.tbl-view-small td {padding:0 2px;}

.tbl_deals { table-layout:fixed; width:100%; }
 .tbl_deals td,
 .tbl_deals th { font-size:11px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
 .tbl_deals .tbl_deals-col_offers { width:80px; color:#999; }
 .tbl_deals .tbl_deals-col_num { width:40px; }
 .tbl_deals .tbl_deals-col_date { width:60px; }
 .tbl_deals .tbl_deals-col_street { width:100px; }
 .tbl_deals .tbl_deals-col_prefix { width:80px; }
 .tbl_deals .tbl_deals-col_dzialanie { width:150px; }
 .tbl_deals .tbl_deals-col_opis { width:auto; }
 .tbl_deals .tbl_deals-col_deal_type { width:auto; }

  .tbl_deals .tbl_deals-col_dzialanie-BRAK-BOK { color:silver; }
  .tbl_deals .tbl_deals-col_dzialanie-TELEMARKETING { color:lightgreen; }
  .tbl_deals .tbl_deals-col_dzialanie-UMOWA-W-BOK-ZWYCZAJNA { color:lightgreen; }
  .tbl_deals .tbl_deals-col_dzialanie-UMOWA_BEZPOSREDNIA { color:green; }
  .tbl_deals .tbl_deals-col_dzialanie-UMOWA_POSREDNIA { color:lightgreen; }
  .tbl_deals .tbl_deals-col_dzialanie-WYPOWIEDZENIE-PRZEZ-OPERATORA-ZA-DLUGI { color:red; }
  .tbl_deals .tbl_deals-col_dzialanie-REZYGNACJA-CESJA,
  .tbl_deals .tbl_deals-col_dzialanie-REZYGNACJA-INNE,
  .tbl_deals .tbl_deals-col_dzialanie-REZYGNACJA-NIEZADOWOLENIE,
  .tbl_deals .tbl_deals-col_dzialanie-REZYGNACJA-PROBLEMY-TECHNICZNE,
  .tbl_deals .tbl_deals-col_dzialanie-REZYGNACJA-SLABA-OFERTA,
  .tbl_deals .tbl_deals-col_dzialanie-REZYGNACJA-WYPROWADZKA,
  .tbl_deals .tbl_deals-col_dzialanie-REZYGNACJA-ZLA-OBSLUGA-BOK,
  .tbl_deals .tbl_deals-col_dzialanie-REZYGNACJA-ZMIANA-OPERATORA { color:red; }

	" . '</style>';

	$tblOutCells = array();
	$tblOutCells['ID'] = 								(object)array('class'=>'num', 'type'=>'link', 'link_format'=>'<a href="index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=895#EDIT/{ID}" target="_blank" title="Edytuj rekord {ID}">{ID}</a>');
	$tblOutCells['P_DEALDATE'] = 				(object)array('class'=>'date');
	$tblOutCells['ID_BILLING_USERS'] = 	(object)array('class'=>'num');
	$tblOutCells['S_ADDRESS_STREET'] = 	(object)array('class'=>'street');
	$tblOutCells['P_DEALPREFIX'] = 			(object)array('class'=>'prefix');
	$tblOutCells['P_DEALNUMBER_OLD'] = 	(object)array('class'=>'num');
	$tblOutCells['ID_OFFERS_GROUP'] = 	(object)array('class'=>'num');
	$tblOutCells['ID_OFFERS_ON'] = 			(object)array('class'=>'csv_num', 'label'=>'ID ofert do włączenia');
	$tblOutCells['ID_OFFERS_OFF'] = 		(object)array('class'=>'csv_num', 'label'=>'ID ofert do wyłączenia');
	$tblOutCells['RODZAJ_DZIALANIA_HANDLOWEGO'] = (object)array('class'=>'dzialanie');
	$tblOutCells['DEALDESC'] = 		(object)array('class'=>'opis');
	$tblOutCells['deal_type'] = 	(object)array('class'=>'deal_type', 'label'=>'Wykryty rodzaj dokumentu');
	$tblOutCells['abonament_srednia_netto'] = (object)array('class'=>'num', 'type'=>'number', 'label'=>'Średni miesięczny abonament netto');
	$tblOutCells['zysk'] = 				(object)array('class'=>'num', 'type'=>'number', 'label'=>'Średni miesięczny zysk netto');
	$tblOutCells['miesiecy'] = 		(object)array('class'=>'num', 'label'=>'Ilość miesięcy obowiązywania umowy');
	$tblOutCells['aneks_diff'] = 	(object)array('class'=>'num', 'label'=>'Ilość miesięcy obowiązywania poprzedniej umowy');
	$tblOutCells['aneks_loss'] = 	(object)array('class'=>'num', 'label'=>'Strata w zysku związana z okresem obowiązywania poprzedniej umowy');
	$tblOutCells['zysk_total'] = 	(object)array('class'=>'num', 'type'=>'number', 'label'=>'Zysk całkowity: Zysk * Mies. - Aneks Strata');
	$tblOutCells['verify_deal_link'] = 	(object)array('class'=>'num', 'type'=>'link', 'link_format'=>'<a href="index.php?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&task=verify_deal&id_deal={ID}" target="_blank" title="verify deal {ID}">verify</a>');
	$tblOutCells['check_errors'] = 			(object)array('class'=>'num', 'type'=>'array_of_errors');

	if(V::get('DBG_PO', '', $_GET)>0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">deals (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($deals);echo'</pre>';}
	$dealsAll = PokazOfertyHelper::get_deals_created_in_month($month, array('A_STATUS'=>'NORMAL', 'pominId'=>array_keys($deals)));
	if(V::get('DBG_PO', '', $_GET)>0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">dealsAll (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($dealsAll);echo'</pre>';}

	$dealsOut = array();
	foreach ($deals as $k_id => $v_deal_row)    $dealsOut[$k_id] = $v_deal_row;
	foreach ($dealsAll as $k_id => $v_deal_row) $dealsOut[$k_id] = $v_deal_row;

	foreach ($dealsOut as $k_id => $v_deal_row) {
		$deal = new Column_deals_table();
		$deal->set_from_raw_data($v_deal_row);

		$v_deal_row->deal_type = $deal->get_type();
		$v_deal_row->zysk = 0;
		$v_deal_row->miesiecy = PokazOfertyHelper::date_diff_months($v_deal_row->P_DEALDATE_TERM, $v_deal_row->P_DEALDATE);
		$v_deal_row->aneks_diff = 0;
		$v_deal_row->aneks_loss = 0;
		$v_deal_row->aneks_loss_abo_netto = 0;
		$v_deal_row->zysk_total = 0;
		$v_deal_row->check_errors = array();

		$out_html_attr = array();
		if ('REZYGNACJA' == $v_deal_row->deal_type) {
			$v_deal_row->miesiecy = 0;

			$deal_old_id = $deal->get('P_DEALNUMBER_OLD');
			if ($deal_old_id <= 0) {
				$v_deal_row->check_errors[] = "Error: REZYGNACJA - brak P_DEALNUMBER_OLD";
			} else {
				$deal_old_row = PokazOfertyHelper::get_deal($deal_old_id);
				if (!$deal_old_row) {
					$v_deal_row->check_errors[] = "Error: REZYGNACJA - brak rekordu starej umowy (qP_DEALNUMBER_OLD={$deal_old_id})";
				} else {
					$deal_old = new Column_deals_table();
					$deal_old->set_from_raw_data($deal_old_row);
					$deal_old_type = $deal_old->get_type();

					$id_offers_group = $deal_old->get('ID_OFFERS_GROUP');
					if ($id_offers_group <= 0) {
						$v_deal_row->check_errors[] = "Error: REZYGNACJA - brak ID_OFFERS_GROUP w starej umowie (P_DEALNUMBER_OLD={$deal_old_id})";
					} else {
						$group = PokazOfertyHelper::get_group($id_offers_group);
						if (!$group) {
							$v_deal_row->check_errors[] = "Error: REZYGNACJA - brak pakietu (ID_OFFERS_GROUP={$id_offers_group}) w starej umowie (P_DEALNUMBER_OLD={$deal_old_id})";
						} else {
							$group->fetch_offers();
							$group->recount_costs();
							$v_deal_row->zysk = $group->get_zysk_netto();
							$v_deal_row->zysk_total = $v_deal_row->zysk * -1;
							$v_deal_row->abonament_srednia_netto = $group->get_srednia_netto();
						}
					}
				}
			}
		}
		else if ($v_deal_row->deal_type) {
			$id_offers_group = $deal->get('ID_OFFERS_GROUP');
			if ($id_offers_group > 0) {
				$group = PokazOfertyHelper::get_group($id_offers_group);
				if ($group) {
					$group->fetch_offers();
					$v_deal_row->zysk = $group->get_zysk_netto();
					$v_deal_row->abonament_srednia_netto = $group->get_srednia_netto();
				}
			}

			if ($v_deal_row->deal_type == 'ANEKS') {
				$deal_old_id = $deal->get('P_DEALNUMBER_OLD');

				$old_offers_ids = array();
				if ($deal->get('ID_OFFERS_OFF') != '') {
					$old_offers_ids = explode(',', $deal->get('ID_OFFERS_OFF'));
				} else {
					$v_deal_row->check_errors []= "Error: ANEKS - powinno być uzupełnione pole ID_OFFERS_OFF - numery ofert do wyłączenia";
				}

				$deal_old_row = PokazOfertyHelper::get_deal($deal_old_id);
				if (!$deal_old_row) {
					$out_html_attr ['P_DEALNUMBER_OLD'] = ' style="background-color:red" title="' . "umowa ID {$deal_old_id} nie istnieje" . '"';
				} else {
					$deal_old = new Column_deals_table();
					$deal_old->set_from_raw_data($deal_old_row);
					$deal_old_type = $deal_old->get_type();
					if ($deal_old->get('P_DEALDATE_TERM') > $deal->get('P_DEALDATE')) {
						$v_deal_row->check_errors []= "Data zakończenia poprzedniej umowy: " . '<b>' . $deal_old->get('P_DEALDATE_TERM') . '</b>' . " - należy od zysku z nowej umowy odjąć zysk z pozostałej części starej umowy.";

						$diff_days = PokazOfertyHelper::date_diff_days($deal_old->get('P_DEALDATE_TERM'), $deal->get('P_DEALDATE'));
						$diff_months = PokazOfertyHelper::date_diff_months($deal_old->get('P_DEALDATE_TERM'), $deal->get('P_DEALDATE'));
						$v_deal_row->aneks_diff = $diff_months;

						if (empty($old_offers_ids)) {
							$users2_deals_rows = PokazOfertyHelper::get_users2_deals_by_deal_id($deal_old->get('ID'), array('WAITING','NORMAL'));
							foreach ($users2_deals_rows as $v_users2_deal) {
								if ($v_users2_deal->P_OFFER_ID_NEW > 0) {
									$old_offers_ids []= $v_users2_deal->P_OFFER_ID_NEW;
								}
							}
							if (!empty($old_offers_ids)) {
								$v_deal_row->check_errors []= "Na podstawie wpisów w USERS2_DEALS dla umowy ID " . $deal_old->get('ID') . " udało się wykryć numery ofert: " . implode(',', $old_offers_ids);
							} else {
								$v_deal_row->check_errors []= "Nie udało się wykryć numerów ofert dla umowy ID " . $deal_old->get('ID') . " na podstawie wpisów w USERS2_DEALS.";
							}
						}

						if (!empty($old_offers_ids)) {
							if ($diff_months > 0) {
								$loss_log = array();
								$old_deal_months = PokazOfertyHelper::date_diff_months($deal_old->get('P_DEALDATE_TERM'), $deal_old->get('P_DEALDATE'));
								$loss = PokazOfertyHelper::get_aneks_loss($old_offers_ids, $diff_months, $old_deal_months, $loss_log);
								$v_deal_row->aneks_loss = $loss;
								$v_deal_row->aneks_loss_abo_netto = PokazOfertyHelper::get_aneks_loss_abonament_netto($old_offers_ids, $diff_months, $old_deal_months, $loss_log);
							}
						}

					} else {
						$out_html_attr ['aneks_diff'] = ' style="background-color:silver" title="' . "Poprzednia umowa przeszła na czas nieokreślony" . '"';
					}
				}
			}

			if ($v_deal_row->ID_OFFERS_GROUP <= 0) {
				if ($v_deal_row->deal_type == 'NEW_DEAL') {
					$out_html_attr['ID_OFFERS_GROUP'] = ' style="background-color:red" title="' . "Nowa umowa musi mieć wypełnione pole ID_OFFERS_GROUP" . '"';
				}
			}

			$v_deal_row->zysk_total = $group->get_zysk_netto_by_months($v_deal_row->miesiecy);//$v_deal_row->zysk * $v_deal_row->miesiecy;
			if ($v_deal_row->deal_type == 'ANEKS') {
				if ($v_deal_row->aneks_diff > 0 && $v_deal_row->aneks_loss) {
					$v_deal_row->zysk_total -= $v_deal_row->aneks_loss;
				}
			}
		}

		$dealsOut[$k_id] = $v_deal_row;
	}
	if(V::get('DBG_PO', '', $_GET)>0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">dealsOut (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($dealsOut);echo'</pre>';}

	?>
	<table cellspacing="0" cellpadding="0" border="1" class="tbl_deals tbl-view tbl-view-small">
	<thead>
	<?php foreach ($tblOutCells as $kCell => $vCellConf) : ?>
		<?php
			$cellLabel = str_replace('_', ' ', $kCell);
			$cellLabel = V::get('label', $cellLabel, $vCellConf);
		?>
		<th class="tbl_deals-col_<?php echo V::get('class', '', $vCellConf); ?>" title="<?php echo $cellLabel; ?>">
			<?php echo $cellLabel; ?>
		</th>
	<?php endforeach; ?>
	</thead>
	<tbody>
	<?php foreach ($dealsOut as $kId => $r) : ?>
		<tr>
		<?php foreach ($tblOutCells as $kCell => $vCellConf) : ?>
			<?php
				$cellValue = '';
				if ('number' == V::get('type', '', $vCellConf)) {
					$cellValue = number_format($r->{$kCell}, 2, ',', '');
					$cellLabel = $cellValue;
				}
				else if ('array_of_errors' == V::get('type', '', $vCellConf)) {
					if (!empty($r->check_errors)) {
						$cellValue = '<span title="' . implode("\n", $r->check_errors) . '" style="color:red">' . " Errors " . '</span>';
					}
					$cellLabel = V::get('label', $kCell, $vCellConf);
				}
				else if ('link' == V::get('type', '', $vCellConf)) {
					$link_format = V::get('link_format', '', $vCellConf);
					$link = str_replace('{ID}', $r->ID, $link_format);
					$cellValue = $link;
					$cellLabel = V::get('label', $kCell, $vCellConf);
				}
				else if (isset($r->{$kCell})) {
					$cellValue = $r->{$kCell};
					$cellLabel = $cellValue;
				}

				$clsAdd = '';
				if ('RODZAJ_DZIALANIA_HANDLOWEGO' == $kCell) {
					$clsAdd = ' tbl_deals-col_' . V::get('class', '', $vCellConf) . '-' . str_replace(' ', '-', $r->{$kCell});
				}
			?>
			<td class="tbl_deals-col_<?php echo V::get('class', '', $vCellConf); echo $clsAdd; ?>" title="<?php echo $cellLabel; ?>">
				<?php echo $cellValue; ?>
			</td>
		<?php endforeach; ?>
		</tr>
	<?php endforeach; ?>
	</tbody>
	</table>
	<?php

	$statsType = array();
	foreach ($dealsOut as $kId => $r) {
		if (!isset($statsType[$r->RODZAJ_DZIALANIA_HANDLOWEGO])) {
			$vStat = new stdClass();
			$vStat->ilosc = 1;
			$statsType[$r->RODZAJ_DZIALANIA_HANDLOWEGO] = $vStat;
		}
		else {
			$statsType[$r->RODZAJ_DZIALANIA_HANDLOWEGO]->ilosc += 1;
		}
	}

	if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($dealsOut);echo'</pre>';}
	$statsByFoundType = array();
	/** @2014-08-20
	 * [13245] KOMORKA bok_nowa_umowa_wartosc_sprzed_kontrakt bok nowa um. wart.sprzed.kontr. Jaka wartość wynika ze sprzedanych kontraktów z tytułu nowych umów. Czyli kwota abonamentu razy długość kontraktu.
	 * 
	 * [13246] KOMORKA bok_nowa_umowa_zysk_kontrakt bok nowa um. zysk kontakt Jaki jest zysk wynikły ze sprzedanych kontraktów z tytułu nowej umowy.
	 * 
	 * [13247] KOMORKA bok_aneks_wartosc_sprzed_kontrakt bok aneks wart.sprzed. Jaka jest wartość sprzedaży wynikła z podpisania aneksu. Czyli jeżeli klient przeszedł z umowy na czas nieokreślony, będzie to okres umowy razy ilość abonamentów. Jeżeli zmienił umowę z innej umowy na czas określony, to z zysku należy odjąć wartość, jaka wynikała z jego poprzedniej umowy i terminu obowiązywania.
	 * 
	 * [13248] KOMORKA bok_aneks_zysk_kontrakt bok aneks zysk kontrakt Jaki jest zysk z tytułu kontraktów jakie zamówił klient w wyniku podpisania aneksu. Należy odjąć zysk od usług które były wcześniej zamówione na okres pokrywający się. Czyli jeżeli klient miał umowę na rok za usługę z zyskiem 50zł, to jeżeli podpisał umowę na 2 lata na usługę z takim samym zyskiem, to należy od zysku 24m-c x 50 PLN odjąć pozostały okres umowy 12m-c x 50 PLN = 1200-600 = 600 PLN.
	 * 
	 * [13249] KOMORKA bok_rezygnacja_strata_zysk_1_mies bok rez.wart.strac.zysk 1mies. Należy zsumować wartość zysku jaka przestanie wpływać do firmy z tytułu zakupywanych usług przez klientów.
	 * 
	 * [13250] KOMORKA bok_rezygnacja_strata_wartosc_sprzed bok rez.wart.straty 1mies Należy tutaj zsumować wartość abonamentów jakie przestaną wpływać do firmy z tytułu zakupywanych usług przez klientów, którzy złożyli rezygnacje.
	 * 
	 * $statsByFoundType:
	 *   zysk_total - KPI: [13246], [13248]
	 *   abonament_srednia_netto
	 */
	$errosNoGroupIDInOldDeal = array();
	foreach ($dealsOut as $kId => $r) {
		$vStat = V::get($r->deal_type, null, $statsByFoundType);
		if (!$vStat) {
			$vStat = new stdClass();
			$vStat->ilosc = 0;
			$vStat->zysk_total = 0;
			$vStat->abonament_srednia_netto = 0;
			$vStat->sum_abonament_srednia_netto = 0;
		}

		$vStat->ilosc += 1;
		$vStat->zysk_total += $r->zysk_total;
		if (!$r->abonament_srednia_netto) {
			$errosNoGroupIDInOldDeal[$r->ID] = $r;
		} else {
			$vStat->abonament_srednia_netto += $r->abonament_srednia_netto;
			if ('NEW_DEAL' == $r->deal_type) {
				$vStat->sum_abonament_srednia_netto += $r->abonament_srednia_netto * $r->miesiecy;
			} else if ('ANEKS' == $r->deal_type) {
				$vStat->sum_abonament_srednia_netto += $r->abonament_srednia_netto * $r->miesiecy - $r->aneks_loss_abo_netto;
			}
		}

		$statsByFoundType[$r->deal_type] = $vStat;
	}

	$sumaSrAboZoff = 0;
	$sumaSrZyskZoff = 0;
	foreach ($errosNoGroupIDInOldDeal as $k => $r) {
		if ('REZYGNACJA' == $r->deal_type && !empty($r->ID_OFFERS_OFF)) {
			$group = new Column_users2_offers_groups();
			$group->setForce('P_DEALTERM_MONTHS', 24);
			$group->fetch_offers_by_ids(explode(',', $r->ID_OFFERS_OFF));
			$group->recount_costs();
			if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">group for deal('.$r->ID.') ID_OFFERS_OFF('.$r->ID_OFFERS_OFF.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($group);echo'</pre>';}
			$errosNoGroupIDInOldDeal[$k]->abonament_srednia_netto_prze_1mies = $group->get_srednia_netto();
			$errosNoGroupIDInOldDeal[$k]->zysk_total = -1 * $group->get_zysk_netto();

			$sumaSrAboZoff += $errosNoGroupIDInOldDeal[$k]->abonament_srednia_netto_prze_1mies;
			$sumaSrZyskZoff += $errosNoGroupIDInOldDeal[$k]->zysk_total;
		}
	}

	?>
	<h3>Podsumowanie:</h3>
	<table cellspacing="0" cellpadding="0" border="0">
		<tr>
			<td style="vertical-align:top">
				<table cellspacing="0" cellpadding="0" border="1" class="tbl-view tbl-view-small">
				<thead>
					<th>RODZAJ_DZIALANIA_HANDLOWEGO</th>
					<th>ilość</th>
				</thead>
				<tbody>
					<?php foreach ($statsType as $type => $vStat) : ?>
					<tr>
						<td><?php echo $type; ?></td><td><?php echo $vStat->ilosc; ?></td>
					</tr>
					<?php endforeach; ?>
				</tbody>
				</table>
			</td>
			<td style="vertical-align:top;padding-left:20px;">
				<table cellspacing="0" cellpadding="0" border="1" class="tbl-view tbl-view-small">
				<thead>
					<th>Wykryty rodzaj umowy</th>
					<th>ilość</th>
					<th class="tbl_deals-col_num" title="Zysk całkowity: Zysk * Mies. - Aneks Strata">Zysk</th>
					<th class="tbl_deals-col_num" title="Średni miesięczny abonament netto">Śr. abonament</th>
					<th class="tbl_deals-col_num" title="Abonament netto wyliczony na podstawie średniego miesięcznego abonamentu">Suma abonamonet</th>
				</thead>
				<tbody>
					<?php foreach ($statsByFoundType as $type => $vStat) : ?>
					<tr>
						<td><?php echo $type; ?></td>
						<td><?php echo $vStat->ilosc; ?></td>
						<td><?php echo number_format($vStat->zysk_total, 2, ',', ''); ?></td>
						<td><?php echo number_format($vStat->abonament_srednia_netto, 2, ',', ''); ?></td>
						<td><?php echo number_format($vStat->sum_abonament_srednia_netto, 2, ',', ''); ?></td>
					</tr>
					<?php endforeach; ?>
				</tbody>
				</table>
				<?php if (!empty($errosNoGroupIDInOldDeal)) : ?>
					<h4 style="color:red">Błędy w umowach (<?php echo count($errosNoGroupIDInOldDeal); ?>):</h4>
					<table cellspacing="0" cellpadding="0" border="1" class="tbl-view tbl-view-small">
						<thead>
							<th title="Numer umowy">Nr</th>
							<th title="Numer klienta">Klient</th>
							<th title="Wykryty rodzaj umowy">Typ</th>
							<th title="Numery ofert do wyłączenia">ID_OFFERS_OFF</th>
							<th title="Średni miesięczny zysk netto na podstawie numerów ofert do wyłączenia">Śr. zysk</th>
							<th title="Średni miesięczny abonament netto na podstawie numerów ofert do wyłączenia">Śr. abonament</th>
						</thead>
						<tfoot>
							<td style="text-align:right" colspan="4">Suma:</td>
							<td><?php echo $sumaSrZyskZoff; ?></td>
							<td><?php echo $sumaSrAboZoff; ?></td>
						</tfoot>
						<tbody>
						<?php foreach ($errosNoGroupIDInOldDeal as $deal) : ?>
							<tr>
								<td style="padding:0 3px;"><?php echo $deal->ID; ?></td>
								<td style="padding:0 3px;"><?php echo $deal->ID_BILLING_USERS; ?></td>
								<td style="padding:0 3px;"><?php echo $deal->deal_type; ?></td>
								<td style="padding:0 3px;"><?php echo $deal->ID_OFFERS_OFF; ?></td>
								<td style="padding:0 3px;">
									<?php if (!$deal->zysk_total) : ?>
										<b style="color:red">Brak</b>
									<?php else : ?>
										<?php echo number_format($deal->zysk_total, 2, ',', ''); ?>
									<?php endif; ?>
								</td>
								<td style="padding:0 3px;">
									<?php if (!$deal->abonament_srednia_netto_prze_1mies) : ?>
										<b style="color:red">Brak</b>
									<?php else : ?>
										<?php echo number_format($deal->abonament_srednia_netto_prze_1mies, 2, ',', ''); ?>
									<?php endif; ?>
								</td>
							</tr>
						<?php endforeach; ?>
						</tbody>
					</table>
				<?php endif; ?>
				
				<?php if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($errosNoGroupIDInOldDeal);echo'</pre>';} ?>
			</td>
		</tr>
	</table>
	<?php
}


function POKAZ_OFERTY_AKTUALNE_FUNC__klient_umowy($id_user) {

	Lib::loadClass('ColumnDealsStatus');
	ColumnDealsStatus::run_update_for_user($id_user);

	$id_user = (int)$id_user;
	if ($id_user <= 0) {
		echo '<p>' . "Error: brak danych" . '</p>';
		return;
	}

	?>
		<h1>
			<a href="index.php?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&task=klient_umowy&id_user=<?php echo $id_user; ?>">Klient <?php echo $id_user; ?></a>
		</h1>
	<?php

	$user = PokazOfertyHelper::get_user_info($id_user);
	if (!$user) {
		echo '<p>' . "Error: brak danych o kliencie {$id_user}" . '</p>';
		return;
	}

	$active_deals_by_id = PokazOfertyHelper::get_deals_active_by_user($user->ID_BILLING_USERS, false);
	if(V::get('DBG',0,$_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none">active_deals_by_id (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($active_deals_by_id);echo'</pre>';}

	$pokaz_oferty_view = new PokazOfertyView();
	echo $pokaz_oferty_view->print_css();
	$pokaz_oferty_view->user_with_services($user, $active_deals_by_id);

	$id_deal = V::get('id_deal', 0, $_GET, 'int');

	if (empty($active_deals_by_id)) {
		echo '<p style="color:red">' . "Error: brak aktualnych umów." . '</p>';
		return;
	}

	foreach ($active_deals_by_id as $k_id => $v_deal) {
		echo '<p>';
			echo "Umowa ID {$k_id}: ";
			echo '<a href="' . "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&task=umowa_add_options&id_user={$user->ID_BILLING_USERS}&id_deal={$k_id}" . '">' . "Dodaj opcje" . '</a>';
			echo " lub ";
			echo '<a href="' . "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&task=umowa_rm_options&id_user={$user->ID_BILLING_USERS}&id_deal={$k_id}" . '">' . "Wyłącz opcje" . '</a>';
		echo '</p>';
	}

}


function POKAZ_OFERTY_AKTUALNE_FUNC__umowa_add_options($id_user, $id_deal) {
	$id_user = (int)$id_user;
	$id_deal = (int)$id_deal;
	if ($id_user <= 0) {
		echo '<p>' . "Error: id_user" . '</p>';
		return;
	}
	if ($id_deal <= 0) {
		echo '<p>' . "Error: id_deal" . '</p>';
		return;
	}

	echo '<h1>';
		echo '<a href="' . "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&task=klient_umowy&id_user={$id_user}" . '">' . "Klient {$id_user}" . '</a>';
		echo " - " . '<a href="' . "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&task=umowa_add_options&id_user={$id_user}&id_deal={$id_deal}" . '">' . "Umowa {$id_deal}" . '</a>';
		echo " - Zamówienie opcji";
	echo '</h1>';

	$user = PokazOfertyHelper::get_user_info($id_user);
	if (!$user) {
		echo '<p>' . "Error: brak danych o kliencie {$id_user}" . '</p>';
		return;
	}

	$active_deals_by_id = PokazOfertyHelper::get_deals_active_by_user($user->ID_BILLING_USERS);
	if (empty($active_deals_by_id)) {
		echo '<p style="color:red">' . "Error: brak aktualnych umów." . '</p>';
		return;
	}

	$pokaz_oferty_view = new PokazOfertyView();
	echo $pokaz_oferty_view->print_css();
	$pokaz_oferty_view->user_with_services($user, $active_deals_by_id);

	$deal_info = $active_deals_by_id[$id_deal];
	if (!$deal_info) {
		echo '<p style="color:red">' . "Error: danych umowy." . '</p>';
		return;
	}
	echo '<p>' . "Wybrano umowe ID {$deal_info->ID_DEALS}" . '</p>';
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none;">deal_info (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($deal_info);echo'</pre>';
	if ($deal_info->ID_OFFERS_GROUP <= 0) {
		echo '<p style="color:red">' . "Error: brak id pakietu (ID_OFFERS_GROUP)." . '</p>';
		return;
	}

	$group = PokazOfertyHelper::get_group($deal_info->ID_OFFERS_GROUP);
	if (!$group) {
		echo '<p style="color:red">' . "Error: brak danych o pakiecie ({$deal_info->ID_OFFERS_GROUP})." . '</p>';
		return;
	}

	// $deal_info->ID_OFFERS_ON
	// $this->_group->set_offers(PokazOfertyHelper::get_offers_by_id($offers_ids));
	if ($deal_info->ID_OFFERS_ON) {
		$offers_ids = explode(',', $deal_info->ID_OFFERS_ON);
		$group->fetch_offers_by_ids($offers_ids);
	}
	else {
		$group->fetch_offers();
	}
	echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none;">group (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($group);echo'</pre>';

	$oferty_opcje = PokazOfertyHelper::get_oferty_opcje();
	//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">$oferty_opcje: ';print_r($oferty_opcje);echo'</pre>';
	//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($oferty_group_add_info ['labels']);echo'</pre>';
	if (empty($oferty_opcje)) {
		$pokaz_oferty_view->print_group_info($group, array('hide_print'=>true));
		echo '<p style="color:red">' . "Brak opcji w bazie danych" . '</p>';
		return;
	}

	$deal_form = new DealAddOptionsForm();
	$deal_form->set_options($_GET);
	$deal_form->set_oferty_opcje($oferty_opcje);
	$deal_form->set_deal($deal_info);
	$deal_form->set_group($group);
	$deal_form->set_group_view($pokaz_oferty_view);
	$deal_form->run();
}


function POKAZ_OFERTY_AKTUALNE_FUNC__umowa_rm_options($id_user, $id_deal) {
	$id_user = (int)$id_user;
	$id_deal = (int)$id_deal;
	if ($id_user <= 0) {
		echo '<p>' . "Error: id_user" . '</p>';
		return;
	}
	if ($id_deal <= 0) {
		echo '<p>' . "Error: id_deal" . '</p>';
		return;
	}

	echo '<h1>';
		echo '<a href="' . "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&task=klient_umowy&id_user={$id_user}" . '">' . "Klient {$id_user}" . '</a>';
		echo " - " . '<a href="' . "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&task=umowa_rm_options&id_user={$id_user}&id_deal={$id_deal}" . '">' . "Umowa {$id_deal}" . '</a>';
		echo " - Rezygnacja z opcji";
	echo '</h1>';

	$user = PokazOfertyHelper::get_user_info($id_user);
	if (!$user) {
		echo '<p>' . "Error: brak danych o kliencie {$id_user}" . '</p>';
		return;
	}

	$active_deals_by_id = PokazOfertyHelper::get_deals_active_by_user($user->ID_BILLING_USERS);
	if (empty($active_deals_by_id)) {
		echo '<p style="color:red">' . "Error: brak aktualnych umów." . '</p>';
		return;
	}

	$pokaz_oferty_view = new PokazOfertyView();
	echo $pokaz_oferty_view->print_css();
	$pokaz_oferty_view->user_with_services($user, $active_deals_by_id);

	$deal_info = $active_deals_by_id[$id_deal];
	if (!$deal_info) {
		echo '<p style="color:red">' . "Error: danych umowy." . '</p>';
		return;
	}
	echo '<p>' . "Wybrano umowe ID {$deal_info->ID_DEALS}" . '</p>';
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none;">deal_info (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($deal_info);echo'</pre>';
	if ($deal_info->ID_OFFERS_GROUP <= 0) {
		echo '<p style="color:red">' . "Error: brak id pakietu (ID_OFFERS_GROUP)." . '</p>';
		return;
	}

	$group = PokazOfertyHelper::get_group($deal_info->ID_OFFERS_GROUP);
	if (!$group) {
		echo '<p style="color:red">' . "Error: brak danych o pakiecie ({$deal_info->ID_OFFERS_GROUP})." . '</p>';
		return;
	}

	// $deal_info->ID_OFFERS_ON
	// $this->_group->set_offers(PokazOfertyHelper::get_offers_by_id($offers_ids));
	if ($deal_info->ID_OFFERS_ON) {
		$offers_ids = explode(',', $deal_info->ID_OFFERS_ON);
		$group->fetch_offers_by_ids($offers_ids);
	}
	else {
		$group->fetch_offers();
	}
	echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none;">group (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($group);echo'</pre>';

	$oferty_opcje = PokazOfertyHelper::get_oferty_opcje();
	//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">$oferty_opcje: ';print_r($oferty_opcje);echo'</pre>';
	//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($oferty_group_add_info ['labels']);echo'</pre>';
	if (empty($oferty_opcje)) {
		$pokaz_oferty_view->print_group_info($group, array('hide_print'=>true));
		echo '<p style="color:red">' . "Brak opcji w bazie danych" . '</p>';
		return;
	}

	$deal_form = new DealRmOptionsForm();
	$deal_form->set_options($_GET);
	$deal_form->set_oferty_opcje($oferty_opcje);
	$deal_form->set_deal($deal_info);
	$deal_form->set_group($group);
	$deal_form->set_group_view($pokaz_oferty_view);
	$deal_form->run();
}


class DealOptionsForm {

	var $options;
	var $oferty_opcje;
	var $allowed_services;
	var $deal;
	var $group;
	var $group_view;
	var $_sent;
	var $_errors;

	function __construct() {
		$this->options = array();
		$this->oferty_opcje = array();
		$this->oferty_opcje_by_id = array();
		$this->allowed_services = array('NET','TV','TEL', 'TVC');
		$this->deal = array();
		$this->group = array();
		$this->group_view = array();
		$this->_sent = false;
		$this->_errors = array();
	}

	function set_options($options_arr) {
		if (empty($options_arr)) {
			return;
		}
		foreach ($this->allowed_services as $v_service) {
			$options = V::get('id_options_' . $v_service, null, $options_arr, 'array');
			if (!empty($options)) {
				$this->options[$v_service] = $options;
			}
		}

		if (!empty($this->options)) {
			$this->_sent = true;
		}
	}

	function has_option($p_service, $offer_id) {
		if (array_key_exists($p_service, $this->options)) {
			if (in_array($offer_id, $this->options[$p_service])) {
				return true;
			}
		}
		return false;
	}

	function set_deal($deal) {
		$this->deal = $deal;
	}

	function set_group($group) {
		$this->group = $group;
	}

	function set_group_view($group_view) {
		$this->group_view = $group_view;
	}

	function set_oferty_opcje($oferty_opcje) {
		$this->oferty_opcje = $oferty_opcje;
	}

	function get_oferty_opcje_by_service($p_service) {
		$options = array();
		if (!$this->group->has_service($p_service)) {
			return $options;
		}
		if (array_key_exists($p_service, $this->oferty_opcje)) {
			foreach ($this->oferty_opcje[$p_service] as $k_id => $v_oferta) {
				$options[$k_id] = $v_oferta;
			}
		}
		return $options;
	}

	function get_oferta_opcja($p_service, $offer_id) {
		if (array_key_exists($p_service, $this->oferty_opcje)) {
			if (array_key_exists($offer_id, $this->oferty_opcje[$p_service])) {
				return $this->oferty_opcje[$p_service][$offer_id];
			}
		}
		return null;
	}

	function get_oferty_opcje_by_id() {
		$opcje_by_id = array();
		foreach ($this->options as $k_service => $v_options_ids) {
			foreach ($v_options_ids as $v_option_id) {
				$v_opcja = $this->get_oferta_opcja($k_service, $v_option_id);
				if ($v_opcja) {
					$opcje_by_id[$v_opcja->ID] = $v_opcja;
				}
			}
		}
		return $opcje_by_id;
	}

	function print_selected_options($title) {
		$options_tree = array();
		foreach ($this->options as $k_service => $v_options) {
			$options_tree[$k_service] = array();
			foreach ($v_options as $k_option_id) {
				$v_option = $this->get_oferta_opcja($k_service, $k_option_id);
				if ($v_option) {
					$options_tree[$k_service][$k_option_id] = $v_option;
				}
			}
		}
		$cols = PokazOfertyHelper::get_oferty_opcje_visible_cols();
		PokazOfertyView::print_options_tree($options_tree, $cols, $title);
	}

	function is_sent() {
		return $this->_sent;
	}

	function is_valid() {
		return empty($this->_errors);
	}

	function is_confirmed() {
		return ('' != V::get('accept', '', $_POST));
	}

	function validate() {
	}

	function print_form() {
	}

	function run() {
	}

	function save() {
	}

}


class DealRmOptionsForm extends DealOptionsForm {

	function generate_print_link() {
		$link_href = "./odt2xhtml/4138.opcje-rezygnacja.php";
		$link_args = array();
		foreach ($this->options as $k_service => $v_options_ids) {
			foreach ($v_options_ids as $v_option_id) {
				$link_args []= "id_options_{$k_service}[]={$v_option_id}";
			}
		}
		$link_href .= "?id_user={$this->deal->ID_BILLING_USERS}&" . implode("&", $link_args);
		$link_ico = '<img src="icon/print.gif" height="24" />';
		$out = '<a href="' . $link_href . '" target="_blank">' . " drukuj {$link_ico}" . '</a>';
		return $out;
	}

	function validate() {
		$opcje_by_id = $this->get_oferty_opcje_by_id();
		if (empty($opcje_by_id)) {
			$this->_errors []= 'Nie wybrano żadnych opcji';
		}
	}

	function print_form() {
		if ($this->is_sent() && $this->is_valid()) {
			return;
		}

		echo '<p>' . "Zaznacz opcje do wyłączenia" . '</p>';
		echo '<form action="" method="GET">';
			echo '<input type="hidden" name="' . "MENU_INIT" . '" value="' . "POKAZ_OFERTY_AKTUALNE_FUNC" . '" />';
			echo '<input type="hidden" name="' . "task" . '" value="' . "umowa_rm_options" . '" />';
			echo '<input type="hidden" name="' . "id_user" . '" value="' . $this->deal->ID_BILLING_USERS . '" />';
			echo '<input type="hidden" name="' . "id_deal" . '" value="' . $this->deal->ID_DEALS . '" />';
		$this->group_view->print_group_info($this->group, array('hide_print'=>true, 'DealRmOptionsForm'=>$this));
		echo '<p>' . '<input type="submit" value="' . "Wybierz zaznaczone opcje" . '" />' . '</p>';
		echo '</form>';
	}

	function run() {

		if ($this->is_sent()) {

			$this->validate();

			if ($this->is_valid()) {
				if (!$this->is_confirmed()) {
					$print_link = $this->generate_print_link();
					$this->print_selected_options("Wybrano dodatkowe opcje do wyłączenia {$print_link}");
					echo '<form action="" method="POST">';
						echo '<input type="submit" name="accept" value="' . "Wyłącz wybrane opcje" . '" />';
						echo " lub ". '<a href="' . "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&task=klient_umowy&id_user={$this->deal->ID_BILLING_USERS}" . '">' . "cofnij" . '</a>';
					echo '</form>';
				} else {
					$this->save();
				}
				return;
			}
			else {
				echo '<p style="color:red">' . "Wystąpiły następujące błędy: ". '<br />' . implode('<br />', $this->_errors) . '</p>';
			}
		}

		$this->print_form();
	}

	function save() {
		$this->print_selected_options('Wybrano dodatkowe opcje do wyłączenia');

		$opcje_by_id = $this->get_oferty_opcje_by_id();

		$deals_table = new Column_deals_table();
		$deals_table->set('P_ID', $this->deal->ID_DEALS);
		$deals_table->set('ID_BILLING_USERS', $this->deal->ID_BILLING_USERS);
		$deals_table->set('S_ADDRESS_STREET', $this->deal->S_ADDRESS_STREET);
		$deals_table->set('DEALDESC', 'Deaktywacja opcji ' . implode(',', array_keys($opcje_by_id)));
		$deals_table->set('P_DEALDATE', date('Y-m-d'));
		$deals_table->_offers_rows = $opcje_by_id;

		$new_deal_id = $deals_table->create_opcje_deaktywacja();
		if ($new_deal_id > 0) {
			echo '<p style="color:green">' . "Pomyślnie utworzono rekord w DEALS_TABLE {$new_deal_id}" . '</p>';

			$users2_deals = new Column_users2_deals();
			$users2_deals->set_deal_table($deals_table);
			$users2_deals->set_s_address_street($this->deal->S_ADDRESS_STREET);
			$users2_deals->set_p_dealnumber_new($new_deal_id);
			if (!$users2_deals->create_rows()) {
				echo '<p style="color:red">' . "Error: wystąpił błąd podczas dodawania rekordów do USERS2_DEALS" . '</p>';
				$this->_show_deal_form = true;
			} else {
				echo '<p style="color:green">' . "Utworzono rekordy w tabeli USERS2_DEALS dla nowej umowy (ID=" . $new_deal_id . ")" . '</p>';
				$this->_show_deal_form = false;
			}
		} else {
			echo '<p style="color:red">' . "Nie udało się utworzyć rekordu w DEALS_TABLE" . '</p>';
		}
	}

}


class DealAddOptionsForm extends DealOptionsForm {

	function generate_print_link() {
		$link_href = "./odt2xhtml/1657.opcje-zamowienie.php";
		$link_args = array();
		foreach ($this->options as $k_service => $v_options_ids) {
			foreach ($v_options_ids as $v_option_id) {
				$link_args []= "id_options_{$k_service}[]={$v_option_id}";
			}
		}
		$link_href .= "?id_user={$this->deal->ID_BILLING_USERS}&" . implode("&", $link_args);
		$link_ico = '<img src="icon/print.gif" height="24" />';
		$out = '<a href="' . $link_href . '" target="_blank">' . " drukuj {$link_ico}" . '</a>';
		return $out;
	}

	function validate() {
		$opcje_by_id = $this->get_oferty_opcje_by_id();
		if (empty($opcje_by_id)) {
			$this->_errors []= 'Nie wybrano żadnych opcji';
		}
	}

	function print_form() {
		if ($this->is_sent() && $this->is_valid()) {
			return;
		}

		echo '<p>' . "Zaznacz opcje do dodania do umowy {$this->deal->ID_DEALS}" . '</p>';
		echo '<form action="" method="GET">';
			echo '<input type="hidden" name="' . "MENU_INIT" . '" value="' . "POKAZ_OFERTY_AKTUALNE_FUNC" . '" />';
			echo '<input type="hidden" name="' . "task" . '" value="' . "umowa_add_options" . '" />';
			echo '<input type="hidden" name="' . "id_user" . '" value="' . $this->deal->ID_BILLING_USERS . '" />';
			echo '<input type="hidden" name="' . "id_deal" . '" value="' . $this->deal->ID_DEALS . '" />';
		$this->group_view->print_group_info($this->group, array('hide_print'=>true, 'DealAddOptionsForm'=>$this));
		echo '<p>' . '<input type="submit" value="' . "Wybierz zaznaczone opcje" . '" />' . '</p>';
		echo '</form>';
	}

	function run() {

		if ($this->is_sent()) {

			$this->validate();

			if ($this->is_valid()) {
				if (!$this->is_confirmed()) {
					$print_link = $this->generate_print_link();
					$this->print_selected_options("Wybrano dodatkowe opcje do uruchomienia {$print_link}");
					echo '<form action="" method="POST">';
						echo '<input type="submit" name="accept" value="' . "Dodaj wybrane opcje do umowy" . '" />';
						echo " lub ". '<a href="' . "?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&task=klient_umowy&id_user={$this->deal->ID_BILLING_USERS}" . '">' . "cofnij" . '</a>';
					echo '</form>';
				} else {
					$this->save();
				}
				return;
			}
			else {
				echo '<p style="color:red">' . "Wystąpiły następujące błędy: ". '<br />' . implode('<br />', $this->_errors) . '</p>';
			}
		}

		$this->print_form();
	}

	function save() {
		$this->print_selected_options('Wybrano dodatkowe opcje do uruchomienia');

		$opcje_by_id = $this->get_oferty_opcje_by_id();

		$deals_table = new Column_deals_table();
		$deals_table->set('P_ID', $this->deal->ID_DEALS);
		$deals_table->set('ID_BILLING_USERS', $this->deal->ID_BILLING_USERS);
		$deals_table->set('S_ADDRESS_STREET', $this->deal->S_ADDRESS_STREET);
		$deals_table->set('DEALDESC', 'Aktywacja opcji ' . implode(',', array_keys($opcje_by_id)));
		$deals_table->set('P_DEALDATE', date('Y-m-d'));
		$deals_table->_offers_rows = $opcje_by_id;

		$new_deal_id = $deals_table->create_opcje_aktywacja();
		if ($new_deal_id > 0) {
			echo '<p style="color:green">' . "Pomyślnie utworzono rekord w DEALS_TABLE {$new_deal_id}" . '</p>';

			$users2_deals = new Column_users2_deals();
			$users2_deals->set_deal_table($deals_table);
			$users2_deals->set_s_address_street($this->deal->S_ADDRESS_STREET);
			$users2_deals->set_p_dealnumber_new($new_deal_id);
			if (!$users2_deals->create_rows()) {
				echo '<p style="color:red">' . "Error: wystąpił błąd podczas dodawania rekordów do USERS2_DEALS" . '</p>';
				$this->_show_deal_form = true;
			} else {
				echo '<p style="color:green">' . "Utworzono rekordy w tabeli USERS2_DEALS dla nowej umowy (ID=" . $new_deal_id . ")" . '</p>';
				$this->_show_deal_form = false;
			}
		} else {
			echo '<p style="color:red">' . "Nie udało się utworzyć rekordu w DEALS_TABLE" . '</p>';
		}
	}

}


class DealActivateOptionsForm {

	var $deal;
	var $active_deals_by_id;
	var $p_active_deal;
	var $offers_rows;
	var $user;
	var $group;// Column_users2_offers_groups

	function set_deal($deal) {
		$this->deal = $deal;
	}

	function fetch_data() {
		$this->user = PokazOfertyHelper::get_user_info($this->deal->get('ID_BILLING_USERS'));
		$this->active_deals_by_id = PokazOfertyHelper::get_deals_active_by_user($this->user->ID_BILLING_USERS);
		$this->p_active_deal = $this->active_deals_by_id[$this->deal->get('P_ID')];
		$id_offers_on = $this->deal->get('ID_OFFERS_ON');
		$id_offers_on = explode(',', $id_offers_on);
		$this->group = PokazOfertyHelper::get_group($this->p_active_deal->ID_OFFERS_GROUP);
		$this->group->fetch_offers();
		$this->offers_rows = PokazOfertyHelper::get_offers_by_id($id_offers_on);
	}

	function run() {
		$this->fetch_data();

		$pokaz_oferty_view = new PokazOfertyView();
		echo $pokaz_oferty_view->print_css();
		$pokaz_oferty_view->user_with_services($this->user, $this->active_deals_by_id);
		$pokaz_oferty_view->print_group_info($this->group, array('hide_print'=>true));

		$options_tree = array();
		foreach ($this->offers_rows as $k_offer_id => $v_offer) {
			$options_tree[$v_offer->P_SERVICE_PARENT][$k_offer_id] = $v_offer;
		}
		$cols = PokazOfertyHelper::get_oferty_opcje_visible_cols();
		$pokaz_oferty_view->print_options_tree($options_tree, $cols);

		$this->save_preview();

		if (1 == V::get('accept', 0, $_POST, 'int')) {
			$this->save();
		}

		echo '<form action="" method="POST">';
			echo '<input type="hidden" name="' . "accept" . '" value="' . "1" . '" />';
			echo '<input type="submit" value="' . "Aktywuj wybrane opcje" . '" />';
		echo '</form>';

		echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">active_deal (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->p_active_deal);echo'</pre>';
		echo '<p>TODO: run L.' . __LINE__ . '</p>';
		echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this);echo'</pre>';
	}

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

	function save_preview() {
		echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this);echo'</pre>';
		$this->_srv_to_create = array();
		$this->_srv_to_update = array();
		// generate preview
		// $this->p_active_deal;
		// $this->p_active_deal->services
		// $this->p_active_deal->services_by_id
		// $this->p_active_deal->ses_x_a
		foreach ($this->offers_rows as $k_id => $v_option) {
			echo '<p>' . "opcja {$k_id}; P_SERVICE_PARENT: {$v_option->P_SERVICE_PARENT}" . '</p>';
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($v_option);echo'</pre>';
			if (!empty($v_option->ID_DOMAINS)	&& $v_option->ID_DOMAINS_PACKET_ID > 0) {
				$this->_srv_to_create[$v_option->ID] = $v_option;
			}
			else {
				$found_service = null;
				if (array_key_exists($v_opcja->P_SERVICE_PARENT, $this->p_active_deal->services)) {
					if (count($this->p_active_deal->services[$v_opcja->P_SERVICE_PARENT]) > 1) {
						// TODO: za duzo SERVICES
					}
				}
				//$offers[$k_id]->_options[$k_option_id] = $offers[$k_option_id];
			}
		}
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">_srv_to_create (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_srv_to_create);echo'</pre>';
		return;

		// create new _services objects
		foreach ($this->_srv_to_create as $k_offer_id => $v_params) {
			$offer = $offers[$k_offer_id];
			$srv = new Column_services();
			$srv->set_id_deals_table($this->_deal->get('ID'));
			$srv->set_id_billing_users($this->_deal->get('ID_BILLING_USERS'));
			$srv->set_s_address_street($this->_deal->get('S_ADDRESS_STREET'));
			$srv->set_services_map($this->get_service_type_map());
			$srv->set_data_from_oferta_row($offer);

			if (($old_srv_id = V::get('old_srv_id', 0, $v_params)) > 0) {
				$srv->set_old_srv_id($old_srv_id);
				$srv->set_old_srv($this->get_old_srv_by_id($old_deal_id, $old_srv_id));
				$srv->set('A_STATUS', 'NORMAL');
				// TODO: HANGUP_FROM i inne parametry wymagane do uruchomienia usługi
				
				// _srv_to_off
				$this->_srv_to_off [$old_srv_id] = true;
			}

			$this->_services []= $srv;
		}

	}

}


class DealActivateRezygnacja {

	var $deal;
	var $_user_active_deals = null;
	var $_errors = array();

	function add_error($msg) {
		$this->_errors []= $msg;
	}

	function get_errors() {
		return $this->_errors;
	}

	function has_errors() {
		return !empty($this->_errors);
	}

	function set_deal($deal) {
		$this->deal = $deal;
	}

	function _fetch_active_deals() {
		if ($this->_user_active_deals === null) {
			$user_id = $this->deal->get('ID_BILLING_USERS');
			$this->_user_active_deals = array();
			if ($user_id > 0) {
				$this->_user_active_deals = PokazOfertyHelper::get_deals_active_by_user($user_id);
			}
		}
		return $this->_user_active_deals;
	}

	function get_deal_old() {
		$old_active_deals = $this->_fetch_active_deals();
		$deal_old_id = $this->deal->get('P_DEALNUMBER_OLD');
		if ($deal_old_id <= 0) {
			return false;
		}
		if (array_key_exists($deal_old_id, $old_active_deals)) {
			return $old_active_deals[$deal_old_id];
		}
		return false;
	}

	function validate() {
		$user_id = $this->deal->get('ID_BILLING_USERS');
		if ($user_id <= 0) {
			$this->add_error('Brak ID klienta (ID_BILLING_USERS)');
		}
		$deal_old_id = $this->deal->get('P_DEALNUMBER_OLD');
		if ($deal_old_id <= 0) {
			$this->add_error('Brak numeru ID starej umowy (P_DEALNUMBER_OLD)');
		}
		$street = $this->deal->get('S_ADDRESS_STREET');
		if (empty($street)) {
			$this->add_error('Brak adresu (S_ADDRESS_STREET)');
		}
		$l2_hangup_from = $this->deal->get('L2_HANGUP_FROM');
		if (empty($l2_hangup_from)) {
			$this->add_error('Brak daty odłączenia usług (L2_HANGUP_FROM)');
		}
		else if (strlen($l2_hangup_from) != 10 || strlen(str_replace('-', '', $l2_hangup_from)) != 8 || !is_numeric(str_replace('-', '', $l2_hangup_from))) {
			$this->add_error('Błędna data odłączenia usług (L2_HANGUP_FROM)');
		}

		//$id_offers_off = $this->deal->get('ID_OFFERS_OFF');// wypełnić poprawnymi ID ofert z aktualnych usług
		//$id_offers_off = (!empty($id_offers_off))? explode(',', $id_offers_off) : array();
		if (!$this->has_errors()) {
			$old_deal = $this->get_deal_old();
			if (empty($old_deal)) {
				$this->add_error("Umowa ID {$deal_old_id} nie ma aktywnych usług (P_DEALNUMBER_OLD)");
			} else {
				if (!empty($old_deal->services_by_id)) {
					$id_offers_off_by_srv = array();
					foreach ($old_deal->services_by_id as $k_srv_id => $v_srv) {
						if ($v_srv->ID_OFFERS > 0) {
							$id_offers_off_by_srv []= $v_srv->ID_OFFERS;
						} else {
							$this->add_error("Brak numeru oferty w usłudze ID {$v_srv->ID} typu {$v_srv->P_SERVICE} (ID_OFFERS)");
						}
					}
					//if (empty($id_offers_off) || count($id_offers_off_by_srv) > count($id_offers_off)) {
					$this->deal->set('ID_OFFERS_OFF', implode(',', $id_offers_off_by_srv));
					//}
				}
			}
		}

		return !$this->has_errors();
	}

	function run() {
		echo '<h1>' . "Aktywacja rezygnacji" . '</h1>';

		if (!$this->validate()) {
			echo '<p style="color:red">' . "Error: nie można aktywować rezygnacji:" . '</p>';
			echo '<ul style="color:red"><li>' . implode('</li><li>', $this->get_errors()) . '</li></ul>';
		}

		$id_user = $this->deal->get('ID_BILLING_USERS');
		$user = PokazOfertyHelper::get_user_info($id_user);
		if (!$user) {
			echo '<p>' . "Error: brak danych o kliencie {$id_user}" . '</p>';
			return;
		}

		$active_deals_by_id = $this->_fetch_active_deals();

		$pokaz_oferty_view = new PokazOfertyView();
		echo $pokaz_oferty_view->print_css();
		echo $pokaz_oferty_view->print_jquery_ui();
		$pokaz_oferty_view->user_with_services($user, $active_deals_by_id);

		if (1 == V::get('accept', 0, $_POST, 'int')) {
			Lib::loadClass('SimulateDBTask');
			$db = DB::getDB();
			$simulate_db = new SimulateDBTask($db, "DEALS_TABLE-" . $this->deal->get('ID'));

			if ($this->save($simulate_db)) {
				echo $pokaz_oferty_view->print_ui_widget_ok("Rezygnację aktywowano pomyślnie");

				if ($simulate_db) {
					echo '<div style="border:1px solid #333; background:#eee; display:none;">';
					echo '<p>' . "Run database tasks:" . '</p>';
					$simulate_db->run();
					echo '<p>' . "database tasks end." . '</p>';
					echo '</div>';
				}

				return;
			} else {
				echo $pokaz_oferty_view->print_ui_widget_errors('wystąpiły błądy podczas aktywacji rezygnacji', $this->get_errors());
			}

		}

		$old_deal = $this->get_deal_old();
		echo '<h2>' . "Podgląd wprowadzanych zmian - rezygnacja z umowy ID {$old_deal->ID_DEALS}" . '</h2>';
		if (!empty($old_deal->services_by_id)) {
			$id_offers_off_by_srv = array();
			foreach ($old_deal->services_by_id as $k_srv_id => $v_srv) {
				$cols = array('ID', 'NAME_LIST_SERVICES', 'A_STATUS', 'ABONAMENT_VALUE', 'description', 'ID_OFFERS', 'HANGUP_FROM', 'HANGUP_STATUS');
				$v_srv->HANGUP_FROM = $this->deal->get('L2_HANGUP_FROM');
				$v_srv->HANGUP_STATUS = 'OFF_HARD';
				$v_srv->HANGUP_RATIO = 1;
				PokazOfertyView::print_simple_tbl($v_srv, $cols, "Usługa {$v_srv->P_SERVICE} (ID={$v_srv->ID})");

				$cols = array('ID', 'S_ADDRESS_STREET', 'A_PROBLEM', 'A_PROBLEM_DESC', 'A_PROBLEM_DATE');
				$v_srv_a = $old_deal->ses_x_a[$k_srv_id];
				$v_srv_a->A_PROBLEM = 'UNVERIFIED';
				$v_srv_a->A_PROBLEM_DATE = date('Y-m-d-H:i');
				$v_srv_a->A_PROBLEM_DESC = "Rezygnacja z dniem: " . $this->deal->get('L2_HANGUP_FROM') . "\n" . $v_srv_a->A_PROBLEM_DESC;
				PokazOfertyView::print_simple_tbl($v_srv_a, $cols, "Parametry usługi {$v_srv->P_SERVICE} (ID={$v_srv->ID})");
			}
		}

		echo '<br />';
		echo '<form action="" method="POST">';
			echo '<input type="hidden" name="' . "accept" . '" value="' . "1" . '" />';
			echo '<input type="submit" value="' . "Aktywuj rezygnację" . '" />';
		echo '</form>';
	}

	function save($simulate_db = null) {
		$log_arr = array();
		$id_offers_off_by_srv = array();
		$old_deal = $this->get_deal_old();
		if (!empty($old_deal->services_by_id)) {
			foreach ($old_deal->services_by_id as $k_srv_id => $v_srv) {
				$id_offers_off_by_srv []= $v_srv->ID_OFFERS;

				$sql_obj = new stdClass();
				$sql_obj->ID = $v_srv->ID;
				$sql_obj->HANGUP_STATUS = 'OFF_HARD';
				$sql_obj->HANGUP_FROM = $this->deal->get('L2_HANGUP_FROM');
				$sql_obj->HANGUP_RATIO = 1;
				if ($simulate_db) {
					$simulate_db->add('UPDATE_OBJ', 'SERVICES', $sql_obj);
				} else {
					if ($db->UPDATE_OBJ('SERVICES', $sql_obj) <= 0) {
						$this->add_error("nie udało się wyłączyć usługi {$v_srv->ID}");
					} else {
						$log_arr []= "wyłączono usługę {$v_srv->ID} (HANGUP_STATUS na OFF_HARD, HANGUP_FROM: " . $this->deal->get('L2_HANGUP_FROM') . ")";
					}
				}

				if ($v_srv->NAME_LIST_SERVICES == 'USERS2') {
					continue;// nie wystawiaj problemów dla internetu
				}

				if (isset($old_deal->ses_x_a[$k_srv_id])) {
					$v_srv_a = $old_deal->ses_x_a[$k_srv_id];
					$sql_obj = new stdClass();
					$sql_obj->ID = $v_srv_a->ID;
					$sql_obj->A_PROBLEM = 'UNVERIFIED';
					$sql_obj->A_PROBLEM_DATE = date('Y-m-d-H:i');
					$sql_obj->A_PROBLEM_DESC = "Rezygnacja z dniem: " . $this->deal->get('L2_HANGUP_FROM');
					if (!empty($v_srv_a->A_PROBLEM) && !empty($v_srv_a->A_PROBLEM_DESC)) {
						$sql_obj->A_PROBLEM_DESC .= "\n" . $v_srv_a->A_PROBLEM_DESC;
					}

					$ses_x_a_tbl = 'SES_' . $v_srv->NAME_LIST_SERVICES . '_A';
					if ($simulate_db) {
						$simulate_db->add('UPDATE_OBJ', $ses_x_a_tbl, $sql_obj);
					} else {
						if ($db->UPDATE_OBJ($ses_x_a_tbl, $sql_obj) <= 0) {
							$this->add_error("nie udało się dodać problemu dla usługi {$v_srv->ID}");
						} else {
							$log_arr []= "dodano problem do usługi {$ses_x_a_tbl} ID_SERVICES={$v_srv->ID}";
						}
					}

				} else {
					$this->add_error("brak rekordu ses_x_a dla usługi {$v_srv->ID}");
				}
			}
		}

		$sql_obj = new stdClass();
		$sql_obj->ID = $this->deal->get('ID');
		$sql_obj->A_STATUS = 'NORMAL';
		$sql_obj->ID_OFFERS_OFF = implode(',', $id_offers_off_by_srv);
		if ($simulate_db) {
			$simulate_db->add('UPDATE_OBJ', 'DEALS_TABLE', $sql_obj);
		} else {
			if ($db->UPDATE_OBJ('DEALS_TABLE', $sql_obj) <= 0) {
				$this->add_error("nie udało się aktywować umowy " . $this->deal->get('ID'));
				return false;
			} else {
				$log_arr []= "aktywowano umowę " . $this->deal->get('ID') . " (status na NORMAL)";
			}
		}
		return !$this->has_errors();
	}

}


// &task=activate_services_tv&id_services={ID_SERVICES}&id_ses_a={ID}
function POKAZ_OFERTY_AKTUALNE_FUNC__activate_services_tv() {
	echo '<div class="container">';
	POKAZ_OFERTY_AKTUALNE_FUNC__activate_services('tv');
	echo '</div>';
}


// &task=activate_services_net&id_services={ID_SERVICES}&id_ses_a={ID}
function POKAZ_OFERTY_AKTUALNE_FUNC__activate_services_net() {
	echo '<div class="container">';
	POKAZ_OFERTY_AKTUALNE_FUNC__activate_services('net');
	echo '</div>';
}


// &task=activate_services_voip&id_services={ID_SERVICES}&id_ses_a={ID}
function POKAZ_OFERTY_AKTUALNE_FUNC__activate_services_voip() {
	echo '<div class="container">';
	POKAZ_OFERTY_AKTUALNE_FUNC__activate_services('voip');
	echo '</div>';
}


function POKAZ_OFERTY_AKTUALNE_FUNC__activate_services($type) {
	$id_services = V::get('id_services', 0, $_GET, 'int');
	$id_ses_a = V::get('id_ses_a', 0, $_GET, 'int');

	$sqlTable = '';
	$sqlSesBTable = '';
	if ($type == 'tv') {
		$sqlTable = 'SES_TV_A';
		$sqlSesBTable = 'SES_TV_B';
	} else if ($type == 'net') {
		$sqlTable = 'SES_USERS2_A';
		$sqlSesBTable = 'SES_USERS2_B';
	} else if ($type == 'voip') {
		$sqlTable = 'SES_VOIP_A';
		$sqlSesBTable = 'SES_VOIP_B';
	}

	if (empty($sqlTable)) {
		echo '<div class="alert alert-error">Wrong type</div>';
		return;
	}

	$db = DB::getDB();

	$srv = $db->get_by_id('SERVICES', $id_services);
	$ses_a = $db->get_by_id($sqlTable, $id_ses_a);

	if (!$srv) {
		echo '<div class="alert alert-error">Services nie istnieje</div>';
		return;
	}
	if (!$ses_a) {
		echo '<div class="alert alert-error">Ses_x_a nie istnieje</div>';
		return;
	}

	if ($ses_a->ID_SERVICES != $srv->ID) {
		echo '<div class="alert alert-error">Błąd w strukturze - ID_SERVICES</div>';
		return;
	}

	if(V::get('DBG_UA', '', $_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$srv (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($srv);echo'</pre>';}
	if(V::get('DBG_UA', '', $_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$ses_a (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($ses_a);echo'</pre>';}

	// fetch SES_X_B
	$sesB = array();
	$sql = "select b.*
		from `{$sqlSesBTable}` as b
		where b.`ID_SERVICES`='{$id_services}'
			and b.`TYPE`=4
	";
	$res = $db->query($sql);
	while ($r = $db->fetch($res)) {
		$sesB[] = $r;
	}

	if (!empty($sesB)) {
		$activationDate = end($sesB);
		$activationDate = $activationDate->VALUE1;
		echo '<div class="alert alert-info">' . "Usługa została już aktywowana dnia {$activationDate}" . '</div>';
	} else {
		echo '<div class="alert alert-warning">' . "Usługa nie została jeszcze poprawnie aktywowana" . '</div>';
	}

	$frmFldsNamesOnly = array('ID', 'ID_SERVICES', 'T_WHO_CONNECTED', 'T_WHEN_CONNECTED', 'S_ADDRESS_STREET');
	$frmFldsNamesWriteOnly = array('T_WHO_CONNECTED', 'T_WHEN_CONNECTED');

	Lib::loadClass('ProcesHelper');
	$zasobID = ProcesHelper::getZasobTableID($sqlTable);

	$userAcl = User::getAcl();
	$userAcl->fetchGroups();

	if (!$userAcl->hasTableAcl($zasobID)) {
		die("Brak uprawnień do tabeli ID={$zasobID}");
	}

	$tblAcl = $userAcl->getTableAcl($zasobID);

	$forceTblAclInit = ('1' == V::get('_force', '', $_GET));
	$tblAcl->init($forceTblAclInit);

	Lib::loadClass('Data_Source');
	$dataSource = new Data_Source($tblAcl->getDB());
	$dataSource->setTable($tblAcl->getName());
	$dataSource->setCols($tblAcl->getRealFieldList());
	$dataSource->setColTypes($tblAcl->getTypes());
	$dataSource->setVirtualCols($tblAcl->getVirtualFieldList());
	$dataSource->setFieldGroupWrite('A_ADM_COMPANY', $tblAcl->hasFieldType('A_ADM_COMPANY'));
	$dataSource->setFieldGroupRead('A_CLASSIFIED', $tblAcl->hasFieldType('A_CLASSIFIED'));

	$cols = array();

	$record = $dataSource->getItem($id_ses_a);
	if (!$tblAcl->canWriteRecord($record)) {
		echo '<div class="alert alert-error">';
			echo "Brak dostępu do rekordu";// TODO: more info - reason
		echo '</div>';
		return;
	}

	$fieldsList = $tblAcl->getFields();
	foreach ($fieldsList as $kID => $vCol) {
		if (!in_array($vCol['name'], $frmFldsNamesOnly)) {
			unset($fieldsList[$kID]);
			continue;
		}

		if ($vCol['name'] == 'ID') {
			unset($fieldsList[$kID]);
			continue;
		}
		$cols[$kID] = V::get($vCol['name'], '', $record);
		$cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);

		if ($vCol['name'] == 'T_WHEN_CONNECTED' && empty($cols[$kID])) {
			$cols[$kID] = date("Y-m-d");
		}

		$fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : str_replace('_', ' ', $vCol['name']);
	}

	$tsValues = array();
	if (!empty($fieldsList)) {
		Lib::loadClass('Typespecial');
		foreach ($fieldsList as $vColID => $vCol) {
			$typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
			if ($typeSpecial) {
				$colValue = V::get($vCol['name'], '', $record);
				$specialValues = $typeSpecial->getEditSelectedValuesByIds($zasobID, $record->ID, $vCol['name'], $colValue);
				if (!empty($specialValues)) {
					$tsValues[$vColID] = implode('<br>', $specialValues);
				}
			}
		}
	}

	POKAZ_OFERTY_AKTUALNE_FUNC__activate_services_save($tblAcl, $fieldsList, $sqlTable, $sqlSesBTable, $_POST);

	?>
	<form class="form-horizontal" action="" method="post">
		<input type="hidden" name="_save" value="1">
			<fieldset>
				<legend>Aktywacja usługi <?php echo $type; ?></legend>

				<?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
					<?php if (in_array($vCol['name'], $frmFldsNamesWriteOnly) && $tblAcl->isAllowed($kID, 'W', $record)) : ?>
						<div class="control-group">
							<label class="control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
								<i class="icon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
							</label>
							<div class="controls">
								<?php
									$fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
									if (!empty($tsValues[$kID])) {
										$fieldParams['typespecialValue'] = $tsValues[$kID];
									}
									echo $tblAcl->showFormItem('W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record);
								?>
							</div>
						</div>
					<?php elseif ($tblAcl->isAllowed($kID, 'R', $record)) : ?>
						<div class="control-group">
							<label class="control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
								<i class="icon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
							</label>
							<div class="controls">
								<p style="margin-top:5px;">
								<?php
									//echo $this->_acl->showFormItem('R', $kID, "f{$kID}", $cols[$kID], array('appendBack'=>true), $record);
									if (!empty($tsValues[$kID])) {
										echo $tsValues[$kID];
									} else if (!empty($record->{$vCol['name']})) {
										echo $record->{$vCol['name']};
									}
								?>
								</p>
							</div>
						</div>
					<?php endif; ?>
				<?php endforeach; ?>

				<div class="control-group">
					<div class="controls">
						<button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Zapisz</button>
						<a class="btn btn-default" href="index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $zasobID; ?>">Wróć</a>
					</div>
				</div>

			</fieldset>
	</form>

	<script>
	jQuery(document).ready(function(){
		jQuery('.frm-help').popover({trigger:'hover'});
	});
	</script>
	<?php
}

function POKAZ_OFERTY_AKTUALNE_FUNC__activate_services_save($tblAcl, $fieldsList, $sqlTable, $sqlSesBTable, $args) {
	if (1 != V::get('_save', '', $_POST, 'int')) {
		return;
	}

	$id_ses_a = V::get('id_ses_a', 0, $_GET, 'int');
	$T_WHEN_CONNECTED = '';

	foreach ($fieldsList as $kID => $vCol) {
		if ($vCol['name'] == 'T_WHEN_CONNECTED') {
			$T_WHEN_CONNECTED = V::get("f{$kID}", '', $args);
		}
	}

	if(V::get('DBG_UA', '', $_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">args (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($args);echo'</pre>';}

	if (empty($T_WHEN_CONNECTED)) {
		echo '<div class="alert alert-error">' . "Brak daty podłączenia (T_WHEN_CONNECTED)" . '</div>';
		return;
	}

	$db = DB::getDB();

	$record = $db->get_by_id($sqlTable, $id_ses_a);
	if (!$tblAcl->canWriteRecord($record)) {
		echo '<div class="alert alert-error">';
			echo "Brak dostępu do rekordu";// TODO: more info - reason
		echo '</div>';
		return;
	}

	$sqlObj = new stdClass();
	foreach ($fieldsList as $kID => $vField) {
		if (!$tblAcl->isAllowed($kID, 'W', $record)) {
			continue;
		}
		if (array_key_exists("f{$kID}", $args)) {
			$sqlObj->{$vField['name']} = $args["f{$kID}"];

			if (empty($args["f{$kID}"]) && strlen($args["f{$kID}"]) == 0) {// fix bug in input type date and value="0000-00-00"
				$sqlObj->{$vField['name']} = $this->fixEmptyValueFromUser($kID);
			}
		}
	}
	$sqlObj->ID = $record->ID;
	if(V::get('DBG_UA', '', $_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sqlObj);echo'</pre>';}

	$ret = $db->UPDATE_OBJ($sqlTable, $sqlObj);
	if ($ret > 0) {
		echo '<div class="alert alert-success">';
			echo "Rekord zapisany pomyślnie";//"Record saved successfully";
		echo '</div>';
	} else if ($ret == 0) {
		echo '<div class="alert alert-info">';
			echo "Nie wprowadzono żadnych zmian";
		echo '</div>';
	} else {
		header('HTTP/1.0 404 Not Found');
		echo '<div class="alert alert-error">';
			echo '<h4>' . "Wystąpiły błędy!" . '</h4>';
			if ($db->has_errors()) {
				$errors = $db->get_errors();
				echo implode('<br>', $errors);
			}
		echo '</div>';
		exit;
	}

	$sql = "insert into {$sqlSesBTable} (`ID`, `ID_SERVICES`, `ID_BILLING_USERS`, `TIMESTAMP`, `TYPE`, `VALUE1`)
		select '', U.ID_SERVICES, SV.ID_BILLING_USERS, now(), '4', '{$T_WHEN_CONNECTED}'
		from {$sqlTable} as U
			left join SERVICES as SV on SV.`ID`=U.`ID_SERVICES`
		where U.`ID`='{$id_ses_a}'
	";
	if(V::get('DBG_UA', '', $_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql 1 (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
	$res = $db->query($sql);
	if (!$res) {
		echo '<div class="alert alert-error">' . "Nie udało się dodać rekordu do tabeli {$sqlSesBTable}" . '</div>';
	} else {
		$ret_id = $db->insert_id();
		if (!$ret_id) {
			echo '<div class="alert alert-error">' . "Nie udało się dodać rekordu do tabeli {$sqlSesBTable}" . '</div>';
		} else {
			echo '<div class="alert alert-success">' . "Dodano rekord do tabeli {$sqlSesBTable}" . '</div>';
		}
	}

	$sql = "update `SERVICES` as SV, `{$sqlTable}` as U
		set SV.`A_STATUS`='NORMAL', U.`A_STATUS`='NORMAL'
		where U.`ID_SERVICES`=SV.`ID`
			and SV.`A_STATUS` in('WAITING', 'NORMAL')
			and U.`ID`='{$id_ses_a}'
	";
	if(V::get('DBG_UA', '', $_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql 2 (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
	$res = $db->query($sql);
	if (!$res) {
		echo '<div class="alert alert-error">' . "Nie udało się zaktualizować statusów" . '</div>';
	} else {
		$ret = $db->affected_rows();
		if ($ret > 0) {
			echo '<div class="alert alert-info">' . "Zaktualizowano statusy dla {$ret} rekordów" . '</div>';
		}
	}


}

function POKAZ_OFERTY_AKTUALNE_FUNC__ajaxUmowaZysk() {
	$jsonData = new stdClass();
	
	try {
		$jsonData = POKAZ_OFERTY_AKTUALNE_FUNC__ajaxUmowaZysk_createJson();
	}
	catch (Exception $e) {
		$jsonData->type = 'error';
		$jsonData->msg = $e->getMessage();
	}
	echo json_encode($jsonData);
	exit;
}

function POKAZ_OFERTY_AKTUALNE_FUNC__ajaxUmowaZysk_createJson() {
	$jsonData = new stdClass();
	$con = new PokazOfertyController();
	$con->set_params_from_request();

	if ($con->hasOptionsToServices()) {
		if (!$con->convertOptionsToSrv()) {
			throw new Exception("Nie udało się utworzyć nowej grupy na podstawie wybranych parametrów.");
		}
	}

	$jsonData->con = $con;

	$group = $con->get_group();
	if (!$group) {
		throw new Exception("Brak grupy");
	}

	$group->fetch_offers();
	$jsonData->zysk = $group->get_zysk_netto();
	$jsonData->zyskabonament_srednia_netto = $group->get_srednia_netto();

	$procenty = array();
	$procenty[]= 2;
	$procenty[]= 5;
	$procenty[]= 10;
	$procenty[]= 15;
	$procenty[]= 30;

	$suma_P_PROMO_MONTH_PRICE = $group->suma_P_PROMO_MONTH_PRICE;
	$suma_P_CONTRACT_PRICE = $group->suma_P_CONTRACT_PRICE;

	ob_start();
	?>

<b>Oferty</b> <i>(w promocji/po promocji)</i>
<?php foreach ($group->_offers_by_id as $nrOferty => $oferta) : ?>
	<br>&nbsp;&nbsp; <span title="<?php echo $oferta->P_SERVICE_NAME; ?>">
		<?php echo $oferta->ID; ?> <?php echo $oferta->P_SERVICE; ?>
		<i>(<?php echo number_format($oferta->P_PROMO_MONTH_PRICE, 2, ',', ''); ?>
			/
			<?php echo number_format($oferta->P_CONTRACT_PRICE, 2, ',', ''); ?>)
		</i>
	</span>
<?php endforeach; ?>

<br><b>Zysk</b> <i>(netto)</i>: <?php echo number_format($jsonData->zysk, 2, ',', ''); ?>
<?php foreach ($procenty as $procent) : ?>
	<br>&nbsp;&nbsp;&nbsp; <?php echo $procent; ?>%: <?php echo number_format($jsonData->zysk * $procent / 100, 2, ',', ''); ?>
<?php endforeach; ?>
<br><b>Abonament miesięczny</b> <i>(brutto)</i>:
<br>&nbsp;&nbsp; w promocyjnych mies.: <?php echo number_format($suma_P_PROMO_MONTH_PRICE, 2, ',', ' '); ?>
<br>&nbsp;&nbsp; po promocji: <?php echo number_format($suma_P_CONTRACT_PRICE, 2, ',', ' '); ?>

	<?php
	$jsonData->html = ob_get_contents();
	ob_clean();

	return $jsonData;
}
