<?php


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



/**
 * Module PANEL klienta (?MENU_INIT=USERS2_WINDYKACJA_PANEL) - to mv to USERS2_PANEL
 * 
 */
function USERS2_WINDYKACJA_STATUS() {
	global $thiss;

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

	// router
	$q = V::get('q', '', $_REQUEST);
	$user_id = V::get('_user_id', 0, $_REQUEST, 'int');
	$task = V::get('task', '', $_REQUEST);

	if ($task != '') {
		if ($task == 'view_faktura') {
			$faktura_id = V::get('id', 0, $_REQUEST, 'int');
			WindykacjaView::view_faktura( $faktura_id );
			return;
		}
		else if ($task == 'zadluzenia') {
			$user_id = V::get('user_id', 0, $_REQUEST, 'int');
			if ($user_id > 0) {
				$user = WindykacjaStatsModel::get_user_by_id( $user_id );
				if (!$user) {
					echo'<p style="color:red">'."Użytkownik nie istnieje.".'</p>';
				} else {
					WindykacjaView::zadluzenia( $user );
					return;
				}
			} else {
				echo'<p style="color:red">'."Bledne dane.".'</p>';
			}
		}
		else if ($task == 'wezwanie') {
			$user_id = V::get('user_id', 0, $_REQUEST, 'int');
			if ($user_id > 0) {
				$user = WindykacjaStatsModel::get_user_by_id( $user_id );
				if (!$user) {
					echo'<p style="color:red">'."Użytkownik nie istnieje.".'</p>';
				} else {
					WindykacjaView::wezwanie( $user, $user->PAY_TERM );
					return;
				}
			} else {
				echo'<p style="color:red">'."Bledne dane.".'</p>';
			}
		}
		else if ($task == 'wezwanie_ostateczne') {
			$user_id = V::get('user_id', 0, $_REQUEST, 'int');
			if ($user_id > 0) {
				$user = WindykacjaStatsModel::get_user_by_id( $user_id );
				if (!$user) {
					echo'<p style="color:red">'."Użytkownik nie istnieje.".'</p>';
				} else {
					WindykacjaView::wezwanie_ostateczne( $user, $user->PAY_TERM );
					return;
				}
			} else {
				echo'<p style="color:red">'."Bledne dane.".'</p>';
			}
		}
		else if ($task == 'bok_rozwiazanie_umowy') {
			$user_id = V::get('user_id', 0, $_REQUEST, 'int');
			if ($user_id > 0) {
				$user = WindykacjaStatsModel::get_user_by_id( $user_id );
				if (!$user) {
					echo'<p style="color:red">'."Użytkownik nie istnieje.".'</p>';
				} else {
					WindykacjaView::task_bok_rozwiazanie_umowy( $user );
					return;
				}
			} else {
				echo'<p style="color:red">'."Bledne dane.".'</p>';
			}
		}
		else if ($task == 'bok_rozwiazanie_umowy_print') {
			$user_id = V::get('user_id', 0, $_REQUEST, 'int');
			if ($user_id > 0) {
				$user = WindykacjaStatsModel::get_user_by_id( $user_id );
				if (!$user) {
					echo'<p style="color:red">'."Użytkownik nie istnieje.".'</p>';
				} else {
					WindykacjaView::task_bok_rozwiazanie_umowy_print( $user, V::get('id_koresp', 0, $_REQUEST, 'int') );
					return;
				}
			} else {
				echo'<p style="color:red">'."Bledne dane.".'</p>';
			}
		}
		else if ($task == 'stats_update') {
			WindykacjaView::task_update_stats();
			return;
		}
		else if ($task == 'export_csv') {

			$items = array();

			$page_nav = new stdClass();
			$page_nav->total = 0;
			$page_nav->page_total = 0;
			$page_nav->base_link_arr = array('MENU_INIT'=>"USERS2_WINDYKACJA_STATUS", 'q'=>$q);
			$page_nav->page_limit = 100000;
			$page_nav->page_nr = 0;
			$page_nav->base_link_arr ['_f'] = V::get('_f', '', $_GET);
			if ($page_nav->page_nr > 0) {
				$page_nav->base_link_arr ['_p'] = $page_nav->page_nr;
			}
			// sortowanie, filtr wyszukiwania
			$page_nav->base_link_arr ['_oby'] = 'ID';
			$page_nav->base_link_arr ['_odir'] = 'DESC';
			if (($order_by = V::get('_oby', '', $_GET)) != '') {
				$page_nav->base_link_arr ['_oby'] = $order_by;
			}
			if (($order_dir = V::get('_odir', '', $_GET)) != '') {
				$page_nav->base_link_arr ['_odir'] = $order_dir;
			}

			if (!empty($q)) {
				$page_nav->total = WindykacjaStatsModel::get_users_total( $q );
				$page_nav->last_page_nr = floor($page_nav->total / $page_nav->page_limit);

				$items = WindykacjaStatsModel::get_users($q, $page_nav->page_limit, $page_nav->page_nr * $page_nav->page_limit, $page_nav->base_link_arr['_oby'], $page_nav->base_link_arr['_odir']);
				$page_nav->page_total = count($items);
			}
			else {
				$page_nav->total = WindykacjaStatsModel::get_users_total( $q );
				$page_nav->last_page_nr = floor($page_nav->total / $page_nav->page_limit);

				$items = WindykacjaStatsModel::get_users($q, $page_nav->page_limit, $page_nav->page_nr * $page_nav->page_limit, $page_nav->base_link_arr['_oby'], $page_nav->base_link_arr['_odir']);
				$page_nav->page_total = count($items);
			}

			if ($page_nav->total > 0) {
				WindykacjaView::export_csv( $q, $page_nav, $items );
			} else {
				echo'<p>' . "Brak danych" . '</p>';
			}
			exit;
		}
	}

	WindykacjaView::css();

	if ($user_id > 0) {
		$user = WindykacjaStatsModel::get_user_by_id( $user_id );
		if (!$user) {
			echo'<p>'."Użytkownik nie istnieje.".'</p>';
			return;
		}

		WindykacjaView::user( $user );

		WindykacjaView::user_umowy( $user );

		WindykacjaView::user_historia_platnosci( $user );

	}
	else {
		// aktualiacja danych
		WindykacjaStatsHelper::update_users_table();

		$items = array();

		$page_nav = new stdClass();
		$page_nav->total = 0;
		$page_nav->page_total = 0;
		$page_nav->base_link_arr = array('MENU_INIT'=>"USERS2_WINDYKACJA_STATUS", 'q'=>$q);
		$page_nav->page_limit = 50;
		$page_nav->page_nr = V::get('_p', 0, $_REQUEST, 'int');
		$page_nav->base_link_arr ['_f'] = V::get('_f', '', $_GET);
		if ($page_nav->page_nr > 0) {
			$page_nav->base_link_arr ['_p'] = $page_nav->page_nr;
		}
		// sortowanie, filtr wyszukiwania
		$page_nav->base_link_arr ['_oby'] = 'ID';
		$page_nav->base_link_arr ['_odir'] = 'DESC';
		if (($order_by = V::get('_oby', '', $_GET)) != '') {
			$page_nav->base_link_arr ['_oby'] = $order_by;
		}
		if (($order_dir = V::get('_odir', '', $_GET)) != '') {
			$page_nav->base_link_arr ['_odir'] = $order_dir;
		}

		if (!empty($q)) {
			$page_nav->total = WindykacjaStatsModel::get_users_total( $q );
			$page_nav->last_page_nr = floor($page_nav->total / $page_nav->page_limit);

			$items = WindykacjaStatsModel::get_users($q, $page_nav->page_limit, $page_nav->page_nr * $page_nav->page_limit, $page_nav->base_link_arr['_oby'], $page_nav->base_link_arr['_odir']);
			$page_nav->page_total = count($items);
		}
		else {
			$page_nav->total = WindykacjaStatsModel::get_users_total( $q );
			$page_nav->last_page_nr = floor($page_nav->total / $page_nav->page_limit);

			$items = WindykacjaStatsModel::get_users($q, $page_nav->page_limit, $page_nav->page_nr * $page_nav->page_limit, $page_nav->base_link_arr['_oby'], $page_nav->base_link_arr['_odir']);
			$page_nav->page_total = count($items);
		}

		WindykacjaView::form( $q );

		$to_update_total = WindykacjaStatsHelper::get_to_update_total();
		if ($to_update_total > 0) {
			echo'<p>';
			echo'<a style="color:red" href="' . "?MENU_INIT=USERS2_WINDYKACJA_STATUS&task=stats_update&q=".$q."&_p=".V::get('_p', 0, $_GET, 'int') . '">' . "Aktualizuj statusy (" . $to_update_total . ")" . '</a>';
			echo'</p>';
		}

		WindykacjaView::items_filters();
		if ($page_nav->total > 0) {
			WindykacjaView::items( $q, $page_nav, $items );
		} else {
			echo'<p>' . "Brak danych" . '</p>';
		}
	}


}


class WindykacjaView {


	function user( &$user ) {

		$bad_address_task = V::get('bad_address', '', $_POST);
		$bad_address_msg = array();
		if ($bad_address_task) {
			$id_koresp = V::get('ID_KORESP', 0, $_POST, 'int');
			if ($id_koresp <= 0) {
				$bad_address_msg['error_id_koresp'] = true;
			} else {
				if ($bad_address_task == 'save') {
					if (!WindykacjaStatsHelper::bad_address_save($user, $id_koresp)) {
						$bad_address_msg['error'] = true;
					} else {
						$bad_address_msg['ok'] = true;
					}
				}
				else if ($bad_address_task == 'confirm') {
					if (!WindykacjaStatsHelper::bad_address_confirm($user, $id_koresp)) {
						$bad_address_msg['error'] = true;
					} else {
						$bad_address_msg['ok'] = true;
					}
				}
			}
		}

		$change_status_task = V::get('change_status', '', $_POST);
		$change_status_msg = array();
		if ($change_status_task) {
			if ($change_status_task == 'change') {
				$new_status = V::get('new_status', '', $_POST);
				$fltr_arr = WindykacjaStatsHelper::get_filters();
				if (!array_key_exists($new_status, $fltr_arr)) {
					$change_status_msg['error'] = true;
				} else {
					if (!WindykacjaStatsHelper::change_status_save($user, $new_status)) {
						$change_status_msg['error'] = true;
					} else {
						$change_status_msg['ok'] = true;
					}
				}
			}
		}

		$set_nr_sprawy_krd_task = V::get('set_nr_sprawy_krd', '', $_POST);
		$set_nr_sprawy_krd_msg = array();
		if ($set_nr_sprawy_krd_task) {
			if ($set_nr_sprawy_krd_task == 'change') {
				$nr_sprawy_krd = V::get('nr_sprawy_krd', '', $_POST);
				if (!WindykacjaStatsHelper::nr_sprawy_krd_save($user, $nr_sprawy_krd)) {
					$set_nr_sprawy_krd_msg['error'] = true;
				} else {
					$set_nr_sprawy_krd_msg['ok'] = true;
				}
			}
		}

		$set_nr_sprawy_sad_task = V::get('set_nr_sprawy_sad', '', $_POST);
		$set_nr_sprawy_sad_msg = array();
		if ($set_nr_sprawy_sad_task) {
			if ($set_nr_sprawy_sad_task == 'change') {
				$nr_sprawy_sad = V::get('nr_sprawy_sad', '', $_POST);
				if (!WindykacjaStatsHelper::nr_sprawy_sad_save($user, $nr_sprawy_sad)) {
					$set_nr_sprawy_sad_msg['error'] = true;
				} else {
					$set_nr_sprawy_sad_msg['ok'] = true;
				}
			}
		}

		$set_nr_sprawy_komornik_task = V::get('set_nr_sprawy_komornik', '', $_POST);
		$set_nr_sprawy_komornik_msg = array();
		if ($set_nr_sprawy_komornik_task) {
			if ($set_nr_sprawy_komornik_task == 'change') {
				$nr_sprawy_komornik = V::get('nr_sprawy_komornik', '', $_POST);
				if (!WindykacjaStatsHelper::nr_sprawy_komornik_save($user, $nr_sprawy_komornik)) {
					$set_nr_sprawy_komornik_msg['error'] = true;
				} else {
					$set_nr_sprawy_komornik_msg['ok'] = true;
				}
			}
		}

		$set_ustalenia_info_task = V::get('set_ustalenia_info', '', $_POST);
		$set_ustalenia_info_msg = array();
		if ($set_ustalenia_info_task) {
			if ($set_ustalenia_info_task == 'change') {
				$ustalenia_date = V::get('ustalenia_date', '', $_POST);
				$ustalenia_info = V::get('ustalenia_info', '', $_POST);
				if (!WindykacjaStatsHelper::ustalenia_info_save($user, $ustalenia_date, $ustalenia_info)) {
					$set_ustalenia_info_msg['error'] = true;
				} else {
					$set_ustalenia_info_msg['ok'] = true;
				}
			}
		}

		echo'<h3>';
			echo' <a href="'."?MENU_INIT=USERS2_WINDYKACJA_STATUS&q=".V::get('q','', $_REQUEST)."&_p=".V::get('_p', '', $_REQUEST)."&_f=".V::get('_f', '', $_REQUEST)."&_oby=".V::get('_oby', '', $_REQUEST)."&_odir=".V::get('_odir', '', $_REQUEST).'">'."Klienci".'</a>';
			echo ' &raquo; <code style="font-size:normal;color:green;">'."[".$user->id_users."]".'</code>';
			echo ' <b>'.$user->P_NAME.' '.$user->P_NAME_SECOND.'</b>';
		echo'</h3>';

		echo '<table class="" cellspacing="0" cellpadding="0" border="0"><tr><td style="vertical-align:top">';
		echo '<table class="tbl-view tbl-umowy-l2" cellspacing="0" cellpadding="0" border="1">';
		echo '<caption>';
			echo "Dane " . (($user->is_firma)? "firmy" : "klienta") . " ";
			if ($user->BAD_ADDRESS) {
				echo '<form action="" method="POST" style="display:inline">';
					echo '<input type="hidden" name="'."bad_address".'" value="'."confirm".'" />';
					$js = "if(this.nextSibling.style.display=='none'){this.nextSibling.style.display='block'}else{this.nextSibling.style.display='none'}; return false;";
					echo '<input type="button" value="'."popraw adres".'" onclick="'.$js.'" style="margin:1px 2px;padding:0 6px;" />';
					echo '<div style="display:none;">';
						echo '<label for="ID_KORESP">'."ID Koresp.".'</label>';
						echo '<input type="text" name="' . "ID_KORESP" . '" size="5" value="' . "" . '" />';
						echo '<input type="submit" value="'."zapisz".'" />';
					echo '</div>';
				echo '</form>';
			} else {
				echo '<form action="" method="POST" style="display:inline">';
					echo '<input type="hidden" name="'."bad_address".'" value="'."save".'" />';
					$js = "if(this.nextSibling.style.display=='none'){this.nextSibling.style.display='block'}else{this.nextSibling.style.display='none'}; return false;";
					echo '<input type="button" value="'."zgłoś błędny adres".'" onclick="'.$js.'" style="margin:1px 2px;padding:0 6px;" />';
					echo '<div style="display:none;">';
						echo '<label for="ID_KORESP">'."ID Koresp.".'</label>';
						echo '<input type="text" name="' . "ID_KORESP" . '" size="5" value="' . "" . '" />';
						echo '<input type="submit" value="'."zapisz".'" />';
					echo '</div>';
				echo '</form>';
			}
			if (!empty($bad_address_msg)) {
				if ('id_koresp' == V::get('error', '', $bad_address_msg)) {
					echo '<div class="red">'."Podaj poprawny ID Koresp.".'</div>';
				} else if (true == V::get('error', false, $bad_address_msg)) {
					echo '<div class="red">'."Error!".'</div>';
				} else if (true == V::get('ok', false, $bad_address_msg)) {
					echo '<div style="color:green">'."Zapisano pomyślnie.".'</div>';
				}
			}
		echo '</caption>';
		echo'<tr>';
			echo'<th>' . "Adres:" . '</th>';
			echo'<td'.(($user->BAD_ADDRESS)? ' style="background-color:#FF7878;"' : '').'>';
				echo "ul. ".$user->P_ADDRESS_STREET." ".$user->P_ADDRESS_HOUSE."/".$user->P_ADDRESS_HOME.", ".$user->P_ADDRESS_POST_CODE." ".$user->P_ADDRESS_CITY;
			echo'</td>';
		echo'</tr>';
		echo'<tr>';
			echo'<th>' . "Pesel:" . '</th>';
			echo'<td>';
				if ($user->P_PESEL) {
					echo $user->P_PESEL;
				} else {
					echo '<span style="color:#f00;">'."Brak numeru PESEL!".'</span>';
				}
			echo'</td>';
		echo'</tr>';
		echo'<tr>';
			echo'<th>' . "Nr telefonu:" . '</th>';
			echo'<td>';
				if ($user->P_PHONE) {
					echo $user->P_PHONE;
				} else {
					echo '<span style="color:#f00;">'."Brak!".'</span>';
				}
			echo'</td>';
		echo'</tr>';
		echo'<tr>';
			echo'<th>' . "Nr dowodu:" . '</th>';
			echo'<td>';
				if ($user->P_OTHER_DOC) {
					echo $user->P_OTHER_DOC;
				} else {
					echo '<span style="color:#f00;">'."Brak!".'</span>';
				}
			echo'</td>';
		echo'</tr>';
		echo'<tr>';
			echo'<th>' . "e-mail:" . '</th>';
			echo'<td>';
				if ($user->user_mail_contact) {
					echo '<a href="mailto:'.$user->user_mail_contact.'">'.$user->user_mail_contact.'</a>';
				} else {
					echo '<span style="color:#f00;">'."Brak!".'</span>';
				}
			echo'</td>';
		echo'</tr>';
		echo'<tr>';
			echo'<th>' . "Klient firmy:" . '</th>';
			echo'<td>';
				if ($user->BILLING_OWNER == 1) {
					echo 'BN - BIALL-NET';
				} else if ($user->BILLING_OWNER == 2) {
					echo 'ND - NETDAY';
				} else {
					echo 'nieznany';
				}
			echo'</td>';
		echo'</tr>';
		echo'<tr>';
			echo'<th>' . "Blokada:" . '</th>';
			echo'<td>';
				if ($user->STATUS == 9) {
					echo '<b style="color:red">' . "ZABLOKOWANY" . '</b>';
				} else {
					echo 'brak blokady';
				}
			echo'</td>';
		echo'</tr>';
		echo '</table>';

		echo '</td><td>' . "&nbsp;" . '</td><td style="vertical-align:top">';

		echo '<table class="tbl-view tbl-umowy-l2'.(($user->A_STATUS_UPDATE_DATE < date("Y-m-d"))? ' wind-status-old' : '').'" cellspacing="0" cellpadding="0" border="1">';
		echo '<caption>';
			echo "Status windykacji ";
			echo '<code style="font-size:x-small; color:#ccc;">' . "(" . $user->WINDYKACJA_ID . ")" . '</code>';
			if ($user->A_STATUS_UPDATE_DATE < date("Y-m-d")) {
				echo " " . '<a style="color:red" href="' . "?MENU_INIT=USERS2_WINDYKACJA_STATUS&q=".V::get('q','', $_REQUEST)."&_p=".V::get('_p','', $_REQUEST)."&_f=".V::get('_f', '', $_REQUEST)."&_user_id=".$user->ID . '">' . "Aktualizuj status" . '</a>';
			}
			// TODO: zmien status klienta - przypisanie do odpowiedniej grupy
		echo '</caption>';
		echo '<tr>';
			echo '<th>' . "status:" . '</th>';
			echo '<td>';
				echo $user->A_STATUS;
if (V::get('DBG', '', $_GET, 'int') > 0) {// TODO: TEST
	if ($user->A_STATUS == 'waiting-krd') {
		echo '<br />' . "wezwanie2_DATE: {$user->wezwanie2_DATE}";
		$wzw2 = new stdClass();
		$wzw2->Y = intval(substr($user->wezwanie2_DATE, 0, 4));
		$wzw2->m = intval(substr($user->wezwanie2_DATE, 5, 2));
		$wzw2->d = intval(substr($user->wezwanie2_DATE, 8, 2));
		echo '<br />' . "wzw2: {$wzw2->Y}-{$wzw2->m}-{$wzw2->d}";
		$wzw2->plus_60 = date("Y-m-d", mktime(0,0,0, $wzw2->m, $wzw2->d + 60, $wzw2->Y));
		echo '<br />' . "wezwanie2_DATE + 60 dni: {$wzw2->plus_60}";
		if ($wzw2->plus_60 < date("Y-m-d")) {
			echo '<br />' . "TODO: przenieść do krd";
		}
	}
}// TODO: TEST
				echo ' &nbsp;&nbsp; <form action="" method="POST" style="display:inline">';
					echo '<input type="hidden" name="'."change_status".'" value="'."change".'" />';
					$fltr_arr = WindykacjaStatsHelper::get_filters();
					$fltr_options = array();
					foreach ($fltr_arr as $k_status => $v_arr) {
						$fltr_options[$k_status] = reset($v_arr);
					}
					echo '<select name="' . "new_status" . '">';
					foreach ($fltr_options as $k_ind => $v_label) {
						$sel = ($k_ind == $user->A_STATUS)? ' selected="selected"' : '';
						echo '<option value="' . $k_ind . '"' . $sel . '>' . "{$k_ind}: {$v_label}" . '</option>';
					}
					echo '</select>';
					echo '<input type="submit" value="'."zmień".'" />';
				echo '</form>';

			echo '</td>';
		echo '</tr>';
		echo '<tr>';
			echo '<th>' . "Nr sprawy w krd" . '</th>';
			echo '<td>';
				echo ' <form action="" method="POST" style="display:inline">';
					echo '<input type="hidden" name="'."set_nr_sprawy_krd".'" value="'."change".'" />';
					echo '<input type="text" name="'."nr_sprawy_krd".'" value="'.$user->NR_SPRAWY_KRD.'" />';
					echo '<input type="submit" value="'."zmień".'" />';
				echo '</form>';
			echo '</td>';
		echo '</tr>';
		echo '<tr>';
			echo '<th>' . "Nr sprawy w sądzie" . '</th>';
			echo '<td>';
				echo ' <form action="" method="POST" style="display:inline">';
					echo '<input type="hidden" name="'."set_nr_sprawy_sad".'" value="'."change".'" />';
					echo '<input type="text" name="'."nr_sprawy_sad".'" value="'.$user->NR_SPRAWY_SAD.'" />';
					echo '<input type="submit" value="'."zmień".'" />';
				echo '</form>';
			echo '</td>';
		echo '</tr>';
		echo '<tr>';
			echo '<th>' . "Nr sprawy u komornika" . '</th>';
			echo '<td>';
				echo ' <form action="" method="POST" style="display:inline">';
					echo '<input type="hidden" name="'."set_nr_sprawy_komornik".'" value="'."change".'" />';
					echo '<input type="text" name="'."nr_sprawy_komornik".'" value="'.$user->NR_SPRAWY_KOMORNIK.'" />';
					echo '<input type="submit" value="'."zmień".'" />';
				echo '</form>';
			echo '</td>';
		echo '</tr>';
		echo '<tr>';
			echo '<th>' . "Aktualne ustalenia z klientem" . '</th>';
			echo '<td>';
				echo ' <form action="" method="POST" style="display:inline">';
					echo '<input type="hidden" name="'."set_ustalenia_info".'" value="'."change".'" />';
					echo '<textarea style="width:100%" type="text" name="'."ustalenia_info".'">' . $user->L_APPOITMENT_INFO . '</textarea>';
					echo '<br />' . "Data: ";
					echo '<input type="text" name="'."ustalenia_date".'" value="'.$user->L_APPOITMENT_DATE.'" />';
					echo '<input type="submit" value="'."zmień".'" />';
					$js = "this.form.ustalenia_info.value=''; this.form.ustalenia_date.value='0000-00-00'; return false;";
					echo '<input type="reset" value="'."wyszyść".'" onclick="'.$js.'" />';
				echo '</form>';
			echo '</td>';
		echo '</tr>';
		echo '<tr>';
			echo '<th>' . "data ostatniej wpłaty:" . '</th>';
			echo '<td>';
				if ($user->LAST_PAY_DATE && $user->LAST_PAY_DATE != '0000-00-00') {
					echo $user->LAST_PAY_DATE;
				} else {
					echo '---';
				}
			echo '</td>';
		echo '</tr>';
		echo '<tr>';
			echo '<th>' . "data wymagalności ostatniej faktury:" . '</th>';
			echo '<td>';
				if ($user->PAY_DATE != '0000-00-00') {
					echo $user->PAY_DATE;
				}
			echo '</td>';
		echo '</tr>';
		echo '<tr>';
			echo '<th>' . "termin płatności:" . '</th>';
			echo '<td>';
				if ($user->PAY_TERM != '0000-00-00') {
					echo $user->PAY_TERM;
				}
			echo '</td>';
		echo '</tr>';
		echo '</table>';

		echo '</td></tr></table>';

		// TODO: windykacja_status_info - grupa filtrow do ktorej nalezy klient
		Lib::loadClass('CompanyHelper');
		$db = DB::getDB();
		$comHelper = new CompanyHelper($db);
		$usr = $comHelper->getById($user->ID);
		$dealsActive = $comHelper->getDealsFull($user->ID, false);

		Lib::loadClass('PokazOfertyView');
		$pokaz_oferty_view = new PokazOfertyView();
		echo $pokaz_oferty_view->print_css();
		$pokaz_oferty_view->printServices($usr, $dealsActive);

		// aktualny status klienta
		echo'<div>';
			if ($user->A_STATUS_UPDATE_DATE < date("Y-m-d")) {
			}
			else {
				switch ($user->A_STATUS) {
					case 'WAITING': {
						echo'<p>' . "Status OK" . '</p>';
					}
					break;
					case 'wezwanie1': {
						$default_PAY_TERM = date("Y-m-d", mktime(0,0,0,date('m'), date('d') + 14, date('Y')));
						$frm_errors = array();
						$frm_msgs = array();
						$frm = array();
						$frm['wezwanie1_DATE'] = date("Y-m-d");
						$frm['PAY_TERM'] = V::get('PAY_TERM', $default_PAY_TERM, $_POST);
						$frm['ID_PROJ'] = V::get('ID_PROJ', 0, $_POST, 'int');
						if ('set_wezwanie' == V::get('user_task', '', $_POST)) {
							if ($frm['ID_PROJ'] == 0) {
								$frm_errors []= "Brak numeru ID Projketu";
							}
							if (empty($frm_errors)) {
								$ret = WindykacjaStatsHelper::update_user( $user, $frm );
								if ($ret) {
									$frm_msgs []= "Status klienta został zaktualizowany";
								} else {
									$frm_errors []= "Status klienta nie został zaktualizowany";
								}
							}
						}
						echo '<div class="box box-blue" style="margin:6px 0;">';
							if ($user->PAY_FVAT > 0 && $user->PAY_SALDO < 0) {
								echo "Saldo klienta: " . '<b style="color:#f00">' . $user->PAY_SALDO . " zł" . '</b>' . " (" . $user->PAY_FVAT ." niezapłaconych faktur)" . '<br />';
								echo'<br />';
							}
							echo '<b style="color:#0B0B8E">'."Wysłać wezwanie do zapłaty".'</b>'.'<br />';
							if (!empty($frm_errors)) {
								echo'<p style="color:#f00">' . implode('<br />', $frm_errors) . '</p>';
							}
							if (!empty($frm_msgs)) {
								echo'<p style="color:green">' . implode('<br />', $frm_msgs) . '</p>';
							}
							echo'<form action="" method="post">';
								echo'<input type="hidden" name="'."user_task".'" value="'."set_wezwanie".'" />';
								echo "Data płatności: ";
									echo'<input type="text" name="'."PAY_TERM".'" value="'.$frm['PAY_TERM'].'" />';
								echo " ID Projektu: ";
									echo'<input type="text" name="'."ID_PROJ".'" value="'.$frm['ID_PROJ'].'" />';
								echo'<input type="submit" value="'."Zapisz".'" />';
							echo'</form>';
						if ($user->wezwanie1_DATE != '0000-00-00') {
							echo'<br />';
							$ico_print = '<img src="icon/print.gif" height="16" />';
							echo'<a href="'."?MENU_INIT=USERS2_WINDYKACJA_STATUS&q=".V::get('q','', $_REQUEST)."&task="."wezwanie"."&user_id=".$user->ID.'" target="_blank">'.$ico_print." wezwanie do zapłaty".'</a>';
						}
						echo '</div>';// .box-blue
					}
					break;
					case 'waiting-wezwanie2': {// TODO: only auto update ?
						echo '<div class="box box-blue" style="margin:6px 0;">';
							if ($user->PAY_FVAT > 0 && $user->PAY_SALDO < 0) {
								echo "Saldo klienta: " . '<b style="color:#f00">' . $user->PAY_SALDO . " zł" . '</b>' . " (" . $user->PAY_FVAT ." niezapłaconych faktur)" . '<br />';
								echo'<br />';
							}
							echo '<b style="color:#0B0B8E">'."Oczekiwanie na uzbieranie kwoty 300zł (firmy 500zł)".'</b>'.'<br />';
							if (!empty($frm_errors)) {
								echo'<p style="color:#f00">';
									echo implode('<br />', $frm_errors);
								echo'</p>';
							}
							echo'<form action="" method="post">';
							//	echo'<input type="hidden" name="'."user_task".'" value="'."set_".'" />';
							//	echo'<input type="submit" value="'."Zapisz".'" />';
							echo'</form>';
							if ($user->wezwanie1_DATE != '0000-00-00') {
								echo'<br />';
								$ico_print = '<img src="icon/print.gif" height="16" />';
								echo'<a href="'."?MENU_INIT=USERS2_WINDYKACJA_STATUS&q=".V::get('q','', $_REQUEST)."&task="."wezwanie"."&user_id=".$user->ID.'" target="_blank">' . $ico_print . " wezwanie do zapłaty".'</a>'.'<em>'." (termin płatności: " . $user->PAY_TERM . ")".'</em>';
							}
						echo '</div>';// .box-blue
					}
					break;
					case 'wezwanie2': {
						$default_PAY_TERM = date("Y-m-d", mktime(0,0,0,date('m'), date('d') + 14, date('Y')));
						$frm_msgs = array();
						$frm_errors = array();
						$frm = array();
						$frm['wezwanie2_DATE'] = date("Y-m-d");
						$frm['PAY_TERM'] = V::get('PAY_TERM', $default_PAY_TERM, $_POST);
						$frm['ID_PROJ'] = V::get('ID_PROJ', 0, $_POST, 'int');
						if ('set_wezwanie2' == V::get('user_task', '', $_POST)) {
							if ($frm['ID_PROJ'] == 0) {
								$frm_errors []= "Brak numeru ID korespondencji";
							}
							if (empty($frm_errors)) {
								$ret = WindykacjaStatsHelper::update_user( $user, $frm );
								if ($ret) {
									$frm_msgs []= "Status klienta został zaktualizowany";
								} else {
									$frm_errors []= "Status klienta nie został zaktualizowany";
								}
							}
						}
						echo '<div class="box box-blue" style="margin:6px 0;border-color:#666;">';
							if ($user->PAY_FVAT > 0 && $user->PAY_SALDO < 0) {
								echo "Saldo klienta: " . '<b style="color:#f00">' . $user->PAY_SALDO . " zł" . '</b>' . " (" . $user->PAY_FVAT ." niezapłaconych faktur)" . '<br />';
								echo'<br />';
							}
							echo '<b style="color:#0B0B8E">'."Wysłać ostateczne wezwanie do zapłaty".'</b>'.'<br />';
							if (!empty($frm_errors)) {
								echo'<p style="color:#f00">' . implode('<br />', $frm_errors) . '</p>';
							}
							if (!empty($frm_msgs)) {
								echo'<p style="color:green">' . implode('<br />', $frm_msgs) . '</p>';
							}
							echo'<form action="" method="post">';
								echo'<input type="hidden" name="'."user_task".'" value="'."set_wezwanie2".'" />';
								echo "Data płatności: ";
									echo'<input type="text" name="'."PAY_TERM".'" value="'.$frm['PAY_TERM'].'" />';
								echo " ID Projektu: ";
									echo'<input type="text" name="'."ID_PROJ".'" value="'.$frm['ID_PROJ'].'" />';
								echo'<input type="submit" value="'."Zapisz".'" />';
							echo'</form>';
						if ($user->wezwanie2_DATE != '0000-00-00') {
							echo'<br />';
							$ico_print = '<img src="icon/print.gif" height="16" />';
							echo'<a href="'."?MENU_INIT=USERS2_WINDYKACJA_STATUS&q=".V::get('q','', $_REQUEST)."&task="."wezwanie_ostateczne"."&user_id=".$user->ID.'" target="_blank">' . $ico_print . " ostateczne wezwanie do zapłaty".'</a>';
						}
						echo '</div>';// .box-blue
					}
					break;
					case 'waiting-krd': {
						if ($user->wezwanie2_DATE != '0000-00-00') {
							echo'<br />';
							$ico_print = '<img src="icon/print.gif" height="16" />';
							echo'<a href="'."?MENU_INIT=USERS2_WINDYKACJA_STATUS&q=".V::get('q','', $_REQUEST)."&task="."wezwanie_ostateczne"."&user_id=".$user->ID.'" target="_blank">' . $ico_print . " ostateczne wezwanie do zapłaty".'</a>';
						}
					}
					break;
					default:
						echo'<p>' . "TODO: (".$user->A_STATUS.")" . '</p>';
				}
			}
			//if ($user->BA_TIMESTAMP) {
			//	echo "Stan wzajemnych rozrachunków:";
			//	echo " WINIEN: <b>".$user->BA_WINIEN."</b> -  MA: <b>".$user->BA_MA."</b>    SALDO(DO ZAPŁATY): <b>".($user->BA_WINIEN - $user->BA_MA)."</b>";
			//	echo", i jest to stan na dzień ".date("Y-m-d",$user->BA_TIMESTAMP)." ";
			//}
			// phone contact
			$phone_status_info = WindykacjaStatsHelper::get_phone_status_info( $user );
			$frm_errors = array();
			$frm_msgs = array();
			if (1 == V::get('phone_contact_save', 0, $_POST, 'int')) {
				if ('' == ($phone_status = V::get('phone_status', '', $_POST))) {
					$frm_errors []= "Nic nie zaznaczono!";
				} else {
					if (!array_key_exists($phone_status, $phone_status_info)) {
						$frm_errors []= "Nieprawidłowa wartość!";
					} else {
						$ret = WindykacjaStatsHelper::update_phone_status( $user, $phone_status );
						if ($ret) {
							$frm_msgs []= "Dane zapisano pomyślnie";
						} else {
							$frm_errors []= "Wystąpił błąd podczas zapisu danych";
						}
					}
				}
			}
			// add old id_koresp to hist (events)
			if (1 == V::get('contact_add_id_koresp_save', 0, $_POST, 'int')) {
				if (($id_koresp = V::get('id_koresp', '', $_POST, 'int')) <= 0) {
					$frm_errors []= "Nie podano numeru korespondencji!";
				} else {
					$koresp_type = V::get('koresp_type', '', $_POST);
					$ret = WindykacjaStatsHelper::update_old_id_koresp( $user, $id_koresp, $koresp_type );
					if ($ret) {
						$frm_msgs []= "Dane zapisano pomyślnie";
					} else {
						$frm_errors []= "Wystąpił błąd podczas zapisu danych";
					}
				}
			}
			echo'<script type="text/javascript">'."
function frm_kontakt_phone_submit_callback(frm){
	var len=frm.phone_status.length;
	var val='';
	for(var i=0; i < len; i++){
		if(frm.phone_status[i].checked){
			var val = frm.phone_status[i].value;
		}
	}
	if (val!='') {
		return true;
	} else {
		alert('Nic nie zaznaczono.');
	}
	return false;
}
function frm_kontakt_add_id_koresp(frm){
	var val=frm.id_koresp.value;
	if (val!='') {
		return true;
	} else {
		alert('Nie podano numeru korespondencji.');
	}
	return false;
}
			".'</script>';
			echo'<div class="box" style="margin:6px 0;border-color:#666;">';
				if (!empty($frm_errors)) {
					echo'<p style="color:#f00">' . implode('<br />', $frm_errors) . '</p>';
				}
				if (!empty($frm_msgs)) {
					echo'<p style="color:green">' . implode('<br />', $frm_msgs) . '</p>';
				}
				echo'<form action="" method="post" onsubmit="' . "return frm_kontakt_phone_submit_callback(this);" . '">';
				echo '<table cellspacing="0" cellpadding="0" border="0" class="tbl-td-top"><tr>';
				echo '<td style="padding:0 20px 0 0;color:blue;">';
					echo'<img src="' . "icon/phone.png" . '" alt="tel"  />';
					echo " kontakt z klientem ";
				echo '</td>';
				echo '<td style="padding:0 5px;text-align:right">';
					echo " Co ustalono: ";
				echo '</td>';
				echo '<td>';
					echo'<div id="'."kontakt-phone".'">';
						echo'<input type="hidden" name="'."phone_contact_save".'" value="'."1".'" />';
						foreach ($phone_status_info as $k_type => $v_info) {
							echo'<input type="radio" name="'."phone_status".'" value="' . $k_type . '" />'; echo " " . $v_info['label'] . " " . $v_info['date'] . '<br />';
						}
					echo'</div>';
				echo '</td>';
				echo '<td>';
					echo'<input type="submit" value="'."zapisz".'" />';
				echo '</td>';
				echo '</tr></table>';
				echo'</form>';
			echo'</div>';// .box

			echo'<div class="box" style="margin:6px 0;border-color:#666;">';
			echo'<form action="" method="post" onsubmit="' . "return frm_kontakt_add_id_koresp(this);" . '">';
				echo'<input type="hidden" name="'."contact_add_id_koresp_save".'" value="'."1".'" />';
				echo "Dodaj korespondencję z klientem - ID_KORESP: ";
				echo '<input type="text" name="'."id_koresp".'" value="' . "" . '" class="i" />';
				echo ' <input type="submit" value="'."zapisz".'" />';
			echo'</form>';
			echo'</div>';// .box

			echo'<div class="box" style="margin:6px 0;border-color:#666;">';
				$ico_print = '<img src="icon/print.gif" height="16" />';
				echo '<a href="'."?MENU_INIT=USERS2_WINDYKACJA_STATUS&q=".V::get('q','', $_REQUEST)."&task="."bok_rozwiazanie_umowy"."&user_id=".$user->ID.'" target="_blank">' . $ico_print . " rozwiązanie umowy".'</a>';
			echo'</div>';// .box

		echo'</div>';
	}


	function items_filters() {
		$filter_arr = WindykacjaStatsHelper::get_filters();
		$filter_selected = WindykacjaStatsHelper::get_filter_selected();
		$status_cnt = WindykacjaStatsHelper::get_status_count();// {cnt, suma_zaleglosci}
		// pomin filtry
		unset($filter_arr['15']);
		unset($filter_arr['blokada']);
		unset($filter_arr['WAITING']);
		$sub_filters = array('tel1', 'bad_address', '3 m-ce przed', 'po-terminie', 'has_nr_sad', 'has_nr_komornik', 'has_ustalenia', 'sad_and_komornik', 'sad_bez_komornik');
		$sub_filters_arr = array();
		foreach ($sub_filters as $v_filter_name) {
			if (array_key_exists($v_filter_name, $filter_arr)) {
				$sub_filters_arr[$v_filter_name] = $filter_arr[$v_filter_name];
				unset($filter_arr[$v_filter_name]);
			}
		}
		$zewn_filters = array('waiting-sad', 'sad');
		$zewn_filters_arr = array();
		foreach ($zewn_filters as $v_filter_name) {
			if (array_key_exists($v_filter_name, $filter_arr)) {
				$zewn_filters_arr[$v_filter_name] = $filter_arr[$v_filter_name];
				unset($filter_arr[$v_filter_name]);
			}
		}

		echo'<table cellspacing="0" cellpadding="0" border="1" style="background:#ddd;border-color:#666;"><tr><td style="vertical-align:top">';
		if (!empty($filter_selected)) {
				echo'<a href="' . "??MENU_INIT=USERS2_WINDYKACJA_STATUS" . '" title="'."Kasuj filtry".'">' . '<img src="icon/del.png" height="16" alt="'."Kasuj filtry".'" />' . '</a>';
			echo '</td><td>';
		}

		echo'<table class="tbl-view historia-platnosci-filters" cellspacing="0" cellpadding="0" border="1">';
		echo'<thead>';
		echo'<tr>';
			foreach ($filter_arr as $k => $v_arr) {
				$cls = ($filter_selected == $k)? ' class="selected"' : '';
				echo'<td' . $cls . '>';
					if ($desc = V::get('desc', '', $v_arr)) {
						echo '<span title="' . end($desc) . '">' . reset($desc) . '</span>';
					}
				echo'</td>';
			}
			if (!empty($zewn_filters_arr)) {
				echo '<td colspan="'.count($zewn_filters_arr).'" style="background:#f00;color:#fff;font-weight:bold;">' . "Windykacja zewnętrzna" . '</td>';
			}
		echo'</tr>';
		echo'<tr>';
			foreach ($filter_arr as $k => $v_arr) {
				$cls = ($filter_selected == $k)? ' class="selected"' : '';
				echo'<td' . $cls . '>';
					echo '<a href="' . "?MENU_INIT=USERS2_WINDYKACJA_STATUS&_f=" . $k . '">' . reset($v_arr) . '</a>';
					//$stat_cnt = V::get($k, 0, $status_cnt, 'int');
					//echo ' <span style="color:#f00;" title="' . $stat_cnt . " klinetów" . '">' . "(" . $stat_cnt . ")" . '</span>';
						$stat_cnt = 0;
					if (array_key_exists($k, $status_cnt)) {
						$stat_cnt = $status_cnt[$k]->cnt;
						echo ' <span style="color:#000;" title="' . $stat_cnt . " klinetów" . '">' . "(" . $stat_cnt . ")" . '</span>';
						$stat_saldo = number_format($status_cnt[$k]->suma_zaleglosci, 2, ',', ' ');
						echo '<br />' . '<span style="color:#f00;" title="' . $stat_saldo . " zł zagdłużenia" . '">' . $stat_saldo . '</span>';
					} else {
						echo ' <span style="color:#000;" title="' . $stat_cnt . " klinetów" . '">' . "(" . $stat_cnt . ")" . '</span>';
					}
				echo'</td>';
			}
			if (!empty($zewn_filters_arr)) {
				foreach ($zewn_filters_arr as $k => $v_arr) {
					$cls = ($filter_selected == $k)? ' class="selected"' : '';
					echo'<td' . $cls . '>';
						echo '<a href="' . "?MENU_INIT=USERS2_WINDYKACJA_STATUS&_f=" . $k . '">' . reset($v_arr) . '</a>';
						//$stat_cnt = V::get($k, 0, $status_cnt, 'int');
						//echo ' <span style="color:#f00;" title="' . $stat_cnt . " klinetów" . '">' . "(" . $stat_cnt . ")" . '</span>';
							$stat_cnt = 0;
						if (array_key_exists($k, $status_cnt)) {
							$stat_cnt = $status_cnt[$k]->cnt;
							echo ' <span style="color:#000;" title="' . $stat_cnt . " klinetów" . '">' . "(" . $stat_cnt . ")" . '</span>';
							$stat_saldo = number_format($status_cnt[$k]->suma_zaleglosci, 2, ',', ' ');
							echo '<br />' . '<span style="color:#f00;" title="' . $stat_saldo . " zł zagdłużenia" . '">' . $stat_saldo . '</span>';
						} else {
							echo ' <span style="color:#000;" title="' . $stat_cnt . " klinetów" . '">' . "(" . $stat_cnt . ")" . '</span>';
						}
					echo'</td>';
				}
			}
		echo'</tr>';
		echo'</thead>';
		echo'</table>';

		if (!empty($sub_filters_arr)) {
			echo '<table class="tbl-view historia-platnosci-subfilters" cellspacing="0" cellpadding="0" border="1">';
			echo '<thead><tr>';
			foreach ($sub_filters_arr as $k => $v_arr) {
				$cls = ($filter_selected == $k)? ' class="selected"' : '';
				echo'<td' . $cls . '>';
					echo '<a href="' . "?MENU_INIT=USERS2_WINDYKACJA_STATUS&_f=" . $k . '">' . reset($v_arr) . '</a>';
					//$stat_cnt = V::get($k, 0, $status_cnt, 'int');
					//echo ' <span style="color:#f00;" title="' . $stat_cnt . " klinetów" . '">' . "(" . $stat_cnt . ")" . '</span>';
						$stat_cnt = 0;
					if (array_key_exists($k, $status_cnt)) {
						$stat_cnt = $status_cnt[$k]->cnt;
						echo ' <span style="color:#000;" title="' . $stat_cnt . " klinetów" . '">' . "(" . $stat_cnt . ")" . '</span>';
						$stat_saldo = number_format($status_cnt[$k]->suma_zaleglosci, 2, ',', ' ');
						echo '<br />' . '<span style="color:#000;" title="' . $stat_saldo . " zł zagdłużenia" . '">' . $stat_saldo . '</span>';
					} else {
						echo ' <span style="color:#000;" title="' . $stat_cnt . " klinetów" . '">' . "(" . $stat_cnt . ")" . '</span>';
					}
				echo'</td>';
			}
			echo '</tr></thead>';
			echo '</table>';
		}

		echo '</td></tr></table>';

		echo'<br />';
	}


	function items( $q, &$page_nav, &$items ) {
		$page_nav->links = array();

		$out_link_arr = V::copy( $page_nav->base_link_arr );
		$out_link_arr['_p'] = 0;
		$out_link = V::make_link('', $out_link_arr);
		$page_nav->links []= '<a href="' . $out_link . '" title="'."Pierwsza strona".'">'."|&lt;&lt;".'</a>';

		if ($page_nav->page_nr > 0) {
			$out_link_arr = V::copy( $page_nav->base_link_arr );
			$out_link_arr['_p'] = $page_nav->page_nr - 1;
			$out_link = V::make_link('', $out_link_arr);
			$page_nav->links []=  '<a href="' . $out_link . '" title="'."Poprzednia strona".'">'."&lt;&lt; -".$page_nav->page_limit.'</a>';
		} else {
			$page_nav->links []=  " &lt;&lt; ";
		}

		$page_nav->links []=  '<span>'.($page_nav->page_nr * $page_nav->page_limit).'</span>';
		$page_nav->links []=  '<span title="'."Znaleziono ".$page_nav->total." rekordów".'">'."(".$page_nav->total.") ".'</span>';

		$out_link_arr = V::copy( $page_nav->base_link_arr );
		$out_link_arr['_p'] = $page_nav->page_nr + 1;
		$out_link = V::make_link('', $out_link_arr);
		$page_nav->links []=  '<a href="' . $out_link . '" title="'."Nastepna strona".'">'."+".$page_nav->page_limit." &gt;&gt;".'</a>';

		$out_link_arr = V::copy( $page_nav->base_link_arr );
		$out_link_arr['_p'] = $page_nav->last_page_nr;
		$out_link = V::make_link('', $out_link_arr);
		$page_nav->links []=  '<a href="' . $out_link . '" title="'."Ostatnia strona".'">'."&gt;&gt;|".'</a>';

		$page_nav_out = '<div class="tbl-page-nav">' . implode(" ", $page_nav->links);
			$out_link_arr = V::copy( $page_nav->base_link_arr );
			$out_link_arr['task'] = 'export_csv';
			$out_link = V::make_link('', $out_link_arr);
			$page_nav_out .= ' <a style="margin:0 0 0 20px;" href="' . $out_link . '" target="_blank">export csv</a>';
		$page_nav_out .= '</div>';
		if (empty($items)) {
			echo'<p style="color:red">'."Brak danych".'</p>';
			return;
		}
		echo $page_nav_out;

		$cols_order_by = WindykacjaStatsModel::get_order_by_fields();
		$cols = array();
		$cols['ID_BILLING_USERS'] = array('label'=>'Nr klienta', 'title'=>'ID_BILLING_USERS');
		$cols['is_firma'] = array('label'=>'F', 'title'=>'is_firma: Firma 1 - tak, 0 nie');
		$cols['BILLING_OWNER'] = array('label'=>'COM', 'title'=>'BILLING_OWNER: Klient firmy 1 - BIALL-NET, 2 - NETDAY');
		$cols['BLOKADA'] = array('label'=>'B', 'title'=>'BLOKADA: Informacja o blokadzie');
		$cols['P_NAME'] = array('label'=>'imie i nazwisko', 'title'=>'P_NAME');
		$cols['P_ADDRESS_STREET'] = array('label'=>'adres', 'title'=>'P_ADDRESS_STREET');
		$cols['A_STATUS'] = array('label'=>'status', 'title'=>'A_STATUS');
		$cols['A_STATUS_UPDATE_DATE'] = array('label'=>'data aktualizacji', 'title'=>'A_STATUS_UPDATE_DATE');
		$cols['PAY_SALDO'] = array('label'=>'saldo', 'title'=>'PAY_SALDO');
		$cols['PAY_FVAT'] = array('label'=>'zaległe faktury', 'title'=>'PAY_FVAT');
		$cols['PAY_DATE'] = array('label'=>'data wymagalności<br /> ostatniej faktury', 'title'=>'PAY_DATE');
		$cols['LAST_PAY_DATE'] = array('label'=>'data ostatniej wpłaty', 'title'=>'LAST_PAY_DATE');
		$cols['PAY_TERM'] = array('label'=>'termin płatności', 'title'=>'PAY_TERM');

		echo'<table class="tbl-view historia-platnosci" border="1" cellspacing="0" cellpaddin="0">';
		echo'<thead>';
			echo'<tr>';
			foreach ($cols as $k_field => $v_params) {
				echo'<th' . ((!empty($v_params['title'])) ? ' title="' . $v_params['title'] . '"' : '') . '>';
					echo $v_params['label'];

					if (in_array($k_field, $cols_order_by)) {
						$sel_oby  = (isset($page_nav->base_link_arr['_oby']))?  $page_nav->base_link_arr['_oby']  : '';
						$sel_odir = 'DESC';
						if ($k_field == $sel_oby) {
							$sel_odir = (isset($page_nav->base_link_arr['_odir']))? $page_nav->base_link_arr['_odir'] : '';
							$sel_odir = ($sel_odir == 'ASC')? 'ASC' : 'DESC';
						}

						$out_link_arr = V::copy( $page_nav->base_link_arr );
						$out_link_arr['_p'] = 0;
						$out_link_arr['_oby'] = $k_field;
						$out_link_arr['_odir'] = ($sel_odir == 'DESC')? 'ASC' : 'DESC';
						$out_link = V::make_link('', $out_link_arr);
						echo ' <a style="' . (($k_field == $sel_oby)? 'color:red;' : '') . 'text-decoration:none" href="' . $out_link . '">' . (($sel_odir == 'DESC')? 'v' : '^') . '</a>';
					}
				echo '</th>';
			}
			echo'</tr>';
		echo'</thead>';
		echo'<tbody>';
		$t = 0;
		foreach ($items as $k_id => $user) {
			echo'<tr class="row-'.($t = 1 - $t).'">';
				echo'<td>';
					echo'<nobr>';
					$out_link_arr = V::copy( $page_nav->base_link_arr );
					$out_link_arr['_user_id'] = $k_id;
					$out_link = V::make_link('', $out_link_arr);
					echo '<a href="' . $out_link . '">'.'<img src="icon/edit.png" height="16" alt="Edit">'.'</a>';
					echo " ";
					echo '<a href="' . $out_link . '">'.$k_id.'</a>';
					echo'</nobr>';
				echo'</td>';
				echo '<td>';
					echo $user->is_firma;
				echo '</td>';
				echo '<td>';
					if ($user->BILLING_OWNER == 1) {
						echo '<span title="' . "BIALL-NET" . '">' . 'BN' . '</span>';
					} else if ($user->BILLING_OWNER == 2) {
						echo '<span title="' . "NETDAY" . '">' . 'ND' . '</span>';
					} else {
						echo '0';
					}
				echo '</td>';
				echo '<td>';
					if ($user->STATUS == 9) {
						echo '<b style="color:red" title="' . "ZABLOKOWANY" . '">' . "Z" . '</b>';
					} else {
						echo '<em style="color:silver" title="' . "brak blokady" . '">' . "0" . '</em>';
					}
				echo '</td>';
				echo'<td>';
					$cell_out = $user->P_NAME.' '.$user->P_NAME_SECOND;
					echo '<b title="' . $cell_out . '">' . ((strlen($cell_out) > 30)? substr($cell_out, 0, 30) . ' ...' : $cell_out) . '</b>';
				echo'</td>';
				echo'<td'.(($user->BAD_ADDRESS)? ' style="background-color:#FF7878;"' : '').'>';
					$cell_out = "ul. " . $user->P_ADDRESS_STREET . " " . $user->P_ADDRESS_HOUSE . "/" . $user->P_ADDRESS_HOME . ", " . $user->P_ADDRESS_POST_CODE . " " . $user->P_ADDRESS_CITY;
					echo '<i title="' . (($user->BAD_ADDRESS)? "błędny adres zameldowania: " : '') . $cell_out . '">' . ((strlen($cell_out) > 30)? mb_substr($cell_out, 0, 30, "UTF-8") . ' ...' : $cell_out) . '</i>';
				echo'</td>';
				echo'<td>';
					echo '<nobr>';
					switch ($user->A_STATUS) {
						case 'WAITING':
							echo '<span style="color:#666;">' . $user->A_STATUS . '</span>';
							break;
						default:
							echo $user->A_STATUS;
					}
					echo '</nobr>';
				echo'</td>';
				echo'<td>';
					if ($user->A_STATUS_UPDATE_DATE != '0000-00-00') {
						echo $user->A_STATUS_UPDATE_DATE;
					} else {
						echo '<span style="color:#666;">' . $user->A_STATUS_UPDATE_DATE . '</span>';
					}
				echo'</td>';
				echo'<td>';
					echo '<nobr>';
					if ($user->PAY_SALDO != 0) {
						$col = ($user->PAY_SALDO > 0)? '#333' : '#f00';
						echo '<span style="color:' . $col . '">' . $user->PAY_SALDO . " zł" . '</span>';
					} else {
						echo'<span style="color:#666">' . "0" . '</span>';
					}
					echo '</nobr>';
				echo'</td>';
				echo'<td>';
					if ($user->PAY_FVAT > 0) {
						$st = ($user->PAY_FVAT > 1)? ' style="color:#f00"' : '';
						echo' <span title="' . $user->PAY_FVAT . " nieopłaconych faktur" . '"'.$st.'>' . $user->PAY_FVAT . '</span>';
					} else {
						echo $user->PAY_FVAT;
					}
				echo'</td>';
				echo'<td>';
					if ($user->PAY_DATE != '0000-00-00') {
						echo $user->PAY_DATE;
					}
				echo'</td>';
				echo'<td>';
					if ($user->LAST_PAY_DATE && $user->LAST_PAY_DATE != '0000-00-00') {
						echo $user->LAST_PAY_DATE;
					} else {
						echo '---';
					}
				echo'</td>';
				echo'<td>';
					if ($user->PAY_TERM != '0000-00-00') {
						echo $user->PAY_TERM;
					}
				echo'</td>';
				//, w.`USER_PAY_TERM_ADD`
				//, w.`L_APPOITMENT_DATE`
				//, w.`L_APPOITMENT_USER`
			echo'</tr>';
		}//end foreach
		echo'</tbody>';
		echo'</table>';
		echo $page_nav_out;
	}


	function export_csv( $q, &$page_nav, &$items ) {
		if (empty($items)) {
			echo "Brak danych";
			return;
		}
		$cols_order_by = WindykacjaStatsModel::get_order_by_fields();
		$cols = array();
		$cols['ID_BILLING_USERS'] = array('label'=>'Nr klienta', 'title'=>'ID_BILLING_USERS');
		$cols['is_firma'] = array('label'=>'F', 'title'=>'is_firma: Firma 1 - tak, 0 nie');
		$cols['BILLING_OWNER'] = array('label'=>'COM', 'title'=>'BILLING_OWNER: Klient firmy 1 - BIALL-NET, 2 - NETDAY');
		$cols['BLOKADA'] = array('label'=>'B', 'title'=>'BLOKADA: Informacja o blokadzie');
		$cols['P_NAME'] = array('label'=>'imie i nazwisko', 'title'=>'P_NAME');
		$cols['P_ADDRESS_STREET'] = array('label'=>'adres', 'title'=>'P_ADDRESS_STREET');
		$cols['A_STATUS'] = array('label'=>'status', 'title'=>'A_STATUS');
		$cols['A_STATUS_UPDATE_DATE'] = array('label'=>'data aktualizacji', 'title'=>'A_STATUS_UPDATE_DATE');
		$cols['PAY_SALDO'] = array('label'=>'saldo', 'title'=>'PAY_SALDO');
		$cols['PAY_FVAT'] = array('label'=>'zaległe faktury', 'title'=>'PAY_FVAT');
		$cols['PAY_DATE'] = array('label'=>'data wymagalności ostatniej faktury', 'title'=>'PAY_DATE');
		$cols['LAST_PAY_DATE'] = array('label'=>'data ostatniej wpłaty', 'title'=>'LAST_PAY_DATE');
		$cols['PAY_TERM'] = array('label'=>'termin płatności', 'title'=>'PAY_TERM');

		$out_cols = array();
		foreach ($cols as $k_field => $v_params) {
			$out_cols []= '"' . $v_params['label'] . '"';
		}
		echo implode(";", $out_cols) . "<br />\n";
		foreach ($items as $k_id => $user) {
			$out_cols = array();
			$out_cols []= '"' . $k_id . '"';
			$out_cols []= '"' . $user->is_firma . '"';
			if ($user->BILLING_OWNER == 1) {
				$out_cols []= '"' . 'BN' . '"';
			} else if ($user->BILLING_OWNER == 2) {
				$out_cols []= '"' . 'ND' . '"';
			} else {
				$out_cols []= '"' . '0' . '"';
			}
			$out_cols []= '"' . (($user->STATUS == 9)? "Z" : "0") . '"';
			$out_cols []= '"' . $user->P_NAME.' '.$user->P_NAME_SECOND . '"';
			$out_cols []= '"' . "ul. " . $user->P_ADDRESS_STREET . " " . $user->P_ADDRESS_HOUSE . "/" . $user->P_ADDRESS_HOME . ", " . $user->P_ADDRESS_POST_CODE . " " . $user->P_ADDRESS_CITY . '"';
			$out_cols []= '"' . $user->A_STATUS . '"';
			$out_cols []= '"' . $user->A_STATUS_UPDATE_DATE . '"';
			$out_cols []= '"' . (($user->PAY_SALDO != 0)? $user->PAY_SALDO . " zł" : "0") . '"';
			$out_cols []= '"' . $user->PAY_FVAT . '"';
			$out_cols []= '"' . (($user->PAY_DATE != '0000-00-00')? $user->PAY_DATE : '') . '"';
			$out_cols []= '"' . (($user->LAST_PAY_DATE && $user->LAST_PAY_DATE != '0000-00-00')? $user->LAST_PAY_DATE : '---') . '"';
			$out_cols []= '"' . (($user->PAY_TERM != '0000-00-00')? $user->PAY_TERM : '') . '"';
			echo implode(";", $out_cols) . "<br />\n";
		}
	}


	function form($q = '') {

		SEF("MENU");
		MENU();

		echo'<div class="box box-blue">';
		echo'<form action="" method="get">';
			echo'<input type="hidden" name="'."MENU_INIT".'" value="'."USERS2_WINDYKACJA_STATUS".'" />';
			echo'<p style="margin:0;">'."Wyszukaj klienta: ";
				echo'<input type="text" name="'."q".'" value="'.htmlspecialchars($q).'" />';
				echo " ".'<em>'."(imie, nazwisko lub numer klineta)".'</em>';//, adres
				echo " ".'<input type="submit" value="'."szukaj".'" />';
			echo'</p>';
		echo'</form>';
		echo'</div>';// .box-blue
	}


	function css() {
		echo'<style type="text/css">'."
body{font-family:arial;}
.box{border:1px solid #999;padding:5px;margin:5px;}
.box-center{border:1px solid #999;padding:5px;margin:5px auto;}
.box-silver{border-color:#999;}
.box-red{border-color:#f00;}
.box-blue{border-color:#00f;}
.box-green{border-color:#008000;}
.box-hover-active{background:#fff;border-color:#999;}
.box-hover-active:hover{background:#eee;border-color:#000;}

.btn-box{margin:0 2px 0 0;padding:0 3px;background:#bbb;color:#fff;text-decoration:none;border:0;font-weight:bold;}

.tbl-page-nav{font-size:small;}
 .tbl-page-nav a{font-size:small; text-decoration:none;}
 .tbl-page-nav a:hover{background-color:#eee;}

.tbl-view {margin:0;font-size:small;}
.tbl-view caption{text-align:left;font-style:italic;font-size:medium;}
.tbl-view caption em{padding:0 5px;font-size:13px;font-style:normal;}
.tbl-view th{padding:0 3px;font-size:small;}
.tbl-view td{padding:0 3px;}
.tbl-view .r{text-align:right;}
.tbl-view thead th {background:#F3F3F3;}
.tbl-view thead td {background:#F3F3F3;}
.historia-platnosci-filters thead td{text-align:center;}
.historia-platnosci-filters td.selected {background-color:#FFE6E9;}
.historia-platnosci-filters td:hover {background-color:#E6FFE6;}
.historia-platnosci-subfilters thead td{text-align:center;background:#fff;}
.historia-platnosci-subfilters td.selected {background-color:#FFE6E9;}
.historia-platnosci-subfilters td:hover {background-color:#E6FFE6;}

.tbl-td-top th,
.tbl-td-top td {vertical-align:top;}

		".'</style>';
	}


	function user_umowy( &$user ) {

		Lib::loadClass('Tree');
		Lib::loadClass('TreeHelper');
		// build tree by P_ID - array or 0
		function Tree_Helper__create_tree_rec( $p_id, &$items ) {
			static $rec_ind;
			$rec_ind++;
			$ret = array();
			if (!array_key_exists($p_id, $items)) {
				return false;
			} else {
				$r = $items[$p_id];
				if (empty($r->sub)) {
					return false;
				}
				foreach ($r->sub as $k_id => $v) {
					$ret [$k_id] = Tree_Helper__create_tree_rec( $k_id, $items );
				}//end foreach
				return $ret;
			}
		}

		function tree_callback__show_item_from_SERVICES( &$r, &$tree ) {
			$cls = array();
			$cls []= 'HANGUP_STATUS-' . $r->HANGUP_STATUS;
			$cls = (!empty($cls))? ' class="'.implode(' ', $cls).'"' : '';

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

			$out_id = ($r->ID < 10)? '&nbsp;'.$r->ID.'' : $r->ID;
			echo'<b class="item_id btn-box">'.$out_id.'</b>';
			//echo'<a href="'."?MENU_INIT=IN7_MK_BAZA_DYSTRYBUCJI_EDIT&ARG1=EDIT&ARG1_VAL=".$r->ID.'" class="btn" title="'."Edit".'">'."E".'</a>';

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

			echo'<span class="desc">';
				echo'<span class="btn-box" style="'.$st_status_bg.'">'.$r->A_STATUS.'</span>';
				echo' <b style="color:#333;">'.$r->description.'</b>';
				if ($r->ID_OFFERS) {
					echo' <code>' . "(Nr oferty: " . $r->ID_OFFERS . ")" . '</code>';
				} else {
					echo' <span style="color:#f00">'."Brak numeru oferty!".'</span>';
				}

				$st_status_bg = '';
				if ($r->HANGUP_STATUS == 'NORMAL') {
					$st_status_bg = 'background-color:#8F8;';
				} else if ($r->HANGUP_STATUS == 'WAITING') {
					$st_status_bg = 'background-color:#F8F;';
				} else if ($r->HANGUP_STATUS == 'DELETED') {
					$st_status_bg = 'background-color:#ccc;';
				} else if ($r->HANGUP_STATUS == 'OFF_SOFT') {
					$st_status_bg = 'background-color:#F99;';
				} else if ($r->HANGUP_STATUS == 'OFF_HARD') {
					$st_status_bg = 'background-color:#f00;color:#fff;';
				}
				echo ' <span class="btn-box" style="' . $st_status_bg . '">' . "{$r->HANGUP_STATUS} ({$r->HANGUP_FROM} - {$r->HANGUP_TILL}) - {$r->A_STATUS_DESC}" .'</span>';
			echo'</span>';
			echo'</dt>';
			echo'</dl>'."\n";
		}

		$uslugi_l2 = WindykacjaStatsModel::get_uslugi_from_l2( $user );
		$umowy_l2 = WindykacjaStatsModel::get_umowy_from_l2( $user );

		$uslugi_l2_nieprzypisane = array();
		foreach ($uslugi_l2 as $k_id => $h) {
			$uslugi_l2_nieprzypisane[$k_id] = true;
		}//end foreach
		if (is_array($umowy_l2) && !empty($umowy_l2)) {
			if (is_array($uslugi_l2) && !empty($uslugi_l2)) {
				foreach ($umowy_l2 as $k_umowa_ind => $h_umowa) {
					$umowy_l2[$k_umowa_ind]['uslugi'] = array();
					foreach ($uslugi_l2 as $k_id => $h_usluga) {
						if ($h_usluga['ID_DEALS_TABLE'] == $h_umowa['ID']) {
							$umowy_l2[$k_umowa_ind]['uslugi'] [$k_id] = $h_usluga;
							if (isset($uslugi_l2_nieprzypisane[$k_id])) unset($uslugi_l2_nieprzypisane[$k_id]);
						}
					}//end foreach
				}//end foreach
			}
		}

		echo'<style type="text/css">'."
.tbl-umowy-l2 .umowa-id{font-weight:bold;font-size:big;font-family:arial;}
.tbl-umowy-l2 .row-umowa td{border-top:2px solid #00f;}
.wind-status-old td,
.wind-status-old th {color:#666;}
		".'</style>';

		$ARGS['ZAPISZ'] = true;
		Lay_Html_Toggle::start( "Aktualne umowy i usługi ", array('open'=>(($ARGS['ZAPISZ'])? false : true)) );
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">umowy_l2: ';print_r($umowy_l2);echo'</pre>';
		echo'<table class="tbl-view tbl-umowy-l2" cellspacing="0" cellpadding="0" border="1">';
		//echo'<caption>'."Aktualne umowy".'<em>'." (l2)".'</em>'.'</caption>';
		if ($umowy_l2 == -1) {
			echo'<tr><td>';
				echo'<span style="color:red">'."Blad polaczenia do bazy dancyh webone_billing - Zasob [931]".'</span>';
			echo'</td></tr>';
		} else if (empty($umowy_l2)) {
			echo'<tr><td>'."Brak umów.".'</td></tr>';
		}
		else {
			$tbl_umowy_cols = 5;
			echo'<thead>';
				echo'<tr>';
					echo'<th>'."Nr umowy".'</th>';
					echo'<th>'."Prefix".'</th>';
					echo'<th>'."Data umowy".'</th>';
					echo'<th>'."Termin".'</th>';
					echo'<th>'."".'</th>';
				echo'</tr>';
			echo'</thead>';
			$t = 0;
			foreach ($umowy_l2 as $h) {
				echo'<tr class="row-umowa row-'.($t = 1 - $t).'">';
					echo'<td class="r umowa-id">' . $h['P_DEALNUMBER'] . '</td>';
					echo'<td>' . $h['P_DEALPREFIX'] . '</td>';
					echo'<td class="r">' . $h['P_DEALDATE'] . '</td>';
					echo'<td class="r">' . $h['P_DEALDATE_TERM'] . '</td>';
					echo'<td>';
						if ($h['Wcześniejszy Nr umowy']) echo "Wcześniejszy Nr umowy: ".$h['Wcześniejszy Nr umowy'].'<br />';// TODO: Undefined index
						if ($h['DEALDESC']) echo "Notatki: ".$h['DEALDESC'].'<br />';
						echo "Koniecznosc podpisania aneksu lub innego dokumentu: ".$h['ANEX_NEEDED'].'<br />';
						echo "Data potwierdzenia podpisania aneksu/dokumentu: ".$h['ANEX_CONFIRM_DATE'].'<br />';
					echo'</td>';
				echo'</tr>';
				if (!empty($h['uslugi'])) {
					// TODO: make TREE by P_ID_SERVICES
					$items = array();
					foreach ($h['uslugi'] as $k_id_usluga => $h_suluga) {
						$h_suluga['sub'] = array();
						$items [$k_id_usluga] = (object)$h_suluga;
					}//end foreach
					$uslugi_tree = array();// tree root
					foreach ($items as $k_id => $r) {
						if ($r->P_ID == 0) {
							$uslugi_tree [ $r->ID ] = array();
							if (array_key_exists($r->P_ID, $items)) {
								$items[$r->P_ID]->sub [$r->ID] = true;
							}
						} else {// array
							if (array_key_exists($r->P_ID, $items)) {
								$items[$r->P_ID]->sub [$r->ID] = true;
							}
						}
					}//end foreach
					ksort($uslugi_tree);

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

					foreach ($uslugi_tree as $k_id => $v_childrens) {
						if (array_key_exists($k_id, $items)) {
							$uslugi_tree[$k_id] = Tree_Helper__create_tree_rec( $k_id, $items );
						}
					}

					echo'<tr class="row-'.($t).'">';
						echo'<td>'."&nbsp;".'</td>';
						echo'<td colspan="'.($tbl_umowy_cols - 1).'" style="padding:0;">';
							$tree = new Tree( 'SERVICES' );
							$tree->set_parent_id_col( 'P_ID' );
							$tree->set_param('show_item_callback', "tree_callback__show_item_from_SERVICES");
							$tree->set_param('ajax', "NIE");
							$tree->set_param('rozwin', true);
							$tree->show_css();
							$tree->show_js();
							$_COOKIE[$tree->cookie_name] = implode(' ', array_keys($items));
							echo "\n".'<div class="tree-wrap">'."\n";
							$tree->show_rec_by_tree($uslugi_tree, $items);
							echo '</div>'."\n";
						echo'</td>';
					echo'</tr>';
				}
			}//end foreach
		}
		echo'</table>';

		if (!empty($uslugi_l2_nieprzypisane)) {
			echo'<table class="tbl-view tbl-umowy-l2" cellspacing="0" cellpadding="0" border="1">';
			echo'<caption>'."Nieprzypisane usługi".'<em>'." (l2)".'</em>'.'</caption>';
			echo'<head>';
				echo'<tr>';
					echo'<th>'."ID".'</th>';
					echo'<th>'."usługa".'</th>';
					echo'<th>'."status".'</th>';
					echo'<th>'."nr umowy".'</th>';
					echo'<th>'."id oferty".'</th>';
				echo'</tr>';
			echo'</head>';
			foreach ($uslugi_l2_nieprzypisane as $k_id => $v_bool) {
				$h_usluga = $uslugi_l2[ $k_id ];
				echo'<tr>';
					echo'<td class="r">' . $h_usluga['ID'] . '</td>';
					echo'<td>' . $h_usluga['description'] . '</td>';
					echo'<td>' . $h_usluga['A_STATUS_DESC'] . '</td>';
					echo'<td class="r">' . '<b>';
						if (array_key_exists($h['ID_DEALS_TABLE'], $umowy_l2)) {
							echo $umowy_l2[ $h['ID_DEALS_TABLE'] ] ['P_DEALNUMBER'];
						} else {
							//TODO: get P_DEALNUMBER from DEALS_TABLE where ID = $h['ID_DEALS_TABLE']
						}
					echo'</b>' . '</td>';
					echo'<td class="r">';
						if ($h_usluga['ID_OFFERS']) {
							echo'<code>' . $h_usluga['ID_OFFERS'] . '</code>';
						} else {
							echo'<span style="color:#f00">'."Brak!".'</span>';
						}
					echo'</td>';
				echo'</tr>';
			}//end foreach
			echo'</table>';
		}

		Lay_Html_Toggle::end();

		$umowy_l3 = WindykacjaStatsModel::get_umowy_from_l3( $user );
		$ARGS['ZAPISZ'] = true;
		Lay_Html_Toggle::start( "Aktualne usługi".'<em>'." (l3)".'</em>', array('open'=>(($ARGS['ZAPISZ'])? false : true)) );
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">umowy_l3: ';print_r($umowy_l3);echo'</pre>';
		echo'<table class="tbl-view tbl-umowy-l2" cellspacing="0" cellpadding="0" border="1">';
		if (empty($umowy_l3)) {
			echo'<tr><td>'."Brak usług.".'</td></tr>';
		}
		else {
			echo'<thead>';
				echo'<tr>';
					echo'<th rowspan="2">'."ID".'</th>';
					echo'<th rowspan="2">'."status".'</th>';
					echo'<th rowspan="2">'."data dok".'</th>';
					echo'<th rowspan="2">'."adres".'</th>';
					echo'<th rowspan="2">'."usługa".'</th>';
					echo'<th rowspan="2">'."S_OTHER_INFO".'</th>';
					echo'<th colspan="2" title="'."ID_BILLING_USERS".'">'. "nr klienta" .'</th>';
					echo'<th colspan="2" title="'."ID_SERVICES".'">'."nr usługi".'</th>';
					echo'<th colspan="2" title="'."P_OFFER_ID".'">'."nr oferty".'</th>';
					echo'<th colspan="2" title="'."P_DEAL_DATE".'">'."data umowy".'</th>';
					echo'<th colspan="2">'."nr umowy".'</th>';
					echo'<th colspan="2">'."termin umowy".'</th>';
					echo'<th colspan="2" title="'."MONTH COST".'">'."abonament".'</th>';
					echo'<th rowspan="2">'."INICJALY HANDLOWCA".'</th>';
					echo'<th rowspan="2">'."RODZAJ DZIALANIA HANDLOWEGO".'</th>';
				echo'</tr>';
				echo'<tr>';
					echo'<td>'."OLD".'</td>';
					echo'<td>'."NEW".'</td>';
					echo'<td>'."OLD".'</td>';
					echo'<td>'."NEW".'</td>';
					echo'<td>'."OLD".'</td>';
					echo'<td>'."NEW".'</td>';
					echo'<td>'."OLD".'</td>';
					echo'<td>'."NEW".'</td>';
					echo'<td>'."OLD".'</td>';
					echo'<td>'."NEW".'</td>';
					echo'<td>'."OLD".'</td>';
					echo'<td>'."NEW".'</td>';
					echo'<td>'."OLD".'</td>';
					echo'<td>'."NEW".'</td>';
				echo'</tr>';
			echo'</thead>';
			foreach ($umowy_l3 as $h) {
				echo'<tr>';
					echo'<td>' . $h['ID'] . '</td>';
					echo'<td>' . $h['A_STATUS'] . '</td>';
					echo'<td>' . '<nobr>' . $h['DATA_DOK'] . '</nobr>' . '</td>';
					echo'<td>' . $h['S_ADDRESS_STREET'] . '</td>';
					echo'<td>' . '<b>' . $h['P_SERVICE'] . '</b>' . '</td>';
					echo'<td>' . $h['S_OTHER_INFO'] . '</td>';
					echo'<td>' . $h['ID_BILLING_USERS_OLD'] . '</td>';
					echo'<td>' . $h['ID_BILLING_USERS_NEW'] . '</td>';
					echo'<td>' . $h['ID_SERVICES_OLD'] . '</td>';
					echo'<td>' . $h['ID_SERVICES_NEW'] . '</td>';
					echo'<td>' . $h['P_OFFER_ID_OLD'] . '</td>';
					echo'<td>' . $h['P_OFFER_ID_NEW'] . '</td>';
					echo'<td>' . '<nobr>' . $h['P_DEAL_DATE_OLD'] . '</nobr>' . '</td>';
					echo'<td>' . '<nobr>' . $h['P_DEAL_DATE_NEW'] . '</nobr>' . '</td>';
					echo'<td>' . $h['P_DEALNUMBER_OLD'] . '</td>';
					echo'<td>' . $h['P_DEALNUMBER_NEW'] . '</td>';
					echo'<td>' . '<nobr>' . $h['P_DEALTERM_OLD'] . '</nobr>' . '</td>';
					echo'<td>' . '<nobr>' . $h['P_DEALTERM_NEW'] . '</nobr>' . '</td>';
					echo'<td>' . $h['MONTH_COST_OLD'] . '</td>';
					echo'<td>' . $h['MONTH_COST_NEW'] . '</td>';
					echo'<td>' . $h['INICJALY_HANDLOWCA'] . '</td>';
					echo'<td>' . $h['RODZAJ_DZIALANIA_HANDLOWEGO'] . '</td>';
				echo'</tr>';
			}//end foreach
		}
		echo'</table>';
		Lay_Html_Toggle::end();
	}


	function user_historia_platnosci( &$user ) {
		echo'<style type="text/css">';
		echo"
.hide .to-hide{display:none;}
.may-hide .btn-hide{display:inline;padding:0 5px;border:1px solid #bbb;}
.may-hide .btn-show{display:none;padding:0 5px;border:1px solid #bbb;}
.hide .btn-hide{display:none;}
.hide .btn-show{display:inline;}
		";
		echo'</style>';
		Lay_Html_Toggle::show_js();

		$billing_docs = WindykacjaStatsModel::get_bill_dosc_by_date( $user );

		// add events
		$umowy_l2 = WindykacjaStatsModel::get_umowy_from_l2( $user );
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">billing_docs ';print_r($billing_docs);echo'</pre>';
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">billing_docs ';print_r(reset($billing_docs));echo'</pre>';
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">umowy_l2 ';print_r($umowy_l2);echo'</pre>';
		if (!empty($umowy_l2)) {
			foreach ($umowy_l2 as $h) {
				$billing_docs->add_event( $h['P_DEALDATE'], 'UMOWA', $h );

				if ($h['P_DEALDATE_TERM'] != '0000-00-00') {// < date('Y-m-d')) {
					$billing_docs->add_event( $h['P_DEALDATE_TERM'], 'KONIEC UMOWY', $h );
				}
			}
		}

		$user_hist_events = WindykacjaStatsHelper::get_user_hist_status_events( $user );
		if (!empty($user_hist_events)) {
			foreach ($user_hist_events as $v_hist) {
				$bill_doc = (array)$v_hist;
				$billing_docs->add_event( $v_hist->A_STATUS_UPDATE_DATE, 'HIST_STATUS', $bill_doc );
			}
		}

		$user_hist_events = WindykacjaStatsHelper::get_user_hist_phone_events( $user );
		if (!empty($user_hist_events)) {
			foreach ($user_hist_events as $v_hist) {
				$bill_doc = (array)$v_hist;
				$billing_docs->add_event( substr($v_hist->A_RECORD_UPDATE_DATE, 0, 10), 'HIST_PHONE', $bill_doc );
			}
		}

		$user_hist_events = WindykacjaStatsHelper::get_user_bad_address_events( $user );
		if (!empty($user_hist_events)) {
			foreach ($user_hist_events as $v_hist) {
				$bill_doc = (array)$v_hist;
				$billing_docs->add_event( substr($v_hist->A_RECORD_UPDATE_DATE, 0, 10), 'HIST_BAD_ADDRESS', $bill_doc );
			}
		}

		// add today
		$bill_doc = array();
		$bill_doc['saldo'] = $billing_docs->get_saldo();
		$billing_docs->add_event( date('Y-m-d'), 'TODAY', $bill_doc );

		$billing_docs->sort_docs();
		//$billing_docs = array_reverse($billing_docs, true);
		//echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;">billing_docs: ';print_r($billing_docs);echo'</pre>';

		$billing_docs_arr = $billing_docs->get_docs();

		$types_finanse = array();
		$types_finanse []= 'KW';
		$types_finanse []= 'KP';
		$types_finanse []= 'WB_MASS';
		$types_finanse []= 'WB';
		$types_finanse []= 'KORV';
		$types_finanse []= 'FVAT';

		$saldo_all = 0;
		$out_tbl = array();
		foreach ($billing_docs_arr as $k_data => $v_docs_arr) {
			foreach ($v_docs_arr as $k_ind => $v_doc) {
				$out_tr = array();
				$out_tr ['data'] = $k_data;
				if ($k_data == date("Y-m-d")) $out_tr ['class'] = 'today';
				$out_tr ['ID'] = '';
				$out_tr ['nr'] = '';
				$out_tr ['winien'] = '';
				$out_tr ['ma'] = '';
				$out_tr ['saldo'] = '';
				$out_tr ['saldo_all'] = '';
				if ($v_doc->get_class() == 'BILLING') {
					$saldo_all += $v_doc->get_saldo();
					$out_tr ['ID'] = $v_doc->get_type();
					$type_desc = WindykacjaStatsModel::get_billing_type_desc( $v_doc->get_type() );
					if ($type_desc) {
						if ($v_doc->get_type() == 'FVAT') $type_desc .= "\n Wystawiona: ".$v_doc->get('BILL_DATE')."\n Termin płatności: ".$v_doc->get('PAYMENT_TERM');
						$out_tr['ID'] = '<span title="'.$type_desc.'">'.$out_tr['ID'].'</span>';
						// TODO: podglad faktury
						//if ($h['type'] == 'FVAT') $out_tr['ID'] .= ' <a href="'."?MENU_INIT=USERS2_WINDYKACJA_STATUS&_user_id=".$user->ID."&task=view_faktura&id=".$h['ID'].'" target="_blank">'.'<img src="'."icon/search.png".'" alt="'."U".'" title="'."Podgląd faktury".'" />'.'</a>';
					}
					$out_tr ['ID'] .= ' <code style="font-size:10px">'."(".$v_doc->get('ID').")".'</code>';// TODO: dla KP,KW: ID_BILLING_NUMBERS zamiast ID
					$out_tr ['nr'] = $v_doc->get('nr');
					$out_tr ['winien'] = number_format($v_doc->get('WINIEN'), 2, ',', ' ');
					$out_tr ['ma'] = number_format($v_doc->get('MA'), 2, ',', ' ');
					$out_tr ['saldo'] = number_format($v_doc->get_saldo(), 2, ',', ' ');
					$out_tr ['saldo_all'] = number_format($saldo_all, 2, ',', ' ');

					// style
					if ($out_tr['winien'] == '0,00') $out_tr['winien'] = '<span style="color:#666;">' . $out_tr['winien'] . '</span>';
					if ($out_tr['ma'] == '0,00') $out_tr['ma'] = '<span style="color:#666;">' . $out_tr['ma'] . '</span>';
				}
				else if ($v_doc->get_class() == 'EVENT') {
					if ($v_doc->get_type() == 'TODAY') {
						$out_tr ['class'] = 'today';
						$v_doc_saldo = V::get('saldo', '', $v_doc->get_data());
						$out_tr ['saldo_all'] = number_format($v_doc_saldo, 2, ',', ' ');
					}
					else if ($v_doc->get_type() == 'HIST_STATUS') {
						// search for koresp files
						// TODO: mv to ::get_koresp_file( $id_koresp );
						$id_koresp = intval($v_doc->get('ID_KORESP'));
						$found_files = array();
						{
							$CNF = new stdClass();
							$CNF->koresp_dir = '/home/samba/BIALL-NET/PISMA/OUT';
							$CNF->koresp_www_path = '/se-dev/PISMA/OUT';
							if ($id_koresp > 0) {
								$pattern = $CNF->koresp_dir . '/' . '*.' . $id_koresp . '.pdf';
								$file_tmp_list = glob($pattern);//, GLOB_NOSORT);
								if (!empty($file_tmp_list)) {
									foreach ($file_tmp_list as $v_file) {
										$test_file = end( explode('/', $v_file) );
										$found_files []= $CNF->koresp_www_path . '/' . $test_file;
									}//end foreach
								}
							}
						//	return $found_files;
						}
						switch ($v_doc->get('A_STATUS')) {
							case 'WAITING':
								$out_tr ['add'] = "powrót do oczekujących";
								break;

							case 'waiting-wezwanie2':
								$out_tr ['add'] = "wezwanie do zapłaty - ID_KORESP: <b>".$v_doc->get('ID_KORESP')."</b> <em>(termin: ".$v_doc->get('PAY_TERM').")</em> ";
								break;

							case 'waiting-krd':
								$out_tr ['add'] = "wezwanie do zapłaty ost. - ID_KORESP: <b>".$v_doc->get('ID_KORESP')."</b> <em>(termin: ".$v_doc->get('PAY_TERM').")</em> ";
								break;

							case 'N/S;':
								$out_tr ['add'] = "ID_KORESP: <b>".$v_doc->get('ID_KORESP')."</b> <em>(" . $v_doc->get('K_ZAWARTOS') . ")</em>";// TODO: get opis from koresp
								//echo '('.$v_doc->get('ID_KORESP').', '.$v_doc->get('K_ZAWARTOS').'='.substr($v_doc->get('K_ZAWARTOS'), 0, strlen('rozwiazanie umowy')).')';
								if ($v_doc->get('ID_KORESP') > 0 && substr($v_doc->get('params'), 0, strlen('rozwiazanie umowy')) == 'rozwiazanie umowy') {
									$out_tr ['add'] .= " " . '<a href="'."?MENU_INIT=USERS2_WINDYKACJA_STATUS&q=".V::get('q','', $_REQUEST)."&task="."bok_rozwiazanie_umowy_print"."&user_id=".$user->ID."&id_koresp=".$v_doc->get('ID_KORESP').'" target="_blank" title="' . "Generuj druk rozwiązania umowy" . '">' . "druk" . '</a>';
								}
								break;

							default:
								$out_tr ['add'] = "zmiana statusu na: ".$v_doc->get('A_STATUS')." ";
						}
						if ($id_koresp > 0) {
							if (!empty($out_tr ['add']) && !empty($found_files)) {
								$add_link_koresp = reset($found_files);// first file from koresp
								$out_tr ['add'] .= " " . '<a href="' . $add_link_koresp . '" target="_blank">' . "P" . '</a>';
							}
							//$koresp_edit_link = "?MENU_INIT=IN7_DZIENNIK_KORESP_EDIT&ARG1=EDIT&ARG1_VAL=" . $id_koresp;
							Lib::loadClass('ProcesHelper');
							$zasobKorespID = ProcesHelper::getZasobTableID('IN7_DZIENNIK_KORESP');
							$koresp_edit_link = "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$zasobKorespID}#EDIT/{$id_koresp}";
							$out_tr ['add'] .= " " . '<a href="' . $koresp_edit_link . '" title="' . "Edycja KORESP. (" . $id_koresp . ")" . '" target="_blank">' . "KOR" . '</a>';
						}
					}
					else if ($v_doc->get_type() == 'HIST_PHONE') {
						$date = $v_doc->get('PAY_TERM');
						if ($date == 'N/S;') $date = '';
						switch ($v_doc->get('LAST_PHONE_STATUS')) {
							case 'nie_zaplaci':
								$out_tr ['add'] = "nie zapłaci";
								break;

							case 'zaplaci_w_terminie':
								$out_tr ['add'] = "zapłaci w terminie " . $date . " " . '<em style="font-size:small;">' . "(ustalono " . $v_doc->get('A_RECORD_UPDATE_DATE') . ")" . '</em>';
								break;

							case 'zaplaci_za_1mc':
								$out_tr ['add'] = "zapłaci miesiąc później " . $date . " " . '<em style="font-size:small;">' . "(ustalono " . $v_doc->get('A_RECORD_UPDATE_DATE') . ")" . '</em>';
								break;

							case 'zaplaci_za_2mc':
								$out_tr ['add'] = "zapłaci 2 miesiące później " . $date . " " . '<em style="font-size:small;">' . "(ustalono " . $v_doc->get('A_RECORD_UPDATE_DATE') . ")" . '</em>';
								break;

							case 'zaplaci_za_3mc':
								$out_tr ['add'] = "zapłaci 3 miesiące później " . $date . " " . '<em style="font-size:small;">' . "(ustalono " . $v_doc->get('A_RECORD_UPDATE_DATE') . ")" . '</em>';
								break;

							default:
								$out_tr ['add'] = "kontakt z klientem: " . $v_doc->get('LAST_PHONE_STATUS') . " " . '<em style="font-size:small;">' . "(ustalono " . $v_doc->get('A_RECORD_UPDATE_DATE') . ")" . '</em>';
						}
					} else if ($v_doc->get_type() == 'HIST_BAD_ADDRESS') {
						if ($v_doc->get('BAD_ADDRESS')) {
							$out_tr ['add'] = "błędny adres zameldowania ";
						} else {
							$out_tr ['add'] = "poprawa adresu zameldowania ";
						}
						if ($v_doc->get('ID_KORESP') > 0) {
							$out_tr ['add'] .= " - ID Koresp. (" . '<a href="' . "index.php?MENU_INIT=IN7_DZIENNIK_KORESP_EDIT&ARG1=EDIT&ARG1_VAL=" . $v_doc->get('ID_KORESP') . '" target="_blank">' . $v_doc->get('ID_KORESP') . '</a>' . ")";
						}
					} else {
						$out_tr ['ID'] = $v_doc->get_type().' <code style="font-size:10px">'."(".$v_doc->get('ID').")".'</code>';// TODO: dla KP,KW: ID_BILLING_NUMBERS zamiast ID
						if ($v_doc->get_type() == 'UMOWA') {
							$out_tr ['add'] = "umowa nr <b>".$v_doc->get('P_DEALNUMBER')."</b> <em>(termin ".$v_doc->get('P_DEALDATE_TERM').")</em>";
						} else if ($v_doc->get_type() == 'KONIEC UMOWY') {
							$out_tr ['add'] = "zakończenie umowy nr <b>".$v_doc->get('P_DEALNUMBER')."</b> <em>(z dnia ".$v_doc->get('P_DEALDATE').")</em>";
						}
					}
				}
				//$out_tbl []= $out_tr;// add to the end
				array_unshift($out_tbl, $out_tr);// add to the begining
			}//end foreach
		}//end foreach

		echo'<style type="text/css">'."
.tbl-windykacja td{padding:0 5px;}
.tbl-windykacja .cell-data{white-space:nowrap;}
.tbl-windykacja .cell-winien{text-align:right;}
.tbl-windykacja .cell-ma{text-align:right;}
.tbl-windykacja .cell-saldo{text-align:right;}
.tbl-windykacja .cell-saldo_all{text-align:right; white-space:nowrap; background-color:#E5E5E5;}
.tbl-windykacja .cell-nr{font-family:monospace;text-align:right;}
.tbl-windykacja .change-year td{border-top:3px solid #00f;}
.tbl-windykacja .today td{background:#FFFF98;}
.tbl-windykacja .cell-add em{color:#666;}
		".'</style>';
		$last_year = '';
		$cols = array();
		$cols ['data'] = "data";
		$cols ['ID'] = "ID";
		$cols ['nr'] = "nr";
		$cols ['winien'] = "winien";
		$cols ['ma'] = "ma";
		//$cols ['saldo'] = "saldo";
		$cols ['saldo_all'] = "saldo";
		$cols ['add'] = "uwagi";
		echo'<h4>'."Historia płatności".'<em>'." (l1)".'</em>'.'</h4>';
		echo'<table border="1" class="tbl-view tbl-windykacja" cellspacing="0" cellpadding="0">';
		echo'<thead>';
			echo'<tr>';
			echo'<th>'."rok".'</th>';
			foreach ($cols as $col_name => $col_label) {
				echo'<th>' . $col_label . '</th>';
			}//end foreach
			echo'</tr>';
		echo'</thead>';
		foreach ($out_tbl as $out_tr) {
			$change_year = false;
			$k_data = $out_tr['data'];
			$rok = substr($k_data, 0, 4);
			if ($rok != $last_year) {
				$change_year = true;
			}
			$cls = array();
			if ($change_year) $cls []= 'change-year';
			if ($add_cls = V::get('class', '', $out_tr)) $cls []= $add_cls;
			$cls = (!empty($cls))? ' class="'.implode(' ', $cls).'"' : '';
			echo'<tr'.$cls.'>';
			echo'<td>';
			echo ($change_year)? $rok : "&nbsp;";
			echo'</td>';
			$last_year = $rok;
			foreach ($cols as $col_name => $col_label) {
			//foreach ($out_tr as $k_col_name => $v_val) {
				if (array_key_exists($col_name, $out_tr)) {
					echo'<td class="'."cell-".$col_name.'">' . $out_tr[$col_name] . '</td>';
				} else {
					echo'<td>'."&nbsp;".'</td>';
				}
			}//end foreach
			echo'</tr>';
		}//end foreach
		echo'</table>';
		echo'<br />';
		echo'<br />';
		WindykacjaStatsHelper::update_stats( $user, $billing_docs );
	}


	function view_faktura( $faktura_id ) {
		// https://l1.webone.pl/modules/make_billing/edit.php?mod=make_billing&form=make_faktura&adm=edit&uid=11381&fpos=&dz=
		// https://l1.webone.pl/modules/make_billing/edit.php?mod=make_billing&form=html_faktura&adm=edit&uid=11381&fpos=&dz=&close=0&doc=483930&doctype=1
		echo'{'.$faktura_id.'}';
	}


	function zadluzenia( &$user ) {
		$THIS_DATA_DO = null;// TODO: pobierac z PAY_TERM z tabeli USERS2_WINDYKACJA_STATUS
		$post_sent = (!empty($_POST['sbmt']));
		$post_DATA_DO = (isset($_POST['DATA_DO']))? $_POST['DATA_DO'] : date("Y-m-d", mktime(0,0,0,date('m'), date('d') + 14, date('Y')));
		if (!$post_sent) {
			echo'<table style="margin:10px 50px;padding:20px;border:1px solid blue;"><tr><td>';
			echo'<form action="" method="post">';
				$post_DATA_DO = (isset($_POST['DATA_DO']) && strlen($_POST['DATA_DO']) == 10)? $_POST['DATA_DO'] : date("Y-m-d", mktime(0,0,0,date('m'), date('d') + 14, date('Y')));
				echo'<p>'."Termin płatności: ".'</p>';
				echo'<input type="text" name="'."DATA_DO".'" value="'.$post_DATA_DO.'" />';
				echo'<input type="submit" name="sbmt" value="'."Wyslij".'" />';
			echo'</form>';
			echo'</td></tr></table>';
			return;
		} else {
			$THIS_DATA_DO = $post_DATA_DO;
		}
		self::wezwanie( $user, $THIS_DATA_DO );
	}


	function wezwanie_ostateczne( &$user, $wezwanie_termin ) {
		self::wezwanie( $user, $wezwanie_termin, true );
	}


	function wezwanie( &$user, $wezwanie_termin, $wezwanie_ostateczne = false ) {
		$date_limit = date("Y-m-d");
		$billing_docs = WindykacjaStatsModel::get_bill_dosc_by_date( $user, $date_limit );

		$billing_docs->sort_docs();

		// sprawdz zadluzenie
		if ($billing_docs->get_saldo() >= 0) {
			echo'<p class="green">' . "Brak zadluzenia" . '</p>';
			return;
		}
		else {
			$fvat_arr = $billing_docs->get_unpaid_fvat();
			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">saldo('.$billing_docs->get_saldo().') fvat_arr: ';print_r($fvat_arr);echo'</pre>';
			//foreach ($fvat_arr as $key => $v) {
			//	echo'<br />'.number_format($v['WINIEN_POZOSTALO'], 4, ',', ' ');
			//}//end foreach

			if (empty($fvat_arr)) {
				echo'<p>'."Brak nieoplaconych faktur".'</p>';
				return;
			}

			WindykacjaStatsModel::update_doc_number( $fvat_arr );

			$cols = array();
			$cols ['ID'] = "ID";
			$cols ['nr'] = "nr";
			$cols ['winien'] = "winien";
			$cols ['ma'] = "ma";
			//$cols ['saldo'] = "saldo";
			$cols ['saldo_all'] = "saldo";
			$cols ['add'] = "&nbsp;";

			$saldo_all = 0;
			foreach ($fvat_arr as $f) {
				$saldo_all += round($f['WINIEN_POZOSTALO'], 2);
			}

			$out_tbl = array();
			foreach ($fvat_arr as $v_fvat) {
				$out_tr = array();
				$out_tr ['ID'] = ' <code style="font-size:10px">'."(".$v_fvat['ID'].")".'</code>';// TODO: dla KP,KW: ID_BILLING_NUMBERS zamiast ID
				$out_tr ['nr'] = $v_fvat['NUMBER'] . '/' . $v_fvat['ID_BILLING_PREFIXES'];
				$out_tr ['winien'] = number_format($v_fvat['WINIEN'], 2, ',', ' ');
				$out_tr ['data'] = $v_fvat['BILL_DATE'];
				$out_tr ['termin'] = $v_fvat['PAYMENT_TERM'];
				$out_tr ['pozostalo'] = number_format($v_fvat['WINIEN_POZOSTALO'], 2, ',', ' ');
				array_unshift($out_tbl, $out_tr);// add to the begining
			}

			$razem = $saldo_all;

			$company = WindykacjaStatsModel::get_company( $user );

			$nr_konta = FunkcjeL1::bankowy_formatuj_nrach(FunkcjeL1::bankowy_make_nrach($company->NR_RACH_MASS_PAY, $user->ID_BILLING_USERS, 0));

			echo'<style type="text/css">'."
body{font-family:serif; font-size:10px;line-height:14px;}
td{font-family:verdana; font-size:10px; color:#333;}
table {border-style:none;}
table td, table th {padding:0 2px;border-style:solid;border-collapse:collapse;}
table th {border-width:1px;border-color:#333;}
table td {border-width:1px;border-color:#333;}
			".'</style>';

		echo'<div style="background:#fff;border:none;margin:5px;padding:20px 40px 10px 40px;page-break-after:always;font-size:small;">';
		if ($user->ID_KORESP) {
			$koresp = DB::get_by_id('IN7_DZIENNIK_KORESP', $user->ID_KORESP);
			if ($koresp) {
				echo '<div style="text-align:right;font-weight:bold;">';
					echo $koresp->ID_PROJECT . '-' .$koresp->ID . "/" . substr(date("Y"), 2);
				echo '</div>';
			}
		}

			echo '<table border=0 cellspacing=0 cellpadding=0 style="width:100%;">';
				echo'<tr>';
					echo'<td style="width:60%;border:none;">';
						//echo "&bdquo;BIALL-NET&rdquo; Sp. z o.o.<br />Otomin, ul. Słoneczna 43<br />80-174 Gdańsk";
						echo $company->name1 . '<br />' . "ul. " . $company->ulica . " " . $company->numer_dom . '<br />' . $company->kod . " " . $company->miasto;
					echo'</td>';
					echo'<td style="border:none;text-align:left;vertical-align:top;">';
						echo "Gdańsk, dnia ".date("Y-m-d");
					echo'</td>';
				echo'</tr>';
				echo'<tr>';
					echo'<td style="border:none;">'."&nbsp;".'</td>';
					echo'<td style="border:none;">';
						echo'<p style="margin:50px 0;">';
							echo "Numer klienta: ".$user->ID;
							echo '<br />'."".$user->P_NAME." ".$user->P_NAME_SECOND;
// TODO: P_ADRESS_KORESP_1282
							echo '<br />'."ul. ".$user->P_ADDRESS_STREET." ".$user->P_ADDRESS_HOUSE;
							if ($user->P_ADDRESS_HOME) echo "/".$user->P_ADDRESS_HOME;
							echo '<br />' . $user->P_ADDRESS_POST_CODE . " " . $user->P_ADDRESS_CITY;
						echo'</p>';
					echo'</td>';
				echo'</tr>';
			echo'</table>';

			echo'<h1 style="text-align:center;margin:20px 10px 10px 10px;font-size:28px;">';
				if ($wezwanie_ostateczne) {
					echo "OSTATECZNE WEZWANIE DO ZAPŁATY";
				} else {
					echo "WEZWANIE DO ZAPŁATY";
				}
			echo'</h1>';
			echo'<p style="margin:10px;">'."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Na podstawie art. 476 Kodeksu cywilnego (Dz. U. z 1964 r. nr 16, poz. 93, z późn. zmianami) wzywamy do natychmiastowego uregulowania należnej sumy, zgodnie z poniższym zestawieniem.	".'</p>';

			echo '<table border=0 cellspacing=0 cellpadding=2 style="width:100%;margin:10px;font-size:small;">';
			echo '<thead style="background:#F3F3F3;">';
				echo '<tr>';
					echo '<th>'."Podstawa zobowiązania*".'</th>';
					echo '<th>'."Nr dokumentu".'</th>';
					//echo '<th>'."Kwota netto".'</th>';
					echo '<th>'."Kwota brutto".'</th>';
					echo '<th>'."Data faktury".'</th>';
					echo '<th>'."Termin płatności".'</th>';
					echo '<th>'."Pozostało do zapłaty".'</th>';
				echo '</tr>';
			echo '</thead>';
			echo '<tfoot>';
				echo'<tr>';
					echo'<td colspan="4" style="border:none;"></td>';
					echo'<th style="border-width:2px;border-color:#333;text-align:right;background:#F3F3F3;">'."Razem:".'</th>';
					echo'<td style="border-width:2px;border-color:#333;font-weight:bold;">'.FunkcjeL1::formatuj_grosze($razem).'</td>';
				echo'</tr>';
			echo '</tfoot>';
				echo "\n";
				foreach ($out_tbl as $out_tr) {
					$k_data = $out_tr['data'];
					$rok = substr($k_data, 0, 4);
					$cls = array();
					if ($add_cls = V::get('class', '', $out_tr)) $cls []= $add_cls;
					$cls = (!empty($cls))? ' class="'.implode(' ', $cls).'"' : '';
					echo'<tr'.$cls.'>';
					echo'<td>';
						echo "Faktura Vat";
					echo'</td>';
//$file_total['PODSTAWA_NUMBER'] = $r['NUMBER']."/".$r['ID_BILLING_PREFIXES'];
//$file_total['PODSTAWA_DATA'] = date("Y-m-d",$r['BAF_TIMESTAMP']);
//$file_total['PAYMENT_TERM'] = date("Y-m-d",$r['TERMIN_PL']);
					echo'<td>';
						echo $out_tr['nr'];
					echo'</td>';
					echo'<td>';
						echo $out_tr['winien'];
					echo'</td>';
					echo'<td>';
						echo '<nobr>' . $out_tr['data'] . '</nobr>';
					echo'</td>';
					echo'<td>';
						echo '<nobr>' . $out_tr['termin'] . '</nobr>';
					echo'</td>';
					echo'<td>';
						echo $out_tr['pozostalo'];
					echo'</td>';
					echo'</tr>';
					echo "\n";
				}//end foreach
			echo '</table>';
			echo'<p style="margin:10px;">'."Słownie do zapłaty: ".'<span style="border-bottom:1px dotted #000;padding:0 50px;">'."&nbsp;&nbsp;".'<b>'.FunkcjeL1::slownie($razem).'</b>'."&nbsp;&nbsp;".'</span>'.'</p>';
			echo'<p style="margin:10px;background:#eee;text-align:center;">'."Wymienioną sumę prosimy przekazać na nasz rachunek bankowy <br />".$nr_konta."  w terminie do dnia ".'<span style="border-bottom:1px dotted #000;padding:0 50px;">'."&nbsp;&nbsp;".'<b>'.$wezwanie_termin.'</b>'."&nbsp;&nbsp;".'</span>'.'</p>';
			echo'<ul style="margin:10px;font-size:small;padding:0 0 0 40px;">';
				echo'<li style="line-height:16px;">'."Od nieterminowych płatności mogą zostać naliczone odsetki ustawowe (art.481 § 1 KC).".'</li>';
				echo'<li style="line-height:16px;">'."W przypadku nieterminowej zapłaty nabywca zostanie obciążony wszelkimi kosztami windykacji oraz postępowania sądowego, które zostaną poniesione przez sprzedawcę w celu odzyskania należności.".'</li>';
				echo '<li style="line-height:16px;">' . "W przypadku uregulowania należności przed otrzymaniem niniejszego wezwania, proszę potraktować je za bezprzedmiotowe." . '</li>';
			echo'</ul>';

			echo'<table style="width:100%;border:none">';
			echo'<tr>';
				echo'<td colspan="2" style="border:none;">';
					echo'<p style="margin:5px 0;font-size:10px;">'."W razie problemów prosimy o kontakt z Biurem Obsługi Klienta tel. (58) 741-84-10 wew. 2,
<br> e-mail: bok@biall.net.pl lub z Windykatorem: tel. 513-156-732, (58) 741-84-78".'</p>';
				echo'</td>';
			echo'</tr>';
			echo'</table>';

			echo'<table style="width:100%;border:none">';
			echo'<tr>';
				echo'<td style="width:50%;border:none;">'."&nbsp;".'</td>';
				echo'<td style="width:50%;border:2px solid #999">'."<br /><br /><br /><br />".'</td>';
			echo'</tr>';
			echo'<tr>';
				echo'<td style="border:none;">'."&nbsp;".'</td>';
				echo'<td style="text-align:center;border:none;">'."(pieczęć i podpis wierzyciela)".'</td>';
			echo'</tr>';
			echo'<tr>';
				echo'<td colspan="2" style="border:none;">';
					echo'<p style="margin:10px 0;font-size:xx-small;">'."* Podstawa zobowiązania: Faktura VAT, Rachunek, Umowa, Nota odsetkowa, Nota księgowa,  Weksel, Uznanie długu, Ugoda, Kara umowna, Faktura zbiorowa, Wyrok sądowy, Nakaz zapłaty, Pożyczka, inne.".'</p>';
				echo'</td>';
			echo'</tr>';
			echo'<tr>';
				echo'<td colspan="2" style="border:none">';
					echo'<p style="margin:8px 0;font-size:x-small;text-align:center">'."W przypadku nieuregulowania płatności we wskazanym terminie, zgodnie z &bdquo;Ustawą o udostępnianiu informacji gospodarczych z dnia 14 lutego 2003 r. (Dz. U. Nr 50)&rdquo; , informacje o zadłużeniu zostaną przekazane do:".'</p>';
					echo'<p style="margin:8px 0 0 0;font-size:small;text-align:center">'."<b>Krajowego Rejestru Długów<br />
Biura Informacji Gospodarczej S.A.<br />
ul. Armii Ludowej 21, 51-214 Wrocław<br />
www.krd.pl</b>
<br />
<br />
Informacja o zadłużeniu upubliczniona będzie w systemie KRD do dnia zapłaty  lub 10 lat od daty dokonania wpisu.".'</p>';
				echo'</td>';
			echo'</tr>';
			echo'</table>';
		echo'</div>';
		}
	}


	function task_update_stats() {
		self::css();
		$to_update_step = 500;
		$q = V::get('q', '', $_GET);
		$_p = V::get('_p', 0, $_GET, 'int');
		echo'<a href="' . "?MENU_INIT=USERS2_WINDYKACJA_STATUS&q=".$q."&_p=".$_p . '">' . "Cofnij" . '<img src=icon/back.gif border=0 alt=POWROT>' . '</a>';

		$to_update_total = WindykacjaStatsHelper::get_to_update_total();
		if ($to_update_total <= 0) {
			echo'<p style="color:green">' . "Wszystkie rekordy zaktualizowane" . '</p>';
			return;
		}

		if ($to_update_total > $to_update_step) {
			echo'<br />';
			echo'<a style="color:red" href="' . "?MENU_INIT=USERS2_WINDYKACJA_STATUS&task=stats_update&q=".$q."&_p=".$_p . '">' . "Aktualizuj statusy (" . ($to_update_total - $to_update_step) . ")" . '</a>';
			echo'<br />';
		}

		$to_update_list = WindykacjaStatsHelper::get_to_update_list( $to_update_step );
		if (empty($to_update_list)) {
			echo'<p style="color:green">' . "Wszystkie rekordy zaktualizowane" . '</p>';
			return;
		}
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">to_update_list: ';print_r($to_update_list);echo'</pre>';
		foreach ($to_update_list as $w) {
			//echo'<div class="box box-blue">';
				echo "Nr. klienta: <b>".$w->ID_BILLING_USERS . "</b> ...";
				//echo $w->A_STATUS . ' (' . $w->A_STATUS_UPDATE_DATE . ')';
				$user = WindykacjaStatsModel::get_user_by_id( $w->ID_BILLING_USERS );
				if ($user) {
					$billing_docs = WindykacjaStatsModel::get_bill_dosc_by_date( $user );
					WindykacjaStatsHelper::update_stats( $user, $billing_docs );
				}
			//echo'</div>';// .box-blue
				echo'<br />';
		}//end foreach

		if ($to_update_total > $to_update_step) {
			echo'<br /><br />';
			echo'<a style="color:red" href="' . "?MENU_INIT=USERS2_WINDYKACJA_STATUS&task=stats_update&q=".$q."&_p=".$_p . '">' . "Aktualizuj statusy (" . ($to_update_total - $to_update_step) . ")" . '</a>';
		}
	}

	/**
	 * @params $user
	 * @params $id_koresp
	 */
	function task_bok_rozwiazanie_umowy_print( $user, $id_koresp ) {
		$user_hist_events = WindykacjaStatsHelper::get_user_hist_status_events($user);
		if (empty($user_hist_events)) {
			echo '<p style="color:red">' . "Brak danych HIST" . '</p>';
			return;
		}
		$v_doc = null;
		foreach ($user_hist_events as $v_hist) {
			if ($v_hist->ID_KORESP == $id_koresp) {
				$v_doc = $v_hist;
				break;
			}
		}
		if (!$v_doc) {
			echo '<p style="color:red">' . "Brak danych HIST dla kodresp(".$v_doc->ID_KORESP.")" . '</p>';
			return;
		}

		// params(255): rozwiazanie umowy,9872,3121
		$params = explode(',', $v_doc->params);
		if (count($params) < 3 && $params[0] != 'rozwiazanie umowy') {
			echo '<p style="color:red">' . "Bad params" . '</p>';
			return;
		}

		$koresp = DB::get_by_id('IN7_DZIENNIK_KORESP', $id_koresp);
		if (!$koresp) {
			echo '<p style="color:red">' . "Koresp not exists!" . '</p>';
			return;
		}

		$nr_umowy = $params[1];
		$powod = $params[2];

		$deal_id = '..........................................................';
		$termin_odlaczenia = '.....................';
		if (count($params) > 4) {
			// $data_arr["params"] = "rozwiazanie umowy,{$nr_umowy},{$powod},{$termin_odlaczenia},{$new_id_deals}";
			$termin_odlaczenia = $params[3];
			$deal_id = $params[4];
		}

		$arg_values = array();
		$arg_values['powod'] = array();// [774].[800] - USERS2_DEALS.RODZAJ_DZIALANIA_HANDLOWEGO
//		$arg_values['powod'] ['3226'] = "Finansowe";
//		$arg_values['powod'] ['3227'] = "Niesatysfakcjonująca oferta";
//		$arg_values['powod'] ['3121'] = "Przeprowadzka";
//		$arg_values['powod'] ['3228'] = "Problemy techniczne/awarie";
//		$arg_values['powod'] ['3230'] = "Wyjazd";
//		$arg_values['powod'] ['3229'] = "Zła obsługa BOK/DT";
//		$arg_values['powod'] ['3119'] = "Inne";

		// [895].[3888] - DEALS_TABLE.RODZAJ_DZIALANIA_HANDLOWEGO
		$arg_values['powod']['4192'] = "REZYGNACJA ZMIANA OPERATORA";
		$arg_values['powod']['4193'] = "REZYGNACJA WYPROWADZKA";
		$arg_values['powod']['4194'] = "REZYGNACJA NIEZADOWOLENIE";
		$arg_values['powod']['4195'] = "REZYGNACJA CESJA";
		//$arg_values['powod']['4196'] = "REZYGNACJA FINANSE";
		$arg_values['powod']['4197'] = "REZYGNACJA SLABA OFERTA";
		$arg_values['powod']['4198'] = "REZYGNACJA PROBLEMY TECHNICZNE";
		$arg_values['powod']['4199'] = "REZYGNACJA ZLA OBSLUGA BOK";
		$arg_values['powod']['4200'] = "WYPOWIEDZENIE PRZEZ OPERATORA ZA DLUGI";
		//$arg_values['powod']['4202'] = "REZYGNACJA WYJAZD";
		// $arg_values['powod']['4191'] = "BRAK-BOK (Inne)";
		$arg_values['powod']['4213'] = "REZYGNACJA INNE";

		$com = new stdClass();
		if ($user->BILLING_OWNER == 2) {
			$com->name = 'NET-DAY';
			$com->fullName = 'NET-DAY Sp. z o.o.';
		} else {
			$com->name = 'BIALL-NET';
			$com->fullName = 'BIALL-NET Sp. z o.o.';
		}

		?>
		<style type="text/css">
body{margin:12px;font-family:serif;font-size:11px;line-height:14px;}
td{font-family:verdana; font-size:10px; color:#333;}
table {border-style:none;}
table td, table th {padding:0 2px;border-collapse:collapse;}
table.tbl-bordered {border-style:none;}
table.tbl-bordered td, table.tbl-bordered th {padding:0 2px;border-style:solid;border-collapse:collapse;}
table.tbl-bordered th {border-width:1px;border-color:#333;}
table.tbl-bordered td {border-width:1px;border-color:#333;}
		</style>

		<table cellspacing="0" cellpadding="0" border="0" style="width:100%;"><tr>
			<td>[1612][v3]</td>
			<td style="text-align:right">Nr dziennika przyjęcia pisma <?php echo $com->fullName; ?> <?php echo $koresp->ID_PROJECT; ?>-<?php echo $koresp->ID; ?>/<?php echo substr(date("Y"), 2); ?>
				<br />Gdańsk, dnia: .......................
			</td>
		</tr></table>
		<br /><b>Dane Abonenta</b>
		<br />Imię i Nazwisko / Nazwa firmy: <?php echo "{$user->P_NAME} {$user->P_NAME_SECOND}";?>
		<br />Pesel / nr dowodu osoby reprezentującej firmę: <?php echo $user->P_PESEL; ?>
		<br />Adres zameldowania: ul. <?php echo "{$user->P_ADDRESS_STREET} {$user->P_ADDRESS_HOUSE}/{$user->P_ADDRESS_HOME}, {$user->P_ADDRESS_POST_CODE} {$user->P_ADDRESS_CITY}"; ?>

		<br />Nr ID klienta: <?php echo $user->ID; ?>
		<br />Nr ID Umowy: <?php echo $deal_id; ?>
		<?php
			// <br />ID_SERVICES_OLD: .......................................................... 
		?>
		<table cellspacing="0" cellpadding="0" border="0" style="width:100%;margin:40px 0;"><tr>
			<td>&nbsp;</td>
			<td style="width:260px;text-align:left">
				<?php echo $com->fullName; ?><br />Otomin ul. Słoneczna 43<br />80-174 Gdańsk
			</td>
		</tr></table>
		<p style="margin:50px 0; text-align:center;">ROZWIĄZANIE UMOWY ABONENCKIEJ O ŚWIADCZENIE USŁUG TELEKOMUNIKACYJNYCH NR <sup>[794]</sup></p>
		<p style="margin:0 0 50px 0;text-indent:50px">Proszę o rozwiązanie umowy abonenckiej o świadczeniu Usług Telekomunikacyjnych i odłączenie sygnału <?php echo $com->fullName; ?>. Jednocześnie jestem świadomy/a tego, że jeżeli okres trwania wypowiadanej umowy jeszcze nie uległ zakończeniu to firma <?php echo $com->name; ?> może naliczyć karę za wcześniejsze zerwanie umowy zgodnie z obowiązującym regulaminem i cennikiem.</p>
		<p>Termin odłączenia: <?php echo $termin_odlaczenia; ?>
		<br />(poinformowano o miesięcznym terminie wypowiedzenia, jak również przedstawiono nowe propozycje oferty)</p>
		<p style="margin:30px 0;font-weight:bold;"><sup>[1061]</sup>Powody rezygnacji z Usług (wybierz tylko 1 najważniejszy powód)</p>
		<table cellspacing="0" cellpadding="0" border="1" style="width:100%" class="tbl-bordered">
			<?php foreach ($arg_values['powod'] as $k_powod => $v_label) : ?>
				<?php $sel = ($powod == $k_powod)? "X" : "&nbsp;"; ?>
				<tr><td style="width:26%;"><?php echo $v_label; ?></td><td style="width:5%;text-align:center;"> <?php echo $sel; ?> </td><td></td></tr>
			<?php endforeach; ?>
		</table>
		<table cellspacing="0" cellpadding="0" border="0" style="margin:60px 0;width:100%;">
			<tr>
				<td style="width:15%;">&nbsp;</td>
				<td style="width:20%;border-top:1px dotted #000;text-align:center;">
					Data i podpis pracownika BOK
				</td>
				<td>&nbsp;</td>
				<td style="width:20%;border-top:1px dotted #000;text-align:center;">
					Data i czytelny podpis Klienta
				</td>
				<td style="width:15%;">&nbsp;</td>
			</tr>
		</table>
		<?php
	}

	function task_bok_rozwiazanie_umowy( &$user ) {
		echo'<script type="text/javascript">'."
function frm_bok_rozwiazanie_umowy(frm){
	if (frm.id_proj.value=='') {
		alert('Nie podano numeru projektu!');
	} else if (frm.nr_umowy.value=='') {
		alert('Nie podano numeru umowy!');
	} else if (frm.temin_odlaczenia.value=='') {
		alert('Nie podano daty odłączenia!');
	// TODO: powod - radio
	} else {
		return true;
	}
	return false;
}
		".'</script>';

		$umowy_l2 = WindykacjaStatsModel::get_umowy_from_l2( $user );
		if (empty($umowy_l2)) {
			echo '<p style="color:red">' . "Brak aktualnych umów z klientem" . '</p>';
			return;
		}

		$arg_errors = array();
		$arg_values = array();
		$args = array();
		$args['id_proj'] = V::get('id_proj', '', $_REQUEST, 'int');
		$args['nr_umowy'] = V::get('nr_umowy', '', $_REQUEST, 'int');
		$args['temin_odlaczenia'] = V::get('temin_odlaczenia', '', $_REQUEST);
		$args['powod'] = V::get('powod', '', $_REQUEST, 'int');

		$arg_values['nr_umowy'] = array();
		foreach ($umowy_l2 as $k_id => $v_deal) {
			$arg_values['nr_umowy'] [$v_deal['ID']] = $v_deal['ID'] . ' (Nr umowy: ' . $v_deal['P_DEALNUMBER'] . ', ' . $v_deal['P_DEALDATE'] . ' - ' . $v_deal['P_DEALDATE_TERM'] . ')';
		}

		$arg_values['powod'] = array();// [774].[800] - USERS2_DEALS.RODZAJ_DZIALANIA_HANDLOWEGO
//		$arg_values['powod'] ['3226'] = "REZYGNACJA FINANSE";
//		$arg_values['powod'] ['3227'] = "REZYGNACJA SLABA OFERTA";
//		$arg_values['powod'] ['3121'] = "REZYGNACJA WYPROWADZKA";
//		$arg_values['powod'] ['3228'] = "REZYGNACJA PROBLEMY TECHNICZNE";
//		$arg_values['powod'] ['3230'] = "REZYGNACJA WYJAZD";
//		$arg_values['powod'] ['3229'] = "REZYGNACJA ZLA OBSLUGA BOK";
//		$arg_values['powod'] ['3123'] = "REZYGNACJA CESJA";
//		$arg_values['powod'] ['3119'] = "BRAK-BOK (Inne)";

		// [895].[3888] - DEALS_TABLE.RODZAJ_DZIALANIA_HANDLOWEGO
		//	$arg_values['powod']['4188'] = "UMOWA_BEZPOSREDNIA";
		//	$arg_values['powod']['4189'] = "UMOWA_POSREDNIA";
		//	$arg_values['powod']['4190'] = "TELEMARKETING";
		$arg_values['powod']['4192'] = "REZYGNACJA ZMIANA OPERATORA";
		$arg_values['powod']['4193'] = "REZYGNACJA WYPROWADZKA";
		$arg_values['powod']['4194'] = "REZYGNACJA NIEZADOWOLENIE";
		$arg_values['powod']['4195'] = "REZYGNACJA CESJA";
		//$arg_values['powod']['4196'] = "REZYGNACJA FINANSE";
		$arg_values['powod']['4197'] = "REZYGNACJA SLABA OFERTA";
		$arg_values['powod']['4198'] = "REZYGNACJA PROBLEMY TECHNICZNE";
		$arg_values['powod']['4199'] = "REZYGNACJA ZLA OBSLUGA BOK";
		$arg_values['powod']['4200'] = "WYPOWIEDZENIE PRZEZ OPERATORA ZA DLUGI";
		//	$arg_values['powod']['4201'] = "UMOWA W BOK ZWYCZAJNA";
		//$arg_values['powod']['4202'] = "REZYGNACJA WYJAZD";
		// $arg_values['powod']['4191'] = "BRAK-BOK (Inne)";
		$arg_values['powod']['4213'] = "REZYGNACJA INNE";

		// validate
		if ($args['temin_odlaczenia'] == '') {
			$args['temin_odlaczenia'] = date("Y-m-d", mktime(0, 0, 0, date('m') + 1, date('d'), date('Y')));
		} else {// cehck date format
			if (strlen($args['temin_odlaczenia']) != 10) {
				$arg_errors['temin_odlaczenia'] = "Błędny format daty";
			} else {
				$check_date = explode('-', $args['temin_odlaczenia']);
				if (count($check_date) != 3 || strlen($check_date[0]) != 4 || strlen($check_date[1]) != 2 || strlen($check_date[2]) != 2) {
					$arg_errors['temin_odlaczenia'] = "Błędny format daty";
				} else {
					// ok
				}
			}
		}
		if ($args['id_proj'] <= 0) {
			$arg_errors ['id_proj'] = "Nie podano numeru projektu!";
		}
		if ($args['nr_umowy'] <= 0) {
			$arg_errors ['nr_umowy'] = "Nie wybrano numeru umowy!";
		}
		if ($args['powod'] <= 0) {
			$arg_errors ['powod'] = "Nie wybrano powodu rezygnacji!";
		}

		// add rezygnacja z umowy
		if (1 == V::get('contact_bok_rozwiazanie_umowy_save', 0, $_POST, 'int')) {
			if (!empty($arg_errors)) {
				echo '<p style="color:red">' . "W formularzy wystąpiły błędy:";
					foreach ($arg_errors as $k_field => $v_err) {
						echo '<br />' . $v_err;
					}
				echo '</p>';
			} else {
				$msg_log = array();
				$ret = WindykacjaStatsHelper::update_bok_rozwiazanie_umowy( $user, $args['id_proj'], $args['nr_umowy'], $args['powod'], $arg_values['powod'][ $args['powod'] ], $args['temin_odlaczenia'], $msg_log );
				if ($ret) {
					echo '<p style="color:green">' . "Dane zapisano pomyślnie" . '</p>';
					if (!empty($msg_log)) {
						echo '<p style="color:silver">' . implode('<br />', $msg_log) . '</p>';
					}
					$ico_print = '<img src="icon/print.gif" height="16" />';
					echo '<a href="'."?MENU_INIT=USERS2_WINDYKACJA_STATUS&q=".V::get('q','', $_REQUEST)."&task="."bok_rozwiazanie_umowy_print"."&user_id=".$user->ID."&id_koresp=".$ret.'">' . $ico_print . " rozwiązanie umowy".'</a>';
					return;
				} else {
					echo '<p style="color:red">' . "Wystąpił błąd podczas zapisu danych" . '</p>';
					if (!empty($msg_log)) {
						echo '<p style="color:silver">' . implode('<br />', $msg_log) . '</p>';
					}
				}
			}
		}

		echo'<form action="" method="post" onsubmit="' . "return frm_bok_rozwiazanie_umowy(this);" . '">';
			echo'<input type="hidden" name="'."contact_bok_rozwiazanie_umowy_save".'" value="'."1".'" />';
			echo '<b>' . "Rozwiązanie umowy abonenckiej o świadczenie usług telekomunikacyjnych" . '</b>';
			echo '<br />' . "ID projektu: ";
			echo '<input type="text" name="'."id_proj".'" value="' . $args['id_proj'] . '" class="i" />';
			echo '<br />' . "Nr umowy: ";
				foreach ($arg_values['nr_umowy'] as $k_id => $v_label) {
					$sel = ($k_id == $args['nr_umowy'])? ' checked="checked"' : '';
					echo '<br />' . "&nbsp;&nbsp;&nbsp;&nbsp;" . '<input type="radio" name="'."nr_umowy".'" value="' . $k_id . '" class="i" ' . $sel . ' />' . " " . $v_label;
				}
			echo '<br />' . "Termin odłączenia: ";
			echo '<input type="text" name="'."temin_odlaczenia".'" value="' . $args['temin_odlaczenia']. '" class="i" />';
			echo '<br />' . "Powód rezygnacji z usług: ";
				foreach ($arg_values['powod'] as $k_id => $v_label) {
					$sel = ($k_id == $args['powod'])? ' checked="checked"' : '';
					echo '<br />' . "&nbsp;&nbsp;&nbsp;&nbsp;" . '<input type="radio" name="'."powod".'" value="' . $k_id . '" class="i" ' . $sel . ' />' . " " . $v_label;
				}
			echo '<br />' . '<input type="submit" value="'."zapisz".'" />';
		echo'</form>';
	}

}


class BillingDocs {


	var $_docs;
	var $_saldo;


	function __construct() {
		$this->_docs = array();
		$this->_saldo = 0;
	}


	function add_bill_doc( $data, $type, $h ) {
		$bill_doc = new BillingDoc($type, $h);
		$this->_docs[ $data ] []= $bill_doc;
		if ($data <= date("Y-m-d")) {
			$this->_saldo += $bill_doc->get_saldo();
		}
	}


	function add_event( $data, $type, $h ) {
		$event = new EventDoc($type, $h);
		$this->_docs[ $data ] []= $event;
	}


	function get_saldo() {
		if (round($this->_saldo, 2) === 0.0) {// float point bug round('-6.821210263297E-13', 2) = -0
			$this->_saldo = 0.0;
		}
		return round($this->_saldo, 2);
	}


	function &get_docs() {
		return $this->_docs;
	}


	function sort_docs() {
		ksort($this->_docs);
	}


	function &get_unpaid_fvat() {
		$today_date = date("Y-m-d");
		$fvat_arr = array();
		$saldo_curr = $this->get_saldo();
		if ($saldo_curr >= 0) {
			return $fvat_arr;
		}
		$break = false;
		$saldo_dates_keys = array_keys($this->_docs);
		$saldo_dates_keys = array_reverse($saldo_dates_keys);
		foreach ($saldo_dates_keys as $k_data) {
			if ($k_data > $today_date) continue;
			$v_saldo_arr = $this->_docs[ $k_data ];
			foreach ($v_saldo_arr as $k_ind => $v_doc) {
				if ($v_doc->get_type() == 'FVAT') {
					$h = $v_doc->get_data();
					$h['WINIEN_POZOSTALO'] = round($h['WINIEN'], 2);
					$saldo_curr += round($h['WINIEN'], 2);
					if ($saldo_curr >= 0) {
						$h['WINIEN_POZOSTALO'] -= $saldo_curr;
						$break = true;
					}
					$fvat_arr []= $h;
				}
				if ($break) break;
			}
			if ($break) break;
		}
		return $fvat_arr;
	}


	function get_last_pay_doc() {
		$last_pay_doc = null;
		$today_date = date("Y-m-d");
		$break = false;
		foreach ($this->_docs as $k_data => $v_saldo_arr) {
			if ($k_data > $today_date) continue;
			foreach ($v_saldo_arr as $k_ind => $v_doc) {
				if (in_array($v_doc->get_type(), array('WB_MASS','KP'))) {
					$last_pay_doc = $v_doc;
					break;
				}
			}
			if ($break) break;
		}
		return $last_pay_doc;
	}


}


class TimelineDoc {


	var $_type;
	var $_data;
	var $_class;


	function get_type() { return $this->_type; }
	function get_data() { return $this->_data; }
	function get_class() { return $this->_class; }
	function get( $key ) {
		return $this->_data[ $key ];
	}


}


class EventDoc extends TimelineDoc {


	function __construct( $type, &$data ) {
		$this->_data = $data;
		$this->_class = 'EVENT';
		$this->_type = $type;
	}


}


class BillingDoc extends TimelineDoc {


	function __construct( $type, &$data ) {
		$this->_data = $data;
		$this->_class = 'BILLING';
		$this->_convert_type( $type );
		$this->_count_saldo();
	}


	function get_saldo() { return $this->_saldo; }
	function get( $key ) {
		return $this->_data[ $key ];
	}


	function _convert_type( $type ) {
		$this->_type = $type;
		switch ($this->_type) {
			case 'FVAT':
				$this->_data['nr'] = $this->_data['ID_BILLING_NUMBERS'];
				$this->_data['WINIEN'] = $this->_data['WARTOSC'];
				$this->_data['MA'] = 0;
				break;

			case 'KP':
			case 'KW':
			case 'WB':
			case 'WB_MASS':
			case 'KORV':
				$this->_data['nr'] = $this->_data['NUMBER'];
				break;

			default:

		}
	}


	function _count_saldo() {
		$this->_saldo = 0;
		switch ($this->_type) {
			case 'FVAT':
				$this->_saldo -= round($this->_data['WARTOSC'], 2);
				break;

			case 'KORV':
				$this->_saldo -= round($this->_data['MA'], 2);
				break;

			case 'KP':
			case 'KW':
			case 'WB':
			case 'WB_MASS':
				$this->_saldo += round($this->_data['MA'], 2);
				$this->_saldo -= round($this->_data['WINIEN'], 2);
				break;

			default:

		}
	}


}


class WindykacjaStatsHelper {

	// TODO: `A_RECORD_UPDATE_DATE` aktualizowane tylko wraz ze statusem
	// TODO: statusy:
		// 1. Automatyczne wysłanie powiadomień do Abonentów o niezapłaconych fakturach drogą e-mailową
		//    5 dni roboczych po 10-go na okolo 5 dni przed blokadami
		// - blokada: ??? dni po ostatniej dacie platnosci - odczytac czy zablokowany z l2?
		// - 1 list - wezwanie - jesli min. 2 faktury - czyli 2 m-ce od 1 daty platnosci
		// - 2 list - wezwanie ostateczne - min. 300 zł


	function get_filter_selected() {
		$filter_selected = V::get('_f', '', $_GET);
		$filter_arr = self::get_filters();
		$filter_selected = (array_key_exists($filter_selected, $filter_arr))? $filter_selected : '';
		return $filter_selected;
	}


	function &get_filters() {
		$filter_arr ['stan_zero'] = array("stan zerowy");
		$filter_arr ['10-ego'] = array("termin płatności faktur, saldo na -", 'desc'=>array("10-ego", "10-ego każdego miesiąca - termin płatnosci faktur oraz saldo na minusie"));
		$filter_arr ['WAITING'] = array("termin płatności faktur", 'desc'=>array("10-ego", "10-ego każdego miesiąca - termin płatnosci faktur"));// z regulaminu
		$filter_arr ['15'] = array("mail ponaglenie", 'desc'=>array("10-ego + 5", "10-ego + 5 dni roboczych"));
		$filter_arr ['blokada'] = array("blokada", 'desc'=>array("pn, wt, śr około 25", "najbliższy pn, wt, śr do 25"));// najbliższy pn, wt, śr do 25-ego danego miesiąca
		$filter_arr ['tel1'] = array("kontakt tel.", 'desc'=>array("", "Ostatni kontakt tel. ponad 3 m-ce temu"));
		$filter_arr ['bad_address'] = array("błędny adres");
		$filter_arr ['wezwanie1'] = array("wezwanie do zapłaty", 'desc'=>array("2 x FVat", "2 faktury"));
		$filter_arr ['waiting-wezwanie2'] = array("oczekiwanie na uzbieranie 300 zł (firmy 500 zł)");
		$filter_arr ['wezwanie2'] = array("ostateczne wezwanie do zapłaty, rozwiązanie umowy", 'desc'=>array("wezwanie + 14, 300zł", "wezwanie + 14 dni, min. 300zł (firmy 500zł)"));
		$filter_arr ['waiting-krd'] = array("min. 60 dni od ostatecznego wezwania");
		$filter_arr ['krd'] = array("do przekazania do KRD", 'desc'=>array("wezwanie ost. + 60", "wezwanie ost. + 60 dni"));
		$filter_arr ['waiting-sad'] = array("przekazano do KRD");
		$filter_arr ['sad'] = array("przekazanie sprawy do sądu");// "krd + 14 dni"
		$filter_arr ['3 m-ce przed'] = array("3 m-ce przed przedawnieniem");// 3 m-ce przed przedawnieniem
		$filter_arr ['po-terminie'] = array("po terminie");// 3 lata po dacie platnosci faktur
		$filter_arr ['has_nr_sad'] = array("nr sprawy sąd");
		$filter_arr ['has_nr_komornik'] = array("nr sprawy komornik");
		$filter_arr ['has_ustalenia'] = array("ustalenia z klientem");
		$filter_arr ['sad_and_komornik'] = array("sąd z komornik");
		$filter_arr ['sad_bez_komornik'] = array("sąd bez komornik");
		return $filter_arr;
	}


	function &get_by_user( &$user ) {
		$sql = "select * from `USERS2_WINDYKACJA_STATUS` as w where w.`ID_BILLING_USERS`='" . $user->ID . "' ";
		$res = DB::query( $sql );
		$ret = DB::fetch( $res );
		return $ret;
	}


	/**
	 * Auto update user stats.
	 * 
	 * @returns boolean - status changed or not
	 * @param $user - object return from function WindykacjaStatsModel::get_user_by_id
	 * @param $billing_docs - user billing docs
	 * 
	 * @used in task_update_stats - for all users
	 * @used in WindykacjaView::user_historia_platnosci after view billing docs
	 * 
	 * save HIST at status change to WAITING
	 */
	function update_stats( &$user, &$billing_docs ) {
		$data_arr = array();
		if ($user->A_STATUS_UPDATE_DATE >= date("Y-m-d")) {
			return;
		}
		$saldo = $billing_docs->get_saldo();
		$data_arr["A_STATUS_UPDATE_DATE"] = date("Y-m-d");

		$data_arr["A_RECORD_UPDATE_DATE"] = date("Y-m-d-H:i");
		$data_arr["A_RECORD_UPDATE_AUTHOR"] = "stat-update";
		// set default values
		//$data_arr["A_STATUS"] = "WAITING";
		//$data_arr["PAY_FVAT"] = 0;
		//$data_arr["PAY_DATE"] = "0000-00-00";
		// update values
		{// LAST_PAY_DATE
			$last_pay_doc = $billing_docs->get_last_pay_doc();
			if ($last_pay_doc) {
				$last_pay_doc = $last_pay_doc->get_data();
				$data_arr["LAST_PAY_DATE"] = $last_pay_doc['BILL_DATE'];
			}
		}
		$data_arr["PAY_SALDO"] = $saldo;
		$data_arr["PAY_FVAT"] = 0;
		if ($saldo <= 0) {
			$fvat_arr = $billing_docs->get_unpaid_fvat();
			$data_arr["PAY_FVAT"] = count($fvat_arr);
			if (count($fvat_arr) > 0) {
				foreach ($fvat_arr as $v_fvat) {
					if (!isset($data_arr["PAY_DATE"]) || $v_fvat['PAYMENT_TERM'] > $data_arr["PAY_DATE"]) {
						$data_arr["PAY_DATE"]	= $v_fvat['PAYMENT_TERM'];
					}
				}
			}
		}

		// zmiana statusu na kolejny wg. salda
		switch ($user->A_STATUS) {
			case 'WAITING':// auto
				if ($user->wezwanie1_DATE == '0000-00-00') {
					if ($saldo < 0) {
						$fvat_arr = $billing_docs->get_unpaid_fvat();
						if (count($fvat_arr) > 1) {
							$data_arr["A_STATUS"] = "wezwanie1";
						}
					}
				}
				else if ($user->wezwanie2_DATE == '0000-00-00') {
					$data_arr["A_STATUS"] = "waiting-wezwanie2";
				}
				else {
					$data_arr["A_STATUS"] = "wezwanie2";
				}
				break;

			case 'wezwanie1':// wymaga `PAY_TERM`, `wezwanie1_DATE`, `ID_KORESP`
				break;

			case 'waiting-wezwanie2':// auto -> wezwanie2
				if ($user->wezwanie2_DATE == '0000-00-00') {
					if ($saldo <= -300) {// TODO: data od pierwszego wezwania
						$data_arr["A_STATUS"] = "wezwanie2";
					}
				}
				break;

			case 'wezwanie2':// wymaga `PAY_TERM`, `wezwanie2_DATE`, `ID_KORESP`
				break;

			case 'waiting-krd':// auto -> krd jesli minelo 60 dni od wystawienia wezwanie2
				if ($user->wezwanie2_DATE != '0000-00-00') {
					$wzw2 = new stdClass();
					$wzw2->Y = intval(substr($user->wezwanie2_DATE, 0, 4));
					$wzw2->m = intval(substr($user->wezwanie2_DATE, 5, 2));
					$wzw2->d = intval(substr($user->wezwanie2_DATE, 8, 2));
					$wzw2->plus_60 = date("Y-m-d", mktime(0,0,0, $wzw2->m, $wzw2->d + 60, $wzw2->Y));
					if ($wzw2->plus_60 < date("Y-m-d")) {
						$data_arr["A_STATUS"] = "krd";
					}
				}
				break;

			default:
				
		}

		// zmiana statusu na czysty - WAITING
		if ($saldo >= 0 || $data_arr["PAY_FVAT"] < 2) {
			$data_arr["A_STATUS"] = "WAITING";
			// TODO: wyczyszczenie pol
			$data_arr["wezwanie2_DATE"] = '0000-00-00';
			$data_arr["wezwanie1_DATE"] = '0000-00-00';
			//$data_arr["PAY_DATE"] = '0000-00-00';// TODO: ?
		}

		$sql_arr = array();
		foreach ($data_arr as $k => $v) {
			$sql_arr []= "`" . $k . "`='" . $v . "'";
		}
		$sql = "update `USERS2_WINDYKACJA_STATUS` set " . implode(",", $sql_arr) . " where `ID`='" . $user->WINDYKACJA_ID . "' limit 1 ; ";
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($sql);echo'</pre>';
		DB::query( $sql );

		// update HIST - tylko zmiana na WAITING - powrót do oczekujących
		if (isset($data_arr["A_STATUS"]) && $data_arr["A_STATUS"] == "WAITING" && $user->A_STATUS != "WAITING") {
			//if (DB::affected()) {
			$sql_arr = array();
			foreach ($data_arr as $k => $v) {
				$sql_arr ["`" . $k . "`"] = "'" . $v . "'";
			}
			$sql_arr ["`ID_USERS2`"] = "'" . $user->WINDYKACJA_ID . "'";
			$sql = "insert into `USERS2_WINDYKACJA_STATUS_HIST`(" . implode(",", array_keys($sql_arr)) . ") values(" . implode(",", array_values($sql_arr)) . ");";
			DB::query( $sql );
			//}
		}
	}


	function &get_phone_status_array( &$user ) {
		$ret = array();
		$status_info = self::get_phone_status_info( $user );
		foreach ($status_info as $k => $v) {
			$ret[ $k ] = $v['label'];
		}//end foreach
		return $ret;
	}


	/**
	 * @param $user
	 * 
	 * @returns array of 'label', 'date' -> nowy PAY_TERM ustalony wg. aktualnego stanu
	 */
	function &get_phone_status_info( &$user ) {
		$ret = array();
		$ret['nie_zaplaci'] = array('label'=>"nie zapłaci", 'date'=>'');
		$today = date("Y-m-d");
		$date = date("Y-m-d");
		{// PAY_TERM jesli jest ustalony np. z wewaznie1 lub wezwanie2
			if ($user->PAY_TERM != '0000-00-00') {
				if ($user->PAY_TERM > $today) {
					// jest już ustalona data platnosci na przyszłość
					$date = $user->PAY_TERM;
				}
			}
		}

		if ($date > $today) {// data platnosci w przyszlosci -> ok
			{// zapłaci w terminie today +14 dni lub PAY_TERM jesli jest ustalony np. z wewaznie1 lub wezwanie2
				$ret['zaplaci_w_terminie'] = array('label'=>"zapłaci w terminie", 'date'=>$date);
			}
		}
		else {// data platnosci w przeszlosci - przeterminowana -> ustalic nowa (+14,+1mc,+2mc,+3mc)
			{// zapłaci w terminie today +14 dni lub PAY_TERM jesli jest ustalony np. z wewaznie1 lub wezwanie2
				$date = date("Y-m-d", mktime(0,0,0,date('m'), date('d') + 14, date('Y')));
				$ret['zaplaci_w_terminie'] = array('label'=>"zapłaci w terminie", 'date'=>$date);
			}
			{// zaplaci za 1-mc pozniej
				$date = date("Y-m-d", mktime(0,0,0,date('m') + 1, date('d'), date('Y')));
				$ret['zaplaci_za_1mc'] = array('label'=>"zapłaci miesiąc później", 'date'=>$date);
			}
			{// zaplaci za 2-mce pozniej
				$date = date("Y-m-d", mktime(0,0,0,date('m') + 2, date('d'), date('Y')));
				$ret['zaplaci_za_2mc'] = array('label'=>"zapłaci 2 miesiące później", 'date'=>$date);
			}
			{// zaplaci za 3-mce pozniej
				$date = date("Y-m-d", mktime(0,0,0,date('m') + 3, date('d'), date('Y')));
				$ret['zaplaci_za_3mc'] = array('label'=>"zapłaci 3 miesiące później", 'date'=>$date);
			}
		}

		$ret['nie_odbiera'] = array('label'=>"nie obiera lub wyłączony telefon", 'date'=>'');
		$ret['zly_numer'] = array('label'=>"zły numer telefonu", 'date'=>'');
		return $ret;
	}


	/**
	 * Update user phone status.
	 * 
	 * @returns boolean - status changed or not
	 * @param $user - object return from function WindykacjaStatsModel::get_user_by_id
	 * @param $phone_status - phone status
	 * 
	 */
	function update_phone_status( &$user, $phone_status ) {
		$data_arr = array();

		$data_arr["A_RECORD_UPDATE_DATE"] = date("Y-m-d-H:i");
		$data_arr["A_RECORD_UPDATE_AUTHOR"] = $_SESSION['ADM_ACCOUNT'];
		$data_arr["LAST_PHONE_STATUS"] = $phone_status;
		$data_arr["LAST_PHONE_STATUS_DATE"] = date("Y-m-d");
		$status_info = self::get_phone_status_info( $user );
		if (array_key_exists($phone_status, $status_info)) {
			$date = V::get('date', '', $status_info[$phone_status]);
			if ($date != '' && $date != '0000-00-00') {
				$data_arr["PAY_TERM"] = $date;
			}
		}

		$sql_arr = array();
		foreach ($data_arr as $k => $v) {
			$sql_arr []= "`" . $k . "`='" . $v . "'";
		}//end foreach
		$sql = "update `USERS2_WINDYKACJA_STATUS` set " . implode(",", $sql_arr) . " where `ID`='" . $user->WINDYKACJA_ID . "' limit 1 ; ";
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($sql);echo'</pre>';
		DB::query( $sql );

		// update HIST
		//if (DB::affected()) {
			$sql_arr = array();
			foreach ($data_arr as $k => $v) {
				$sql_arr ["`" . $k . "`"] = "'" . $v . "'";
			}//end foreach
			$sql_arr ["`ID_USERS2`"] = "'" . $user->WINDYKACJA_ID . "'";
			$sql = "insert into `USERS2_WINDYKACJA_STATUS_HIST`(" . implode(",", array_keys($sql_arr)) . ") values(" . implode(",", array_values($sql_arr)) . ");";
			DB::query( $sql );
		//}
		return true;
	}


	function update_old_id_koresp( &$user, $id_koresp, $koresp_type ) {
		$db = DB::getDB();
		$koresp = DB::get_by_id('IN7_DZIENNIK_KORESP', $id_koresp);
		if (!$koresp) {
			return false;
		}

		// check if ID koresp already exists in HIST table!
		$sql = "select wh.`ID`,wh.``,wh.`` from `USERS2_WINDYKACJA_STATUS_HIST` as wh where ";

		$data_arr = array();
		$data_arr["A_RECORD_UPDATE_DATE"] = date("Y-m-d-H:i");
		$data_arr["A_RECORD_UPDATE_AUTHOR"] = $_SESSION['ADM_ACCOUNT'];
		$data_arr["ID_USERS2"] = $user->WINDYKACJA_ID;
		$data_arr["ID_KORESP"] = $id_koresp;
		//$data_arr["A_STATUS_UPDATE_DATE"] = $koresp->K_DATA_OTRZYMANEJ_KORESP;// data utworzenia
		$data_arr["A_STATUS_UPDATE_DATE"] = $koresp->K_DATA_OTRZYM_KORESP;// data wyslania
		// $koresp_type ?

		// update HIST
		$sql_arr = array();
		foreach ($data_arr as $k => $v) {
			$sql_arr ["`" . $k . "`"] = "'" . $v . "'";
		}//end foreach
		$sql = "insert into `USERS2_WINDYKACJA_STATUS_HIST`(" . implode(",", array_keys($sql_arr)) . ") values(" . implode(",", array_values($sql_arr)) . ");";
		$db->query($sql);
		return true;
	}

	/**
	 * @returns int - ID Koresp or null if error
	 */
	function update_bok_rozwiazanie_umowy( &$user, $id_proj, $nr_umowy, $powod, $powod_desc, $termin_odlaczenia, &$msg_log ) {
		$data_arr = array();
		if ($id_proj > 0 && $nr_umowy > 0 && $powod != '') {
			$new_id_deals = WindykacjaStatsModel::create_deals_rozwiazanie($user->ID, $nr_umowy, $termin_odlaczenia, $powod_desc);
			if (!$new_id_deals) {
				$msg_log []= "Nie udało się utworzyć rekordu w DEALS_TABLE";
				return null;
			}
			$msg_log []= "Utworzonno rekord w DEALS_TABLE ID={$new_id_deals}";

			$new_id_koresp = WindykacjaStatsModel::create_koresp($user, 'rozwiazanie umowy', $id_proj, array('nr_umowy'=>$nr_umowy, 'powod'=>$powod, 'powod_desc'=>$powod_desc));
			if (!$new_id_koresp) {
				$msg_log []= "Nie udało się utworzyć rekordu KORESP";
				return null;
			}
			$msg_log []= "Utworzonno rekord KORESP ID={$new_id_koresp}";
			$data_arr["ID_KORESP"] = $new_id_koresp;
		} else {
			return null;
		}
		$data_arr["params"] = "rozwiazanie umowy,{$nr_umowy},{$powod},{$termin_odlaczenia},{$new_id_deals}";
		$data_arr["A_STATUS_UPDATE_DATE"] = date("Y-m-d");// zawsze podana jesli jest zmiana A_STATUS

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

		//if (DB::affected()) {
		// update $user data
		foreach ($data_arr as $k => $v) {
			$user->$k = $v;
		}
		$sql_arr = array();
		foreach ($data_arr as $k => $v) {
			$sql_arr ["`" . $k . "`"] = "'" . $v . "'";
		}
		$sql_arr ["`ID_USERS2`"] = "'" . $user->WINDYKACJA_ID . "'";
		$sql = "insert into `USERS2_WINDYKACJA_STATUS_HIST`(" . implode(",", array_keys($sql_arr)) . ") values(" . implode(",", array_values($sql_arr)) . ");";
		DB::query( $sql );
		//}
		return $new_id_koresp;
	}


	function update_users_table() {
		if (!isset($_SESSION['USERS2_WINDYKACJA_PANEL'])) $_SESSION['USERS2_WINDYKACJA_PANEL'] = array();
		$_SESSION['USERS2_WINDYKACJA_PANEL']['_initialized'] = 0;// always actualize
		if (0 == V::get('_initialized', 0, $_SESSION['USERS2_WINDYKACJA_PANEL'], 'int')) {
			$sql = "insert ignore into `USERS2_WINDYKACJA_STATUS` (`ID_BILLING_USERS`, `A_RECORD_CREATE_DATE`, `A_RECORD_CREATE_AUTHOR`)
				select `id_users`, '" . date("Y-m-d-H:i") . "', 'sync-users' from `BILLING_USERS_ADD`
			";
			$res = DB::query( $sql );

			$_SESSION['USERS2_WINDYKACJA_PANEL']['_initialized'] = 1;
		}
	}


	function _to_update_where() {
		$sql_where = "";
		$sql_where_and_arr = array();
		//$sql_where_and_arr []= "w.`A_STATUS`='WAITING'";
		$sql_where_and_arr []= "w.`A_STATUS_UPDATE_DATE`<CURDATE()";
		$sql_where = implode(" and ", $sql_where_and_arr);
		return $sql_where;
	}


	function get_to_update_total() {
		$ret = array();
		$sql_where = self::_to_update_where();
		$sql = "select count(1) as cnt
			from `USERS2_WINDYKACJA_STATUS` as w
			where $sql_where
		";
		$res = DB::query( $sql );
		while ($r = DB::fetch( $res )) {
			$ret = $r->cnt;
		}
		return $ret;
	}


	function &get_to_update_list( $limit ) {
		$ret = array();
		$sql_where = self::_to_update_where();
		$sql_limit = ($limit > 0)? "limit ".$limit : "";
		$sql = "select w.*
			from `USERS2_WINDYKACJA_STATUS` as w
			where $sql_where
			order by ID desc
			$sql_limit
		";
		$res = DB::query( $sql );
		while ($r = DB::fetch( $res )) {
			$ret []= $r;
		}
		return $ret;
	}


	/**
	 * @returns boolean - status changed or not
	 * @param $user - object return from function WindykacjaStatsModel::get_user_by_id
	 * @param $data - array of new user data
	 *   1. wysłanie 1 wezwania do zapłaty ($user->A_STATUS='wezwanie1'; `PAY_TERM`, `wezwanie1_DATE`, `ID_PROJ`)
	 *   2. wysłanie 2 wezwania do zapłaty ($user->A_STATUS='wezwanie2'; `PAY_TERM`, `wezwanie2_DATE`, `ID_KORESP`)
	 *   3. klient spłacił wszystkie zobowiązania (`PAY_SALDO`>=0)
	 * TODO: 4. bledny adres klienta - ponowne wyslanie wezwania - niezaleznie od statusu?
	 * 
	 * if $user->A_STATUS == 'wezwanie1' @param $data:
	 *   $data['wezwanie1_DATE'] - user data
	 *   $data['PAY_TERM'] - user data
	 *   $data['ID_PROJ'] - do WindykacjaStatsModel::create_koresp
	 */
	function &update_user( $user, $data ) {
		if (empty($data)) {
			return $user;
		}
		$data_arr = array();
		// set up status by current status and $data
		switch ($user->A_STATUS) {
			case 'WAITING':// auto
				break;

			case 'wezwanie1':// wymaga `PAY_TERM`, `wezwanie1_DATE`, `ID_KORESP` - wysłanie wezwanie1 (z podaniem ID_KORESP, i PAY_TERM=NOW()+14dni)
				// TODO: ID_KORESP z utworzonego rekordu KORESP (wymaga ID_PROJ)
				if ("" != V::get('wezwanie1_DATE' ,'', $data) && "" != V::get('PAY_TERM' ,'', $data) && V::get('ID_PROJ' ,'', $data, 'int') > 0) {
					$new_id_koresp = WindykacjaStatsModel::create_koresp($user, 'wezwanie1', V::get('ID_PROJ' ,'', $data, 'int'));
					if (!$new_id_koresp) {
						// TODO: revert changes - DB error
						return $user;
					}
					$data_arr["ID_KORESP"] = $new_id_koresp;
					$data_arr["A_STATUS"] = "waiting-wezwanie2";
					$data_arr["wezwanie1_DATE"] = V::get('wezwanie1_DATE' ,'', $data);
					$data_arr["PAY_TERM"] = V::get('PAY_TERM' ,'', $data);
					unset($data['ID_PROJ']);// TODO: RM after mv $data to $data_arr
				}
				break;

			case 'waiting-wezwanie2':// auto
				break;

			case 'wezwanie2':// wymaga `PAY_TERM`, `wezwanie2_DATE`, `ID_KORESP` - wysłanie wezwanie2 (z podaniem ID_KORESP, i PAY_TERM=NOW()+14dni)
				if ("" != V::get('wezwanie2_DATE' ,'', $data) && "" != V::get('PAY_TERM' ,'', $data) && V::get('ID_PROJ' ,'', $data, 'int') > 0) {
					$new_id_koresp = WindykacjaStatsModel::create_koresp($user, 'wezwanie2', V::get('ID_PROJ' ,'', $data, 'int'));
					if (!$new_id_koresp) {
						// TODO: revert changes - DB error
						return $user;
					}
					$data_arr["ID_KORESP"] = $new_id_koresp;
					$data_arr["A_STATUS"] = "waiting-krd";
					$data_arr["wezwanie2_DATE"] = V::get('wezwanie2_DATE' ,'', $data);
					$data_arr["PAY_TERM"] = V::get('PAY_TERM' ,'', $data);
				}
				break;

			default:
				
		}

		// if status not set, check id user saldo is ok
		if (!isset($data_arr["A_STATUS"])) {
			if (isset($data['PAY_SALDO']) && $data['PAY_SALDO'] >= 0) {
				$data_arr["A_STATUS"] = "WAITING";
			}
		}

		// error jesli nie ustalono statusu
		if (!isset($data_arr["A_STATUS"])) {
			return false;
		}

		$data_arr["A_STATUS_UPDATE_DATE"] = date("Y-m-d");// zawsze podana jesli jest zmiana A_STATUS

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

		//if (DB::affected()) {
		// update $user data
		foreach ($data_arr as $k => $v) {
			$user->$k = $v;
		}
		$sql_arr = array();
		foreach ($data_arr as $k => $v) {
			$sql_arr ["`" . $k . "`"] = "'" . $v . "'";
		}
		$sql_arr ["`ID_USERS2`"] = "'" . $user->WINDYKACJA_ID . "'";
		$sql = "insert into `USERS2_WINDYKACJA_STATUS_HIST`(" . implode(",", array_keys($sql_arr)) . ") values(" . implode(",", array_values($sql_arr)) . ");";
		DB::query( $sql );
		//}
		return true;
	}

	function bad_address_save($user, $id_koresp) {
		$data_arr = array();
		$data_arr["A_RECORD_UPDATE_DATE"] = date("Y-m-d-H:i");
		$data_arr["A_RECORD_UPDATE_AUTHOR"] = $_SESSION['ADM_ACCOUNT'];
		$data_arr["BAD_ADDRESS"] = 1;
		$data_arr["ID_KORESP"] = $id_koresp;
		return self::_sql_update($user, $data_arr);
	}

	function bad_address_confirm($user, $id_koresp) {
		$data_arr = array();
		$data_arr["A_RECORD_UPDATE_DATE"] = date("Y-m-d-H:i");
		$data_arr["A_RECORD_UPDATE_AUTHOR"] = $_SESSION['ADM_ACCOUNT'];
		$data_arr["BAD_ADDRESS"] = 0;
		$data_arr["ID_KORESP"] = $id_koresp;
		return self::_sql_update($user, $data_arr);
	}

	function _sql_update($user, $data_arr) {
		// update values
		$sql_arr = array();
		foreach ($data_arr as $k => $v) {
			$sql_arr []= "`{$k}`='{$v}'";
		}
		$sql = "update `USERS2_WINDYKACJA_STATUS` set " . implode(",", $sql_arr) . " where `ID`='{$user->WINDYKACJA_ID}' limit 1 ";
		DB::query( $sql );
		// update $user data
		foreach ($data_arr as $k => $v) {
			$user->$k = $v;
		}
		$sql_arr = array();
		foreach ($data_arr as $k => $v) {
			$sql_arr ["`{$k}`"] = "'{$v}'";
		}
		$sql_arr ["`ID_USERS2`"] = "'{$user->WINDYKACJA_ID}'";
		$sql = "insert into `USERS2_WINDYKACJA_STATUS_HIST`(" . implode(",", array_keys($sql_arr)) . ") values(" . implode(",", array_values($sql_arr)) . ");";
		DB::query( $sql );
		return true;
	}

	function change_status_save($user, $new_status) {
		$data_arr = array();
		$data_arr["A_RECORD_UPDATE_DATE"] = date("Y-m-d-H:i");
		$data_arr["A_RECORD_UPDATE_AUTHOR"] = $_SESSION['ADM_ACCOUNT'];
		$data_arr["A_STATUS_UPDATE_DATE"] = date("Y-m-d");
		$data_arr["A_STATUS"] = $new_status;
		return self::_sql_update($user, $data_arr);
	}

	function nr_sprawy_krd_save($user, $nr_sprawy_krd) {
		$data_arr = array();
		$data_arr["A_RECORD_UPDATE_DATE"] = date("Y-m-d-H:i");
		$data_arr["A_RECORD_UPDATE_AUTHOR"] = $_SESSION['ADM_ACCOUNT'];
		$data_arr["NR_SPRAWY_KRD"] = $nr_sprawy_krd;
		return self::_sql_update($user, $data_arr);
	}

	function nr_sprawy_sad_save($user, $nr_sprawy_sad) {
		$data_arr = array();
		$data_arr["A_RECORD_UPDATE_DATE"] = date("Y-m-d-H:i");
		$data_arr["A_RECORD_UPDATE_AUTHOR"] = $_SESSION['ADM_ACCOUNT'];
		$data_arr["NR_SPRAWY_SAD"] = $nr_sprawy_sad;
		return self::_sql_update($user, $data_arr);
	}

	function nr_sprawy_komornik_save($user, $nr_sprawy_komornik) {
		$data_arr = array();
		$data_arr["A_RECORD_UPDATE_DATE"] = date("Y-m-d-H:i");
		$data_arr["A_RECORD_UPDATE_AUTHOR"] = $_SESSION['ADM_ACCOUNT'];
		$data_arr["NR_SPRAWY_KOMORNIK"] = $nr_sprawy_komornik;
		return self::_sql_update($user, $data_arr);
	}

	function ustalenia_info_save($user, $ustalenia_date, $ustalenia_info) {
		$data_arr = array();
		$data_arr["A_RECORD_UPDATE_DATE"] = date("Y-m-d-H:i");
		$data_arr["A_RECORD_UPDATE_AUTHOR"] = $_SESSION['ADM_ACCOUNT'];
		$data_arr["L_APPOITMENT_DATE"] = $ustalenia_date;
		$data_arr["L_APPOITMENT_INFO"] = $ustalenia_info;
		$data_arr["L_APPOITMENT_USER"] = $_SESSION['ADM_ACCOUNT'];

		if (empty($ustalenia_info) && (empty($ustalenia_date) || $ustalenia_date == '0000-00-00')) {
			$data_arr["L_APPOITMENT_USER"] = '';
		}
		return self::_sql_update($user, $data_arr);
	}

	function &get_user_hist_events( &$user ) {
		$db = DB::getDB();
		$ret = array();
		$sql = "select wh.*
			from `USERS2_WINDYKACJA_STATUS_HIST` as wh
			where wh.`ID_USERS2`='" . $user->WINDYKACJA_ID . "'
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$ret []= $r;
		}
		return $ret;
	}


	function &get_user_hist_status_events( &$user ) {
		$db = DB::getDB();
		$ret = array();
		$sql = "select wh.*, kor.`K_ZAWARTOS`
			from `USERS2_WINDYKACJA_STATUS_HIST` as wh
				left join `IN7_DZIENNIK_KORESP` as kor on(wh.`ID_KORESP`!='N/S;' and kor.`ID`=wh.`ID_KORESP`)
			where wh.`ID_USERS2`='" . $user->WINDYKACJA_ID . "'
				and wh.`A_STATUS_UPDATE_DATE`!='N/S;'
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$ret []= $r;
		}
		return $ret;
	}


	function &get_user_hist_phone_events( &$user ) {
		$ret = array();
		$db = DB::getDB();
		$sql = "select wh.*
			from `USERS2_WINDYKACJA_STATUS_HIST` as wh
			where wh.`ID_USERS2`='" . $user->WINDYKACJA_ID . "'
				and wh.`LAST_PHONE_STATUS`!='N/S;'
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$ret []= $r;
		}
		return $ret;
	}


	function &get_user_bad_address_events( &$user ) {
		$ret = array();
		$db = DB::getDB();
		$sql = "select wh.*
			from `USERS2_WINDYKACJA_STATUS_HIST` as wh
			where wh.`ID_USERS2`='" . $user->WINDYKACJA_ID . "'
				and wh.`BAD_ADDRESS`!='N/S;'
			order by wh.`ID` ASC
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$ret []= $r;
		}
		return $ret;
	}


	function &get_status_count() {
		$ret = array();
		$sql = " select w.`A_STATUS`, count(1) as cnt
				, sum(IF(w.`PAY_SALDO`<0, w.`PAY_SALDO`, 0)) as suma_zaleglosci
			from  `USERS2_WINDYKACJA_STATUS` as w
			group by w.`A_STATUS` 
		";
		$res = DB::query( $sql );
		while ($r = DB::fetch( $res )) {
			$ret[ $r->A_STATUS ] = $r;
		}
		// filter: 'po-terminie'
		$sql = "select w.`A_STATUS`
				, count(1) as cnt
				, sum(IF(w.`PAY_SALDO`<0, w.`PAY_SALDO`, 0)) as suma_zaleglosci
			from  `USERS2_WINDYKACJA_STATUS` as w
			where
				w.`PAY_SALDO`<0
				and w.`PAY_DATE`!='0000-00-00'
				and w.`PAY_DATE`<DATE_SUB(NOW(), INTERVAL 36 MONTH)
		";
		$res = DB::query( $sql );
		if ($r = DB::fetch( $res )) {
			$ret[ 'po-terminie' ] = $r;
		}
		// filter: '3 m-ce przed'
		$sql = "select w.`A_STATUS`
				, count(1) as cnt
				, sum(IF(w.`PAY_SALDO`<0, w.`PAY_SALDO`, 0)) as suma_zaleglosci
			from  `USERS2_WINDYKACJA_STATUS` as w
			where
				w.`PAY_SALDO`<0
				and w.`PAY_DATE`!='0000-00-00'
				and w.`PAY_DATE`<DATE_SUB(NOW(), INTERVAL 33 MONTH)
				and w.`PAY_DATE`>DATE_SUB(NOW(), INTERVAL 36 MONTH)
		";
		$res = DB::query( $sql );
		if ($r = DB::fetch( $res )) {
			$ret[ '3 m-ce przed' ] = $r;
		}
		// filter: 'tel1'
		$sql = "select w.`A_STATUS`
				, count(1) as cnt
				, sum(IF(w.`PAY_SALDO`<0, w.`PAY_SALDO`, 0)) as suma_zaleglosci
			from  `USERS2_WINDYKACJA_STATUS` as w
			where
				w.`PAY_SALDO`<0
				and w.`A_STATUS` in('wezwanie1', 'waiting-wezwanie2', 'wezwanie2', 'waiting-krd')
				and ( w.`LAST_PHONE_STATUS_DATE`='0000-00-00'
					or w.`LAST_PHONE_STATUS_DATE`<DATE_SUB(NOW(), INTERVAL 3 MONTH) )
		";
		$res = DB::query( $sql );
		if ($r = DB::fetch( $res )) {
			$ret[ 'tel1' ] = $r;
		}
		// filter: 'bad_address'
		$sql = "select w.`A_STATUS`
				, count(1) as cnt
				, sum(IF(w.`PAY_SALDO`<0, w.`PAY_SALDO`, 0)) as suma_zaleglosci
			from  `USERS2_WINDYKACJA_STATUS` as w
			where
				w.`PAY_SALDO`<0
				-- and w.`A_STATUS` in('wezwanie1', 'waiting-wezwanie2', 'wezwanie2', 'waiting-krd')
				and w.`BAD_ADDRESS`>0
		";
		$res = DB::query( $sql );
		if ($r = DB::fetch( $res )) {
			$ret[ 'bad_address' ] = $r;
		}
		// filter: 'stan_zero', '10-ego'
		$sql = "select w.`A_STATUS`
				, count(1) as cnt
				, sum(IF(w.`PAY_SALDO`>=0, 1, 0)) as cnt_stan_zero
				, sum(IF(w.`PAY_SALDO`<0, 1, 0)) as cnt_stan_minus
				, sum(IF(w.`PAY_SALDO`<0, w.`PAY_SALDO`, 0)) as suma_zaleglosci
			from  `USERS2_WINDYKACJA_STATUS` as w
			where
				w.`A_STATUS`='WAITING'
		";
		$res = DB::query( $sql );
		if ($r = DB::fetch( $res )) {
			$ret[ 'stan_zero' ] = (object)array('A_STATUS'=>'stan_zero', 'cnt'=>$r->cnt_stan_zero, 'suma_zaleglosci'=>0);
			$ret[ '10-ego' ] = (object)array('A_STATUS'=>'10-ego', 'cnt'=>$r->cnt_stan_minus, 'suma_zaleglosci'=>$r->suma_zaleglosci);
		}
		// filter: 'has_nr_sad', 'has_nr_komornik', 'has_ustalenia'
		$sql = "select w.`A_STATUS`
				, count(1) as cnt
				, sum(IF(w.`NR_SPRAWY_SAD`!='', 1, 0)) as cnt_sad
				, sum(IF(w.`NR_SPRAWY_KOMORNIK`!='', 1, 0)) as cnt_komornik
				, sum(IF(w.`L_APPOITMENT_INFO`!='', 1, 0)) as cnt_ustalenia
			from  `USERS2_WINDYKACJA_STATUS` as w
			where
				(w.`NR_SPRAWY_SAD`!=''
					or w.`NR_SPRAWY_KOMORNIK`!=''
					or w.`L_APPOITMENT_INFO`!=''
				)
		";
		$res = DB::query( $sql );
		if ($r = DB::fetch( $res )) {
			$ret[ 'has_nr_sad' ] = (object)array('A_STATUS'=>'has_nr_sad', 'cnt'=>$r->cnt_sad, 'suma_zaleglosci'=>null);
			$ret[ 'has_nr_komornik' ] = (object)array('A_STATUS'=>'has_nr_komornik', 'cnt'=>$r->cnt_komornik, 'suma_zaleglosci'=>null);
			$ret[ 'has_ustalenia' ] = (object)array('A_STATUS'=>'has_ustalenia', 'cnt'=>$r->cnt_ustalenia, 'suma_zaleglosci'=>null);
		}
		// filter: 'sad_and_komornik', 'sad_bez_komornik'
		$sql = "select w.`A_STATUS`
				, count(1) as cnt
				, sum(IF(w.`NR_SPRAWY_KOMORNIK`!='', 1, 0)) as cnt_komornik
			from  `USERS2_WINDYKACJA_STATUS` as w
			where
				w.`A_STATUS`='sad'
		";
		$res = DB::query( $sql );
		if ($r = DB::fetch( $res )) {
			$ret[ 'sad_and_komornik' ] = (object)array('A_STATUS'=>'sad_and_komornik', 'cnt'=>$r->cnt_komornik, 'suma_zaleglosci'=>null);
			$ret[ 'sad_bez_komornik' ] = (object)array('A_STATUS'=>'sad_bez_komornik', 'cnt'=>($r->cnt - $r->cnt_komornik), 'suma_zaleglosci'=>null);
		}
		return $ret;
	}
}


class WindykacjaStatsModel {


	function _parse_query( $q ) {
		$sql_where = '';
		$sql_where_and_arr = array();
		$filter_selected = WindykacjaStatsHelper::get_filter_selected();
		if ($filter_selected) {
			if ($filter_selected == 'po-terminie') {
				$sql_where_and_arr []= "w.`PAY_SALDO`<0";
				$sql_where_and_arr []= "w.`PAY_DATE`!='0000-00-00'";
				$sql_where_and_arr []= "w.`PAY_DATE`<DATE_SUB(NOW(), INTERVAL 36 MONTH)";
			}
			else if ($filter_selected == '3 m-ce przed') {
				$sql_where_and_arr []= "w.`PAY_SALDO`<0";
				$sql_where_and_arr []= "w.`PAY_DATE`!='0000-00-00'";
				$sql_where_and_arr []= "w.`PAY_DATE`<DATE_SUB(NOW(), INTERVAL 33 MONTH)";
				$sql_where_and_arr []= "w.`PAY_DATE`>DATE_SUB(NOW(), INTERVAL 36 MONTH)";
			}
			else if ($filter_selected == 'tel1') {
				$sql_where_and_arr []= "w.`PAY_SALDO`<0";
				$sql_where_and_arr []= "w.`A_STATUS` in('wezwanie1', 'waiting-wezwanie2', 'wezwanie2', 'waiting-krd')";
				$sql_where_and_arr []= "( w.`LAST_PHONE_STATUS_DATE`='0000-00-00'
					or w.`LAST_PHONE_STATUS_DATE`<DATE_SUB(NOW(), INTERVAL 3 MONTH) )";
			}
			else if ($filter_selected == 'bad_address') {
				$sql_where_and_arr []= "w.`BAD_ADDRESS`>0";
				$sql_where_and_arr []= "w.`PAY_SALDO`<0";
			}
			else if ($filter_selected == 'stan_zero') {
				$sql_where_and_arr []= "w.`A_STATUS`='WAITING'";
				$sql_where_and_arr []= "w.`PAY_SALDO`>=0";
			}
			else if ($filter_selected == '10-ego') {
				$sql_where_and_arr []= "w.`A_STATUS`='WAITING'";
				$sql_where_and_arr []= "w.`PAY_SALDO`<0";
			}
			else if ($filter_selected == 'has_nr_sad') {
				$sql_where_and_arr []= "w.`NR_SPRAWY_SAD`!=''";
			}
			else if ($filter_selected == 'has_nr_komornik') {
				$sql_where_and_arr []= "w.`NR_SPRAWY_KOMORNIK`!=''";
			}
			else if ($filter_selected == 'has_ustalenia') {
				$sql_where_and_arr []= "w.`L_APPOITMENT_INFO`!=''";
			}
			else if ($filter_selected == 'sad_and_komornik') {
				$sql_where_and_arr []= "w.`A_STATUS`='sad' and w.`NR_SPRAWY_KOMORNIK`!=''";
			}
			else if ($filter_selected == 'sad_bez_komornik') {
				$sql_where_and_arr []= "w.`A_STATUS`='sad' and w.`NR_SPRAWY_KOMORNIK`=''";
			}
			else {
				$sql_where_and_arr []= "w.`A_STATUS`='" . $filter_selected . "'";
			}
		}
		if (!empty($q)) {
			$q = trim($q);
			if (is_numeric($q)) {// billing number
				$sql_where_and_arr []= "a.`id_users`='".DB::_($q)."'";
			}
			else {// string - name, second name
				$q_arr_values = array();
				$q_exp = explode(' ', $q);
				foreach ($q_exp as $v_q) {
					$v_q = trim($v_q);
					if (strlen($v_q) > 2) {// min. 3 znaki
						$q_arr_values []= strtolower($v_q);
					}
				}

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

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

					$sql_filter_q []= "a.`P_NAME` like '".DB::_($q_value)."%'";
					$sql_filter_q []= "a.`P_NAME_SECOND` like '".DB::_($q_value)."%'";

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

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

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

					$sql_where_and_arr []= "(" . implode(" or ", $sql_filter_q) . ")";
				}
			}
		}
		if (!empty($sql_where_and_arr)) {
			$sql_where = implode(" and ", $sql_where_and_arr);
		} else {
			$sql_where = "1=1";
		}
		return $sql_where;
	}

	function get_order_by_fields() {
		$order_by_fields = array();
		$order_by_fields []= 'ID';
		$order_by_fields []= 'is_firma';
		$order_by_fields []= 'BILLING_OWNER';
		$order_by_fields []= 'STATUS';
		$order_by_fields []= 'BLOKADA';
		$order_by_fields []= 'ID_BILLING_USERS';
		$order_by_fields []= 'P_NAME';
		$order_by_fields []= 'PAY_SALDO';
		$order_by_fields []= 'PAY_FVAT';
		$order_by_fields []= 'PAY_DATE';
		$order_by_fields []= 'PAY_TERM';
		return $order_by_fields;
	}

	function get_users_total( $q = '' ) {
		$total = 0;
		$sql_where = WindykacjaStatsModel::_parse_query( $q );
		$sql = "select count(1) as cnt
			from `USERS2_WINDYKACJA_STATUS` as w
				left join `BILLING_USERS_ADD` as a on(a.`id_users`=w.`ID_BILLING_USERS`)
			where ".$sql_where."
		";
		$res = DB::query($sql);
		if ($r = DB::fetch($res)) {
			$total = $r->cnt;
		}
		return $total;
	}

	function get_sql_users_select() {
		$sql_select = "
				a.`id_users` as ID
				, a.`id_users`
				, a.`P_NAME`
				, a.`P_NAME_SECOND`
				, a.`P_ADDRESS_STREET`
				, a.`P_ADDRESS_HOME`
				, a.`P_ADDRESS_HOUSE`
				, a.`P_ADDRESS_CITY`
				, a.`P_ADDRESS_POST_CODE`
				, a.`P_ADDRESS_REGION`
				, a.`P_PESEL`
				, a.`P_PHONE`
				, a.`P_OTHER_DOC`
				, a.`user_mail_contact`
				, a.`is_firma`
				, w.`ID` as WINDYKACJA_ID
				, w.`ID_BILLING_USERS`
				, w.`A_STATUS`
				, w.`A_STATUS_UPDATE_DATE`
				, w.`USER_PAY_TERM_ADD`
				, w.`L_APPOITMENT_DATE`
				, w.`L_APPOITMENT_USER`
				, w.`L_APPOITMENT_INFO`
				, w.`PAY_DATE`
				, w.`PAY_TERM`
				, w.`PAY_SALDO`
				, w.`PAY_FVAT`
				, w.`wezwanie1_DATE`
				, w.`wezwanie2_DATE`
				, w.`ID_KORESP`
				, w.`LAST_PAY_DATE`
				, w.`BAD_ADDRESS`
				-- , (select bu.`BILLING_OWNER` from `BILLING_USERS` as bu where bu.`ID`=w.`ID_BILLING_USERS` limit 1) as BILLING_OWNER
				-- , (select bu.`STATUS` from `BILLING_USERS` as bu where bu.`ID`=w.`ID_BILLING_USERS` limit 1) as STATUS
				, bu.`STATUS`
				, bu.`BILLING_OWNER`
				, w.`NR_SPRAWY_KRD`
				, w.`NR_SPRAWY_SAD`
				, w.`NR_SPRAWY_KOMORNIK`
		";
		return $sql_select;
	}

	function &get_users( $q = '', $limit = 10, $limit_start = 0, $order_by = '', $order_dir = '' ) {
		$ret = array();

		$sql_select = self::get_sql_users_select();
		$sql_where = WindykacjaStatsModel::_parse_query( $q );
		$sql_limit = "limit " . (($limit > 0)? $limit : "10");
		if ($limit_start > 0) $sql_limit .= " offset {$limit_start}";
		$sql_order_by = "";
		$order_by_allowed = self::get_order_by_fields();
		if (in_array($order_by, $order_by_allowed)) {
			if (in_array($order_by, array('P_NAME','is_firma'))) {
				$order_by = "a.{$order_by}";
			} else if (in_array($order_by, array('BILLING_OWNER','STATUS'))) {
				$order_by = "bu.{$order_by}";
			} else if ($order_by == 'BLOKADA') {
				$order_by = "bu.`STATUS`";
			} else {
				$order_by = "w.{$order_by}";
			}
			$sql_order_by .= " order by {$order_by}";
			if (in_array($order_dir, array('DESC','ASC'))) {
				$sql_order_by .= " {$order_dir}";
			}
		}
		$sql = "select {$sql_select}
			from `USERS2_WINDYKACJA_STATUS` as w
				left join `BILLING_USERS` as bu on(bu.`ID`=w.`ID_BILLING_USERS`)
				left join `BILLING_USERS_ADD` as a on(a.`id_users`=w.`ID_BILLING_USERS`)
			where {$sql_where}
			{$sql_order_by}
			{$sql_limit}
		";
		$res = DB::query($sql);
		while ($r = DB::fetch($res)) {
			$ret[$r->id_users] = $r;
		}
		return $ret;
	}

	function &get_user_by_id( $id ) {
		$ret = null;
		if ($id <= 0) return $ret;

		$sql_select = self::get_sql_users_select();
		$sql_where = "a.`id_users`='".$id."'";
		$sql = "select " . $sql_select . "
			from `USERS2_WINDYKACJA_STATUS` as w
				left join `BILLING_USERS` as bu on(bu.`ID`=w.`ID_BILLING_USERS`)
				left join `BILLING_USERS_ADD` as a on(a.`id_users`=w.`ID_BILLING_USERS`)
			where ".$sql_where."
		";
		$res = DB::query($sql);
		if ($r = DB::fetch($res)) {
			if(0){
				$r->BA_WINIEN = "";
				$r->BA_MA = "";
				$r->BA_TIMESTAMP = "";
				$sql = "select BA.`WINIEN` as BA_WINIEN
						, BA.`MA` as BA_MA
						, unix_timestamp(BA.TIMESTAMP) as BA_TIMESTAMP
					from `BILLING_ACCOUNTS` as BA
					where BA.`ID_BILLING_USERS`='" . $r->ID . "'
				";
				$db_webone = DB::getDB('931');
				if ($db_webone) {
					$res_fin = $db_webone->query($sql);
					if ($r_fin = $db_webone->fetch($res_fin)) {
						$r->BA_WINIEN = $r_fin->BA_WINIEN;
						$r->BA_MA = $r_fin->BA_MA;
						$r->BA_TIMESTAMP = $r_fin->BA_TIMESTAMP;
					}
				}
			}
			$ret = $r;
		}
		return $ret;
	}


	function get_company( &$user ) {
		if (!isset($user->_company)) {
			/*
				id					1 / 2
				name1				"BIALL-NET" Sp. z o.o. / "NET-DAY" s.c.
				name2				--- / Adrian i Ewa Wieczorkowscy
				kod     		80-174 / 80-809
				miasto			Gdańsk, Otomin / Gdańsk
				ulica				Słoneczna / Cieszyńskiego
				numer_dom		43 / 38
				numer_pos		NULL / NULL
				uwagi				--- / ---
				tel					0-58 320-72-92 / 0-58 741 84 54
				fax					0-58 320-72-96 / 0-58 741 84 56
				nip					593-22-68-672 / 583-27-54-031
				regon				192120212 / 192578721
				bank				Bank Zachodni WBK SA I O/Gdansk / ---
				nr_rach			46 1090 1098 0000 0001 0253 7156 / 84 1500 1171 1211 7002 9997 0000
				NR_RACH_MASS_PAY		109000049887 / 109000049669
				BILLING_OWNER_EMAIL	biall-net@biall.net.pl / netday@netday.pl
			 */
			$sql = "select
					bo.`id`
					, bo.`name1`
					, bo.`name2`
					, bo.`kod`
					, bo.`miasto`
					, bo.`ulica`
					, bo.`numer_dom`
					, bo.`tel`
					, bo.`fax`
					, bo.`nip`
					, bo.`regon`
					, bo.`bank`
					, bo.`nr_rach`
					, bo.`NR_RACH_MASS_PAY`
					, bo.`BILLING_OWNER_EMAIL`
				from `BILLING_USERS` as bu
					left join `BILLING_OWNER` as bo on (bo.`ID`=bu.`BILLING_OWNER`)
				where
					bu.`ID`='" . $user->ID_BILLING_USERS . "'
			";
			//$db_webone = DB::getDB('931');
			//if ($db_webone) {
				//$res = $db_webone->query( $sql );
				//if ($r = $db_webone->fetch( $res )) {
				//	$user->_company = $r;
				//}
			//}
			$res = DB::query( $sql );
			if ($r = DB::fetch( $res )) {
				$user->_company = $r;
			}
		}
		return $user->_company;
	}


	function &get_billing_type( $type_id ) {
		$ret = null;
		$types = WindykacjaStatsModel::get_billing_types();
		if (array_key_exists($type_id, $types)) {
			$ret = $types[ $type_id ];
		}
		return $ret;
	}


	function get_billing_type_desc( $type ) {
		$ret = '';
		if ($type == 'FVAT') {
			return "Faktura Vat";
		}
		$types = WindykacjaStatsModel::get_billing_types();
		foreach ($types as $h) {
			if ($h['TYPE'] == $type) {
				return $h['DESC'];
			}
		}//end foreach
		return $ret;
	}


	function &get_billing_types( $ids = array() ) {
		static $_cache;
		if (empty($_cache)) $_cache = array();
		$cache_key = implode(".", $ids);
		if (!array_key_exists($cache_key, $_cache)) {
			$billing_types = array();
			$db_webone = DB::getDB('931');
			if ($db_webone) {
				$sql_where = "1=1";
				if (!empty($ids)) {
					$sql_where = "`ID` in ('".implode("','", $ids)."')";
				}
				$sql = "select *
					from `BILLING_NUMBERS_TYPE`
					where
						$sql_where
				";
				$res = $db_webone->query($sql);
				while ($h = $db_webone->fetch_assoc($res)) {
					$billing_types [ $h['ID'] ] = $h;
				}
			}
			$_cache[$cache_key] = $billing_types;
		}
		return $_cache[$cache_key];
	}


	function &get_umowy_from_l2( &$user ) {
		$ret = array();
		$db_webone = DB::getDB();
		if (!$db_webone) {
			return -1;
		}

		$sql = "select
				d.`ID`, d.`P_DEALPREFIX`, d.`P_DEALNUMBER`, d.`P_DEALNUMBER_OLD`, d.`P_DEALDATE`, d.`P_DEALDATE_TERM`, d.`DEALDESC`, d.`ANEX_NEEDED`, d.`ANEX_CONFIRM_DATE`
			from `DEALS_TABLE` as d
			where d.`ID_BILLING_USERS`='".$user->ID."'
			order by d.`ID` DESC
		";
		$res = $db_webone->query($sql);
		while ($h = $db_webone->fetch_assoc($res)) {
			$ret [ $h['ID'] ] = $h;
		}
		return $ret;
	}


	function &get_uslugi_from_l2( &$user ) {
		// l2: www/modules/webone/form/edit_user_status.php
		// Aktualne: Usługa [Status] => list_services2($user->ID);
		$uID = $user->ID;

		$ret = array();
		$db_webone = DB::getDB();
		if (!$db_webone) {
			return -1;
		}

		if(0){//	SERVICES table struct example:
			//[ID_BILLING_USERS] => 11363
			//[active] => 1
			//[TAB_UPDATE_STAT] => 1
			//[TAB_UPDATE_DATE] => 2012-02-03 17:43:44
			//[TAB_UPDATE_INFO] => OK-PREUPDATE-DELETED---UPDATED-OK-:195.117.2.79
			//[SERVICE_TYPE] => ABONAMENT
			//[ID_BILLING_NUMBERS_TYPE] => 1
			//[ABONAMENT_PERIOD] => 1
			//[ABONAMENT_VALUE] => 26.01
			//[VAT] => 23
			//[ID_CURRENCY] => 0
			//[ABONAMENT_PAYMENT] => UP
			//[ABONAMENT_START] => 1
			//[MINIMUM_BILLING_VALUE] => 0.00
			//[BILLED_TILL] => 2012-06-01 00:00:00
			//[HANGUP_FROM] => 
			//[HANGUP_TILL] => 
			//[HANGUP_STATUS] => 
			//[HANGUP_RATIO] => 1.00
			//[TIMESTAMP] => 20120504125053
			//[P_ID_SERVICES] => 0
			//[uwagi] => 
			//[ID_DEALS_TABLE] => 9373
			//[VAT_NAME] => 23
			//[id_list_sww] => 1
			//[SERV_ID_BILLING_PREFIXES] => 0
			//[ID_OFFERS] => 833
			//[A_RECORD_CREATE_DATE] => 
			//[A_RECORD_CREATE_AUTHOR] => 
			//[A_RECORD_UPDATE_DATE] => 
			//[A_RECORD_UPDATE_AUTHOR] => 
		}
		$sql = "select
				s.`ID`, s.`NAME_LIST_SERVICES`, s.`A_STATUS`
				, s.`ID_OFFERS`
				, s.`ID_DEALS_TABLE`
				, s.`P_ID_SERVICES`
				, s.`P_ID_SERVICES` as P_ID
				, s.`HANGUP_STATUS`
				, s.`HANGUP_FROM`
				, s.`HANGUP_TILL`
				, ls.`description` as description
				, lst.`name` as A_STATUS_DESC
			from `SERVICES` as s
				left join `LIST_SERVICES` as ls on(ls.`name`=s.`NAME_LIST_SERVICES`)
				left join `LIST_status` as lst on(lst.`ses_users2`=s.`HANGUP_STATUS` and lst.`ID`>2)
			where `ID_BILLING_USERS`='".$user->ID."'
		";
		$res = $db_webone->query($sql);
		while ($h = $db_webone->fetch_assoc($res)) {
			$ret [ $h['ID'] ] = $h;
		}
		return $ret;
	}


	function &get_umowy_from_l3( &$user ) {
		$ret = array();
		$sql = "select d.*
			from `USERS2_DEALS` as d
			where
				(d.`ID_BILLING_USERS_OLD`='".$user->ID."' or d.`ID_BILLING_USERS_NEW`='".$user->ID."')
			order by d.`ID` DESC
		";
		$res = DB::query($sql);
		while ($h = DB::fetch_assoc($res)) {
			$ret []= $h;
		}
		return $ret;
	}


	function &get_bill_dosc_by_date( &$user, $date_limit = null ) {
		// fetch finanse data from remote DB
		$billing_docs = new BillingDocs();
		$db_webone = DB::getDB('931');
		if (!$db_webone) {
			echo'<p style="color:red">'."Blad polaczenia do bazy dancyh webone_billing - Zasob [931]".'</p>';
			return;
		}
		$sql_where = " BILLS_FVAT.OPEN='N' and  BILLS_FVAT.ID_BILLING_USERS ='".$user->ID."' ";
		// blad w zaokragleniach
		//		, sum((BILLS_FVAT_POS.AMMOUNT * BILLS_FVAT_POS.PRICE)*(1 + BILLS_FVAT_POS.VAT/100)) as WARTOSC
		if ($date_limit) {
			$sql_where .= " and BILLS_FVAT.PAYMENT_TERM <= '" . $date_limit . "' ";
		}
		$sql = "select
				BILLS_FVAT.*
				, count(BILLS_FVAT_POS.ID) as ILOSC_POZYCJI
				, BILLS_FVAT_POS.ID_BILLS_FVAT
				, round(sum((BILLS_FVAT_POS.AMMOUNT * BILLS_FVAT_POS.PRICE)*(1 + BILLS_FVAT_POS.VAT/100)), 2) as WARTOSC
				-- , count(BILLS_FVAT_POS.PRICE) as ILOSC_POZYCJI
			from `BILLS_FVAT`
				left join `BILLS_FVAT_POS` on BILLS_FVAT.ID=BILLS_FVAT_POS.ID_BILLS_FVAT
			where $sql_where
			group by BILLS_FVAT.ID
			order by BILLS_FVAT.ID_BILLING_NUMBERS ASC
		";
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($sql);echo'</pre>';
		$res = $db_webone->query($sql);
		while ($h = $db_webone->fetch_assoc($res)) {
			if (0){// ? dla kazdej faktury ?
			$sql = "select t1.ID_BILLING_NUMBERS AS NR_DOK
					, t1.ID_BILLING_USERS as PLATNIK
					, t1.WINIEN,t1.MA
					, t1.ID_FIN_WINIEN as ID_F_W
					, t1.ID_FIN_WINIEN_VAL as F_WINIEN_V
					, t1.ID_FIN_MA as ID_F_M
					, t1.ID_FIN_MA_VAL as F_MA_V
					, max(t2.ID)
					, sum(t2.ID_FIN_WINIEN_VAL) as ROZ_WINIEN
					, max(t3.ID)
					, sum(t3.ID_FIN_MA_VAL) as ROZ_MA
					, t1.WINIEN - sum(t2.ID_FIN_WINIEN_VAL) - sum(t3.ID_FIN_MA_VAL) as POZ_WINIEN
					, t1.MA - sum(t3.ID_FIN_MA_VAL) - sum(t2.ID_FIN_WINIEN_VAL) as POZ_MA
				from `BILLING_ACCOUNTS_FILES` as t1
					left join `BILLING_ACCOUNTS_FILES` as t2 on (t1.ID_BILLING_NUMBERS=t2.ID_FIN_WINIEN)
					left join `BILLING_ACCOUNTS_FILES` as t3 on (t1.ID_BILLING_NUMBERS=t3.ID_FIN_MA)
				where
					t1.ID_FIN_WINIEN is NULL and t1.ID_FIN_MA is NULL and t1.MA = 0 and  t1.WINIEN > 0
					and t1.ID_BILLING_NUMBERS=".$user->ID."
				group by t1.ID_BILLING_NUMBERS
				limit 0,1
			";
			}
			//$h['type'] = 'FVAT';
			//$h['nr'] = $h['ID_BILLING_NUMBERS'];
			//$h['WINIEN'] = $h['WARTOSC'];
			//$h['MA'] = 0;
			$billing_docs->add_bill_doc( $h['PAYMENT_TERM'], 'FVAT', $h );
		}

		$faktury_cols = array();
		//$faktury_cols['ID_BILLING_USERS'] = "id klienta";// 
		$faktury_cols['ID_BILLING_NUMBERS'] = "numer";// numer faktury
		$faktury_cols['BILL_DATE'] = "";// data('Y-m-d')
		$faktury_cols['SELL_DATE'] = "";// data('Y-m-d')
		$faktury_cols['PAYMENT_TERM'] = "";// data('Y-m-d')

		//$billing_types = WindykacjaStatsModel::get_billing_types( array(3, 4, 5, 7, 8) );
		$billing_types = WindykacjaStatsModel::get_billing_types();

		foreach ($billing_types as $bill_type) {
			if ($bill_type['CLASS'] == 'FINANCE') {
				$sql_where = ($date_limit)? " and ".$bill_type['TABLE'].".BILL_DATE <= '" . $date_limit . "' " : "";
				$sql = "select ".$bill_type['TABLE'].".ID
						, ".$bill_type['TABLE'].".ID_BILLING_NUMBERS
						, ".$bill_type['TABLE'].".BILL_DATE
						, round(".$bill_type['TABLE'].".WINIEN, 2) as WINIEN
						, round(".$bill_type['TABLE'].".MA, 2) as MA
						, ".$bill_type['TABLE'].".ID_FK_DEKRET
						, ".$bill_type['TABLE'].".OPEN
						, ".$bill_type['TABLE'].".FK_ZAKSIEG
						, ".$bill_type['TABLE'].".do_dokumentu
						, ".$bill_type['BILLING_NUMBERS_TABLE'].".NUMBER
						, ".$bill_type['BILLING_NUMBERS_TABLE'].".ID_BILLING_PREFIXES
						, ".$bill_type['BILLING_NUMBERS_TABLE'].".ID_BILLING_NUMBERS_TYPE
					from ".$bill_type['TABLE']."
						left join ".$bill_type['BILLING_NUMBERS_TABLE']." on (".$bill_type['BILLING_NUMBERS_TABLE'].".ID=".$bill_type['TABLE'].".ID_BILLING_NUMBERS)
					where ".$bill_type['TABLE'].".ID_BILLING_USERS='".$user->ID."'
						".$sql_where."
				";
				$res = $db_webone->query($sql);
				while ($h = $db_webone->fetch_assoc($res)) {
					$billing_docs->add_bill_doc( $h['BILL_DATE'], $bill_type['TYPE'], $h );
				}
			}
			else if ($bill_type['CLASS'] == 'SELL_MA') {
				$sql_where = ($date_limit)? " and ".$bill_type['TABLE'].".BILL_DATE <= '" . $date_limit . "' " : "";
				$sql = "select ".$bill_type['TABLE'].".ID
						, count(".$bill_type['TABLE']."_POS.ID) as cnt
						, ".$bill_type['TABLE']."_POS.ID_BILLS_FVAT
						, ".$bill_type['TABLE'].".ID_CURRENCY
						, round(sum((".$bill_type['TABLE']."_POS.N_AMMOUNT * ".$bill_type['TABLE']."_POS.N_PRICE) * ( 1 + ".$bill_type['TABLE']."_POS.N_VAT / 100)),2) as WINIEN
						, round(sum( 
								((".$bill_type['TABLE']."_POS.AMMOUNT * ".$bill_type['TABLE']."_POS.PRICE) * ( 1 + ".$bill_type['TABLE']."_POS.VAT / 100))
								- (".$bill_type['TABLE']."_POS.N_AMMOUNT * ".$bill_type['TABLE']."_POS.N_PRICE * ".$bill_type['TABLE']."_POS.N_VAT / 100)
								+ (".$bill_type['TABLE']."_POS.N_AMMOUNT * ".$bill_type['TABLE']."_POS.N_PRICE * ".$bill_type['TABLE']."_POS.VAT / 100)
							),2) as MA
						, ".$bill_type['TABLE'].".ID_BILLING_NUMBERS , ".$bill_type['TABLE'].".OPEN , ".$bill_type['TABLE'].".FK_ZAKSIEG
						, ".$bill_type['TABLE'].".IF_KORV , ".$bill_type['TABLE'].".BILL_DATE , ".$bill_type['BILLING_NUMBERS_TABLE'].".NUMBER
					from ".$bill_type['TABLE']."
						left join ".$bill_type['BILLING_NUMBERS_TABLE']." on ".$bill_type['BILLING_NUMBERS_TABLE'].".ID=".$bill_type['TABLE'].".ID_BILLING_NUMBERS
						left join ".$bill_type['TABLE']."_POS on ".$bill_type['TABLE'].".ID=".$bill_type['TABLE']."_POS.ID_BILLS_FVAT
					where ".$bill_type['TABLE'].".ID_BILLING_USERS='".$user->ID."'
						".$sql_where."
					group by ".$bill_type['TABLE'].".ID
					order by ".$bill_type['TABLE'].".ID
				";
				$res = $db_webone->query($sql);
				while ($h = $db_webone->fetch_assoc($res)) {
					$billing_docs->add_bill_doc( $h['BILL_DATE'], $bill_type['TYPE'], $h );
				}
			}
		}//end foreach

		return $billing_docs;
	}


	/**
	 * @used in FunkcjeL1::billing_billwiev_przeterminowania
	 */
	function &get_billing_account_files( $user_id ) {
		$baf = array();
		$ECHO_PARAM = '';
		$ID_BILLING_USERS_PARAM = $user_id;

		$db_webone = DB::getDB('931');
		if (!$db_webone) {
			echo'<p style="color:red">'."Blad polaczenia do bazy dancyh webone_billing - Zasob [931]".'</p>';
			return $baf;
		}

		$WHERE = "";
		if ($ID_BILLING_USERS_PARAM) $WHERE .= " and BAF.ID_BILLING_USERS='$ID_BILLING_USERS_PARAM' ";
		//UZGODNIENIE_SALD
		if (strstr($ECHO_PARAM, 'saldo_rok')) {
			global $base_path ;
			include_once($base_path."/modules/billing/bill/modules/billing_financefunc.inc");
			if ($ID_BILLING_USERS_PARAM) {
				if ($vdb->sql_numrows($vdb->sql_query("select ID from BILLING_ACCOUNTS_TILL where ID_BILLING_USERS='$ID_BILLING_USERS_PARAM' and TILL=YEAR(NOW())-1 ;")) != 1) {
					UAKTUALNIJ_KONTA($ID_BILLING_USERS_PARAM);
				}
			}
			$WHERE .= " AND YEAR(BN.TIMESTAMP)<YEAR(NOW()) ";
		}
		$WHERE_FIRMA = "";
		if ($_GET['FIRMA']) $WHERE_FIRMA = "and BILLING_USERS.BILLING_OWNER='".$_GET['FIRMA']."'" ;
		//$billing_account_files = WindykacjaStatsModel::
		$sql = "create temporary table TEMP_BILLING_ACCOUNTS_FILES
			select BAF.ID
				, BAF.ID_BILLING_USERS
				, BAF.WINIEN
				, BAF.MA
				, BAF.ID_BILLING_NUMBERS_TYPE
				, BN.NUMBER
				, BN.ID_BILLING_PREFIXES
				, BAF_WINIEN.ID_FIN_WINIEN
				, BAF_WINIEN.ID_BILLING_NUMBERS_TYPE as ID_BILLING_NUMBERS_TYPE_W
				, BAF_BN_WINIEN.NUMBER as NUMBER_W
				, BAF_BN_WINIEN.ID_BILLING_PREFIXES as ID_BILLING_PREFIXES_W
				, unix_timestamp(BAF_BN_WINIEN.TIMESTAMP) as TIMESTAMP_W
				, BAF_WINIEN.ID_FIN_WINIEN_VAL
				, NULL as ID_FIN_MA
				, NULL as	ID_BILLING_NUMBERS_TYPE_M
				, NULL as	NUMBER_M
				, NULL as ID_BILLING_PREFIXES_M
				, NULL as TIMESTAMP_M
				, NULL as	ID_FIN_MA_VAL
				, unix_timestamp(ifnull(BILLS_FVAT.PAYMENT_TERM, BILLS_KORV.PAYMENT_TERM)) as TERMIN_PL
				, BUA.P_NAME
				, BUA.P_NAME_SECOND
				, BUA.P_ADDRESS_CITY
				, BUA.P_ADDRESS_STREET
				, BUA.P_ADDRESS_HOUSE
				, BUA.P_ADDRESS_HOME
				, BUA.user_mail_contact
				, BA.WINIEN as BA_WINIEN
				, BA.MA as BA_MA
				, unix_timestamp(BA.TIMESTAMP) as BA_TIMESTAMP
				, unix_timestamp(BAF.TIMESTAMP) as BAF_TIMESTAMP
			from BILLING_ACCOUNTS_FILES as BAF
				left join BILLING_USERS on BILLING_USERS.ID=BAF.ID_BILLING_USERS 
				left join BILLING_USERS_ADD  as BUA on BUA.id_users=BAF.ID_BILLING_USERS
				left join BILLING_NUMBERS as BN on BN.ID=BAF.ID_BILLING_NUMBERS 
				left join BILLING_ACCOUNTS as BA on BA.ID_BILLING_USERS=BAF.ID_BILLING_USERS
				left join BILLS_FVAT on BILLS_FVAT.ID_BILLING_NUMBERS=BAF.ID_BILLING_NUMBERS 
				left join BILLS_KORV on BILLS_KORV.ID_BILLING_NUMBERS=BAF.ID_BILLING_NUMBERS 
				left join BILLING_ACCOUNTS_FILES as BAF_WINIEN on BAF_WINIEN.ID_FIN_WINIEN=BAF.ID_BILLING_NUMBERS 
				left join BILLING_NUMBERS as BAF_BN_WINIEN on BAF_BN_WINIEN.ID=BAF_WINIEN.ID_BILLING_NUMBERS
			where BAF.ID_FIN_WINIEN is NULL and BAF.ID_FIN_MA is NULL and BAF.ID_FIN_WINIEN is NULL
				$WHERE
				$WHERE_FIRMA
		";

		$sql2 = "insert into TEMP_BILLING_ACCOUNTS_FILES
			select BAF.ID
				, BAF.ID_BILLING_USERS
				, BAF.WINIEN
				, BAF.MA
				, BAF.ID_BILLING_NUMBERS_TYPE
				, BN.NUMBER
				, BN.ID_BILLING_PREFIXES
				, NULL as ID_FIN_WINIEN
				, NULL as ID_BILLING_NUMBERS_TYPE_W
				, NULL as NUMBER_W
				, NULL as ID_BILLING_PREFIXES_W
				, NULL as TIMESTAMP_W
				, NULL as ID_FIN_WINIEN_VAL
				, BAF_MA.ID_FIN_MA
				, BAF_MA.ID_BILLING_NUMBERS_TYPE as ID_BILLING_NUMBERS_TYPE_M
				, BAF_BN_MA.NUMBER as NUMBER_M
				, BAF_BN_MA.ID_BILLING_PREFIXES as ID_BILLING_PREFIXES_M
				, unix_timestamp(BAF_BN_MA.TIMESTAMP) as TIMESTAMP_M
				, BAF_MA.ID_FIN_MA_VAL
				, unix_timestamp(ifnull(BILLS_FVAT.PAYMENT_TERM, BILLS_KORV.PAYMENT_TERM))
				, BUA.P_NAME
				, BUA.P_NAME_SECOND
				, BUA.P_ADDRESS_CITY
				, BUA.P_ADDRESS_STREET
				, BUA.P_ADDRESS_HOUSE
				, BUA.P_ADDRESS_HOME
				, BUA.user_mail_contact
				, BA.WINIEN as BA_WINIEN
				, BA.MA as BA_MA
				, unix_timestamp(BA.TIMESTAMP) as BA_TIMESTAMP
				, unix_timestamp(BAF.TIMESTAMP) as BAF_TIMESTAMP
			from BILLING_ACCOUNTS_FILES as BAF
				left join BILLING_USERS on (BILLING_USERS.ID=BAF.ID_BILLING_USERS)
				left join BILLING_USERS_ADD as BUA on (BUA.id_users=BAF.ID_BILLING_USERS)
				left join BILLING_NUMBERS as BN on (BN.ID=BAF.ID_BILLING_NUMBERS)
				left join BILLING_ACCOUNTS as BA on (BA.ID_BILLING_USERS=BAF.ID_BILLING_USERS)
				left join BILLS_FVAT on (BILLS_FVAT.ID_BILLING_NUMBERS=BAF.ID_BILLING_NUMBERS)
				left join BILLS_KORV on (BILLS_KORV.ID_BILLING_NUMBERS=BAF.ID_BILLING_NUMBERS)
				left join BILLING_ACCOUNTS_FILES as BAF_MA on (BAF_MA.ID_FIN_MA=BAF.ID_BILLING_NUMBERS)
				left join BILLING_NUMBERS as BAF_BN_MA on (BAF_BN_MA.ID=BAF_MA.ID_BILLING_NUMBERS)
			where
				BAF.ID_FIN_WINIEN is NULL and BAF.ID_FIN_MA is NULL
				$WHERE
				$WHERE_FIRMA
		";
		if (strstr($ECHO_PARAM,'saldo_rok')) {
			$sql = "create temporary table TEMP_BILLING_ACCOUNTS_FILES
				select
					BAF.ID, BAF.ID_BILLING_USERS , BAF.WINIEN, BAF.MA, BAF.ID_BILLING_NUMBERS_TYPE, BN.NUMBER , BN.ID_BILLING_PREFIXES,
					BAF_WINIEN.ID_FIN_WINIEN,
					BAF_WINIEN.ID_BILLING_NUMBERS_TYPE as  ID_BILLING_NUMBERS_TYPE_W,
					BAF_BN_WINIEN.NUMBER as  NUMBER_W,
					BAF_BN_WINIEN.ID_BILLING_PREFIXES as  ID_BILLING_PREFIXES_W,
					unix_timestamp(BAF_BN_WINIEN.TIMESTAMP) as  TIMESTAMP_W,
					BAF_WINIEN.ID_FIN_WINIEN_VAL,
					NULL as  ID_FIN_MA, 
					NULL as	 ID_BILLING_NUMBERS_TYPE_M,
					NULL as	 NUMBER_M,
					NULL as  ID_BILLING_PREFIXES_M,
					NULL as  TIMESTAMP_M,
					NULL as	 ID_FIN_MA_VAL,
					unix_timestamp(ifnull(BILLS_FVAT.PAYMENT_TERM,ifnull( BILLS_KORV.PAYMENT_TERM,BN.TIMESTAMP ))) as TERMIN_PL ,
					BUA.P_NAME , BUA.P_NAME_SECOND  , BUA.P_ADDRESS_CITY , BUA.P_ADDRESS_STREET ,BUA.P_ADDRESS_HOUSE  , BUA.P_ADDRESS_HOME , BUA.user_mail_contact ,
					BA.WINIEN as BA_WINIEN , BA.MA as BA_MA , unix_timestamp(BA.TIMESTAMP) as BA_TIMESTAMP,
					unix_timestamp(BAF.TIMESTAMP) as BAF_TIMESTAMP, 
					BILLING_ACCOUNTS_TILL.TILL as BAT_TILL , BILLING_ACCOUNTS_TILL.WINIEN as BAT_WINIEN, BILLING_ACCOUNTS_TILL.MA as BAT_MA 
				from BILLING_ACCOUNTS_FILES as BAF
					left join BILLING_USERS_ADD  as BUA on BUA.id_users=BAF.ID_BILLING_USERS
					left join BILLING_NUMBERS as BN on BN.ID=BAF.ID_BILLING_NUMBERS 
					left join BILLING_ACCOUNTS as BA on BA.ID_BILLING_USERS=BAF.ID_BILLING_USERS
					left join BILLS_FVAT on BILLS_FVAT.ID_BILLING_NUMBERS=BAF.ID_BILLING_NUMBERS 
					left join BILLS_KORV on BILLS_KORV.ID_BILLING_NUMBERS=BAF.ID_BILLING_NUMBERS 
					left join BILLING_ACCOUNTS_FILES as BAF_TRG on ( BAF.ID_FIN_WINIEN=BAF_TRG.ID_BILLING_NUMBERS or BAF.ID_FIN_MA=BAF_TRG.ID_BILLING_NUMBERS )
					left join BILLING_NUMBERS as BAF_TRG_BN on ( BAF_TRG.ID_BILLING_NUMBERS=BAF_TRG_BN.ID )
					left join BILLING_ACCOUNTS_FILES as BAF_WINIEN on ( BAF_WINIEN.ID_FIN_WINIEN=BAF.ID_BILLING_NUMBERS or BAF_WINIEN.ID_FIN_MA=BAF.ID_BILLING_NUMBERS )
					left join BILLING_NUMBERS as BAF_BN_WINIEN on ( BAF_BN_WINIEN.ID=BAF_WINIEN.ID_BILLING_NUMBERS )
					left join BILLING_ACCOUNTS_TILL on (BILLING_ACCOUNTS_TILL.ID_BILLING_USERS=BAF.ID_BILLING_USERS and BILLING_ACCOUNTS_TILL.TILL=year(now())-1  ) 
				where 
					( 	BAF.ID_FIN_WINIEN is NULL and BAF.ID_FIN_MA is NULL or year(BAF_TRG_BN.TIMESTAMP)>year(NOW())-1   )
					and (YEAR(BAF_BN_WINIEN.TIMESTAMP)<YEAR(NOW()) or BAF_BN_WINIEN.TIMESTAMP is NULL ) 	 
					$WHERE   
				limit 2000 ;
			";

			$sql2 = " insert into TEMP_BILLING_ACCOUNTS_FILES select
					BAF.ID, BAF.ID_BILLING_USERS , BAF.WINIEN, BAF.MA, BAF.ID_BILLING_NUMBERS_TYPE, BN.NUMBER , BN.ID_BILLING_PREFIXES,
					NULL as ID_FIN_WINIEN,
					NULL as ID_BILLING_NUMBERS_TYPE_W,
					NULL as NUMBER_W ,
					NULL as ID_BILLING_PREFIXES_W,
					NULL as TIMESTAMP_W ,
					NULL as ID_FIN_WINIEN_VAL ,
					BAF_MA.ID_FIN_MA,
					BAF_MA.ID_BILLING_NUMBERS_TYPE as ID_BILLING_NUMBERS_TYPE_M,
					BAF_BN_MA.NUMBER as NUMBER_M,
					BAF_BN_MA.ID_BILLING_PREFIXES as ID_BILLING_PREFIXES_M,
					unix_timestamp(BAF_BN_MA.TIMESTAMP) as TIMESTAMP_M,
					BAF_MA.ID_FIN_MA_VAL,
					unix_timestamp(ifnull(BILLS_FVAT.PAYMENT_TERM,ifnull( BILLS_KORV.PAYMENT_TERM,BN.TIMESTAMP ))) as TERMIN_PL ,

					BUA.P_NAME , BUA.P_NAME_SECOND  , BUA.P_ADDRESS_CITY , BUA.P_ADDRESS_STREET ,BUA.P_ADDRESS_HOUSE  , BUA.P_ADDRESS_HOME , BUA.user_mail_contact ,
					BA.WINIEN as BA_WINIEN , BA.MA as BA_MA , unix_timestamp(BA.TIMESTAMP) as BA_TIMESTAMP,
					unix_timestamp(BAF.TIMESTAMP) as BAF_TIMESTAMP,
					BILLING_ACCOUNTS_TILL.TILL as BAT_TILL , BILLING_ACCOUNTS_TILL.WINIEN as BAT_WINIEN, BILLING_ACCOUNTS_TILL.MA as BAT_MA 
				from BILLING_ACCOUNTS_FILES as BAF
					left join BILLING_USERS_ADD  as BUA on BUA.id_users=BAF.ID_BILLING_USERS
					left join BILLING_NUMBERS as BN on BN.ID=BAF.ID_BILLING_NUMBERS
					left join BILLING_ACCOUNTS as BA on BA.ID_BILLING_USERS=BAF.ID_BILLING_USERS
					left join BILLS_FVAT on BILLS_FVAT.ID_BILLING_NUMBERS=BAF.ID_BILLING_NUMBERS
					left join BILLS_KORV on BILLS_KORV.ID_BILLING_NUMBERS=BAF.ID_BILLING_NUMBERS 
					left join BILLING_ACCOUNTS_FILES as BAF_TRG on ( BAF.ID_FIN_WINIEN=BAF_TRG.ID_BILLING_NUMBERS or BAF.ID_FIN_MA=BAF_TRG.ID_BILLING_NUMBERS )
					left join BILLING_NUMBERS as BAF_TRG_BN on ( BAF_TRG.ID_BILLING_NUMBERS=BAF_TRG_BN.ID )
					left join BILLING_ACCOUNTS_FILES as BAF_MA on ( BAF_MA.ID_FIN_WINIEN=BAF.ID_BILLING_NUMBERS or BAF_MA.ID_FIN_MA=BAF.ID_BILLING_NUMBERS )
					left join BILLING_NUMBERS as BAF_BN_MA on ( BAF_BN_MA.ID=BAF_MA.ID_BILLING_NUMBERS )
					left join BILLING_ACCOUNTS_TILL on (BILLING_ACCOUNTS_TILL.ID_BILLING_USERS=BAF.ID_BILLING_USERS and BILLING_ACCOUNTS_TILL.TILL=year(now())-1  ) 
				where
					( 	BAF.ID_FIN_WINIEN is NULL and BAF.ID_FIN_MA is NULL or year(BAF_TRG_BN.TIMESTAMP)>year(NOW())-1   )
					and BAF.ID_BILLING_USERS='1047'  AND YEAR(BN.TIMESTAMP)<YEAR(NOW())  
					and  (YEAR(BAF_BN_MA.TIMESTAMP)<YEAR(NOW())  or BAF_BN_MA.TIMESTAMP is NULL ) 	 
					$WHERE
				limit 1000,1000 ;
			";
		}//EOF if saldo_rok param

		$sql_alter = "alter table TEMP_BILLING_ACCOUNTS_FILES
			modify ID_FIN_MA int(11)
			, modify ID_BILLING_NUMBERS_TYPE_M int(2)
			, modify NUMBER_M int(10)
			, modify ID_BILLING_PREFIXES_M int(2) default NULL NULL
			, modify TIMESTAMP_M int(10)
			, modify ID_FIN_MA_VAL decimal(10,2)
			, modify ID_BILLING_PREFIXES int(2) default NULL NULL
			, modify ID_BILLING_PREFIXES_W int(2)  default NULL NULL
		";

		$db_webone->query( "drop TEMPORARY table TEMP_BILLING_ACCOUNTS_FILES" );
		$result_create = $db_webone->query( $sql );
		$result_alter = $db_webone->query( $sql_alter );
		$result_create2 = $db_webone->query( $sql2 );
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">db_webone: ';print_r($db_webone);echo'</pre>';

		$sql = "select * from TEMP_BILLING_ACCOUNTS_FILES  order by ID_BILLING_USERS,ID ";
		$sql_count = "select count(1) as cnt from TEMP_BILLING_ACCOUNTS_FILES ";
		$count = 0;
		$res = $db_webone->query( $sql_count );
		if ($r_count = $db_webone->fetch( $res )) {
			$count = $r_count->cnt;
		}
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">count: ';print_r($count);echo'</pre>';
		if ($count > 0 && $ID_BILLING_USERS_PARAM > 0) {
			$result = $db_webone->query($sql);
		} else {
			$sql_none = "insert into TEMP_BILLING_ACCOUNTS_FILES (ID,ID_BILLING_USERS,BAT_TILL,BAT_WINIEN,BAT_MA)
				select '0',ID_BILLING_USERS,TILL ,WINIEN ,MA from BILLING_ACCOUNTS_TILL where ID_BILLING_USERS='$ID_BILLING_USERS_PARAM' and TILL=YEAR(NOW())-1
			";
			$db_webone->query( $sql_none );
			$result = $db_webone->query($sql);
		}
		while ($h_baf = $db_webone->fetch_row($result)) {
			$baf []= $h_baf;
		}
		return $baf;
	}


	function update_doc_number( &$fvat_arr ) {
		$fetch_ids = array();
		foreach ($fvat_arr as $k => $fvat) {
			$fetch_ids []= $fvat['ID_BILLING_NUMBERS'];
		}//end foreach
		if (!empty($fetch_ids)) {
			$db_webone = DB::getDB('931');
			if (!$db_webone) {
				return -1;
			}

			$sql = "select `ID`, `NUMBER`, `ID_BILLING_PREFIXES`
				from `BILLING_NUMBERS`
				where
					`ID` in(".implode(",", $fetch_ids).")
			";
			$res = $db_webone->query( $sql );
			$bnum = array();
			while ($h = $db_webone->fetch_assoc( $res )) {
				$bnum [ $h['ID'] ] = $h;
			}
			foreach ($bnum as $k_id => $bn) {
				foreach ($fvat_arr as $k_fvat => $fvat) {
					if ($bn['ID'] == $fvat['ID_BILLING_NUMBERS']) {
						$fvat_arr[ $k_fvat ]['NUMBER'] = $bn['NUMBER'];
						$fvat_arr[ $k_fvat ]['ID_BILLING_PREFIXES'] = $bn['ID_BILLING_PREFIXES'];
					}
				}//end foreach				
			}//end foreach
		}
	}

	/**
	 * @param $user - Windykacja status user
	 * @param $taks - wezwanie1, wezwanie2
	 * @param $id_proj - ID Projektu
	 * @returns int - ID created record
	 */
	function create_koresp($user, $task, $id_proj, $params = array()) {
		$sql_data = array();
		$sql_zawartosc = '';
		if ($task == 'wezwanie1') {
			$sql_zawartosc = 'wezwanie do zaplaty';
			$sql_data['K_TYP_KORESP'] = 'OUT';
			$sql_data['K_TYP_RODZAJ'] = 'POLECONY';
			$sql_data['K_LOKALIZACJA'] = 'PROJEKT';
			$sql_data['K_LOKALIZACJA_NEW'] = 'PROJEKT';
		} else if ($task == 'wezwanie2') {
			$sql_zawartosc = 'wezwanie do zaplaty - ostateczne';
			$sql_data['K_TYP_KORESP'] = 'OUT';
			$sql_data['K_TYP_RODZAJ'] = 'POLECONY';
			$sql_data['K_LOKALIZACJA'] = 'PROJEKT';
			$sql_data['K_LOKALIZACJA_NEW'] = 'PROJEKT';
		} else if ($task == 'rozwiazanie umowy') {
			$sql_zawartosc = 'rozwiazanie umowy ID ' . $params['nr_umowy'] . ' - ' . $params['powod_desc'];
			$sql_data['K_TYP_KORESP'] = 'IN';
		}
		if (!$sql_zawartosc) {
			return false;
		}

/**
 * przykładowe wezwania:
 *   SELECT * FROM `IN7_DZIENNIK_KORESP` WHERE `K_ZAWARTOS` LIKE '%wezwanie%' ORDER BY `IN7_DZIENNIK_KORESP`.`ID` DESC;
 * przykład:
 *   SELECT * FROM `IN7_DZIENNIK_KORESP` WHERE `ID`=25951;
 */

		$db = DB::getDB();
		$sql_obj = new stdClass();
		$sql_obj->A_STATUS = 'WAITING';
		foreach ($sql_data as $k_field => $v_value) {
			$sql_obj->$k_field = $v_value;
		}
		$sql_obj->ID_BILLING_USERS = $user->ID;
		$sql_obj->K_DATA_OTRZYM_KORESP = '';// data ?
		$sql_obj->K_DATA_OTRZYMANEJ_KORESP = '';// data ?
		$sql_obj->K_OD_KOGO = "{$user->P_NAME} {$user->P_NAME_SECOND}";
		$sql_obj->OD_KOGO_ADRES = "ul. {$user->P_ADDRESS_STREET} {$user->P_ADDRESS_HOUSE}/{$user->P_ADDRESS_HOME}, {$user->P_ADDRESS_POST_CODE} {$user->P_ADDRESS_CITY}";
		$sql_obj->K_ZAWARTOS = $sql_zawartosc;
		$sql_obj->K_ZNAK_REFERENTA = User::getFullName() . ' (' . User::getInicjaly() . ')';
		$sql_obj->ID_PROJECT = $id_proj;
		$ret_id = $db->ADD_NEW_OBJ('IN7_DZIENNIK_KORESP', $sql_obj);
		return $ret_id;
	}

	/**
	 * @param int $user_id - IS klienta
	 * @param int $id_deals_old - ID umowy do wyłączenia
	 * @param date 'Y-m-d' $termin_odlaczenia - Termin odłączenia
	 * @returns int - ID created record
	 */
	function create_deals_rozwiazanie($user_id, $id_deals_old, $termin_odlaczenia, $powod_desc = '') {
		$db = DB::getDB();
		$old_deal = $db->get_by_id('DEALS_TABLE', $id_deals_old);
		if (!$old_deal) {
			return false;
		}

		$sql_obj = new stdClass();
		$sql_obj->DEALDESC = "Rezygnacja z dniem {$termin_odlaczenia}";
		$sql_obj->A_STATUS = 'WAITING';
		$sql_obj->ID_BILLING_USERS = $user_id;
		$sql_obj->P_DEALNUMBER_OLD = $old_deal->ID;
		$sql_obj->S_ADDRESS_STREET = $old_deal->S_ADDRESS_STREET;
		$sql_obj->P_DEALDATE = $old_deal->P_DEALDATE;
		$sql_obj->P_DEALDATE_TERM = $old_deal->P_DEALDATE_TERM;
		$sql_obj->L2_HANGUP_FROM = $termin_odlaczenia;
		$sql_obj->RODZAJ_DZIALANIA_HANDLOWEGO = $powod_desc;
		// TODO: $sql_obj->ID_OFFERS_OFF = get_active_services_id($old_deal->ID);
/*
		if(
			SV.HANGUP_STATUS=SV.A_STATUS
			, coalesce(SV.A_STATUS)
			, if(
				( unix_timestamp(NOW()) > unix_timestamp(SV.HANGUP_FROM)
					and  ( SV.HANGUP_TILL='0000-00-00' or SV.HANGUP_TILL is NULL )
					and ( SV.HANGUP_FROM<>'0000-00-00' and SV.HANGUP_FROM is not null )
				)
				, coalesce(SV.HANGUP_STATUS)
				, if(
					( unix_timestamp(NOW()) < unix_timestamp(SV.HANGUP_FROM) 
						and (SV.HANGUP_TILL='0000-00-00' or SV.HANGUP_TILL is NULL )
						and ( SV.HANGUP_FROM<>'0000-00-00' and SV.HANGUP_FROM is not null )
					)
					, coalesce(SV.A_STATUS)
					, if(
						( unix_timestamp(NOW()) > unix_timestamp(SV.HANGUP_FROM)
							and unix_timestamp(NOW()) < unix_timestamp(SV.HANGUP_TILL)
							and ( SV.HANGUP_TILL<>'0000-00-00' and SV.HANGUP_TILL is not NULL )
							and ( SV.HANGUP_FROM<>'0000-00-00' and SV.HANGUP_FROM is not null )
						)
					, coalesce(SV.HANGUP_STATUS)
					, if(
							( unix_timestamp(NOW()) < unix_timestamp(SV.HANGUP_FROM) and  unix_timestamp(NOW())< unix_timestamp(SV.HANGUP_TILL) 
			and  ( SV.HANGUP_TILL<>'0000-00-00' and SV.HANGUP_TILL is not NULL )
			and ( SV.HANGUP_FROM<>'0000-00-00' and SV.HANGUP_FROM is not null ))
							, coalesce(SV.A_STATUS)
							, if(
									(	( SV.HANGUP_TILL='0000-00-00' or SV.HANGUP_TILL is NULL )
			and ( SV.HANGUP_FROM='0000-00-00' or SV.HANGUP_FROM is null ))
									, coalesce(SV.A_STATUS)
									, if( unix_timestamp(NOW()) > unix_timestamp(SV.HANGUP_FROM)
											and  unix_timestamp(NOW()) > unix_timestamp(SV.HANGUP_TILL)
											and (
												( SV.HANGUP_TILL<>'0000-00-00' and SV.HANGUP_TILL is not NULL )
												and ( SV.HANGUP_FROM<>'0000-00-00' and SV.HANGUP_FROM is not null )
											)
										, coalesce(SV.A_STATUS)
										, if(
											unix_timestamp(NOW()) > unix_timestamp(SV.HANGUP_FROM)
											and unix_timestamp(NOW()) > unix_timestamp(SV.HANGUP_TILL)
											and SV.HANGUP_FROM<SV.HANGUP_TILL
											and (
			( SV.HANGUP_TILL<>'0000-00-00' and SV.HANGUP_TILL is not NULL )
			and ( SV.HANGUP_FROM<>'0000-00-00' and SV.HANGUP_FROM is not null )) , 'ERROR1', 
			'ERROR2'
			)
			)      
			)    
			)
			)
			)    
			)
		)
 */
/*
		$id_offers_off = array();
		$sql = "select
				s.``
				, s.`ID_OFFERS`
			from `SERVICES` as s
			where
				s.`ID_DEALS_TABLE`='{$old_deal->ID}'
				and s.`ID_BILLING_USERS`='{$user_id}'
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$id_offers_off []= $r;
		}
 */
		$ret_id = $db->ADD_NEW_OBJ('DEALS_TABLE', $sql_obj);
		return $ret_id;
	}

}


class Lay_Html_Toggle {


	function start( $title, $attrs = array() ){
		$cls = array();
		$cls []= 'may-hide';
		if (array_key_exists('open', $attrs) && $attrs['open'] == false) $cls []= 'hide';
		echo'<div class="'.implode(' ', $cls).'">';
		$st = array();
		$st []= 'margin-bottom:0';
		if (!empty($attrs['color'])) $st []= 'color:'.$attrs['color'];
		echo'<h4 style="'.implode(';', $st).'">'.$title;
			echo'<a class="btn-hide" href="#" onclick="'."return hide(this);".'">'."-".'</a>';
			echo'<a class="btn-show" href="#" onclick="'."return hide(this);".'">'."+".'</a>';
		echo'</h4>';
		echo'<div class="to-hide">';
	}


	function end(){
			echo'</div>';// .to-hide
		echo'</div>';// .may-hide'
	}


	function show_js() {
		echo'<script type="text/javascript">'."
		function hide( n ){
			jQuery(n).parent().parent().toggleClass('hide');
			return false;
		}
		".'</script>';
	}


}


class FunkcjeL1 {


	function bankowy_make_nrach($NR_RACH_MASS_PAY,$ID_BILLING_USERS,$ID_BILLING_NUMBERS) {
		//echo "TTUTAJ <hr> AASDADS f. bankowy_make_nrach($NR_RACH_MASS_PAY,$ID_BILLING_USERS,$ID_BILLING_NUMBERS) <br>";
		$ID_BILLING_USERS=str_pad($ID_BILLING_USERS,10,0,STR_PAD_LEFT) ;
		$ID_BILLING_NUMBERS=str_pad($ID_BILLING_NUMBERS,2,0,STR_PAD_LEFT) ; 
		$ID_BILLING_NUMBERS=substr($ID_BILLING_NUMBERS,-2) ; 
		$NN = self::bankowy_make($NR_RACH_MASS_PAY.$ID_BILLING_NUMBERS.$ID_BILLING_USERS) ;
		if($NN) return $NN.$NR_RACH_MASS_PAY.$ID_BILLING_NUMBERS.$ID_BILLING_USERS ;
	}


	function bankowy_make($nrb) {
			$nrb=preg_replace("/[^0-9]/","",$nrb);
			if (strlen($nrb)<>24) return 0;
		$nrb .="252100";
					$modulo=self::my_bcmod($nrb,97) ;
					$modulo= 98 - $modulo ;
		if(strlen($modulo)==1) $modulo="0".$modulo ;
		return $modulo ;
		if ($nrb[0]==$liczba[0] and $nrb[1]==$liczba[1]){
				return 1;
		}
		return 0;
	}


	function my_bcmod( $x, $y ) {
		 // how many numbers to take at once? carefull not to exceed (int)
		 $take = 5;    
		 $mod = '';
		 do
		 {
				 $a = (int)$mod.substr( $x, 0, $take );
				 $x = substr( $x, $take );
				 $mod = $a % $y;    
		 } 
		 while ( strlen($x) );
		 return (int)$mod;
	}


	function bankowy_formatuj_nrach($NR_RACH_MASS_PAY) {
		$NR_RACH_MASS_PAY_FORMATTED = '';
		if ($NR_RACH_MASS_PAY) {
			for ($i=4; $i<(strlen($NR_RACH_MASS_PAY)); $i=$i+4) {
				$NR_RACH_MASS_PAY_FORMATTED = " ".substr($NR_RACH_MASS_PAY,-$i,4).$NR_RACH_MASS_PAY_FORMATTED;
			}
			$NR_RACH_MASS_PAY_FORMATTED = substr($NR_RACH_MASS_PAY,0,$i-strlen($NR_RACH_MASS_PAY))." ".$NR_RACH_MASS_PAY_FORMATTED;
		}
		return $NR_RACH_MASS_PAY_FORMATTED ;
	}


	function policz($l,$t1,$t2,$t3) {
		$j = array("", "jeden ", "dwa ", "trzy ", "cztery ", "pięć ", "sześć ",
		"siedem ", "osiem ", "dziewięć ", "dziesięć ", "jedenaście ", 
		"dwanaście ", "trzynaście ", "czternaście ", "piętnaście ", 
		"szesnaście ", "siedemnaście ", "osiemnaście ", "dziewiętnaście ");
		$d = array("", "", "dwadzieścia ", "trzydzieści ", "czterdzieści ",
		"pięćdziesiąt ", "sześćdziesiąt ", "siedemdziesiąt ", 
		"osiemdziesiąt ", "dziewięćdziesiąt ");
		$s = array("","sto ", "dwieście ", "trzysta ", "czterysta ", "pięćset ",
		"sześćset ", "siedemset ", "osiemset ", "dziewięćset ");

		$txt = $s[0+substr($l,0,1)];
		if (substr($l,1,2)<20) {
			$txt .= $j[0+substr($l,1,2)];
		}
		else {
			$txt .= $d[0+substr($l, 1,1)].$j[0+substr($l, 2,1)];
		}
		if ($l<>0) {
			if ($l==1) {
				$txt .= "$t1 ";
			} else {
				if ((substr($l,2,1)==2 or substr($l,2,1)==3 or substr($l,2,1)==4) and (substr($l,1,2)>20 or substr($l,1,2)<10)) {
					$txt .= "$t2 ";
				} else {
					$txt .= "$t3 ";
				}
			}
		}
		return $txt;
	}


	function slownie( $liczba ) {
		$txt = '';
		$kwota = explode(".", $liczba);
		if (strlen($kwota[1])==1) $kwota[1] = $kwota[1]."0";
		$kwotazl = sprintf("%012d",$kwota[0]);
		$kwotagr = sprintf("%03d",$kwota[1]);
		$txt .= self::policz(substr($kwotazl, 0,3),"miliard","miliardy","miliardów");
		$txt .= self::policz(substr($kwotazl, 3,3),"milion","miliony","milionów");
		$txt .= self::policz(substr($kwotazl, 6,3),"tysiąc","tysiące","tysięcy");
		$txt .= self::policz(substr($kwotazl, 9,3),"złoty","złote","złotych");
		if ($kwotazl==0) $txt .= "zero złotych ";
		$txt .= " i ";
		$txt .= self::policz($kwotagr,"grosz","grosze","groszy");
		if ($kwotagr==0) $txt .= "zero groszy";
		return $txt;
	}


	function formatuj_grosze( $kwota ) {
		$kwota = round($kwota, 2);
		$liczba = explode(".", $kwota);
		if (!$liczba[1]) {
			$liczba = explode(",", $kwota);
			if (!$liczba[1]) $liczba[1] = "00";
		}
		if (strlen($liczba[1]) == 1) $liczba[1] = $liczba[1] . "0";
		$liczba_out = $liczba[0] . "." . "$liczba[1]";
		return $liczba_out;
	}


	function billing_billwiev_przeterminowania($ID_BILLING_USERS_PARAM, $IF_PRINT_PARAM, $ECHO_PARAM) {
		global $vdb
			, $STOPA_ODSETEK // from billing-l1/www/config.php
			, $form_mail_sender // billing-l1/www/config.php:24:$form_mail_sender="/usr/bin/mutt";
			, $form_send_from_param // billing-l1/www/config.php:19:$form_send_from_param="biall-net@biall.net.pl";
		;

		//NAGLOWKI DO HTML MAILA
		$naglowki  = "From: ".$form_send_from_param."\r\n";
		$naglowki .= "MIME-Version: 1.0\r\n";
		$naglowki .= "Content-type: text/html; charset=iso-8859-1\r\n";

		//PODRECZNE_ZAPYTANIE_SLOWNIKOWE_DO_TYPOW_DOKUMENTOW
		$BNT = array();
		$bnt_types = WindykacjaStatsModel::get_billing_types();
		foreach ($bnt_types as $k_type_id => $h_type) {
			$BNT[ $h_type['ID'] ] = $h_type['TYPE'];
		}//end foreach

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

		if ($_GET['ID_BILLING_USERS_PARAM']) $ID_BILLING_USERS_PARAM = $_GET['ID_BILLING_USERS_PARAM'];

		if (!$IF_PRINT_PARAM && !$ECHO_PARAM) {
			echo'<p style="text-align:right">';
			echo"<a href=\"javascript:openWindow('/modules/make_billing/edit.php?op=zadluzenia&print=1&FIRMA=1&uid=$ID_BILLING_USERS_PARAM','print','scrollbars,resizable=yes,width=750,height=550')\">";
			echo"<img border=\"0\" src=\"$xpath/ico/kw.gif\" width=\"16\" height=\"16\" alt=\"Zadłużenia\">";
			echo"Druki wezwania do zaplaty";
			echo"</a>";
			echo'</p>';
		}

		$user_id = $ID_BILLING_USERS_PARAM;
		$billing_account_files = WindykacjaStatsModel::get_billing_account_files( $user_id );
		echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">billing_account_files: ';print_r($billing_account_files);echo'</pre>';
	die('F.' . __FUNCTION__ . ' ...');

		$NAGLOWEK = "<table border=\"1\" width=\"100%\"><tr><td>Płatnik</td><td>WINIEN</td><td>MA</td><td>DOK</td><td>Numer</td><td>(T)ermin pł./(D)ata ksiegowania </td><td>Dni przeterminowania</td><td>Kwota przeterminowana</td><td>Odsetki</td></tr>";
		//while ($BAF = $vdb->sql_fetchrow($result)) {
		foreach ($billing_account_files as $BAF) {
			//RESETUJEMY FORM - jak nie chcemy pojedynczego odczytu:
			if (!$ID_BILLING_USERS_PARAM) unset($FORM);
			if (!$LAST_PLATNIK) $LAST_PLATNIK = $BAF[1];
			if (!$LPD) $LPD = $BAF;
			if (($BAF[0] <> $LAST_ID)) {// ID
				//DRUKUJEMY_STARE_PODSUMOWANIE (DLA_FAKTURY POJEDYNCZEJ)
				if ($LAST_ID) {
					$FORM_2.="<tr><td></td><td><b>".FunkcjeL1::formatuj_grosze($LTOTAL[WINIEN])."</b></td><td><b>".FunkcjeL1::formatuj_grosze($LTOTAL[MA])."</b></td><td colspan=\"3\"></td>";
					$FORM_S.= "<tr><td></td><td><b>".FunkcjeL1::formatuj_grosze($LTOTAL[WINIEN])."</b></td><td><b>".FunkcjeL1::formatuj_grosze($LTOTAL[MA])."</b></td><td colspan=\"3\"></td>";
					$LDNI = floor((date("U") - $DOC_TERM) / 86400) ; 
					if(($LDNI>0) && ($DOC_TERM) && ($LTOTAL['WINIEN_MA'] == "WINIEN")) {
						$LODSETKI= FunkcjeL1::formatuj_grosze( $LTOTAL[$LTOTAL[WINIEN_MA]] * $STOPA_ODSETEK  * $LDNI / 365 ) ;
						$POD_ODSETEK=$LTOTAL[$LTOTAL[WINIEN_MA]] ;
						$PLATNIK_DATA[PRZETER][ODSETKI]+=$LODSETKI ;
						$PLATNIK_DATA[PRZETER][WINIEN]+=$LTOTAL[$LTOTAL[WINIEN_MA]] ;								
					} else {
						unset($LODSETKI);
						unset($LDNI);
						unset($POD_ODSETEK);
					}
					$FORM_2.= "<td>$LDNI</td><td>$POD_ODSETEK</td>";
					$FORM_2.= "<td>$LODSETKI</td>";
					$FORM_S.= "<td>---</td><td>---</td><td>---</td>";
					//  if(!$PLATNIK_DATA[TOTAL][WINIEN]) 
					$PLATNIK_DATA[TOTAL][WINIEN]+=FunkcjeL1::formatuj_grosze($LTOTAL[WINIEN]) ;
					//  if(!$PLATNIK_DATA[TOTAL][MA])
					$PLATNIK_DATA[TOTAL][MA]+=FunkcjeL1::formatuj_grosze($LTOTAL[MA]) ;
					$FORM_2.= "</tr>";
					$FORM_2.= "<tr><td colspan=\"6\"><hr></td></tr>";
					$FORM_S.="</tr><tr><td colspan=\"6\"><hr></td></tr>";
					$TOTAL[WINIEN]+=$LTOTAL[WINIEN] ; $TOTAL[MA]+=$LTOTAL[MA] ;
					if ($LAST_PLATNIK <> $BAF[1]) {//PODSUMOWANIE_DLA_PLATNIKA
						$TOTAL[PRZETER]+=$PLATNIK_DATA[PRZETER][WINIEN];
						$TOTAL[ODSETKI]+=$PLATNIK_DATA[PRZETER][ODSETKI];
						$FORM_2.= "<tr><td colspan=\"9\">Podsumowanie salda niezbilansowanych zobowiązań dla platnika $LAST_PLATNIK 
						$LPD[P_NAME] $LPD[P_NAME_SECOND] $LPD[P_ADDRESS_CITY] $LPD[P_ADDRESS_STREET] $LPD[P_ADDRESS_HOUSE] $LPD[P_ADDRESS_HOME]
						<br> WINIEN: <b>".$PLATNIK_DATA[TOTAL][WINIEN]."</b> - MA: <b>".$PLATNIK_DATA[TOTAL][MA]."</b>  DO ZAPŁATY: <b>".FunkcjeL1::formatuj_grosze($PLATNIK_DATA[TOTAL][WINIEN]-$PLATNIK_DATA[TOTAL][MA])."</b> " ;
						if($PLATNIK_DATA[PRZETER][WINIEN]) $FORM_2.=", z czego przeterminowane <font color=\"red\"><b> ".FunkcjeL1::formatuj_grosze($PLATNIK_DATA[PRZETER][WINIEN])." </b></font> ";
						if($PLATNIK_DATA[PRZETER][ODSETKI]) $FORM_2.= " ( aktualnie nalezne odsetki to ".$PLATNIK_DATA[PRZETER][ODSETKI]." PLN , które mogą zostać naliczone ) " ;
						if($LPD[BA_TIMESTAMP]) $FORM_2.=" <br> Stan wzajemnych rozrachunków:  WINIEN: <b>$LPD[BA_WINIEN]</b> -  MA: <b>$LPD[BA_MA]</b>    SALDO(DO ZAPŁATY): <b>".FunkcjeL1::formatuj_grosze($LPD[BA_WINIEN]-$LPD[BA_MA])."</b> , i jest to stan na dzień ".date("Y-m-d",$LPD[BA_TIMESTAMP])." ";
						$RETURN_ARR="";
						$FORM_S.="<tr><td colspan=\"9\"></td></tr></table>";
						$FORM_2.="<br>W razie problemów prosimy o kontakt z biurem obsługi. <br><font size=\"1\" color=\"#CCCCCC\">webone billing system &copy;2004 by Arkadiusz Binder & www.grafnet.pl | finance module by A.Binder </font>";
						$FORM_2.= "  </tr></table>";
						$FORM_2 = $NAGLOWEK . " \n " . $FORM_2 ;
						$FORM_S= $NAGLOWEK . " \n " . $FORM_S ;
						if ($IF_PRINT_PARAM) {
							$delivery_subject="Stan rozrachunków dla  $LPD[P_NAME] $LPD[P_NAME_SECOND]"	;
							$sql2="insert into HIST_CONTACTS (ID_BILLING_USERS,ID_BILLING_NUMBERS,SUBJECT,BODY_HTML,REQUEST_STATUS_MAIL) values
							('".$LAST_PLATNIK."','','$delivery_subject','$FORM_2','CONFIRM_SENT_MAIL') ";
							$res = $vdb->sql_query($sql2) ;
							echo "<hr> $sql2 <hr>****"; 
						} else if (!$ECHO_PARAM) {
							echo $FORM_2;
						}
						$LAST_PLATNIK=$BAF[1];
						unset($PLATNIK_DATA);
						$FORM.=$FORM_2 ;
						unset($FORM_2);
						$FORM_SS.=$FORM_S ;
						unset($FORM_S);
					} else {
					}
					//$PLATNIK_DATA[TOTAL][WINIEN]+=$BAF[2];
					//$PLATNIK_DATA[TOTAL][MA]+=$BAF[3];
					$LPD = $BAF;
					$LAST_PLATNIK = $BAF[1];
				}
				else {
				}
				//DODAJEMY_NOWY_REKORD_OD_SAMEJ_PLATNOSCI
				unset($LTOTAL);
				$FORM_2.= "<tr><td>$BAF[1]</td><td>$BAF[2]</td><td>$BAF[3]</td><td>".$BNT[$BAF[4]]."</td><td>$BAF[5]/$BAF[6]</td>   <td colspan=\"1\">";
				if ($BAF[19]) $FORM_2.="T: ".date("Y-m-d",$BAF[19])." "; else  $FORM_2.="D: ".date("Y-m-d",$BAF['BAF_TIMESTAMP'])." "; 
				$FORM_2.="</td></tr>";
				$FORM_S.= "<tr><td>$BAF[1]</td><td>$BAF[2]</td><td>$BAF[3]</td><td>".$BNT[$BAF[4]]."</td><td>$BAF[5]/$BAF[6]</td>   <td colspan=\"1\">";
				if($BAF[19])$FORM_S.="T: ".date("Y-m-d",$BAF[19])." "; else  $FORM_2.="D: ".date("Y-m-d",$BAF['BAF_TIMESTAMP'])." "; 
				$FORM_S.="</td></tr>";
				$DOC_TERM = $BAF[19];
				if ($BAF[2] > 0) $LTOTAL['WINIEN_MA'] = "WINIEN"; else $LTOTAL['WINIEN_MA'] = "MA";
				$LTOTAL[$LTOTAL['WINIEN_MA']] = $BAF[2] + $BAF[3];
			} else {
				//DRUKUJEMY_PODSTUMOWANIE_STAREGO i ZAPODAJEMY NOWY_REKORD
			}

			if ($BAF[12]) {// ID_FIN_WINIEN_VAL
				$FORM_2.= "<tr><td colspan=\"1\"></td>";
				$FORM_S.= "<tr><td colspan=\"1\"></td>";
				if($LTOTAL['WINIEN_MA']=="MA") { 
				$FORM_2.= "<td><font color=\"green\"><b> $BAF[12] </b> </font></td>";
				$FORM_2.= "<td></td>";
				$FORM_S.="<td><font color=\"green\"><b> $BAF[12] </b> </font></td><td></td>";
				} else {
				$FORM_2.= "<td></td>";
				$FORM_2.= "<td><font color=\"green\"><b> $BAF[12] </b> </font></td>";
				$FORM_S.="<td></td><td><font color=\"green\"><b> $BAF[12] </b> </font></td>";
				} 
				$FORM_2.= "<td>".$BNT[$BAF[8]]."</td>";
				$FORM_2.= "<td> $BAF[9]/$BAF[10] </td><td>D: ".date("Y-m-d",$BAF[11])."</td> ";

				$FORM_S.= "<td>".$BNT[$BAF[8]]."</td>";
				$FORM_S.= "<td> $BAF[9]/$BAF[10] </td><td>D: ".date("Y-m-d",$BAF[11])."</td> ";

				$LDNI = floor(($BAF[11] - $DOC_TERM) / 86400);
				if (($LDNI > 0) && ($DOC_TERM) && ($LTOTAL['WINIEN_MA'] == "WINIEN")) {
					$DOC_TERM = $BAF[11];
					$LODSETKI = FunkcjeL1::formatuj_grosze( $LTOTAL[$LTOTAL['WINIEN_MA']] * $STOPA_ODSETEK  * $LDNI / 365 );
					$POD_ODSETEK = $LTOTAL[$LTOTAL['WINIEN_MA']];
					$PLATNIK_DATA['PRZETER']['ODSETKI'] += $LODSETKI;
				} else {
					unset($LODSETKI);
					unset($LDNI);
					unset($POD_ODSETEK);
				}
				$FORM_2.= "<td>$LDNI</td><td>$POD_ODSETEK</td>";
				$FORM_2.= "<td>$LODSETKI</td>";
				$FORM_2.= "</tr>";
				$FORM_S.="<td>---</td><td>---</td><td>---</td></tr>";
				$LTOTAL[$LTOTAL['WINIEN_MA']] -= $BAF[12];
			}

			if ($BAF[18]) {// ID_FIN_MA_VAL
				$FORM_2.= "<tr><td colspan=\"1\"></td>";
				$FORM_S.= "<tr><td colspan=\"1\"></td>";
				if ($LTOTAL['WINIEN_MA'] == "MA") {
					$FORM_2.= "<td><font color=\"red\"><b> $BAF[18] </b> </font></td>";
					$FORM_2.= "<td></td>";
					$FORM_S.= "<td><font color=\"red\"><b> $BAF[18] </b> </font></td><td></td>";
				} else {
					$FORM_2.= "<td></td>";
					$FORM_2.= "<td><font color=\"red\"><b> $BAF[18] </b> </font></td>";
					$FORM_S.="<td></td><td><font color=\"red\"><b> $BAF[18] </b> </font></td>";
				} 
				$FORM_2.= "<td>".$BNT[$BAF[14]]."</td>";
				$FORM_2.= "<td> $BAF[15]/$BAF[16] </td> <td>D: ".date("Y-m-d",$BAF[17])."</td> ";
				$FORM_S.="<td>".$BNT[$BAF[14]]."</td> <td> $BAF[15]/$BAF[16] </td> <td>D: ".date("Y-m-d",$BAF[17])."</td> ";

				$LDNI=floor(($BAF[17] - $DOC_TERM) / 86400) ; 
				//				$LDNI=10;
				if (($LDNI > 0) && ($DOC_TERM) && ($LTOTAL['WINIEN_MA'] == "WINIEN")) {
					$LODSETKI = FunkcjeL1::formatuj_grosze( $LTOTAL[$LTOTAL[WINIEN_MA]] * $STOPA_ODSETEK  * $LDNI / 365 ) ;
					$POD_ODSETEK = $LTOTAL[$LTOTAL['WINIEN_MA']];
					$PLATNIK_DATA['PRZETER']['ODSETKI'] += $LODSETKI;
				} else {
					unset($LODSETKI);
					unset($LDNI);
					unset($POD_ODSETEK);
				}
				$FORM_2.= "<td>$LDNI</td><td>$POD_ODSETEK</td>";
				$FORM_S.= "<td>$LDNI</td><td>$POD_ODSETEK</td>";
				$FORM_2.= "<td>$LODSETKI</td>";
				$FORM_S.= "<td>$LODSETKI</td>";
				$FORM_2.= "</tr>";
				$FORM_S.= "</tr>";
				$LTOTAL[$LTOTAL['WINIEN_MA']]-=$BAF[18] ;
			}

			$LAST_ID = $BAF[0];
			$L_BAF = $BAF;
		}//eof SQL while($BAF=$vdb->sql_fetchrow($result)) {

		//DODANIE_ZESTAWIENIA KOPIA_Z_GORY

		//DRUKUJEMY_STARE_PODSUMOWANIE (DLA_FAKTURY POJEDYNCZEJ)
		if ($LAST_ID) {
			$FORM_2.="<tr><td></td><td><b>".FunkcjeL1::formatuj_grosze($LTOTAL['WINIEN'])."</b></td><td><b>".FunkcjeL1::formatuj_grosze($LTOTAL['MA'])."</b></td><td colspan=\"3\"></td>";
			$FORM_S.="<tr><td></td><td><b>".FunkcjeL1::formatuj_grosze($LTOTAL['WINIEN'])."</b></td><td><b>".FunkcjeL1::formatuj_grosze($LTOTAL['MA'])."</b></td><td colspan=\"3\"></td>";

			$LDNI = round((date("U") - $DOC_TERM) / 86400, 0);
			if (($LDNI > 0) && ($DOC_TERM)) {
				$LODSETKI = FunkcjeL1::formatuj_grosze( $LTOTAL[$LTOTAL['WINIEN_MA']] * $STOPA_ODSETEK  * $LDNI / 365);
				$POD_ODSETEK = $LTOTAL[$LTOTAL['WINIEN_MA']];
				$PLATNIK_DATA['PRZETER']['ODSETKI'] += $LODSETKI ;
				$PLATNIK_DATA['PRZETER']['WINIEN'] += $LTOTAL[$LTOTAL['WINIEN_MA']];
			} else {
				unset($LODSETKI);
				unset($LDNI);
				unset($POD_ODSETEK);
			}
			$FORM_2.= "<td>$LDNI</td><td>".FunkcjeL1::formatuj_grosze($POD_ODSETEK)."</td>";
			$FORM_2.= "<td>$LODSETKI</td>";
			$FORM_S.="<td>---</td><td>---</td><td>---</td>";

			//  if(!$PLATNIK_DATA[TOTAL]['WINIEN'])
			$PLATNIK_DATA['TOTAL']['WINIEN']+=FunkcjeL1::formatuj_grosze($LTOTAL['WINIEN']) ;
			//  if(!$PLATNIK_DATA[TOTAL][MA])
			$PLATNIK_DATA['TOTAL']['MA']+=FunkcjeL1::formatuj_grosze($LTOTAL['MA']) ;

			$FORM_2.= "</tr>";
			$FORM_2.= "<tr><td colspan=\"6\"><hr></td></tr>";
			$FORM_S.="</tr><tr><td colspan=\"6\"><hr></td></tr>";
			$TOTAL['WINIEN']+=$LTOTAL['WINIEN'] ; $TOTAL['MA']+=$LTOTAL['MA'] ;

			if ($LAST_PLATNIK <> $BAF[1]) {//PODSUMOWANIE_DLA_PLATNIKA

				$TOTAL['PRZETER'] += $PLATNIK_DATA['PRZETER']['WINIEN'];
				$TOTAL['ODSETKI'] += $PLATNIK_DATA['PRZETER']['ODSETKI'];
				if (!$LPD) $LPD = $L_BAF ;
				$FORM_2.= "<tr><td colspan=\"9\">Podsumowanie salda niezbilansowanych zobowiązań dla platnika $LAST_PLATNIK 
				$LPD[P_NAME] $LPD[P_NAME_SECOND] $LPD[P_ADDRESS_CITY] $LPD[P_ADDRESS_STREET] $LPD[P_ADDRESS_HOUSE] $LPD[P_ADDRESS_HOME]
				<br> WINIEN: <b>".$PLATNIK_DATA['TOTAL']['WINIEN']."</b> - MA: <b>".$PLATNIK_DATA['TOTAL']['MA']."</b> 
				DO ZAPŁATY: <b>".FunkcjeL1::formatuj_grosze($PLATNIK_DATA['TOTAL']['WINIEN']-$PLATNIK_DATA['TOTAL']['MA'])."</b> " ;
				if ($PLATNIK_DATA['PRZETER']['WINIEN']) $FORM_2.=", z czego przeterminowane <font color=\"red\"><b> ".FunkcjeL1::formatuj_grosze($PLATNIK_DATA['PRZETER']['WINIEN'])." </b></font> ";
				if ($PLATNIK_DATA['PRZETER']['ODSETKI']) $FORM_2.= " ( aktualnie nalezne odsetki to ".$PLATNIK_DATA['PRZETER']['ODSETKI']." PLN , które mogą zostać naliczone ) " ;
				if ($LPD['BA_TIMESTAMP']) $FORM_2.=" <br> Stan wzajemnych rozrachunków:  WINIEN: <b>".$LPD['BA_WINIEN']."</b> -  MA: <b>".$LPD['BA_MA']."</b>    SALDO(DO ZAPŁATY): <b>".FunkcjeL1::formatuj_grosze($LPD['BA_WINIEN']-$LPD['BA_MA'])."</b> , i jest to stan na dzień ".date("Y-m-d",$LPD['BA_TIMESTAMP'])." ";
				$RETURN_ARR="";
				$FORM_S.="<tr><td colspan=\"9\"></td></tr></table>";

				$FORM_2.="<br>W razie problemów prosimy o kontakt z biurem obsługi. <br><font size=\"1\" color=\"#CCCCCC\">webone billing system &copy;2004 by Arkadiusz Binder & www.grafnet.pl | finance module by A.Binder </font>";
				$FORM_2.= "  </tr></table>";


				$FORM_2 = $NAGLOWEK . " \n " . $FORM_2 ;
				$FORM_S = $NAGLOWEK . $FORM_S ;

				//DRUKOWANIE ZESTAWIENIA
				if ($IF_PRINT_PARAM) {
					$delivery_subject="Stan rozrachunków dla  $LPD[P_NAME] $LPD[P_NAME_SECOND]"	;
					//         exec("echo  \"Pliki zostały dołączone do załącznika\" | $form_mail_sender -n -a \"$filename\" $delivery_mail -s ".$delivery_subject."" );
					$sql2="insert into HIST_CONTACTS (ID_BILLING_USERS,ID_BILLING_NUMBERS,SUBJECT,BODY_HTML,REQUEST_STATUS_MAIL) values
						('".$LAST_PLATNIK."','','$delivery_subject','$FORM_2','CONFIRM_SENT_MAIL') ";
					$res = $vdb->sql_query($sql2) ;
					echo "<hr> $sql2 <hr>***"; 
				} else if (!$ECHO_PARAM) {
					echo $FORM_2;
				}
				//EOF DRUKOWANIE ZESTAWIENIA itp

				$LAST_PLATNIK = $BAF[1];
				$ECHO_DATA=$PLATNIK_DATA;
				unset($PLATNIK_DATA);

				$FORM .= $FORM_2 . "</table>" ;
				$FORM_SS .= $FORM_S . "</table>" ;
				unset($FORM_2);
				unset($FORM_S);
			}
		}

		$FORM_2.= $NAGLOWEK;
		$FORM_2.= "<tr><td>TOT</td><td><b>$TOTAL[WINIEN]</b></td><td><b>$TOTAL[MA]</b></td><td colspan=\"4\"></td>
			<td><b>$TOTAL[PRZETER]</b></td><td><b>$TOTAL[ODSETKI]</b></td></tr>";
		$FORM_2 .= "</table>";
		if (!$ECHO_PARAM)	echo "$FORM_2";
		$FORM_S.=  "</table> ";
		if ($ECHO_PARAM == "zadluzenie") return FunkcjeL1::formatuj_grosze($ECHO_DATA['PRZETER']['WINIEN']);
		if ($ECHO_PARAM == "saldo") return FunkcjeL1::formatuj_grosze($LPD['BA_WINIEN']-$LPD['BA_MA']);
		if ($ECHO_PARAM == "zadluzenie_lista") return $FORM;
		if ($ECHO_PARAM == "saldo_rok") {
			$L_BAF['FORM'] = $FORM;
			$L_BAF['FORM_SALDO'] = $FORM_SS;
			return $L_BAF;
		}
	}


}
