<?php


/**
 * Module AKCJE (?MENU_INIT=USERS2_MARKETING_AKCJE)
 * 
 * TODO: add AKCJA_TYPE enum('ULOTKA','ANKIETA') NOT NULL DEFAULT 'ULOTKA';
 * TODO: add FILTR_OPERATOR enum('WSZYSCY', 'TYLKO NASI (BN i ND)', 'TYLO OBCY') NOT NULL DEFAULT 'WSZYSCY'
 * TODO: add FILTR_MARKETING_DATA enum('TAK', 'NIE') NOT NULL DEFAULT 'NIE';
 * TODO: add FILTR_USLUGI set('NET','TV','TEL') NOT NULL DEFAULT '';
 * 
 * 
 */
function USERS2_MARKETING_AKCJE() {
	global $thiss, $SQL_USER, $SQL_DATABASE, $INTERFACE_ADDR, $SQL_USER_PASS;

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

	{// DETECT_TABLE_COLUMN();
		$thiss->DETECT_TABLE_COLUMN = 'USERS2_MARKETING_AKCJE_COLUMN';
		$thiss->DETECT_TABLE_NAME = 'USERS2_MARKETING_AKCJE';
		$thiss->DETECT_HIST_FUNCTION = 'USERS2_MARKETING_AKCJE_HIST';
		$thiss->DETECT_EDIT_FUNCTION = 'USERS2_MARKETING_AKCJE_EDIT';
	}

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

	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']["DATA"] = "R";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']["W_DATA_DOSTARCZONO"] = "RWX";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']["W_DATA_WPROWADZONO"] = "RWX";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']["K_DATA_DOSTARCZONO"] = "RWX";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']["K_DATA_WPROWADZONO"] = "RWX";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']['A_ADM_COMPANY'] = '';
	//$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT'][""] = "";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']["DO_ROZNIESIENIA"] = "R";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']["A_STATUS"] = "R";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']["ROZNIESIONO"] = "R";

	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG']["ID_PROJECT"] = "ID projektu ulotki/plakatu";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG']["FILTR_BEZ_BN"] = "Czy pominac operatora BN?";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG']["FILTR_ANEKSY"] = "Czy brac pod uwage koniec aktualnej umowy (3-mc przed koncem)";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG']["FILTR_MIN_ULOTEK_NA_BUDYNEK"] = "Maksymalne nasycenie na budynku (procent 0-100)";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG']["FILTR_MIN_DATA_OSTATNIEJ_AKCJI"] = "Uwzględnij tylko budynki z datą akcji do:";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG']["W_USER"] = "Pracownik wykonujacy zadanie";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG']["W_DATA"] = "Termin wykonania zadania";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG']["K_USER"] = "Kontroler wykonania zadania";
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG']["K_DATA"] = "Termin wykonania kontroli";

	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['TYPESPECIAL']['ID_PROJECT'] = 'USERS2_MARKETING_AKCJE_typespecial_ID_PROJECT';
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['TYPESPECIAL']['FILTR_M_REWIR'] = 'USERS2_MARKETING_AKCJE_typespecial_FILTR_M_REWIR';
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['TYPESPECIAL']['FILTR_S_ADDRESS_STREET'] = 'USERS2_MARKETING_AKCJE_typespecial_FILTR_S_ADDRESS_STREET';
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['TYPESPECIAL']['W_USER'] = 'USERS2_MARKETING_AKCJE_typespecial_W_USER';
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['TYPESPECIAL']['K_USER'] = 'USERS2_MARKETING_AKCJE_typespecial_K_USER';

	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['HIDE'][ $_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_KEY']["FILTR_M_REWIR"] ] = 'HIDE';

	// router
	global $ARG1,$ARG1_VAL;
	switch ($ARG1) {
		case 'ADD': {
			if (isset($_POST)) {
				// update new record in session
				foreach ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'] as $field_name) {
					if (strstr($_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT'][$field_name], "C")) {
						if (isset($_POST[$field_name])) {
							$_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD'][$field_name] = $_POST[$field_name];
						}
					}
				}//end foreach
			}
			if (isset($_POST['task'])) {
				if ($_POST['task'] == 'save') {
					$ret = USERS2_MARKETING_AKCJE_task_ADD_save();
					if ($ret) {
						echo'<p>'."Dodano nowy rekord (ID = ".$ret.")".'</p>';
						echo'<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE".'">'."Cofnij ".'<img src=icon/back.gif border=0 alt=POWROT>'.'</a>';
					} else {
						USERS2_MARKETING_AKCJE_task_ADD_verify();
					}
					return;
				}
				if ($_POST['task'] == 'verify') {
					// show budynki by filter
					USERS2_MARKETING_AKCJE_task_ADD_verify();
					return;
				} else {
					// ??
				}
			}

			USERS2_MARKETING_AKCJE_task_ADD();
			return;

			break;
		}
		case 'EDIT': {
			// fetch ID from ARG1_VAL
			$record_id = V::get('ARG1_VAL', '', $_REQUEST, 'int');
			if ($record_id < 0) {
				echo'<p style="color:red">'."Wrong ID".'</p>';
				return;
			}
			// fetch object by ID
			if (empty($_SESSION[$thiss->DETECT_TABLE_COLUMN]['WIEVID'])) {
				$_SESSION[$thiss->DETECT_TABLE_COLUMN]['WIEVID'] = $record_id;
			} else if ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['WIEVID'] != $record_id) {
				// TODO: clean ses cache data
				$_SESSION[$thiss->DETECT_TABLE_COLUMN]['WIEVID'] = $record_id;
			}

			$zapSQL = "SELECT * from `".$thiss->DETECT_TABLE_NAME."` where `ID`='" . $_SESSION[$thiss->DETECT_TABLE_COLUMN]['WIEVID'] . "' ";
			if (isset($_SESSION[$thiss->DETECT_TABLE_COLUMN]['TYPE']['A_ADM_COMPANY'])) {
				$zapSQL .= " and `A_ADM_COMPANY` like '".$_SESSION['ADM_COMPANY']."' ";
			}
			$result = DB::query($zapSQL) or die("Blad zapytania2!");
			$num_rows = DB::num_rows($result);
			$_SESSION[$thiss->DETECT_TABLE_COLUMN]['MYSQL_NUM_ROWS'] = $num_rows;
			$record = DB::fetch_assoc($result);
			if (!$record) {
				echo'<p style="color:red">'."Record not exists!".'</p>';
				return;
			}

			$task = V::get('task', '', $_REQUEST);
			switch ($task) {
				case 'zlecenie':
					USERS2_MARKETING_AKCJE_task_EDIT_zlecenie($record_id, $record);
					break;
				case 'wprowadz_zlecenie_data':
					USERS2_MARKETING_AKCJE_task_EDIT_wprowadz_zlecenie_data($record_id, $record);
					break;
				case 'wprowadz_zlecenie':
					USERS2_MARKETING_AKCJE_task_EDIT_wprowadz_zlecenie($record_id, $record);
					break;
				case 'zlecenie_kontroli':
					USERS2_MARKETING_AKCJE_task_EDIT_zlecenie_kontroli($record_id, $record);
					break;
				case 'wprowadz_zlecenie_kontroli_data':
					USERS2_MARKETING_AKCJE_task_EDIT_wprowadz_zlecenie_kontroli_data($record_id, $record);
					break;
				case 'wprowadz_zlecenie_kontroli':
					USERS2_MARKETING_AKCJE_task_EDIT_wprowadz_zlecenie_kontroli($record_id, $record);
					break;
				case 'delete':
					USERS2_MARKETING_AKCJE_task_EDIT_A_STATUS('delete', $record_id, $record);
					break;
				case 'undelete':
					USERS2_MARKETING_AKCJE_task_EDIT_A_STATUS('undelete', $record_id, $record);
					break;
				default:
					USERS2_MARKETING_AKCJE_task_EDIT($record_id, $record);
			}
			break;
		}
		case 'HIST': {
			USERS2_MARKETING_AKCJE_task_HIST();
			return;
			break;
		}
		case 'PODSUMOWANIE':
			USERS2_MARKETING_AKCJE_podsumowanie();
			break;
		case 'PODSUMOWANIE_USER':
			USERS2_MARKETING_AKCJE_podsumowanie_user();
			break;
		default: {
			// update sql like RELATIVEDB
			$sql = "update `USERS2_MARKETING_AKCJE` as a set
					a.`DO_ROZNIESIENIA`=(select sum(ab.DO_ROZNIESIENIA) from USERS2_MARKETING_AKCJE_BUILDINGS as ab where ab.ID_AKCJA=a.ID)
					, a.`ROZNIESIONO`=(select sum(ab.ROZNIESIONO) from USERS2_MARKETING_AKCJE_BUILDINGS as ab where ab.ID_AKCJA=a.ID)
				where 1=1
			";
			DB::query($sql);

			USERS2_MARKETING_AKCJE_list();
		}
	}
}


class USERS2_MARKETING_AKCJE {


	function &get_buildings($record_id, &$record) {
		global $thiss;
		// USERS2_MARKETING_AKCJE_BUILDINGS
		{
			$thiss->DETECT_TABLE_COLUMN = 'USERS2_MARKETING_AKCJE_BUILDINGS_COLUMN';
			$thiss->DETECT_TABLE_NAME = 'USERS2_MARKETING_AKCJE_BUILDINGS';
			$thiss->DETECT_HIST_FUNCTION = 'USERS2_MARKETING_AKCJE_HIST';
			$thiss->DETECT_EDIT_FUNCTION = 'USERS2_MARKETING_AKCJE_EDIT';
			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">thiss: ';print_r($thiss);echo'</pre>';
			$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']['A_ADM_COMPANY'] = '';
			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">SES[thiss]: ';print_r($_SESSION[$thiss->DETECT_TABLE_COLUMN]);echo'</pre>';
		}
		$buildings = array();
		$sql = "select a.*
			from `" . $thiss->DETECT_TABLE_NAME . "` as a
			where
				a.`ID_AKCJA`='" . $record_id . "'
			order by a.`S_ADDRESS_STREET`
		";
		$res = DB::query($sql) or die("sql error: $sql");
		while ($h = DB::fetch_assoc($res)) {
			$h['S_ADDRESS_STREET'] = strtoupper($h['S_ADDRESS_STREET']);
			$h['nr_domu'] = intval( preg_replace('/[^0-9]/', '', $h['S_ADDRESS_STREET']) );
			$h['street_short'] = preg_replace('/[0-9]/', '', $h['S_ADDRESS_STREET']);
			$buildings[ $h['S_ADDRESS_STREET'] ] = $h;
		}
		if (empty($buildings)) {
			echo'<p style="color:red">'."Brak przypisanych budynkow!".'</p>';
			return;
		}
		function sort_marketing_akcje_buildings_callback($a, $b) {
			if ($a['street_short'] < $b['street_short']) {
				return -1;
			} else if ($a['street_short'] > $b['street_short']) {
				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( $buildings, 'sort_marketing_akcje_buildings_callback' );
		return $buildings;
	}


	function fetch_buildings_types(&$buildings) {
		if (empty($buildings)) {
			return;
		}
		$sql_buildings_streets = array();
		foreach ($buildings as $k_street => $v_building) {
			$sql_buildings_streets []= "'" . $k_street . "'";
			$buildings[$k_street]['T_BUILDING_TYPE'] = '';
		}
		if (empty($sql_buildings_streets)) {
			return;
		}
		$sql = "select b.`S_ADDRESS_STREET`, b.`T_BUILDING_TYPE`
			from `BUILDINGS` as b
			where b.`S_ADDRESS_STREET` in(" . implode(", ", $sql_buildings_streets) . ")
		";
		$res = DB::query($sql);
		while ($r = DB::fetch($res)) {
			if (isset($buildings[$r->S_ADDRESS_STREET])) {
				$buildings[$r->S_ADDRESS_STREET]['T_BUILDING_TYPE'] = $r->T_BUILDING_TYPE;
			}
		}
	}


	function &get_buildings_by_user_month($user, $month, $order_by = 'S_ADDRESS_STREET', $order_dir = 'ASC') {
		global $thiss;
		// USERS2_MARKETING_AKCJE_BUILDINGS
		{
			$thiss->DETECT_TABLE_COLUMN = 'USERS2_MARKETING_AKCJE_BUILDINGS_COLUMN';
			$thiss->DETECT_TABLE_NAME = 'USERS2_MARKETING_AKCJE_BUILDINGS';
			$thiss->DETECT_HIST_FUNCTION = 'USERS2_MARKETING_AKCJE_HIST';
			$thiss->DETECT_EDIT_FUNCTION = 'USERS2_MARKETING_AKCJE_EDIT';
			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">thiss: ';print_r($thiss);echo'</pre>';
			$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']['A_ADM_COMPANY'] = '';
			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">SES[thiss]: ';print_r($_SESSION[$thiss->DETECT_TABLE_COLUMN]);echo'</pre>';
		}
		if (!$order_by) $order_by = 'S_ADDRESS_STREET';
		$buildings = array();
		$sql = "select ab.*, a.`ID_PROJECT`
			from `" . 'USERS2_MARKETING_AKCJE' . "` as a
				left join `" . $thiss->DETECT_TABLE_NAME . "` as ab on(ab.`ID_AKCJA`=a.`ID`)
			where
				a.`A_STATUS`!='DELETED'
				and a.`W_USER`='" . $user . "'
				and a.`W_DATA` like '" . $month . "-%'
			order by ab.`" .  $order_by . "` " . $order_dir . "
		";
		$res = DB::query($sql) or die("sql error: $sql");
		while ($h = DB::fetch_assoc($res)) {
			$h['S_ADDRESS_STREET'] = strtoupper($h['S_ADDRESS_STREET']);
			$h['nr_domu'] = intval( preg_replace('/[^0-9]/', '', $h['S_ADDRESS_STREET']) );
			$h['street_short'] = preg_replace('/[0-9]/', '', $h['S_ADDRESS_STREET']);
			$buildings[ $h['ID'] ] = $h;
		}
		if (empty($buildings)) {
			echo'<p style="color:red">'."Brak przypisanych budynkow!".'</p>';
			return;
		}
		if ($order_by == 'S_ADDRESS_STREET') {
			// TODO: sort_dir - DESC
			function sort_marketing_akcje_buildings_callback($a, $b) {
				if ($a['street_short'] < $b['street_short']) {
					return -1;
				} else if ($a['street_short'] > $b['street_short']) {
					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( $buildings, 'sort_marketing_akcje_buildings_callback' );
		}
		return $buildings;
	}


	function &get_mieszkania($record_id, &$record) {
		global $thiss;
		// USERS2_MARKETING_AKCJE_BUILDINGS
		{
			$thiss->DETECT_TABLE_COLUMN = 'USERS2_MARKETING_AKCJE_BUILDINGS_COLUMN';
			$thiss->DETECT_TABLE_NAME = 'USERS2_MARKETING_AKCJE_BUILDINGS';
			$thiss->DETECT_HIST_FUNCTION = 'USERS2_MARKETING_AKCJE_HIST';
			$thiss->DETECT_EDIT_FUNCTION = 'USERS2_MARKETING_AKCJE_EDIT';
			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">thiss: ';print_r($thiss);echo'</pre>';
			$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']['A_ADM_COMPANY'] = '';
			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">SES[thiss]: ';print_r($_SESSION[$thiss->DETECT_TABLE_COLUMN]);echo'</pre>';
		}
		$mieszkania = array();
		$sql_filter_bez_bn = "";
		if ($record['FILTR_BEZ_BN'] == 'TAK') {
			$sql_filter_bez_bn = " and m.`I_OPER`!='BN' ";
		}
		$sql = "select m.`T_TELBOX_BUILDING_IN`, m.`S_ADDRESS_STREET`, m.`I_OPER`
			from `" . $thiss->DETECT_TABLE_NAME . "` as ab
				left join `USERS2_MARKETING` as m on(m.`T_TELBOX_BUILDING_IN`=ab.`S_ADDRESS_STREET`)
			where ab.`ID_AKCJA`='" . $record_id . "'
				$sql_filter_bez_bn
			order by ab.`S_ADDRESS_STREET` asc
		";
		$res = DB::query($sql) or die("sql error: $sql");
		while ($h = DB::fetch_assoc($res)) {
			$h['T_TELBOX_BUILDING_IN'] = strtoupper($h['T_TELBOX_BUILDING_IN']);
			$h['S_ADDRESS_STREET'] = strtoupper($h['S_ADDRESS_STREET']);
			$s_address_street = explode('/', $h['S_ADDRESS_STREET'], 2);
			$h['dom'] = intval( preg_replace('/[^0-9]/', '', reset($s_address_street)) );// reset($s_address_street);
			$h['nr_domu'] = end($s_address_street);
			$mieszkania[ $h['T_TELBOX_BUILDING_IN'] ] []= $h;
		}
		function sort_marketing_akcje_mieszkania_callback($a, $b) {
			if ($a['T_TELBOX_BUILDING_IN'] < $b['T_TELBOX_BUILDING_IN']) {
				return -1;
			} else if ($a['T_TELBOX_BUILDING_IN'] > $b['T_TELBOX_BUILDING_IN']) {
				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;
			}
		}
		foreach ($mieszkania as $k_building => $v_arr) {
			uasort( $mieszkania[$k_building], 'sort_marketing_akcje_mieszkania_callback' );
			//ksort( $mieszkania[$k_building]);
		}
		function sort_marketing_akcje_budynki_callback($a_arr, $b_arr) {
			$a = reset($a_arr);
			$b = reset($b_arr);
			if ($a['T_TELBOX_BUILDING_IN'] < $b['T_TELBOX_BUILDING_IN']) {
				return -1;
			} else if ($a['T_TELBOX_BUILDING_IN'] > $b['T_TELBOX_BUILDING_IN']) {
				return 1;
			} else if ($a['dom'] < $b['dom']) {
				return -1;
			} else if ($a['dom'] > $b['dom']) {
				return 1;
			} else {
				return 0;
			}
		}
		uasort( $mieszkania, 'sort_marketing_akcje_budynki_callback' );
		return $mieszkania;
	}


	function print_rewir_tree_css() {
		echo'<style type="text/css">'."
#tree {font-size:small;}
#tree, #tree ul { padding:0; margin:0; list-style-type:none; background: url(./stuff/i/tree-vline.png) repeat-y; }
#tree ul { margin-left:10px; }
#tree li { margin:0; padding:0 6px; line-height:16px; background:url(./stuff/i/tree-node.png) no-repeat; color:#666; font-weight:bold; }
#tree li.last { background:#fff url(./stuff/i/tree-lastnode.png) no-repeat; }

#tree .pr{color:#00B700;}
#tree .pr-highest{color:#f00;}
#tree .pr-high{color:#FF6300;}
#tree .pr-medium{color:#00f;}
#tree .pr-disable{color:#BFBFBF;text-decoration:line-through;}
#tree .selected b{background-color:#FFFFAB;}
#tree b.disabled{background-color:#E1E1E1;}
#tree .btn{margin:0 2px;padding:0 2px;color:#FF5D5D;}
		".'</style>';
	}
	function print_rewir_tree_js() {
		echo'<script type="text/javascript" src="stuff/jquery.js"></script>';
		echo'<script type="text/javascript">'."
jQuery(document).ready(function(){

	jQuery('#frm select[name=ID_PROJECT]').css('width', '400px');

	jQuery('#tree ul').each(function(ind,n){
		jQuery(n).find('li:last-child').addClass('last');
	});

	fieldChangeRefresh();
});

function treeClearAll(){
	jQuery('#tree input').each(function(ind,item){
		item.checked = false;
	});
	jQuery('#tree .selected').removeClass('selected');
}

function fieldChangeRefresh() {
	//console.log('fieldChangeRefresh...')
	treeClearAll();

	var rewiry=jQuery('#frm textarea[name=FILTR_M_REWIR]').text();
	var street=jQuery('#frm textarea[name=FILTR_S_ADDRESS_STREET]').text();
	if (rewiry.length > 0) {
		rewiry = rewiry.split(',');
		//console.log(rewiry)
		var item=null;
		for(var i=0; i<rewiry.length; ++i){
			//console.log('searching for ' + rewiry[i] + ' ...')
			item=jQuery('#frm input[value=\"rewir_'+rewiry[i]+'\"]');
			//console.log(item)
			if (item) {
				itemChange(item.get(0), true, true)
			}
		}
	}
	if (street.length > 0) {
		street = street.split(',');
		//console.log(street)
		var item=null;
		for(var i=0; i<street.length; ++i){
			//console.log('searching for ' + street[i] + ' ...')
			item=jQuery('#frm input[value=\"street_'+street[i]+'\"]');
			//console.log(item)
			if (item) {
				itemChange(item.get(0), true, true)
			}
		}
	}
	return false;
}

function fieldChangeRec(f, n){
	fieldChange(f, n);
	jQuery(n).parent().find('input').each( function(i,node){
		if(!node.checked) {
			var filtr = jQuery(node).attr('filtr');
			if (filtr) {
				node.checked = n.checked;
				fieldChange(node.form[filtr], node);
			}
		}
	})
}

function fieldChange(f, n, value){
	if (n.checked) {// zaznacz
		if (f.innerHTML == '') {
			f.innerHTML = value;
		} else {
			f.innerHTML += ',' + value;
		}
	} else {// odznacz
		f.innerHTML = (',' + f.innerHTML + ',').replace(',' + value + ',', ',');
		f.innerHTML = f.innerHTML.replace(/,,/g, ',');
		f.innerHTML = f.innerHTML.substr(1, f.innerHTML.length - 2);
	}
}

function onItemChange(n){
	var frm=n.form;
	itemChange(n, n.checked)
}

function itemChange(n, checked, dont_change_field){
	var frm=n.form;
	n.checked = checked;
	if (!dont_change_field) {
		if (n.value.substring(0,6) == 'street') {
			fieldChange(frm.FILTR_S_ADDRESS_STREET, n, n.value.substring(7))
		} else if (n.value.substring(0,6) == 'rewir_') {
			fieldChange(frm.FILTR_M_REWIR, n, n.value.substring(6))
		}
	}
	jQuery(n).parent().toggleClass('selected');
}
		".'</script>';
	}
	function print_rewir_tree(&$record_data) {
		global $thiss;
		$rewiry = array();
		$buildings = array();
		$rewiry_selected = explode(',', $record_data['FILTR_M_REWIR']);
		$buildings_selected = explode(',', $record_data['FILTR_S_ADDRESS_STREET']);

		// fetch old actions on buildings
		$old_actions = array();
		$sql = "select
				mb.`S_ADDRESS_STREET` as street
				, max(ma.`DATA`) as last_date
			from `USERS2_MARKETING_AKCJE_BUILDINGS` as mb
				left join `USERS2_MARKETING_AKCJE` as ma on(ma.`ID`=mb.`ID_AKCJA`)
			where
				ma.`A_STATUS`!='DELETED'
			group by mb.`S_ADDRESS_STREET`
		";
		$res = DB::query($sql);
		while ($r = DB::fetch($res)) {
			$r->street = strtoupper($r->street);
			$old_actions[$r->street] = $r->last_date;
		}

		// filtr bez BN
		$sql_ulotek = "ov.`MIESZKAN`";
		if ($record_data['FILTR_BEZ_BN'] == 'TAK') {
			$sql_ulotek = "(ov.`MIESZKAN` - ov.`ABO_I`)";
		}
		// filtr FILTR_MIN_ULOTEK_NA_BUDYNEK
		$sql_ulotek_enable = "1";
		if ($filtr_min_ulotek_na_budynek = V::get('FILTR_MIN_ULOTEK_NA_BUDYNEK', 0, $record_data, 'int')) {
			if ($record_data['FILTR_BEZ_BN'] == 'TAK') {
				$sql_ulotek_enable = "  ( (100 * ov.`ABO_I`) / ov.`MIESZKAN` ) <= ".$filtr_min_ulotek_na_budynek."";
			}
		}
		// TODO: filtr aneksy

		$sql = "select b.`ID`, b.`M_REWIR`, b.`S_ADDRESS_STREET`, b.`P_ADDRESS_STREET`
				, ov.`ABO_I`, ov.`MIESZKAN`
				, $sql_ulotek as ile_ulotek
				, ( (100 * ".$sql_ulotek.") / ov.`MIESZKAN` ) as pr
				, $sql_ulotek_enable as ulotek_enable
				, 1 as data_enable
			from `BUILDINGS` as b
				left join `USERS2_MARKETING_OVERWIEV` as ov on(ov.`T_TELBOX_BUILDING_IN`=b.`S_ADDRESS_STREET`)
			where
				b.`A_STATUS` in('NORMAL','WARNING')
			group by b.`ID`
			order by b.`M_REWIR`
		";
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none">sql (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
		$res = DB::query($sql);
		while ($r = DB::fetch($res)) {
			if ($filtr_data = V::get('FILTR_MIN_DATA_OSTATNIEJ_AKCJI', 0, $record_data)) {
				if (array_key_exists($r->S_ADDRESS_STREET, $old_actions)) {
					if ($old_actions[$r->S_ADDRESS_STREET] >= $filtr_data) {
						$r->data_enable = 0;
						$r->last_action_date = $old_actions[$r->S_ADDRESS_STREET];
					}
				}
			}
			$r->rewir = explode('.', strtoupper($r->M_REWIR));
			$r->dom = intval( preg_replace('/[^0-9]/', '', $r->S_ADDRESS_STREET) );
			$rewir = $r->M_REWIR;
			$buildings [$r->ID] = $r;
			if ($r->dom > 0) {
				$rewiry [strtoupper($r->M_REWIR)] []= $r;
			}
		}

		function buildings_map_tree_add( &$tree, &$r, $filtr_last_data, $add_path, $cur_path = array() ) {
			if ($add_path == '') {
				$disable = false;
				$disable_reaseon = '';
				if (!$r->ulotek_enable) {
					$disable = true;
					$disable_reaseon = ' - za duże nasycenie';
				}
				if (!$r->data_enable) {
					$disable = true;
					$disable_reaseon = ' - data ostatniej akcji '.$r->last_action_date.' &gt; '.$filtr_last_data;
				}

				// 			, ov.`ABO_I`, ov.`MIESZKAN`
				$procent = round(($r->ABO_I * 100) / $r->MIESZKAN);
				$st = '';
				$cls = '';
				if ($procent < 30) $cls = 'pr-highest';
				else if ($procent < 60) $cls = 'pr-high';
				else if ($procent < 80) $cls = 'pr-medium';
				$out_title = $r->P_ADDRESS_STREET.": ".$r->ABO_I." abonentow /".$r->MIESZKAN." mieszkan";
				if ($disable) {
					$cls = 'pr-disable';
					$out_title .= $disable_reaseon;
				}
				$out = '';
				$out .= '<b class="pr '.$cls.'" title="'.$out_title.'">';
				$out .= '<span>'.$r->S_ADDRESS_STREET.'</span>';
				$out .= ' <span style="font-size:small;color:#666">('.$procent."%".')</span>';
				$out .= '</b>';
				$tree['buildings'] [$r->S_ADDRESS_STREET] = $out;
				return;
			}
			$path = explode('.', strtoupper($add_path));
			$cur_path []= array_shift($path);// 1st elem
			$cur_path_str = implode('.', $cur_path);
			if (!array_key_exists($cur_path_str, $tree)) {
				$tree [$cur_path_str] = array();
			}
			buildings_map_tree_add( $tree[$cur_path_str], $r, $filtr_last_data, implode('.', $path), $cur_path );
		}

		function buildings_map_show_tree( &$tree, &$rewiry_selected, &$buildings_selected ) {
			if (empty($tree)) {
				return;
			}
			echo'<ul>';
				foreach ($tree as $k => $v) {
					$id = '';
					$out = '';
					$cls = '';
					if ($k == 'buildings') {
						foreach ($v as $k_street_short => $v_long) {
							$checked = '';//(in_array($k_street_short, $buildings_selected))? ' checked="checked"' : '';
							$out .= '<nobr>';
							$out .= '<input type="checkbox" value="'."street_".$k_street_short.'" onclick="'."return onItemChange(this)".'" '.$checked.' />';
							$out .= $v_long;
							$out .= '</nobr>';
							$out .= ' ';
						}//end foreach
					}
					else {
						$cls = '';
						$checked = '';
						if (in_array($k, $rewiry_selected)) {
							$checked = '';//' checked="checked"';
							$cls = '';//' class="selected"';
						}
						$id = ' id="rewir_'.$k.'"';
						$out .= '<input type="checkbox" value="'."rewir_".$k.'" onclick="'."return onItemChange(this)".'" '.$checked.' />';
						$out .=  '<b>'.$k.'</b>';
					}

					echo'<li'.$cls.''.$id.'>';
					echo $out;
					if ($k != 'buildings') {
						if (is_array($v)) {
							if ($k) {
								buildings_map_show_tree( $v, $rewiry_selected, $buildings_selected );
							}
						}
					}
					echo'</li>';
				}//end foreach
			echo'</ul>';
		}

		$rewiry_tree = array();
		foreach ($rewiry as $k_rewir => $v_budynki) {
			foreach ($v_budynki as $r) {
				$filtr_last_data = V::get('FILTR_MIN_DATA_OSTATNIEJ_AKCJI', 0, $record_data);
				buildings_map_tree_add( $rewiry_tree, $r, $filtr_last_data, $r->M_REWIR );
			}
		}
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($rewiry_tree);echo'</pre>';

		echo'<div id="tree">';
			$js = "this.form.task.value='';this.form.submit()";
			echo'<button onclick="'.$js.'">'."odswiez".'</button>';
		buildings_map_show_tree( $rewiry_tree, $rewiry_selected, $buildings_selected );
		echo'</div>';

		self::print_rewir_tree_css();
		self::print_rewir_tree_js();
	}


	function &print_akcje_table_item($field_name, &$record_arr) {
		$out = $record_arr[$field_name];
		switch ($field_name) {
			case 'FILTR_S_ADDRESS_STREET': {
				$out = str_replace(',', ', ', $out);
				$max_length = 60;
				if (strlen($out) > $max_length) {
					$out = '<span title="'.$out.'">'.substr($out, 0, $max_length)."...".'</span>';
				}
				break;
			}
			case 'A_STATUS': {
				if ($record_arr[$field_name] == 'DELETED') {
					$js = "return confirm('Czy jestes pewien ze chcesz przywrócić rekord ID=" . $record_arr['ID'] . "');";
					$out = '<span style="color:silver">' . $out . '</span>';
					$out .= '<br />' . '<a href="' . "index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=EDIT&ARG1_VAL=" . $record_arr['ID'] . "&task=undelete" . '" onclick="' . $js . '">' . "przywróć" . '</a>';
				}
				else {
					$js = "return confirm('Czy jestes pewien ze chcesz usunac rekord ID=" . $record_arr['ID'] . "');";
					$out = '<span style="color:green">' . $out . '</span>';
					$out .= '<br />' . '<a href="' . "index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=EDIT&ARG1_VAL=" . $record_arr['ID'] . "&task=delete" . '" onclick="' . $js . '">' . "usuń" . '</a>';
				}
				break;
			}
			default:
				
		}
		
		return $out;
	}
}// class


function USERS2_MARKETING_AKCJE_task_ADD_save() {
	global $thiss;

	$arr = array();
	foreach ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'] as $field_name) {
		if (strstr($_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT'][$field_name],"C")) {
			if (isset($_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD'][$field_name])) {
				$arr[$field_name] = $_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD'][$field_name];
			}
		}
	}

	$arr['A_RECORD_CREATE_DATE'] = date('Y-m-d-H:i');
	$arr['A_RECORD_CREATE_AUTHOR'] = $_SESSION['ADM_ACCOUNT'];
	$arr['DATA'] = date("Y-m-d");
	if (!empty($_POST['update_FILTR_S_ADDRESS_STREET'])) {
		$arr['FILTR_S_ADDRESS_STREET'] = $_POST['update_FILTR_S_ADDRESS_STREET'];
	}
	if (!empty($_POST['update_ILE_ULOTEK'])) {
		//TODO: $arr['ILE_ULOTEK'] = $_POST['update_ILE_ULOTEK'];
	}

	if (empty($arr)) {
		return false;
	}

	$sql_arr = array();
	foreach ($arr as $k => $v) {
		$sql_arr["`".$k."`"] = "'".$v."'";
	}//end foreach
	
	$sql = "insert into `".$thiss->DETECT_TABLE_NAME."` (".implode(",", array_keys($sql_arr)).") values(".implode(",", $sql_arr)."); ";
	DB::query($sql);
	$ret_id = DB::insert_id();
	if (!$ret_id) {
		return;
	}

	if(1){
	// filtr bez BN
	$sql_ulotek = "ov.`MIESZKAN`";
	if ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD']['FILTR_BEZ_BN'] == 'TAK') {
		$sql_ulotek = "(ov.`MIESZKAN` - ov.`ABO_I`)";
	}
	// filtr FILTR_MIN_ULOTEK_NA_BUDYNEK
	$sql_ulotek_enable = "1=1";
	if ($filtr_min_ulotek_na_budynek = V::get('FILTR_MIN_ULOTEK_NA_BUDYNEK', 0, $record_data, 'int')) {
		if ($record_data['FILTR_BEZ_BN'] == 'TAK') {
			$sql_ulotek_enable = "  ( (100 * ov.`ABO_I`) / ov.`MIESZKAN` ) <= ".$filtr_min_ulotek_na_budynek."";
		}
	}
	// TODO: filtr aneksy - 3-mce przed koncem umowy

	$streets = explode(',', $arr['FILTR_S_ADDRESS_STREET']);
	$sql = "insert into `USERS2_MARKETING_AKCJE_BUILDINGS` (`A_RECORD_CREATE_DATE`,`A_RECORD_CREATE_AUTHOR`,`ID_AKCJA`,`S_ADDRESS_STREET`,`DO_ROZNIESIENIA`)
		select '".$_SESSION['AUTHORIZE_USER']."'
			, NOW()
			, ".$ret_id."
			, ov.`T_TELBOX_BUILDING_IN`
			, ".$sql_ulotek."
		from `USERS2_MARKETING_OVERWIEV` as ov
		where
			ov.`T_TELBOX_BUILDING_IN` in('".implode("','", $streets)."')
			and ".$sql_ulotek_enable."
	";
	echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;display:none">sql: ';print_r($sql);echo'</pre>';
	DB::query($sql);
	}

	// clean session cache
	unset($_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD']);

	return $ret_id;
}


function USERS2_MARKETING_AKCJE_task_EDIT($record_id, &$record) {
	global $thiss;

	echo'<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE".'">'."Cofnij ".'<img src=icon/back.gif border=0 alt=POWROT>'.'</a>';

	if(0){// EDIT form, @uses TABLE_UPDATEDB
		echo'<table width="100%" border="1" cellspacing="0" cellpadding="0" class="tbl-view">';
		echo'<thead>';
		echo '</TD><TD>'."Nazwa_POLA";
		//CREATE_MENUFUNC_INIT_2($thiss->DETECT_HIST_FUNCTION,'HISTORY',$_SESSION[$thiss->DETECT_TABLE_COLUMN]['WIEVID'],'<img src=icon/history.gif alt=HISTORIA border=0>');
		// TODO: HIST function
		echo '</TD><TD>'."WARTOSC".'</TD></TR>';
		echo'</thead>';
		echo'<tbody>';
		echo '<FORM ACTION="" method="POST">';
		echo '<input type="HIDDEN" name="WIEVID" value="'.$_SESSION[$thiss->DETECT_TABLE_COLUMN]['WIEVID'].'">';
		echo '<input type="HIDDEN" name="FUNCTION_INIT" value="TABLE_UPDATEDB">';

		$t = 0;
		foreach ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['ID'] as $value) {
			$_SESSION[$thiss->DETECT_TABLE_COLUMN]['EDITRECORD'][ $_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'][$value] ] = $record[$value];
			if(strstr($_SESSION[$thiss->DETECT_TABLE_COLUMN][PERMEDIT][$_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC][$value]],"R")) {
			echo'<tr class="row-' . ($t = 1 - $t) . '">';
			echo "<TD><font size=-2>" ;//. $_SESSION[$thiss->DETECT_TABLE_COLUMN][PERMEDIT][$_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC][$value]];
			echo "<BR>";
			echo "</TD><TD>";
			if($_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC_TO_LANG][$_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC]["$value"]]) { echo $_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC_TO_LANG][$_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC]["$value"]] . "<br>";
			echo "<font size=-2>".$_SESSION[$thiss->DETECT_TABLE_COLUMN]["DESC"]["$value"]."</font>";
			} else echo $_SESSION[$thiss->DETECT_TABLE_COLUMN]["DESC"]["$value"];
			echo "</TD>";
			echo "<TD ";
			USERS_COLUMN_COLOR($_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC][$value],$_SESSION[$thiss->DETECT_TABLE_COLUMN][EDIT_TEMPLATE][$_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC][$value]],bgcolor);
			echo ">";

			//echo "$_SESSION[$thiss->DETECT_TABLE_COLUMN][PERMEDIT][$value]==RW";
			if((strstr($_SESSION[$thiss->DETECT_TABLE_COLUMN][PERMEDIT][$_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC][$value]],"RW")) && (!isset($_SESSION[$thiss->DETECT_TABLE_COLUMN][TYPESPECIAL][$_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC][$value]]))) {
			GETFORMITEM($_SESSION[$thiss->DETECT_TABLE_COLUMN][EDIT_TEMPLATE][$_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC][$value]],$_SESSION[$thiss->DETECT_TABLE_COLUMN][TYPE][$_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC][$value]],$_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC][$value]);
			echo "($record[$value])"; 
			} else if(isset($_SESSION[$thiss->DETECT_TABLE_COLUMN][TYPESPECIAL][$_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC][$value]])) {
			//    echo "special viev of func " . $_SESSION[$thiss->DETECT_TABLE_COLUMN][TYPESPECIAL][$_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC][$value]] . "(" .  $_SESSION[$thiss->DETECT_TABLE_COLUMN]["WIEVID"] .  ") not currently implemented" ;
			$_SESSION[$thiss->DETECT_TABLE_COLUMN][TYPESPECIAL][$_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC][$value]]($_SESSION[$thiss->DETECT_TABLE_COLUMN]["WIEVID"],$_SESSION[$thiss->DETECT_TABLE_COLUMN][EDIT_TEMPLATE][$_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC][$value]]);
			} else echo $_SESSION[$thiss->DETECT_TABLE_COLUMN][EDIT_TEMPLATE][$_SESSION[$thiss->DETECT_TABLE_COLUMN][DESC][$value]];
				echo "</td></TR>";
			}
		}
		echo '<tr><td colspan="3" style="text-align:left"><input type="submit" value="          OK          "></td></tr></form></table>';
	}

	$show_columns = array();
	$show_columns []= 'ID';
	$show_columns []= 'DATA';
	$show_columns []= 'ID_PROJECT';
	$show_columns []= 'FILTR_BEZ_BN';
	$show_columns []= 'FILTR_ANEKSY';
	$show_columns []= 'FILTR_MIN_ULOTEK_NA_BUDYNEK';
	$show_columns []= 'FILTR_MIN_DATA_OSTATNIEJ_AKCJI';
	$show_columns []= 'FILTR_S_ADDRESS_STREET';
	$show_columns []= 'W_USER';
	$show_columns []= 'W_DATA';
	$show_columns []= 'W_DATA_DOSTARCZONO';
	$show_columns []= 'W_DATA_WPROWADZONO';
	$show_columns []= 'K_USER';
	$show_columns []= 'K_DATA';
	$show_columns []= 'K_DATA_DOSTARCZONO';
	$show_columns []= 'K_DATA_WPROWADZONO';

	echo'<table width="100%" border="1" cellspacing="0" cellpadding="0" class="tbl-view">';
	$t = 0;
	foreach ($show_columns as $field_name) {
		if (!strstr($_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT'][ $field_name ], "R")) {
			continue;
		}
		echo '<tr class="row-' . ($t = 1 - $t) . '">';
		echo '<td>';
		if (!empty($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG'][$field_name])) {
			echo $_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG'][$field_name];
			echo '<br /><code style="font-size:x-small">'.$field_name.'</code>';
		} else {
			echo '<code>'.$field_name.'</code> ';
		}
		echo '</td>';
		echo '<td>';
			if (in_array($field_name, array('FILTR_M_REWIR', 'FILTR_S_ADDRESS_STREET'))) {
				echo str_replace(',', ', ', $record[ $field_name ]);
			} else {
				echo $record[ $field_name ];
			}
		echo '</td>';
		echo '</tr>';
	}
	echo'</table>';


	echo'<div style="margin:10px;padding:5px 10px;border:1px solid #666;">';
		// TODO: w zaleznosci od stanu akcji
		$btns = array();
		$btns []= '<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=EDIT&ARG1_VAL=".$record_id."&task=zlecenie".'">'."drukuj zlecenie".'</a>';

		$out_btn = '<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=EDIT&ARG1_VAL=".$record_id."&task=wprowadz_zlecenie_data".'">'."wprowadz date dostarczenia raportu".'</a>';
		$out_btn .= (($record['W_DATA_DOSTARCZONO'] == '0000-00-00')? " <b>!!!</b>" : " (<em>".$record['W_DATA_DOSTARCZONO']."</em>)");
		$btns []= $out_btn;

		$out_btn = '<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=EDIT&ARG1_VAL=".$record_id."&task=wprowadz_zlecenie".'">'."wprowadz zlecenie do systemu".'</a>';
		$out_btn .= (($record['W_DATA_WPROWADZONO'] == '0000-00-00')? " <b>!!!</b>" : " (<em>".$record['W_DATA_WPROWADZONO']."</em>)");
		$btns []= $out_btn;

		echo "<b>Zlecenie dystrybucji:</b> ".'<ul style="list-style-type:decimal">'.'<li>'.implode('</li><li>', $btns).'</li>'.'</ul>';

		if (!empty($record['K_USER'])) {// if K_USER - kontroler
			$btns = array();
			$btns []= '<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=EDIT&ARG1_VAL=".$record_id."&task=zlecenie_kontroli".'">'."drukuj zlecenie kontroli".'</a>';

			$out_btn = '<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=EDIT&ARG1_VAL=".$record_id."&task=wprowadz_zlecenie_kontroli_data".'">'."wprowadz date dostarczenia raportu z kontroli".'</a>';
			$out_btn .= (($record['K_DATA_DOSTARCZONO'] == '0000-00-00')? " <b>!!!</b>" : " (<em>".$record['K_DATA_DOSTARCZONO']."</em>)");
			$btns []= $out_btn;

			$out_btn = '<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=EDIT&ARG1_VAL=".$record_id."&task=wprowadz_zlecenie_kontroli".'">'."wprowadz zlecenie kontroli do systemu".'</a>';
			$out_btn .= (($record['K_DATA_WPROWADZONO'] == '0000-00-00')? " <b>!!!</b>" : " (<em>".$record['K_DATA_WPROWADZONO']."</em>)");
			$btns []= $out_btn;

			echo "<b>Zlecenie kontroli:</b> ".'<ul style="list-style-type:decimal">'.'<li>'.implode('</li><li>', $btns).'</li>'.'</ul>';
		}
	echo'</div>';


	// USERS2_MARKETING_AKCJE_BUILDINGS
	{
		$thiss->DETECT_TABLE_COLUMN = 'USERS2_MARKETING_AKCJE_BUILDINGS_COLUMN';
		$thiss->DETECT_TABLE_NAME = 'USERS2_MARKETING_AKCJE_BUILDINGS';
		$thiss->DETECT_HIST_FUNCTION = 'USERS2_MARKETING_AKCJE_HIST';
		$thiss->DETECT_EDIT_FUNCTION = 'USERS2_MARKETING_AKCJE_EDIT';
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">thiss: ';print_r($thiss);echo'</pre>';
		$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']['A_ADM_COMPANY'] = '';
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">SES[thiss]: ';print_r($_SESSION[$thiss->DETECT_TABLE_COLUMN]);echo'</pre>';
	}

	$buildings = USERS2_MARKETING_AKCJE::get_buildings($record_id, $record);
	USERS2_MARKETING_AKCJE::fetch_buildings_types($buildings);// add T_BUILDING_TYPE

	$suma_do_rozniesienia = 0;
	$suma_rozniesiono = 0;
	foreach ($buildings as $k_street => $h) {
		$suma_do_rozniesienia += $h['DO_ROZNIESIENIA'];
		$suma_rozniesiono += $h['ROZNIESIONO'];
	}

	echo'<style type="text/css">'."
.akcje-buildings th { font-size:x-small; }
.akcje-buildings th.field-T_BUILDING_TYPE { color:#333; }
.akcje-buildings td.field-T_BUILDING_TYPE { font-size:x-small; color:#333; }
	".'</style>';
	echo'<h2>'."Budynki dotyczące zlecenia".'</h2>';
	echo '<p>'."Do rozniesienia ".$suma_do_rozniesienia." - rozniesiono ".$suma_rozniesiono.".";
		echo '<b>'." Skuteczność akcji: ".(($suma_rozniesiono > 0)? round((100 * $suma_rozniesiono/$suma_do_rozniesienia)) : 0)."%".'</b>';
	echo '</p>';
	echo'<table width="100%" border="1" cellspacing="0" cellpadding="0" class="tbl-view akcje-buildings">';
	echo'<thead>';
	echo'<tr>';
		foreach ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'] as $field_name) {
			if (!strstr($_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT'][ $field_name ], "R")) {
				continue;
			}
			echo '<th>' . str_replace('_', ' ', $field_name) . '</th>';
			if ($field_name == 'S_ADDRESS_STREET') {
				echo '<th class="field-T_BUILDING_TYPE">' . str_replace('_', ' ', 'T_BUILDING_TYPE') . '</th>';
			}
		}
	echo'</tr>';
	echo'</thead>';
	echo'<tbody>';
	$t = 0;
	foreach ($buildings as $h) {
		echo '<tr class="row-' . ($t = 1 - $t) . '">';
		foreach ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'] as $field_name) {
			if (!strstr($_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT'][ $field_name ], "R")) {
				continue;
			}
			echo '<td>' . $h[$field_name] . '</td>';
			if ($field_name == 'S_ADDRESS_STREET') {
				echo '<td class="field-T_BUILDING_TYPE">' . $h['T_BUILDING_TYPE'] . '</td>';
			}
		}
		echo'</tr>';
	}//end foreach
	echo'</tbody>';
	echo'</table>';
	
}


function USERS2_MARKETING_AKCJE_task_EDIT_zlecenie($record_id, &$record) {
	global $thiss;

	echo'<style type="text/css">'."
body{font-size:small;padding:0 6px;}
td,table,tr{font-size:small;line-height:1.4em;}
input{margin:0;padding:0;}
	".'</style>';

	$buildings = USERS2_MARKETING_AKCJE::get_buildings($record_id, $record);
	$mieszkania = USERS2_MARKETING_AKCJE::get_mieszkania($record_id, $record);

	if (!empty($mieszkania)) {
		$building_cols = array();// [page_nr] => [col_nr] => [line_nr] => (street, nr)
		$limit_lines = 50;// aby sie zmiescilo na 1 stornie
		$limit_cols = 4;// limit kolumn
		$cur_page_nr = 0;
		$cur_col_ind = 0;
		$cur_line = 0;
		foreach ($mieszkania as $k_street => $v_arr) {
			reset($mieszkania[$k_street]);
			$v_ile = count($v_arr);
			for ($i = 0; $i < $v_ile; $i++) {
				$cur_line++;
				if ($cur_line >= $limit_lines) {
					$cur_line = 1;
					$cur_col_ind++;
					if ($cur_col_ind >= $limit_cols) {
						$cur_col_ind = 0;
						$cur_page_nr++;
					}
				}
				$mieszkanie = current($mieszkania[$k_street]);
				$building_cols[ $cur_page_nr ][ $cur_col_ind ] []= array('street'=>$k_street, 'nr'=>$mieszkanie['S_ADDRESS_STREET']);
				next($mieszkania[$k_street]);
			}
			// podsumowanie
			$cur_line++;
			$building_cols[ $cur_page_nr ][ $cur_col_ind ] []= array('street'=>$k_street, 'nr'=>'podsumowanie', 'x'=>$buildings[$k_street]['DO_ROZNIESIENIA']);
			// godzina
			$cur_line++;
			$building_cols[ $cur_page_nr ][ $cur_col_ind ] []= array('street'=>$k_street, 'nr'=>'godzina');
			// odstep
			$cur_line++;
			$building_cols[ $cur_page_nr ][ $cur_col_ind ] []= array('street'=>$k_street, 'nr'=>'empty');
		}

		$worker_name = $record['W_USER'];
		{// get user name
			$sql = "select a.`ADM_NAME` from `ADMIN_USERS` as a where a.`ADM_ACCOUNT`='".$record['W_USER']."' ";
			$res = DB::query($sql) or die("Blad zapytania! ".$sql);
			$r = DB::fetch($res);
			if ($r) {
				$worker_name = $r->ADM_NAME;
			}
		}

		USERS2_MARKETING_AKCJE_view_zlecenie_1_strona( $record_id, $record, $buildings, $worker_name );

		foreach ($building_cols as $k_page_nr => $v_page_arr) {
			// header
			echo '<p style="page-break-before:always">' . "ZLECENIE KOLPORTAŻU z dnia  <i><b>".$record['DATA']."</b></i>, do procesu dystrybucji nr <i><b>".$record_id."</b></i> z dnia <i><b>".$record['W_DATA']."</b></i>" . '</p>';
//			echo'<p style="page-break-before:always">'."Imię i nazwisko: ".$worker_name;
//				echo " Wprowadzono do SE? ............";
//				echo'<br />';
//				echo "Data kolportażu: ".$record['W_DATA'].".";
//				echo " Kolportarz należy przeprowadzić od godz. ..... do godz. .....";
//				echo'<br />';
//				echo "Raport dostarczyć do: "."BOK Chełm do dnia ................. do godz. .....";
//			echo'</p>';

			echo'<table width="100%" border="0" cellspacing="0" cellpadding="0">';
			$max_col_count = 0;
			foreach ($v_page_arr as $k_col_id => $v_col_arr) {
				$max_col_count = max($max_col_count, count($v_col_arr));
			}
			for ($line_nr = 0; $line_nr < $max_col_count; $line_nr++) {
				echo'<tr>';
				for ($col_nr = 0; $col_nr < $limit_cols; $col_nr++) {
					echo'<td style="width:25%">';
						if (isset($v_page_arr[$col_nr][$line_nr])) {
							if ($v_page_arr[$col_nr][$line_nr]['nr'] == 'empty') {
								echo "&nbsp;";
							} else if ($v_page_arr[$col_nr][$line_nr]['nr'] == 'podsumowanie') {
								echo "<b> suma dla </b>";
								echo $v_page_arr[$col_nr][$line_nr]['street'];
								echo " ";
								echo '<input type="text" size="5" value="'."".'" style="display:inline;width:40px;height:auto;border:1px solid #000;border-radius:0;padding:0;margin:0;outline:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;" />';
								//echo''.$v_page_arr[$col_nr][$line_nr]['x'] . '/'.count($mieszkania[$v_page_arr[$col_nr][$line_nr]['street']]);
							} else if ($v_page_arr[$col_nr][$line_nr]['nr'] == 'godzina') {
								echo "<b> godzina:</b> ";
								echo '<input type="text" size="8" value="'."".'" style="display:inline;width:60px;height:auto;border:1px solid #000;border-radius:0;padding:0;margin:0;outline:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;" />';
							} else {
								echo $v_page_arr[$col_nr][$line_nr]['street'];
								echo " (";
								echo $v_page_arr[$col_nr][$line_nr]['nr'];
								echo ") ";
								echo '<input type="checkbox" value="'."".'" style="display:inline;padding:0;margin:0;" />';
							}
						} else {
							echo "&nbsp;&nbsp;&nbsp;";
						}
					echo'</td>';
				}
				echo'</tr>';
			}
			echo'</tbody>';
			echo'</table>';			
		}

	}

	echo'<div style="page-break-before:always">';
		echo'<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=EDIT&ARG1_VAL=".$record_id.'">'."Cofnij ".'<img src=icon/back.gif border=0 alt=POWROT>'.'</a>';
	echo'</div>';
}


function USERS2_MARKETING_AKCJE_task_EDIT_wprowadz_zlecenie($record_id, &$record) {
	global $thiss;

	// USERS2_MARKETING_AKCJE_BUILDINGS
	{
		$thiss->DETECT_TABLE_COLUMN = 'USERS2_MARKETING_AKCJE_BUILDINGS_COLUMN';
		$thiss->DETECT_TABLE_NAME = 'USERS2_MARKETING_AKCJE_BUILDINGS';
		$thiss->DETECT_HIST_FUNCTION = 'USERS2_MARKETING_AKCJE_HIST';
		$thiss->DETECT_EDIT_FUNCTION = 'USERS2_MARKETING_AKCJE_EDIT';
	}

	echo'<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=EDIT&ARG1_VAL=".$record_id.'">'."Cofnij ".'<img src=icon/back.gif border=0 alt=POWROT>'.'</a>';

	echo'<h1>'."Wprowadz zlecenie do systemu".'</h1>';

	$buildings = USERS2_MARKETING_AKCJE::get_buildings($record_id, $record);

	echo'<p>'."Dotyczy akcji ".$record['ID']." z dnia ".$record['DATA'].'</p>';

	$post_saved = array();
	$post = array();
	foreach ($buildings as $k_street => $h) {
		$post[$k_street] = V::get($k_street, $h['ROZNIESIONO'], $_POST);
	}//end foreach
	if (1 == V::get('save', '', $_POST)) {
		if ("zakoncz" == V::get('sbmt', '', $_POST)) {
			$form_saved = false;
			$arr = array();
			$arr['A_RECORD_UPDATE_DATE'] = date('Y-m-d-H:i');
			$arr['A_RECORD_UPDATE_AUTHOR'] = $_SESSION['ADM_ACCOUNT'];
			$arr['W_DATA_WPROWADZONO'] = date('Y-m-d');

			$sql_arr = array();
			foreach ($arr as $k => $v) {
				$sql_arr []= "`".$k."`='".$v."'";
			}//end foreach
			$sql = "update `USERS2_MARKETING_AKCJE` set ".implode(",", $sql_arr)." where `ID`='".$record_id."' limit 1 ";
			DB::query($sql);
			$ret_affected = DB::affected_rows();
			if (!$ret_affected) {
				echo'<p style="color:red">'."Error: nie udalo sie zapisac rekordu".'</p>';
			} else {
				$form_saved = true;
			}

			// save HIST
			$sql_arr = array();
			foreach ($arr as $k => $v) {
				$sql_arr["`".$k."`"] = "'".$v."'";
			}//end foreach
			$sql_arr["`ID_USERS2`"] = "'".$record_id."'";
			$hist_table =  "USERS2_MARKETING_AKCJE_HIST";
			$sql = "insert into `".$hist_table."` (".implode(",", array_keys($sql_arr)).") values(".implode(",", $sql_arr)."); ";
			DB::query($sql);
			$ret_id = DB::insert_id();
			if (!$ret_id) {
				echo'<p style="color:red">'."Error: nie udalo sie zapisac danych do tabeli HIST".'</p>';
			}

			if ($form_saved) {
				echo'<p style="color:green">'."Dane zapisano pomyslnie".'</p>';
				return;
			}
		}
		else {
			foreach ($buildings as $k_street => $h) {
				if (empty($post[$k_street]) && $post[$k_street] !== '0') continue;
				if ($post[$k_street] == $h['ROZNIESIONO']) continue;
				$arr = array();
				$arr['A_RECORD_UPDATE_DATE'] = date('Y-m-d-H:i');
				$arr['A_RECORD_UPDATE_AUTHOR'] = $_SESSION['ADM_ACCOUNT'];
				$arr['ROZNIESIONO'] = $post[$k_street];
				$sql_arr = array();
				foreach ($arr as $k => $v) {
					$sql_arr []= "`".$k."`='".$v."'";
				}//end foreach
				$sql = "update `".$thiss->DETECT_TABLE_NAME."` set ".implode(",", $sql_arr)." where `ID`='".$h['ID']."' limit 1 ";
				DB::query($sql);
				$ret_affected = DB::affected_rows();
				$post_saved[$k_street] = $ret_affected;
				if (0) {
					// save HIST
					$sql_arr = array();
					foreach ($arr as $k => $v) {
						$sql_arr["`".$k."`"] = "'".$v."'";
					}//end foreach
					$sql_arr["`ID_USERS2`"] = "'".$record_id."'";
					$hist_table = $thiss->DETECT_TABLE_NAME . "_HIST";
					$sql = "insert into `".$hist_table."` (".implode(",", array_keys($sql_arr)).") values(".implode(",", $sql_arr)."); ";
					DB::query($sql);
					$ret_id = DB::insert_id();
					if (!$ret_id) {
						echo'<p style="color:red">'."Error: nie udalo sie zapisac danych do tabeli HIST".'</p>';
					}
				}
			}//end foreach

			$all_ok = true;
			if (!empty($post_saved)) {
				foreach ($post_saved as $k_street => $val) {
					if (!$val) $all_ok = false;
				}//end foreach
			}
			if ($all_ok) {
				echo'<p style="color:green">'."Dane zapisano pomyslnie".'</p>';
			}
		}
	}

	if (date('Y-m-d') <= $record['W_DATA']) {// TODO: do akcji - wprowadz date dostarczenia raportu
		echo'<p style="color:green">'."Raport dostarczono w terminie".'</p>';
	} else {
		echo'<p style="color:red">'."Raportu nie dostarczono w terminie!".'</p>';
	}

	if (!empty($buildings)) {
		echo'<form action="" method="POST">';
		echo'<input type="hidden" name="'."save".'" value="1" />';
		$out_buildings = array();
		$out_tabindex = 0;
		foreach ($buildings as $k_street => $h) {
			$out_item = $k_street.' ';
			$out_item .= '<input name="'.$k_street.'" type="text" size="4" value="'.$post[$k_street].'" tabindex="'.(++$out_tabindex).'" />';
			$out_item .= '/'.$h['DO_ROZNIESIENIA'];
			$out_buildings []= $out_item;
		}//end foreach

		// split to cols
		$building_cols = array();// [col_nr] => [line_nr] => {obj}
		$limit_cols = 4;// limit kolumn
		$limit_lines = ceil(count($buildings) / $limit_cols) + 1;
		$cur_col_ind = 0;
		$cur_line = 0;
		foreach ($out_buildings as $out_item) {
			$cur_line++;
			if ($cur_line >= $limit_lines) {
				$cur_line = 1;
				$cur_col_ind++;
			}
			$building_cols[ $cur_col_ind ][ $cur_line ] = $out_item;
		}//end foreach

		$max_col_count = 0;
		foreach ($building_cols as $k_col_nr => $v_col_arr) {
			$max_col_count = max($max_col_count, count($v_col_arr));
		}//end foreach

		echo'<table border="0" cellspacing="0" cellpadding="0">';
		for ($line_nr = 0; $line_nr <= $max_col_count; $line_nr++) {
			echo'<tr>';
			for ($col_nr = 0; $col_nr < $limit_cols; $col_nr++) {
				echo'<td style="width:25%;padding:0 10px;">';
					if (isset($building_cols[ $col_nr ][ $line_nr ])) {
						echo $building_cols[ $col_nr ][ $line_nr ];
					} else {
						echo "&nbsp;&nbsp;&nbsp;";
					}
				echo'</td>';
			}
			echo'</tr>';
		}
		echo'</tbody>';
		echo'</table>';			

		echo'<input type="submit" value="'."zapisz".'" />';
		echo'<p>';
			echo "Jesli wprowadzono wszystkie dane ";
			echo '<input type="submit" name="'."sbmt".'" value="'."zakoncz".'" />';
			echo " wprowadzanie raportu";
		echo'</p>';
		echo'</form>';
	}
}


function USERS2_MARKETING_AKCJE_task_EDIT_wprowadz_zlecenie_data($record_id, &$record) {
	global $thiss;

	echo'<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE".'">'."Cofnij ".'<img src=icon/back.gif border=0 alt=POWROT>'.'</a>';

	echo'<h1>'."Wprowadz datę dostarczenia zlecenia przez pracownika".'</h1>';

	$form_saved = false;
	$post = array();
	$post['W_DATA_DOSTARCZONO'] = V::get('W_DATA_DOSTARCZONO', date('Y-m-d'), $_POST);
	if (1 == V::get('save', '', $_POST)) {
		// verify data
		if (!empty($post['W_DATA_DOSTARCZONO'])) {
			$arr = array();
			$arr['A_RECORD_UPDATE_DATE'] = date('Y-m-d-H:i');
			$arr['A_RECORD_UPDATE_AUTHOR'] = $_SESSION['ADM_ACCOUNT'];
			$arr['W_DATA_DOSTARCZONO'] = $post['W_DATA_DOSTARCZONO'];

			$sql_arr = array();
			foreach ($arr as $k => $v) {
				$sql_arr []= "`".$k."`='".$v."'";
			}//end foreach
			$sql = "update `".$thiss->DETECT_TABLE_NAME."` set ".implode(",", $sql_arr)." where `ID`='".$record_id."' limit 1 ";
			DB::query($sql);
			$ret_affected = DB::affected_rows();
			if (!$ret_affected) {
				echo'<p style="color:red">'."Error: nie udalo sie zapisac rekordu".'</p>';
			} else {
				$form_saved = true;
			}

			// save HIST
			$sql_arr = array();
			foreach ($arr as $k => $v) {
				$sql_arr["`".$k."`"] = "'".$v."'";
			}//end foreach
			$sql_arr["`ID_USERS2`"] = "'".$record_id."'";
			$hist_table = $thiss->DETECT_TABLE_NAME . "_HIST";
			$sql = "insert into `".$hist_table."` (".implode(",", array_keys($sql_arr)).") values(".implode(",", $sql_arr)."); ";
			DB::query($sql);
			$ret_id = DB::insert_id();
			if (!$ret_id) {
				echo'<p style="color:red">'."Error: nie udalo sie zapisac danych do tabeli HIST".'</p>';
			}

			if ($form_saved) {
				echo'<p style="color:green">'."Dane zapisano pomyslnie".'</p>';
				return;
			}
		}
	}
	echo'<form action="" method="POST">';
		echo'<input type="hidden" name="'."save".'" value="'."1".'" />';
		echo "Data: ";
		echo '<input name="'."W_DATA_DOSTARCZONO".'" type="text" size="10" value="'.$post['W_DATA_DOSTARCZONO'].'" />';
	echo'<input type="submit" value="'."zapisz".'" />';
	echo'</form>';
}


function USERS2_MARKETING_AKCJE_task_EDIT_zlecenie_kontroli($record_id, &$record) {
	global $thiss;

	{
		$thiss->DETECT_TABLE_COLUMN = 'USERS2_MARKETING_AKCJE_BUILDINGS_COLUMN';
		$thiss->DETECT_TABLE_NAME = 'USERS2_MARKETING_AKCJE_BUILDINGS';
		$thiss->DETECT_HIST_FUNCTION = 'USERS2_MARKETING_AKCJE_HIST';
		$thiss->DETECT_EDIT_FUNCTION = 'USERS2_MARKETING_AKCJE_EDIT';
	}

	echo'<style type="text/css">'."
body{font-size:small;padding:0 6px;}
td,table,tr{font-size:xx-small;line-height:1.4em;}
input{margin:0;padding:0;}
	".'</style>';

	$buildings = USERS2_MARKETING_AKCJE::get_buildings($record_id, $record);

	$post_saved = array();
	$post = array();
	foreach ($buildings as $k_street => $h) {
		$post[$k_street] = V::get($k_street, $h['ROZNIESIONO'], $_POST);
	}//end foreach
	if (1 == V::get('print', '', $_POST)) {

	}

	if (!empty($buildings)) {
		echo '<table border="1" cellspacing="0" cellpadding="0" width="100%">';
		echo "\n".'<tr>'.'<td colspan="14">'."ZLECENIE KONTROLI DYSTRYBUCJI (" . $record['ID'] . ")".'</td></tr>';
		echo '<tr><td rowspan="2" width="5">'."lp".'</font></td>';
			echo'<td rowspan="2">'."Data".'</td>';
			echo'<td rowspan="2">'."Godzina".'</td>';
			echo'<td rowspan="2">'."Ulica/Budynek".'</td>';
			echo'<td rowspan="2">'."Klatka".'</td>';
			echo'<td colspan="2">'."Plakat klatka".'</td>';
			echo'<td colspan="2">'."Ulotka gumka klamka".'</td>';
			echo'<td colspan="2">'."Ulotka skrzynka".'</td>';
			echo'<td colspan="2">'."Materiał ostatnie pietro".'</td>';
			echo'<td rowspan="2" width="90">'."Inne uwagi".'</td>';
		echo'</tr>';
		echo '<tr>';
			echo'<td>'."JEST".'</td>';
			echo'<td>'."BRAK".'</td>';
			echo'<td>'."JEST".'</td>';
			echo'<td>'."BRAK".'</td>';
			echo'<td>'."JEST".'</td>';
			echo'<td>'."BRAK".'</td>';
			echo'<td>'."JEST".'</td>';
			echo'<td>'."BRAK".'</td>';
			for ($i = 1; $i <= 30; $i++) {
				echo '<tr height="5">';
					echo'<td width="10">'.$i.'</td>';
					echo'<td>'.". . ".'</td>';
					echo'<td>'.". . ".'</td>';
					echo'<td>'.". . ".'</td>';
					echo'<td>'.". . ".'</td>';
					echo'<td>'.". . ".'</td>';
					echo'<td>'.". . ".'</td>';
					echo'<td>'.". . ".'</td>';
					echo'<td>'.". . ".'</td>';
					echo'<td>'.". . ".'</td>';
					echo'<td>'.". . ".'</td>';
					echo'<td>'.". . ".'</td>';
					echo'<td>'.". . ".'</td>';
					echo'<td>'.". . ".'</td>';
				echo'</tr>'."\n";
			}
		echo '<tr>'.'<td colspan="2">'."Imię i nazwisko sprawdzającego:".'</td>';
			echo'<td colspan="4">'.$record['K_USER'].'</td>';
			echo'<td colspan="4">'." Data procesu dystrybucji ".'</td>';//Data i numer procesu dystrybucji
			echo'<td colspan="5">'.$record['W_DATA'] . " (" . $record['ID'] . ")" . '</td>';
		echo'</tr>';
		echo '<tr><td colspan="6" rowspan="2">'."Obszar dla kontroli: ";
			echo str_replace(',', ', ', $record['FILTR_S_ADDRESS_STREET']);
		echo '</td>';
		echo'<td colspan="4">'."Okres badania:".'</td>';
		echo'<td colspan="5">'."wyłącznie w dniu: ".$record['K_DATA']." , <br> pomiędzy godzinami od ... do ...".'</td>';
		echo'</tr>';
		echo'<tr>';
			echo'<td colspan="4">'."Termin i miejsce dostarczenia raportu kontroli".'</td>';
			echo'<td colspan="5">'."raport należy dostarczyć w ........ do godziny ..... w miejsce:".'</td>';
		echo'</tr>';
		echo'<tr>';
			echo'<td colspan="14">'."Regulamin wypełnienia raportu: 1. Zleceniobiorca zobowiązuje się sprawdzić czy materiały reklamowe zostały rozmieszczone na wyznaczonym obszarze działania.";
			echo'<br>'."2.Wyniki kontroli rozmieszczenia materiałów reklamowych należy zapisywać w trakcie trwania kontroli w otrzymanym Raporcie kontroli ulotek. Musi on zawierać rzetelnie i czytelnie wypełnione pola.";
			echo'<br />'."Sposób wypełnienia niniejszego raportu wygląda następująco: W kolumnie .Data. oraz .Godzina. należy wpisać każdorazowo datę oraz godzinę rozpoczęcia czynności na danym budynku, w kolumnie .Ulica budynek. wpisać stosownany skrót np. .CH7. to Całubińskiego 7 w kolumnie .klatka. wpisać A,B lub C(i tak dalej), w pozostałych kolumnach umiescić X w stosownym miejscu w zależności czy był materiał reklamowy, czy nie; w .Inne/Uwagi. wpisywać np. czy były problemy z wejściem do budynku, jeśli tak, to kto nie chciał wpuścicić.";
			echo'<br />'."3. Zleceniobiorca zobowiązuje się przeprowadzić kontrolę w wyżej określonym przedziale czasu  .";
			echo'<br />'."4. Raport kontroli ulotek należy dostarczyć zgodnie z zapisami w tabeli względnie czytelny skan na adres e-mail: marketing@biall.net.pl , z zaznaczeniem w temacie Daty i numeru procesu dystrybucji : $DATA_PROCESU_DYSTRYBUCJI / $NUMER_PROCESU_DYSTRYBUCJI .";
			echo'<br />'."5. Raporty kontroli ulotek winny być wypełnione wg schematu w raporcie (oznaczonego w pkt. x), czyli np. w polu .godzina/data. należy umieścić datę i godzinę rozpoczęcia kontroli rozmieszczenia materiałów na danym budynku. Niewypełnienie tych pól lub/i raportu jest równoznaczne z niewykonaniem zlecenia. Brane będą wyłącznie pod uwagę fragmenty raportu wypełnione w pełni, rzetelnie i czytelnie. Wszystkie inne pola (rzędy arkusza) wypełnione częściowo lub w ogóle, będą traktowane jakoby w danym adresie dystrybucja nie miała miejsca. Od momentu oddania raportu  kontroli ulotek zakazane jest uzupełnianie raportu przez którąkolwiek ze stron. Wpisy w danym rzędzie w raporcie winny być wypełnione jednym i tym samym długopisem.";
			echo'<br />'."6. Zlecenie realizowane jest tylko wyznaczonym obszarze (Obszar dla kontroli).";
			echo'<br />'."7. Nie wywiązanie się z wyżej wymienionych zadań równoznaczne jest z nie wykonaniem powierzonej pracy, co się wiąże brakiem wynagrodzenia a nawet pokryciem strat firmy wynikających z tego tytułu.".'</td>';
		echo'</tr>';
		echo '</table>';
	}
	
	echo '<p style="page-break-before:always">'."\n";
	echo'<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=EDIT&ARG1_VAL=".$record_id.'">'."Cofnij ".'<img src="icon/back.gif" border="0" alt="POWROT"></a>';
}


function USERS2_MARKETING_AKCJE_task_EDIT_wprowadz_zlecenie_kontroli_data($record_id, &$record) {
	global $thiss;

	echo'<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=EDIT&ARG1_VAL=".$record_id.'">'."Cofnij ".'<img src="icon/back.gif" border="0" alt="POWROT"></a>';

	echo'<h1>'."Wprowadz datę dostarczenia kontroli dystrybucji przez pracownika".'</h1>';

	$form_saved = false;
	$post = array();
	$post['K_DATA_DOSTARCZONO'] = V::get('K_DATA_DOSTARCZONO', date('Y-m-d'), $_POST);
	if (1 == V::get('save', '', $_POST)) {
		// verify data
		if (!empty($post['K_DATA_DOSTARCZONO'])) {
			$arr = array();
			$arr['A_RECORD_UPDATE_DATE'] = date('Y-m-d-H:i');
			$arr['A_RECORD_UPDATE_AUTHOR'] = $_SESSION['ADM_ACCOUNT'];
			$arr['K_DATA_DOSTARCZONO'] = $post['K_DATA_DOSTARCZONO'];

			$sql_arr = array();
			foreach ($arr as $k => $v) {
				$sql_arr []= "`".$k."`='".$v."'";
			}//end foreach
			$sql = "update `".$thiss->DETECT_TABLE_NAME."` set ".implode(",", $sql_arr)." where `ID`='".$record_id."' limit 1 ";
			DB::query($sql);
			$ret_affected = DB::affected_rows();
			if (!$ret_affected) {
				echo'<p style="color:red">'."Error: nie udalo sie zapisac rekordu".'</p>';
			} else {
				$form_saved = true;
			}

			// save HIST
			$sql_arr = array();
			foreach ($arr as $k => $v) {
				$sql_arr["`".$k."`"] = "'".$v."'";
			}//end foreach
			$sql_arr["`ID_USERS2`"] = "'".$record_id."'";
			$hist_table = $thiss->DETECT_TABLE_NAME . "_HIST";
			$sql = "insert into `".$hist_table."` (".implode(",", array_keys($sql_arr)).") values(".implode(",", $sql_arr)."); ";
			DB::query($sql);
			$ret_id = DB::insert_id();
			if (!$ret_id) {
				echo'<p style="color:red">'."Error: nie udalo sie zapisac danych do tabeli HIST".'</p>';
			}

			if ($form_saved) {
				echo'<p style="color:green">'."Dane zapisano pomyslnie".'</p>';
				return;
			}
		}
	}
	echo'<form action="" method="POST">';
		echo'<input type="hidden" name="'."save".'" value="'."1".'" />';
		echo "Data: ";
		echo '<input name="'."K_DATA_DOSTARCZONO".'" type="text" size="10" value="'.$post['K_DATA_DOSTARCZONO'].'" />';
	echo'<input type="submit" value="'."zapisz".'" />';
	echo'</form>';
}


function USERS2_MARKETING_AKCJE_task_EDIT_wprowadz_zlecenie_kontroli($record_id, &$record) {
	global $thiss;

	// USERS2_MARKETING_AKCJE_BUILDINGS
	{
		$thiss->DETECT_TABLE_COLUMN = 'USERS2_MARKETING_AKCJE_BUILDINGS_COLUMN';
		$thiss->DETECT_TABLE_NAME = 'USERS2_MARKETING_AKCJE_BUILDINGS';
		$thiss->DETECT_HIST_FUNCTION = 'USERS2_MARKETING_AKCJE_HIST';
		$thiss->DETECT_EDIT_FUNCTION = 'USERS2_MARKETING_AKCJE_EDIT';
	}

	echo'<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=EDIT&ARG1_VAL=".$record_id.'">'."Cofnij ".'<img src=icon/back.gif border=0 alt=POWROT>'.'</a>';

	echo'<h1>'."Wprowadz zlecenie do systemu".'</h1>';

	$buildings = USERS2_MARKETING_AKCJE::get_buildings($record_id, $record);

	echo'<p>'."Dotyczy akcji ".$record['ID']." z dnia ".$record['DATA'].'</p>';

	$post_saved = array();
	$post = array();
	foreach ($buildings as $k_street => $h) {
		$post[$k_street] = V::get($k_street, $h['KONTROLA'], $_POST);
		$post['UWAGI_'.$k_street] = V::get('UWAGI_'.$k_street, $h['KONTROLA_UWAGI'], $_POST);
	}//end foreach
	if (1 == V::get('save', '', $_POST)) {
		if ("zakoncz" == V::get('sbmt', '', $_POST)) {
			$form_saved = false;
			$arr = array();
			$arr['A_RECORD_UPDATE_DATE'] = date('Y-m-d-H:i');
			$arr['A_RECORD_UPDATE_AUTHOR'] = $_SESSION['ADM_ACCOUNT'];
			$arr['K_DATA_WPROWADZONO'] = date('Y-m-d');

			$sql_arr = array();
			foreach ($arr as $k => $v) {
				$sql_arr []= "`".$k."`='".$v."'";
			}//end foreach
			$sql = "update `USERS2_MARKETING_AKCJE` set ".implode(",", $sql_arr)." where `ID`='".$record_id."' limit 1 ";
			DB::query($sql);
			$ret_affected = DB::affected_rows();
			if (!$ret_affected) {
				echo'<p style="color:red">'."Error: nie udalo sie zapisac rekordu".'</p>';
			} else {
				$form_saved = true;
			}

			// save HIST
			$sql_arr = array();
			foreach ($arr as $k => $v) {
				$sql_arr["`".$k."`"] = "'".$v."'";
			}//end foreach
			$sql_arr["`ID_USERS2`"] = "'".$record_id."'";
			$hist_table =  "USERS2_MARKETING_AKCJE_HIST";
			$sql = "insert into `".$hist_table."` (".implode(",", array_keys($sql_arr)).") values(".implode(",", $sql_arr)."); ";
			DB::query($sql);
			$ret_id = DB::insert_id();
			if (!$ret_id) {
				echo'<p style="color:red">'."Error: nie udalo sie zapisac danych do tabeli HIST".'</p>';
			}

			if ($form_saved) {
				echo'<p style="color:green">'."Dane zapisano pomyslnie".'</p>';
				return;
			}
		}
		else {
			foreach ($buildings as $k_street => $h) {
				if (!in_array($post[$k_street], array('TAK','NIE'))) continue;
				$arr = array();
				$arr['A_RECORD_UPDATE_DATE'] = date('Y-m-d-H:i');
				$arr['A_RECORD_UPDATE_AUTHOR'] = $_SESSION['ADM_ACCOUNT'];
				$arr['KONTROLA'] = $post[$k_street];
				$arr['KONTROLA_UWAGI'] = $post['UWAGI_'.$k_street];
				$sql_arr = array();
				foreach ($arr as $k => $v) {
					$sql_arr []= "`".$k."`='".$v."'";
				}//end foreach
				$sql = "update `".$thiss->DETECT_TABLE_NAME."` set ".implode(",", $sql_arr)." where `ID`='".$h['ID']."' limit 1 ";
				DB::query($sql);
				$ret_affected = DB::affected_rows();
				$post_saved[$k_street] = $ret_affected;
				if (0) {
					// save HIST
					$sql_arr = array();
					foreach ($arr as $k => $v) {
						$sql_arr["`".$k."`"] = "'".$v."'";
					}//end foreach
					$sql_arr["`ID_USERS2`"] = "'".$record_id."'";
					$hist_table = $thiss->DETECT_TABLE_NAME . "_HIST";
					$sql = "insert into `".$hist_table."` (".implode(",", array_keys($sql_arr)).") values(".implode(",", $sql_arr)."); ";
					DB::query($sql);
					$ret_id = DB::insert_id();
					if (!$ret_id) {
						echo'<p style="color:red">'."Error: nie udalo sie zapisac danych do tabeli HIST".'</p>';
					}
				}
			}//end foreach

			$all_ok = true;
			if (!empty($post_saved)) {
				foreach ($post_saved as $k_street => $val) {
					if (!$val) $all_ok = false;
				}//end foreach
			}
			if ($all_ok) {
				echo'<p style="color:green">'."Dane zapisano pomyslnie".'</p>';
			}
		}
	}

	if (!empty($buildings)) {
		echo'<form action="" method="POST">';
		echo'<input type="hidden" name="'."save".'" value="1" />';
		$out_buildings = array();
		$out_tabindex = 0;
		foreach ($buildings as $k_street => $h) {
			$out_item = $k_street.' ';
			//$out_item .= '/'.$h['DO_ROZNIESIENIA'];
			$checked = ($post[$k_street] == 'TAK')? ' checked="checked"' : '';
			$out_item .= '<input name="'.$k_street.'" type="radio" value="'."TAK".'" tabindex="'.(++$out_tabindex).'" '.$checked.' />'."<code>TAK</code>";
			$checked = ($post[$k_street] == 'NIE')? ' checked="checked"' : '';
			$out_item .= '<input name="'.$k_street.'" type="radio" value="'."NIE".'" tabindex="'.(++$out_tabindex).'" '.$checked.' />'."<code>NIE</code>";
			$f_uwagi = 'UWAGI_'.$k_street;
			$out_item .= ' <em style="font-size:small;">'."Uwagi:".'</em>';
			$out_item .= '<input name="'.$f_uwagi.'" type="text" value="'.$post[$f_uwagi].'" tabindex="'.(++$out_tabindex).'" />';
			$out_buildings []= $out_item;
		}//end foreach

		// split to cols
		$building_cols = array();// [col_nr] => [line_nr] => {obj}
		$limit_cols = 2;// limit kolumn
		$limit_lines = ceil(count($buildings) / $limit_cols) + 1;
		$cur_col_ind = 0;
		$cur_line = 0;
		foreach ($out_buildings as $out_item) {
			$cur_line++;
			if ($cur_line >= $limit_lines) {
				$cur_line = 1;
				$cur_col_ind++;
			}
			$building_cols[ $cur_col_ind ][ $cur_line ] = $out_item;
		}//end foreach

		$max_col_count = 0;
		foreach ($building_cols as $k_col_nr => $v_col_arr) {
			$max_col_count = max($max_col_count, count($v_col_arr));
		}//end foreach

		echo'<table border="0" cellspacing="0" cellpadding="0">';
		for ($line_nr = 0; $line_nr <= $max_col_count; $line_nr++) {
			echo'<tr>';
			for ($col_nr = 0; $col_nr < $limit_cols; $col_nr++) {
				echo'<td style="width:25%;padding:0 10px;">';
					if (isset($building_cols[ $col_nr ][ $line_nr ])) {
						echo $building_cols[ $col_nr ][ $line_nr ];
					} else {
						echo "&nbsp;&nbsp;&nbsp;";
					}
				echo'</td>';
			}
			echo'</tr>';
		}
		echo'</tbody>';
		echo'</table>';			

		echo'<input type="submit" value="'."zapisz".'" />';
		echo'<p>';
			echo "Jesli wprowadzono wszystkie dane ";
			echo '<input type="submit" name="'."sbmt".'" value="'."zakoncz".'" />';
			echo " wprowadzanie raportu";
		echo'</p>';
		echo'</form>';
	}
}


function USERS2_MARKETING_AKCJE_list() {
global $thiss, $GETZAPSQL,$SQL_USER,$USERS_FILTER_STATUS,$SQL_WIEV,$USERS_COLUMN,$USERS_COLUMN_DESC,$USERS_HIDECOLUMN;

SEF("MENU");
MENU();

if (!$_SESSION[$thiss->DETECT_TABLE_COLUMN]['SQL_WIEV_CURR_SQL']) SQL_WIEV();

GETZAPSQL();

$zapSQL = "SELECT ".$GETZAPSQL['WHAT_SQL']." from ".$GETZAPSQL['FROM_SQL']."  where ".$GETZAPSQL['WHERE']."  ;";
if ($_SESSION['DEBUG']) {
	echo "zapSQL is $zapSQL<hr>".$_SESSION[$thiss->DETECT_TABLE_COLUMN]['FINDSQL']."<hr>";
	echo "<hr>GETZAPSQL[SQL] $GETZAPSQL[SQL]<hr>";
} //EOF GETZAPSQL TESTS

$result = DB::query($zapSQL) or die("Blad $zapSQL zapytania2!");
$_SESSION['MYSQL_NUM_ROWS_TOTAL']['USERS'] = DB::num_rows($result); //TO_REMOVE_VARIABLE TODO
$_SESSION[$thiss->DETECT_TABLE_COLUMN]['MYSQL_NUM_ROWS_TOTAL'] = DB::num_rows($result);
$zapSQL = "SELECT ".$GETZAPSQL['WHAT_SQL']." from ".$GETZAPSQL['FROM_SQL']."  where ".$GETZAPSQL['WHERE2']."  ;";
if ($_SESSION['DEBUG']) echo "<hr>CORRECT_SQL_ZAPYTANIE **/*/* $thiss->DETECT_TABLE_COLUMN $zapSQL **/*";
$result = DB::query($zapSQL) or die("Blad zapytania2 $zapSQL!");
$num_rows = DB::num_rows($result);
$_SESSION['MYSQL_NUM_ROWS'] = $num_rows;

NAVIGATOR();
//if(strstr($_SESSION[$thiss->DETECT_TABLE_COLUMN]['FUNCPERMEDIT']['P_NEW_DEAL'],'RW')) {
echo "&nbsp;&nbsp; | &nbsp;&nbsp;";
CREATE_MENUFUNC_INIT_2('USERS2_MARKETING_AKCJE','ADD','','<font size=-1>( DODAJ NOWY<img src=icon/new.gif border=0 alt="DODAJ NOWY"> )</font>') ;
//}
echo "&nbsp;&nbsp; | &nbsp;&nbsp;";
CREATE_MENUFUNC_INIT_2('USERS2_MARKETING_AKCJE','PODSUMOWANIE','','<font size=-1> PODSUMOWANIE </font>') ;

echo'<table width="100%" border="1" cellspacing="0" cellpadding="0" class="tbl-view">';
echo'<thead>';
	echo "<tr><TD><font size=-1>";
		CREATE_MENU_NOTD_INIT_3('FILTER_SEARCH','MENU_FIND','ENABLE','<img src=icon/search.gif alt=SZUKAJ border=0>');
	echo "</TD>";
	foreach ($GETZAPSQL['ID'] as $value) {
		if (true) {
			echo "<td><font size='-2'>";
			$ALT = $_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG'][ $GETZAPSQL['WHAT_DESC'][$value] ];

			if ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['SORTED'][ $GETZAPSQL['WHAT_DESC'][$value] ] == 'PRI')  $border=1; else $border=0;
			CREATE_MENU_NOTD_INIT_2('USERS_SORTER', 'USERS_SORTER', 'USERS_SORTER1', $GETZAPSQL['WHAT_DESC'][$value], '<img src=icon/sortred.gif border='.$border.' alt=SORTUJ><img src=icon/sortred.gif border='.$border.' alt=SORTUJ>');

			if (($_SESSION[$thiss->DETECT_TABLE_COLUMN]['USERS_SORTER_SQL']) || ($_SESSION['USERS_SORTER_SQL'])) { //TODO remove second extra cond.
				if ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['SORTED'][$GETZAPSQL['WHAT_DESC'][$value]]=='SEC')  $border=1; else $border=0; // echo "<font color='green'><img src=icon/sort.gif width=10 border=0 alt=sortuj></font>";
				CREATE_MENU_NOTD_INIT_2('USERS_SORTER','USERS_SORTER','USERS_SORTER2',$GETZAPSQL['WHAT_DESC'][$value],'<img src=icon/sort.gif border='.$border.' alt=sortuj>') ; 
			}
			//CREATE_MENU_NOTD_INIT_3('USERS_COLUMN',$_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_KEY'][$GETZAPSQL['WHAT_DESC'][$value]],'HIDE','<img src=icon/shutdown.gif border=0 alt="WYLACZ_KOLUMNE '.$ALT.'">') ;

			echo "<br><b>" .str_replace('_',' ',$GETZAPSQL['WHAT_DESC'][$value]) . "</font></b></td>";    
			//echo "<br><b>" . $GETZAPSQL[WHAT_DESC][$value] . "</font></b></td>"; 
		}
	}
	echo "</tr> \n";

	//SECOND_ROW
	if ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['MENU_FIND'] == 'ENABLE') {
		echo '<tr>';
			echo '<td>';
				echo '<font size="-2">';
				echo '<form action="" method="POST" name="FILTER_SEARCH">';
				CREATE_MENU_NOTD_INIT_3('FILTER_SEARCH', 'MENU_FIND', '', 'X');
				echo '<input type="button" onclick="ClearAllFind()" value="Czyść" />';
				echo '<input type="hidden" name="FUNCTION_INIT" value="FILTER_SEARCH" />';
				echo '<input type="submit" value="OK" />';
			echo '</td>';
			foreach ($GETZAPSQL['ID'] as $value) {
				if (true) {
					echo '<td>';
						echo '<font size="-2">';
						GETFORMITEM($_SESSION[$thiss->DETECT_TABLE_COLUMN]['FIND'][$GETZAPSQL['WHAT_DESC'][$value]], $_SESSION[$thiss->DETECT_TABLE_COLUMN]['TYPE'][$GETZAPSQL['WHAT_DESC'][$value]], $GETZAPSQL['WHAT_DESC'][$value]);
						echo '</font>';
					echo '</td>';
				} //EOF if (!$thiss->DETECT_TABLE_COLUMN[HIDE][$value]==HIDE)
			} //EOF foreach ($thiss->DETECT_TABLE_COLUMN[ID] as $value)
		echo '</form>';
		echo '</tr>' . "\n";
	} //EOF  if ($_SESSION[$thiss->DETECT_TABLE_COLUMN][MENU_FIND]==ENABLE)
	echo'</thead>';
	if ( $num_rows == 0 ) {
		echo "</tr></table>Brak Danych";
	} else {
		$t = 0;
		echo'<tbody>';
    while ($h = DB::fetch_assoc($result)) {
			$row_id = $h['ID'];
			echo '<TR class="row-' . ($t = 1 - $t) . '">';
			echo '<TD align="center">';
				echo'<a href="'."./index.php?FUNCTION_INIT=COPY_RECORD&amp;ARG1=NR_POZ&amp;ARG1_VAL=".$row_id.'" onclick="'."return confirm('Czy na pewno chcesz utworzyć nowy rekord na podstawie danych z rekordu ID = ".$row_id."?');".'">'."CP".'</a>';
				echo "&nbsp;&nbsp;";

				echo'<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=HIST&ARG1_VAL=".$row_id.'"><img src="icon/history.gif" alt="HISTORIA" border="0" width="18"></a>';
				echo'<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=EDIT&ARG1_VAL=".$row_id.'"><img src="icon/edit.gif" alt="EDYCJA" border="0" width="20"></a>';
			echo'</td>';

			foreach ($GETZAPSQL['WHAT_DESC'] as $field_name) {
				echo '<td>';
				echo USERS2_MARKETING_AKCJE::print_akcje_table_item($field_name, $h);
				echo '</td>';
			}
			echo "</TR>\n";
		}
		echo'</tbody>';
	}
	echo "</table>";
}


// hist view function
function USERS2_MARKETING_AKCJE_task_HIST() {
	//WIEVTABLE_HIST();
	global $thiss;
	global $MENU_INIT,$ARG1,$ARG1_VAL,$SQL_USER,$SQL_DATABASE,$INTERFACE_ADDR,$SQL_USER_PASS,$USERS_FILTER_STATUS,$SQL_WIEV,$USERS_COLUMN,$USERS_COLUMN_DESC,$USERS_HIDECOLUMN;

	{
		$thiss->DETECT_TABLE_COLUMN = 'USERS2_MARKETING_AKCJE_HIST_COLUMN';
		$thiss->DETECT_TABLE_NAME = 'USERS2_MARKETING_AKCJE_HIST';
		$thiss->DETECT_HIST_FUNCTION = 'USERS2_MARKETING_AKCJE_HIST';
		$thiss->DETECT_EDIT_FUNCTION = 'USERS2_MARKETING_AKCJE_EDIT';
	}

	if (($MENU_INIT == $thiss->DETECT_HIST_FUNCTION) && ($ARG1 = 'HISTORY')) {
		$_SESSION[$thiss->DETECT_TABLE_COLUMN]['WIEVID'] = "$ARG1_VAL";
		if ($_SESSION['DEBUG']) echo "VALUALIZED at $thiss->DETECT_TABLE_COLUMN func _SESSION[$thiss->DETECT_TABLE_COLUMN][WIEVID] = $ARG1_VAL";
	}

	SEF("MENU");
	MENU();
	NAVIGATOR();
	TOOLBAR_DETECT();

	$zapSQL = "SELECT * from `".$thiss->DETECT_TABLE_NAME."` where `ID_USERS2`='".$_SESSION[$thiss->DETECT_TABLE_COLUMN]['WIEVID']."' ;";
	$result = DB::query($zapSQL) or die("Blad zapytania2!L");
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['MYSQL_NUM_ROWS_TOTAL'] = DB::num_rows($result);
	$zapSQL = "SELECT * from `".$thiss->DETECT_TABLE_NAME."`  where `ID_USERS2`='".$_SESSION[$thiss->DETECT_TABLE_COLUMN]['WIEVID']."' ".$_SESSION[$thiss->DETECT_TABLE_COLUMN]['USERS_SORTER_SQL']." ". $_SESSION[$thiss->DETECT_TABLE_COLUMN]['SQL_WIEV_CURR_SQL']." ;";

	$result = DB::query($zapSQL) or die("Blad zapytania2!");
	$num_rows = DB::num_rows($result);
	$_SESSION[$thiss->DETECT_TABLE_COLUMN]['MYSQL_NUM_ROWS'] = $num_rows;
	echo "<BR>LICZBA_WIERSZY $num_rows<BR>";

	echo "\n<table width='100%' border='1' cellspacing='0' cellpadding='0'>";
	echo "<TD><font size=-2>";
	echo "</TD>";
	foreach ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['ID'] as $value) {
		if (!$_SESSION[$thiss->DETECT_TABLE_COLUMN]['HIDE'][$value] == 'HIDE') {
			echo "<td><font size='-2'>" ;
			if ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['SORTED'][ $_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'][$value] ] == 'PRI') $border=1; else $border=0;
			CREATE_MENU_NOTD_INIT_2('USERS_SORTER','USERS_SORTER','USERS_SORTER1',$_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'][$value],'<img src=icon/sortred.gif border='.$border.' alt=SORTUJ><img src=icon/sortred.gif border='.$border.' alt=SORTUJ>') ; 
			if ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['USERS_SORTER_SQL']) { 
				if ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['SORTED'][ $_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'][$value] ] == 'SEC') $border=1; else $border=0;
				CREATE_MENU_NOTD_INIT_2('USERS_SORTER','USERS_SORTER','USERS_SORTER2',$_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'][$value],'<img src=icon/sort.gif border='.$border.' alt=sortuj>') ; 
			}
			CREATE_MENU_NOTD_INIT_3('USERS_COLUMN',$value,'HIDE','<img src=icon/shutdown.gif border=0 alt=sortuj>');
			echo "<br><b>" . $_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'][$value] . "</font></b></td>";
		}
	}
	if( $num_rows == 0 ) {
		echo "</tr></table>Brak Danych" ;
		return;
	}

	while ($h = DB::fetch_row($result)) {
		echo "<TR><TD><font size=-2>";
		echo "</TD>";
		foreach ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['ID'] as $value) {
			if (!$_SESSION[$thiss->DETECT_TABLE_COLUMN]['HIDE'][$value] == 'HIDE') {
				echo "<TD";
					USERS_COLUMN_COLOR($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'][$value],$h[$value],'bgcolor');
				echo ">";
				if (!( "$h[$value]" == 'N/S;')) echo "$h[$value]";
				echo "</td>";
			}
		}
		echo "</tr>";
	}
	echo "</table>";
	$result = DB::query($zapSQL) or die("Blad zapytania2!");
	echo '<table border=1 cellspacing=0 cellpadding=0>';
	while ($h = DB::fetch_row($result)) {
		echo "<tr><TD>";
		foreach ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['ID'] as $value) {
			if ((!$_SESSION[$thiss->DETECT_TABLE_COLUMN]['HIDE'][$value]=='HIDE') && (!($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'][$value]=='ID')) && (!($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'][$value]=='ID_USERS2')) ) {
				echo "<font ";
				USERS_COLUMN_COLOR($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'][$value],$h[$value],'color');
				echo ">";
				if((!( "$h[$value]" == 'N/S;')) && (!($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'][$value]=='P_SERVICE_QUOTA_PROFILE'))) {
					echo  $_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'][$value] . "</font>=" . "$h[$value]" . "<BR>"; 
				} else {
					echo'</font>';
				}
			}
		}
		echo "</td></tr>";
	}
	echo "</table>";
}


// typespecial
function USERS2_MARKETING_AKCJE_typespecial_W_USER($action, $selected_value) {
	FORM_typespecial_USER_SELECT('W_USER', $selected_value);
}
function USERS2_MARKETING_AKCJE_typespecial_K_USER($action, $selected_value) {
	FORM_typespecial_USER_SELECT('K_USER', $selected_value);
}
function FORM_typespecial_USER_SELECT($field_name, $selected_value) {
	$res = DB::query("select * from `ADMIN_USERS` where `A_STATUS`='NORMAL' and `ADM_TECH_WORKER`!='NO' and `ADM_COMPANY` like '".$_SESSION['ADM_COMPANY']."' ");
	echo'<select name="'.$field_name.'"><option value="">'."&nbsp;".'</option>';
	while ($r = DB::fetch($res)) {
		echo'<option value="'.$r->ADM_ACCOUNT.'" ';
		if ($r->ADM_ACCOUNT == $selected_value) {
			echo'selected="selected"';
		}
		echo'>'.$r->ADM_NAME.'('.$r->ADM_ACCOUNT.')</option>';
	}
	echo'</select>';
}
function USERS2_MARKETING_AKCJE_typespecial_ID_PROJECT($action, $selected_value) {
	$res = DB::query("select * from IN7_MK_BAZA_DYSTRYBUCJI  where A_STATUS='NORMAL' or A_STATUS='OFF_SOFT' or A_STATUS='OFF_HARD'  order by `ID` ");
	echo '<select name="ID_PROJECT">';
		echo '<option value=""> </option>';
		while ($r = DB::fetch($res)) {
			echo "\n".'<option value="' . $r->ID . '"';
				if ($r->ID == $selected_value)	echo ' selected="selected"';
			echo '>' . $r->ID . "=" . $r->M_DIST_DESC . "(". $r->M_DISTRIBUTOR ." ".$r->TV_NAZWA_PROGRAMU. ")".'</option>';
		}
	echo '</select>';
}
function USERS2_MARKETING_AKCJE_typespecial_FILTR_M_REWIR($action, $value) {
	FORM_typespecial_USER_TEXTAREA_readonly('FILTR_M_REWIR', $value);
}
function USERS2_MARKETING_AKCJE_typespecial_FILTR_S_ADDRESS_STREET($action, $value) {
	FORM_typespecial_USER_TEXTAREA_readonly('FILTR_S_ADDRESS_STREET', $value);
}
function FORM_typespecial_USER_TEXTAREA_readonly($field_name, $value) {
	echo'<textarea name="'.$field_name.'" id="'.$field_name.'" rows="4" cols="100" readonly="readonly">'.$value.'</textarea>';
}


function USERS2_MARKETING_AKCJE_task_ADD() {
	global $thiss, $ARG1, $ARG1_VAL, $SQL_USER, $USERS_FILTER_STATUS, $SQL_WIEV, $USERS_COLUMN, $USERS_COLUMN_DESC, $USERS_HIDECOLUMN;

	echo "Podaj dane do wprowadzenia do bazy  ";
	echo'<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE".'">'."Cofnij ".'<img src=icon/back.gif border=0 alt=POWROT>'.'</a>';

	$default_values = array();
	$default_values['DATA'] = date('Y-m-d');
	$default_values['FILTR_BEZ_BN'] = 'TAK';
	$default_values['FILTR_ANEKSY'] = 'NIE';
	$default_values['FILTR_MIN_ULOTEK_NA_BUDYNEK'] = '0';
	$default_values['FILTR_MIN_DATA_OSTATNIEJ_AKCJI'] = '0';
	$default_values['W_DATA'] = date("Y-m-d", mktime(0,0,0, date("m"), date("d") + 7, date("Y")));// domyslnie plus 7 dni na realizacje - doniesienie raportu
	foreach ($default_values as $k_field_name => $v_field_value) {
		if (empty($_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD'][$k_field_name])) {
			$_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD'][$k_field_name] = $v_field_value;
		}
	}

	//MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=ADD&ARG1_VAL=
	echo'<form action="" method="POST" id="frm">';
		echo'<table cellspacing="0" cellpadding="0" border="1">';

	$t = 0;
	foreach ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'] as $value) {
		if (!strstr($_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']["$value"],"C")) {
			continue;
		}
		echo'<tr class="row-' . ($t = 1 - $t) . '">';
		echo '<td>';
		if (!empty($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG'][$value])) {
			echo $_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG'][$value];
			echo '<br /><code style="font-size:x-small">'.$value.'</code>';
		} else {
			echo '<code>'.$value.'</code> ';
		}
		echo'</td>';
		echo'<td>';
		if ($_SESSION['LAST_MENU'] == $thiss->DETECT_TABLE_NAME) {
			//$_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD'][$value] = $_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG'][$value];
			if ((strstr($ARG1_VAL,'RESTORE'))) $_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD'][$value] = $_SESSION[$thiss->DETECT_TABLE_COLUMN]['EDIT_TEMPLATE'][$value];
		}
		if (!isset($_SESSION[$thiss->DETECT_TABLE_COLUMN]['TYPESPECIAL'][$value])) {
			GETFORMITEM($_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD'][$value],$_SESSION[$thiss->DETECT_TABLE_COLUMN]['TYPE'][$value],$_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'][$_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_KEY'][$value]]);
			echo "($h[$value])"; 
			echo $_SESSION[$thiss->DETECT_TABLE_COLUMN]['TYPESPECIAL'][$value];
		} else if (isset($_SESSION[$thiss->DETECT_TABLE_COLUMN]['TYPESPECIAL'][$value])) {
			$_SESSION[$thiss->DETECT_TABLE_COLUMN]['TYPESPECIAL'][$value]('', $_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD'][$value]);
		} else {
			echo $_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD'][$value];
		}
		echo " ".'</td></tr>'."\n";
	}
	echo'<tr>';
		echo'<td colspan="2">';
			USERS2_MARKETING_AKCJE::print_rewir_tree( $_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD'] );
		echo'</td>';
	echo'</tr>';

	echo'<tr>';
		echo'<td colspan="2" style="text-align:left">';
			echo'<input type="hidden" name="'."task".'" value="'."verify".'" />';
			echo'<input type="submit" value="'."Dalej".'" />';
		echo'</td>';
	echo'</tr>';

	echo'</table>';

	echo'</form>';
}


function USERS2_MARKETING_AKCJE_task_ADD_verify() {
	global $thiss;

	$buildings = array();
	$ile_ulotek = 0;

	echo "Zweryfikuj dane ";

	// validation
	$validation_errors = array();
	if (empty($_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD']['ID_PROJECT'])) {
		$validation_errors['ID_PROJECT'] []= "nie wybrano projektu";
	}
	if (empty($_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD']['FILTR_M_REWIR']) && empty($_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD']['FILTR_S_ADDRESS_STREET'])) {
		if (empty($_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD']['FILTR_M_REWIR'])) {
			$validation_errors['FILTR_M_REWIR'] []= "nie wybrano rewirow";
		}
		if (empty($_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD']['FILTR_S_ADDRESS_STREET'])) {
			$validation_errors['FILTR_S_ADDRESS_STREET'] []= "nie wybrano budynkow";
		}
	} else {

		$rewiry = explode(',', $_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD']['FILTR_M_REWIR']);
		$streets = explode(',', $_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD']['FILTR_S_ADDRESS_STREET']);

		$sql_where_or_arr = array();
		if (!empty($rewiry)) {
			foreach ($rewiry as $rewir) {
				$rewir = trim($rewir);
				if (!empty($rewir)) {
					$sql_where_or_arr []= "`M_REWIR` like '".$rewir."%'";
				}
			}//end foreach
		}
		if (!empty($streets)) {
			foreach ($streets as $street) {
				$street = trim($street);
				if (!empty($street)) {
					$sql_where_or_arr []= "`S_ADDRESS_STREET`='".$street."'";
				}
			}//end foreach
		}
		$sql = "select `S_ADDRESS_STREET` from `BUILDINGS` where ".implode(" or ", $sql_where_or_arr);

		$res = DB::query($sql);
		while ($r = DB::fetch($res)) {
			$buildings []= $r->S_ADDRESS_STREET;
		}

		if (empty($buildings)) {
			$validation_errors['FILTR_S_ADDRESS_STREET'] []= "brak budynkow pasujacych do kryteriow";
		} else {
			$buildings_rows = array();
			$buildings_street = $buildings;
{// filtr 
	$record_data = $_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD'];
	$buildings = array();
	$rewiry_selected = explode(',', $record_data['FILTR_M_REWIR']);
	$buildings_selected = explode(',', $record_data['FILTR_S_ADDRESS_STREET']);

	// fetch old actions on buildings
	$old_actions = array();// [street] = last action date
	$sql = "select
			mb.`S_ADDRESS_STREET` as street
			, max(ma.`DATA`) as last_date
		from `USERS2_MARKETING_AKCJE_BUILDINGS` as mb
			left join `USERS2_MARKETING_AKCJE` as ma on(ma.`ID`=mb.`ID_AKCJA`)
		where
			ma.`A_STATUS`!='DELETED'
		group by mb.`S_ADDRESS_STREET`
	";
	$res = DB::query($sql);
	while ($r = DB::fetch($res)) {
		$r->street = strtoupper($r->street);
		$old_actions[$r->street] = $r->last_date;
	}

	// filtr bez BN
	$sql_ulotek = "ov.`MIESZKAN`";
	if ($record_data['FILTR_BEZ_BN'] == 'TAK') {
		$sql_ulotek = "(ov.`MIESZKAN` - ov.`ABO_I`)";
	}
	// filtr FILTR_MIN_ULOTEK_NA_BUDYNEK
	$sql_ulotek_enable = "1";
	if ($filtr_min_ulotek_na_budynek = V::get('FILTR_MIN_ULOTEK_NA_BUDYNEK', 0, $record_data, 'int')) {
		if ($record_data['FILTR_BEZ_BN'] == 'TAK') {
			$sql_ulotek_enable = "  ( (100 * ov.`ABO_I`) / ov.`MIESZKAN` ) <= ".$filtr_min_ulotek_na_budynek."";
		}
	}
	// TODO: filtr aneksy - max 3-mce przed koncem umowy == pomin umowy konczace sie za ponad 3 miesiace
	$aneksy_arr = array();
	if (0) {//if ('TAK' == V::get('FILTR_ANEKSY', '', $record_data)) {
		$sql = "select td.`SERVICES_S_ADDRESS_STREET`, td.`P_DEALDATE_TERM`
			from `temp_DEALS_STATUS` as td
			where td.`DEALS_ACTIVE`='1'
				and td.`P_DEALDATE_TERM` > DATE_ADD(CURDATE(), INTERVAL 3 MONTH)
				and td.`SERVICES_S_ADDRESS_STREET` in ('".implode("','", $buildings_street)."')
		";
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql FILTR_ANEKSY: ';print_r($sql);echo'</pre>';
		$res = DB::query($sql);
		while ($r = DB::fetch($res)) {
			$r->SERVICES_S_ADDRESS_STREET = strtoupper($r->SERVICES_S_ADDRESS_STREET);
			$aneksy_arr [$r->SERVICES_S_ADDRESS_STREET] = $r->P_DEALDATE_TERM;
		}
	}

	$sql = "select b.`ID`, b.`M_REWIR`, b.`S_ADDRESS_STREET`, b.`P_ADDRESS_STREET`
			, ov.`ABO_I`, ov.`MIESZKAN`
			, $sql_ulotek as ile_ulotek
			, ( (100 * ".$sql_ulotek.") / ov.`MIESZKAN` ) as pr
			, $sql_ulotek_enable as ulotek_enable
			, 1 as data_enable
		from `BUILDINGS` as b
			left join `USERS2_MARKETING_OVERWIEV` as ov on(ov.`T_TELBOX_BUILDING_IN`=b.`S_ADDRESS_STREET`)
		where
			b.`A_STATUS` in ('NORMAL','WARNING')
			and b.`S_ADDRESS_STREET` in ('".implode("','", $buildings_street)."')
		group by b.`ID`
		order by b.`M_REWIR`
	";
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none">sql FILTR_ANEKSY: ';print_r($sql);echo'</pre>';

	$res = DB::query($sql);
	while ($r = DB::fetch($res)) {
//		$r->p_dealdate_term = null;
//		$r->S_ADDRESS_STREET = strtoupper($r->S_ADDRESS_STREET);
//		if ('TAK' == V::get('FILTR_ANEKSY', '', $record_data)) {
//			if (array_key_exists($r->S_ADDRESS_STREET, $aneksy_arr)) {
//				$r->p_dealdate_term = $aneksy_arr[$r->S_ADDRESS_STREET];
//			}
//		}
		if ($filtr_data = V::get('FILTR_MIN_DATA_OSTATNIEJ_AKCJI', 0, $record_data)) {
			if (array_key_exists($r->S_ADDRESS_STREET, $old_actions)) {
				if ($old_actions[$r->S_ADDRESS_STREET] >= $filtr_data) {
					$r->data_enable = 0;
					$r->last_action_date = $old_actions[$r->S_ADDRESS_STREET];
				}
			}
		}
		$buildings [$r->ID] = $r;
	}

	foreach ($buildings as $r) {
		if (!$r->ulotek_enable) continue;
		if (!$r->data_enable) continue;
		$buildings_rows []= $r->S_ADDRESS_STREET;
	}
	$buildings = $buildings_rows;
}// filtr			

			$sql = "select sum(".$sql_ulotek.") as cnt
				from `USERS2_MARKETING_OVERWIEV` as ov
				where ov.`T_TELBOX_BUILDING_IN` in('".implode("','", $buildings)."')
			";
			$res = DB::query($sql);
			if ($r = DB::fetch($res)) {
				$ile_ulotek = $r->cnt;
			}
		}
	}
	if (empty($_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD']['W_USER'])) {
		$validation_errors['W_USER'] []= "nie wybrano pracownika";
	}
	if (empty($_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD']['W_DATA'])) {
		$validation_errors['W_DATA'] []= "nie wybrano terminu wykonania zadania";
	}
	if (!empty($_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD']['K_USER'])) {
		if (empty($_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD']['K_DATA'])) {
			$validation_errors['K_DATA'] []= "nie wybrano terminu wykonania kontroli";
		}
	}



echo'<form action="" method="POST" id="frm">';
	echo'<table cellspacing="0" cellpadding="0" border="1">';

$t = 0;
foreach ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'] as $field_name) {
	if (strstr($_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT'][$field_name],"C")) {
		echo'<tr class="row-' . ($t = 1 - $t) . '">';
			echo '<td>';
			if (!empty($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG'][$field_name])) {
				echo $_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC_TO_LANG'][$field_name];
				echo '<br /><code style="font-size:x-small">'.$field_name.'</code>';
			} else {
				echo '<code>'.$field_name.'</code> ';
			}
			echo'</td>';
			echo'<td>';
			if (array_key_exists($field_name, $validation_errors)) {
				echo'<b style="color:red"> !!! </b>';
			}
			echo $_SESSION[$thiss->DETECT_TABLE_COLUMN]['NEW_RECORD'][$field_name];
			echo'</td>';
		echo'</tr>'."\n";
	}
}
	echo'<tr>';
		echo'<td colspan="2">';
		if (!empty($validation_errors)) {
			echo'<p style="color:red">'."Formularz zawiera bledy:".'</p>';
			echo'<ul>';
			foreach ($validation_errors as $k_field_name => $v_err) {
				echo '<li>'."Pole ".$k_field_name.": ".implode(', ', $v_err).'</li>';
			}//end foreach
			echo'</ul>';
		} else {
			echo'<input type="hidden" name="'."update_FILTR_S_ADDRESS_STREET".'" value="'.implode(",", $buildings).'" />';
			echo'<input type="hidden" name="'."update_ILE_ULOTEK".'" value="'.$ile_ulotek.'" />';

			if (empty($buildings)) {
				echo "Brak pasujacych budynkow";
			} else {
				echo "<b>Budynki:</b> ".implode(', ', $buildings);
			}
			echo'<br />'.'<b>'."Liczba potrzebnych ulotek: ".$ile_ulotek.'</b>';
		}
		echo'</td>';
	echo'</tr>';

	echo'<tr>';
		echo'<td colspan="2" style="text-align:left">';
			if (empty($validation_errors)) {
				echo'<input type="hidden" name="'."task".'" value="'."save".'" />';
				echo "Jesli dane sa poprawne przejdz ";
				echo'<input type="submit" value="'."Dalej".'" />';

				echo " lub ";
			}
			echo " cofnij w celu poprawienia danych ";
			//CREATE_MENUFUNC_NOTD_INIT('USERS2_MARKETING_AKCJE','<img src=icon/back.gif border=0 alt=POWROT>');
			echo'<a href="'."index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=ADD&ARG1_VAL=".'"><img src="icon/back.gif" border="0" alt="POWROT"></a>';
		echo'</td>';
	echo'</tr>';

	echo'</table>';


echo'</form>';
}


function USERS2_MARKETING_AKCJE_view_zlecenie_1_strona( $record_id, &$record, &$buildings, $worker_name ) {
	$DATA_ZLECENIA_KOLPORTAZU = $record['DATA'];
	$DATA_PROCESU_DYSTRYBUCJI = $record['W_DATA'];
	$NUMER_PROCESU_DYSTRYBUCJI = $record_id;
	$ZLECENIOBIORCA = $worker_name;
	$ILOSC_POWIERZONYCH_SZTUK_MATERIALOW = 1;// TODO: suma ulotek do rozniesienia
	$mieszkan = 0;// TODO: suma ulotek do rozniesienia
	{// get suma do rozniesienia
		foreach ($buildings as $building) {
			$mieszkan += $building['DO_ROZNIESIENIA'];
		}//end foreach
		// zaokroglenie w gore
		$ILOSC_POWIERZONYCH_SZTUK_MATERIALOW = ceil(($mieszkan + 1) / 100) * 100;
	}
	$streets = array();
	{// get street names
		$sql_where_or_arr = array();
		foreach ($buildings as $building) {
			$sql_where_or_arr []= "'" . $building['S_ADDRESS_STREET'] . "'";
		}//end foreach
		$sql = "select `S_ADDRESS_STREET`, `P_ADDRESS_STREET` from `BUILDINGS` where `S_ADDRESS_STREET` in (".implode(",", $sql_where_or_arr).")";

		$res = DB::query($sql);
		while ($r = DB::fetch($res)) {
			$streets [$r->P_ADDRESS_STREET] []= $r->S_ADDRESS_STREET;
		}
	}
	$JAKIE_POWIERZONO_MATERIALY_plakaty_ulotki_itp = 'ulotki';
	$INNE_POWIERZONE_PRZEDMIOTY_np_nozyczki_tasma_itp = ".................";
	$MATERIALY_NALEZY_POJEDYNCZO_UMIESZCZAC_NA_np_klamka_drzwi_itp = "W skrzynce pocztowej";
	$MATERIALY_NALEZY_ROZNIESC_W_DNIU = $record['W_DATA'];
	$MATERIALY_NALEZY_ROZNIESC_OD_GODZINY = ".....";
	$MATERIALY_NALEZY_ROZNIESC_TEGO_SAMEGO_DNIA_DO_GODZINY = ".....";
	$MIEJSCE_DOSTARCZENIA_RAPORTU = "biuro Chełm";
	$TERMIN_DATA_DOSTARCZENIA_RAPORTU = "..........";
	$GODZINA_DOSTARCZENIA_RAPORTU = ".....";
	$DODATKOWE_CZYNNOSCI_DO_ZROBIENIA_np_poskladac_ogumkowac_itp = "..........";
	$LACZNA_WARTOSC_POWIERZONYCH_MAETRIALOW = ".....";// TODO: wartosc ulotek = koszt 1 ulotki z projektu * ilosc przekazanych ulotek
	$WARTOSC_ZLECENIA = ".....";
  $kara = (is_numeric($LACZNA_WARTOSC_POWIERZONYCH_MAETRIALOW) && is_numeric($WARTOSC_ZLECENIA))? ($LACZNA_WARTOSC_POWIERZONYCH_MAETRIALOW + $WARTOSC_ZLECENIA) * 2 : ".....";

	echo '<table border="0" width="100%" cellspacing="0" cellpadding="0">';
	echo '<tr><td colspan=14>';
		echo '<br>'."ZLECENIE KOLPORTAŻU z dnia  <i><b>".$DATA_ZLECENIA_KOLPORTAZU."</b></i>, do procesu dystrybucji nr <i><b>".$NUMER_PROCESU_DYSTRYBUCJI."</b></i> z dnia <i><b>".$DATA_PROCESU_DYSTRYBUCJI."</b></i>";
		echo'<br><br>';
		echo "Zleceniodawca:".'<br>';
		echo "BIALL-NET sp. z o.o. 80-174 Gdańsk, Otomin ul. Słoneczna 43.".'<br><br>';
		echo "Zleceniobiorca:".'<br>';
		echo '<b>'.$ZLECENIOBIORCA.'</b><br>';
		echo '<font size=1>';
		echo "1) Zleceniobiorca zobowiązuje się rozprowadzić materiały  reklamowe na obszarze (wg oznaczenia kodowego REWIRÓW i ULIC):";
		echo '</font>';
	echo '</td></tr>';
	echo '<tr><td colspan=14>';
		// TODO: add street names in ()
		foreach ($streets as $k_street => $v_short_arr) {
			echo "&nbsp;&nbsp;&nbsp; " . $k_street . ": " . implode(", ", $v_short_arr) . '<br />';
		}//end foreach
	echo '</td></tr>';

echo "<tr><td colspan=14>
<font size=1>
2) Zleceniodawca powierza <b>$ILOSC_POWIERZONYCH_SZTUK_MATERIALOW</b> sztuk <b>$JAKIE_POWIERZONO_MATERIALY_plakaty_ulotki_itp</b> oraz inne przedmioty (<b>$INNE_POWIERZONE_PRZEDMIOTY_np_nozyczki_tasma_itp</b>)*, wszystkie o łącznej wartości <b>$LACZNA_WARTOSC_POWIERZONYCH_MAETRIALOW</b> PLN. zł.<br>
3) Powierzone materiały reklamowe, pod rygorem niewypłacenia wartości zlecenia Zleceniobiorcy lub/i dodatkowo powstania innych roszczeń Zleceniodawcy tytułem strat wobec Zleceniobiorcy, rozprowadzić należy na wyznaczonym terenie w dniu <b>$MATERIALY_NALEZY_ROZNIESC_W_DNIU</b> od godziny <b>$MATERIALY_NALEZY_ROZNIESC_OD_GODZINY</b> do godziny <b>$MATERIALY_NALEZY_ROZNIESC_TEGO_SAMEGO_DNIA_DO_GODZINY</b> <br>
4) Powierzone materiały reklamowe należy umieszczać pojedynczo na <b>$MATERIALY_NALEZY_POJEDYNCZO_UMIESZCZAC_NA_np_klamka_drzwi_itp</b> <br>
5) Niniejsze zlecenie z uzupelnionymi polami Raportu roznoszenia ulotek  wraz z pozostałymi materiałami reklamowymi, należy dostarczyć do dnia: <b>$TERMIN_DATA_DOSTARCZENIA_RAPORTU</b> do godziny: <b>$GODZINA_DOSTARCZENIA_RAPORTU</b> w miejsce <b>$MIEJSCE_DOSTARCZENIA_RAPORTU</b> .<br>
6) Dodatkowe czynności, które zobowiązuje się przeprowadzić Zleceniobiorca przed rozprowadzeniem materiałów reklamowych: <b>$DODATKOWE_CZYNNOSCI_DO_ZROBIENIA_np_poskladac_ogumkowac_itp</b> <br>
7) Wartość zlecenia wynosi <b>$WARTOSC_ZLECENIA</b>  złotych.<br>
8) Materiały opisane w pkt. 2) winny trafić w 100% do ustalonych miejsc dystrybucji (wg pkt. 1) oraz pkt. 4))  . W przypadku jakichkolwiek odstępstw od powyższego zlecającemu zostanie potrącona wysokość wynagrodzenia do 20% wartości zlecenia opisanego w pkt.7).<br>
9) W przypadku, kiedy materiały opisane wyżej, w ilości większej lub równej 10% sztuk określonych w pkt. 2), zostały umieszczone w innych miejscach niż określa <nobr>pkt. 4) bądź </nobr> nie zostały umieszczone w ogóle, Zlecającemu przysługuje prawo do dodatkowego odszkodowania tytułem strat handlowych do wysokości ";
  echo "<b>$kara</b>";
echo " zł.<br>
10) Raporty roznoszenia ulotek winny być wypełnione wg schematu w raporcie ( oznaczonego w pkt. 5), czyli np. w polu .godzina/data. należy umieścić datę i godzinę rozpoczęcia dystrybucji materiałów danym budynku. Niewypełnienie tych pól lub/i raportu jest równoznaczne ze niewykonaniem zlecenia. Brane będą wyłącznie pod uwagę fragmenty raportu wypełnione w pełni, rzetelnie i czytelnie. Wszystkie inne pola (rzędy arkusza) wypełnione częściowo lub w ogóle, będą traktowane jakoby w danym adresie dystrybucja nie miała miejsca. Od momentu oddania raportu dystrybucji zakazane jest uzupełnianie raportu przez którąkolwiek ze stron. Wpisy w danym rzędzie w raporcie winny być wypełnione jednym i tym samym długopisem.<br>
11) Nie wywiązanie się z wyżej wymienionych zadań równoznaczne jest z nie wykonaniem powierzonej pracy, co się wiąże brakiem wynagrodzenia a nawet pokryciem strat firmy wynikających z tego tytułu.<br>
12) Zlecenie realizowane jest na obszarze <b>$mieszkan</b> mieszkań, według danych z systemu BIALL-NET. Zakłąda się, że mogą być od tej liczby odstępstwa, które zostaną zweryfikowane na podstawie niniejszego zlecenia. <br>
</font>
";
	?>
		<table style="width:100%;margin:20px 0;" border="0">
			<tr>
				<td style="width:10%">
				</td>
				<td style="text-aling:cetner;">
					ZLECENIODAWCA
					<br /><br />
					............. 
				</td>
				<td style="width:10%">
				</td>
				<td style="text-aling:cetner;">
					ZLECENIOBIORCA
					<br /><br />
					<b><?php echo $ZLECENIOBIORCA; ?></b>
				</td>
				<td style="width:10%">
				</td>
			</tr>
		</table>
	</td></tr>
	</table>
	<?php
}


function USERS2_MARKETING_AKCJE_podsumowanie() {
	global $thiss;

	Lib::loadClass('DB');

	SEF("MENU");
	MENU();

	echo '<h1>' . "Podsumowanie akcji:" . '</h1>';

	$select_daty = array();
	$selected_data = V::get('W_DATA', '', $_REQUEST);
	$sql = "
		select
			substring(a.`W_DATA`, 1, 7) as data_akcji
		from `USERS2_MARKETING_AKCJE` as a
		where a.`A_STATUS`!='DELETED'
		group by data_akcji
		order by data_akcji desc
	";
	$res = DB::query( $sql );
	while ($r = DB::fetch( $res )) {
		$select_daty[$r->data_akcji] = $r->data_akcji;
	}
	//if (!ereg("^[[:digit:]]{4}-[[:digit:]]{2}$", $selected_data)) {
	if (!array_key_exists($selected_data, $select_daty)) {
		$selected_data = '';
	}


	echo '<form action="" method="post">';
	echo "Wybierz miesiąc ";
	echo '<select name="' . "W_DATA" . '" onchange="' . "this.form.submit()" . '">';
	foreach ($select_daty as $k_option => $v_value) {
		$sel = ($k_option == $selected_data)? ' selected="selected"' : '';
		echo '<option value="' . $k_option . '"' . $sel . '>' . $v_value . '</option>';
	}//end foreach
	echo '</select>';
	echo " ";
	echo '<input type="submit" value="' . "Szukaj" . '" />';
	echo '</form>';
	echo '<br />';
	echo '<br />';

	if ($selected_data != '') {
		$sum = array();
		$sql = "select a.`ID`, a.`ID_PROJECT`, a.`W_DATA`, a.`W_USER`
				, sum(ab.`ROZNIESIONO`) as sum_ROZNIESIONO
			from `USERS2_MARKETING_AKCJE` as a
				left join `USERS2_MARKETING_AKCJE_BUILDINGS` as ab on (ab.`ID_AKCJA`=a.`ID`)
			where
				a.`A_STATUS`!='DELETED'
				and a.`W_DATA` like '" . $selected_data . "-%'
			group by `ID`
		";
		$res = DB::query( $sql );
		while ($r = DB::fetch( $res )) {
			$sum []= $r;
		}
		$podsumowanie_user = array();

		echo '<style type="text/css">' . "
			.tbl td{padding:0 3px;}
			.tbl th{padding:0 3px;}
		" . '</style>';

		echo '<table border="1" cellspacing="0" cellpadding="0" class="tbl">';
		echo '<tr>';
			echo '<th>' . "ID" . '</th>';
			echo '<th>' . "ID_PROJECT" . '</th>';
			echo '<th>' . "User" . '</th>';
			echo '<th>' . "Rozniesiono" . '</th>';
		echo '</tr>';
		foreach ($sum as $r) {
			$podsumowanie_user[$r->W_USER] += $r->sum_ROZNIESIONO;
			echo '<tr>';
				echo '<td>' . $r->ID . '</td>';
				echo '<td>' . $r->ID_PROJECT . '</td>';
				echo '<td>' . $r->W_USER . '</td>';
				echo '<td>' . $r->sum_ROZNIESIONO . '</td>';
			echo '</tr>';
		}
		echo '</table>';

		echo '<h4>' . "Podsumowanie wg pracownika" . '</h4>';
		echo '<table border="1" cellspacing="0" cellpadding="0" class="tbl">';
		echo '<tr>';
			echo '<th>' . "User" . '</th>';
			echo '<th>' . "Rozniesiono" . '</th>';
		echo '</tr>';
		foreach ($podsumowanie_user as $k_user => $v_rozniesiono) {
			echo '<tr>';
				echo '<td>';
					$link = "index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=PODSUMOWANIE_USER&ARG1_VAL=";
					$link .= "&f_DATA=" . $selected_data . "&f_USER=" . $k_user;
					echo '<a href="' . $link . '">' . $k_user . '</a>';
				echo '</td>';
				echo '<td>' . $v_rozniesiono . '</td>';
			echo '</tr>';
		}
		echo '</table>';
	}
}


function USERS2_MARKETING_AKCJE_podsumowanie_user() {
	global $thiss;
	Lib::loadClass('DB');

	SEF("MENU");
	MENU();

	$selected_data = V::get('f_DATA', '', $_GET);
	$selected_user = V::get('f_USER', '', $_GET);
	$sort_by = V::get('f_sort_by', 'S_ADDRESS_STREET', $_GET);
	$sort_dir = V::get('f_sort_dir', 'asc', $_GET);

	// USERS2_MARKETING_AKCJE_BUILDINGS
	{
		$thiss->DETECT_TABLE_COLUMN = 'USERS2_MARKETING_AKCJE_BUILDINGS_COLUMN';
		$thiss->DETECT_TABLE_NAME = 'USERS2_MARKETING_AKCJE_BUILDINGS';
		$thiss->DETECT_HIST_FUNCTION = 'USERS2_MARKETING_AKCJE_HIST';
		$thiss->DETECT_EDIT_FUNCTION = 'USERS2_MARKETING_AKCJE_EDIT';
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">thiss: ';print_r($thiss);echo'</pre>';
		$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']['A_ADM_COMPANY'] = '';
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">SES[thiss]: ';print_r($_SESSION[$thiss->DETECT_TABLE_COLUMN]);echo'</pre>';
	}

	// validation
	if ($sort_dir) {
		$sort_dir = strtolower($sort_dir);
		if (!in_array($sort_dir, array('asc', 'desc'))) {
			$sort_dir = 'asc';
		}
	}
	if ($sort_by) {
		$sort_by = strtoupper($sort_by);
		if (!in_array($sort_by, $_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'])) {
			$sort_by = 'S_ADDRESS_STREET';
		}
	}

	echo '<h1>';
		echo '<a href="' . "index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=PODSUMOWANIE&ARG1_VAL=&DATA=" . $selected_data . '">' . "Podsumowanie akcji" . '</a>';
		echo " &raquo; ";
		echo "dla pracownika '" . $selected_user . "' w miesiącu " . $selected_data . ":" ;
	echo '</h1>';

	$buildings = USERS2_MARKETING_AKCJE::get_buildings_by_user_month($selected_user, $selected_data, $sort_by, $sort_dir);
	// TODO: add column 'ID_PROJECT'

	{// add ID_PROJECT
		if (!in_array('ID_PROJECT', $_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'])) {
			$_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'][] = 'ID_PROJECT';
		}
		if (!array_key_exists('ID_PROJECT', $_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT'])) {
			$_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']['ID_PROJECT'] = 'R';
		}
	}

	$suma_do_rozniesienia = 0;
	$suma_rozniesiono = 0;
	foreach ($buildings as $k_street => $h) {
		$suma_do_rozniesienia += $h['DO_ROZNIESIENIA'];
		$suma_rozniesiono += $h['ROZNIESIONO'];
	}
	echo '<p>'."Do rozniesienia ".$suma_do_rozniesienia." - rozniesiono ".$suma_rozniesiono.".";
		echo '<b>'." Skuteczność akcji: ".(($suma_rozniesiono > 0)? round((100 * $suma_rozniesiono/$suma_do_rozniesienia)) : 0)."%".'</b>';
	echo '</p>';
	echo'<table width="100%" border="1" cellspacing="0" cellpadding="0" class="tbl-view">';
	echo'<thead>';
	echo'<tr>';
		foreach ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'] as $field_name) {
			if (!strstr($_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT'][ $field_name ], "R")) {
				continue;
			}
			echo '<th style="font-size:x-small;">';
				echo str_replace('_', ' ', $field_name);
				$cur_order_dir = 'asc';
				$cur_link = "index.php?MENU_INIT=USERS2_MARKETING_AKCJE&ARG1=PODSUMOWANIE_USER&ARG1_VAL=&f_DATA=" . $selected_data . "&f_USER=" . $selected_user . "&f_sort_by=" . $field_name;
				if ($field_name == $sort_by) {
					$cur_order_dir = strtolower($sort_dir);
					if ($sort_dir == 'asc') {
						$cur_link .= "&f_sort_dir=" . 'DESC';
					}
				}
				echo '<a href="' . $cur_link . '">' . '<img src="./icon/sort-' . $cur_order_dir . '.gif" alt="sort - ' . $cur_order_dir . '" />' . '</a>';
			echo '</th>';
		}
	echo'</tr>';
	echo'</thead>';
	echo'<tbody>';
	$t = 0;
	foreach ($buildings as $h) {
		echo '<tr class="row-' . ($t = 1 - $t) . '">';
		foreach ($_SESSION[$thiss->DETECT_TABLE_COLUMN]['DESC'] as $field_name) {
			if (!strstr($_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT'][ $field_name ], "R")) {
				continue;
			}
			echo '<td>';
			echo $h[$field_name];
			echo '</td>';
		}
		echo'</tr>';
	}
	echo'</tbody>';
	echo'</table>';
}


function USERS2_MARKETING_AKCJE_task_EDIT_A_STATUS( $task, $record_id, &$record ) {
	if ($record_id < 0) {
		echo '<p style="color:red">' . "Wrong Param record_id!" . '</p>';
		return;
	}
	if (empty($record)) {
		echo '<p style="color:red">' . "Wrong Param record!" . '</p>';
		return;
	}
	$allowed_task = array('delete', 'undelete');
	if (!in_array($task, $allowed_task)) {
		echo '<p style="color:red">' . "Wrong Task!" . '</p>';
		return;
	}


	$data_arr = array();
	if ($task == 'delete') {
		if ($record['A_STATUS'] != 'DELETED') {
			$data_arr ['A_STATUS'] = 'DELETED';
		}
	}
	else if ($task == 'undelete') {
		if ($record['A_STATUS'] == 'DELETED') {
			$data_arr ['A_STATUS'] = 'NORMAL';
		}
	}

	if (empty($data_arr)) {
		$error_msg = "";// ??
		echo '<p style="color:red">' . $error_msg . '</p>';
		echo '<a href="' . "index.php?MENU_INIT=USERS2_MARKETING_AKCJE" . '">' . "Wróć" . '</a>';// TODO: back link
		return;
	}

	$sql_arr = array();
	foreach ($data_arr as $k => $v) {
		$sql_arr []= "`" . $k . "`='" . $v . "'";
	}//end foreach
	$sql_arr []= "`A_RECORD_UPDATE_AUTHOR`='" . $_SESSION['ADM_ACCOUNT'] . "'";
	$sql_arr []= "`A_RECORD_UPDATE_DATE`='" . date('Y-m-d-H:i') . "'";
	$sql = "update `USERS2_MARKETING_AKCJE`
			set " . implode(", ", $sql_arr) . "
		where `ID`='" . $record_id . "'
		limit 1
		;
	";
	DB::query($sql);

	// add HIST
	$sql_arr = array();
	foreach ($data_arr as $k => $v) {
		$sql_arr ["`" . $k . "`"] = "'" . $v . "'";
	}//end foreach
	$sql_arr ["`A_RECORD_CREATE_AUTHOR`"] = "'" . $_SESSION['ADM_ACCOUNT'] . "'";
	$sql_arr ["`A_RECORD_CREATE_DATE`"] = "'" . date('Y-m-d-H:i') . "'";
	$sql_arr ["`ID_USERS2`"] = "'" . $record_id . "'";
	$sql = "insert into `USERS2_MARKETING_AKCJE_HIST` (" . implode(", ", array_keys($sql_arr)) . ")
			values(" . implode(", ", array_values($sql_arr)) . ")
		;
	";
	DB::query($sql);

	$msg = "";
	if ($task == 'delete') {
		$msg = "Rekord usunięto.";
	}
	else if ($task == 'undelete') {
		$msg = "Rekord przywrócono.";
	}
	echo '<p>' . $msg . '</p>';
	echo '<a href="' . "index.php?MENU_INIT=USERS2_MARKETING_AKCJE" . '">' . "Wróć" . '</a>';// TODO: back link
}
