<?php

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

/**
 * Module init.
 */
function USERS2_OFFERS_GROUPS() {
	global $thiss;

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

	// init columns if not set
	if (empty($_SESSION['USERS2_OFFERS_GROUPS' . "_COLUMN"]['ID'])) {
		SEF('USERS_COLUMN_INIT2');
		USERS_COLUMN_INIT2('USERS2_OFFERS_GROUPS', '', 'RWXC');
	}

	// router
	$task = V::get('task', '', $_REQUEST);
	$sub_task = V::get('sub_task', '', $_REQUEST);
	switch ($sub_task) {
		case 'GROUP_STATUS': {// POST: sub_task=GROUP_STATUS&group_id=
			USERS2_OFFERS_GROUPS_group_status();
			break;
		}
		case 'GROUP_WWW': {// POST: sub_task=GROUP_WWW&group_id=
			USERS2_OFFERS_GROUPS_group_www();
			break;
		}
		case 'GROUP_STATUS_ALL': {// POST: sub_task=GROUP_STATUS_ALL
			USERS2_OFFERS_GROUPS_group_status_all();
			break;
		}
		case 'GROUP_WWW_ALL': {// POST: sub_task=GROUP_WWW_ALL
			USERS2_OFFERS_GROUPS_group_www_all();
			break;
		}
	}

	$params = array();
	$params['toolbar'] = array();
	$params['toolbar'] []= '<a href="' . "?MENU_INIT=USERS2_OFFERS_GROUPS" . "&task=KONFIGURATOR" . '">' . "KONFIGURATOR" . '</a>';

	switch ($task) {
		case 'KONFIGURATOR': {
			USERS2_OFFERS_GROUPS_konfigurator();
			break;
		}
		case 'KONFIGURATOR2': {
			$subtask = V::get('subtask', '', $_REQUEST);
			switch ($subtask) {
				case 'ajax_save': {
					USERS2_OFFERS_GROUPS_konfigurator2_ajax_save();
					break;
				}
				case 'ajax_fltrs': {
					USERS2_OFFERS_GROUPS_konfigurator2_ajax_fltrs();
					break;
				}
				default:
					USERS2_OFFERS_GROUPS_konfigurator2();
			}
			break;
		}
		default:
			WIEVTABLE( $params );// TODO: redirect to index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=1614
	}
}

function USERS2_OFFERS_GROUPS_EDIT() {
	SEF('EDIT_TABLE_RECORD');
	EDIT_TABLE_RECORD();
}

function USERS2_OFFERS_GROUPS_HIST() {
	SEF('WIEVTABLE_HIST');
	WIEVTABLE_HIST();
}

function USERS2_OFFERS_GROUPS_group_status() {
	$group_id = V::get('group_id', '', $_REQUEST, 'int');
	$change = V::get('change', '', $_REQUEST);
	if ($change == '-') {
		$change = 'OFF_HARD';
	}
	else if ($change == '+') {
		$change = 'NORMAL';
	}
	if ($group_id <= 0 || !in_array($change, array('NORMAL', 'OFF_HARD'))) {
		return;
	}

	$db = DB::getDB();
	$sqlObj = new stdClass();
	$sqlObj->ID = $group_id;
	$sqlObj->A_STATUS = $change;
	$db->UPDATE_OBJ('USERS2_OFFERS_GROUPS', $sqlObj);
}

function USERS2_OFFERS_GROUPS_group_www() {
	$group_id = V::get('group_id', '', $_REQUEST, 'int');
	$change = V::get('change', '', $_REQUEST);
	if ($change == '-') {
		$change = 'NIE';
	}
	else if ($change == '+') {
		$change = 'TAK';
	}
	if ($group_id <= 0 || !in_array($change, array('NIE', 'TAK'))) {
		return;
	}

	$db = DB::getDB();
	$sqlObj = new stdClass();
	$sqlObj->ID = $group_id;
	$sqlObj->OFERTA_WWW = $change;
	$db->UPDATE_OBJ('USERS2_OFFERS_GROUPS', $sqlObj);
}

function USERS2_OFFERS_GROUPS_group_status_all() {
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($_POST);echo'</pre>';
	$change = V::get('change', '', $_REQUEST);
	$sqlChange = '';
	if ($change == '-') {
		$sqlChange = 'OFF_HARD';
	}
	else if ($change == '+') {
		$sqlChange = 'NORMAL';
	}
	if (!in_array($sqlChange, array('NORMAL', 'OFF_HARD'))) {
		return;
	}

	$filters = array();// sql field -> form field name
	$filters ['P_PROMOTION_NAME']= 'f_P_PROMOTION_NAME';
	$filters ['P_OFFER_TERM_BEGIN']= 'f_P_OFFER_TERM_BEGIN';
	$filters ['P_OFFER_TERM']= 'f_P_OFFER_TERM';
	$filters ['P_SERVICE_COMPANY']= 'f_P_SERVICE_COMPANY';
	$filters ['A_STATUS']= 'f_A_STATUS';
	$filters ['S_ADDRESS_STREET']= 'f_S_ADDRESS_STREET';

	$args = array();
	foreach ($filters as $k_field_name => $v_req_field_name) {
		$args[$k_field_name] = V::get($v_req_field_name, '%', $_REQUEST);
	}

	$filters_empty = true;
	foreach ($args as $k => $v_value) {
		if ($v_value != '%') {
			$filters_empty = false;
		}
	}

	if (!$filters_empty) {
		$items = array();
		$total = 0;
		$totalAll = Offers_Groups_Model::get_total($args);
		if ($totalAll > 0) {
			$items = Offers_Groups_Model::get_items($args);

			$params = Offers_Groups_Konfigurator_Model::get_params_from_items($items);
			// user selected params
			$user_params_empty = true;
			$user_params = array();
			foreach ($params as $k_type => $v_params) {
				if (empty($v_params)) continue;
				$k_field_name = "p_" . $k_type;// "[]"
				$user_params[$k_type] = V::get($k_field_name, null, $_GET, 'array');
				if (!empty($user_params[$k_type])) {
					$user_params_empty = false;
				}
			}
			$user_items = Offers_Groups_Konfigurator_Model::get_items_by_params($items, $user_params);
			$total = count($user_items);
		}

		echo '<p>' . "Do zmiany ({$total}) rekordów:";
			echo '<form action="" method="POST" style="display:inline">';
			echo '<input type="hidden" name="sub_task" value="GROUP_STATUS_ALL" />';
			foreach ($_POST as $k => $v) {
				if ($k == 'sub_task') continue;
				if ($k == 'confirm') continue;
				if ($k == 'change') continue;
				echo '<input type="hidden" name="'.$k.'" value="'.$v.'" />';
			}
			echo '<input type="hidden" name="confirm" value="YES" />';
			echo " Aktualizuj wszystkie zmiany";
			echo '<input type="submit" name="change" value="'.$change.'" />';
			echo '</form>';
		echo '</p>';
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">';
		if ($total > 0) {
			$db = DB::getDB();
			foreach ($user_items as $item) {
				$sqlObj = new stdClass();
				$sqlObj->ID = $item->ID;
				$sqlObj->A_STATUS = $sqlChange;
				echo "TODO: " . json_encode($sqlObj) . "...";
				if ('YES' == V::get('confirm', '', $_REQUEST)) {
					echo " TODO-SQL";
					if (false) {
						$ret = $db->UPDATE_OBJ('USERS2_OFFERS_GROUPS', $sqlObj);
						if ($ret > 0) {
							echo " DONE ({$ret})";
						} else {
							echo " ERR";
						}
					}
				}
				echo "\n";
			}
		}
echo'</pre>';
	}

}

function USERS2_OFFERS_GROUPS_group_www_all() {
	$change = V::get('change', '', $_REQUEST);
	$sqlChange = '';
	if ($change == '-') {
		$sqlChange = 'NIE';
	}
	else if ($change == '+') {
		$sqlChange = 'TAK';
	}
	if (!in_array($sqlChange, array('NIE', 'TAK'))) {
		return;
	}

	$filters = array();// sql field -> form field name
	$filters ['P_PROMOTION_NAME']= 'f_P_PROMOTION_NAME';
	$filters ['P_OFFER_TERM_BEGIN']= 'f_P_OFFER_TERM_BEGIN';
	$filters ['P_OFFER_TERM']= 'f_P_OFFER_TERM';
	$filters ['P_SERVICE_COMPANY']= 'f_P_SERVICE_COMPANY';
	$filters ['A_STATUS']= 'f_A_STATUS';
	$filters ['S_ADDRESS_STREET']= 'f_S_ADDRESS_STREET';

	$args = array();
	foreach ($filters as $k_field_name => $v_req_field_name) {
		$args[$k_field_name] = V::get($v_req_field_name, '%', $_REQUEST);
	}

	$filters_empty = true;
	foreach ($args as $k => $v_value) {
		if ($v_value != '%') {
			$filters_empty = false;
		}
	}

	if (!$filters_empty) {
		$items = array();
		$total = 0;
		$totalAll = Offers_Groups_Model::get_total($args);
		if ($totalAll > 0) {
			$items = Offers_Groups_Model::get_items($args);

			$params = Offers_Groups_Konfigurator_Model::get_params_from_items($items);
			// user selected params
			$user_params_empty = true;
			$user_params = array();
			foreach ($params as $k_type => $v_params) {
				if (empty($v_params)) continue;
				$k_field_name = "p_" . $k_type;// "[]"
				$user_params[$k_type] = V::get($k_field_name, null, $_GET, 'array');
				if (!empty($user_params[$k_type])) {
					$user_params_empty = false;
				}
			}
			$user_items = Offers_Groups_Konfigurator_Model::get_items_by_params($items, $user_params);
			$total = count($user_items);
		}

		echo '<p>' . "Do zmiany ({$total}) rekordów:";
			echo '<form action="" method="POST" style="display:inline">';
			echo '<input type="hidden" name="sub_task" value="GROUP_WWW_ALL" />';
			foreach ($_POST as $k => $v) {
				if ($k == 'sub_task') continue;
				if ($k == 'confirm') continue;
				if ($k == 'change') continue;
				echo '<input type="hidden" name="'.$k.'" value="'.$v.'" />';
			}
			echo '<input type="hidden" name="confirm" value="YES" />';
			echo " Aktualizuj wszystkie zmiany";
			echo '<input type="submit" name="change" value="'.$change.'" />';
			echo '</form>';
		echo '</p>';
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">';
		if ($total > 0) {
			$db = DB::getDB();
			foreach ($user_items as $item) {
				$sqlObj = new stdClass();
				$sqlObj->ID = $item->ID;
				$sqlObj->OFERTA_WWW = $sqlChange;
				echo "TODO: " . json_encode($sqlObj) . "...";
				if ('YES' == V::get('confirm', '', $_REQUEST)) {
					echo " TODO-SQL";
					if (false) {
						$ret = $db->UPDATE_OBJ('USERS2_OFFERS_GROUPS', $sqlObj);
						if ($ret > 0) {
							echo " DONE ({$ret})";
						} else {
							echo " ERR";
						}
					}
				}
				echo "\n";
			}
		}
echo'</pre>';
	}
}

function USERS2_OFFERS_GROUPS_konfigurator() {
	global $thiss;

	//echo '<a href="' . "?MENU_INIT=USERS2_OFFERS_GROUPS" . '">' . "USERS2_OFFERS_GROUPS" . '</a>';
	echo '<a href="index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=1614">[1614] USERS2_OFFERS_GROUPS</a>';

	$filters = array();// sql field -> form field name
	$filters ['P_PROMOTION_NAME']= 'f_P_PROMOTION_NAME';
	$filters ['P_OFFER_TERM_BEGIN']= 'f_P_OFFER_TERM_BEGIN';
	$filters ['P_OFFER_TERM']= 'f_P_OFFER_TERM';
	$filters ['P_SERVICE_COMPANY']= 'f_P_SERVICE_COMPANY';
	$filters ['A_STATUS']= 'f_A_STATUS';
	$filters ['S_ADDRESS_STREET']= 'f_S_ADDRESS_STREET';

	$args = array();
	foreach ($filters as $k_field_name => $v_req_field_name) {
		$args[$k_field_name] = V::get($v_req_field_name, '%', $_REQUEST);
	}

	Offers_Groups_View::filters($filters, $args);

	$filters_empty = true;
	foreach ($args as $k => $v_value) {
		if ($v_value != '%') {
			$filters_empty = false;
		}
	}

	if ($filters_empty) {
		echo '<p class="red">' . "Wybierz parametry pakietów" . '</p>';
	} else {
		Offers_Groups_View::show_css();
		echo '<br />';
		echo '<dl class="t-collapse' . ((V::get('sub_task', '', $_REQUEST))? '' : ' t-collapse-hide') . '">';
		$items = array();
		$total = Offers_Groups_Model::get_total($args);
		if ($total > 0) {
			echo '<dt>' . "Znaleziono " . $total . " rekordów.";
				echo '<span class="add-show">' . " (+ ukryj)" . '</span>';
				echo '<span class="add-hidden">' . " (+ pokaż)" . '</span>';
			echo '</dt>';
		} else {
			echo '<dt class="red">' . "Nie znaleziono pakietów pasujących do podanych kryteriów." . '</dt>';
		}
		if ($total > 0) {
			echo '<dd>';
			$items = Offers_Groups_Model::get_items($args);
			Offers_Groups_View::items($items);
			echo '</dd>';
		}
		echo '</dl>';// .t-collapse

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

		// user selected params
		$user_params_empty = true;
		$user_params = array();
		foreach ($params as $k_type => $v_params) {
			if (empty($v_params)) continue;
			$k_field_name = "p_" . $k_type;// "[]"
			$user_params[$k_type] = V::get($k_field_name, null, $_GET, 'array');
			if (!empty($user_params[$k_type])) {
				$user_params_empty = false;
			}
		}
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">$user_params: ';print_r($user_params);echo'</pre>';

		if (!$user_params_empty) {
			// tylko pakiety pasujące do wybranych parametrów
			
		}

		// konfigurator form
		echo '<form action="" method="get">';
		foreach ($filters as $k_field_name => $v_req_field_name) {
			$v_value = V::get($k_field_name, '', $args);
			if (!empty($v_value) && $v_value != '%') {
				echo '<input type="hidden" name="' . $v_req_field_name . '" value="' . $v_value .'" />';
			}
		}
		echo '<input type="hidden" name="' . "MENU_INIT" . '" value="' . "USERS2_OFFERS_GROUPS"  .'" />';
		echo '<input type="hidden" name="' . "task" . '" value="' . "KONFIGURATOR"  .'" />';
		echo '<table cellspacing="0" cellpadding="0" border="1" class="tbl-view tbl-top">';
			echo '<tr>';
			foreach ($params as $k_type => $v_params) {
				if (empty($v_params)) continue;
				echo '<th>' . $k_type . '</th>';
			}
			echo '</tr>';
			echo '<tr>';
			foreach ($params as $k_type => $v_params) {
				if (empty($v_params)) continue;
				echo '<td>';
				if ($k_type != 'TVCP') {
					$val = "BRAK";
					$k_field_name = "p_" . $k_type;
					$chkd = (!empty($user_params[$k_type]) && in_array($val, $user_params[$k_type]))? ' checked="checked"' : '';
					echo '<input type="radio" name="' . $k_field_name . '" value="' . $val . '" ' . $chkd . '/>';
					echo " " . $val . '<br />';
				}
				foreach ($v_params as $key => $val) {
					if ($k_type == 'TVCP') {
						$chkd = (!empty($user_params[$k_type]) && in_array($val, $user_params[$k_type]))? ' checked="checked"' : '';
						$k_field_name = "p_" . $k_type . "[]";
						echo '<input type="checkbox" name="' . $k_field_name . '" value="' . $val . '" ' . $chkd . '/>';
					} else {
						$chkd = (!empty($user_params[$k_type]) && in_array($val, $user_params[$k_type]))? ' checked="checked"' : '';
						$k_field_name = "p_" . $k_type;
						echo '<input type="radio" name="' . $k_field_name . '" value="' . $val . '" ' . $chkd . '/>';
					}
					echo " " . $val . '<br />';
				}
				echo '</td>';
			}
			echo '</tr>';
		echo '</table>';
		echo '<input type="submit" value="' . "Wyślij" . '" />';
		echo '</form>';

		if (!$user_params_empty) {
			// tylko pakiety pasujące do wybranych parametrów
			$user_items = Offers_Groups_Konfigurator_Model::get_items_by_params($items, $user_params);
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">$user_items: ';print_r($user_items);echo'</pre>';
			if (empty($user_items)) {
				echo '<p class="red">' . "Brak ofert pasujących do wybranych kryteriów." . '</p>';
			} else {
				echo '<br />' . "\n";
				echo '<dl class="t-collapse t-collapse-hide">';
				echo '<dt>' . "Oferty pasujące do wybranych kryteriów (" . count($user_items) . "):";
					echo '<span class="add-show">' . " (+ ukryj)" . '</span>';
					echo '<span class="add-hidden">' . " (+ pokaż)" . '</span>';
				echo '</dt>';
				echo '<dd>';
					Offers_Groups_View::items($user_items);
				echo '</dd>';
				echo '</dl>';
			}
		}
		Offers_Groups_View::show_js();
	}

}

function USERS2_OFFERS_GROUPS_konfigurator2() {
	$model = new Offers_Groups_Konfigurator2_Model();

	?>
	<style type="text/css">
.conf2 { width:100%; }
 .conf2 thead th { background:#eee; }
.conf2-cnt { width:100%; table-layout:fixed; }
 .conf2-cnt thead th { background:#FFEFC6; font-size:10px; }
 .conf2-cnt tbody td { text-align:center; }
 .conf2-cnt tbody td,
 .conf2-cnt thead th { border:1px solid #eee; }
 .conf2-cnt tbody tr:hover td{ background:#eee; }

 .conf2-cnt thead > tr, .conf2-cnt tbody{ display:block; }
 .conf2-cnt thead > tr th, .conf2-cnt tbody td{ width:100px; }

#conf2-cnt { height:300px; overflow:auto; }
.conf2-fun { width:30px; }
	</style>
	<table class="conf2" id="conf2">
		<thead class="conf2-head">
			<tr>
				<th>Oferty Filtr</th>
				<td style="text-align:right">[4968] OD <input type="date" name="fltr_o_od" value="<?php echo $model->getCache('fltr_o_od'); ?>"></td>
				<td style="text-align:right">P SERVICE COMPANY <input type="text" name="fltr_COM" value="<?php echo $model->getCache('fltr_COM', 'BN'); ?>"></td>
				<!-- <td style="text-align:right">[4968] DO <input type="date" name="fltr_o_do" value=""></td> -->
				<td><button name="refresh">odśwież</button></td>
			</tr>
			<tr>
				<th>
					Pakiety
					Filtr / Dodaj
				</th>
				<td style="text-align:right">
					[1615] S ALIAS <input type="text" name="fltr_p_1615" value="<?php echo $model->getCache('fltr_p_1615'); ?>"><br>
					[1616] P PROMOTION NAME <input type="text" name="fltr_p_1616" value="<?php echo $model->getCache('fltr_p_1616'); ?>"><br>
					[1617] P DEALTERM MONTHS <input type="text" name="fltr_p_1617" value="<?php echo $model->getCache('fltr_p_1617'); ?>">
				</td>
				<td style="text-align:right">
					[1618] P OFFER TERM BEGIN <input type="text" name="fltr_p_1618" value="<?php echo $model->getCache('fltr_p_1618'); ?>"><br>
					[1619] P OFFER TERM <input type="text" name="fltr_p_1619" value="<?php echo $model->getCache('fltr_p_1619'); ?>"><br>
					[1627] M REWIR <input type="text" name="fltr_p_1627" value="<?php echo $model->getCache('fltr_p_1627'); ?>">
				</td>
				<td></td>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td colspan="4">
					<table class="conf2-cnt">
						<thead>
							<tr id="conf2-cnt-services">
								<td class="conf2-fun">&nbsp;</td>
								<th>12Mb/s</th>
								<th>50Mb/s</th>
								<th>100Mb/s</th>
								<th>150Mb/s</th>
								<th>TV1</th>
								<th>TV2</th>
								<th>TV3</th>
								<th>TV4</th>
								<th>TEL1</th>
								<th>TEL2</th>
								<th>TEL3</th>
								<th>TEL4</th>
							</tr>
						</thead>
						<tbody id="conf2-cnt">
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
							<tr>
								<th class="conf2-fun">&nbsp;</th>
								<td>12Mb/s</td>
								<td>50Mb/s</td>
								<td>100Mb/s</td>
								<td>150Mb/s</td>
								<td>TV1</td>
								<td>TV2</td>
								<td>TV3</td>
								<td>TV4</td>
								<td>TEL1</td>
								<td>TEL2</td>
								<td>TEL3</td>
								<td>TEL4</td>
							</tr>
						</tbody>
					</table>
				</td>
			</tr>
		</tbody>
	</table>


	<table cellspacing="0" cellpadding="0" border="1">
		<thead>
			<tr colspan="99"><a href="#" id="dbg-offers-filter_toggle">Oferty pasujące do filtra <b id="dbg-offers-filter_total"></b></a></tr>
		</thead>
		<tbody id="dbg-offers-filter" style="display:none;">
		</tbody>
	</table>
	<table cellspacing="0" cellpadding="0" border="1">
		<thead>
			<tr colspan="99"><a href="#" id="dbg-groups-filter_toggle">Grupy pasujące do filtra <b id="dbg-groups-filter_total"></b></a></tr>
		</thead>
		<tbody id="dbg-groups-filter" style="display:none;">
		</tbody>
	</table>

	<div id="conf2-Modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
		<form action="" id="conf2-modal-frm" class="form-horizontal">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			<h3 id="myModalLabel">Grupa ofert</h3>
		</div>
		<div class="modal-body">
			<input type="hidden" name="f_ID" value="">
			<div class="control-group">
				<label for="f_COM" class="control-label">P SERVICE COMPANY </label>
				<div class="controls">
					<input type="text" name="f_COM" value="<?php echo $model->getCache('fltr_COM', 'BN'); ?>">
				</div>
			</div>

			<div class="control-group">
				<label for="f_S_ALIAS" class="control-label">[1615] S ALIAS </label>
				<div class="controls">
					<input type="text" name="f_S_ALIAS" value="<?php echo $model->getCache('fltr_p_1615'); ?>">
				</div>
			</div>

			<div class="control-group">
				<label for="f_P_PROMOTION_NAME" class="control-label">[1616] P PROMOTION NAME </label>
				<div class="controls">
					<input type="text" name="f_P_PROMOTION_NAME" value="<?php echo $model->getCache('fltr_p_1616'); ?>">
				</div>
			</div>

			<div class="control-group">
				<label for="f_P_DEALTERM_MONTHS" class="control-label">[1617] P DEALTERM MONTHS </label>
				<div class="controls">
					<input type="text" name="f_P_DEALTERM_MONTHS" value="<?php echo $model->getCache('fltr_p_1617'); ?>">
				</div>
			</div>

			<div class="control-group">
				<label for="f_P_OFFER_TERM_BEGIN" class="control-label">[1618] P OFFER TERM BEGIN </label>
				<div class="controls">
					<input type="text" name="f_P_OFFER_TERM_BEGIN" value="<?php echo $model->getCache('fltr_p_1618'); ?>">
				</div>
			</div>

			<div class="control-group">
				<label for="f_P_OFFER_TERM" class="control-label">[1619] P OFFER TERM </label>
				<div class="controls">
					<input type="text" name="f_P_OFFER_TERM" value="<?php echo $model->getCache('fltr_p_1619'); ?>">
				</div>
			</div>

			<div class="control-group">
				<label for="f_M_REWIR" class="control-label">[1627] M REWIR </label>
				<div class="controls">
					<input type="text" name="f_M_REWIR" value="<?php echo $model->getCache('fltr_p_1627'); ?>">
				</div>
			</div>

			<div class="control-group">
				<label for="f_ID_NET" class="control-label">[1743] ID_NET </label>
				<div class="controls">
					<select name="f_ID_NET"></select>
				</div>
			</div>

			<div class="control-group">
				<label for="f_ID_TV" class="control-label">[1744] ID_TV </label>
				<div class="controls">
					<select name="f_ID_TV"></select>
				</div>
			</div>

			<div class="control-group">
				<label for="f_ID_TVC" class="control-label">[1745] ID_TVC </label>
				<div class="controls">
					<select name="f_ID_TVC"></select>
				</div>
			</div>

			<div class="control-group">
				<label for="f_ID_TEL" class="control-label">[1747] ID_TEL </label>
				<div class="controls">
					<select name="f_ID_TEL"></select>
				</div>
			</div>

		</div>
		<div class="modal-footer">
			<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
			<button class="btn btn-primary" class="btn-save">Zapisz/Dodaj</button>
		</div>
		</form>
	</div>

	<script>

var Konfigurator2 = {

	groups_sorted: [],
	groups: [],
	services: [],
	srv_offer_ids: [],
	offers: [],
	editInd: 0,

	editModal: function(ind) {
		var $modal = jQuery('#conf2-Modal'),
			$frm = jQuery('#conf2-modal-frm'),
			group = null;

		this.editInd = ind;
		console.log('conf2-Modal show', this.groups_sorted[ind]);
		if (this.groups_sorted[ind]['gID']) {
			group = this.groups[this.groups_sorted[ind]['gID']];
		}

		$frm.find("[name='f_ID']").val('');
		if (group) {
			$frm.find("[name='f_ID']").val(group['ID']);
			$frm.find("[name='f_COM']").val(group['P_SERVICE_COMPANY']);
			$frm.find("[name='f_S_ALIAS']").val(group['S_ALIAS']);
			$frm.find("[name='f_P_PROMOTION_NAME']").val(group['P_PROMOTION_NAME']);
			$frm.find("[name='f_M_REWIR']").val(group['M_REWIR']);
			$frm.find("[name='f_P_DEALTERM_MONTHS']").val(group['P_DEALTERM_MONTHS']);
			$frm.find("[name='f_P_OFFER_TERM']").val(group['P_OFFER_TERM']);
			$frm.find("[name='f_P_OFFER_TERM_BEGIN']").val(group['P_OFFER_TERM_BEGIN']);
		} else {
			var Conf2 = jQuery('#conf2');
			$frm.find("[name='f_COM']").val(Conf2.find("[name='fltr_COM']").val());
			$frm.find("[name='f_S_ALIAS']").val(Conf2.find("[name='fltr_p_1615']").val());
			$frm.find("[name='f_P_PROMOTION_NAME']").val(Conf2.find("[name='fltr_p_1616']").val());
			$frm.find("[name='f_M_REWIR']").val(Conf2.find("[name='fltr_p_1627']").val());
			$frm.find("[name='f_P_DEALTERM_MONTHS']").val(Conf2.find("[name='fltr_p_1617']").val());
			$frm.find("[name='f_P_OFFER_TERM']").val(Conf2.find("[name='fltr_p_1619']").val());
			$frm.find("[name='f_P_OFFER_TERM_BEGIN']").val(Conf2.find("[name='fltr_p_1618']").val());
		}

		console.log('conf2-Modal this.srv_offer_ids', this.srv_offer_ids);
		for (var s in this.services) {// s: NET, TV, TVC, TEL
			var fName = 'f_ID_' + s,
				$fld = $frm.find("[name='" + fName + "']");
			$fld.find('option').remove();
			if (s in this.groups_sorted[ind]['_params']) {
				var srvVal = this.groups_sorted[ind]['_params'][s];
				$fld.val('TEST: ' + srvVal);
				for (var i in this.srv_offer_ids[s][srvVal]) {
					var oID = this.srv_offer_ids[s][srvVal][i];
					var o = this.offers[oID];
					var oLabel = '[' + o.ID + '] ' + o.P_PROMO_MONTH_PRICE + '/' + o.P_CONTRACT_PRICE;
					var sel = '';
					if (group) {
						if (group['ID_' + s] > 0 && group['ID_' + s] == oID) {
							sel = ' selected="selected"';
						}
					}
					$fld.append('<option value="' + oID + '"' + sel + '>' + oLabel + '</option>');
				}
			} else {
				$fld.append('<option value="0">0</option>');
			}
		}

		$modal.find('.modal-body');
		//.html(this.groups_sorted[ind]);
		$modal.modal('show');
		return false;
	},

	saveModal: function(evt) {
		var $frm = jQuery('#conf2-modal-frm'),
			params = $frm.serialize();
		console.log('conf2-Modal saveModal', this.groups_sorted[this.editInd], ' frm: ', params);

		$.ajax({
			url: 'index.php?FUNCTION_INIT=USERS2_OFFERS_GROUPS&HEADER_NOT_INIT=YES&task=KONFIGURATOR2&subtask=ajax_save',
			type: 'POST',
			dataType: 'json',
			data: params,
			async: true,
			success: function (data) {
				console.log('save data: ', data);

				var Conf2 = jQuery('#conf2');
				Konfigurator2.refresh(Conf2, evt);
			},
			error: function (err) {
				console.log('err');
			}
		});

		return false;
	},

	find_group_id: function(params, dbg) {
		var groupID = null,
			paramsTotal = 0,
			services = ['NET','TV','TVC','TEL'],
			dbg = dbg || false;
		for (var i in params) {
			paramsTotal++;
		}

var dbg_limit = 2;
		for (var g in this.groups) {
			var paramsCmp = 0;

			for (var srv in this.services) {
				if (!this.groups[g]['_params']) continue;
//if(dbg_limit--){console.log('find_group_id, srv(',srv,') paramsTotal:', paramsTotal, ', params:', params, ', 1:', (srv in this.groups[g]['_params']), ', 2:', (srv in params), ', 3:', params[srv], ' == ', this.groups[g]['_params'][srv]);}
				if (srv in this.groups[g]['_params']) {
					if (srv in params) {
						if (params[srv] == this.groups[g]['_params'][srv]) {
							paramsCmp++;
						}
					}
				}
			}

			if (paramsCmp == paramsTotal) {
				groupID = this.groups[g]['ID'];
			}
		}

		return groupID;
	},

	sort_groups: function() {
		this.groups_sorted = [];// all combinations

		//for (var g in this.groups) this.groups_sorted[g] = this.groups[g];

		var ind = 90000;

//console.log('services: ', this.services);
		for (var s in this.services) {
			for (var p in this.services[s]) {
				var group = {_params:{}, gID:null};
				group['_params'][s] = this.services[s][p];
console.log('group add: ', group);
				this.groups_sorted[ind++] = group;
			}
		}

		// pakiety 2w1
		for (var s in this.services) {
			for (var p in this.services[s]) {
				for (var s2 in this.services) {
					if (s2 == s) continue;
					if (s2 == 'TVC' && s == 'TV') continue;
					if (s2 == 'TV'  && s == 'TVC') continue;
					for (var p2 in this.services[s2]) {
						var group = {_params:{}, gID:null};
						group['_params'][s] = this.services[s][p];
						group['_params'][s2] = this.services[s2][p2];
						group['gID'] = this.find_group_id(group['_params']);
						this.groups_sorted[ind++] = group;
					}
				}
			}
		}

		// pakiety 3w1
		for (var s in this.services) {
			for (var p in this.services[s]) {
				var lastS = s;
				for (var s2 in this.services) {
					if (lastS == s2) {
						lastS = true;
						continue;
					}
					if (lastS !== true) continue;

					if (s2 == s) continue;
					if (s2 == 'TVC' && s == 'TV') continue;
					if (s2 == 'TV'  && s == 'TVC') continue;
					for (var p2 in this.services[s2]) {
						var lastS2 = s2;
						for (var s3 in this.services) {
							if (lastS2 == s3) {
								lastS2 = true;
								continue;
							}
							if (lastS2 !== true) continue;

							if (s3 == s) continue;
							if (s3 == s2) continue;
							if (s3 == 'TV'  && (s == 'TVC' || s2 == 'TVC')) continue;
							if (s3 == 'TVC' && (s == 'TV' || s2 == 'TV')) continue;
							for (var p3 in this.services[s3]) {
								var group = {_params:{}, gID:null};
								group['_params'][s] = this.services[s][p];
								group['_params'][s2] = this.services[s2][p2];
								group['_params'][s3] = this.services[s3][p3];
								group['gID'] = this.find_group_id(group['_params']);
console.log('group 3w1 add: (',s,',',s2,',',s3,') ', group);
								this.groups_sorted[ind++] = group;
							}
						}
					}
				}
			}
		}

		return this.groups_sorted;
	},

	refresh: function(Conf2, evt){
		console.log('TODO: update filters dbg-offers-filter, dbg-groups-filter ... evt:', evt);
		jQuery('#dbg-offers-filter')
		var params = {};
		params['fltr_o_od'] = Conf2.find("input[name='fltr_o_od']").val();
		params['fltr_COM'] = Conf2.find("input[name='fltr_COM']").val();
		//params['fltr_o_do'] = Conf2.find("input[name='fltr_o_do']").val();
		params['fltr_p_1615'] = Conf2.find("input[name='fltr_p_1615']").val();
		params['fltr_p_1616'] = Conf2.find("input[name='fltr_p_1616']").val();
		params['fltr_p_1617'] = Conf2.find("input[name='fltr_p_1617']").val();
		params['fltr_p_1618'] = Conf2.find("input[name='fltr_p_1618']").val();
		params['fltr_p_1619'] = Conf2.find("input[name='fltr_p_1619']").val();
		params['fltr_p_1627'] = Conf2.find("input[name='fltr_p_1627']").val();
		console.log('TODO: params: ', params);

		// 4968 KOMORKA A_RECORD_CREATE_DATE
		$.ajax({
			url: 'index.php?FUNCTION_INIT=USERS2_OFFERS_GROUPS&HEADER_NOT_INIT=YES&task=KONFIGURATOR2&subtask=ajax_fltrs',
			type: 'GET',
			dataType: 'json',
			data: params,
			async: true,
			success: function (data) {
				//console.log('data: ', data);
				var out_offers_total = 0, out_groups_total = 0
					, out_offers = '', out_groups = ''
					, out_cnt = '', out_services = '';

				if (data.offers) {
					for (var i in data.offers) {
						out_offers_total += 1;
						out_offers += '<tr>' +
							'<td>' + data.offers[i]['ID'] + '</td>' +
							'<td>' + data.offers[i]['P_NAME'] + '</td>' +
							'<td>' + data.offers[i]['P_SERVICE_NAME'] + '</td>' +
							'<td>' + data.offers[i]['P_S_PARAM1'] + '</td>' +
							'<td>' + data.offers[i]['P_INSTALL_QUOTE'] + '</td>' +
							'<td>' + data.offers[i]['P_CONTRACT_PRICE'] + '</td>' +
							'<td>' + data.offers[i]['P_PROMO_MONTH_PRICE'] + '</td>' +
							'<td>' + data.offers[i]['P_NORMAL_PRICE'] + '</td>' +
						'</tr>';
					}
				}

				for (var i in data.groups) {
					out_groups_total += 1;
					out_groups += '<tr>' +
						'<td>' + data.groups[i]['ID'] + '</td>' +
						'<td>' + data.groups[i]['ID_TEL'] + '</td>' +
						'<td>' + data.groups[i]['ID_TV'] + '</td>' +
						'<td>' + data.groups[i]['ID_TVC'] + '</td>' +
						'<td>' + data.groups[i]['ID_TEL'] + '</td>' +
						'<td>' + data.groups[i]['S_ALIAS'] + '</td>' +
						'<td>' + data.groups[i]['P_PROMOTION_NAME'] + '</td>' +
						'<td>' + data.groups[i]['P_DEALTERM_MONTHS'] + '</td>' +
						'<td>' + data.groups[i]['P_OFFER_TERM_BEGIN'] + '</td>' +
						'<td>' + data.groups[i]['P_OFFER_TERM'] + '</td>' +
						'<td>' + data.groups[i]['M_REWIR'] + '</td>' +
					'</tr>';
				}

				if (data.services) {
					out_services += '<td class="conf2-fun">&nbsp;</td>';
					for (var j in data.services) {
						for (var k in data.services[j]) {
							out_services += '<th>' + data.services[j][k] + '</th>';
						}
					}
				}

				Konfigurator2.groups = data.groups;
				Konfigurator2.services = data.services;
				Konfigurator2.srv_offer_ids = data.srv_offer_ids;
				Konfigurator2.offers = data.offers;
				groups_sorted = Konfigurator2.sort_groups();
console.log('groups_sorted:', groups_sorted);
console.log('groups_sorted Konfigurator2:', Konfigurator2);

				for (var i in groups_sorted) {
					var out_fun = (groups_sorted[i].gID > 0)? '#' : '+';
					out_fun = '<a href="#" onclick="return Konfigurator2.editModal(' + i + ');">' + out_fun + '</a>';
					out_cnt += '<tr id="edit-group-' + i + '">';
					out_cnt += '<th class="conf2-fun">' + out_fun + '</th>';
					for (var j in data.services) {
						for (var k in data.services[j]) {
							out_cnt += '<td>';
							if (j in groups_sorted[i]._params && k == groups_sorted[i]._params[j]) {
								out_cnt += 'X';
							} else {
								out_cnt += '---';
							}
							out_cnt += '</td>';
						}
					}
					out_cnt += '</tr>';
				}

				jQuery('#dbg-offers-filter_total').text(out_offers_total);
				jQuery('#dbg-offers-filter').html(out_offers);
				jQuery('#dbg-groups-filter_total').text(out_groups_total);
				jQuery('#dbg-groups-filter').html(out_groups);
				jQuery('#conf2-cnt-services').html(out_services);
				jQuery('#conf2-cnt').html(out_cnt);
			},
			error: function (err) {
				console.log('err');
			}
		});
	}

};

jQuery(document).ready(function(){
	var Conf2 = jQuery('#conf2');
	Conf2.find('.conf2-head input').on('change', function(evt){
		Konfigurator2.refresh(Conf2, evt);
	});
	Conf2.find(".conf2-head button[name='refresh']").on('click', function(evt){
		Konfigurator2.refresh(Conf2, evt);
	});

	jQuery('#dbg-offers-filter_toggle').on('click', function(){
		jQuery('#dbg-offers-filter').toggle();
		return false;
	});
	jQuery('#dbg-groups-filter_toggle').on('click', function(){
		jQuery('#dbg-groups-filter').toggle();
		return false;
	});

	jQuery('#conf2-modal-frm').submit(function(evt){
		evt.preventDefault();
		Konfigurator2.saveModal(evt);
		return false;
	});

});
	</script>
	<?php
}

function USERS2_OFFERS_GROUPS_konfigurator2_ajax_save() {
	$db = DB::getDB();

	$obj = new stdClass();
	$obj->ID = V::get('f_ID', 0, $_POST, 'int');
	$obj->P_SERVICE_COMPANY = V::get('f_COM', '', $_POST);
	$obj->S_ALIAS = V::get('f_S_ALIAS', '', $_POST);
	$obj->P_PROMOTION_NAME = V::get('f_P_PROMOTION_NAME', '', $_POST);
	$obj->P_DEALTERM_MONTHS = V::get('f_P_DEALTERM_MONTHS', '', $_POST);
	$obj->P_OFFER_TERM_BEGIN = V::get('f_P_OFFER_TERM_BEGIN', '', $_POST);
	$obj->P_OFFER_TERM = V::get('f_P_OFFER_TERM', '', $_POST);
	$obj->M_REWIR = V::get('f_M_REWIR', '', $_POST);
	$obj->ID_NET = V::get('f_ID_NET', 0, $_POST, 'int');
	$obj->ID_TV = V::get('f_ID_TV', 0, $_POST, 'int');
	$obj->ID_TVC = V::get('f_ID_TVC', 0, $_POST, 'int');
	$obj->ID_TEL = V::get('f_ID_TEL', 0, $_POST, 'int');

	$data = new stdClass();
	$data->ret = null;

	if ($obj->ID > 0) {
		$data->ret = $db->UPDATE_OBJ('USERS2_OFFERS_GROUPS', $obj);
	} else {
		$data->ret = $db->ADD_NEW_OBJ('USERS2_OFFERS_GROUPS', $obj);
	}

	echo json_encode($data);

	exit;
}

function USERS2_OFFERS_GROUPS_konfigurator2_ajax_fltrs() {
	$model = new Offers_Groups_Konfigurator2_Model();

	$data = new stdClass();
	$data->offers = array();
	$data->groups = array();
	$data->services = array();
	$data->services['NET'] = array();
	$data->services['TV'] = array();
	$data->services['TVC'] = array();
	$data->services['TEL'] = array();
	$data->srv_offer_ids = array();

	$params = array();
	$params['fltr_o_od'] = V::get('fltr_o_od', '', $_GET);
	$params['fltr_COM'] = V::get('fltr_COM', '', $_GET);
	$params['fltr_p_1615'] = V::get('fltr_p_1615', '', $_GET);
	$params['fltr_p_1616'] = V::get('fltr_p_1616', '', $_GET);
	$params['fltr_p_1617'] = V::get('fltr_p_1617', '', $_GET);
	$params['fltr_p_1618'] = V::get('fltr_p_1618', '', $_GET);
	$params['fltr_p_1619'] = V::get('fltr_p_1619', '', $_GET);
	$params['fltr_p_1627'] = V::get('fltr_p_1627', '', $_GET);

	$model->setCache('fltr_o_od', $params['fltr_o_od']);
	$model->setCache('fltr_COM', $params['fltr_COM']);
	$model->setCache('fltr_p_1615', $params['fltr_p_1615']);
	$model->setCache('fltr_p_1616', $params['fltr_p_1616']);
	$model->setCache('fltr_p_1617', $params['fltr_p_1617']);
	$model->setCache('fltr_p_1618', $params['fltr_p_1618']);
	$model->setCache('fltr_p_1619', $params['fltr_p_1619']);
	$model->setCache('fltr_p_1627', $params['fltr_p_1627']);

	if (empty($params['fltr_p_1615'])) {
		$params['fltr_p_1615'] = '%';
	}
	if (empty($params['fltr_p_1616'])) {
		$params['fltr_p_1616'] = '%';
	}
	if (empty($params['fltr_p_1617'])) {
		$params['fltr_p_1617'] = '%';
	}
	if (empty($params['fltr_p_1618'])) {
		$params['fltr_p_1618'] = '%';
	}
	if (empty($params['fltr_p_1619'])) {
		$params['fltr_p_1619'] = '%';
	}
	if (empty($params['fltr_p_1627'])) {
		$params['fltr_p_1627'] = '%';
	}

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

	if (empty($params['fltr_o_od'])) {
		$data->err_msg = "Ustaw pole OD (fltr_o_od)";
		echo json_encode($data);
		exit;
	}

	$db = DB::getDB();

	$sql = "select o.`ID`
			, o.`P_NAME`
			, o.`P_SERVICE_NAME`
			, o.`P_S_PARAM1`
			, o.`P_INSTALL_QUOTE`
			, o.`P_CONTRACT_PRICE`
			, o.`P_PROMO_MONTH_PRICE`
			, o.`P_NORMAL_PRICE`
			, o.`P_SERVICE`
			, o.`P_SERVICE_COMPANY`
		from `USERS2_OFFERS` as o
		where o.`A_RECORD_CREATE_DATE`>'{$params['fltr_o_od']}'
			and o.`A_STATUS` in('WAITING', 'NORMAL')
			and o.`P_SERVICE` in('NET','TV','TVC','TEL')
			and o.`P_SERVICE_COMPANY`='{$params['fltr_COM']}'
		limit 1000
	";
	if(V::get('DBG', '', $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$sql-offers (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
	$res = $db->query($sql);
	while ($r = $db->fetch($res)) {
		$data->offers[$r->ID] = $r;
		if ($r->P_SERVICE == 'NET') {
			$data->services[$r->P_SERVICE][$r->P_S_PARAM1] = $r->P_S_PARAM1;
			$data->srv_offer_ids[$r->P_SERVICE][$r->P_S_PARAM1][] = $r->ID;
		}
		else if ($r->P_SERVICE == 'TV') {
			$data->services[$r->P_SERVICE][$r->P_SERVICE_NAME] = $r->P_SERVICE_NAME;
			$data->srv_offer_ids[$r->P_SERVICE][$r->P_SERVICE_NAME][] = $r->ID;
		}
		else if ($r->P_SERVICE == 'TVC') {
			$data->services[$r->P_SERVICE][$r->P_SERVICE_NAME] = $r->P_SERVICE_NAME;
			$data->srv_offer_ids[$r->P_SERVICE][$r->P_SERVICE_NAME][] = $r->ID;
		}
		else if ($r->P_SERVICE == 'TEL') {
			$data->services[$r->P_SERVICE][$r->P_SERVICE_NAME] = $r->P_SERVICE_NAME;
			$data->srv_offer_ids[$r->P_SERVICE][$r->P_SERVICE_NAME][] = $r->ID;
		}
	}

	foreach ($data->services as $k => $v) {
		asort($data->services[$k]);
	}

	$sql = "select g.`ID`
			, g.`S_ALIAS`
			, g.`P_PROMOTION_NAME`
			, g.`P_DEALTERM_MONTHS`
			, g.`P_OFFER_TERM_BEGIN`
			, g.`P_OFFER_TERM`
			, g.`M_REWIR`
			, g.`ID_NET`
			, g.`ID_TV`
			, g.`ID_TVC`
			, g.`ID_TEL`
		from `USERS2_OFFERS_GROUPS` as g
		where g.`S_ALIAS` like '{$params['fltr_p_1615']}'
			and g.`P_PROMOTION_NAME` like '{$params['fltr_p_1616']}'
			and g.`P_DEALTERM_MONTHS` like '{$params['fltr_p_1617']}'
			and g.`P_OFFER_TERM_BEGIN` like '{$params['fltr_p_1618']}'
			and g.`P_OFFER_TERM` like '{$params['fltr_p_1619']}'
			and g.`M_REWIR` like '{$params['fltr_p_1627']}'
			and g.`A_STATUS` in('WAITING', 'NORMAL','MONITOR')
			and g.`P_SERVICE_COMPANY`='{$params['fltr_COM']}'
		limit 1000
	";
	if(V::get('DBG', '', $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$sql-offers (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
	$res = $db->query($sql);
	while ($r = $db->fetch($res)) {
		$r->_params = array();
		if ($r->ID_NET > 0) {
			if (empty($data->offers[$r->ID_NET])) {
				continue;
			}
			$r->_params['NET'] = $data->offers[$r->ID_NET]->P_S_PARAM1;
		}
		if ($r->ID_TV > 0) {
			if (empty($data->offers[$r->ID_TV])) {
				continue;
			}
			$r->_params['TV'] = $data->offers[$r->ID_TV]->P_SERVICE_NAME;
		}
		if ($r->ID_TVC > 0) {
			if (empty($data->offers[$r->ID_TVC])) {
				continue;
			}
			$r->_params['TVC'] = $data->offers[$r->ID_TVC]->P_SERVICE_NAME;
		}
		if ($r->ID_TEL > 0) {
			if (empty($data->offers[$r->ID_TEL])) {
				continue;
			}
			$r->_params['TEL'] = $data->offers[$r->ID_TEL]->P_SERVICE_NAME;
		}

		$data->groups[$r->ID] = $r;
	}

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

	echo json_encode($data);
	exit;
}


class Offers_Groups_Konfigurator2_Model {

	public function __construct() {
		if (!isset($_SESSION['Offers_Groups_Konfigurator2_Model'])) {
			$_SESSION['Offers_Groups_Konfigurator2_Model'] = array();
		}
	}

	public function getCache($key, $default = '') {
		return V::get($key, $default, $_SESSION['Offers_Groups_Konfigurator2_Model']);
	}

	public function setCache($key, $val) {
		$_SESSION['Offers_Groups_Konfigurator2_Model'][$key] = $val;
	}

}


class Offers_Groups_Konfigurator_Model {

	function get_base_params() {
		$ret = array();
		$ret['NET'] = array();
		$ret['TV'] = array();
		$ret['TVC'] = array();
		$ret['TVCP'] = array();// multi
		$ret['TEL'] = array();
		return $ret;
	}

	function get_params_from_items(&$items) {
		$ret = self::get_base_params();
		if (empty($items)) {
			return $ret;
		}
		foreach ($items as $g_id => $v_group) {
			foreach ($v_group->oferty as $o_id => $v_offer) {
				switch ($v_offer->P_SERVICE) {
					case 'NET':
						$ret['NET'] [$v_offer->P_S_PARAM1] = true;
						break;
					case 'TV':
						$ret['TV'] [$v_offer->P_SERVICE_NAME] = true;
						break;
					case 'TVC':
						$ret['TVC'] [$v_offer->P_SERVICE_NAME] = true;
						break;
					case 'TVCP':
						$ret['TVCP'] [$v_offer->P_SERVICE_NAME] = true;
						break;
					case 'TEL':
						$ret['TEL'] [$v_offer->P_SERVICE_NAME] = true;
						break;
					default:
						
				}
			}
		}

		// reverse keys - values
		foreach ($ret as $k_service => $v_arr) {
			$ret [$k_service] = array_keys($v_arr);
		}

		uasort($ret['NET'], array('self', 'sort_net_by_param1_callback'));

		return $ret;
	}

	public static function sort_net_by_param1_callback( $a1, $a2 ) {
		// clean vars
		$args = array($a1, $a2);
		foreach ($args as $k => $v_arg) {
			$arg = $v_arg;
			if (strpos($arg, 'Mb/s') !== false) $arg = str_replace('Mb/s', '', $arg);
			else if (strpos($arg, 'kb/s') !== false) $arg = str_replace('kb/s', '', $arg);
			if (is_numeric($arg)) {
				$args[$k] = $arg;
			}
		}
		if ($args[0] < $args[1]) {
			return -1;
		} else if ($args[0] > $args[1]) {
			return 1;
		} else {
			return 0;
		}
	}

	function get_items_by_params(&$items, &$user_params) {
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">$user_params: ';print_r($user_params);echo'</pre>';
		$user_params_checked_ok = 0;
		foreach ($user_params as $k_type => $v_params) {
			$user_params_checked_ok += count($v_params);
		}

		$ret = array();
		foreach ($items as $item) {
			$user_params_checked = 0;
			foreach ($user_params as $k_type => $v_params) {
				if (empty($v_params)) continue;

				// if $k_type != 'TVCP' - jesli BRAK to powinno nie byc danej oferty
				if ($k_type != 'TVCP') {
					$v_param = reset($v_params);
					if ($v_param == 'BRAK') {
						$field_id_offer = "ID_" . $k_type;
						if ($item->$field_id_offer <= 0) {
							$user_params_checked++;
						}
						continue;
					}
				}

				$v_offer = null;
				$field_id_offer = "ID_" . $k_type;
				if ($k_type == 'TVCP') {// ID_TVCP_1, ID_TVCP_2, ID_TVCP_3, ID_TVCP_4
					for ($i = 1; $i <= 4; $i++) {
						$field_id_offer_tvcp = $field_id_offer . "_" . $i;
						if ($item->$field_id_offer_tvcp > 0) {
							$v_offer = V::get($item->$field_id_offer_tvcp, '', $item->oferty);
							if ($v_offer && in_array($v_offer->P_SERVICE_NAME, $v_params)) {
								$user_params_checked++;
							}
						}
					}
				}
				if ($item->$field_id_offer > 0) {
					$v_offer = V::get($item->$field_id_offer, '', $item->oferty);
				}
				if (!$v_offer) continue;

				switch ($k_type) {
					case 'NET':
						if (in_array($v_offer->P_S_PARAM1, $v_params)) {
							$user_params_checked++;
						}
						break;
					case 'TV':
					case 'TVC':
					//case 'TVCP':
					case 'TEL':
						if (in_array($v_offer->P_SERVICE_NAME, $v_params)) {
							$user_params_checked++;
						}
						break;
					default:
						
				}
			}
			if ($user_params_checked == $user_params_checked_ok) {
				$ret [$item->ID] = $item;
			}
		}
		return $ret;
	}

}


class Offers_Groups_View {

	function show_css() {
?>
<style type="text/css">
.t-collapse {margin:0 0 10px 0; padding:0;}
 .t-collapse dt {display:block; margin:0; padding:3px 10px; background:#812EA5; color:white; cursor:pointer;}
 .t-collapse dd {display:block; margin:0; padding:4px 10px; background:#E5E5E5; color:black; overflow:hidden; border:1px solid #812EA5;}
	.t-collapse dt em {}
	.t-collapse dd .box {display:block; float:left; width:98px; height:120px; text-align:center; font-size:11px; color:#999;}
	.t-collapse dd .box img {clear:both; margin:0 0 3px 0;}
	.t-collapse dd .tbl-view {background:#fff;}
  .t-collapse dt .add-show,
  .t-collapse dt .add-hidden {font-size:normal; font-family:monospace; font-weight:bold;}
.t-collapse-hide dd {display:none;}
 .t-collapse dt .add-show {display:inline;}
 .t-collapse dt .add-hidden {display:none;}
 .t-collapse-hide dt .add-show {display:none;}
 .t-collapse-hide dt .add-hidden {display:inline;}
.t-collapse .tbl-view th,
.t-collapse .tbl-view td {font-size:small;}

.tbl-top td{vertical-align:top;}
</style>
<?php
	}

	function show_js() {
?>
<script type="text/javascript">
jQuery(document).ready(function(){
	jQuery(".t-collapse dt").click(function(){
		jQuery(this).parent().toggleClass('t-collapse-hide');
		return false
	});
});
</script>
<?php
	}

	function filters($filters, $args) {
		echo '<form action="" method="get">';
			echo '<table class="tbl-view" cellpadding="0" cellspacing="0" border="1">';
			echo '<caption>' . "Konfigurator - filtr pakietów" . '</caption>';
			echo '<tr>';
				foreach ($filters as $k_field_name => $v_req_field_name) {
					echo '<th>';
						echo $k_field_name;
					echo '</th>';
				}
				echo '<th>' . "&nbsp;" . '</th>';
			echo '</tr>';
			echo '<tr>';
				foreach ($filters as $k_field_name => $v_req_field_name) {
					echo '<td>';
						if ($k_field_name == 'A_STATUS') {
							$filter_values = array();
							$filter_values['%'] = "%";
							$filter_values['WAITING'] = "WAITING";
							$filter_values['NORMAL'] = "NORMAL";
							$filter_values['MONITOR'] = "MONITOR";
							$filter_values['OFF_HARD'] = "OFF_HARD";
							$filter_values['WAITING_NORMAL'] = "NORMAL + WAITING";
							echo '<select name="' . $v_req_field_name .'">';
							$filter_value_selected = V::get($k_field_name, '', $args);
							foreach ($filter_values as $k_filter_value => $v_filter_label) {
								$sel = ($k_filter_value == $filter_value_selected)? 'selected="selected"' : '';
								echo '<option value="' . $k_filter_value . '"' . $sel . '>' . $v_filter_label . '</option>';
							}
							echo '</select>';
						} else {
							echo '<input name="' . $v_req_field_name . '" type="text" value="' . V::get($k_field_name, '', $args) . '" />';
						}
					echo '</td>';
				}
				echo '<td>';
					echo '<input type="hidden" name="' . "MENU_INIT" . '" value="' . "USERS2_OFFERS_GROUPS"  .'" />';
					echo '<input type="hidden" name="' . "task" . '" value="' . "KONFIGURATOR"  .'" />';
					echo '<input type="submit" value="' . "Wyślij" . '" />';
				echo '</td>';
			echo '</tr>';
			echo '</table>';
		echo '</form>';
	}

	function items($items) {
		Lib::loadClass('PokazOfertyView');
		$view = new PokazOfertyView();
		echo $view->print_css();
		echo $view->print_jquery_ui();

		$cols = array();
		$cols []= 'ID';
		$cols []= 'S_ALIAS';
		$cols []= 'P_PROMOTION_NAME';
		$cols []= 'P_DEALTERM_MONTHS';
		$cols []= 'P_OFFER_TERM_BEGIN';
		$cols []= 'P_OFFER_TERM';
		$cols []= 'P_SERVICE_COMPANY';
		$cols []= 'ID_NET';
		$cols []= 'ID_TEL';
		$cols []= 'ID_TV';
		$cols []= 'ID_TVC';
		//$cols []= 'ID_TVCP'; - niużywane pole
		$cols []= 'ID_TVCP_1';
		$cols []= 'ID_TVCP_2';
		$cols []= 'ID_TVCP_3';
		$cols []= 'ID_TVCP_4';
		//$cols []= 'S_OTHER_INFO';
		$cols []= 'M_REWIR';
		$cols []= 'A_STATUS';
		$cols []= 'OFERTA_WWW';

		$view->set('show_zysk', true);
		$www_action = '<form action="" method="POST" style="display:inline">';
		$www_action .= '<input type="hidden" name="sub_task" value="GROUP_WWW_ALL" />';
		$www_action .= '<input type="submit" name="change" value="+" title="Activate" />';
		$www_action .= '<input type="submit" name="change" value="-" title="Deactivate" />';
		$www_action .= '</form>';
		$view->set('show_www', $www_action);
		$status_action = '<form action="" method="POST" style="display:inline">';
		$status_action .= '<input type="hidden" name="sub_task" value="GROUP_STATUS_ALL" />';
		$status_action .= '<input type="submit" name="change" value="+" title="Activate" />';
		$status_action .= '<input type="submit" name="change" value="-" title="Deactivate" />';
		$status_action .= '</form>';
		$view->set('show_status', $status_action);
		$view->set('show_rewir', true);
		$view->print_groups_info_header();
		foreach ($items as $item) {
			$www_action = '<form action="" method="POST" style="display:inline">';
			$www_action .= '<input type="hidden" name="sub_task" value="GROUP_WWW" />';
			$www_action .= '<input type="hidden" name="group_id" value="' . $item->ID . '" />';
			$www_action .= '<input type="submit" name="change" value="+" title="Activate" />';
			$www_action .= '<input type="submit" name="change" value="-" title="Deactivate" />';
			$www_action .= '</form>';
			$view->set('show_www', $www_action);
			$status_action = '<form action="" method="POST" style="display:inline">';
			$status_action .= '<input type="hidden" name="sub_task" value="GROUP_STATUS" />';
			$status_action .= '<input type="hidden" name="group_id" value="' . $item->ID . '" />';
			$status_action .= '<input type="submit" name="change" value="+" title="Activate" />';
			$status_action .= '<input type="submit" name="change" value="-" title="Deactivate" />';
			$status_action .= '</form>';
			$view->set('show_status', $status_action);
			$group = new X_Column_users2_offers_groups();
			$group->set_from_raw_data($item);
			$group->set_offers($item->oferty);
			$view->print_group_info($group, array('hide_header'=>true));
		}
		$view->print_groups_info_footer();
		echo $view->print_js_show_hide_groups();

		if (false) {// TODO: RMME
			echo '<table class="tbl-view" cellspacing="0" cellpadding="0" border="1">';
			echo '<thead>';
				echo '<tr>';
					foreach ($cols as $field_name) {
						echo '<th>' . str_replace('_', ' ', $field_name) . '</th>';
					}
					echo '<th title="' . "Suma abonamentów w promocyjnych miesiącach" . '">' . "cena" . '</th>';
					echo '<th title="' . "Suma opłat instalacyjnych" . '">' . "cena instalacji" . '</th>';
					//echo '<th title="' . "Średnia" . '">' . "średnia" . '</th>';
				echo '</tr>';
			echo '</thead>';
			echo '<tbody>';
			foreach ($items as $item) {
				$suma_P_PROMO_MONTH_PRICE = 0;
				$suma_P_PROMO_INSTALL_PRICE = 0;
				$suma_P_OFFER_SREDNIA = 0;
				//$suma_P_OFFER_COSTS = 0;
				foreach ($item->oferty as $v_oferta) {
					$suma_P_PROMO_MONTH_PRICE += $v_oferta->P_PROMO_MONTH_PRICE;
					$suma_P_PROMO_INSTALL_PRICE += $v_oferta->P_PROMO_INSTALL_PRICE;
					//  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`,
					$srednia = 0;
					$srednia += ($item->P_DEALTERM_MONTHS - $v_oferta->P_DEAL_PROMO_MONTHS) * $v_oferta->P_CONTRACT_PRICE;
					$srednia += $v_oferta->P_DEAL_PROMO_MONTHS * $v_oferta->P_PROMO_MONTH_PRICE;
					$srednia += $v_oferta->P_INSTALL_QUOTE;
					$srednia = round($srednia / $item->P_DEALTERM_MONTHS, 2);
					$suma_P_OFFER_SREDNIA += $srednia;
				}

				echo '<tr>';
					foreach ($cols as $field_name) {
						echo '<td>' . $item->$field_name . '</td>';
					}
					echo '<td>' . '<nobr style="font-weight:bold;">' . number_format($suma_P_PROMO_MONTH_PRICE, 2, ',', ' ') . '</nobr>' . '</td>';
					echo '<td>' . '<nobr>' . number_format($suma_P_PROMO_INSTALL_PRICE, 2, ',', ' ') . '</nobr>' . '</td>';
					//echo '<td>' . '<nobr>' . number_format($suma_P_OFFER_SREDNIA, 2, ',', ' ') . '</nobr>' . '</td>';
				echo '</tr>';
			}
			echo '</tbody>';
			echo '</table>';
		}
	}
}

class Offers_Groups_Model {

	function cols_groups() {
		$cols = array();
		$cols []= 'ID';
		$cols []= 'S_ALIAS';
		$cols []= 'P_PROMOTION_NAME';
		$cols []= 'P_DEALTERM_MONTHS';
		$cols []= 'P_OFFER_TERM_BEGIN';
		$cols []= 'P_OFFER_TERM';
		$cols []= 'P_SERVICE_COMPANY';
		$cols []= 'ID_NET';
		$cols []= 'ID_TEL';
		$cols []= 'ID_TV';
		$cols []= 'ID_TVC';
		$cols []= 'ID_TVCP_1';
		$cols []= 'ID_TVCP_2';
		$cols []= 'ID_TVCP_3';
		$cols []= 'ID_TVCP_4';
		$cols []= 'S_OTHER_INFO';
		$cols []= 'A_STATUS';
		$cols []= 'M_REWIR';
		$cols []= 'OFERTA_WWW';
		return $cols;
	}

	function cols_offers() {
		$cols = array();
		$cols []= 'ID';
		$cols []= 'A_STATUS';
		$cols []= 'S_ALIAS';
		$cols []= 'P_SERVICE';
		$cols []= 'P_SERVICE_PARENT';
		$cols []= 'P_SERVICE_NAME';
		$cols []= 'P_PROMOTION_NAME';
		$cols []= 'P_S_PARAM1';
		$cols []= 'P_S_PARAM2';
		$cols []= 'P_DEALTERM_MONTHS';
		$cols []= 'P_DEAL_PROMO_MONTHS';
		$cols []= 'P_INSTALL_QUOTE';
		$cols []= 'P_INSTALL_QUOTE_NORMAL';
		$cols []= 'P_CONTRACT_PRICE';
		$cols []= 'P_PROMO_MONTH_PRICE';
		$cols []= 'P_NORMAL_PRICE';
		$cols []= 'P_OFFER_TERM_BEGIN';
		$cols []= 'P_OFFER_TERM';
		$cols []= 'P_PROMO_MONTH_PRICE_NETTO';
		$cols []= 'P_CONTRACT_PRICE_NETTO';
		$cols []= 'S_OTHER_INFO';
		return $cols;
	}

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

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

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

	function _parse_where($args) {
		$sql_where_and_arr = array();
		foreach ($args as $k_field => $v_value) {
			if ($k_field == 'A_STATUS') {
				if ($v_value == '%') {
				}
				else if ($v_value == 'WAITING_NORMAL') {
					$sql_where_and_arr []= "g.`" . $k_field . "` in('WAITING', 'NORMAL')";
				} else {
					$sql_where_and_arr []= "g.`" . $k_field . "`='" . DB::_($v_value) . "'";
				}
			}
			else if ($k_field == 'S_ADDRESS_STREET') {
				if (!empty($v_value) && $v_value != '%') {
					$buildings = self::get_buildings_by_mieszk($v_value);
					$building = reset($buildings);
					if ($building) {
						$sql_where_and_arr []= "'{$building->M_REWIR}' like g.`M_REWIR`";
					} else {
						echo '<p style="color:red">' . "Nie odnaleziono mieszkania {$v_value}" . '</p>';
					}
				}
			}
			else {
				$sql_where_and_arr []= "g.`" . $k_field . "` like '" . DB::_($v_value) . "'";
			}
		}
		$sql_where = (!empty($sql_where_and_arr))? implode(" and ", $sql_where_and_arr) : "";
		if (1 == V::get('DBG', '', $_GET)) {
			echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql_where (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql_where);echo'</pre>';
		}
		return $sql_where;
	}

	function get_total($args) {
		$ret = 0;
		$sql_where = self::_parse_where($args);
		$sql = "select count(1) as cnt
			from `USERS2_OFFERS_GROUPS` as g
			where $sql_where
		";
		$res = DB::query($sql);
		if ($r = DB::fetch($res)) {
			$ret = $r->cnt;
		}
		return $ret;
	}

	function get_items($args) {
		$db = DB::getDB();
		$external_offer_fields = array();
		$external_offer_fields []= 'ID_NET';
		$external_offer_fields []= 'ID_TEL';
		$external_offer_fields []= 'ID_TV';
		$external_offer_fields []= 'ID_TVC';
		$external_offer_fields []= 'ID_TVCP_1';
		$external_offer_fields []= 'ID_TVCP_2';
		$external_offer_fields []= 'ID_TVCP_3';
		$external_offer_fields []= 'ID_TVCP_4';
		$oferty_ids = array();

		$ret = array();
		$sql_where = self::_parse_where($args);
		$sql_select = array();
		$cols = self::cols_groups();
		foreach ($cols as $v_col) {
			$sql_select []= "g.`" . $v_col . "`";
		}
		$sql_select = implode(", ", $sql_select);
		$sql = "select {$sql_select}
			from `USERS2_OFFERS_GROUPS` as g
			where {$sql_where}
			order by ID DESC
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$ret [$r->ID] = $r;
			foreach ($external_offer_fields as $external_offer_field) {
				if ($r->$external_offer_field > 0) $oferty_ids [$r->$external_offer_field] []= $r->ID;
			}
		}
		if (!empty($oferty_ids)) {
			$sql_oferty_ids = array();
			foreach ($oferty_ids as $k_offer_id => $v) {
				$sql_oferty_ids []= "'" . $k_offer_id . "'";
			}
			
			$sql_select = array();
			$cols = self::cols_offers();
			foreach ($cols as $v_col) {
				$sql_select []= "o.`" . $v_col . "`";
			}
			//$sql_select []= "'' as upust";
			//$sql_select []= "o.P_NORMAL_PRICE*12 - o.P_DEAL_PROMO_MONTHS*o.P_PROMO_MONTH_PRICE - (12 - o.P_DEAL_PROMO_MONTHS)*o.P_CONTRACT_PRICE + (o.P_INSTALL_QUOTE_NORMAL - o.P_INSTALL_QUOTE) as `test_upust`";

			//$sql_select []= "ROUND(( ((12 - o.P_DEAL_PROMO_MONTHS)*o.P_CONTRACT_PRICE) + (o.P_DEAL_PROMO_MONTHS*o.P_PROMO_MONTH_PRICE) + (o.P_INSTALL_QUOTE))/12, 2) as test_srednia";
			//$sql_select []= "ROUND(( ((12 - 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))/12, 2) as test_srednia_netto";


			$sql_select = implode(", ", $sql_select);
			$sql = "select {$sql_select}
				from `USERS2_OFFERS` as o
			where
				o.`ID` in(" . implode(", ", $sql_oferty_ids) . ")
			";
			$res = $db->query($sql);
			while ($r = $db->fetch($res)) {
				$group_ids_to_add = $oferty_ids[$r->ID];
				foreach ($group_ids_to_add as $v_group_id) {
					if (!isset($ret [$v_group_id]->oferty)) $ret [$v_group_id]->oferty = array();
					$ret [$v_group_id]->oferty [$r->ID] = clone $r;
				}
			}
		}
		return $ret;
	}

	function get_offers_costs_by_offer_ids($offer_ids = array()) {
		$oferty_costs = array();
		$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 ] = $r->P_OFFER_COSTS;
		}
		return $oferty_costs;
	}

}

class X_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 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 X_Column_users2_offers_groups extends X_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;

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

	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;

		$oferty_costs = Offers_Groups_Model::get_offers_costs_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];
			}
		}

	}

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

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

}

