<?php

error_reporting(E_ALL);

session_start();


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

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

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


SEF('DEBUG_S');

if(!isset($_SESSION['DEBUG'])) $_SESSION['DEBUG']=0;
echo "<HTML><BODY LEFTMARGIN=0 TOPMARGIN=0>";


function ZAP_SQL($zapSQL) {
//echo "   $zapSQL <br><br>   \n";
global $result,$SQL_DATABASE,$INTERFACE_ADDR,$SQL_USER_PASS,$SQL_USER;
$conn=mysql_pconnect($INTERFACE_ADDR,$SQL_USER,$SQL_USER_PASS);
if (!$conn) die("ERROR podczas tworzenia polaczenia do bazy $SQL_DATABASE !\n");
mysql_select_db($SQL_DATABASE) or die("ERROR podczas wyboru bazy R50!");
//$zapSQL=" from $TABLE";
if($_SESSION[DEBUG]) echo "<hr>ZAP_SQL_UPDATE($zapSQL) :::<br>";
$result = mysql_query($zapSQL,$conn) or die("Blad zapytania ZAP_SQL. *$zapSQL*!");
$_SESSION[MYSQL_NUM_ROWS] = mysql_num_rows($result);
}

function GETFORMITEM($VALUE,$TYPE,$NAME) {
//VERSION 2006-03-20 , ale na l2 moze byc swiezsze

global $thiss;
//echo "***************$VALUE,,,,$TYPE";
if(strstr($TYPE,"enum")) {
list($SMIEC,$TYPE)=split("\(",$TYPE);
list($TYPE,$SMIEC)=split("\)",$TYPE);
list($TYPE1,$SMIEC1)=split(",",$TYPE);

$TYPE=explode(",",$TYPE);
echo "<select name=$NAME>"; //TODO 2006-03 sprawdzic czy dawanie do wyszukiwania getformitem w menu % zawsze moze dawac??
if(($_SESSION[CURRENT_MENU]==USERS) || ($_SESSION[CURRENT_MENU]==TELBOXES) || ($_SESSION[CURRENT_MENU]==DEVICES) || ($_SESSION[CURRENT_MENU]==BUILDINGS) ||($_SESSION[CURRENT_MENU]!=$thiss->DETECT_EDIT_FUNCTION)) echo "<option value='%'>%</option>";
foreach ($TYPE as $value) {
//echo "***  $value =============== $VALUE *** * *** *";
if ("'$VALUE'"==$value) { echo "<option value=$value selected=true> $value </option>"; } else echo "<option value=$value>$value</option>";
 } //EOF foreach
echo "</select>";
} else if((strstr($TYPE,"char")) || (strstr($TYPE,"int"))) {
//echo "THIS IS CHAR";
list($SMIEC,$TYPE)=split("\(",$TYPE);
list($TYPE,$SMIEC)=split("\)",$TYPE);
$SIZE = strlen($VALUE) + 10;
$SIZE="size=$SIZE";
if(($_SESSION[CURRENT_MENU]==USERS) || ($_SESSION[CURRENT_MENU]==TELBOXES) || ($_SESSION[CURRENT_MENU]==DEVICES) || ($_SESSION[CURRENT_MENU]==BUILDINGS) ) if(!($VALUE)) $VALUE = "%";
echo "<INPUT TYPE=TEXT NAME='$NAME' VALUE='$VALUE' maxlength='$TYPE' $SIZE >";
} else  if((strstr($TYPE,"datetime"))||(strstr($TYPE,"date")||strstr($TYPE,"timestamp"))) {
list($SMIEC,$TYPE)=split("\(",$TYPE);
list($TYPE,$SMIEC)=split("\)",$TYPE);
$VALUE=substr($VALUE,0,10);
$SIZE = 10 ;
$SIZE="size=$SIZE";
echo "<INPUT TYPE=TEXT NAME='$NAME' VALUE='$VALUE' maxlength='$TYPE' $SIZE >";
} else  if(strstr($TYPE,"double")) {
list($SMIEC,$TYPE)=split("\(",$TYPE);
list($TYPE,$SMIEC)=split("\)",$TYPE);
$VALUE=substr($VALUE,0,10);
$SIZE = 4 ;
$SIZE="size=$SIZE";
echo "<INPUT TYPE=TEXT NAME='$NAME' VALUE='$VALUE' maxlength='$TYPE' $SIZE >";
} else {
echo "THIS IS TEXT_OR_OTHER f.GETFORMITEM($VALUE,$TYPE,$NAME)";
}
}

function T_WORKPOINTS_USER_SELECT() {
global $result;
ZAP_SQL("select * from ADMIN_USERS where A_STATUS='NORMAL' and ADM_COMPANY like '$_SESSION[ADM_COMPANY]'");
#ZAP_SQL("select * from ADMIN_USERS where A_STATUS='NORMAL' and ADM_TECH_WORKER!='NO' and ADM_COMPANY like '$_SESSION[ADM_COMPANY]'");
//echo "select * from ADMIN_USERS where A_STATUS='NORMAL' and ADM_TECH_WORKER!='NO' and ADM_COMPANY like '$_SESSION[ADM_COMPANY]'";
	echo "<select name=T_WORKPOINTS_USER><option value=''> </option>
 ";
        while ($h=mysql_fetch_row($result)) {
	echo "<option value='" . $h[$_SESSION[ADMIN_COLUMN][DESC_TO_KEY][ADM_ACCOUNT]] . "'" ;
if((strstr($_SESSION[USERS2_MARKETING_COLUMN][EDITRECORD][T_WORKPOINTS_USER],strtoupper($h[$_SESSION[ADMIN_COLUMN][DESC_TO_KEY][ADM_ACCOUNT]]))) ||
(strstr(strtoupper($_SESSION[BUILDINGS_COLUMN][EDITRECORD][T_WORKPOINTS_USER]),strtoupper($h[$_SESSION[ADMIN_COLUMN][DESC_TO_KEY][ADM_ACCOUNT]]))))	echo "selected";
	echo ">" . $h[$_SESSION[ADMIN_COLUMN][DESC_TO_KEY][ADM_NAME]] . "(". $h[$_SESSION[ADMIN_COLUMN][DESC_TO_KEY][ADM_ACCOUNT]] . ")</option>" ;
//	echo $_SESSION[ADMIN_COLUMN][DESC_TO_KEY][ADM_ACCOUNT];
//	print_r($h);
	 }
	echo "</select>";
}

User::auth();

echo "<a href=$PHP_SELF/?LOGIN=LOGOUT>LOGOUT</a>\n<br>";
echo "<a href=$PHP_SELF> ODSWIEZ </a>\n<br>";
echo "<a href=http://se.dev.webone.pl> http://se.dev.webone.pl - POWROT DO SE </a>\n<br>";
echo'<br /><br />';
echo "<a href=$PHP_SELF?STATYSTYKA_TABELE=1> ZROB TABELE PODRECZNIKOWE DO STATYSTYKI </a> (uwaga trwa do minuty, jak klikniesz musisz poczekac do konca az sie pojawi na samym dole napis EOF!!!)\n <br>";
echo "<a href=$PHP_SELF?STATYSTYKA_WYSWIETL=1> WYSWIETL ANALIZE PODRECZNIKOWYCH TABEL DO STATYSTYKI </a>\n<BR>";
echo "<a href=$PHP_SELF?DODAJ_REKORDY_MIESZKAN=1> DODAJ ZASOBY MIESZKANIOWE DO BAZY HANDLOWEJ </a>\n<BR>";
echo "<a href=$PHP_SELF?DODAJ_WYNIK_ANKIETY=1> DODAJ WYNIK ANKIETY/BADANIA DO BAZY HANDLOWEJ </a>\n<BR>";
echo '<a href="' . "index.php?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC" . '">' . " POKAZ_OFERTY_AKTUALNE " . '</a>' . "\n" . '<BR>';

echo "<a href=$PHP_SELF?DODAJ_RAPORT_ULOTEK=1>DODAJ RAPORT ULOTEK </a>\n<br> ";
echo "<a href=$PHP_SELF?GDZIE_ROZNIESC_ZRYWKI=1>GDZIE ROZNIESC ZRYWKI </a>( lub na jakich budynkach wykonac inne dzialania, raport bedacy nastepstwem wprowadzania danych w tabeli BUILDINGS w L3 )\n<BR>";
echo "<a href=$PHP_SELF?GDZIE_PUSCIC_HANDLOWCA=1>GDZIE PUSCIC HANDLOWCA </a>\n";
echo "| <a href=$PHP_SELF?GDZIE_PUSCIC_HANDLOWCA_2=1>GDZIE PUSCIC HANDLOWCA DATAMI UMOW </a>\n<br>";
echo "<a href=$PHP_SELF?RAPORT_DZIALAN_OGOLNY_1=1>RAPORT_DZIALAN_OGOLNY_1 (wersja testowa) </a>\n<br>";
echo "<a href=$PHP_SELF?RAPORT_DZIALAN_OGOLNY_2=1>RAPORT_DZIALAN_OGOLNY_2 (wersja testowa podsumowania dzialan w okresie) </a>\n<br>";
echo "<a href=$PHP_SELF?ROZNIESIONE_ZRYWKI=1>ROZNIESIONE ZRYWKI</a>\n";
echo "<a href=$PHP_SELF?ROZNIESIONE_ZRYWKI_2=1>ROZNIESIONE ZRYWKI_2</a> (test rozliczenia prac na rewiry)\n<br>";
echo "<a href=$PHP_SELF?ZLECENIE_DYSTRYBUCJI_1=1>TODO 2007-03-24 HD2.2.1 ZLECENIE_DYSTRYBUCJI i KONTROLI</a>\n<br>";
echo "<a href=$PHP_SELF?ZLECENIE_BADAN_1=1>TODO 2007-04-18 HD3.1.1.1 ZLECENIE WYKONANIA BADAN / HD4.1 DZIALAN HANDLOWYCH W TERENIE</a>\n<br>";
echo "<a href=$PHP_SELF?POPRAWIANIE_DANYCH=1>POPRAWIANIE DANYCH TODO BZYK!!!</a>\n<br>";
echo "<a href=$PHP_SELF?NADANIE_PROBLEMOW=1>NADANIE_PROBLEMOW np dla telemarketingu todo2007-09!!!</a>\n<br>";
echo "<a href=$PHP_SELF?KSIEG_DOKUMENTY_ANALIZA=1>KSIEG_DOKUMENTY_ANALIZA (TODO)</a>\n |";
echo "<a href=$PHP_SELF?KSIEG_DOKUMENTY_ANALIZA_KONTA=1>KSIEG_DOKUMENTY_ANALIZA_KONTA  analiza stanu kont (TODO)</a>\n |";
echo "<a href=$PHP_SELF?KSIEG_DOKUMENTY_ANALIZA_KONTA_4=1>KSIEG_DOKUMENTY_ANALIZA_KONTA_4  analiza stanu kont 4 (TODO)</a>\n |";
echo "<a href=$PHP_SELF?KSIEG_DOKUMENTY_GENERUJ_SYMULACJE=1>KSIEG_DOKUMENTY_Generowanie wynikow dla przyjetych zalozen z pola \"POWTARZALNOSC\" (TODO)</a>\n <br>";
echo "<a href=$PHP_SELF?KSIEG_DOKUMENTY_ZASOB1182_SUBIEKT_MSSQL_IMPORT=1>KSIEG_DOKUMENTY_ZASOB1182_SUBIEKT_MSSQL_IMPORT import do tabeli FAKTUR (TODO)</a>\n <br>";

echo "<a href=$PHP_SELF?KSIEG_DOKUMENTY_ANALIZA_INWESTYCJI=1>KSIEG_DOKUMENTY_ANALIZA_INWESTYCJI Na podstawie tabeli FVAT_POS, rewirow oraz kont 0-80 analiza zwrotu inwestycji (TODO)</a>\n <br>";
echo "<a href=$PHP_SELF?RAPORT_PROJECT_COSTS=1>RAPORT_PROJECT_COSTS Analiza oplat licencyjnych dla projektow typu ZAKUP_LICENCJI_TV</a>\n <br>";

echo "<a href=$PHP_SELF?HANDL_ANALIZA_HISTORII=1>HANDL_ANALIZA_HISTORII Na podstawie tabeli USERS2_MARKETING</a>\n <br>";
echo "<a href=$PHP_SELF?ANALIZA_HISTORII_USERS2=1>ANALIZA_HISTORII_USERS2 Na podstawie tabeli USERS2_HIST</a>\n <br>";
if($_SESSION[ADMIN_LEVEL]==0) echo "<a href=$PHP_SELF?ANALIZA_HISTORII_ALL=1>ANALIZA_HISTORII_ALL Na podstawie tabeli X_HIST</a>\n <br>";
if($_SESSION[ADMIN_LEVEL]==0) echo "<a href=$PHP_SELF?ANALIZA_HISTORII_DEALS=1>ANALIZA_HISTORII_DEALS Na podstawie tabeli ANALIZA_HISTORII_DEALS_HIST</a>\n <br>";

echo "<a href=$PHP_SELF?ROZLICZENIE_BUDZETU_2010=1>ROZLICZENIE_BUDZETU_2010 na podstawie  KSIEG_DOKUMENTY, PODLACZENIA, UMOWY, WINDYKACJA </a>\n <br>";

if ($_SESSION['ADMIN_LEVEL'] == 0) echo '<a href="' . $_SERVER['PHP_SELF'] . "?SYNC_OFFERS_TO_L1=1" . '">' . "sync OFFERS, COSTS, COSTS GROUPS do L1" . '</a>' . "\n " . '<br>';

echo "<hr>SPRAWY TECHNICZNE: <a href=$PHP_SELF?MAGAZYN_SUPEREDIT=1>MAGAZYN SUPEREDIT</a>\n<br>";

//print_r($_SESSION);
//echo "dupaaaa";
//

//foreach($_GET as $key=>$value) {
//$_GET[$key]=strtoupper($value);
//}


if ($_GET['SYNC_OFFERS_TO_L1']) {
	echo '<h3>' . "sync OFFERS, COSTS, COSTS GROUPS do L1" . '</h3>';
	if ($_SESSION['ADMIN_LEVEL'] != 0) {
		die('Brak dostepu!');
	}

	$cnf = Config::getZasobConf( 'X931' );// tymczasowy dostep do 931 - dostep tylko do tabel USERS2_OFFERS, USERS2_OFFERS_COSTS, USERS2_OFFERS_COSTS_GROUPS
	if (!$cnf) {
		die("Error - brak configu do l1!");
	}
	$CNF_ZASOB_SRC = 14;
	$CNF_ZASOB_DST = 931;
	$CNF_ZASOB[$CNF_ZASOB_DST]['INTERFACE_ADDR'] = $cnf['host'];
	$CNF_ZASOB[$CNF_ZASOB_DST]['SQL_USER'] = $cnf['user'];
	$CNF_ZASOB[$CNF_ZASOB_DST]['SQL_USER_PASS'] = $cnf['pass'];
	$CNF_ZASOB[$CNF_ZASOB_DST]['SQL_DATABASE'] = $cnf['database'];

	SEF('SYNC_MYDATABASE_SQIX');// SYNC_MYDATABASE_SQIX( $CNF_ZASOB_SRC, $src_tables_array, $CNF_ZASOB_DST )
	$sync_tables = array('USERS2_OFFERS', 'USERS2_OFFERS_COSTS', 'USERS2_OFFERS_COSTS_GROUPS', 'IN7_MK_BAZA_DYSTRYBUCJI');
	//SYNC_MYDATABASE_SQIX('719', $sync_tables, '14');
	// '719' -> l1.webone.pl (931 -> BAZA_DANYCH webone - baza danych do ewidencji uslug)
	// '14' -> se.dev.webone.pl (36 -> SES_USERS2)
	SYNC_MYDATABASE_SQIX($CNF_ZASOB_SRC, $sync_tables, $CNF_ZASOB_DST);

	die('<br /><br />.EOF');
}


if($_GET['ANALIZA_HISTORII_DEALS']) {
	include("budynki-ANALIZA_HISTORII_DEALS.php");
	die();
}



if($_GET['ANALIZA_HISTORII_ALL']) {
	include("budynki-ANALIZA_HISTORII_ALL.php");
	die();
}




if($_GET['ROZLICZENIE_BUDZETU_2010']) {
	include("budynki-ROZLICZENIE_BUDZETU_2010.php");
}



if(isset($_GET['KSIEG_DOKUMENTY_ZASOB1182_SUBIEKT_MSSQL_IMPORT'])) {
    require("KSIEG_DOKUMENTY_ZASOB1182_SUBIEKT_MSSQL_IMPORT.php");
}

if($_GET['GDZIE_PUSCIC_HANDLOWCA']) {
echo "SZUKANIE MIEJSC GDZIE_PUSCIC_HANDLOWCA <form  method=\"GET\">"; //action=$PHP_SELF
echo "<input type=hidden name=ADD value=ADD>";
echo "<input type=hidden name=GDZIE_PUSCIC_HANDLOWCA value=1>";


echo "<table border=1><tr><td>";

echo "Dodaj Lancuch dla poszukiwan ulicy , (zakoncz znakiem %) - 500 rekordow</td><td>  <input type=text name=S_ADDRESS_STREET size=10 value=$_GET[S_ADDRESS_STREET]></td></tr>";
echo "<tr><td colspan=1><input type=submit name=ADD value=SZUKAJ></td><td>ZAINTERES</td><td>Data_Bad</td><td>OPER</td><td>OPER_FIN</td><td>OPER_ZAD</td></tr>";

if($_GET['S_ADDRESS_STREET']) ZAP_SQL("SELECT * FROM USERS2_MARKETING where ( S_ADDRESS_STREET like '".$_GET['S_ADDRESS_STREET']."' or M_REWIR like '".$_GET[S_ADDRESS_STREET]."' or T_NETWORK_SERVER like '".$_GET[S_ADDRESS_STREET]."'  ) and I_OPER_ZAINT!='NIEWIADOMO'    and (I_OPER_FIN < from_unixtime(unix_timestamp(now())+2592000) or I_OPER_FIN='0000-00-00' )   and I_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)
 order by  I_OPER_FIN desc  , I_OPER_ZAINT desc   limit 500 ");

while($DWA=mysql_fetch_array($result)) {


echo "<tr><td>".$DWA['S_ADDRESS_STREET']." $DWA[P_NAME] $DWA[P_PHONE]  $DWA[S_ALIAS] ( $DWA[S_OTHER_INFO] ) </td><td>".$DWA['I_OPER_ZAINT']."</td><td>".$DWA[I_BAD_DATE]." ";
echo "</td><td>$DWA[I_OPER]</td><td>$DWA[I_OPER_FIN]</td><td>$DWA[I_OPER_ZAD]</td></tr>";

 }

echo "</table>";

} //EOF IF




if($_GET['RAPORT_PROJECT_COSTS']) {

    require('budynki-RAPORT_PROJECT_COSTS.php');
}



if ($_GET['HANDL_ANALIZA_HISTORII']) {
	include("superedit-HANDL_ANALIZA_HISTORII.php");
	HANDL_ANALIZA_HISTORII();
}
include("superedit-ANALIZA_HISTORII_USERS2.php");



if($_GET[KSIEG_DOKUMENTY_GENERUJ_SYMULACJE]) {
echo "SZUKANIE MIEJSC GDZIE_PUSCIC_HANDLOWCA <form  method=\"GET\">"; //action=$PHP_SELF
echo "<input type=hidden name=ADD value=ADD>";
echo "<input type=hidden name=KSIEG_DOKUMENTY_GENERUJ_SYMULACJE value=1>";


echo "<table border=1><tr><td>";

echo "Podaj rok i  miesiac zrodlowy YYYY-MM-DD</td><td>  <input type=text name=KSIEG_DOKUMENTY_GENERUJ_SYMULACJE_SRC size=10 value=$_GET[KSIEG_DOKUMENTY_GENERUJ_SYMULACJE_SRC]></td>";
echo "<td>Podaj zakres symulacji w miesiacach</td><td><input type=text name=KSIEG_DOKUMENTY_GENERUJ_SYMULACJE_MONTHS size=10 value=$_GET[KSIEG_DOKUMENTY_GENERUJ_SYMULACJE_MONTHS]></td></tr>";
echo "<tr><td colspan=1><input type=submit name=ADD value=SZUKAJ></td><td>ZAINTERES</td><td>Data_Bad</td><td>OPER</td><td>OPER_FIN</td><td>OPER_ZAD</td></tr>";



if($_GET[KSIEG_DOKUMENTY_GENERUJ_SYMULACJE_SRC]) {

$ZAP_SQL="update KSIEG_DOKUMENTY set CENA_JEDN_NETTO=REPLACE(CENA_JEDN_NETTO, ',', '.'), ILOSC=REPLACE(ILOSC, ',', '.') ";
echo "ZAP SQL to $ZAP_SQL \n <br>";
ZAP_SQL("$ZAP_SQL");


$POWTARZALNOSC_ARR = array ("1","2","3","6","12","24");
foreach ( $POWTARZALNOSC_ARR as $POWTARZALNOSC ) {
$PETLA=$POWTARZALNOSC ;
//$POWTARZALNOSC=1;

while (($PETLA <= $_GET[KSIEG_DOKUMENTY_GENERUJ_SYMULACJE_MONTHS])&&($PETLA<=24)) {

echo "PETLA TO $PETLA ,  POWTARZALNOSC =  $POWTARZALNOSC \n <br>";


$ZAP_SQL="delete from KSIEG_DOKUMENTY where TYP_DOKUMENTU='AUTO-SYMULACJA' and POWTARZALNOSC='$POWTARZALNOSC' and year(DATA_DOK)=year(DATE_ADD( '$_GET[KSIEG_DOKUMENTY_GENERUJ_SYMULACJE_SRC]', INTERVAL $PETLA MONTH))
and month(DATA_DOK)=month(DATE_ADD( '$_GET[KSIEG_DOKUMENTY_GENERUJ_SYMULACJE_SRC]', INTERVAL $PETLA MONTH));";
echo "ZAP SQL to $ZAP_SQL \n <br>";
 ZAP_SQL("$ZAP_SQL");


$ZAP_SQL="
insert ignore into KSIEG_DOKUMENTY ( A_RECORD_CREATE_DATE, DATA_DOK ,NUMER_DOK , SPRZEDAWCA , ID_SPRZEDAWCA , ID_KONTO_KSIEG , NR_POZ ,
NR_POZ_OPIS , ILOSC , CENA_JEDN_NETTO , STAWKA_VAT , CZY_URZADZENIE  ,
ID_BUDZET , BUDZET,A_ADM_COMPANY,POWTARZALNOSC ,TYP_DOKUMENTU )
select
curdate(),  DATE_ADD( DATA_DOK, INTERVAL $PETLA MONTH) as DATA_DOK ,
NUMER_DOK , SPRZEDAWCA , ID_SPRZEDAWCA , ID_KONTO_KSIEG , NR_POZ ,
NR_POZ_OPIS , ILOSC , CENA_JEDN_NETTO , STAWKA_VAT , CZY_URZADZENIE  ,
ID_BUDZET , BUDZET,A_ADM_COMPANY,POWTARZALNOSC , 'AUTO-SYMULACJA' as TYP_DOKUMENTU
 from KSIEG_DOKUMENTY
where year(DATA_DOK)=YEAR('$_GET[KSIEG_DOKUMENTY_GENERUJ_SYMULACJE_SRC]') and month(DATA_DOK)=month('$_GET[KSIEG_DOKUMENTY_GENERUJ_SYMULACJE_SRC]') and POWTARZALNOSC='$POWTARZALNOSC' and A_STATUS='NORMAL';";

echo "ZAP SQL to $ZAP_SQL \n <br>";


 ZAP_SQL("$ZAP_SQL");

while($DWA=mysql_fetch_array($result)) {


echo "<tr><td>".$DWA[S_ADDRESS_STREET]." $DWA[P_NAME] $DWA[P_PHONE]  $DWA[S_ALIAS] ( $DWA[S_OTHER_INFO] ) </td><td>".$DWA[I_OPER_ZAINT]."</td><td>".$DWA[I_BAD_DATE]." ";
echo "</td><td>$DWA[I_OPER]</td><td>$DWA[I_OPER_FIN]</td><td>$DWA[I_OPER_ZAD]</td></tr>";

 } //EOF while sqlfetch

 $PETLA=$PETLA+$POWTARZALNOSC;

} //EOF PETLA
} //EOF foreach ( $POWTARZALNOSC_ARR as $POWTARZALNOSC )


} //EOF if($_GET[KSIEG_DOKUMENTY_GENERUJ_SYMULACJE_SRC])





echo "</table>";

} //EOF IF


if($_GET[KSIEG_DOKUMENTY_ANALIZA_INWESTYCJI]) {

echo "<pre>";

/*
echo "

//Tutaj bedziemy szukac wszystkich projektow jakie sa w bazie i zapiszemy je do tablicy:
 // PROJECTS[x][LOCAL]
 //				  [PARENT]= rodzic (STALA)
 //				  [COSTS]= koszty  (KWOTA); +[CUMULATED_COSTS] - koszty skumulwoane z poprzednich okresow
 //				  [ilosc_faktur]= (KWOTA) ilosc faktur ; +[CUMULATED_ilosc_faktur]
 //			      [REWIRS] = rewirow (STAN)
 //
 //			      [HC]= ile mieszkan (STAN)
 // 		     [CHILD]=dzieci? (STAN)
 //			       [COSTS]= kosztow z dolu (KWOTA)
 //			       [REWIRS] = rewirow z dolu (STAN)
 //			       [HC]= ile mieszkan z dolu (STAN)
 //				['CALCULATED']['RATIO_LOCAL']= wspolczynnik kosztu [LOCAL][HC]/(\$SUMA_HC['HC'])  , \$HC_SUM+= foreach(\$DATA[\$ID_PROJECT]['CHILD'] as \$SUMA_HC)
 //						      ['COST_LOCAL'] = wyliczony koszt projektu z ratio (LOCAL_COSTS+CHILD_COST)*RATIO_LOCAL
 //							  ['COST_PARENT'] = wyliczony przynalezny z PARENT'a koszt danego projektu
 //				               ['CUMULATED_COST_LOCAL']  - tak jak wyzej, tylko, ze cumulated od poczatku zestawienia
 //				           	   ['CUMULATED_COST_PARENT']  - tak jak wyzej, tylko, ze cumulated od poczatku zestawienia
 //			   aby wyliczyc koszt projektu, patrz na ['CALCULATED']['COST_LOCAL'] (koszt lokalny+dzieci)
 //			   oraz dodaj do tego ['CALCULATED']['COST_PARENT']
 //			";
 echo "

 // strategia :-1) obsluga tabeli RAPORT_CROSS (dane per projekt) i  RAPORT_CROSS_XML (cale i wszystkie obiekty)
 //					a) truncate table//?
 //					a1) wczytujemy XML'e (unserialize) , aby nie robic analiz od poczatku zawsze ! TODO
 //					   to dajemy zaraz po petli-> goto 0) a1)
 //					a2) w kodzie  tagujemy fragmenty kodu do olewania : if($AD0a1['FLAG_RAPORT_NOT_EXISTS']==1) {
 //					b) przy wyswietlaniu tabeli na koncu , bedziemy robic inserty RAPORT_CROSS
 //					c) na koncu robimy insert into RAPORT_XML przy resetowaniu - linia ok 13xx
 //					d) ??? czy my chcemy - wyswietlic jakis miesiac ? <<< TODO ten wariant
 //					e) ??? czy my chcemy wyswietlic aktualny/ostatni stan ? <<< ten wariant robimy
 //							 - wiec bierzemy ostatni miesiac znanego raportu, a reszte UNSET
 //
 //				0) teraz mamy juz wszystko i bedziemy robic analizy miesiac-po-miesiacu
 //					a) tabela INDEKS24 rok-miesiac trzeba stworzyc
 //					a1) sprawdzamy czy jest taki rekord w tabeli RAPORT_CROSS_XML i robimy UNSERIALIZE
 //					b) analizujemy koszty i sprzedaz w nastepujacy sposob:
 //						1. do \$DATA_HIST[] dodajemy \$DATA[�.],
 //						2. tam dodajemy strukture i dane z danego miesiaca
 //						(TODO jak brac koszty za uslugi rozliczane wstecz ? czy naliczac koszt uslugi z innego miesiaca??)
 //						2b. TODO struktura kosztow projektow : 1) zmiany w strukturach mieszkan,
 //															   2) rozksiegowujemy koszty wg nowej struktury
 //															   3) porownujemy ze starymi -> \$roznice ,
 //															   4) roznice dodajemy/odejmujemy do sum projektow ? TODO
 //						3. po czym zerujemy $DATA
 //					    4. mamy wartosci kosztow zsumowane we wszystkich DATA, rentownosc i wszystko mamy po zsumowaniu wszystkiego
 //						5. nie zapominajmy o wliczaniu kosztow uslug (sprzedazy) - inwestycja moze byc z poczatku na plusie potem moze dawac dupy
 //
 //					c) resetujemy STALE (nie kwoty) aby miec obrac wartosci kumulowany do poprzedniego arraya _HIST :
 //						i $DATA[$DWA['ID_PROJECT']]['LOCAL'][ILOSC_FAKTUR]
 //						i $DATA[$DWA['ID_PROJECT']]['LOCAL'][ILOSC_POZYCJI]
 //						i $DATA[$DWA['ID_PROJECT']]['OFER_USED'][$DWA['T11_ID_OFFERS']]['ILOSC_FAKTUR']
 //						i $DATA[$DWA['ID_PROJECT']]['OFER_USED'][$DWA['T11_ID_OFFERS']]['ILOSC_POZYCJI']
 //						i 	 $DATA_R[$DWA['M_REWIR']][ILOSC_FAKTUR]+=$DWA['ILOSC_FAKTUR']; //TODO bedzie zle CUMULATED
 //						i	 $DATA_R[$DWA['M_REWIR']][ILOSC_POZYCJI]+=$DWA['ILOSC_POZYCJI']
 //				1) struktura projektow i wyjecie kosztow tych projektow z informacjami
 //				2) przelecenie struktury rekursywne
 //				  x) idziemy od konca - budujemy do kazdego wezla \$PATH i sortujemy po LENGHT
 //				  a) do rodzica X dorzucamy info dziecka Y w zmiennej [X][CHILD][Y][HC]
 //				  b) jestesmy u rodzica i analizujemy stosunek CHILD[..][HC] i przekazujemy go jako zsumowany
 //				  e) na samym poczatku zawsze szukamy wezlow, ktore nie maja nic w CHILD i nic w HC , i dajemy ich koszty do PARENT 100%
 //				   e1) wezly kosztow, ktore sa uzywane przez OFFER_COSTS - nie puszczaja dalej w gore drzewa kosztu (jakby mialy 1 mieszkanie)
 //				  c) teraz z dolu idziemy do gory pokolei - narzucamy ceny do dzieci (sort od najmniejszego path) [X][RATIO][COST]
 //					 w stosunku CENA/(SUMA HC) * HC(X) , do wezla wyzej
 //				  d) wezel wyzej dodaje swoja cene, do wezla wyzej dodajac koszty LOCAL+RATIO
 //				 3) Koszty Sprzedazy uslug - w dwoch kategoriach -
 //				  a) jakie koszty uslug powstaly na ID_PROJECT(USERS2_OFFERS_COSTS)
 //				  a) Na Projekcie(Inwestycji)->BUILDINGS->ID_SERVICES->ID_OFFER->USERS2_OFFERS_COSTS->(ratio : Price/Weight(Mbits�))->USERS2_OFFERS_COSTS
 //				  b) Jak dana pozycja kosztu ID_PROJECT zostala sprzedana ID_PROJECT(USERS2_OFFERS_COST_SALE)
 //				  b)   ID_SERVICES->ID_OFFER=>USERS2_OFFERS_COSTS <-ID_PROJECTS_COSTS ||
 //				  b) ID_PROJECT(COST) || ID_OFFER(ratios: price/weight(mbits))->ID_SERVICES->
 //				  c) 2011-09-30 mamy juz koszty ofert, wiec mozna przemielic przez sprzedaz ponownie i nadac koszty na projekty/rewiry
 //				  4) Raport uzytych licencji - kosztow -> \$DATA[CALCULATED_AD4_TO_RAPORT][FROM_OFFERS]
 //				    a) Ile uzyto danych licencji na ilosc (poz faktur), ilosc (ilosc na fakturach) - z podaniem wartosci elementarnych / pakietow
 //					b) obsluga-export do tabeli RAPORT_PROJECT_COSTS
 //
 //				";
*/

echo "KSIEG_DOKUMENTY_ANALIZA_INWESTYCJI<form  method=\"GET\">"; //action=$PHP_SELF
echo "<input type=hidden name=ADD value=ADD>";
echo "<input type=hidden name=KSIEG_DOKUMENTY_ANALIZA_INWESTYCJI value=1>";
echo "<input type=text name=MIESIAC value=".$_GET['MIESIAC']."> Ilosc miesiecy wstecz analizy 0=teraz <br>";
// TODO to jest zmiennna juz systemowa i sie nadpisuje� echo "<input type=text name=DATA_ANALIZY value=".$_GET[DATA_ANALIZY]."> DATA_ANALIZY - wpisz % <br>";
echo "<input type=text name=REQ_DATA_ANALIZY value=".$_GET['REQ_DATA_ANALIZY']."> REQ_DATA_ANALIZY - wpisz miesiac, jaki chcesz zobaczyc szczegolowo <br>";
echo "<input type=text name=REQ_DELETE_RAPORT_AFTER value=".$_GET['REQ_DELETE_RAPORT_AFTER']."> REQ_DELETE_RAPORT_AFTER - wpisz , od jakiej daty chcesz ponownie wyliczac raporty YYYY-MM-DD <br>";
echo "<input type=checkbox name=RAPORT_AFTER_TABLE> RAPORT_AFTER_TABLE - podsumowanie po kazdej tabeli <br>";
echo "<input type=checkbox name=REMOVE_RAPORT_TABLES> REMOVE_RAPORT_TABLES - usuniecie tabel RAPORT_CROSS,RAPORT_CROSS_XML,RAPORT_PROJECT_COSTS<br>";


//echo "<input type=text name=ILOSC_MIESIECY_DO_ANALIZY_WSTECZ value=".$_GET[ILOSC_MIESIECY_DO_ANALIZY_WSTECZ]."> ILOSC_MIESIECY_DO_ANALIZY_WSTECZ - wpisz % <br>";


echo "<input type=SUBMIT name=SUBMIT value=wyslij>";

if(!isset($_GET['SUBMIT'])) die("Stop: Nacisjij WYSLIJ");

//TODO testowa aktualizacja tabeli SERVICES o niezbedne pola ID_OFFERS , oraz naladowanie testowe tych pol
		ZAP_SQL('describe SERVICES');
		while($h=mysql_fetch_array($result)) {
			$H[]=$h[0];
		}
/*		if(!in_array('ID_OFFERS',$H)) echo "JEST";
		else {
		//	ZAP_SQL('alter table SERVICES add ID_OFFERS int(11) ');
		//	ZAP_SQL('alter table SERVICES add INDEX(ID_OFFERS) ');
			ZAP_SQL("update SERVICES as t1, SES_USERS2_A as t2 set t1.ID_OFFERS='116' where t1.NAME_LIST_SERVICES='USERS2' and t1.ID=t2.ID_SERVICES and t2.P_SERVICE_QUOTA<4028");
			ZAP_SQL("update SERVICES as t1, SES_USERS2_A as t2 set t1.ID_OFFERS='280' where t1.NAME_LIST_SERVICES='USERS2' and t1.ID=t2.ID_SERVICES and t2.P_SERVICE_QUOTA>4028");
			ZAP_SQL("update SERVICES as t1, SES_USERS2_A as t2 set t1.ID_OFFERS='182' where t1.NAME_LIST_SERVICES='TV' and t1.ABONAMENT_VALUE<40");
			ZAP_SQL("update SERVICES as t1, SES_USERS2_A as t2 set t1.ID_OFFERS='372' where t1.NAME_LIST_SERVICES='TV' and t1.ABONAMENT_VALUE>=40 and t1.ABONAMENT_VALUE<80");
			//ZAP_SQL("update SERVICES as t1, SES_USERS2_A as t2 set t1.ID_OFFERS='182' where t1.NAME_LIST_SERVICES='TV' and t1.ABONAMENT_VALUE>=40 and t1.ABONAMENT_VALUE<80");

		}

*/
//		print_r($H);
		unset($H);



//echo "<table border=1><tr><td>";


if(!isset($_GET[MIESIAC])) $_GET[MIESIAC]='0';

echo "// AD -1 RAPORT_CROSS tabela truncate etc.";
	$ZAP_SQL="truncate table RAPORT_CROSS";
	ZAP_SQL($ZAP_SQL);

				if($_GET[REQ_DELETE_RAPORT_AFTER]) {
				//jezeli jest $_GET[REQ_DELETE_RAPORT_AFTER], to nalezy raz usunac rekordy z datami po tej dacie
				$ZAP_SQL="delete from RAPORT_CROSS_XML where RPAD_DATA>'".$_GET[REQ_DELETE_RAPORT_AFTER]."'";
			    echo "<br> ".$ZAP_SQL;
				ZAP_SQL($ZAP_SQL);
				}


				if($_GET[REMOVE_RAPORT_TABLES]) {
				//jezeli jest $_GET[REQ_DELETE_RAPORT_AFTER], to nalezy raz usunac rekordy z datami po tej dacie
				$ZAP_SQL="truncate table  RAPORT_CROSS_XML";
			    echo "<br> ".$ZAP_SQL;
				ZAP_SQL($ZAP_SQL);
				$ZAP_SQL="truncate table  RAPORT_CROSS";
			    echo "<br> ".$ZAP_SQL;
				ZAP_SQL($ZAP_SQL);
				$ZAP_SQL="truncate table  RAPORT_PROJECT_COSTS";
			    echo "<br> ".$ZAP_SQL;
				ZAP_SQL($ZAP_SQL);

				}


echo "// AD0 - ";
error_reporting(E_ALL);

		include("superedit-SEF.php");
	   SEF("INDEKS24_SQIX");
//	   INDEKS24_SQIX(90,2);
	// 	die("dupa");


				//0. Budowa tabeli slownikowej INDEKS24
				$ILOSC_MIESIECY_DO_ANALIZY_WSTECZ=12;
	//		echo "<br>//Tworze slownikowa tabele od 0 do ".$ILOSC_MIESIECY_DO_ANALIZY_WSTECZ." miesiecy w przeszlosc\n";
			 $ZAP_SQL=" drop  table  if exists   INDEKS24 ;"; //echo "<br> $ZAP_SQL  <br>\n";
			 			 ZAP_SQL($ZAP_SQL);
			 $ZAP_SQL=" create   table INDEKS24 (ID int(3)  , DATA date , DATA_LIKE varchar(50) ) ;";
			// echo "<br> $ZAP_SQL  <br>\n";
			 ZAP_SQL($ZAP_SQL);
			 $i=-10; //ile wprzod zaczac (minus)
			 $LP=$i*-1;
			  while ($i < $ILOSC_MIESIECY_DO_ANALIZY_WSTECZ ) {
			 	 $i++;
				 $LP--;
			 //echo "Nas            z miesiac to $i<br>";
			 $ZAP_SQL="insert into INDEKS24 SELECT '".$LP."', DATE_FORMAT(concat(PERIOD_ADD( DATE_FORMAT(now(), '%Y%m') ,-$i),'01'),'%Y-%m-%d') , DATE_FORMAT(concat(PERIOD_ADD( DATE_FORMAT(now(), '%Y%m') ,-$i),'01'),'%Y-%m-%'); ";
			 ZAP_SQL($ZAP_SQL);
			//TODO uncomment DATA_CREATE
			  // echo " $ZAP_SQL \n <br>";
			//EOF Tworze slownikowa tabele od 0 do 24
			 }

		ZAP_SQL("select 1+1");

		$ZAP_SQL="select * from INDEKS24 order by ID";
		 $RES_PETLA_AD0=mysql_query($ZAP_SQL);
		while($RPAD=mysql_fetch_object($RES_PETLA_AD0)) {

		echo "<hr>    Jade date ".$RPAD->DATA_LIKE." oraz ".$RPAD->DATA." poprzedni \$PETLA_AD0['LAST_RPAD_DATA'] to : ".$PETLA_AD0['LAST_RPAD_DATA'];
		$_GET[DATA_ANALIZY]=$RPAD->DATA_LIKE ;


//echo "// AD0 a1)  ( AD-1 a1) Wczytanie danych z RAPORT_CROSS ) , jak sa.



				//wczytujemy tylko ostatni raport, reszte trzeba olac, wiec szukamy ostatniego, jaki jest
				$ZAP_SQL="select RPAD_DATA , LAST_RPAD_DATA from RAPORT_CROSS_XML where RPAD_DATA='".$RPAD->DATA."' order by ID ";
				echo "<br>AD0e: ".$ZAP_SQL ;
				$RES_AD0e=mysql_query($ZAP_SQL);

				 while($RES_AD0e_R=mysql_fetch_object($RES_AD0e)) { //zczytujemy tablice do skryptu!
				  $AD0e['LAST_RPAD_DATA']=$RES_AD0e_R->RPAD_DATA ;
				  $PETLA_AD0['LAST_RPAD_DATA']=$RES_AD0e_R->LAST_RPAD_DATA; //TODO wywalic?
				  echo "<br> znalazlem rapot XML last to : ".$RES_AD0e_R->LAST_RPAD_DATA;

				 }
				 if((mysql_num_rows($RES_AD0e)==0)||(strstr($RPAD->DATA_LIKE,$_GET[REQ_DATA_ANALIZY]))) {
				  $AD0e['LOAD_RPAD_DATA_FLAG']=$AD0e['LAST_RPAD_DATA'];
				  echo "<br> Adduje FLAGE ".$AD0e['LOAD_RPAD_DATA_FLAG']." , i ide dalej z caloscia, bo numrows: ".mysql_num_rows($RES_AD0e)." oraz strstr(".$RPAD->DATA_LIKE.",".$_GET[REQ_DATA_ANALIZY].")=1" ;
				 } else { continue ;  //przerywamy dalsze kroki w petli AD0?
				 echo "<br> Kontynuuje bo result to: ".mysql_num_rows($RES_AD0e)." oraz strstr(".$RPAD->DATA_LIKE.",".$_GET[REQ_DATA_ANALIZY].")=1";
				 }
		$ZAP_SQL="select * from RAPORT_CROSS_XML where RPAD_DATA='".$AD0e['LAST_RPAD_DATA']."' or RPAD_DATA='xxxxx".$RPAD->DATA."' order by ID desc limit 1 ";
		echo "<br> RObie AD0 ".$ZAP_SQL;
		 $RES_AD0a1=mysql_query($ZAP_SQL);
		 $AD0a1['FLAG_RAPORT_NOT_EXISTS']=0;
		 while($RES_AD0a1_R=mysql_fetch_object($RES_AD0a1)) { //zczytujemy tablice do skryptu!
		//	print_r($RES_AD0a1_R);
			if(isset($UNSERIALIZE)) unset($UNSERIALIZE);
			$UNSERIALIZE=array();
			$UNSERIALIZE=unserialize($RES_AD0a1_R->XML);
		//	print_r($UNSERIALIZEE);
			//echo $RES_AD0a1_R->XML;
		//	die('problem...');
		 //	$DATA[$RES_AD0a1_R->DATA__ID_PROJECT]=$UNSERIALIZE[''] ;
			echo "<br> Zapisuje do DATA_HIST[".$RES_AD0a1_R->RPAD_DATA."]['DATA']=" ;
		//	print_r($UNSERIALIZE['DATA']);
		//	die();
			$DATA_HIST[$RES_AD0a1_R->RPAD_DATA]['DATA']=$UNSERIALIZE['DATA'];
			$DATA_HIST[$RES_AD0a1_R->RPAD_DATA]['OFER']=$UNSERIALIZE['OFER'];
			$DATA_HIST[$RES_AD0a1_R->RPAD_DATA]['OFER_TOTAL']=$UNSERIALIZE['OFER_TOTAL'];
			$DATA_HIST[$RES_AD0a1_R->RPAD_DATA]['DATA_R']=$UNSERIALIZE['DATA_R']; //rewir historia
			$DATA_SORT=$UNSERIALIZE['DATA_SORT'];
			$PETLA_AD0['LAST_RPAD_DATA']=$RES_AD0a1_R->LAST_RPAD_DATA ;  //do uzycia PRZYROSTOW_Z_OSTATNIEGO dla WARTOSCI/PARAMETROW
			echo "<br> Z AD0 l585 : poprzedni \$PETLA_AD0['LAST_RPAD_DATA'] to : ".$PETLA_AD0['LAST_RPAD_DATA'];
		 	$AD0a1['FLAG_RAPORT_NOT_EXISTS']=1;
		 }
		  if($AD0a1['FLAG_RAPORT_NOT_EXISTS']==1) {
		  	$DATA=$UNSERIALIZE['DATA']; // w ostatnim ID napelniamy ostatnie DATA, jako aktualne DATA
//			$OFER=$UNSERIALIZE['OFER']; // w ostatnim ID napelniamy ostatnie DATA, jako aktualne DATA
//			$OFER_TOTAL=$UNSERIALIZE['OFER_TOTAL']; // w ostatnim ID napelniamy ostatnie DATA, jako aktualne DATA
//			print_r($DATA_HIST);
//			die();
			echo "<br> mamy tobic CONTINUE";
			if(!strstr($RPAD->DATA_LIKE,$_GET[DATA_ANALIZY])) {
			 echo "<br>//Olewamy dalsza analize skryptu w rozumieniu $RES_AD0a1_R->RPAD_DATA ";
			 continue;

			}
//		  tagujemy fragmenty kodu do olewania : if($AD0a1['FLAG_RAPORT_NOT_EXISTS']==1) {
//												} //eof if($AD0a1['FLAG_RAPORT_NOT_EXISTS']==1)
		  }

//echo "// AD0 b) - jedziemy po datach i tworzymy DATA_HIST, ale na samym koncu ";
		//  AD0 b) , jak chcemy wylaczyc petle lat, to trzeba wyremowac AD0 b) nizej na lini 1058  EOF�


 //die();
 flush();


 		//echo "// AD0



echo "// AD0 c) - kasujemy zmienne kumulacyjne dla stalych okresowych ";
	 foreach($DATA as $DATA_I=>$DATA_V) { //kasujemy dane w PROJEKTACH = DATA
	 	if(isset($DATA_V['LOCAL']['ILOSC_FAKTUR']))  unset($DATA[$DATA_I]['LOCAL']['ILOSC_FAKTUR']);
	 	if(isset($DATA_V['LOCAL']['ILOSC_POZYCJI'])) unset($DATA[$DATA_I]['LOCAL']['ILOSC_POZYCJI']);
//		foreach($DATA_V['OFER_USED'] as $OFER_USER_I=>$OFER_USED_V) {
//			 	if(isset($OFER_USED_V['ILOSC_FAKTUR'])) unset($DATA[$DATA_I]['OFER_USED'][$OFER_USED_V]['ILOSC_FAKTUR']);
//			 	if(isset($OFER_USED_V['ILOSC_POZYCJI'])) unset($DATA[$DATA_I]['OFER_USED'][$OFER_USED_V]['ILOSC_POZYCJI']);
//		}
		if(isset($DATA_V['OFER_USED'])) unset($DATA[$DATA_I]['OFER_USED']);
		if(isset($DATA_V['LOCAL']['HC'])) unset($DATA[$DATA_I]['LOCAL']['HC']);
		if(isset($DATA_V['LOCAL']['ilosc_budynkow'])) unset($DATA[$DATA_I]['LOCAL']['ilosc_budynkow']);
		if(isset($DATA_V['LOCAL']['np_budynek'])) unset($DATA[$DATA_I]['LOCAL']['np_budynek']);
		if(isset($DATA_V['LOCAL']['ILOSC_POWIAZANYCH_KOSZTOW_OFERT'])) unset($DATA[$DATA_I]['LOCAL']['ILOSC_POWIAZANYCH_KOSZTOW_OFERT']);
		if(isset($DATA_V['LOCAL']['M_REWIR'])) unset($DATA[$DATA_I]['LOCAL']['M_REWIR']);
		if(isset($DATA_V['CALCULATED_AD4_TO_RAPORT'])) unset($DATA[$DATA_I]['CALCULATED_AD4_TO_RAPORT']);


	 }
   if(isset($DATA_R)) {
	  	  foreach($DATA_R as $IND=>$VAL) { //kasujemy dane w REWIRACH
    		if(isset($VAL['ILOSC_FAKTUR'])) unset($DATA_R[$IND]['ILOSC_FAKTUR']);
    		if(isset($VAL['ILOSC_POZYCJI'])) unset($DATA_R[$IND]['ILOSC_POZYCJI']);
		  }
  }
  //EOF AD0 c) - kasujemy zmienne

 //new od 2011-09-07
 $ZAP_SQL="select min(t1.ID_SERVICES) as ID_SERVICES , sum(t1.PRICE*t1.AMMOUNT) as SUM_TOTAL ,
        sum(t1.PRICE*if(year(t1.DATE_FROM)=year(now()) and month(t1.DATE_FROM)=month(now())-".$RPAD->DATA.",t1.AMMOUNT,0)) as SPRZED_LAST_MC ,
	sum(if(year(t1.DATE_FROM)=year(now()) and month(t1.DATE_FROM)=month(now())-".$RPAD->DATA.",1,0)) as ILOSC_ABO,
	t2.T_NETWORK_SERVER , COALESCE(t3.M_REWIR,'BRAK-REWIR') as M_REWIR , COALESCE(t4.ID_PROJECT,'BRAK') as ID_PROJECT , t4.ID as BUILDINGS_ID , t2.S_ADDRESS_STREET as S_ADDRESS_STREET , t11.NAME_LIST_SERVICES as NAME_LIST_SERVICES
	, t11.ID_OFFERS as T11_ID_OFFERS , count(t1.ID) as ILOSC_FAKTUR , count(t1.AMMOUNT) as ILOSC_POZYCJI

	from BILLS_FVAT_POS as t1
		left join BILLS_FVAT as BFV on BFV.ID=t1.ID_BILLS_FVAT
	left join SERVICES as t11 on t1.ID_SERVICES=t11.ID
	left join SES_USERS2_A as t2 on t1.ID_SERVICES=t2.ID_SERVICES

        left join USERS2_MARKETING as t3 on ( t2.S_ADDRESS_STREET=t3.S_ADDRESS_STREET )
	left join BUILDINGS as t4 on ( t3.T_TELBOX_BUILDING_IN=t4.S_ADDRESS_STREET  and t4.A_STATUS!='DELETED')
        where t1.ID_SERVICES > 0
                 and t11.NAME_LIST_SERVICES='USERS2'
                            and BFV.BILL_DATE like '".$_GET[DATA_ANALIZY]."'
       group by t3.M_REWIR  , t11.ID_OFFERS
         union

         select min(t1.ID_SERVICES) as ID_SERVICES , sum(t1.PRICE*t1.AMMOUNT) as SUM_TOTAL ,
        sum(t1.PRICE*if(year(t1.DATE_FROM)=year(now()) and month(t1.DATE_FROM)=month(now())-".$RPAD->DATA.",t1.AMMOUNT,0)) as SPRZED_LAST_MC ,
	sum(if(year(t1.DATE_FROM)=year(now()) and month(t1.DATE_FROM)=month(now())-".$RPAD->DATA.",1,0)) as ILOSC_ABO,
	t2.T_NETWORK_SERVER , COALESCE(t3.M_REWIR,'BRAK-REWIR') as M_REWIR , COALESCE(t4.ID_PROJECT,'BRAK') as ID_PROJECT , t4.ID as BUILDINGS_ID , t2.S_ADDRESS_STREET as S_ADDRESS_STREET , t11.NAME_LIST_SERVICES as NAME_LIST_SERVICES
	, t11.ID_OFFERS as T11_ID_OFFERS , count(t1.ID) as ILOSC_FAKTUR , count(t1.AMMOUNT) as ILOSC_POZYCJI

	from BILLS_FVAT_POS as t1
	 		left join BILLS_FVAT as BFV on BFV.ID=t1.ID_BILLS_FVAT
	left join SERVICES as t11 on t1.ID_SERVICES=t11.ID
	left join SES_TV_A as t2 on t1.ID_SERVICES=t2.ID_SERVICES

        left join USERS2_MARKETING as t3 on ( t2.S_ADDRESS_STREET=t3.S_ADDRESS_STREET )
	left join BUILDINGS as t4 on ( t3.T_TELBOX_BUILDING_IN=t4.S_ADDRESS_STREET  and t4.A_STATUS!='DELETED')
        where t1.ID_SERVICES > 0
         and t11.NAME_LIST_SERVICES='TV'
                            and BFV.BILL_DATE like '".$_GET[DATA_ANALIZY]."'

	group by t3.M_REWIR , t11.ID_OFFERS

	union

       select min(t1.ID_SERVICES) as ID_SERVICES , sum(t1.PRICE*t1.AMMOUNT) as SUM_TOTAL ,
        sum(t1.PRICE*if(year(t1.DATE_FROM)=year(now()) and month(t1.DATE_FROM)=month(now())-".$RPAD->DATA.",t1.AMMOUNT,0)) as SPRZED_LAST_MC ,
	sum(if(year(t1.DATE_FROM)=year(now()) and month(t1.DATE_FROM)=month(now())-".$RPAD->DATA.",1,0)) as ILOSC_ABO,
	t2.T_NETWORK_SERVER , COALESCE(t3.M_REWIR,'BRAK-REWIR') as M_REWIR , COALESCE(t4.ID_PROJECT,'BRAK') as ID_PROJECT , t4.ID as BUILDINGS_ID , t2.S_ADDRESS_STREET as S_ADDRESS_STREET , t11.NAME_LIST_SERVICES as NAME_LIST_SERVICES
	, t11.ID_OFFERS as T11_ID_OFFERS , count(t1.ID) as ILOSC_FAKTUR , count(t1.AMMOUNT) as ILOSC_POZYCJI
	from BILLS_FVAT_POS as t1
	 		left join BILLS_FVAT as BFV on BFV.ID=t1.ID_BILLS_FVAT
	left join SERVICES as t11 on t1.ID_SERVICES=t11.ID
        	left join SERVICES as t111 on t11.ID=t111.P_ID_SERVICES

	left join SES_USERS2_A as t2 on t2.ID_SERVICES=t111.ID

        left join USERS2_MARKETING as t3 on ( t2.S_ADDRESS_STREET=t3.S_ADDRESS_STREET )
	left join BUILDINGS as t4 on ( t3.T_TELBOX_BUILDING_IN=t4.S_ADDRESS_STREET  and t4.A_STATUS!='DELETED')
        where t1.ID_SERVICES > 0
         and t11.NAME_LIST_SERVICES='VOIP'
                            and BFV.BILL_DATE like '".$_GET[DATA_ANALIZY]."'


		group by t3.M_REWIR , t11.ID_OFFERS


	order by M_REWIR,ID_PROJECT

	 ; "; //group by t3.M_REWIR //zrobmy limit TODO usunac limit
	  //TODO zmienic po 2011-09-30 , aby bylo group by BILLS_FVAT_POS.ID_OFFERS zamiast SERVICES_ID_OFFERS
 	  //TODO czy count(ID) od faktur to jest ilosc uslug, czy COUNT(AMMOUNT) ? do dalszych rozwazan 2011-09-30


//echo "ZAP SQL to $ZAP_SQL \n <br>";


if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else  ZAP_SQL("$ZAP_SQL");

echo "<table border=1>";
echo "<tr><td>ID_SRV </td><td>SPRZED_TOTAL</td><td>SPRZED_LAST_MC</td><td>ILOSC_ABO_LAST</td><td>T_NETWK_SERV</td><td>REWIR</td><td>ID_PROJECT</td><td> </td></tr>";
while($DWA=mysql_fetch_array($result)) {
	//print_r($DWA);
	echo "<tr><td> ".$DWA['ID_SERVICES']."</td><td>".$DWA['SUM_TOTAL']."</td><td>".$DWA['SPRZED_LAST_MC']."</td><td>".$DWA['ILOSC_ABO']."</td><td>".$DWA['T_NETWORK_SERVER']."</td><td>".$DWA['M_REWIR']."</td><td>".$DWA['ID_PROJECT']."/".$DWA['BUILDINGS_ID']."/".$DWA['S_ADDRESS_STREET']."/".$DWA['NAME_LIST_SERVICES']."</td></tr>\n";
	$DATA[$DWA['ID_PROJECT']]['ID_PROJECT']=$DWA['ID_PROJECT'];
	$DATA[$DWA['ID_PROJECT']]['LOCAL']['REWIR']=$DWA['M_REWIR'];
//TO NIC NIE DAJE sql	$DATA[$DWA['ID_PROJECT']]['LOCAL'][ILOSC_ABO_LAST]+=$DWA['ILOSC_ABO']; //TODO bedzie zle CUMULATED
//TO NIC NIE DAJE sql	$DATA[$DWA['ID_PROJECT']]['LOCAL'][SPRZED_LAST_MC]+=$DWA['SPRZED_LAST_MC']; //TODO bedzie zle CUMULATED
	$DATA[$DWA['ID_PROJECT']]['LOCAL']['SPRZED_TOTAL']+=$DWA['SUM_TOTAL']; //czy ?? TODO bedzie zle CUMULATED
	 $DATA[$DWA['ID_PROJECT']]['LOCAL']['ILOSC_FAKTUR']+=$DWA['ILOSC_FAKTUR'];   //RESETOWANE
	 $DATA[$DWA['ID_PROJECT']]['LOCAL']['ILOSC_POZYCJI']+=$DWA['ILOSC_POZYCJI']; //RESETOWANE
	//niby na potrzeby AD3c - wkladamy ilosc uzycia ofert
	$DATA[$DWA['ID_PROJECT']]['OFER_USED'][$DWA['T11_ID_OFFERS']]['ILOSC_FAKTUR']+=$DWA['ILOSC_FAKTUR']; //RESETOWANE
	$DATA[$DWA['ID_PROJECT']]['OFER_USED'][$DWA['T11_ID_OFFERS']]['ILOSC_POZYCJI']+=$DWA['ILOSC_POZYCJI']; //RESETOWANE



	$DATA_R[$DWA['M_REWIR']][ID_PROJECT]=$DWA['ID_PROJECT'];
	$DATA_R[$DWA['M_REWIR']][REWIR]=$DWA['M_REWIR'];
//	$DATA_R[$DWA['M_REWIR']][ILOSC_ABO_LAST]+=$DWA['ILOSC_ABO']; //TODO bedzie zle CUMULATED
//	$DATA_R[$DWA['M_REWIR']][SPRZED_LAST_MC]+=$DWA['SPRZED_LAST_MC']; //TODO bedzie zle CUMULATED
	$DATA_R[$DWA['M_REWIR']][SPRZED_TOTAL]+=$DWA['SUM_TOTAL']; //TODO bedzie zle CUMULATED
 	 $DATA_R[$DWA['M_REWIR']][ILOSC_FAKTUR]+=$DWA['ILOSC_FAKTUR']; //TODO bedzie zle CUMULATED
 	 $DATA_R[$DWA['M_REWIR']][ILOSC_POZYCJI]+=$DWA['ILOSC_POZYCJI']; //TODO bedzie zle CUMULATED

 } //EOF while sqlfetch
echo "</table>";


 // echo " //AD.1) szukamy kosztow projektow i ich wzajemnych powiazan- moze i tez ich mieszkan";
  /* przed 2018-03- $ZAP_SQL="select t1.ID, t1.P_ID , t1.M_DIST_DESC,  sum(t2.wartosc) as t2_wartosc , count(t2.ID) as ilosc_faktur  ,    min(t2.DATA_DOK) as I_ZACZETO , max(t2.DATA_DOK) as I_ZAKONCZONO
    from IN7_MK_BAZA_DYSTRYBUCJI as t1
    left join KSIEG_DOKUMENTY as t2 on t1.ID=t2.ID_PROJECT
    where t2.A_STATUS!='DELETED'
    and t2.DATA_DOK like '".$_GET[DATA_ANALIZY]."'
    	 group by t1.ID  		 "; //and ( t1.ID=138 or t1.ID=168 or t1.ID=446 )
*/
//@2018-03 - zastapienie danych rekordami z IN7_DZIENNIK_KORESP
$ZAP_SQL="select t1.ID, t1.P_ID , t1.M_DIST_DESC,  sum(t2.COST_VALUE) as t2_wartosc , count(t2.ID) as ilosc_faktur  ,   
	 min(t2.K_DATA_OTRZYMANEJ_KORESP) as I_ZACZETO , max(t2.K_DATA_OTRZYMANEJ_KORESP) as I_ZAKONCZONO
	 , group_concat(MK_Rewiry.NAZWA_REWI) as NAZWA_REWI
    from IN7_MK_BAZA_DYSTRYBUCJI as t1
    left join IN7_DZIENNIK_KORESP as t2 on t1.ID=t2.ID_PROJECT
    left join MK_Rewiry as MK_Rewiry on t1.ID = MK_Rewiry.ID_PROJECT
    where t2.A_STATUS!='DELETED'
    and t2.K_DATA_OTRZYMANEJ_KORESP like '".$_GET[DATA_ANALIZY]."'
    	 group by t1.ID  		 "; 

	echo "\n".$ZAP_SQL."\n"; //koszty wyliczone 1 raz dla calosci to :
	//446=3 152,07+ 0,00 (3 152,07) = 3 152,07 ; zgadza sie przy wyzwoleniach perLATA
	// 138=52 355,67+ 0,00 (52 355,67) = 52 355,67 ; to tez OK ;
	// 168=181,41+ 0,00 (181,41) = 181,41 ; to tez OK ;
    ZAP_SQL($ZAP_SQL);
    flush();
    while($R2=mysql_fetch_object($result)) {
		//print_r($R2);
		$DATA[$R2->ID]['LOCAL']['ID_PROJECT']=$R2->ID;
		list($DATA[$R2->ID]['LOCAL']['PARENT'])=split('[ ,]',$R2->P_ID);
		$DATA[$R2->ID]['LOCAL']['COSTS']+=floatval($R2->t2_wartosc); //CUMULATED - KWOTA
		$DATA[$R2->ID]['LOCAL']['ilosc_faktur']+=floatval($R2->ilosc_faktur); //CUMULATED - KWOTA
		$DATA[$R2->ID]['LOCAL']['I_ZACZETO']=$R2->I_ZACZETO;
		$DATA[$R2->ID]['LOCAL']['I_ZAKONCZONO']=$R2->I_ZAKONCZONO;
		$DATA[$R2->ID]['LOCAL']['NAZWA_REWI']=$R2->NAZWA_REWI;
    }

/*  //AD.1)  e1) i jeszcze dodajemy koszty projektow z ID_PROJECT do kosztow glownego projektu -
  2011-09-30 !!! TODO zaniechano to dzialanie, z uwagi na niekonsekwencje ID_PROJECT i balagan z tym zwiazany - usunac kolumne ID_PROJECT z projektow!
   $ZAP_SQL="select t1.ID, t1.P_ID , t1.M_DIST_DESC, t1.ID_PROJECT ,  sum(t2.wartosc) as t2_wartosc , count(t2.ID) as ilosc_faktur  ,    min(t2.DATA_DOK) as I_ZACZETO , max(t2.DATA_DOK) as I_ZAKONCZONO	 from IN7_MK_BAZA_DYSTRYBUCJI as t1	 left join KSIEG_DOKUMENTY as t2 on t1.ID=t2.ID_PROJECT where t1.ID_PROJECT>0		 group by t1.ID  		 ";
	echo "\n".$ZAP_SQL."\n";
    ZAP_SQL($ZAP_SQL);
    flush();
    while($R2=mysql_fetch_object($result)) {
		//print_r($R2);
		$DATA[$R2->ID_PROJECT]['ID_PROJECT']['ID_PROJECT']=$R2->ID;
		list($DATA[$R2->ID_PROJECT]['ID_PROJECT']['PARENT'])=split('[ ,]',$R2->P_ID);
		$DATA[$R2->ID_PROJECT]['ID_PROJECT']['COSTS']=floatval($R2->t2_wartosc);
		$DATA[$R2->ID_PROJECT]['ID_PROJECT']['ilosc_faktur']=floatval($R2->ilosc_faktur);
		$DATA[$R2->ID_PROJECT]['ID_PROJECT']['I_ZACZETO']=$R2->I_ZACZETO;
		$DATA[$R2->ID_PROJECT]['ID_PROJECT']['I_ZAKONCZONO']=$R2->I_ZAKONCZONO;
    }

*/

echo " //AD.1-1) szukamy kosztow projektow i ich wzajemnych powiazan- moze i tez ich mieszkan";
   $ZAP_SQL="select t1.ID, t1.P_ID , t1.M_DIST_DESC, count(t3.ID) as ilosc_budynkow , t3.S_ADDRESS_STREET as np_budynek ,
     		sum(t4.MIESZKAN) as HC      		 from IN7_MK_BAZA_DYSTRYBUCJI as t1
     	left join BUILDINGS as t3 on t1.ID=t3.ID_PROJECT   		   left join USERS2_MARKETING_OVERWIEV as t4 on t3.S_ADDRESS_STREET=t4.T_TELBOX_BUILDING_IN
     	group by t1.ID   "; //TODO brac budynki tylko po dacie $RPAD->DATA
	echo "\n".$ZAP_SQL."\n";
    ZAP_SQL($ZAP_SQL);
    flush();
    while($R2=mysql_fetch_object($result)) {
	//	print_r($R2);
		$DATA[$R2->ID]['LOCAL']['M_DIST_DESC']=$R2->M_DIST_DESC;
		$DATA[$R2->ID]['LOCAL']['HC']=$R2->HC;
		$DATA[$R2->ID]['LOCAL']['ilosc_budynkow']=$R2->ilosc_budynkow;
		$DATA[$R2->ID]['LOCAL']['np_budynek']=$R2->np_budynek;
		 if(($R2->HC<1)&&($R2->ilosc_budynkow>=1)) { echo "<font color=red size=-1><br>Error z mieszkaniami dla proj: ".$R2->ID."</font>"; $DATA[$R2->ID]['LOCAL']['HC']=1 ;}
    }
//echo "//AD.1-2) szukamy kosztow projektow i ich wzajemnych powiazan- moze i tez ich mieszkan - REWIR_INFO";
   $ZAP_SQL="select t1.ID, t1.P_ID , t1.M_DIST_DESC, count(t3.ID) as ilosc_budynkow , 	  		 t3.S_ADDRESS_STREET as np_budynek ,
   			sum(t4.MIESZKAN) as HC , t3.M_REWIR as M_REWIR     		 from IN7_MK_BAZA_DYSTRYBUCJI as t1
   				 left join BUILDINGS as t3 on t1.ID=t3.ID_PROJECT
   				  		   left join USERS2_MARKETING_OVERWIEV as t4 on t3.S_ADDRESS_STREET=t4.T_TELBOX_BUILDING_IN
   				  		   	 group by t1.ID,t3.M_REWIR   		 ";
//	echo "\n".$ZAP_SQL."\n";
ZAP_SQL($ZAP_SQL);
    flush();
    while($R2=mysql_fetch_object($result)) {
	//	print_r($R2);
		list($DATA[$R2->ID]['LOCAL']['PARENT'])=split('[ ,]',$R2->P_ID);
		$DATA[$R2->ID]['LOCAL']['M_REWIR'][$R2->M_REWIR]['HC']=$R2->HC;
		$DATA[$R2->ID]['LOCAL']['M_REWIR'][$R2->M_REWIR]['ilosc_budynkow']=$R2->ilosc_budynkow;
		$DATA[$R2->ID]['LOCAL']['M_REWIR'][$R2->M_REWIR]['np_budynek']=$R2->np_budynek;
    }

//echo "// tutaj wykrywamy 2e1) czyli jakie projekty maja powiazane koszty ofert - SA KOSZTAMI OFERT";
   $ZAP_SQL="select t1.ID, t1.M_DIST_DESC ,  count(t2.ID) as ILOSC_POWIAZANYCH_KOSZTOW_OFERT
       		 from IN7_MK_BAZA_DYSTRYBUCJI as t1
       		 left join USERS2_OFFERS_COSTS as t2 on t1.ID=t2.ID_PROJECT group by t1.ID  "; //TODO czy zwiazac to jakos ? $RPAD->DATA

//	echo "\n".$ZAP_SQL."\n";
ZAP_SQL($ZAP_SQL);
    flush();
      while($R2=mysql_fetch_object($result)) {
	//	print_r($R2);
	 	if($R2->ILOSC_POWIAZANYCH_KOSZTOW_OFERT>0) {
			$DATA[$R2->ID]['LOCAL']['HC']+=1; //RESETTED line 600
			$DATA[$R2->ID]['LOCAL']['ilosc_budynkow']+=1; //RESETTED line 600
			$DATA[$R2->ID]['LOCAL']['np_budynek']+=1;//RESETTED line 600
			$DATA[$R2->ID]['LOCAL']['ILOSC_POWIAZANYCH_KOSZTOW_OFERT']+=$R2->ILOSC_POWIAZANYCH_KOSZTOW_OFERT; //TODO CUMULATED//RESETTED line 600
			$DATA[$R2->ID]['LOCAL']['M_REWIR']['']['HC']+=1;//RESETTED line 600
			$DATA[$R2->ID]['LOCAL']['M_REWIR']['']['ilosc_budynkow']+=1;//RESETTED line 600
			$DATA[$R2->ID]['LOCAL']['M_REWIR']['']['np_budynek']+=1;//RESETTED line 600
			$DATA[$R2->ID]['LOCAL']['M_REWIR']['']['ILOSC_POWIAZANYCH_KOSZTOW_OFERT']+=$R2->ILOSC_POWIAZANYCH_KOSZTOW_OFERT;//RESETTED line 600


	 	}
    }


//TODO drzewo mozna zrobic RAZ!
 	if(!isset($DATA_SORT)) {
//		echo " //begin krok2 x) budujemy sciezki po do root'a";
		 foreach($DATA as $ID_PROJECT=>$ARRAY) {

		//	$DATA[$ID_PROJECT]['CHILD']
			 $CURR_ROOT=$ARRAY['LOCAL']['PARENT'];
		     for($i = 1; $i <= 100; $i++){
				if(isset($DATA[$ID_PROJECT]['PATH']))$DATA[$ID_PROJECT]['PATH'].=",". $CURR_ROOT; else $DATA[$ID_PROJECT]['PATH'].=$CURR_ROOT;
				$DATA[$ID_PROJECT]['PATH_LEN']++;
		//			$DATA[$CURR_ROOT]['CHILD'][$ID_PROJECT]['COSTS']=$ARRAY['LOCAL']['COSTS'];
		//			$DATA[$CURR_ROOT]['CHILD'][$ID_PROJECT]['HC']=$ARRAY['LOCAL']['HC'];
		//			$DATA[$CURR_ROOT]['CHILD'][$ID_PROJECT]['ilosc_budynkow']=$ARRAY['LOCAL']['ilosc_budynkow'];
				if($CURR_ROOT==0) break;
				$CURR_ROOT=$DATA[$CURR_ROOT]['LOCAL']['PARENT'];
		     }

		 }
//		echo " //robimy indeks z dlugoscia kluczy";
			foreach($DATA as $ID_PROJECT=>$ARRAY) {
				$DATA_SORT[$ID_PROJECT]=$ARRAY['PATH_LEN'];
			}
			arsort($DATA_SORT);
	}


//echo "//print_r($DATA_SORT); - z dolu do gory  //lecimy ad 2) x - b) - ile HC ";
  foreach($DATA_SORT as $ID_PROJECT=>$VAL){
//	 echo "\n!!!!!!!".$ID_PROJECT;
	  $PARENT=$DATA[$ID_PROJECT]['LOCAL']['PARENT'];

	  $HC_SUM=$DATA[$ID_PROJECT]['LOCAL']['HC'];
	  $CHILD_COST_SUM=0;
	   foreach($DATA[$ID_PROJECT]['CHILD'] as $CHILD_ID=>$CHILD_ID_VAL) { //najdluzszy path(ostatni) nie ma dzieci!
	        $HC_SUM+=$CHILD_ID_VAL['HC'];
	        $CHILD_COST_SUM+=$CHILD_ID_VAL['COSTS'];

	   }
	  if($HC_SUM>0)	  $DATA[$PARENT]['CHILD'][$ID_PROJECT]['HC']=$HC_SUM; //sa mieszkania, to zapisujemy , ze dziecko ma mieszkania i nie dajemy kosztu do dzialy do PARENTA
	  	else if($DATA[$ID_PROJECT]['LOCAL']['COSTS']+$CHILD_COST_SUM>0) //jezeli nie ma mieszkan i ma koszty
	  $DATA[$PARENT]['CHILD'][$ID_PROJECT]['COSTS']=$DATA[$ID_PROJECT]['LOCAL']['COSTS']+$CHILD_COST_SUM; //to zapisujemy koszt siebie, jako koszt dziecka w PARENCIE
      //$DATA[$]
  }
//echo "
 // AD 2. c) - lecimy z kosztami i nadajemy je dzieciom [X][CALCULATED][COST,RATIO] proporcjami od CHILD[HC]
 //brakuje teraz kroku nadania kosztow wyzej z pustych mieszkan!
 //jedziemy z gory do dolu";

if(!isset($DATA_SORT_R)) { //1 wyzwolenie - raz mozna to zrobic
	$DATA_SORT_R=$DATA_SORT;
	asort($DATA_SORT_R);
}
//print_r($DATA_SORT_R);
//die();
	foreach($DATA_SORT_R as $ID_PROJECT=>$ARRAY) {
		$HC_SUM=0;
		$CHILD_COSTS=0;
		foreach($DATA[$ID_PROJECT]['CHILD'] as $CHILD_ID=>$CHILD_ID_VAL){
			$HC_SUM+=$CHILD_ID_VAL['HC'];
			$CHILD_COSTS+=$CHILD_ID_VAL['COSTS'];
		}
		    $DATA[$ID_PROJECT]['CALCULATED']['RATIO_LOCAL']=$DATA[$ID_PROJECT]['LOCAL']['HC']/($HC_SUM+$DATA[$ID_PROJECT]['LOCAL']['HC']);
		    $DATA[$ID_PROJECT]['CALCULATED']['COST_LOCAL']=($DATA[$ID_PROJECT]['LOCAL']['COSTS']+$CHILD_COSTS)*$DATA[$ID_PROJECT]['CALCULATED']['RATIO_LOCAL'];
		    $DATA[$ID_PROJECT]['CALCULATED']['CHILD_COSTS']=$CHILD_COSTS;
		    $DATA[$ID_PROJECT]['CALCULATED']['HC_SUM_CHILD_LOCAL']=$HC_SUM+$DATA[$ID_PROJECT]['LOCAL']['HC'];
		foreach($DATA[$ID_PROJECT]['CHILD'] as $CHILD_ID=>$CHILD_ID_VAL){
				if($CHILD_ID_VAL['HC']/$DATA[$ID_PROJECT]['CALCULATED']['HC_SUM_CHILD_LOCAL']>0) //jezeli wezel kosztu ma mieszkanie to rozliczamy
			$DATA[$ID_PROJECT]['CHILD'][$CHILD_ID]['RATIO']=$CHILD_ID_VAL['HC']/$DATA[$ID_PROJECT]['CALCULATED']['HC_SUM_CHILD_LOCAL'];
				if(($DATA[$ID_PROJECT]['LOCAL']['COSTS']+$DATA[$ID_PROJECT]['LOCAL']['COST_PARENT'])*$DATA[$ID_PROJECT]['CHILD'][$CHILD_ID]['RATIO']>0)
			$DATA[$CHILD_ID]['CALCULATED']['COST_PARENT']=($DATA[$ID_PROJECT]['LOCAL']['COSTS']+$DATA[$ID_PROJECT]['LOCAL']['COST_PARENT'])*$DATA[$ID_PROJECT]['CHILD'][$CHILD_ID]['RATIO'];
		}

	}


/*
echo "
 //AD 3a) jakie koszty uslug powstaly na ID_PROJECT(USERS2_OFFERS_COSTS)
 // statystyka oferty od strony sprzedazy faktur
 // \$OFER['ID']['TOTAL']['COUNT']- ile jest sprzedanych danych ofert w danym miesiacu
 // \$OFER['ID'](YEAR)(MONTH)['START']- ile w danym miesiacu bylo uruchomien danej oferty
 // \$OFER['ID'](YEAR)(MONTH)['DISCONNECT']- ile w danym miesiacu bylo zakonczen danej oferty
 // \$OFER['ID']['TOTAL']['SALE']- jaka jest wartosc sprzedazy danej oferty
 // \$OFER['ID']['COST_PER_SVC']- jaka jest nominalna wartosc zakupow danej oferty/1 usluga
 // \$OFER['ID']['TOTAL']['POWERCOST']- jaka jest nominalna wartosc zakupow danej oferty ( COST_PER_SVC*COUNT)
  //\$OFER['ID']['ID_PROJECTS']['X']['ID_PROJECT_SELL']= ( wartosc sprzedazy zwazona proporcja kosztu )$OFER[$IND]['TOTAL']['SALE']/$OFER[$IND]['COST_PER_SVC']*$R2->T4_COST_POWER


 // statystyka kosztow na danej sprawie
 // \$DATA['ID'][OFFERS_COSTS](YEAR)(MONTH)['TOTAL_POWER']- jaka jest sumaryczna wartosc zakupow w danym miesiacu - do faktur sprzed
 // \$DATA['ID'][OFFERS_COSTS](YEAR)(MONTH)['COSTS']- jaka jest sumaryczna wartosc zakupow w danym miesiacu - z faktur
 // \$DATA['ID'][OFFERS_COSTS](YEAR)(MONTH)['COSTS']

 //
 // najpierw liczymy sprzedaz";
 */
    $ZAP_SQL="select count(t1.ID) as T1_COUNT , sum(t1.AMMOUNT*t1.PRICE) as T1_SALE , t2.ID_OFFERS
   				from BILLS_FVAT_POS as t1
   				left join BILLS_FVAT as t11 on t11.ID=t1.ID_BILLS_FVAT
   				left join SERVICES as t2 on t1.ID_SERVICES=t2.ID  where t11.BILL_DATE like '".$_GET[DATA_ANALIZY]."'
   				 group by t2.ID_OFFERS  ";
//	echo "\n".$ZAP_SQL."\n";
ZAP_SQL($ZAP_SQL);
    flush();
    while($R2=mysql_fetch_object($result)) {
	 $OFER[$R2->ID_OFFERS]['TOTAL']['COUNT']=$R2->T1_COUNT ; //- ile jest sprzedanych danych ofert w danym miesiacu
 	  //$OFER[$R2->ID_OFFERS](YEAR)(MONTH)['START']- ile w danym miesiacu bylo uruchomien danej oferty
 	  //$OFER[$R2->ID_OFFERS](YEAR)(MONTH)['DISCONNECT']- ile w danym miesiacu bylo zakonczen danej oferty
 	 $OFER[$R2->ID_OFFERS]['TOTAL']['SALE']=$R2->T1_SALE; //- jaka jest wartosc sprzedazy danej oferty
 	 //TODO CUMULATED!
    }

//echo "// sprzedaz ciag dalszy �";
 foreach($OFER as $IND=>$VAL) {
	 $ZAP_SQL="select t4.ID_PROJECT as T4_ID_PROJECT_COST , t4.COST_POWER as T4_COST_POWER
   				from  USERS2_OFFERS as t3
  				  left join USERS2_OFFERS_COSTS as t4 on t3.ID_COSTS_GROUPS=t4.ID_COSTS_GROUPS
  				  where t3.ID='".$IND."' group by t4.ID
					  	 		 "; //TODO  TERMINY
//	echo "786: \n".$ZAP_SQL."\n";
  ZAP_SQL($ZAP_SQL);    flush();
 	 while($R2=mysql_fetch_object($result)) { //tu naliczymy koszty na projekt i sprzedaz na projekt
		 $OFER[$IND]['COST_PER_SVC']+=$R2->T4_COST_POWER ; // jaka jest nominalna wartosc zakupow danej oferty
		 $OFER[$IND]['TOTAL']['ID_PROJECTS'][$R2->T4_ID_PROJECT_COST]['ID_PROJECT_COST']=$R2->T4_COST_POWER*$OFER[$IND]['TOTAL']['COUNT'];

		 //$OFER[$IND]['TOTAL']['POWERCOST']=$R2->T4_COST_POWER*$OFER[$IND]['TOTAL']['COUNT'];
 	 }
 }

//echo "// dalej koszty, tu wyliczymy sprzedaz proporcjonalnie do kosztow z danej sprawy wg rozdzialu wskaznikow kosztow";

  foreach($OFER as $IND=>$VAL) {
	 $ZAP_SQL="select t4.ID_PROJECT as T4_ID_PROJECT_COST , t4.COST_POWER as T4_COST_POWER , t3.ID_COSTS_GROUPS
   				from  USERS2_OFFERS as t3
  				  left join USERS2_OFFERS_COSTS as t4 on t3.ID_COSTS_GROUPS=t4.ID_COSTS_GROUPS
  				  where t3.ID='".$IND." group by t4.ID'
					  	 		 ";
//	echo "804: \n".$ZAP_SQL."\n";
  ZAP_SQL($ZAP_SQL);    flush();
 	 while($R2=mysql_fetch_object($result)) { //tu naliczymy koszty na projekt i sprzedaz na projekt
		 //$OFER[$IND]['COST_PER_SVC']+=$R2->T4_COST_POWER ; // jaka jest nominalna wartosc zakupow danej oferty
		 $OFER[$IND]['TOTAL']['ID_COSTS_GROUPS']=$R2->ID_COSTS_GROUPS ;
		 $OFER[$IND]['TOTAL']['ID_PROJECTS'][$R2->T4_ID_PROJECT_COST]['ID_PROJECT_SELL']=$OFER[$IND]['TOTAL']['SALE']/$OFER[$IND]['COST_PER_SVC']*$R2->T4_COST_POWER;

 	 }
 }

//echo "//teraz tworzymy zmienna \$OFER_TOTAL - zawierajaca wyliczenia z galezi \$OFER";

  foreach($OFER as $IND=>$VAL) {
  		foreach($VAL['TOTAL']['ID_PROJECTS'] as $IND1=>$VAL1) {
  			$OFER_TOTAL['ID_PROJECTS'][$IND1]['ID_PROJECT_COST']+=$VAL1['ID_PROJECT_COST'];
  			$OFER_TOTAL['ID_PROJECTS'][$IND1]['ID_PROJECT_SELL']+=$VAL1['ID_PROJECT_SELL'];
  		}
  }
  foreach($OFER_TOTAL['ID_PROJECTS'] as $IND=>$VAL) {
  		$OFER_TOTAL['TOTAL']['ID_PROJECT_COST']+=$VAL['ID_PROJECT_COST'];
  		$OFER_TOTAL['TOTAL']['ID_PROJECT_SELL']+=$VAL['ID_PROJECT_SELL'];
  }

//echo "
// teraz dokladamy dane z DATA (kosztow projektow) , i naliczamy je ofertom
// bierzemy dane z DATA i dorzucamy je do OFFER_TOTAL";
  foreach($OFER_TOTAL['ID_PROJECTS'] as $IND=>$VAL) {
  	  $OFER_TOTAL['ID_PROJECTS'][$IND]['DATA']['COSTS']=$DATA[$IND]['LOCAL']['COSTS'];
  	  $OFER_TOTAL['ID_PROJECTS'][$IND]['DATA']['CHILD_COSTS']=$DATA[$IND]['CALCULATED']['CHILD_COSTS'];

//  	  $OFER_TOTAL['ID_PROJECTS'][$IND]['DATA']['TOTAL_COSTS']=$OFER_TOTAL['ID_PROJECTS'][$IND]['DATA']['CHILD_COSTS']+$OFER_TOTAL['ID_PROJECTS'][$IND]['DATA']['COSTS'];
  	  $OFER_TOTAL['ID_PROJECTS'][$IND]['DATA']['TOTAL_COSTS']=$DATA[$IND]['CALCULATED']['COST_LOCAL'] + $DATA[$IND]['CALCULATED']['COST_PARENT'];
  }


  foreach($OFER as $IND=>$VAL) {
  		foreach($VAL['TOTAL']['ID_PROJECTS'] as $IND1=>$VAL1) {
			//l1 a teraz wyliczamy jakie % udzialu w koszcie danego projektu stanowi dana oferta ==ID_PROJECT_COST_RATIO
	  		//l1:	echo "\n Wyliczam dla Oferty:".$IND." oraz projektu:".$IND1." , gdzie koszt wyniesie:".$VAL1['ID_PROJECT_COST']."/".$OFER_TOTAL['ID_PROJECTS'][$IND1]['ID_PROJECT_COST']." \n!!";
  			$OFER[$IND]['TOTAL']['ID_PROJECTS'][$IND1]['ID_PROJECT_COST_RATIO']=$VAL1['ID_PROJECT_COST']/$OFER_TOTAL['ID_PROJECTS'][$IND1]['ID_PROJECT_COST'];
			//l2 a teraz wyliczamy $OFER['TOTAL']['CALCULATED__ , jaki jest proporcjonalnie nalezny koszt na usluge, jaki wszedl itp
			$OFER[$IND]['TOTAL']['ID_PROJECTS'][$IND1]['CALCULATED_TOTAL_COSTS']=$OFER[$IND]['TOTAL']['ID_PROJECTS'][$IND1]['ID_PROJECT_COST_RATIO']*$OFER_TOTAL['ID_PROJECTS'][$IND1]['DATA']['TOTAL_COSTS'];
			$OFER[$IND]['TOTAL']['CALCULATED_TOTAL_COSTS']+=$OFER[$IND]['TOTAL']['ID_PROJECTS'][$IND1]['CALCULATED_TOTAL_COSTS'];
  		}
  		// udalo sie wyliczyc realny wskaznik kosztu danej oferty
  		$OFER[$IND]['TOTAL']['CALCULATED_COST_PER_SVC']=$OFER[$IND]['TOTAL']['CALCULATED_TOTAL_COSTS']/$OFER[$IND]['TOTAL']['COUNT'];
  }

//echo "// AD3 c) przemielamy ponownie sprzedaz cala, nanosimy koszty projektom w oparciu o dane realne z offer - mamy DATA[OFER_USED]� -robimy CALCULATED_AD3";

 foreach($DATA as $ID_PROJECT=>$ARRAY) {
 		foreach($ARRAY['OFER_USED'] as $OFER_USED=>$OFER_USED_ARR) {
			$DATA[$ID_PROJECT]['CALCULATED_AD3']['OFERS'][$OFER_USED]['CALCULATED_COST_PER_SVC']+=$OFER_USED_ARR['ILOSC_FAKTUR']*$OFER[$OFER_USED]['TOTAL']['CALCULATED_COST_PER_SVC'];
			$DATA[$ID_PROJECT]['CALCULATED_AD3']['OFERS'][$OFER_USED]['COST_PER_SVC']+=$OFER_USED_ARR['ILOSC_FAKTUR']*$OFER[$OFER_USED]['COST_PER_SVC'];
			if($OFER_USED<1) $DATA[$ID_PROJECT]['CALCULATED_AD3']['OFERS'][$OFER_USED]['ERROR_NO_OFFER_ID']+=1;
 			//['ILOSC_FAKTUR']
 		}

 }

//echo "// AD3c) podsumowujemy DATA[CALCULATED_AD3][OFERS] ";
 	foreach($DATA as $ID_PROJECT=>$ARRAY) {
 	 		foreach($ARRAY['CALCULATED_AD3']['OFERS'] as $CALCULATED_AD3=>$CALCULATED_AD3_ARR) {
 	 			$DATA[$ID_PROJECT]['CALCULATED_AD3']['CALCULATED_COST_PER_SVC']+=$CALCULATED_AD3_ARR['CALCULATED_COST_PER_SVC'];
 	 			$DATA[$ID_PROJECT]['CALCULATED_AD3']['COST_PER_SVC']+=$CALCULATED_AD3_ARR['COST_PER_SVC'];
 	 		}

 	}


//echo "// AD4 - Raport uzytych licencji - idziemy po \$OFER[TOTAL][COUNT] i sumujemy  - potem bedziemy jeszcze sprawdzac z projektami
	  //   ze struktur ofert, co wynikalo z nich do raportowania - po offer_costs.
	  // czytamy strukture ofert ";

	$ZAP_SQL="select * from USERS2_OFFERS_COSTS where A_STATUS!='DELETED' ";
	ZAP_SQL($ZAP_SQL);
	 flush();
	 while($R2=mysql_fetch_object($result)) {
	  $ID_COSTS_GROUPS[$R2->ID_COSTS_GROUPS][$R2->ID_PROJECT]['COST_POWER']=$R2->COST_POWER;
	  $ID_COSTS_GROUPS[$R2->ID_COSTS_GROUPS][$R2->ID_PROJECT]['COST_OFFSET_MONTH_BILLED']=$R2->COST_OFFSET_MONTH_BILLED;
	  $ID_COSTS_GROUPS[$R2->ID_COSTS_GROUPS][$R2->ID_PROJECT]['COST_ACCOUNTED_ON']=$R2->COST_ACCOUNTED_ON;
	 }


// echo "// jedziemy teraz po danych z ID_COST_GROUPS dla ofert, ";
		foreach($DATA as $ID_PROJECT=>$ARRAY){
			foreach($ARRAY['OFER_USED'] as $OFER_USED=>$OFER_USED_ARR) {
						// poznajmy klase ID_COSTS_GROUPS z danych z $OFER[$IND]['TOTAL']['ID_COSTS_GROUPS']
					foreach($ID_COSTS_GROUPS[$OFER[$OFER_USED]['TOTAL']['ID_COSTS_GROUPS']] as $IDCG_I=>$IDCG_A) {
						$DATA[$IDCG_I]['CALCULATED_AD4_TO_RAPORT'][$OFER_USED]['COST_POWER_ILOSC_FAKTUR_'.$IDCG_A['COST_POWER']]+=$OFER_USED_ARR['ILOSC_FAKTUR'];
						$DATA[$IDCG_I]['CALCULATED_AD4_TO_RAPORT'][$OFER_USED]['COST_POWER_ILOSC_POZYCJI_'.$IDCG_A['COST_POWER']]+=$OFER_USED_ARR['ILOSC_POZYCJI'];
					}

			}
		}
	//wydrukujmy dane
	echo "<br>Tabela do raportowania uzyc kosztow oplat \n<table border=1><tr>
	<td>ID Projektu</td><td>OPIS sprawy</td><td>Z jakiej oferty</td><td>Wartosc Stawki naliczonej oplaty</td><td>Ilosc faktur</td></tr>";
	foreach($DATA as $ID_PROJECT=>$ARRAY){
//				if(isset($ARRAY['CALCULATED_AD4_TO_RAPORT'])) echo "<tr>";
					foreach($ARRAY['CALCULATED_AD4_TO_RAPORT'] as $CATR_I=>$CATR_A) {
						 foreach($CATR_A as $CATR_I_1=>$CATR_I_1_A) {
								echo "<tr><td>".$ID_PROJECT."</td><td>".$ARRAY['LOCAL']['M_DIST_DESC'] ."</td><td>".$CATR_I."</td>
								<td>".$CATR_I_1."</td><td>".$CATR_I_1_A."</td></tr>";
				//ad 4b) raport licencji do tabeli RAPORT_PROJECT_COSTS
							 unset($ZAP_SQL); unset($AD4b);
							 if(strstr($CATR_I_1,'COST_POWER_ILOSC_POZYCJI_'))
							 		list(,$AD4b['COST_POWER'])=explode("COST_POWER_ILOSC_POZYCJI_",$CATR_I_1);
							  else
							 		list(,$AD4b['ILOSC_FAKTUR'])=explode("COST_POWER_ILOSC_FAKTUR_",$CATR_I_1);
							 $ZAP_SQL['FIELD'][]='A_STATUS';	 $ZAP_SQL['VALUE'][]="'WAITING'";
							 $ZAP_SQL['FIELD'][]='A_RECORD_CREATE_AUTHOR';	 $ZAP_SQL['VALUE'][]="'".$_SESSION['ADM_ACCOUNT']."'";
							 $ZAP_SQL['FIELD'][]='A_RECORD_CREATE_DATE';	 $ZAP_SQL['VALUE'][]="now()";
							 $ZAP_SQL['FIELD'][]='RPAD_DATA';	 $ZAP_SQL['VALUE'][]="'".$RPAD->DATA."'";
							 $ZAP_SQL['FIELD'][]='ID_PROJECT';	 $ZAP_SQL['VALUE'][]="'".$ID_PROJECT."'";
							// $ZAP_SQL['FIELD'][]='XML';	 $ZAP_SQL['VALUE'][]="'"."'";
							 $ZAP_SQL['FIELD'][]='ID_OFFER';	 $ZAP_SQL['VALUE'][]="'".$CATR_I."'";
							 $ZAP_SQL['FIELD'][]='COST_POWER';	 $ZAP_SQL['VALUE'][]="'".$AD4b['COST_POWER']."'";
							 $ZAP_SQL['FIELD'][]='ILOSC_FAKTUR';	 $ZAP_SQL['VALUE'][]="'".$AD4b['ILOSC_FAKTUR']."'";
							 $ZAP_SQL['FIELD'][]='DATA_COUNT';	 $ZAP_SQL['VALUE'][]="'".$CATR_I_1_A."'";


						 $ZAP_SQL['SQL']="insert into RAPORT_PROJECT_COSTS ( ID ";
						  foreach($ZAP_SQL['FIELD'] as $FIELD) {
						    $ZAP_SQL['SQL'].=",`".$FIELD."`" ;
						  }
						  $ZAP_SQL['SQL'].=" ) values ( '' ";
						  foreach($ZAP_SQL['VALUE'] as $VALUE) {
						    $ZAP_SQL['SQL'].=",".$VALUE ;
						  }
						  $ZAP_SQL['SQL'].=" ) ";
						 // echo $ZAP_SQL['SQL'];
						  ZAP_SQL($ZAP_SQL['SQL']);

							}
					}
	}
	echo "</table>\n";

 echo "<table border=1>";
  echo "<tr><td>1ID_PROJEKT</td><td>2a(ILOSC POWIAZANYCH KOSZTOW OFERT) ZAKUP:SPRZED</td><td>2b (LAST ) </td>
  <td>3[M DIST DESC] REWIR PRZYKLAD (HC+HC CHILDS) </td><td>INWESTYCJE LOCAL+PARENT(Local)</td><td>KOSZT DZIECI</td><td>SPRZED_TOTAL</td><td>SPRZED_LAST_MC</td><td>KLIENTOW</td><td>ZA ILE M-CY ZWROT ( z kosztami uslug)</td><td>I_ZACZETO</td><td>I_ZAKONCZONO</td>
   <td>Koszty Sprzedazy Uslug (planowano)</td><td>OFERT SPRZED [ZAKUP] (err)</td>
  </tr>\n";
 foreach($DATA as $DATA_I=>$DATA_V) {
 //ignorowanie niepotrzebnych projektow



  //TODO ZLE TO LICZY!
  $ROZNICA_SPRZED_TOTAL=$DATA_V['LOCAL']['SPRZED_TOTAL']-$DATA_HIST[$PETLA_AD0['LAST_RPAD_DATA']]['DATA'][$DATA_I]['LOCAL']['SPRZED_TOTAL'] ;
  $KIEDY_ZWROT=( ($DATA_V['CALCULATED']['COST_LOCAL']+$DATA_V['CALCULATED']['COST_PARENT'])-$DATA_V['LOCAL']['SPRZED_TOTAL'])/$ROZNICA_SPRZED_TOTAL; //todo - koszty uslug
  $KIEDY_ZWROT_Z_KOSZT_USL=( ($DATA_V['CALCULATED']['COST_LOCAL']+$DATA_V['CALCULATED']['COST_PARENT'])-$DATA_V['LOCAL']['SPRZED_TOTAL']+$DATA_V['CALCULATED_AD3']['CALCULATED_COST_PER_SVC'])/$ROZNICA_SPRZED_TOTAL; //todo - koszty uslug


 if(
   ($DATA_V['LOCAL']['COSTS']==0)&&
   ($DATA_V['CALCULATED']['COST_LOCAL']==0)&&
   ($DATA_V['CALCULATED']['CHILD_COSTS']==0)&&
   ($DATA_V['CALCULATED']['HC_SUM_CHILD_LOCAL']==0)&&
   ($DATA_V['LOCAL']['HC']<1)
  ) continue;


  echo "<tr><td>".$DATA_I."</td>";//1 col

  //TOTAL (ILOSC POWIAZANYCH KOSZTOW OFERT) ZAKUP:SPRZED
		$KOSZTY_OFERT['ZAKUP']=0;$KOSZTY_OFERT['SPRZEDAZ']=0;
		foreach($DATA_HIST as $DATA_HIST_ARR_I=>$DATA_HIST_ARR_V) {
			$KOSZTY_OFERT['ZAKUP']+=$DATA_HIST_ARR_V['OFER_TOTAL']['ID_PROJECTS'][$DATA_I]['ID_PROJECT_COST'];
			$KOSZTY_OFERT['SPRZEDAZ']+=$DATA_HIST_ARR_V['OFER_TOTAL']['ID_PROJECTS'][$DATA_I]['ID_PROJECT_COST'];
		}

  echo "<td><nobr>".number_format($KOSZTY_OFERT['ZAKUP'], 2, ',', ' ')."</nobr>; <nobr>
   			 ".number_format($KOSZTY_OFERT['SPRZEDAZ'], 2, ',', ' ')."</nobr></td>"; //2col


   echo "<td><nobr>(".$DATA_V['LOCAL']['ILOSC_POWIAZANYCH_KOSZTOW_OFERT'].")</nobr> <nobr>".number_format($OFER_TOTAL['ID_PROJECTS'][$DATA_I]['ID_PROJECT_COST'], 2, ',', ' ')."</nobr>;
   			  <nobr>".number_format($OFER_TOTAL['ID_PROJECTS'][$DATA_I]['ID_PROJECT_SELL'], 2, ',', ' ')."</nobr></td>"; //2col

   echo "<td>[<font color=green>".$DATA_V['LOCAL']['M_DIST_DESC']."</font>]";//3 col

//   .$DATA_V[REWIR]."
		foreach($DATA_V['LOCAL']['M_REWIR'] as $REWIR=>$REWIR_A) {
		  echo $REWIR.", ";
		}
		            //INWESTYCJE: number_format($number, 2, ',', ' ')
   echo "(".$DATA_V['LOCAL']['HC']."+".$DATA_V['CALCULATED']['HC_SUM_CHILD_LOCAL'].") </td>
   <td><nobr>".number_format($DATA_V['CALCULATED']['COST_LOCAL'], 2, ',', ' ')."</nobr>+ <nobr>".number_format($DATA_V['CALCULATED']['COST_PARENT'], 2, ',', ' ')."</nobr>
   (<nobr>".number_format($DATA_V['LOCAL']['COSTS'], 2, ',', ' ')."</nobr>) = <nobr>
   <b>".number_format(($DATA_V['CALCULATED']['COST_LOCAL']+$DATA_V['CALCULATED']['COST_PARENT']), 2, ',', ' ')."</nobr></b></td>
   	 	<td>".$DATA_V['CALCULATED']['CHILD_COSTS']."</td>
   <td>"; //SPRZED_TOTAL
   echo number_format($DATA_V['LOCAL']['SPRZED_TOTAL'], 2, ',', ' ')."</td><td>" ;
       echo number_format($ROZNICA_SPRZED_TOTAL, 2, ',', ' ');

//		if(isset($PETLA_AD0['LAST_RPAD_DATA'])) echo number_format(, 2, ',', ' ') ;
     //.number_format($DATA_V['LOCAL']['SPRZED_LAST_MC'], 2, ',', ' ')."
     echo "</td><td>".
     	"-TODO-</td><td>".number_format($KIEDY_ZWROT, 2, ',', ' ')." <nobr>(".number_format($KIEDY_ZWROT_Z_KOSZT_USL, 2, ',', ' ').")</nobr></td><td>
     	".$DATA_V['LOCAL']['I_ZACZETO']."</td><td>".$DATA_V['LOCAL']['I_ZAKONCZONO']."</td>";
     	//Koszty Sprzedazy Uslug
     	echo "<td><nobr>".number_format($DATA_V['CALCULATED_AD3']['CALCULATED_COST_PER_SVC'], 2, ',', ' ')."</nobr>
     	<nobr> (".number_format($DATA_V['CALCULATED_AD3']['COST_PER_SVC'], 2, ',', ' ').")</nobr></td>";
     	//OFERTY:
     	echo "<td>";
     	 foreach($DATA_V['CALCULATED_AD3']['OFERS'] as $OFERR=>$OFER_A) {
		   if($OFER_A['ERROR_NO_OFFER_ID']) echo "<font color=red>(".$OFER_A['ERROR_NO_OFFER_ID'].")</font> ,";
		   else		  echo $OFERR." , ";
  		 }
  		 //W jakich jest ofertach ?
		 foreach($OFER as $OFER_IND=>$OFER_ARR) {
		 	 foreach($OFER_ARR['TOTAL']['ID_PROJECTS'] as $IDP=>$IDP_V) {
		 	    if($IDP==$DATA_I) echo "[".$OFER_IND."] ";
		 	 }
		 }

     	echo "</td>";
     	echo "</tr>\n";




    // 	 echo "AD -1) b) dodajemy do tabeli RAPORT_CROSS";
			 unset($ZAP_SQL);
			 $ZAP_SQL['FIELD'][]='A_STATUS';	 $ZAP_SQL['VALUE'][]="'WAITING'";
			 $ZAP_SQL['FIELD'][]='A_RECORD_CREATE_AUTHOR';	 $ZAP_SQL['VALUE'][]="'".$_SESSION['ADM_ACCOUNT']."'";
			 $ZAP_SQL['FIELD'][]='A_RECORD_CREATE_DATE';	 $ZAP_SQL['VALUE'][]="now()";
			 $ZAP_SQL['FIELD'][]='RPAD_DATA';	 $ZAP_SQL['VALUE'][]="'".$RPAD->DATA."'";
			 $ZAP_SQL['FIELD'][]='DATA__ID_PROJECT';	 $ZAP_SQL['VALUE'][]="'".$DATA_I."'";
			 $ZAP_SQL['FIELD'][]='DATA__LOCAL__SPRZED_TOTAL';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['LOCAL']['SPRZED_TOTAL']."'";
			 $ZAP_SQL['FIELD'][]='DATA__LOCAL__COSTS';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['LOCAL']['COSTS']."'";
			 $ZAP_SQL['FIELD'][]='DATA__LOCAL__ilosc_faktur';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['LOCAL']['ilosc_faktur']."'";
			 $ZAP_SQL['FIELD'][]='DATA__LOCAL__ILOSC_POZYCJI';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['LOCAL']['ILOSC_POZYCJI']."'";
			 $ZAP_SQL['FIELD'][]='DATA__LOCAL__I_ZACZETO';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['LOCAL']['I_ZACZETO']."'";
			 $ZAP_SQL['FIELD'][]='DATA__LOCAL__I_ZAKONCZONO';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['LOCAL']['I_ZAKONCZONO ']."'";
			 $ZAP_SQL['FIELD'][]='DATA__LOCAL__HC';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['LOCAL']['HC']."'";
			 $ZAP_SQL['FIELD'][]='DATA__LOCAL__ilosc_budynkow';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['LOCAL']['ilosc_budynkow']."'";
			 $ZAP_SQL['FIELD'][]='DATA__LOCAL__np_budynek';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['LOCAL']['np_budynek']."'";
			 $ZAP_SQL['FIELD'][]='DATA__LOCAL__M_REWIR__XML';	 $ZAP_SQL['VALUE'][]="'TODO'";
			 $ZAP_SQL['FIELD'][]='DATA__LOCAL__ILOSC_POWIAZANYCH_KOSZTOW_OFERT';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['LOCAL']['ILOSC_POWIAZANYCH_KOSZTOW_OFERT']."'";
			 $ZAP_SQL['FIELD'][]='DATA__PATH';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['PATH']."'";
			 $ZAP_SQL['FIELD'][]='DATA__PATH_LEN';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['PATH_LEN']."'";
			 $ZAP_SQL['FIELD'][]='DATA__CHILD__XML';	 $ZAP_SQL['VALUE'][]="'".serialize($DATA_V['CHILD'])."'";
			 $ZAP_SQL['FIELD'][]='DATA__CALCULATED__RATIO_LOCAL';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['CALCULATED']['RATIO_LOCAL']."'";
			 $ZAP_SQL['FIELD'][]='DATA__CALCULATED__COST_LOCAL';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['CALCULATED']['COST_LOCAL']."'";
			 $ZAP_SQL['FIELD'][]='DATA__CALCULATED__CHILD_COSTS';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['CALCULATED']['CHILD_COSTS']."'";
			 $ZAP_SQL['FIELD'][]='DATA__CALCULATED__HC_SUM_CHILD_LOCAL';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['CALCULATED']['HC_SUM_CHILD_LOCAL']."'";
			 $ZAP_SQL['FIELD'][]='DATA__CALCULATED__COST_PARENT';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['CALCULATED']['COST_PARENT']."'";
			 $ZAP_SQL['FIELD'][]='DATA__CALCULATED_AD3__OFERS__XML';	 $ZAP_SQL['VALUE'][]="'".serialize($DATA_V['CALCULATED_AD3']['OFER'])."'";

			 $ZAP_SQL['FIELD'][]='DATA__CALCULATED_AD3__CALCULATED_COST_PER_SVC';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['CALCULATED_AD3']['CALCULATED_COST_PER_SVC']."'";
			 $ZAP_SQL['FIELD'][]='DATA__CALCULATED_AD3__COST_PER_SVC';	 $ZAP_SQL['VALUE'][]="'".$DATA_V['CALCULATED_AD3']['COST_PER_SVC']."'";
			 $ZAP_SQL['FIELD'][]='DATA__CALCULATED_AD4_TO_RAPORT__XML';	 $ZAP_SQL['VALUE'][]="'".serialize($DATA_V['CALCULATED_AD4_TO_RAPORT'])."'";
			 $ZAP_SQL['FIELD'][]='ROZNICA_SPRZED_TOTAL';	 $ZAP_SQL['VALUE'][]="'".$ROZNICA_SPRZED_TOTAL."'";
			 $ZAP_SQL['FIELD'][]='KIEDY_ZWROT';	 $ZAP_SQL['VALUE'][]="'".$KIEDY_ZWROT."'";
			 $ZAP_SQL['FIELD'][]='KIEDY_ZWROT_Z_KOSZT_USL';	 $ZAP_SQL['VALUE'][]="'".$KIEDY_ZWROT_Z_KOSZT_USL."'";

			 //$ZAP_SQL['FIELD'][]='XML';	 $ZAP_SQL['VALUE'][]="'".serialize($DATA_V)."'";


			 $ZAP_SQL['SQL']="insert into RAPORT_CROSS ( ID ";
			  foreach($ZAP_SQL['FIELD'] as $FIELD) {
			    $ZAP_SQL['SQL'].=",`".$FIELD."`" ;
			  }
			  $ZAP_SQL['SQL'].=" ) values ( '' ";
			  foreach($ZAP_SQL['VALUE'] as $VALUE) {
			    $ZAP_SQL['SQL'].=",".$VALUE ;
			  }
			  $ZAP_SQL['SQL'].=" ) ";

			  ZAP_SQL($ZAP_SQL['SQL']);
		 //EOF AD -1 b)





 } //eof FOREACH
 echo "</table>";





			$DATA_HIST[$RPAD->DATA]['DATA']=$DATA;
			$DATA_HIST[$RPAD->DATA]['OFER']=$OFER;
			$DATA_HIST[$RPAD->DATA]['OFER_TOTAL']=$OFER_TOTAL;
			$DATA_HIST[$RPAD->DATA]['DATA_R']=$DATA_R; //rewir historia
			$DATA_HIST[$RPAD->DATA]['DATA_SORT']=$DATA_SORT; //rewir historia


//echo "// 	c) na koncu robimy insert into RAPORT_XML przy resetowaniu - linia ok 13xx ";
			 unset($ZAP_SQL);
			 $ZAP_SQL['FIELD'][]='A_STATUS';	 $ZAP_SQL['VALUE'][]="'WAITING'";
			 $ZAP_SQL['FIELD'][]='A_RECORD_CREATE_AUTHOR';	 $ZAP_SQL['VALUE'][]="'".$_SESSION['ADM_ACCOUNT']."'";
			 $ZAP_SQL['FIELD'][]='A_RECORD_CREATE_DATE';	 $ZAP_SQL['VALUE'][]="now()";
			 $ZAP_SQL['FIELD'][]='RPAD_DATA';	 $ZAP_SQL['VALUE'][]="'".$RPAD->DATA."'";
			 $ZAP_SQL['FIELD'][]='XML';	 $ZAP_SQL['VALUE'][]="'".serialize($DATA_HIST[$RPAD->DATA])."'";
			 $ZAP_SQL['FIELD'][]='LAST_RPAD_DATA'; $ZAP_SQL['VALUE'][]="'".$PETLA_AD0['LAST_RPAD_DATA']."'";
			/* @2018-03 nie chodzi - raczej nie potrzebne?
				$ZAP_SQL['SQL']="insert into RAPORT_CROSS_XML ( ID ";
			  foreach($ZAP_SQL['FIELD'] as $FIELD) {
			    $ZAP_SQL['SQL'].=",`".$FIELD."`" ;
			  }
			  $ZAP_SQL['SQL'].=" ) values ( '' ";
			  foreach($ZAP_SQL['VALUE'] as $VALUE) {
			    $ZAP_SQL['SQL'].=",".$VALUE ;
			  }
			  $ZAP_SQL['SQL'].=" ) ";

			  ZAP_SQL($ZAP_SQL['SQL']);
			 */
 echo "			// AD 0 b 2b  - TODO zmienna struktura kosztow projektow - nowe mieszkania/zasoby sprzedazy";
		//	unset($DATA);
		unset($DATA_R);
		unset($OFER); //to mozna kasowac, bo latwo wyliczyc sume sprzedazy itp - w przeciwienstwie do $DATA!
		unset($OFER_TOTAL); //to trzeba skasowac, bo jest wyliczeniem dla danego okresu
			if($_GET['RAPORT_AFTER_TABLE']) { echo "<br> chce wydrukowac raport line 1261 dla CUR_RPAD_DATA: ".$RPAD->DATA;
				print_r($_GET);
				echo "<br> Robie print_r Line 1262";
				print_r($DATA_HIST[$RPAD->DATA]['DATA'][129]);
				print_r($DATA_HIST[$RPAD->DATA]['DATA'][326]);
				print_r($DATA_HIST[$RPAD->DATA]['DATA'][492]);


			}
//print_r($DATA_HIST[$PETLA_AD0['LAST_RPAD_DATA']]['DATA'][129]);

			$PETLA_AD0['LAST_RPAD_DATA']=$RPAD->DATA ;  //do uzycia PRZYROSTOW_Z_OSTATNIEGO dla WARTOSCI/PARAMETROW
			if($PETLA_AD0['LAST_LAST_RPAD_DATA']>0) unset($DATA_HIST[$PETLA_AD0['LAST_LAST_RPAD_DATA']]); //TODO TEST IT
			$PETLA_AD0['LAST_LAST_RPAD_DATA']=$PETLA_AD0['LAST_RPAD_DATA'] ;  //mozliwe unsetniecie


		} // EOF AD0 b) , jak chcemy wylaczyc petle lat, to trzeba wyremowac AD0 b) nizej na lini...

//print_r($DATA_HIST[$PETLA_AD0['LAST_RPAD_DATA']]);



echo "Problemy do przyporz�dkowania : \n
";

$ZAP_SQL="select t1.ID_SERVICES as ID_SERVICES ,
	t2.T_NETWORK_SERVER , t3.M_REWIR , if(isnull(t4.ID_KONTO_KSIEG),'BRAK',t4.ID_KONTO_KSIEG) as ID_KONTO_KSIEG
	from BILLS_FVAT_POS as t1
	left join SES_USERS2_A as t2 on t1.ID_SERVICES=t2.ID_SERVICES
        left join USERS2_MARKETING as t3 on t2.S_ADDRESS_STREET=t3.S_ADDRESS_STREET
	left join M_REWIR_INWESTYCJA as t4 on t3.M_REWIR=t4.M_REWIR
	left join SES_TV_A as t5 on t1.ID_SERVICES=t5.ID_SERVICES
        where t1.ID_SERVICES > 0  and ( t2.S_ADDRESS_STREET is NULL or t3.M_REWIR is NULL  ) and month(t1.DATE_FROM)=month(now())
	 and t5.ID is NULL and t1.id_list_services!='12'
	group by t1.ID_SERVICES
	 limit 333; ";

  ZAP_SQL("$ZAP_SQL");
           while($DWA=mysql_fetch_array($result)) {
       //         print_r($DWA);
           }


echo "</pre>";
//echo "</table>";

} //EOF IF




if($_GET[KSIEG_DOKUMENTY_ANALIZA]) {
echo "KSIEG_DOKUMENTY_ANALIZA <form  method=\"GET\">"; //action=$PHP_SELF
echo "<input type=hidden name=ADD value=ADD>";
echo "<input type=hidden name=KSIEG_DOKUMENTY_ANALIZA value=1>";
echo "<table border=1><tr><td>";
echo "Podaj kryteria</td><td>  <input type=text name=DATA_DOK size=3 value=$_GET[DATA_DOK]></td></tr>";
echo "<tr><td colspan=1><input type=submit name=ADD value=SZUKAJ></td><td>MIESIAC</td><td>TYP_DOK</td><td>BUDZET</td><td>FIRMA</td><td>ILOSC</td><td>CENA</td><td>ILOSC</td><td>WARTOS</td><td>ZRODLO</td><td>BILANS</td><td>BILANS_CALK</td></tr>";

if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else // before 2018-03 ZAP_SQL("select YEAR(DATA_DOK) as ROK, MONTH(DATA_DOK) as MIESIAC,ID_KONTO_KSIEG,TYP_DOKUMENTU,ID_BUDZET,A_ADM_COMPANY,count(ID) ILOSC ,max(CENA_JEDN_NETTO) as CENA_JEDN_NETTO , sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC,
//if(ID_KONTO_KSIEG like '5__-01%' or ID_KONTO_KSIEG like '5__-02%','AMORTYZACJA',if(ID_KONTO_KSIEG like '201-%','PRZYCHOD',if(ID_KONTO_KSIEG like '080-%','INWESTYCJE',if(ID_BUDZET like 'WYNAGRODZENIA' or ID_BUDZET like 'ZAKUP-LACZY','STALE','KOSZTY/INNE')))) as TYP
//from
//KSIEG_DOKUMENTY where A_STATUS='NORMAL' and ID_KONTO_KSIEG not like '5%-01%' and DATA_DOK like '".$_GET[DATA_DOK]."'
//group by YEAR(DATA_DOK),month(DATA_DOK),TYP_DOKUMENTU,ID_BUDZET,TYP
//order by DATA_DOK;
//");
die('TODO KSIEG_DOKUMENTY to IN7_DZIENNIK_KORESP');

ZAP_SQL("select YEAR(K_DATA_OTRZYMANEJ_KORESP) as ROK, MONTH(K_DATA_OTRZYMANEJ_KORESP) as MIESIAC,ID_KONTO_KSIEG,TYP_DOKUMENTU,ID_BUDZET,A_ADM_COMPANY,count(ID) ILOSC ,max(CENA_JEDN_NETTO) as CENA_JEDN_NETTO , sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC,
if(ID_KONTO_KSIEG like '5__-01%' or ID_KONTO_KSIEG like '5__-02%','AMORTYZACJA',if(ID_KONTO_KSIEG like '201-%','PRZYCHOD',if(ID_KONTO_KSIEG like '080-%','INWESTYCJE',if(ID_BUDZET like 'WYNAGRODZENIA' or ID_BUDZET like 'ZAKUP-LACZY','STALE','KOSZTY/INNE')))) as TYP
from
KSIEG_DOKUMENTY where A_STATUS='NORMAL' and ID_KONTO_KSIEG not like '5%-01%' and DATA_DOK like '".$_GET[DATA_DOK]."'
group by YEAR(DATA_DOK),month(DATA_DOK),TYP_DOKUMENTU,ID_BUDZET,TYP
order by DATA_DOK;
");



$KOSZTA_INNE=0;
$KOSZTA_INNE_CALK=0;

$STALE=0;
$STALE_CALK=0;

$INWESTYCJE=0;
$INWESTYCJE_CALK=0;

$PRZYCHOD=0;
$PRZYCHOD_CALK=0;

$AMORTYZACJA=0;
$AMORTYZACJA_CALK=0;




$BALANS=0;





$DATER="START";

while($DWA=mysql_fetch_array($result)) {

$CDATER=$DWA[0]."-".$DWA[1];




if(($DATER!=$CDATER)) {

$KOSZTA_INNE_WIDTH=$KOSZTA_INNE/1000;
$KOSZTA_INNE_CALK_WIDTH=$KOSZTA_INNE_CALK/1000;
$STALE_WIDTH=$STALE/1000;
$STALE_CALK_WIDTH=$STALE_CALK/1000;
$INWESTYCJE_WIDTH=$INWESTYCJE/1000;
$INWESTYCJE_CALK_WIDTH=$INWESTYCJE_CALK/1000;
$PRZYCHOD_WIDTH=$PRZYCHOD/1000;
$PRZYCHOD_CALK_WIDTH=$PRZYCHOD_CALK/1000;


$BALANS_CALK=$PRZYCHOD_CALK-$KOSZTA_INNE_CALK-$INWESTYCJE_CALK-$STALE_CALK;
$BALANS=$PRZYCHOD-$KOSZTA_INNE-$INWESTYCJE-$STALE;

$BALANS_WIDTH=abs($PRZYCHOD/1000);
if($BALANS>0) $BALANS_ALIGN="left"; else $BALANS_ALIGN="left";
if($BALANS>0) $BALANS_COLOR="green"; else $BALANS_COLOR="red";

$BALANS_CALK_WIDTH=abs($BALANS_CALK/1000);
if($BALANS_CALK>0) $BALANS_CALK_ALIGN="left"; else $BALANS_CALK_ALIGN="left";
if($BALANS_CALK>0) $BALANS_CALK_COLOR="green"; else $BALANS_CALK_COLOR="red";



echo "<tr><td colspan=8>
<table width=100% cellpadding=0 cellspacing=0>
<tr><td align=left><hr width=$KOSZTA_INNE_WIDTH color=red></td></tr>
";
//<tr><td align=left><hr width=$KOSZTA_INNE_CALK_WIDTH color=red></td></tr>
echo "</table></td>
<td>SUMER</td><td>KOSZTY/INNE</td><td>$KOSZTA_INNE</td><td>$KOSZTA_INNE_CALK</td></tr>\n";

echo "<tr><td colspan=8>
<table width=100% cellpadding=0 cellspacing=0>
<tr><td align=left><hr width=$STALE_WIDTH color=pink></td></tr>
";
//<tr><td align=left><hr width=$STALE_CALK_WIDTH color=magneta></td></tr>
echo "</table>
</td><td>SUMER</td><td>STALE</td><td>$STALE</td><td>$STALE_CALK</td></tr>\n";
echo "<tr><td colspan=8>
<table width=100% cellpadding=0 cellspacing=0>
<tr><td align=left><hr width=$INWESTYCJE_WIDTH color=pink></td></tr>
";
//<tr><td align=left><hr width=$INWESTYCJE_CALK_WIDTH color=magneta></td></tr>
echo "</table>
</td><td>SUMER</td><td>INWESTYCJE</td><td>$INWESTYCJE</td><td>$INWESTYCJE_CALK</td></tr>\n";
echo "<tr><td colspan=8>
<table width=100% cellpadding=0 cellspacing=0>
<tr><td align=left><hr width=$PRZYCHOD_WIDTH color=green></td></tr>
";
//<tr><td align=left><hr width=$PRZYCHOD_CALK_WIDTH color=green></td></tr>
echo "</table></td><td>SUMER</td><td>PRZYCHOD</td><td>$PRZYCHOD</td><td>$PRZYCHOD_CALK</td></tr>\n";
echo "<tr><td colspan=8>
<table width=100% cellpadding=0 cellspacing=0>
<tr><td align=$BALANS_ALIGN><hr width=$BALANS_WIDTH color=$BALANS_COLOR></td></tr>
<tr><td align=$BALANS_CALK_ALIGN><hr width=$BALANS_CALK_WIDTH color=$BALANS_CALK_COLOR></td></tr>
</table>
</td><td>SUMER ALL DO
KUPY</td><td>BALANS</td><td>$BALANS</td><td>$BALANS_CALK</td></tr>\n";
echo "<tr><td colspan=12> - - - - - </td></tr>\n";

$KOSZTA_INNE=0;
$STALE=0;
$INWESTYCJE=0;
$PRZYCHOD=0;

}

//$ZMIENNA="2.2"+"1.1";

echo "<tr><td>$DWA[0]</td><td>".$DWA[1]."</td><td>".$DWA[2]."</td><td>".$DWA[3]." ";
echo "</td><td>$DWA[4]</td><td>$DWA[5]</td><td>".$DWA[6]."</td><td>".$DWA[7]."</td><td>".$DWA[8]."</td><td>".$DWA[9]."</td></tr>";


if($DWA[TYP]=="KOSZTY/INNE") {
$KOSZTA_INNE+=$DWA[8];
$KOSZTA_INNE_CALK+=$DWA[8];
} else if ($DWA[TYP]=="INWESTYCJE") {
$INWESTYCJE+=$DWA[8];
$INWESTYCJE_CALK+=$DWA[8];
} else if ($DWA[TYP]=="STALE") {
$STALE+=$DWA[8];
$STALE_CALK+=$DWA[8];
} else if ($DWA[TYP]=="PRZYCHOD") {
$PRZYCHOD+=$DWA[8];
$PRZYCHOD_CALK+=$DWA[8];
}  else if ($DWA[TYP]=="AMORTYZACJA") {
$AMORTYZACJA+=$DWA[8];
$AMORTYZACJA_CALK+=$DWA[8];
}


$DATER=$DWA[0]."-".$DWA[1];

 }

echo "<tr><td colspan=8>
<table width=100% cellpadding=0 cellspacing=0>
<tr><td align=$BALANS_ALIGN><hr width=$BALANS_WIDTH color=#CCCCCC></td></tr>
<tr><td align=$BALANS_CALK_ALIGN><hr width=$BALANS_CALK_WIDTH color=green></td></tr>
</table>
</td><td>SUMER ALL DO
KUPY</td><td>BALANS</td><td>$BALANS</td><td>$BALANS_CALK</td></tr>\n";
echo "</table>";

echo "END";

} //EOF IF




if($_GET[KSIEG_DOKUMENTY_ANALIZA_KONTA]) {
echo "KSIEG_DOKUMENTY_ANALIZA <form  method=\"GET\">"; //action=$PHP_SELF
echo "<input type=hidden name=ADD value=ADD>";
echo "<input type=hidden name=KSIEG_DOKUMENTY_ANALIZA_KONTA value=1>";
echo "<table border=1><tr>";
echo "<td>Podaj kryteria data MIN od ktorej nalezy liczyc</td><td>  <input type=text name=DATA_DOK_MIN size=3 value=".$_GET[DATA_DOK_MIN]."></td>";
echo "<td>Podaj kryteria data MAX do ktorej nalezy liczyc</td><td>  <input type=text name=DATA_DOK_MAX size=3 value=".$_GET[DATA_DOK_MAX]."></td>";
echo "<td>Podaj konta ksiegowe w % </td><td>  <input type=text name=ID_KONTO_KSIEG size=3 value=".$_GET[ID_KONTO_KSIEG]."></td>";
echo "</tr>";
echo "<tr><td colspan=1><input type=submit name=ADD value=SZUKAJ></td><td>KONTO</td><td>ROK</td><td>MIESIAC</td><td>ILOSC</td><td>WARTOS</td></tr>";

die('todo change to IN7_DZIENNIK_KORESP @2018-03');
if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL("select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-',month(DATA_DOK)) as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC
	from  KSIEG_DOKUMENTY where A_STATUS='NORMAL' and TYP_DOKUMENTU='DOKUMENT' and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."' and
	 COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
   and COALESCE(unix_timestamp(DATA_DOK), 0) > COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
	group by ID_KONTO_KSIEG,YEAR(DATA_DOK),month(DATA_DOK) order by ID_KONTO_KSIEG,DATA_DOK;");
$I=1;
while ($DWA=mysql_fetch_array($result)) {

  list($KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],2);
//   if($KONTO_GRUPA=="080")   list($KONTO_GRUPA)=split(",",$DWA[ID_KONTO_KSIEG],2);

//   $DATA["$KONTO_GRUPA"]["DATA"]=$DWA[DATA];
   $DATA["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];
   $DATA["ALL_SUMA"][WARTOSC_TOT]+=$DWA[WARTOSC];
//  echo "\n<tr><td>".$I++."</td><td>$DWA[0]</td> <td>$DWA[1]</td><td>$DWA[2]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td>$KONTO_GRUPA</td></tr>";
 }

 foreach($DATA as $KONTO_I=>$KONTO_V) {

  foreach($KONTO_V as $DATA_I=>$DATA_V) {
  if($DATA_I!="WARTOSC_TOT")
   echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
    echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>$KONTO_V[WARTOSC_TOT]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
 }

unset($DATA);
echo "</table><hr>MIESIECZNIE SYNTETYCZNIE zespol 80<table border=2>";
die('todo change to IN7_DZIENNIK_KORESP @2018-03');
if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL("select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-',month(DATA_DOK)) as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC
  from  KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and TYP_DOKUMENTU='DOKUMENT'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) > COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
    and ID_KONTO_KSIEG like '080-%'
  group by ID_KONTO_KSIEG,YEAR(DATA_DOK),month(DATA_DOK)
  order by ID_KONTO_KSIEG,DATA_DOK;
");
$I=1;
while ($DWA=mysql_fetch_array($result)) {

  list($KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],2);
   if($KONTO_GRUPA=="080")   list($KONTO_GRUPA)=split(",",$DWA[ID_KONTO_KSIEG],2);

//   $DATA["$KONTO_GRUPA"]["DATA"]=$DWA[DATA];
   $DATA["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];
   $DATA["ALL_SUMA"][WARTOSC_TOT]+=$DWA[WARTOSC];

//  echo "\n<tr><td>".$I++."</td><td>$DWA[0]</td> <td>$DWA[1]</td><td>$DWA[2]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td>$KONTO_GRUPA</td></tr>";
 }

 foreach($DATA as $KONTO_I=>$KONTO_V) {

  foreach($KONTO_V as $DATA_I=>$DATA_V) {
  if($DATA_I!="WARTOSC_TOT")
   echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
    echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>$KONTO_V[WARTOSC_TOT]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
 }

unset($DATA);
echo "</table><hr>MIESIECZNIE SYNTETYCZNIE zespol 139<table border=2>";
die('todo change to IN7_DZIENNIK_KORESP @2018-03');
if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL("select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-',month(DATA_DOK)) as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC
  from  KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and TYP_DOKUMENTU='DOKUMENT'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) > COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
    and ID_KONTO_KSIEG like '139-%'
  group by ID_KONTO_KSIEG,YEAR(DATA_DOK),month(DATA_DOK)
  order by ID_KONTO_KSIEG,DATA_DOK;
");
$I=1;
while ($DWA=mysql_fetch_array($result)) {

  list($KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],2);
   if($KONTO_GRUPA=="139")   list($KONTO_GRUPA)=split(",",$DWA[ID_KONTO_KSIEG],2);

//   $DATA["$KONTO_GRUPA"]["DATA"]=$DWA[DATA];
   $DATA["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];
   $DATA["ALL_SUMA"][WARTOSC_TOT]+=$DWA[WARTOSC];

//  echo "\n<tr><td>".$I++."</td><td>$DWA[0]</td> <td>$DWA[1]</td><td>$DWA[2]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td>$KONTO_GRUPA</td></tr>";
 }

 foreach($DATA as $KONTO_I=>$KONTO_V) {

  foreach($KONTO_V as $DATA_I=>$DATA_V) {
  if($DATA_I!="WARTOSC_TOT")
   echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
    echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>$KONTO_V[WARTOSC_TOT]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
 }

unset($DATA);
echo "</table><hr>MIESIECZNIE SYNTETYCZNIE zespol 221<table border=2>";
die('TODO change to IN7_DZIENNIK_KORESP @2018-03');
if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL("select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-',month(DATA_DOK)) as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC
  from KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and TYP_DOKUMENTU='DOKUMENT'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) > COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
    and ID_KONTO_KSIEG like '221-%'
  group by ID_KONTO_KSIEG,YEAR(DATA_DOK),month(DATA_DOK)
  order by ID_KONTO_KSIEG,DATA_DOK;
");
$I=1;
while ($DWA=mysql_fetch_array($result)) {

  list($KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],2);
   if($KONTO_GRUPA=="221")   list($KONTO_GRUPA)=split(",",$DWA[ID_KONTO_KSIEG],2);

//   $DATA["$KONTO_GRUPA"]["DATA"]=$DWA[DATA];
   $DATA["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];
   $DATA["ALL_SUMA"][WARTOSC_TOT]+=$DWA[WARTOSC];

//  echo "\n<tr><td>".$I++."</td><td>$DWA[0]</td> <td>$DWA[1]</td><td>$DWA[2]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td>$KONTO_GRUPA</td></tr>";
 }

 foreach($DATA as $KONTO_I=>$KONTO_V) {

  foreach($KONTO_V as $DATA_I=>$DATA_V) {
  if($DATA_I!="WARTOSC_TOT")
   echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
    echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>$KONTO_V[WARTOSC_TOT]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
 }


//echo "</table>";

unset($DATA);
echo "</table><hr>ROCZNIE ZESPOLY/SYNTETYCZNIE<br><table border=2>";
die('TODO change to IN7_DZIENNIK_KORESP @2018-03');

if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL("select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-') as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC
  from  KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) > COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
    and TYP_DOKUMENTU='DOKUMENT'
    and ID_KONTO_KSIEG like '080-%'
  group by ID_KONTO_KSIEG,YEAR(DATA_DOK)
  order by ID_KONTO_KSIEG,DATA_DOK;
");
$I=1;
while ($DWA=mysql_fetch_array($result)) {

  list($KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],2);
   if($KONTO_GRUPA=="080")   list($KONTO_GRUPA)=split(",",$DWA[ID_KONTO_KSIEG],2);

//   $DATA["$KONTO_GRUPA"]["DATA"]=$DWA[DATA];
   $DATA["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];
//  echo "\n<tr><td>".$I++."</td><td>$DWA[0]</td> <td>$DWA[1]</td><td>$DWA[2]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td>$KONTO_GRUPA</td></tr>";
 }

 foreach($DATA as $KONTO_I=>$KONTO_V) {

  foreach($KONTO_V as $DATA_I=>$DATA_V) {
  if($DATA_I!="WARTOSC_TOT")
   echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
    echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>$KONTO_V[WARTOSC_TOT]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
 }

echo "</table>";


unset($DATA);
echo "</table><hr>ROCZNIE_ZESPOLY<br><table border=2>";
die('TODO change to IN7_DZIENNIK_KORESP @2018-03');

if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL("select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-') as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC
  from  KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) > COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
    and TYP_DOKUMENTU='DOKUMENT'
  group by ID_KONTO_KSIEG,YEAR(DATA_DOK)
  order by ID_KONTO_KSIEG,DATA_DOK;
");
$I=1;
while ($DWA=mysql_fetch_array($result)) {

  list($KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],2);
//   if($KONTO_GRUPA=="080")   list($KONTO_GRUPA)=split(",",$DWA[ID_KONTO_KSIEG],2);

//   $DATA["$KONTO_GRUPA"]["DATA"]=$DWA[DATA];
   $DATA["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];
//  echo "\n<tr><td>".$I++."</td><td>$DWA[0]</td> <td>$DWA[1]</td><td>$DWA[2]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td>$KONTO_GRUPA</td></tr>";
 }

 foreach($DATA as $KONTO_I=>$KONTO_V) {

  foreach($KONTO_V as $DATA_I=>$DATA_V) {
  if($DATA_I!="WARTOSC_TOT")
   echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
    echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>$KONTO_V[WARTOSC_TOT]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
 }

echo "</table>";


unset($DATA);
die('TODO change to IN7_DZIENNIK_KORESP @2018-03');

$ZAP_SQL="select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-') as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC
  from  KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) > COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
    and ID_KONTO_KSIEG like '5%'
    and TYP_DOKUMENTU='DOKUMENT'
  group by ID_KONTO_KSIEG
  order by ID_KONTO_KSIEG,year(DATA_DOK)
";
echo "</table><hr>ZESPOLY 5XX- wg rodzajow <br> $ZAP_SQL <table border=2>";



if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL($ZAP_SQL);
$I=1;
while ($DWA=mysql_fetch_array($result)) {

  list(,$KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],3);
   	settype($KONTO_GRUPA, "string");
	$KONTO_GRUPA=$KONTO_GRUPA[0].$KONTO_GRUPA[1];

   $DATA["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];

 }

 foreach($DATA as $KONTO_I=>$KONTO_V) {

  foreach($KONTO_V as $DATA_I=>$DATA_V) {
  if($DATA_I!="WARTOSC_TOT")
   echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
    echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>$KONTO_V[WARTOSC_TOT]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
 }

echo "</table>";


unset($DATA);
die('TODO change to IN7_DZIENNIK_KORESP @2018-03');

$ZAP_SQL="select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-') as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC , ID_BUDZET
  from  KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) >= COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
    and ID_KONTO_KSIEG like '%'
    and  ID_KONTO_KSIEG not like 'xxx'
    and TYP_DOKUMENTU='DOKUMENT'
  group by ID_KONTO_KSIEG,ID_BUDZET
  order by ID_KONTO_KSIEG,year(DATA_DOK)
";
echo "</table><hr>ROZLICZNIE BUDZETOW wg rodzajow <br> $ZAP_SQL <table border=2>";



if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL($ZAP_SQL);
$I=1;

$DATA["MARKETING-STALY"]=array();
$DATA["MARKETING-DZIALANIA"]=array();

while ($DWA=mysql_fetch_array($result)) {

  list(,$KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],3);
   	settype($KONTO_GRUPA, "string");
	$KONTO_GRUPA=$KONTO_GRUPA[0].$KONTO_GRUPA[1];


      if(strstr($DWA[ID_KONTO_KSIEG],"201-")&&($DWA[WARTOSC]>"0")) $DWA[ID_BUDZET]="BUDZET_PRZYCHOD";
   else   if(strstr($DWA[ID_KONTO_KSIEG],"999-")&&($DWA[WARTOSC]>"0")) $DWA[ID_BUDZET]="BUDZET_PLUS";
   else   if(strstr($DWA[ID_KONTO_KSIEG],"999-")&&($DWA[WARTOSC]<"0")) {
    $DWA[ID_BUDZET]="BUDZET_MINUS_"."$DWA[ID_BUDZET]";
    $DATA["BUDZET_MINUS"]["WARTOSC_TOT"] += $DWA[WARTOSC];
    $DATA["BUDZET_MINUS"]["$KONTO_GRUPA"][$DWA[DATA]] += $DWA[WARTOSC];
    $DATA["BUDZET_MINUS"]["$KONTO_GRUPA"][WARTOSC_TOT] += $DWA[WARTOSC];
    $DATA["BUDZET_MINUS"][WARTOSC_TOT][$DWA[DATA]] += $DWA[WARTOSC];

   } else if(ereg("^5",$DWA[ID_KONTO_KSIEG]) && ereg("-01",$DWA[ID_KONTO_KSIEG]) ) {
     echo "AMORTY";
     $DWA[ID_BUDZET]="AMORTYZACJA";
   } if(strstr($DWA[ID_KONTO_KSIEG],"220-40")) $DWA[ID_BUDZET]="VAT-NALEZNY";
   else  if(strstr($DWA[ID_KONTO_KSIEG],"221-00")) $DWA[ID_BUDZET]="PODATKI";
   $DATA[$DWA[ID_BUDZET]]["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA[$DWA[ID_BUDZET]]["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];
   $DATA[$DWA[ID_BUDZET]][WARTOSC_TOT]+=$DWA[WARTOSC];

 }


//print_r($DATA);


 foreach($DATA as $BUDZET_I=>$DDATA) {
  foreach($DDATA as $KONTO_I=>$KONTO_V) {

   foreach($KONTO_V as $DATA_I=>$DATA_V) {
    if($DATA_I!="WARTOSC_TOT")
    echo "\n<tr><td>".$I++."</td><td>$BUDZET_I $KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
    else $BDATA+=$DATA_V;
   }
     echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>". $KONTO_V[WARTOSC_TOT]."</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
//    $BDATA-=$DATA_V;
     echo "\n<tr><td>".$I++."</td><td>$BUDZET_I <hr></td> <td>  WARTOSC_TOT_A <hr> </td><td>$BDATA <hr></td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
	$DATA[$BUDZET_I]["WARTOSC_TOT_A"]=$BDATA;
     unset($BDATA);
 }
echo "</table>";


echo "<br> PODSUMOWANIE DYSPOZYCJI BUDZETU";

 echo "<table border=1><tr><td>KOMORKA ORGANIZACYJNA</td><td>PRZYZNANY BUDZET</td><td>WYKORZYSTANY BUDZET</td><td>POZOSTALO DO WYKORZYSTANIA</td></tr>";

 foreach($DATA as $BUDZET_I=>$DDATA) {
  if(!strstr("$BUDZET_I","BUDZET")) {

  echo "<tr><td>$BUDZET_I</td><td>".$DATA["BUDZET_MINUS_".$BUDZET_I][WARTOSC_TOT_A]."</td><td>".$DATA[$BUDZET_I]["WARTOSC_TOT"]."</td>";

	$DO_WYKORZYSTANIA=$DATA["BUDZET_MINUS_".$BUDZET_I]["WARTOSC_TOT"]+$DATA[$BUDZET_I]["WARTOSC_TOT"];
	if($DO_WYKORZYSTANIA>=0) $COLOR="bgcolor=red"; else $COLOR="";
  echo "<td $COLOR>".$DO_WYKORZYSTANIA."</td></tr>";
       $BUDZET_WYKORZYSTANO+=$DATA[$BUDZET_I]["WARTOSC_TOT_A"];
       $BUDZET_PRZYZNANO+=$DATA["BUDZET_MINUS_".$BUDZET_I]["WARTOSC_TOT_A"];
  } else   if(strstr("$BUDZET_I","BUDZET_PLUS")) {
  }




 }
        $BUDZET_WYKORZYSTANO-=$DATA["AMORTYZACJA"]["WARTOSC_TOT_A"];
      $BUDZET_WYKORZYSTANO-=$DATA["VAT-NALEZNY"]["WARTOSC_TOT_A"];
      $BUDZET_WYKORZYSTANO-=$DATA["PODATKI"]["WARTOSC_TOT_A"];
      if(-$BUDZET_PRZYZNANO-$BUDZET_WYKORZYSTANO<0) $COLOR="bgcolor=red"; else $COLOR="";
echo "<tr><td>BUDZET/ Wykorzystanie</td><td>$BUDZET_PRZYZNANO</td><td>$BUDZET_WYKORZYSTANO</td><td $COLOR>".(-$BUDZET_PRZYZNANO-$BUDZET_WYKORZYSTANO)."</td></tr>";
      if($DATA[BUDZET_PLUS][WARTOSC_TOT_A]+$DATA[BUDZET_MINUS][WARTOSC_TOT_A]<0) $COLOR="bgcolor=red"; else $COLOR="";
echo "<tr><td>BUDZET/DYSPOZYCJE</td><td>".$DATA[BUDZET_PLUS][WARTOSC_TOT_A]."</td><td>".$DATA[BUDZET_MINUS][WARTOSC_TOT_A]."</td><td $COLOR>".($DATA[BUDZET_PLUS][WARTOSC_TOT_A]+$DATA[BUDZET_MINUS][WARTOSC_TOT_A])."</td></tr>";
      if($DATA[BUDZET_PLUS][WARTOSC_TOT_A]>$DATA[BUDZET_PRZYCHOD][WARTOSC_TOT_A]) $COLOR="bgcolor=red"; else $COLOR="";
echo "<tr><td>PRZYCHOD/BUDZET</td><td>".$DATA[BUDZET_PRZYCHOD][WARTOSC_TOT_A]."</td><td>".$DATA[BUDZET_PLUS][WARTOSC_TOT_A]."</td><td $COLOR>".($DATA[BUDZET_PRZYCHOD][WARTOSC_TOT_A]-$DATA[BUDZET_PLUS][WARTOSC_TOT_A])." </td></tr>";

echo "</table>";

echo "<pre>";
//print_r($DATA);
echo "</pre>";


} //EOF IF



if($_GET[KSIEG_DOKUMENTY_ANALIZA_KONTA_4]) {
echo "KSIEG_DOKUMENTY_ANALIZA <form  method=\"GET\">"; //action=$PHP_SELF
echo "<input type=hidden name=ADD value=ADD>";
echo "<input type=hidden name=KSIEG_DOKUMENTY_ANALIZA_KONTA_4 value=1>";
echo "<table border=1><tr>";
echo "<td>Podaj kryteria data MIN od ktorej nalezy liczyc</td><td>  <input type=text name=DATA_DOK_MIN size=3 value=".$_GET[DATA_DOK_MIN]."></td>";
echo "<td>Podaj kryteria data MAX do ktorej nalezy liczyc</td><td>  <input type=text name=DATA_DOK_MAX size=3 value=".$_GET[DATA_DOK_MAX]."></td>";
echo "<td>Podaj konta ksiegowe w % </td><td>  <input type=text name=ID_KONTO_KSIEG size=3 value=".$_GET[ID_KONTO_KSIEG]."></td>";
echo "</tr>";
echo "<tr><td colspan=1><input type=submit name=ADD value=SZUKAJ></td><td>KONTO</td><td>ROK</td><td>MIESIAC</td><td>ILOSC</td><td>WARTOS</td></tr>";
die('TODO change to IN7_DZIENNIK_KORESP @2018-03');

if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL("select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-',month(DATA_DOK)) as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC
  from  KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and TYP_DOKUMENTU='DOKUMENT'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) > COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
  group by ID_KONTO_KSIEG,YEAR(DATA_DOK),month(DATA_DOK)
  order by ID_KONTO_KSIEG,DATA_DOK
");
$I=1;
while ($DWA=mysql_fetch_array($result)) {

// list($KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],2);
 //OBCINAM PIERWSZE COS, JEZELI JEST PRZECINEK
//   echo "<br>wchodzi ".$DWA[ID_KONTO_KSIEG]." ";
   list($KONT1,$KONT2)=split(",",$DWA[ID_KONTO_KSIEG],2);
   if(strlen($KONT2)<3) { //echo "dupa";// { // wychodzi na to, ze nie ma drugiego czlona konta , dzialamy na pierwszym xx-xxx
//    echo "... i jest KONT2 less 3 , kont2=".$KONT2;
    $KONT1=$DWA[ID_KONTO_KSIEG];
	list($KONT1)=split(" ",$KONT1,2);
    list($PKONTA,$SKONTA)=split("-",$KONT1);
//    echo "... wiec robimy KONT1=".$KONT1 ;
   } else if(strlen($KONT1)<3) die("Blad w zapisie konta ".$DWA[ID_KONTO_KSIEG]." . Sprawdz zapisy w tabeli kosztow!") ; //dzialamy na xx-xxx, bb-bbb
   else {
//   	echo "a ty, ze pewnie jest  KONT2(".$KONT2."), to dzielimy oryginal ".$DWA[ID_KONTO_KSIEG];
	list($KONT1)=split(" ",$KONT1,2);
       list($PKONTA,$SKONTA)=split("-",$KONT1);
//	echo " , a tu PKONTA i SKONTA robimy ".$PKONTA." ".$SKONTA ;
   }

  if(($PKONTA>=500)&&($PKONTA<=600)) $KONTO_GRUPA="*401-".$SKONTA."" ;
  else $KONTO_GRUPA=$KONT1;



//  list($KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],2);

//  list($KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],2);
//   if($KONTO_GRUPA=="080")   list($KONTO_GRUPA)=split(",",$DWA[ID_KONTO_KSIEG],2);

//   $DATA["$KONTO_GRUPA"]["DATA"]=$DWA[DATA];
   $DATA["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];
   $DATA["ALL_SUMA"][WARTOSC_TOT]+=$DWA[WARTOSC];
//  echo "\n<tr><td>".$I++."</td><td>$DWA[0]</td> <td>$DWA[1]</td><td>$DWA[2]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td>$KONTO_GRUPA</td></tr>";
 }

 foreach($DATA as $KONTO_I=>$KONTO_V) {

  foreach($KONTO_V as $DATA_I=>$DATA_V) {
  if($DATA_I!="WARTOSC_TOT")
   echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
    echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>$KONTO_V[WARTOSC_TOT]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
 }

unset($DATA);
echo "</table><hr>MIESIECZNIE SYNTETYCZNIE zespol 80<table border=2>";
die('TODO change to IN7_DZIENNIK_KORESP @2018-03');

if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL("select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-',month(DATA_DOK)) as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC
  from  KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and TYP_DOKUMENTU='DOKUMENT'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) > COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
    and ID_KONTO_KSIEG like '080-%'
  group by ID_KONTO_KSIEG,YEAR(DATA_DOK),month(DATA_DOK)
  order by ID_KONTO_KSIEG,DATA_DOK
");
$I=1;
while ($DWA=mysql_fetch_array($result)) {

  list($KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],2);
   if($KONTO_GRUPA=="080")   list($KONTO_GRUPA)=split(",",$DWA[ID_KONTO_KSIEG],2);

//   $DATA["$KONTO_GRUPA"]["DATA"]=$DWA[DATA];
   $DATA["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];
   $DATA["ALL_SUMA"][WARTOSC_TOT]+=$DWA[WARTOSC];

//  echo "\n<tr><td>".$I++."</td><td>$DWA[0]</td> <td>$DWA[1]</td><td>$DWA[2]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td>$KONTO_GRUPA</td></tr>";
 }

 foreach($DATA as $KONTO_I=>$KONTO_V) {

  foreach($KONTO_V as $DATA_I=>$DATA_V) {
  if($DATA_I!="WARTOSC_TOT")
   echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
    echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>$KONTO_V[WARTOSC_TOT]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
 }

unset($DATA);
echo "</table><hr>MIESIECZNIE SYNTETYCZNIE zespol 139<table border=2>";
die('TODO change to IN7_DZIENNIK_KORESP @2018-03');

if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL("select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-',month(DATA_DOK)) as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC
  from  KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and TYP_DOKUMENTU='DOKUMENT'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) > COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
    and ID_KONTO_KSIEG like '139-%'
  group by ID_KONTO_KSIEG,YEAR(DATA_DOK),month(DATA_DOK)
  order by ID_KONTO_KSIEG,DATA_DOK
");
$I=1;
while ($DWA=mysql_fetch_array($result)) {

  list($KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],2);
   if($KONTO_GRUPA=="139")   list($KONTO_GRUPA)=split(",",$DWA[ID_KONTO_KSIEG],2);

//   $DATA["$KONTO_GRUPA"]["DATA"]=$DWA[DATA];
   $DATA["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];
   $DATA["ALL_SUMA"][WARTOSC_TOT]+=$DWA[WARTOSC];

//  echo "\n<tr><td>".$I++."</td><td>$DWA[0]</td> <td>$DWA[1]</td><td>$DWA[2]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td>$KONTO_GRUPA</td></tr>";
 }

 foreach($DATA as $KONTO_I=>$KONTO_V) {

  foreach($KONTO_V as $DATA_I=>$DATA_V) {
  if($DATA_I!="WARTOSC_TOT")
   echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
    echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>$KONTO_V[WARTOSC_TOT]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
 }

unset($DATA);
echo "</table><hr>MIESIECZNIE SYNTETYCZNIE zespol 221<table border=2>";
die('TODO change to IN7_DZIENNIK_KORESP @2018-03');

if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL("select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-',month(DATA_DOK)) as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC
  from  KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and TYP_DOKUMENTU='DOKUMENT'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) > COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
    and ID_KONTO_KSIEG like '221-%'
  group by ID_KONTO_KSIEG,YEAR(DATA_DOK),month(DATA_DOK)
  order by ID_KONTO_KSIEG,DATA_DOK
");
$I=1;
while ($DWA=mysql_fetch_array($result)) {

  list($KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],2);
   if($KONTO_GRUPA=="221")   list($KONTO_GRUPA)=split(",",$DWA[ID_KONTO_KSIEG],2);

//   $DATA["$KONTO_GRUPA"]["DATA"]=$DWA[DATA];
   $DATA["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];
   $DATA["ALL_SUMA"][WARTOSC_TOT]+=$DWA[WARTOSC];

//  echo "\n<tr><td>".$I++."</td><td>$DWA[0]</td> <td>$DWA[1]</td><td>$DWA[2]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td>$KONTO_GRUPA</td></tr>";
 }

 foreach($DATA as $KONTO_I=>$KONTO_V) {

  foreach($KONTO_V as $DATA_I=>$DATA_V) {
  if($DATA_I!="WARTOSC_TOT")
   echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
    echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>$KONTO_V[WARTOSC_TOT]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
 }


//echo "</table>";

unset($DATA);
echo "</table><hr>ROCZNIE ZESPOLY/SYNTETYCZNIE<br><table border=2>";
die('TODO change to IN7_DZIENNIK_KORESP @2018-03');

if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL("select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-') as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC
  from  KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) > COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
    and TYP_DOKUMENTU='DOKUMENT'
    and ID_KONTO_KSIEG like '080-%'
  group by ID_KONTO_KSIEG,YEAR(DATA_DOK)
  order by ID_KONTO_KSIEG,DATA_DOK
");
$I=1;
while ($DWA=mysql_fetch_array($result)) {

  list($KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],2);

//KOPIA Z GORY
/*
//   echo "<br>wchodzi ".$DWA[ID_KONTO_KSIEG]." ";
   list($KONT1,$KONT2)=split(",",$DWA[ID_KONTO_KSIEG],2);
   if(strlen($KONT2)<3) { //echo "dupa";// { // wychodzi na to, ze nie ma drugiego czlona konta , dzialamy na pierwszym xx-xxx
//    echo "... i jest KONT2 less 3 , kont2=".$KONT2;
    $KONT1=$DWA[ID_KONTO_KSIEG];
	list($KONT1)=split(" ",$KONT1,2);
    list($PKONTA,$SKONTA)=split("-",$KONT1);
//    echo "... wiec robimy KONT1=".$KONT1 ;
   } else if(strlen($KONT1)<3) die("Blad w zapisie konta ".$DWA[ID_KONTO_KSIEG]." . Sprawdz zapisy w tabeli kosztow!") ; //dzialamy na xx-xxx, bb-bbb
   else {
//   	echo "a ty, ze pewnie jest  KONT2(".$KONT2."), to dzielimy oryginal ".$DWA[ID_KONTO_KSIEG];
	list($KONT1)=split(" ",$KONT1,2);
       list($PKONTA,$SKONTA)=split("-",$KONT1);
//	echo " , a tu PKONTA i SKONTA robimy ".$PKONTA." ".$SKONTA ;
   }

  if(($PKONTA>=500)&&($PKONTA<=600)) $KONTO_GRUPA="*401-".$SKONTA."" ;
  else $KONTO_GRUPA=$KONT1;

//echo "DUPA";
*/
//EOF KOPIA Z GORY

   if($KONTO_GRUPA=="080")   list($KONTO_GRUPA)=split(",",$DWA[ID_KONTO_KSIEG],2);

//   $DATA["$KONTO_GRUPA"]["DATA"]=$DWA[DATA];
   $DATA["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];
//  echo "\n<tr><td>".$I++."</td><td>$DWA[0]</td> <td>$DWA[1]</td><td>$DWA[2]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td>$KONTO_GRUPA</td></tr>";
 }

 foreach($DATA as $KONTO_I=>$KONTO_V) {

  foreach($KONTO_V as $DATA_I=>$DATA_V) {
  if($DATA_I!="WARTOSC_TOT")
   echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
    echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>$KONTO_V[WARTOSC_TOT]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
 }

echo "</table>";


unset($DATA);
echo "</table><hr>ROCZNIE_ZESPOLY<br><table border=2>";
die('TODO change to IN7_DZIENNIK_KORESP @2018-03');

if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL("select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-') as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC
  from  KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) > COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
    and TYP_DOKUMENTU='DOKUMENT'
  group by ID_KONTO_KSIEG,YEAR(DATA_DOK)
  order by ID_KONTO_KSIEG,DATA_DOK
");
$I=1;
while ($DWA=mysql_fetch_array($result)) {

  list($KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],2);
//   if($KONTO_GRUPA=="080")   list($KONTO_GRUPA)=split(",",$DWA[ID_KONTO_KSIEG],2);

//   $DATA["$KONTO_GRUPA"]["DATA"]=$DWA[DATA];
   $DATA["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];
//  echo "\n<tr><td>".$I++."</td><td>$DWA[0]</td> <td>$DWA[1]</td><td>$DWA[2]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td>$KONTO_GRUPA</td></tr>";
 }

 foreach($DATA as $KONTO_I=>$KONTO_V) {

  foreach($KONTO_V as $DATA_I=>$DATA_V) {
  if($DATA_I!="WARTOSC_TOT")
   echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
    echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>$KONTO_V[WARTOSC_TOT]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
 }

echo "</table>";


unset($DATA);
die('TODO change to IN7_DZIENNIK_KORESP @2018-03');

$ZAP_SQL="select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-') as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC
  from  KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) > COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
    and ID_KONTO_KSIEG like '5%'
    and TYP_DOKUMENTU='DOKUMENT'
  group by ID_KONTO_KSIEG
  order by ID_KONTO_KSIEG,year(DATA_DOK)
";
echo "</table><hr>ZESPOLY 5XX- wg rodzajow <br> $ZAP_SQL <table border=2>";



if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL($ZAP_SQL);
$I=1;
while ($DWA=mysql_fetch_array($result)) {




//KOPIA Z GORY

//   echo "<br>wchodzi ".$DWA[ID_KONTO_KSIEG]." ";
   list($KONT1,$KONT2)=split(",",$DWA[ID_KONTO_KSIEG],2);
   if(strlen($KONT2)<3) { //echo "dupa";// { // wychodzi na to, ze nie ma drugiego czlona konta , dzialamy na pierwszym xx-xxx
//    echo "... i jest KONT2 less 3 , kont2=".$KONT2;
    $KONT1=$DWA[ID_KONTO_KSIEG];
	list($KONT1)=split(" ",$KONT1,2);
    list($PKONTA,$SKONTA)=split("-",$KONT1);
//    echo "... wiec robimy KONT1=".$KONT1 ;
   } else if(strlen($KONT1)<3) die("Blad w zapisie konta ".$DWA[ID_KONTO_KSIEG]." . Sprawdz zapisy w tabeli kosztow!") ; //dzialamy na xx-xxx, bb-bbb
   else {
//   	echo "a ty, ze pewnie jest  KONT2(".$KONT2."), to dzielimy oryginal ".$DWA[ID_KONTO_KSIEG];
	list($KONT1)=split(" ",$KONT1,2);
       list($PKONTA,$SKONTA)=split("-",$KONT1);
//	echo " , a tu PKONTA i SKONTA robimy ".$PKONTA." ".$SKONTA ;
   }

  if(($PKONTA>=500)&&($PKONTA<=600)) $KONTO_GRUPA="*401-".$SKONTA."" ;
  else $KONTO_GRUPA=$KONT1;

//echo "DUPA";

//EOF KOPIA Z GORY



//  list(,$KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],3);
   	settype($KONTO_GRUPA, "string");
//	$KONTO_GRUPA=$KONTO_GRUPA[0].$KONTO_GRUPA[1];



   $DATA["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];

 }

 foreach($DATA as $KONTO_I=>$KONTO_V) {

  foreach($KONTO_V as $DATA_I=>$DATA_V) {
  if($DATA_I!="WARTOSC_TOT")
   echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
    echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>$KONTO_V[WARTOSC_TOT]</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
 }

echo "</table>";


unset($DATA);
die('TODO change to IN7_DZIENNIK_KORESP @2018-03');

$ZAP_SQL="select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-') as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC , ID_BUDZET
  from  KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) >= COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
    and ID_KONTO_KSIEG like '%'
    and  ID_KONTO_KSIEG not like 'xxx'
    and TYP_DOKUMENTU='DOKUMENT'
  group by ID_KONTO_KSIEG,ID_BUDZET
  order by ID_KONTO_KSIEG,year(DATA_DOK)
";
echo "</table><hr>ROZLICZNIE BUDZETOW wg rodzajow <br> $ZAP_SQL <table border=2>";



if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL($ZAP_SQL);
$I=1;

$DATA["MARKETING-STALY"]=array();
$DATA["MARKETING-DZIALANIA"]=array();

while ($DWA=mysql_fetch_array($result)) {

  list(,$KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],3);
   	settype($KONTO_GRUPA, "string");
	$KONTO_GRUPA=$KONTO_GRUPA[0].$KONTO_GRUPA[1];


      if(strstr($DWA[ID_KONTO_KSIEG],"201-")&&($DWA[WARTOSC]>"0")) $DWA[ID_BUDZET]="BUDZET_PRZYCHOD";
   else   if(strstr($DWA[ID_KONTO_KSIEG],"999-")&&($DWA[WARTOSC]>"0")) $DWA[ID_BUDZET]="BUDZET_PLUS";
   else   if(strstr($DWA[ID_KONTO_KSIEG],"999-")&&($DWA[WARTOSC]<"0")) {
    $DWA[ID_BUDZET]="BUDZET_MINUS_"."$DWA[ID_BUDZET]";
    $DATA["BUDZET_MINUS"]["WARTOSC_TOT"] += $DWA[WARTOSC];
    $DATA["BUDZET_MINUS"]["$KONTO_GRUPA"][$DWA[DATA]] += $DWA[WARTOSC];
    $DATA["BUDZET_MINUS"]["$KONTO_GRUPA"][WARTOSC_TOT] += $DWA[WARTOSC];
    $DATA["BUDZET_MINUS"][WARTOSC_TOT][$DWA[DATA]] += $DWA[WARTOSC];

   } else if(ereg("^5",$DWA[ID_KONTO_KSIEG]) && ereg("-01",$DWA[ID_KONTO_KSIEG]) ) {
     echo "AMORTY";
     $DWA[ID_BUDZET]="AMORTYZACJA";
   } if(strstr($DWA[ID_KONTO_KSIEG],"220-40")) $DWA[ID_BUDZET]="VAT-NALEZNY";
   else  if(strstr($DWA[ID_KONTO_KSIEG],"221-00")) $DWA[ID_BUDZET]="PODATKI";
   $DATA[$DWA[ID_BUDZET]]["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA[$DWA[ID_BUDZET]]["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];
   $DATA[$DWA[ID_BUDZET]][WARTOSC_TOT]+=$DWA[WARTOSC];

 }


//print_r($DATA);


 foreach($DATA as $BUDZET_I=>$DDATA) {
  foreach($DDATA as $KONTO_I=>$KONTO_V) {

   foreach($KONTO_V as $DATA_I=>$DATA_V) {
    if($DATA_I!="WARTOSC_TOT")
    echo "\n<tr><td>".$I++."</td><td>$BUDZET_I $KONTO_I</td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
    else $BDATA+=$DATA_V;
   }
     echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>  WARTOSC_TOT </td><td>". $KONTO_V[WARTOSC_TOT]."</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
  }
//    $BDATA-=$DATA_V;
     echo "\n<tr><td>".$I++."</td><td>$BUDZET_I <hr></td> <td>  WARTOSC_TOT_A <hr> </td><td>$BDATA <hr></td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
	$DATA[$BUDZET_I]["WARTOSC_TOT_A"]=$BDATA;
     unset($BDATA);
 }
echo "</table>";


echo "<br> PODSUMOWANIE DYSPOZYCJI BUDZETU";

 echo "<table border=1><tr><td>KOMORKA ORGANIZACYJNA</td><td>PRZYZNANY BUDZET</td><td>WYKORZYSTANY BUDZET</td><td>POZOSTALO DO WYKORZYSTANIA</td></tr>";

 foreach($DATA as $BUDZET_I=>$DDATA) {
  if(!strstr("$BUDZET_I","BUDZET")) {

  echo "<tr><td>$BUDZET_I</td><td>".$DATA["BUDZET_MINUS_".$BUDZET_I][WARTOSC_TOT_A]."</td><td>".$DATA[$BUDZET_I]["WARTOSC_TOT"]."</td>";

	$DO_WYKORZYSTANIA=$DATA["BUDZET_MINUS_".$BUDZET_I]["WARTOSC_TOT"]+$DATA[$BUDZET_I]["WARTOSC_TOT"];
	if($DO_WYKORZYSTANIA>=0) $COLOR="bgcolor=red"; else $COLOR="";
  echo "<td $COLOR>".$DO_WYKORZYSTANIA."</td></tr>";
       $BUDZET_WYKORZYSTANO+=$DATA[$BUDZET_I]["WARTOSC_TOT_A"];
       $BUDZET_PRZYZNANO+=$DATA["BUDZET_MINUS_".$BUDZET_I]["WARTOSC_TOT_A"];
  } else   if(strstr("$BUDZET_I","BUDZET_PLUS")) {
  }




 }
        $BUDZET_WYKORZYSTANO-=$DATA["AMORTYZACJA"]["WARTOSC_TOT_A"];
      $BUDZET_WYKORZYSTANO-=$DATA["VAT-NALEZNY"]["WARTOSC_TOT_A"];
      $BUDZET_WYKORZYSTANO-=$DATA["PODATKI"]["WARTOSC_TOT_A"];
      if(-$BUDZET_PRZYZNANO-$BUDZET_WYKORZYSTANO<0) $COLOR="bgcolor=red"; else $COLOR="";
echo "<tr><td>BUDZET/ Wykorzystanie</td><td>$BUDZET_PRZYZNANO</td><td>$BUDZET_WYKORZYSTANO</td><td $COLOR>".(-$BUDZET_PRZYZNANO-$BUDZET_WYKORZYSTANO)."</td></tr>";
      if($DATA[BUDZET_PLUS][WARTOSC_TOT_A]+$DATA[BUDZET_MINUS][WARTOSC_TOT_A]<0) $COLOR="bgcolor=red"; else $COLOR="";
echo "<tr><td>BUDZET/DYSPOZYCJE</td><td>".$DATA[BUDZET_PLUS][WARTOSC_TOT_A]."</td><td>".$DATA[BUDZET_MINUS][WARTOSC_TOT_A]."</td><td $COLOR>".($DATA[BUDZET_PLUS][WARTOSC_TOT_A]+$DATA[BUDZET_MINUS][WARTOSC_TOT_A])."</td></tr>";
      if($DATA[BUDZET_PLUS][WARTOSC_TOT_A]>$DATA[BUDZET_PRZYCHOD][WARTOSC_TOT_A]) $COLOR="bgcolor=red"; else $COLOR="";
echo "<tr><td>PRZYCHOD/BUDZET</td><td>".$DATA[BUDZET_PRZYCHOD][WARTOSC_TOT_A]."</td><td>".$DATA[BUDZET_PLUS][WARTOSC_TOT_A]."</td><td $COLOR>".($DATA[BUDZET_PRZYCHOD][WARTOSC_TOT_A]-$DATA[BUDZET_PLUS][WARTOSC_TOT_A])." </td></tr>";

echo "</table>";

echo "<pre>";
//print_r($DATA);
echo "</pre>";


} //EOF IF






if($_GET[KSIEG_DOKUMENTY_ANALIZA_KONTA_2]) {
echo "KSIEG_DOKUMENTY_ANALIZA <form  method=\"GET\">"; //action=$PHP_SELF
echo "<input type=hidden name=ADD value=ADD>";
echo "<input type=hidden name=KSIEG_DOKUMENTY_ANALIZA_KONTA_2 value=1>";
echo "<table border=1><tr>";
echo "<td>Podaj kryteria data MIN od ktorej nalezy liczyc</td><td>  <input type=text name=DATA_DOK_MIN size=3 value=".$_GET[DATA_DOK_MIN]."></td>";
echo "<td>Podaj kryteria data MAX do ktorej nalezy liczyc</td><td>  <input type=text name=DATA_DOK_MAX size=3 value=".$_GET[DATA_DOK_MAX]."></td>";
echo "<td>Podaj konta ksiegowe w % </td><td>  <input type=text name=ID_KONTO_KSIEG size=3 value=".$_GET[ID_KONTO_KSIEG]."></td>";
echo "</tr>";

echo "<tr><td colspan=1><input type=submit name=ADD value=SZUKAJ></td><td>KONTO</td><td>ROK</td><td>MIESIAC</td><td>ILOSC</td><td>WARTOS</td></tr>";

unset($DATA);
die('TODO change to IN7_DZIENNIK_KORESP @2018-03');

$ZAP_SQL="select ID_KONTO_KSIEG, concat(YEAR(DATA_DOK),'-') as DATA ,sum(ILOSC*CENA_JEDN_NETTO) as WARTOSC , ID_BUDZET , TYP_DOKUMENTU
  from  KSIEG_DOKUMENTY
  where A_STATUS='NORMAL'
    and ID_KONTO_KSIEG like '".$_GET[ID_KONTO_KSIEG]."'
    and COALESCE(unix_timestamp(DATA_DOK), 0) < COALESCE(unix_timestamp('".$_GET[DATA_DOK_MAX]."'), 0)
    and COALESCE(unix_timestamp(DATA_DOK), 0) >= COALESCE(unix_timestamp('".$_GET[DATA_DOK_MIN]."'), 0)
    and ID_KONTO_KSIEG like '%'
    and ID_KONTO_KSIEG not like 'xxx'
  group by ID_KONTO_KSIEG,ID_BUDZET
  order by ID_KONTO_KSIEG,year(DATA_DOK)
";
echo "</table><hr>ROZLICZNIE BUDZETOW wg rodzajow <br> $ZAP_SQL <table border=2>";



if(!$_SESSION['ADM_ADMIN_LEVEL']=="0") echo "BRAK UPRAWNIEN <BR>"; else ZAP_SQL($ZAP_SQL);
$I=1;

$DATA["MARKETING-STALY"]=array();
$DATA["MARKETING-DZIALANIA"]=array();

while ($DWA=mysql_fetch_array($result)) {

  list(,$KONTO_GRUPA)=split("-",$DWA[ID_KONTO_KSIEG],3);
   	settype($KONTO_GRUPA, "string");
	$KONTO_GRUPA=$KONTO_GRUPA[0].$KONTO_GRUPA[1];


      if(strstr($DWA[ID_KONTO_KSIEG],"201-")&&($DWA[WARTOSC]>"0")) $DWA[ID_BUDZET]="BUDZET_PRZYCHOD";
   else   if(strstr($DWA[ID_KONTO_KSIEG],"999-")&&($DWA[WARTOSC]>"0")) $DWA[ID_BUDZET]="BUDZET_PLUS";
   else   if(strstr($DWA[ID_KONTO_KSIEG],"999-")&&($DWA[WARTOSC]<"0")) {
    $DWA[ID_BUDZET]="BUDZET_MINUS_"."$DWA[ID_BUDZET]";
    $DATA["BUDZET_MINUS"][$DWA[TYP_DOKUMENTU]]["WARTOSC_TOT"] += $DWA[WARTOSC];
    $DATA["BUDZET_MINUS"][$DWA[TYP_DOKUMENTU]]["$KONTO_GRUPA"][$DWA[DATA]] += $DWA[WARTOSC];
    $DATA["BUDZET_MINUS"][$DWA[TYP_DOKUMENTU]]["$KONTO_GRUPA"][WARTOSC_TOT] += $DWA[WARTOSC];
    $DATA["BUDZET_MINUS"][$DWA[TYP_DOKUMENTU]][WARTOSC_TOT][$DWA[DATA]] += $DWA[WARTOSC];

   } else if(ereg("^5",$DWA[ID_KONTO_KSIEG]) && ereg("-01",$DWA[ID_KONTO_KSIEG]) ) {
     echo "AMORTY";
     $DWA[ID_BUDZET]="AMORTYZACJA";
   } if(strstr($DWA[ID_KONTO_KSIEG],"220-40")) $DWA[ID_BUDZET]="VAT-NALEZNY";
   else  if(strstr($DWA[ID_KONTO_KSIEG],"221-00")) $DWA[ID_BUDZET]="PODATKI";
   $DATA[$DWA[ID_BUDZET]][$DWA[TYP_DOKUMENTU]]["$KONTO_GRUPA"][$DWA[DATA]]+=$DWA[WARTOSC];
   $DATA[$DWA[ID_BUDZET]][$DWA[TYP_DOKUMENTU]]["$KONTO_GRUPA"][WARTOSC_TOT]+=$DWA[WARTOSC];
   $DATA[$DWA[ID_BUDZET]][$DWA[TYP_DOKUMENTU]][WARTOSC_TOT]+=$DWA[WARTOSC];

 }


echo "<pre>";
print_r($DATA);
echo "</pre>";


 foreach($DATA as $BUDZET_I=>$DDATA) {
  foreach($DDATA as $KONTO_I=>$KONTOT) {

   foreach($KONTOT as $KONTOT_I=>$KONTO_V) {
    foreach($KONTO_V as $DATA_I=>$DATA_V) {
      if($DATA_I!="WARTOSC_TOT")
      echo "\n<tr><td>".$I++."</td><td>$BUDZET_I $KONTO_I </td> <td> $DATA_I </td><td>$DATA_V</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
      else $BDATA+=$DATA_V;
    }
      echo "\n<tr><td>".$I++."</td><td>$KONTO_I</td> <td>   WARTOSC_TOT </td><td>". $KONTO_V[WARTOSC_TOT]."</td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
   }
  }
 //    $BDATA-=$DATA_V;
      echo "\n<tr><td>".$I++."</td><td>$BUDZET_I <hr></td> <td>   WARTOSC_TOT_A <hr> </td><td>$BDATA <hr></td><td>$DWA[3]</td><td>$DWA[4]</td><td>$DWA[5]</td><td></td></tr>";
 	$DATA[$BUDZET_I]["WARTOSC_TOT_A"]=$BDATA;
      unset($BDATA);
 }



echo "</table>";


echo "<br> PODSUMOWANIE DYSPOZYCJI BUDZETU";

 echo "<table border=1><tr><td>KOMORKA ORGANIZACYJNA</td><td>PRZYZNANY BUDZET</td><td>WYKORZYSTANY BUDZET</td><td>POZOSTALO DO WYKORZYSTANIA</td></tr>";

 foreach($DATA as $BUDZET_I=>$DDATA) {
  if(!strstr("$BUDZET_I","BUDZET")) {

  echo "<tr><td>$BUDZET_I</td><td>".$DATA["BUDZET_MINUS_".$BUDZET_I][DOKUMENT][WARTOSC_TOT_A]."</td><td>".$DATA[$BUDZET_I][DOKUMENT]["WARTOSC_TOT"]."</td>";

	$DO_WYKORZYSTANIA=$DATA["BUDZET_MINUS_".$BUDZET_I][DOKUMENT]["WARTOSC_TOT"]+$DATA[$BUDZET_I][DOKUMENT]["WARTOSC_TOT"];
	if($DO_WYKORZYSTANIA>=0) $COLOR="bgcolor=red"; else $COLOR="";
  echo "<td $COLOR>".$DO_WYKORZYSTANIA."</td></tr>";
       $BUDZET_WYKORZYSTANO+=$DATA[$BUDZET_I]["WARTOSC_TOT_A"];
       $BUDZET_PRZYZNANO+=$DATA["BUDZET_MINUS_".$BUDZET_I]["WARTOSC_TOT_A"];
  } else   if(strstr("$BUDZET_I","BUDZET_PLUS")) {
  }




 }
        $BUDZET_WYKORZYSTANO-=$DATA["AMORTYZACJA"]["WARTOSC_TOT_A"];
      $BUDZET_WYKORZYSTANO-=$DATA["VAT-NALEZNY"]["WARTOSC_TOT_A"];
      $BUDZET_WYKORZYSTANO-=$DATA["PODATKI"]["WARTOSC_TOT_A"];
      if(-$BUDZET_PRZYZNANO-$BUDZET_WYKORZYSTANO<0) $COLOR="bgcolor=red"; else $COLOR="";
echo "<tr><td>BUDZET/ Wykorzystanie</td><td>$BUDZET_PRZYZNANO</td><td>$BUDZET_WYKORZYSTANO</td><td $COLOR>".(-$BUDZET_PRZYZNANO-$BUDZET_WYKORZYSTANO)."</td></tr>";
      if($DATA[BUDZET_PLUS][WARTOSC_TOT_A]+$DATA[BUDZET_MINUS][WARTOSC_TOT_A]<0) $COLOR="bgcolor=red"; else $COLOR="";
echo "<tr><td>BUDZET/DYSPOZYCJE</td><td>".$DATA[BUDZET_PLUS][WARTOSC_TOT_A]."</td><td>".$DATA[BUDZET_MINUS][WARTOSC_TOT_A]."</td><td $COLOR>".($DATA[BUDZET_PLUS][WARTOSC_TOT_A]+$DATA[BUDZET_MINUS][WARTOSC_TOT_A])."</td></tr>";
      if($DATA[BUDZET_PLUS][WARTOSC_TOT_A]>$DATA[BUDZET_PRZYCHOD][WARTOSC_TOT_A]) $COLOR="bgcolor=red"; else $COLOR="";
echo "<tr><td>PRZYCHOD/BUDZET</td><td>".$DATA[BUDZET_PRZYCHOD][WARTOSC_TOT_A]."</td><td>".$DATA[BUDZET_PLUS][WARTOSC_TOT_A]."</td><td $COLOR>".($DATA[BUDZET_PRZYCHOD][WARTOSC_TOT_A]-$DATA[BUDZET_PLUS][WARTOSC_TOT_A])." </td></tr>";

echo "</table>";

echo "<pre>";
//print_r($DATA);
echo "</pre>";


} //EOF IF







if($_GET[GDZIE_PUSCIC_HANDLOWCA_2]) {
echo "SZUKANIE MIEJSC GDZIE_PUSCIC_HANDLOWCA <form  method=\"GET\">"; //action=$PHP_SELF
echo "<input type=hidden name=ADD value=ADD>";
echo "<input type=hidden name=GDZIE_PUSCIC_HANDLOWCA_2 value=1>";
echo "<table border=1><tr><td>";
echo "Dodaj Lancuch dla poszukiwan ulicy , (zakoncz znakiem %) - 500 rekordow</td><td>  <input type=text name=S_ADDRESS_STREET size=3 value=$_GET[S_ADDRESS_STREET]></td></tr>";
echo "<tr><td colspan=1><input type=submit name=ADD value=SZUKAJ></td><td>M_REWIR</td><td>ZAINTERES</td><td>Data_Bad</td><td>OPER</td><td>OPER_FIN</td><td>OPER_ZAD</td></tr>";

if($_GET[S_ADDRESS_STREET]) ZAP_SQL("SELECT * FROM USERS2_MARKETING where ( S_ADDRESS_STREET like '".$_GET[S_ADDRESS_STREET]."' or M_REWIR like '".$_GET[S_ADDRESS_STREET]."' or T_NETWORK_SERVER like '".$_GET[S_ADDRESS_STREET]."'    ) and I_OPER_ZAINT!='NIEWIADOMO'    and (I_OPER_FIN < from_unixtime(unix_timestamp(now())+2592000) or I_OPER_FIN='0000-00-00' )   and I_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)
 order by I_OPER_ZAINT desc , I_OPER_FIN desc  limit 500 ");

while($DWA=mysql_fetch_array($result)) {


echo "<tr><td>".$DWA[S_ADDRESS_STREET]." $DWA[P_NAME] $DWA[P_PHONE]  $DWA[S_ALIAS]( $DWA[S_OTHER_INFO] ) </td><td>".$DWA[T_NETWORK_SERVER]."/".$DWA[M_REWIR]."</td><td>".$DWA[I_OPER_ZAINT]."</td><td>".$DWA[I_BAD_DATE]." ";
echo "</td><td>$DWA[I_OPER]</td><td>$DWA[I_OPER_FIN]</td><td>$DWA[I_OPER_ZAD]</td></tr>";

 }

echo "</table>";

} //EOF IF








if($_GET[ZLECENIE_DYSTRYBUCJI_1]) {
echo " .<p style=\"page-break-before: always\">\n . ";
echo "<br>PRZYGOTOWANIE RAPORTU DYSTRYBUCJI INFORMACJI wg ustalen z dn 2007-03-24 ";
echo "<form action=$PHP_SELF method=\"GET\">Czy jest uruchomiony proces dystrybucji lub chcesz go uruchomic dla tego zlecenia? (wype�nienie danych)<input type=\"checkbox\" name=\"ZLECENIE_DYSTRYBUCJI_1_CZY_WYPELNIC_DANE\"";
 if($_GET[ZLECENIE_DYSTRYBUCJI_1_CZY_WYPELNIC_DANE])  echo "checked=\"checked\"";
echo ">";
echo "<br>Czy wyszukac tylko miejsca, gdzie nie bylo dzialan w przeciagu 1-go miesiaca?<input type=\"checkbox\" name=\"ZLECENIE_DYSTRYBUCJI_1_UZUPELNIC_DYSTRYBUCJE\"";
 if($_GET[ZLECENIE_DYSTRYBUCJI_1_UZUPELNIC_DYSTRYBUCJE]) { echo "checked=\"checked\"";
  $ZLECENIE_DYSTRYBUCJI_1_TERMIN_DOSZCZELNIENIA=$_GET[ZLECENIE_DYSTRYBUCJI_1_TERMIN_DOSZCZELNIENIA] ;
// $ZLECENIE_DYSTRYBUCJI_1_UZUPELNIC_DYSTRYBUCJE;
 settype($ZLECENIE_DYSTRYBUCJI_1_UZUPELNIC_DYSTRYBUCJE, "integer");

 $SECONDS=(86400 * $ZLECENIE_DYSTRYBUCJI_1_TERMIN_DOSZCZELNIENIA) ;
 $ZLECENIE_DYSTRYBUCJI_1_UZUPELNIC_DYSTRYBUCJE_SQL="and COALESCE(unix_timestamp(t2.M_ZRYWKA_DATE), 0) < (unix_timestamp(now())-$SECONDS)";

 }
echo ">";

// $SECONDS=86400*$ZLECENIE_DYSTRYBUCJI_1_UZUPELNIC_DYSTRYBUCJE  ;
//  $VAR=$ZLECENIE_DYSTRYBUCJI_1_UZUPELNIC_DYSTRYBUCJE;

//$SECONDS=$ZLECENIE_DYSTRYBUCJI_1_TERMIN_DOSZCZELNIENIA+86400 ;
//echo "$ZLECENIE_DYSTRYBUCJI_1_UZUPELNIC_DYSTRYBUCJE_SQL * ($ZLECENIE_DYSTRYBUCJI_1_TERMIN_DOSZCZELNIENIA)**sec= $SECONDS ";

if($_GET[ZLECENIE_DYSTRYBUCJI_1_UZUPELNIC_DYSTRYBUCJE]) echo "<br>OKRESL TERMIN WYKLUCZENIA AKTUALNOSCI POPRZEDNICH DYSTRYBUCJI w dniach <input type=text name=ZLECENIE_DYSTRYBUCJI_1_TERMIN_DOSZCZELNIENIA value=\"$ZLECENIE_DYSTRYBUCJI_1_TERMIN_DOSZCZELNIENIA\"> ";


if($_GET[ZLECENIE_DYSTRYBUCJI_1_CZY_WYPELNIC_DANE]) {
echo "<br>PROCES DYSTRYBUCJI INFORMACJI wg danych poni�ej:";
$ZMIENNE=array(DATA_ZLECENIA_KOLPORTAZU,NUMER_PROCESU_DYSTRYBUCJI,DATA_PROCESU_DYSTRYBUCJI,ZLECENIOBIORCA,
JAKIE_POWIERZONO_MATERIALY_plakaty_ulotki_itp,INNE_POWIERZONE_PRZEDMIOTY_np_nozyczki_tasma_itp,LACZNA_WARTOSC_POWIERZONYCH_MAETRIALOW,
MATERIALY_NALEZY_ROZNIESC_W_DNIU,MATERIALY_NALEZY_ROZNIESC_OD_GODZINY,MATERIALY_NALEZY_ROZNIESC_TEGO_SAMEGO_DNIA_DO_GODZINY,
MATERIALY_NALEZY_POJEDYNCZO_UMIESZCZAC_NA_np_klamka_drzwi_itp,DODATKOWE_CZYNNOSCI_DO_ZROBIENIA_np_poskladac_ogumkowac_itp,WARTOSC_ZLECENIA,TERMIN_DATA_DOSTARCZENIA_RAPORTU,GODZINA_DOSTARCZENIA_RAPORTU,
MIEJSCE_DOSTARCZENIA_RAPORTU,DATA_ZLECENIA_RAPORTU_KONTROLI,NAZWISKO_KONTROLERA,TERMIN_DATA_DOSTARCZENIA_RAPORTU_KONTROLI,GODZINA_DOSTARCZENIA_RAPORTU_KONTROLI,DATA_DRUKU_PROJEKTU_MATERIALU_MARKETINGOWEGO,
NAZWA_PLIKU_WZORU_LUB_INNE_JEDNOZNACZNE_OKRESLENIE_RODZAJU_MATERIALU,ILOSC_MATERIALU_W_MAGAZYNIE_PRZED_DYSTRYBUCJA,ILOSC_POWIERZONYCH_SZTUK_MATERIALOW,ILOSC_MATERIALU_W_MAGAZYNIE_PO_DYSTRYBUCJI,CZY_NALEZY_DOPROWADZIC_DO_UZUPELNIENIA_MATERIALOW_tak_lub_nie,JAKA_NALEZY_WYKONAC_AKCJE_JAK_ZABRAKNIE_MATERIALU,
 TEORETYCZNA_ILOSC_LOKALI_DO_DYSTRYBUCJI_spisac_ze_zlecenia_punkt_12);
foreach($ZMIENNE as $PARAMETR) {
// echo "$PARAMETR $WARTOSC";
 if($_GET[$PARAMETR]) ${$PARAMETR}="$_GET[$PARAMETR]"; else ${$PARAMETR}=".......................";
 echo "<br>$PARAMETR<input type=text name=$PARAMETR size=40 value=\"".${$PARAMETR}."\">";
 }


echo "<br>Je�eli uzupe�ni�e� mo�liwie Karte Procesu, to j� wydrukuj i umie�� w teczce z aktywnymi dystrybucjami, na podstawie tej kartki i danych w niej zawartych nale�y egzekwowa�/kontrolowa� czynno�ci w terenie. Nie zapomnij dopisa� informacji do CRM (dla odpowiedniego/odpowiednich rewir�w), oto one:<br>
 $DATA_PROCESU_DYSTRYBUCJI Uruchamiam proces dystrybucji nr. $NUMER_PROCESU_DYSTRYBUCJI dla danych $_GET[M_REWIR]/$_GET[S_ADDRESS_STREET] , ulotka $NAZWA_PLIKU_WZORU_LUB_INNE_JEDNOZNACZNE_OKRESLENIE_RODZAJU_MATERIALU druk z dnia $DATA_DRUKU_PROJEKTU_MATERIALU_MARKETINGOWEGO , ilo�� $ILOSC_POWIERZONYCH_SZTUK_MATERIALOW koniec procesu na $TERMIN_DATA_DOSTARCZENIA_RAPORTU_KONTROLI / $TERMIN_DATA_DOSTARCZENIA_RAPORTU. ";
} else {
foreach($ZMIENNE as $PARAMETR) { if($_GET[$PARAMETR]) ${$PARAMETR}=$_GET[$PARAMETR]; else ${$PARAMETR}=".......................";}
}


echo "<input type=hidden name=ADD value=ADD>";
echo "<input type=hidden name=ZLECENIE_DYSTRYBUCJI_1 value=1>";
echo "<br>OKRE�L ZAKRES DZIA�A�  (zakoncz znakami %) - 500 rekordow. REWIR:<input type=text name=M_REWIR size=10 value=$_GET[M_REWIR]> |  S_ADDRESS_STREET:<input type=text name=S_ADDRESS_STREET size=10 value=$_GET[S_ADDRESS_STREET]> | <input type=submit name=ADD value=SZUKAJ>";
echo "<font size=-2>";
echo " .<p style=\"page-break-before: always\">\n . ";
echo "<table border=1 size=100% cellspacing=0 cellpadding=0 bordercolor=\"#cccccc\"><tr><td colspan=14></td></tr>";
echo "<tr><td colspan=14>
<br>
ZLECENIE KOLPORTA�U
Z dnia  <i><b>$DATA_ZLECENIA_KOLPORTAZU</b></i> , do procesu dystrybucji nr <i><b>$NUMER_PROCESU_DYSTRYBUCJI</b></i> z dnia <i><b>$DATA_PROCESU_DYSTRYBUCJI</b></i> <br><br>
Zleceniodawca:<br>
BIALL-NET sp. z o.o. 80-174 Gda�sk, Otomin ul. S�oneczna 43.<br>
<br>
Zleceniobiorca:<br>
<b>$ZLECENIOBIORCA</b> <br>

<font size=1>
1) Zleceniobiorca zobowi�zuje si� rozprowadzi� materia�y  reklamowe na obszarze (wg oznaczenia kodowego REWIR�W i ULIC: $M_REWIR/$S_ADDRESS_STREET):</font>
</td></tr>";
echo "<tr><td colspan=1 rowspan=2 width=10>LP</td><td width=10>M_REWIR</td><td width=10>DATA</td><td width=10>MIESZKAN</td><td colspan=9>Klatki</td><td>---</td></tr>";
echo "<tr><td>ULICA</td><td>GODZINA</td><td>UWAGI</td><td>A</td><td>B</td><td>C</td><td>D</td><td>E</td><td>F</td><td>G</td><td>H</td><td>I-Z</td></tr>";

if($_GET[S_ADDRESS_STREET]) ZAP_SQL("SELECT COUNT(t1.ID) as ILOSC_MIESZKAN , t1.T_TELBOX_BUILDING_IN , t1.M_REWIR , t2.P_ADDRESS_STREET , t2.M_ZRYWKA_DATE FROM USERS2_MARKETING as t1 left join BUILDINGS as t2 on t1.T_TELBOX_BUILDING_IN=t2.S_ADDRESS_STREET where ( t1.T_TELBOX_BUILDING_IN like '".$_GET[S_ADDRESS_STREET]."' and t1.M_REWIR like '".$_GET[M_REWIR]."' $ZLECENIE_DYSTRYBUCJI_1_UZUPELNIC_DYSTRYBUCJE_SQL  ) group by t1.T_TELBOX_BUILDING_IN order by t1.M_REWIR, t1.T_TELBOX_BUILDING_IN ");



//BEGIN WYKRYWANIE ZAKRESU BUDYNKOW
$mieszkan=0;
$i=1;
$ULICE_LIST['ULICE']=array();
$ULICE_LIST['BUDYNKI']=array();
while($DWA=mysql_fetch_array($result)) {
if(in_array($DWA[P_ADDRESS_STREET],$ULICE_LIST[ULICE])) {
} else {
array_push($ULICE_LIST['ULICE'],$DWA["P_ADDRESS_STREET"]) ;
//array_push($ULICE_LIST['ULICE'],"wartosc") ;
  $klucz=array_search($DWA[P_ADDRESS_STREET],$ULICE_LIST[ULICE]);
   if(!in_array($klucz,$ULICE_LIST['BUDYNKI'])) $ULICE_LIST['BUDYNKI'][$klucz]=array();
}
 $NUMER_DOM=ereg_replace("[[:alpha:]]","", $DWA[T_TELBOX_BUILDING_IN]);
// echo "NUMER DOM ..$NUMER_DOM.. ";
  $klucz=array_search($DWA[P_ADDRESS_STREET],$ULICE_LIST[ULICE]);
//   echo "klucz to $klucz ";
   if(!in_array($NUMER_DOM,$ULICE_LIST['BUDYNKI'][$klucz])) array_push($ULICE_LIST['BUDYNKI'][$klucz],$NUMER_DOM);
//EOF BEGIN WYKRYWANIE ZAKRESU BUDYNKOW



echo "<tr><td rowspan=2>$i</td><td><font size=-2><b>".$DWA[M_REWIR]."</b></font> </td><td><font size=-2>07- . . . . . - . . . . . </font></td><td><font size=-2>".$DWA[ILOSC_MIESZKANN]."</font></td><td>. .</td><td>. .</td><td>. .</td><td>. .</td><td>. .</td><td>. .</td><td>. .</td><td>. .</td><td>. .</td><td><font size=-2>Gdzie Umieszcz.</font></td></tr> ";
echo "<tr><td><font size=-2>$DWA[T_TELBOX_BUILDING_IN]"; if($DWA[P_ADDRESS_STREET]) echo " ($DWA[P_ADDRESS_STREET])";
echo " </font></td><td><font size=-2>. . . . . . : . . . . .</font></td><td><font size=-2>. . . . .</font></td><td>. .</td><td>. .</td><td>. .</td><td>. .</td><td>. .</td><td>. .</td><td>. .</td><td>. .</td><td>. .</td><td><font size=-2>Liczb.Mieszkan</font></td></tr> ";
$i++;
$mieszkan+=$DWA[ILOSC_MIESZKAN];

 }
//print_r($ULICE_LIST);
echo "<tr><td colspan=14>
<font size=1>


2) Zleceniodawca powierza <b>$ILOSC_POWIERZONYCH_SZTUK_MATERIALOW</b> sztuk <b>$JAKIE_POWIERZONO_MATERIALY_plakaty_ulotki_itp</b> oraz inne przedmioty (<b>$INNE_POWIERZONE_PRZEDMIOTY_np_nozyczki_tasma_itp</b>)*, wszystkie o ��cznej warto�ci <b>$LACZNA_WARTOSC_POWIERZONYCH_MAETRIALOW</b> PLN. z�.<br>
3) Powierzone materia�y reklamowe, pod rygorem niewyp�acenia warto�ci zlecenia Zleceniobiorcy lub/i dodatkowo powstania innych roszcze� Zleceniodawcy tytu�em strat wobec Zleceniobiorcy, rozprowadzi� nale�y na wyznaczonym terenie w dniu <b>$MATERIALY_NALEZY_ROZNIESC_W_DNIU</b> od godziny <b>$MATERIALY_NALEZY_ROZNIESC_OD_GODZINY</b> do godziny <b>$MATERIALY_NALEZY_ROZNIESC_TEGO_SAMEGO_DNIA_DO_GODZINY</b> <br>
4) Powierzone materia�y reklamowe nale�y umieszcza� pojedynczo na <b>$MATERIALY_NALEZY_POJEDYNCZO_UMIESZCZAC_NA_np_klamka_drzwi_itp</b> <br>
5) Niniejsze zlecenie z uzupelnionymi polami Raportu roznoszenia ulotek  wraz z pozosta�ymi materia�ami reklamowymi, nale�y dostarczy� do dnia: <b>$TERMIN_DATA_DOSTARCZENIA_RAPORTU</b> do godziny: <b>$GODZINA_DOSTARCZENIA_RAPORTU</b> w miejsce <b>$MIEJSCE_DOSTARCZENIA_RAPORTU</b> .<br>
   Sposob wypelnienia niniejszego raportu wygl�da nast�puj�co: W kolumnie Data oraz Godzina nale�y wpisa� ka�dorazowo dat� oraz godzin� rozpocz�cia czynno�ci na danym budynku,
natomiast w kolumnach klatki A,B,C(i tak dalej) nale�y wprowadzi� w rz�dzie
 poziomym \"Gdzie Umieszczono\" literk� oznaczaj�c� faktyczne miejsce kolporta�u , wg wzoru: (  <b>P</b>-skrzynka pocztowa w srodku, <b>S</b>-na skrzynce pocztowej, <b>X</b>-Nie rozniesiono, <b>W</b>-Wycieraczka, <b>D</b>-Drzwi/Gumka-klamka.), natomiast w rz�dzie \"Liczb.Mieszkan\" nale�y wpisa� faktyczn� ilo�� umieszczonych materia��w.<br>
6) Dodatkowe czynno�ci, kt�re zobowi�zuje si� przeprowadzi� Zleceniobiorca przed rozprowadzeniem materia��w reklamowych: <b>$DODATKOWE_CZYNNOSCI_DO_ZROBIENIA_np_poskladac_ogumkowac_itp</b> <br>
7) Warto�� zlecenia wynosi <b>$WARTOSC_ZLECENIA</b>  z�otych.<br>
8) Materia�y opisane w pkt. 2) winny trafi� w 100% do ustalonych miejsc dystrybucji (wg pkt. 1) oraz pkt. 4))  . W przypadku jakichkolwiek odst�pstw od powy�szego zlecaj�cemu zostanie potr�cona wysoko�� wynagrodzenia do 20% warto�ci zlecenia opisanego w pkt.7).<br>
9) W przypadku, kiedy materia�y opisane wy�ej, w ilo�ci wi�kszej lub r�wnej 10% sztuk okre�lonych w pkt. 2), zosta�y umieszczone w innych miejscach ni� okre�la <nobr>pkt. 4) b�d� </nobr> nie zosta�y umieszczone w og�le, Zlecaj�cemu przys�uguje prawo do dodatkowego odszkodowania tytu�em strat handlowych do wysoko�ci ";
  $kara=($LACZNA_WARTOSC_POWIERZONYCH_MAETRIALOW+$WARTOSC_ZLECENIA)*2;
  echo "<b>$kara</b>";
echo " z�.<br>
10) Raporty roznoszenia ulotek winny by� wype�nione wg schematu w raporcie ( oznaczonego w pkt. 5), czyli np. w polu .godzina/data. nale�y umie�ci� dat� i godzin� rozpocz�cia dystrybucji materia��w danym budynku. Niewype�nienie tych p�l lub/i raportu jest r�wnoznaczne ze niewykonaniem zlecenia. Brane b�d� wy��cznie pod uwag� fragmenty raportu wype�nione w pe�ni, rzetelnie i czytelnie. Wszystkie inne pola (rz�dy arkusza) wype�nione cz��ciowo lub w og�le, b�d� traktowane jakoby w danym adresie dystrybucja nie mia�a miejsca. Od momentu oddania raportu dystrybucji zakazane jest uzupe�nianie raportu przez kt�r�kolwiek ze stron. Wpisy w danym rz�dzie w raporcie winny by� wype�nione jednym i tym samym d�ugopisem.<br>
11) Nie wywi�zanie si� z wy�ej wymienionych zada� r�wnoznaczne jest z nie wykonaniem powierzonej pracy, co si� wi��e brakiem wynagrodzenia a nawet pokryciem strat firmy wynikaj�cych z tego tytu�u.<br>
12) Zlecenie realizowane jest na obszarze <b>$mieszkan</b> mieszka�, wed�ug danych z systemu BIALL-NET. Zak��da si�, �e mog� by� od tej liczby odst�pstwa, kt�re zostan� zweryfikowane na podstawie niniejszego zlecenia. <br>
</font>
<pre>

     ZLECENIODAWCA                                        ZLECENIOBIORCA

     .............                                        <b>$ZLECENIOBIORCA</b>
</pre>



</td></tr>";


echo "</table>";
echo " .<p style=\"page-break-before: always\">\n . ";




$font="-3";
echo "<table border=1 cellspacing=0 cellpadding=0 width=100%>";
 echo "\n<tr><td colspan=14>ZLECENIE KONTROLI DYSTRYBUCJI<font size=\"-4\">SupereditMarketingModule &copy;2007 Arkadiusz Binder</font></td></tr>";
echo "<tr><td rowspan=2 width=5><font size=$font>lp</font></td><td rowspan=2><font size=$font>Data</font></td><td rowspan=2><font size=$font>Godzina</font></td><td rowspan=2><font size=$font>Ulica/Budynek</font></td>
 <td rowspan=2><font size=$font>Klatka</font></td><td colspan=2><font size=$font>Plakat klatka</font></td><td colspan=2><font size=$font>Ulotka gumka klamka</font>
 </td><td colspan=2><font size=$font>Ulotka skrzynka</font></td>";
  echo "<td colspan=2><font size=$font>Materia� ostatnie pietro</font></td><td rowspan=2 width=90><font size=$font>Inne uwagi</td></tr>";
  echo "<tr><td><font size=$font>JEST</font></td><td><font size=$font>BRAK</font></td> <td><font size=$font>JEST</font></td><td><font size=$font>BRAK</font></td><td><font size=$font>JEST</font></td><td><font size=$font>BRAK</font></td><td><font size=$font>JEST</font></td><td><font size=$font>BRAK</font></td> ";
$i=0;
while ($i <= 30 ) {
 echo "<tr height=5><td width=10><font size=$font>$i</font></td><td>. . </td><td>. . </td><td>. . </td><td>. . </td><td>. . </td><td>. . </td><td>. . </td><td>. . </td><td>. . </td><td>. . </td><td>. . </td><td>. . </td><td>. . </td></tr>\n";

$i++;
}


 echo "<tr><td colspan=2><font size=$font>Imi� i nazwisko sprawdzaj�cego:</font></td><td colspan=4><font size=$font>$NAZWISKO_KONTROLERA</font></td><td colspan=4><font size=$font>Data i numer procesu dystrybucji</font></td><td colspan=5><font size=$font>$DATA_PROCESU_DYSTRYBUCJI / $NUMER_PROCESU_DYSTRYBUCJI</font></td></tr>";
 echo "<tr><td colspan=6 rowspan=2><font size=$font>Obszar dla kontroli:";
  foreach($ULICE_LIST['ULICE'] as $INDEKS_ULICY=>$ULICA) {
   echo " | $ULICA: ";
   foreach($ULICE_LIST['BUDYNKI'][$INDEKS_ULICY] as $INDEKS_BUDYNKU=>$BUDYNEK) {
    echo "$BUDYNEK , ";
   }
  }
 echo "</font></td><td colspan=4><font size=$font>Okres badania:</font></td><td colspan=5><font size=$font>wy��cznie w dniu: $MATERIALY_NALEZY_ROZNIESC_W_DNIU , <br> pomi�dzy godzinami od: $MATERIALY_NALEZY_ROZNIESC_OD_GODZINY do $MATERIALY_NALEZY_ROZNIESC_TEGO_SAMEGO_DNIA_DO_GODZINY </font></td></tr>";
 echo "<tr><td colspan=4><font size=$font>Termin i miejsce dostarczenia raportu kontroli</font></td><td colspan=5><font size=$font>raport nale�y dostarczy� w $TERMIN_DATA_DOSTARCZENIA_RAPORTU_KONTROLI do godziny $GODZINA_DOSTARCZENIA_RAPORTU_KONTROLI w miejsce $MIEJSCE_DOSTARCZENIA_RAPORTU </font></td></tr>";
 echo "<tr><td colspan=14><font size=$font>Regulamin wype�nienia raportu: 1. Zleceniobiorca zobowi�zuje si� sprawdzi� czy materia�y reklamowe zosta�y rozmieszczone na wyznaczonym obszarze dzia�ania.
2.Wyniki kontroli rozmieszczenia materia��w reklamowych nale�y zapisywa� w trakcie trwania kontroli w otrzymanym Raporcie kontroli ulotek. Musi on zawiera� rzetelnie i czytelnie wype�nione pola.
Spos�b wype�nienia niniejszego raportu wygl�da nast�puj�co: W kolumnie .Data. oraz .Godzina. nale�y wpisa� ka�dorazowo dat� oraz godzin� rozpocz�cia czynno�ci na danym budynku, w kolumnie .Ulica budynek. wpisa� stosownany skr�t np. .CH7. to Ca�ubi�skiego 7 w kolumnie .klatka. wpisa� A,B lub C(i tak dalej), w pozosta�ych kolumnach umiesci� X w stosownym miejscu
w zale�no�ci czy by� materia� reklamowy, czy nie; w .Inne/Uwagi. wpisywa� np. czy by�y problemy z wej�ciem do budynku, je�li tak, to kto nie chcia� wpu�cici�.
3. Zleceniobiorca zobowi�zuje si� przeprowadzi� kontrol� w wy�ej okre�lonym przedziale czasu  .
4. Raport kontroli ulotek nale�y dostarczy� zgodnie z zapisami w tabeli wzgl�dnie czytelny skan na adres e-mail: marketing@biall.net.pl , z zaznaczeniem w temacie Daty i numeru procesu dystrybucji : $DATA_PROCESU_DYSTRYBUCJI / $NUMER_PROCESU_DYSTRYBUCJI .
5. Raporty kontroli ulotek winny by� wype�nione wg schematu w raporcie (oznaczonego w pkt. x), czyli np. w polu .godzina/data. nale�y umie�ci� dat� i godzin� rozpocz�cia kontroli rozmieszczenia materia��w na danym budynku. Niewype�nienie tych p�l lub/i raportu jest r�wnoznaczne z niewykonaniem zlecenia. Brane b�d� wy��cznie pod uwag� fragmenty raportu wype�nione w pe�ni, rzetelnie i czytelnie. Wszystkie inne pola (rz�dy arkusza) wype�nione cz��ciowo lub w og�le, b�d� traktowane jakoby w danym adresie dystrybucja nie mia�a miejsca. Od momentu oddania raportu  kontroli ulotek zakazane jest uzupe�nianie raportu przez kt�r�kolwiek ze stron. Wpisy w danym rz�dzie w raporcie winny by� wype�nione jednym i tym samym d�ugopisem.
6. Zlecenie realizowane jest tylko wyznaczonym obszarze (Obszar dla kontroli).
7. Nie wywi�zanie si� z wy�ej wymienionych zada� r�wnoznaczne jest z nie wykonaniem powierzonej pracy, co si� wi��e brakiem wynagrodzenia a nawet pokryciem strat firmy wynikaj�cych z tego tytu�u. </font></td></tr>";
echo "</table>";




} //EOF IF


if ($_GET['ZLECENIE_BADAN_1']) include('budynki-ZLECENIE_BADAN_1.php');
if ($_GET['DODAJ_WYNIK_ANKIETY']) include('budynki-DODAJ_WYNIK_ANKIETY.php');





if($_GET[GDZIE_ROZNIESC_ZRYWKI]) {
echo "SZUKANIE MIEJSC DO ROZNIESIENIA ZRYWEK <form action=$PHP_SELF method=\"GET\">";
echo "<input type=hidden name=ADD value=ADD>";
echo "<input type=hidden name=GDZIE_ROZNIESC_ZRYWKI value=1>";
echo "<table border=1><tr><td>";
echo "Dodaj Lancuch dla poszukiwan ulicy , (zakoncz znakiem %) - 500 rekordow</td><td>  <input type=text name=S_ADDRESS_STREET size=3 value=$_GET[S_ADDRESS_STREET]></td></tr>";
echo "<tr><td colspan=1><input type=submit name=ADD value=SZUKAJ></td><td>M_REWIR</td><td>T_NETWORK_SERVER</td><td>M_ZRYWKA_DATE</td><td>M_ZRYWKA_NUMBER</td></tr>";

if($_GET[S_ADDRESS_STREET]) ZAP_SQL("SELECT * FROM BUILDINGS where S_ADDRESS_STREET like '".$_GET[S_ADDRESS_STREET]."' or M_REWIR like '".$_GET[S_ADDRESS_STREET]."' or T_NETWORK_SERVER like '".$_GET[S_ADDRESS_STREET]."' order by M_ZRYWKA_DATE  limit 500 ");

while($DWA=mysql_fetch_array($result)) {


echo "<tr><td>".$DWA[S_ADDRESS_STREET]." </td><td> ".$DWA[M_REWIR]." </td><td> ".$DWA[T_NETWORK_SERVER]." </td><td>".$DWA[M_ZRYWKA_DATE]."</td><td>".$DWA[M_ZRYWKA_NUMBER]." ";
echo "</td></tr>";

 }

echo "</table>";

} //EOF IF



//print_r($_SESSION[USERS2_MARKETING_COLUMN]);





if($_GET[DODAJ_RAPORT_ULOTEK]) {
echo "DODAWANIE RAPORTOW (np gdzie zostaly rozniesione zrywki , ulotki itp,
podaj date dzialania adres oraz parametry osoby ktora wykonala prace, co bedzie niezbedne do naliczenia jej wynagrodzenia)
 <form action=$PHP_SELF method=\"GET\">";
$_SESSION[BUILDINGS_COLUMN][EDITRECORD][T_WORKPOINTS_USER]=$_GET[T_WORKPOINTS_USER];
$_SESSION[BUILDINGS_COLUMN][EDITRECORD][T_WORKPOINTS_DATE]=$_GET[T_WORKPOINTS_DATE];
$_SESSION[BUILDINGS_COLUMN][EDITRECORD][T_WORKPOINTS_TYPE]=$_GET[T_WORKPOINTS_TYPE];
$_SESSION[BUILDINGS_COLUMN][EDITRECORD][M_ZRYWKA_DATE]=$_GET[M_ZRYWKA_DATE];

echo "STALE DANE DO SZYBKIEGO WPISYWANIA <br>Autor PRAC: (Inicjaly Handlowca) / @2012-05 nazwa konta z SE ";
SEF('T_WORKPOINTS_USER_SELECT');

T_WORKPOINTS_USER_SELECT();

//echo "<input type=text name=T_WORKPOINTS_USER value=".$_SESSION[BUILDINGS_COLUMN][EDITRECORD][T_WORKPOINTS_USER].">";
echo "<br>DATA PRAC: (YYYY-MM-DD) <input type=text name=T_WORKPOINTS_DATE value=".$_SESSION[BUILDINGS_COLUMN][EDITRECORD][T_WORKPOINTS_DATE].">";
echo "<br>TYP PRAC:  ".$_SESSION[BUILDINGS_COLUMN][EDITRECORD][T_WORKPOINTS_TYPE]." ";
echo "<br>M_ZRYWKA_DATE:  ".$_SESSION[BUILDINGS_COLUMN][EDITRECORD][M_ZRYWKA_DATE]." ";

echo "<input type=hidden name=ADD value=ADD>";
echo "<input type=hidden name=DODAJ_RAPORT_ULOTEK value=1>";
echo "<table border=1><tr><td>";
echo "SKROT ULICY z Nr Budynku (np CI50 dla CIESZYNSKIEGO 50 ) :</td><td>  <input type=text name=S_ADDRESS_STREET size=20 value=$_GET[S_ADDRESS_STREET]></td></tr>";
echo "<tr><td colspan=2><input type=submit name=ADD value=SZUKAJ></td></tr>";

if($_GET[S_ADDRESS_STREET]) ZAP_SQL("SELECT * FROM BUILDINGS where S_ADDRESS_STREET='".$_GET[S_ADDRESS_STREET]."' limit 1 ");

while($DWA=mysql_fetch_array($result)) {

//echo "I_OPER to $DWA[I_OPER] ";
//print_r($_GET);


$NAME="M_ZRYWKA_NUMBER";$VALUE=$DWA[$NAME];$TYPE=$_SESSION[BUILDINGS_COLUMN][TYPE][$NAME];$DESC_TO_LANG=$_SESSION[BUILDINGS_COLUMN][DESC_TO_LANG][$NAME];
echo "<tr><td>$NAME($DESC_TO_LANG)</td><td>";GETFORMITEM($VALUE,$TYPE,$NAME);echo "</td></tr>";
$NAME="M_ZRYWKA_DATE";$VALUE=$_SESSION[BUILDINGS_COLUMN][EDITRECORD][M_ZRYWKA_DATE];$TYPE=$_SESSION[BUILDINGS_COLUMN][TYPE][$NAME];$DESC_TO_LANG=$_SESSION[BUILDINGS_COLUMN][DESC_TO_LANG][$NAME];
echo "<tr><td>$NAME($DESC_TO_LANG)</td><td>";GETFORMITEM($VALUE,$TYPE,$NAME);echo "(DANE SUGEROWANE!)</td></tr>";

$NAME="T_WORKPOINTS_DATE";$VALUE=$_SESSION[BUILDINGS_COLUMN][EDITRECORD][T_WORKPOINTS_DATE];$TYPE=$_SESSION[BUILDINGS_COLUMN][TYPE][$NAME];$DESC_TO_LANG=$_SESSION[BUILDINGS_COLUMN][DESC_TO_LANG][$NAME];
echo "<tr><td>$NAME($DESC_TO_LANG)</td><td>";GETFORMITEM($VALUE,$TYPE,$NAME);echo "(DANE SUGEROWANE!)</td></tr>";







$NAME="S_OTHER_INFO";$VALUE=$DWA[$NAME];$TYPE=$_SESSION[BUILDINGS_COLUMN][TYPE][$NAME];$DESC_TO_LANG=$_SESSION[BUILDINGS_COLUMN][DESC_TO_LANG][$NAME];
echo "<tr><td>$NAME($DESC_TO_LANG)</td><td>";GETFORMITEM($VALUE,$TYPE,$NAME);echo "</td></tr>";

$NAME="T_WORKPOINTS_USER";$VALUE=$_SESSION[BUILDINGS_COLUMN][EDITRECORD][T_WORKPOINTS_USER];$TYPE=$_SESSION[BUILDINGS_COLUMN][TYPE][$NAME];$DESC_TO_LANG=$_SESSION[BUILDINGS_COLUMN][DESC_TO_LANG][$NAME];
//$_SESSION[USERS2_MARKETING_COLUMN][EDITRECORD][T_WORKPOINTS_USER]=$DWA[$NAME];
echo "<tr><td>$NAME($DESC_TO_LANG)</td><td>";T_WORKPOINTS_USER_SELECT();;echo "(DANE SUGEROWANE!)</td></tr>";

$NAME="T_WORKPOINTS_TYPE";$VALUE=$_SESSION[BUILDINGS_COLUMN][EDITRECORD][T_WORKPOINTS_TYPE];$TYPE=$_SESSION[BUILDINGS_COLUMN][TYPE][$NAME];$DESC_TO_LANG=$_SESSION[BUILDINGS_COLUMN][DESC_TO_LANG][$NAME];
echo "<tr><td>$NAME($DESC_TO_LANG)</td><td>";GETFORMITEM($VALUE,$TYPE,$NAME);echo "(DANE SUGEROWANE!)</td></tr>";

echo "<tr><td colspan=2><input type=submit name=ADD_VERIFIED value=ADD_VERIFIED></td></tr>";

//print_r($_SESSION[BUILDINGS_COLUMN][DESC]);
if($_GET[ADD_VERIFIED]) {
     $ZAP_UPD_VAL="update BUILDINGS set ID=ID ";
     $ZAP_UPD_HIST_FIELD="A_RECORD_UPDATE_DATE ,  A_RECORD_UPDATE_AUTHOR , ID_USERS2  ";
     $ZAP_UPD_HIST_VAL=" now() , '".$_SESSION['AUTHORIZE_USER']."' , ID  ";
   foreach($_GET as $GET_KEY => $GET_VAL) {
//     echo "  KEY: $GET_KEY VAL: $GET_VAL <br>\n";
     if(in_array($GET_KEY,$_SESSION[BUILDINGS_COLUMN][DESC])&& $GET_KEY != "S_ADDRESS_STREET"  ) {
       $ZAP_UPD_VAL.=" , $GET_KEY='$GET_VAL' ";
       if(((!strstr($DWA[$GET_KEY],"$GET_VAL")) || ($GET_KEY == "T_WORKPOINTS_USER") || ($GET_KEY == "T_WORKPOINTS_TYPE")  ) ) {
//        echo "!strstr:$GET_KEY($DWA[$GET_KEY],$GET_VAL)";
        $ZAP_UPD_HIST_FIELD.=", $GET_KEY ";
        $ZAP_UPD_HIST_VAL.=", '$GET_VAL' ";
       }
     }
   }
    $ZAP_UPD_VAL.=" where S_ADDRESS_STREET='".$_GET[S_ADDRESS_STREET]."' limit 1 ; "  ;
    $ZAP_UPD_HIST="insert into BUILDINGS_HIST  ( $ZAP_UPD_HIST_FIELD ) select $ZAP_UPD_HIST_VAL from BUILDINGS where S_ADDRESS_STREET='".$_GET[S_ADDRESS_STREET]."' limit 1 ; "  ;



ZAP_SQL(" $ZAP_UPD_VAL ");

//echo "<br>UPDATE: $ZAP_UPD_VAL \n";
//echo "<br>HISTORY: $ZAP_UPD_HIST \n";
ZAP_SQL(" $ZAP_UPD_HIST ");

if(mysql_affected_rows($result)) echo "<br>AKTUALIZOWANO <b> ". mysql_affected_rows($result) ." </b> REKORDOW EOL <br>";
 else echo "<br><font color=red> ZAKTUALIZOWANO lub NIE REKORD, dla $_GET[S_ADDRESS_STREET] ???  </font><br>";
}


}
echo "</table>";










} //EOF if($_GET[DODAJ_RAPORT_ULOTEK])




if ($_GET['DODAJ_REKORDY_MIESZKAN']) {
	include("budynki-DODAJ_REKORDY_MIESZKAN.php");
}




if ($_GET['STATYSTYKA_TABELE']) {
	SEF('STATYSTYKA_TABELE');
	STATYSTYKA_TABELE();
}
if (0) {// export to file superedit-STATYSTYKA_TABELE.php //$_GET[STATYSTYKA_TABELE]) {
//by plabudda 2012-03-26: removed after ADD FOREIGN KEY (`T_TELBOX_BUILDING_IN`)
// echo "<br> Wykonuje UPDATE USERS2_MARKETING SET T_TELBOX_BUILDING_IN=SUBSTRING_INDEX(S_ADDRESS_STREET,'/',1)<br> ";
# ZAP_SQL("UPDATE USERS2_MARKETING SET T_TELBOX_BUILDING_IN=S_ADDRESS_STREET");
// ZAP_SQL("UPDATE USERS2_MARKETING SET T_TELBOX_BUILDING_IN=SUBSTRING_INDEX(S_ADDRESS_STREET,'/',1)");
  $ZAP_SQL="drop table if exists temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL"; echo "<br><br> Wykonuje $ZAP_SQL \n";
 ZAP_SQL($ZAP_SQL);
  $ZAP_SQL="drop table if exists temp_USERS2_INTERNET_STATUS_VOIP_NORMAL"; echo "<br><br> Wykonuje $ZAP_SQL \n";
 ZAP_SQL($ZAP_SQL);
  $ZAP_SQL="drop table if exists temp_USERS2_INTERNET_STATUS_TV_NORMAL"; echo "<br><br> Wykonuje $ZAP_SQL \n";
 ZAP_SQL($ZAP_SQL);

//before 2012-09-24 Bindera:   $ZAP_SQL="create table temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL select ID,S_ADDRESS_STREET,USERS2_INTERNET_STATUS , P_DEALEXPIRE  from temp_USERS2_INTERNET_STATUS where ( USERS2_INTERNET_STATUS like 'NORMAL%' or USERS2_INTERNET_STATUS like 'WAITING%' ) and USERS2_INTERNET_STATUS not like '%VOIP%' group by S_ADDRESS_STREET ;";echo "<br><br> Wykonuje $ZAP_SQL \n";
  $ZAP_SQL="create table temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL select ID,S_ADDRESS_STREET,USERS2_INTERNET_STATUS , P_DEALEXPIRE  from temp_USERS2_INTERNET_STATUS where ( USERS2_INTERNET_STATUS like 'NORMAL%' or USERS2_INTERNET_STATUS like 'WAITING%' ) and NAME_LIST_SERVICES  like 'USERS2' group by S_ADDRESS_STREET ;";echo "<br><br> Wykonuje $ZAP_SQL \n";
 ZAP_SQL($ZAP_SQL);
  $ZAP_SQL="alter table temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL add index(S_ADDRESS_STREET)"; echo "<br><br> Wykonuje $ZAP_SQL \n";
  ZAP_SQL($ZAP_SQL);
//before 2012-09-24   $ZAP_SQL="create table temp_USERS2_INTERNET_STATUS_VOIP_NORMAL select ID,S_ADDRESS_STREET,USERS2_INTERNET_STATUS , P_DEALEXPIRE  from temp_USERS2_INTERNET_STATUS where ( USERS2_INTERNET_STATUS like 'NORMAL%' or USERS2_INTERNET_STATUS like 'WAITING%' ) and USERS2_INTERNET_STATUS  like '%VOIP%' group by S_ADDRESS_STREET ;";echo "<br><br> Wykonuje $ZAP_SQL \n";
  $ZAP_SQL="create table temp_USERS2_INTERNET_STATUS_VOIP_NORMAL select ID,S_ADDRESS_STREET,USERS2_INTERNET_STATUS , P_DEALEXPIRE  from temp_USERS2_INTERNET_STATUS where ( USERS2_INTERNET_STATUS like 'NORMAL%' or USERS2_INTERNET_STATUS like 'WAITING%' ) and NAME_LIST_SERVICES  like 'VOIP' group by S_ADDRESS_STREET ;";echo "<br><br> Wykonuje $ZAP_SQL \n";
 ZAP_SQL($ZAP_SQL);
  $ZAP_SQL="alter table temp_USERS2_INTERNET_STATUS_VOIP_NORMAL add index(S_ADDRESS_STREET)"; echo "<br><br> Wykonuje $ZAP_SQL \n";
  ZAP_SQL($ZAP_SQL);


//before 2012-09-24 by SQIX  $ZAP_SQL="create table temp_USERS2_INTERNET_STATUS_TV_NORMAL select ID,S_ADDRESS_STREET,concat(A_STATUS_BILLING_USERS,'.',A_STATUS,'.',P_SERVICE,'.', SERVICES_ABONAMENT_VALUE) as A_STATUS_BILLING_USERS , DEALS_TABLE_P_DEALDATE_TERM as P_DEALEXPIRE   from SES_TV_A  where A_STATUS_BILLING_USERS like '%NORMAL%' or A_STATUS_BILLING_USERS like '%WAITING%' group by S_ADDRESS_STREET ;";echo "<br><br> Wykonuje $ZAP_SQL \n";
  $ZAP_SQL="create table temp_USERS2_INTERNET_STATUS_TV_NORMAL select ID,S_ADDRESS_STREET,USERS2_INTERNET_STATUS , P_DEALEXPIRE  from temp_USERS2_INTERNET_STATUS where ( USERS2_INTERNET_STATUS like 'NORMAL%' or USERS2_INTERNET_STATUS like 'WAITING%' ) and NAME_LIST_SERVICES  like 'TV' group by S_ADDRESS_STREET ;";echo "<br><br> Wykonuje $ZAP_SQL \n";

 ZAP_SQL($ZAP_SQL);
  $ZAP_SQL="alter table temp_USERS2_INTERNET_STATUS_TV_NORMAL add index(S_ADDRESS_STREET)"; echo "<br><br> Wykonuje $ZAP_SQL \n";
  ZAP_SQL($ZAP_SQL);


  $ZAP_SQL="update USERS2_MARKETING, temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL set USERS2_MARKETING.I_OPER='BN' , USERS2_MARKETING.I_OPER_FIN=temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL.P_DEALEXPIRE where USERS2_MARKETING.S_ADDRESS_STREET=temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL.S_ADDRESS_STREET ; "; echo "<br><br> Wykonuje $ZAP_SQL \n";
  ZAP_SQL($ZAP_SQL);

//Tabela do odlaczen 08-02-22
  $ZAP_SQL="drop table if exists temp_USERS2_INTERNET_STATUS_OFF_HARD"; echo "<br><br> Wykonuje $ZAP_SQL \n";
 ZAP_SQL($ZAP_SQL);


  $ZAP_SQL="create table temp_USERS2_INTERNET_STATUS_OFF_HARD select t1.ID , t1.S_ADDRESS_STREET, t2.ID as T2_ID from USERS2_MARKETING as t1 left join temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL as t2 on t2.S_ADDRESS_STREET=t1.S_ADDRESS_STREET where t2.ID is NULL and t1.I_OPER='BN' ; ";  echo "<br><br> Wykonuje $ZAP_SQL \n";
  ZAP_SQL($ZAP_SQL);
  $ZAP_SQL="update USERS2_MARKETING, temp_USERS2_INTERNET_STATUS_OFF_HARD set USERS2_MARKETING.I_OPER='NIEWIADOMO' where  USERS2_MARKETING.I_OPER='BN'  and USERS2_MARKETING.S_ADDRESS_STREET=temp_USERS2_INTERNET_STATUS_OFF_HARD.S_ADDRESS_STREET ; "; echo "<br><br> Wykonuje $ZAP_SQL \n";
  ZAP_SQL($ZAP_SQL);


  $ZAP_SQL="update USERS2_MARKETING, temp_USERS2_INTERNET_STATUS_VOIP_NORMAL set USERS2_MARKETING.T_OPER='BN' , USERS2_MARKETING.T_OPER_FIN=temp_USERS2_INTERNET_STATUS_VOIP_NORMAL.P_DEALEXPIRE where USERS2_MARKETING.S_ADDRESS_STREET=temp_USERS2_INTERNET_STATUS_VOIP_NORMAL.S_ADDRESS_STREET ; "; echo "<br><br> Wykonuje $ZAP_SQL \n";
  ZAP_SQL($ZAP_SQL);

  $ZAP_SQL="update USERS2_MARKETING, temp_USERS2_INTERNET_STATUS_TV_NORMAL set USERS2_MARKETING.TV_OPER='BN' , USERS2_MARKETING.TV_OPER_FIN=temp_USERS2_INTERNET_STATUS_TV_NORMAL.P_DEALEXPIRE where USERS2_MARKETING.S_ADDRESS_STREET=temp_USERS2_INTERNET_STATUS_TV_NORMAL.S_ADDRESS_STREET ; "; echo "<br><br> Wykonuje $ZAP_SQL \n";
  ZAP_SQL($ZAP_SQL);

  $ZAP_SQL="drop table if exists USERS2_MARKETING_OVERWIEV"; echo "<br><br> Wykonuje $ZAP_SQL \n";
  ZAP_SQL($ZAP_SQL);

 $ZAP_SQL="drop table if exists USERS2_MARKETING_OVERWIEV_REWIR"; echo "<br><br> Wykonuje $ZAP_SQL \n";
  ZAP_SQL($ZAP_SQL);


  $ZAP_SQL="update  USERS2_MARKETING , BUILDINGS set
	 USERS2_MARKETING.M_REWIR=BUILDINGS.M_REWIR
	where USERS2_MARKETING.T_TELBOX_BUILDING_IN=BUILDINGS.S_ADDRESS_STREET and  BUILDINGS.M_REWIR!='' and BUILDINGS.M_REWIR is not null  "; echo "<br><br> Wykonuje $ZAP_SQL \n";
  ZAP_SQL($ZAP_SQL);



//by plabudda 2012-03-26: removed after ADD FOREIGN KEY (`T_TELBOX_BUILDING_IN`)
// $ZAP_SQL="select ID,T_TELBOX_BUILDING_IN from USERS2_MARKETING where T_TELBOX_BUILDING_IN like '%' ;";
// ZAP_SQL($ZAP_SQL);
// $result2=$result;
// while($h=mysql_fetch_row($result2)) {
//echo "$h[0] $h[1] ";

//by Bzyk 2007-03-12
#$T_TELBOX_BUILDING_IN=ereg_replace("([[:alpha:]]*)([[:digit:]]*)?([[:alpha:]])?(/[[:alnum:]]*)?$", "\\1\\2", $h[1]);
//$T_TELBOX_BUILDING_IN=ereg_replace("([[:alpha:]]*)([[:digit:]]*)?([[:alpha:]])?$", "\\1\\2", $h[1]);

#$T_TELBOX_BUILDING_IN=ereg_replace("()[[:alpha:]]?(/[0-9]*)?[[:alpha:]]?$", "\\1", $h[1]);  //ereg_replace("()[[:alpha]?(/[0-9]*)?[[:alpha]?$", "\\1", $string);
// $ZAP_SQL="update USERS2_MARKETING set T_TELBOX_BUILDING_IN='$T_TELBOX_BUILDING_IN' where ID='".$h[0]."' ; ";
//  echo " $ZAP_SQL; <br>\n";
// ZAP_SQL("$ZAP_SQL");
// }



  $ZAP_SQL="update  USERS2_MARKETING , BUILDINGS set
	 USERS2_MARKETING.M_REWIR=BUILDINGS.M_REWIR
	where USERS2_MARKETING.T_TELBOX_BUILDING_IN=BUILDINGS.S_ADDRESS_STREET and  BUILDINGS.M_REWIR!='' and BUILDINGS.M_REWIR is not null  "; echo "<br><br> Wykonuje $ZAP_SQL \n";
  ZAP_SQL($ZAP_SQL);


/* //BYLO przed 2012-04-23 zle dzialalo.
  $ZAP_SQL="

create table USERS2_MARKETING_OVERWIEV select '' as ID , '' as A_ADM_COMPANY ,
USERS2_MARKETING.T_TELBOX_BUILDING_IN , USERS2_MARKETING.M_REWIR , USERS2_MARKETING.T_NETWORK_SERVER ,
count(temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL.S_ADDRESS_STREET) as ABO_I ,count(USERS2_MARKETING.S_ADDRESS_STREET) as MIESZKAN,
(count(temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL.S_ADDRESS_STREET)/count(USERS2_MARKETING.S_ADDRESS_STREET)*100) as NAS_I ,
(count(UM_I_BADAN.ID)/count(USERS2_MARKETING.S_ADDRESS_STREET)*100) as BADAN_I,
(count(UM_I_ANKIET.ID)/count(USERS2_MARKETING.S_ADDRESS_STREET)*100) as ANKIET_I,
count(UM_I_UPC.ID)/count(UM_I_ANKIET.ID)*100 as PR_I_UPC,
count(UM_I_INNY.ID)/count(UM_I_ANKIET.ID)*100 as PR_I_INNY,
count(UM_I_NSM.ID)/count(UM_I_ANKIET.ID)*100 as PR_I_NSM,
count(UM_I_TP.ID)/count(UM_I_ANKIET.ID)*100 as PR_I_TP,
count(UM_I_EIA.ID)/count(UM_I_ANKIET.ID)*100 as PR_I_EIA,
count(UM_I_BRAK.ID)/count(UM_I_ANKIET.ID)*100 as PR_I_BRAK,
count(UM_I_KONKUR.ID)/count(UM_I_ANKIET.ID)*100 as PR_I_KONKUR,
count(UM_I_ZAINT.ID)/count(UM_I_ANKIET.ID)*100 as PR_I_ZAINT,

count(temp_USERS2_INTERNET_STATUS_VOIP_NORMAL.S_ADDRESS_STREET) as ABO_T,
(count(temp_USERS2_INTERNET_STATUS_VOIP_NORMAL.S_ADDRESS_STREET)/count(USERS2_MARKETING.S_ADDRESS_STREET)*100) as NAS_T ,
(count(UM_T_BADAN.ID)/count(USERS2_MARKETING.S_ADDRESS_STREET)*100) as BADAN_T,
(count(UM_T_ANKIET.ID)/count(USERS2_MARKETING.S_ADDRESS_STREET)*100) as ANKIET_T,
count(UM_T_BRAK.ID)/count(UM_T_ANKIET.ID)*100 as PR_T_BRAK,
count(UM_T_KONKUR.ID)/count(UM_T_ANKIET.ID)*100 as PR_T_KONKUR,
count(UM_T_ZAINT.ID)/count(UM_T_ANKIET.ID)*100 as PR_T_ZAINT ,


count(temp_USERS2_INTERNET_STATUS_TV_NORMAL.S_ADDRESS_STREET) as ABO_TV,
(count(temp_USERS2_INTERNET_STATUS_TV_NORMAL.S_ADDRESS_STREET)/count(USERS2_MARKETING.S_ADDRESS_STREET)*100) as NAS_TV ,
(count(UM_TV_BADAN.ID)/count(USERS2_MARKETING.S_ADDRESS_STREET)*100) as BADAN_TV,
(count(UM_TV_ANKIET.ID)/count(USERS2_MARKETING.S_ADDRESS_STREET)*100) as ANKIET_TV,
count(UM_TV_UPC.ID)/count(UM_TV_ANKIET.ID)*100 as PR_TV_UPC,
count(UM_TV_INNY.ID)/count(UM_TV_ANKIET.ID)*100 as PR_TV_INNY,
count(UM_TV_JARSAT.ID)/count(UM_TV_ANKIET.ID)*100 as PR_TV_JARSAT,
count(UM_TV_BRAK.ID)/count(UM_T_ANKIET.ID)*100 as PR_TV_BRAK,
count(UM_TV_KONKUR.ID)/count(UM_T_ANKIET.ID)*100 as PR_TV_KONKUR,
count(UM_TV_ZAINT.ID)/count(UM_T_ANKIET.ID)*100 as PR_TV_ZAINT




from USERS2_MARKETING as USERS2_MARKETING
left join temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL on (temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL.S_ADDRESS_STREET=USERS2_MARKETING.S_ADDRESS_STREET)
left join USERS2_MARKETING as UM_I_BADAN on (UM_I_BADAN.ID=USERS2_MARKETING.ID and UM_I_BADAN.I_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)   )
left join USERS2_MARKETING as UM_I_ANKIET on (UM_I_ANKIET.ID=USERS2_MARKETING.ID and (UM_I_ANKIET.I_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000) or UM_I_ANKIET.I_OPER='BN' )   )
left join USERS2_MARKETING as UM_I_UPC on UM_I_UPC.ID=UM_I_ANKIET.ID and UM_I_UPC.I_OPER='UPC'
left join USERS2_MARKETING as UM_I_INNY on UM_I_INNY.ID=UM_I_ANKIET.ID and UM_I_INNY.I_OPER='INNY'
left join USERS2_MARKETING as UM_I_NSM on UM_I_NSM.ID=UM_I_ANKIET.ID and UM_I_NSM.I_OPER='NSM'
left join USERS2_MARKETING as UM_I_TP on UM_I_TP.ID=UM_I_ANKIET.ID and UM_I_TP.I_OPER='TP'
left join USERS2_MARKETING as UM_I_EIA on UM_I_EIA.ID=UM_I_ANKIET.ID and UM_I_EIA.I_OPER='EIA'
left join USERS2_MARKETING as UM_I_BRAK on UM_I_BRAK.ID=UM_I_ANKIET.ID and UM_I_BRAK.I_OPER='BRAK'
left join USERS2_MARKETING as UM_I_KONKUR on (UM_I_KONKUR.ID=UM_I_ANKIET.ID and (UM_I_KONKUR.I_OPER!='BN' and UM_I_KONKUR.I_OPER!='BRAK' and  UM_I_KONKUR.I_OPER!='NIEWIADOMO'))
left join USERS2_MARKETING as UM_I_ZAINT on UM_I_ZAINT.ID=UM_I_ANKIET.ID and UM_I_ZAINT.I_OPER_ZAINT>2 and  UM_I_ZAINT.I_OPER_ZAINT!='NIEWIADOMO'

left join temp_USERS2_INTERNET_STATUS_VOIP_NORMAL on (temp_USERS2_INTERNET_STATUS_VOIP_NORMAL.S_ADDRESS_STREET=USERS2_MARKETING.S_ADDRESS_STREET)
left join USERS2_MARKETING as UM_T_BADAN on (UM_T_BADAN.ID=USERS2_MARKETING.ID and UM_T_BADAN.T_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)   )
left join USERS2_MARKETING as UM_T_ANKIET on (UM_T_ANKIET.ID=USERS2_MARKETING.ID and (UM_T_ANKIET.T_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000) or UM_T_ANKIET.T_OPER='BN' )   )
left join USERS2_MARKETING as UM_T_BRAK on UM_T_BRAK.ID=UM_T_ANKIET.ID and UM_T_BRAK.T_OPER='BRAK'
left join USERS2_MARKETING as UM_T_KONKUR on (UM_T_KONKUR.ID=UM_T_ANKIET.ID and (UM_T_KONKUR.T_OPER!='BN' and UM_T_KONKUR.T_OPER!='BRAK' and  UM_T_KONKUR.T_OPER!='NIEWIADOMO'))
left join USERS2_MARKETING as UM_T_ZAINT on UM_T_ZAINT.ID=UM_T_ANKIET.ID and UM_T_ZAINT.T_OPER_ZAINT>2 and  UM_T_ZAINT.T_OPER_ZAINT!='NIEWIADOMO'

left join temp_USERS2_INTERNET_STATUS_TV_NORMAL on (temp_USERS2_INTERNET_STATUS_TV_NORMAL.S_ADDRESS_STREET=USERS2_MARKETING.S_ADDRESS_STREET)
left join USERS2_MARKETING as UM_TV_BADAN on (UM_TV_BADAN.ID=USERS2_MARKETING.ID and UM_TV_BADAN.TV_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)   )
left join USERS2_MARKETING as UM_TV_ANKIET on (UM_TV_ANKIET.ID=USERS2_MARKETING.ID and (UM_TV_ANKIET.TV_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000) or UM_TV_ANKIET.TV_OPER='BN' )   )
left join USERS2_MARKETING as UM_TV_UPC on UM_TV_UPC.ID=UM_I_ANKIET.ID and UM_TV_UPC.TV_OPER='UPC'
left join USERS2_MARKETING as UM_TV_INNY on UM_TV_INNY.ID=UM_TV_ANKIET.ID and UM_TV_INNY.TV_OPER='INNY'
left join USERS2_MARKETING as UM_TV_JARSAT on UM_TV_JARSAT.ID=UM_TV_ANKIET.ID and UM_TV_JARSAT.TV_OPER='JARSAT'
left join USERS2_MARKETING as UM_TV_BRAK on UM_TV_BRAK.ID=UM_TV_ANKIET.ID and UM_TV_BRAK.TV_OPER='BRAK'
left join USERS2_MARKETING as UM_TV_KONKUR on (UM_TV_KONKUR.ID=UM_TV_ANKIET.ID and (UM_TV_KONKUR.TV_OPER!='BN' and UM_TV_KONKUR.TV_OPER!='BRAK' and  UM_TV_KONKUR.TV_OPER!='NIEWIADOMO'))
left join USERS2_MARKETING as UM_TV_ZAINT on UM_TV_ZAINT.ID=UM_TV_ANKIET.ID and UM_TV_ZAINT.TV_OPER_ZAINT>2 and  UM_TV_ZAINT.TV_OPER_ZAINT!='NIEWIADOMO'

group by USERS2_MARKETING.T_TELBOX_BUILDING_IN
order by USERS2_MARKETING.M_REWIR DESC ,USERS2_MARKETING.T_TELBOX_BUILDING_IN

;

  "; echo "<br><br> Wykonuje $ZAP_SQL \n ";
 ZAP_SQL($ZAP_SQL);

 */

$COLSFORSTATS=array('I','T','TV');
//$COLSFORSTATS=array('I');

$COLSFORSTATS_OPERS=array('INNY','UPC','NSM','TP','EIA','BRAK','JARSAT');



 //BEGIN MIESZKANIA STATSY

  $ZAP_SQL="
create table USERS2_MARKETING_OVERWIEV
select '' as ID ,
USERS2_MARKETING.T_TELBOX_BUILDING_IN , USERS2_MARKETING.M_REWIR
 ,  BUILDINGS.T_NETWORK_SERVER
, sum(if(USERS2_MARKETING.I_OPER='BN',1,0) ) as ABO_I ,count(USERS2_MARKETING.S_ADDRESS_STREET) as MIESZKAN
-- FOREACH

,round((sum(        if(
 				(   USERS2_MARKETING.I_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)  or
 				    USERS2_MARKETING.T_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)  or
 				    USERS2_MARKETING.TV_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)
			  )   ,1,0 )       )   /count(USERS2_MARKETING.S_ADDRESS_STREET)*100),2) as BADAN_I
,round((sum(if(  (  USERS2_MARKETING.I_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)  or
 				    USERS2_MARKETING.T_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)  or
 				     USERS2_MARKETING.TV_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000) or
 				    USERS2_MARKETING.I_OPER='BN' or USERS2_MARKETING.T_OPER='BN' or USERS2_MARKETING.TV_OPER='BN' )  ,1,0    )   )   /count(USERS2_MARKETING.S_ADDRESS_STREET)*100),2) as ANKIET_I

 				    ,BUILDINGS.A_ADM_COMPANY

";

foreach ( $COLSFORSTATS as $FFS ) {
	$ZAP_SQL.=",round((sum(if(USERS2_MARKETING.".$FFS."_OPER='BN',1,0))  / count(USERS2_MARKETING.S_ADDRESS_STREET)*100),2) as NAS_".$FFS." ";


 foreach($COLSFORSTATS_OPERS as $FFFS ) {
	$ZAP_SQL.=", round((
		 sum(       if(USERS2_MARKETING.".$FFS."_OPER='".$FFFS."',1,0)         )    /     sum(       if( (USERS2_MARKETING.".$FFS."_BAD_DATE!='0000-00-00') and (USERS2_MARKETING.".$FFS."_OPER!='BN')  ,1,0 )       )
	             *
	              (
				 count(USERS2_MARKETING.S_ADDRESS_STREET)  -
			 	 sum(if(USERS2_MARKETING.".$FFS."_OPER='BN',1,0))
	               )  / count(USERS2_MARKETING.S_ADDRESS_STREET)  ) *100 ,2) as PR_".$FFS."_".$FFFS."


	        ";

   }

$ZAP_SQL.="

, round( (
	 sum(       if( (USERS2_MARKETING.".$FFS."_OPER!='BN'  and USERS2_MARKETING.".$FFS."_OPER_ZAINT>2  and USERS2_MARKETING.".$FFS."_OPER_ZAINT!='NIEWIADOMO'),1,0)         )
	   /	  sum(       if( (USERS2_MARKETING.".$FFS."_BAD_DATE!='0000-00-00') and (USERS2_MARKETING.".$FFS."_OPER!='BN')  ,1,0 )       )
             *
              (
			 count(USERS2_MARKETING.S_ADDRESS_STREET)  -
		 	 sum(if(USERS2_MARKETING.".$FFS."_OPER='BN',1,0))
               )  / count(USERS2_MARKETING.S_ADDRESS_STREET)  ) *100 ,2)  as PR_".$FFS."_ZAINT


, round ( (
	 sum(       if( (USERS2_MARKETING.".$FFS."_OPER!='BN'  and USERS2_MARKETING.".$FFS."_OPER!='BRAK' and USERS2_MARKETING.".$FFS."_OPER!='NIEWIADOMO'),1,0)         )
	  /     sum(       if( (USERS2_MARKETING.".$FFS."_BAD_DATE!='0000-00-00') and (USERS2_MARKETING.".$FFS."_OPER!='BN')  ,1,0 )       )
             *
              (
			 count(USERS2_MARKETING.S_ADDRESS_STREET)  -
		 	 sum(if(USERS2_MARKETING.".$FFS."_OPER='BN',1,0))
               )  / count(USERS2_MARKETING.S_ADDRESS_STREET)  ) *100 ,2) as PR_".$FFS."_KONKUR
               ";


}
$ZAP_SQL.="
-- EOF FOREACH

from USERS2_MARKETING as USERS2_MARKETING
left join BUILDINGS on BUILDINGS.S_ADDRESS_STREET=USERS2_MARKETING.T_TELBOX_BUILDING_IN

where USERS2_MARKETING.A_STATUS!='DELETED' and BUILDINGS.A_STATUS!='DELETED'
group by USERS2_MARKETING.T_TELBOX_BUILDING_IN
order by USERS2_MARKETING.M_REWIR DESC ,USERS2_MARKETING.T_TELBOX_BUILDING_IN
;

  "; echo "<br><br> Wykonuje <pre> $ZAP_SQL </pre> \n ";
 ZAP_SQL($ZAP_SQL);


 //EOF BEGIN MIESZKANIA STATSY
 // REEWIRY STATSY
  $ZAP_SQL="
create table USERS2_MARKETING_OVERWIEV_REWIR
select '' as ID ,
group_concat(distinct ' ',USERS2_MARKETING.T_TELBOX_BUILDING_IN) as T_TELBOX_BUILDING_IN  , USERS2_MARKETING.M_REWIR
 ,  BUILDINGS.T_NETWORK_SERVER
, sum(if(USERS2_MARKETING.I_OPER='BN',1,0) ) as ABO_I ,count(USERS2_MARKETING.S_ADDRESS_STREET) as MIESZKAN
-- FOREACH

,round((sum(if(USERS2_MARKETING.I_OPER='BN',1,0))  / count(USERS2_MARKETING.S_ADDRESS_STREET)*100),2) as NAS_I
,round((sum(        if(
 				(   USERS2_MARKETING.I_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)  or
 				    USERS2_MARKETING.T_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)  or
 				    USERS2_MARKETING.TV_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)
			  )   ,1,0 )       )   /count(USERS2_MARKETING.S_ADDRESS_STREET)*100),2) as BADAN_I
,round((sum(if(  (  USERS2_MARKETING.I_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)  or
 				    USERS2_MARKETING.T_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)  or
 				     USERS2_MARKETING.TV_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000) or
 				    USERS2_MARKETING.I_OPER='BN' or USERS2_MARKETING.T_OPER='BN' or USERS2_MARKETING.TV_OPER='BN' )  ,1,0    )   )   /count(USERS2_MARKETING.S_ADDRESS_STREET)*100),2) as ANKIET_I
,BUILDINGS.A_ADM_COMPANY
";


foreach ( $COLSFORSTATS as $FFS ) {

 foreach($COLSFORSTATS_OPERS as $FFFS ) {
		$ZAP_SQL.=", round((
		 sum(       if(USERS2_MARKETING.".$FFS."_OPER='".$FFFS."',1,0)         )    /     sum(       if( (USERS2_MARKETING.".$FFS."_BAD_DATE!='0000-00-00') and (USERS2_MARKETING.".$FFS."_OPER!='BN')  ,1,0 )       )
	             *
	              (
				 count(USERS2_MARKETING.S_ADDRESS_STREET)  -
			 	 sum(if(USERS2_MARKETING.".$FFS."_OPER='BN',1,0))
	               )  / count(USERS2_MARKETING.S_ADDRESS_STREET)  ) *100 ,2) as PR_".$FFS."_".$FFFS."


	        ";
  }

$ZAP_SQL.="

, round( (
	 sum(       if( (USERS2_MARKETING.".$FFS."_OPER!='BN'  and USERS2_MARKETING.".$FFS."_OPER_ZAINT>2  and USERS2_MARKETING.".$FFS."_OPER_ZAINT!='NIEWIADOMO'),1,0)         )
	   /	  sum(       if( (USERS2_MARKETING.".$FFS."_BAD_DATE!='0000-00-00') and (USERS2_MARKETING.".$FFS."_OPER!='BN')  ,1,0 )       )
             *
              (
			 count(USERS2_MARKETING.S_ADDRESS_STREET)  -
		 	 sum(if(USERS2_MARKETING.".$FFS."_OPER='BN',1,0))
               )  / count(USERS2_MARKETING.S_ADDRESS_STREET)  ) *100 ,2)  as PR_".$FFS."_ZAINT


, round ( (
	 sum(       if( (USERS2_MARKETING.".$FFS."_OPER!='BN'  and USERS2_MARKETING.".$FFS."_OPER!='BRAK' and USERS2_MARKETING.".$FFS."_OPER!='NIEWIADOMO'),1,0)         )
	  /     sum(       if( (USERS2_MARKETING.".$FFS."_BAD_DATE!='0000-00-00') and (USERS2_MARKETING.".$FFS."_OPER!='BN')  ,1,0 )       )
             *
              (
			 count(USERS2_MARKETING.S_ADDRESS_STREET)  -
		 	 sum(if(USERS2_MARKETING.".$FFS."_OPER='BN',1,0))
               )  / count(USERS2_MARKETING.S_ADDRESS_STREET)  ) *100 ,2) as PR_".$FFS."_KONKUR
               ";


}
$ZAP_SQL.="
-- EOF FOREACH

from USERS2_MARKETING as USERS2_MARKETING
left join BUILDINGS on BUILDINGS.S_ADDRESS_STREET=USERS2_MARKETING.T_TELBOX_BUILDING_IN

where USERS2_MARKETING.A_STATUS!='DELETED' and BUILDINGS.A_STATUS!='DELETED'

group by USERS2_MARKETING.M_REWIR
order by USERS2_MARKETING.M_REWIR DESC ,USERS2_MARKETING.T_TELBOX_BUILDING_IN
;

  "; echo "<br><br> Wykonuje $ZAP_SQL \n ";
 ZAP_SQL($ZAP_SQL);

  //EOF REEWIRY STATSY



 $ZAP_SQL="ALTER TABLE `USERS2_MARKETING_OVERWIEV` CHANGE `ABO_I` `ABO_I` CHAR( 10 ) NOT NULL DEFAULT '0',
 CHANGE `MIESZKAN` `MIESZKAN` CHAR( 10 ) NOT NULL DEFAULT '0',
 CHANGE `NAS_I` `NAS_I` CHAR( 10 ) NULL DEFAULT NULL ,
 CHANGE `ANKIET_I` `ANKIET_I` CHAR( 10 ) NULL DEFAULT NULL ,
 CHANGE `PR_I_UPC` `PR_I_UPC` CHAR( 10 ) NULL DEFAULT NULL ,
 CHANGE `PR_I_INNY` `PR_I_INNY` CHAR( 10 ) NULL DEFAULT NULL ,  CHANGE `PR_I_NSM` `PR_I_NSM` CHAR( 10 ) NULL DEFAULT NULL ,
 CHANGE `PR_I_TP` `PR_I_TP` CHAR( 10 ) NULL DEFAULT NULL ,  CHANGE `PR_I_EIA` `PR_I_EIA` CHAR( 10 ) NULL DEFAULT NULL ,
 CHANGE `PR_I_BRAK` `PR_I_BRAK` CHAR( 10 ) NULL DEFAULT NULL ,  CHANGE `PR_I_KONKUR` `PR_I_KONKUR` CHAR( 10 ) NULL DEFAULT NULL ,
 CHANGE `BADAN_I` `BADAN_I` CHAR( 10 ) NULL DEFAULT NULL ,
 CHANGE `PR_I_ZAINT` `PR_I_ZAINT` CHAR( 10 ) NULL DEFAULT NULL,
 CHANGE `PR_I_JARSAT` `PR_I_JARSAT` CHAR( 10 ) NULL DEFAULT NULL

  "; echo "<br><br> Wykonuje $ZAP_SQL \n";
// ZAP_SQL($ZAP_SQL);


 $ZAP_SQL="ALTER TABLE `USERS2_MARKETING_OVERWIEV_REWIR` CHANGE `ABO_I` `ABO_I` CHAR( 10 ) NOT NULL DEFAULT '0',
 CHANGE `MIESZKAN` `MIESZKAN` CHAR( 10 ) NOT NULL DEFAULT '0',
 CHANGE `NAS_I` `NAS_I` CHAR( 10 ) NULL DEFAULT NULL ,
 CHANGE `ANKIET_I` `ANKIET_I` CHAR( 10 ) NULL DEFAULT NULL ,
 CHANGE `PR_I_UPC` `PR_I_UPC` CHAR( 10 ) NULL DEFAULT NULL ,
 CHANGE `PR_I_INNY` `PR_I_INNY` CHAR( 10 ) NULL DEFAULT NULL ,  CHANGE `PR_I_NSM` `PR_I_NSM` CHAR( 10 ) NULL DEFAULT NULL ,
 CHANGE `PR_I_TP` `PR_I_TP` CHAR( 10 ) NULL DEFAULT NULL ,  CHANGE `PR_I_EIA` `PR_I_EIA` CHAR( 10 ) NULL DEFAULT NULL ,
 CHANGE `PR_I_BRAK` `PR_I_BRAK` CHAR( 10 ) NULL DEFAULT NULL ,  CHANGE `PR_I_KONKUR` `PR_I_KONKUR` CHAR( 10 ) NULL DEFAULT NULL ,
 CHANGE `BADAN_I` `BADAN_I` CHAR( 10 ) NULL DEFAULT NULL ,
 CHANGE `PR_I_ZAINT` `PR_I_ZAINT` CHAR( 10 ) NULL DEFAULT NULL "; echo "<br><br> Wykonuje $ZAP_SQL \n";
// ZAP_SQL($ZAP_SQL);




  ZAP_SQL("alter table USERS2_MARKETING_OVERWIEV add A_RECORD_CREATE_DATE varchar(30)  ;");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add A_RECORD_CREATE_AUTHOR varchar(100) not null  ;");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add A_RECORD_UPDATE_DATE varchar(30)  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add A_RECORD_UPDATE_AUTHOR varchar(100) not null  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add L_APPOITMENT_DATE varchar(30) not null  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add L_APPOITMENT_USER varchar(100) not null  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add L_APPOITMENT_PERIOD varchar(4) not null  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add L_APPOITMENT_INFO varchar(255) not null  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add L_APPOITMENT_TYPE enum('', 'ARRANGED', 'TO_ARRANGE', 'CANCELLED', 'TO_CANCEL', 'RELATE', 'WAIT')  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add A_PROBLEM enum('', 'WARNING', 'PROBLEM', 'SERIOUS', 'UNVERIFIED')  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add A_PROBLEM_DESC varchar(255) not null  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add A_PROBLEM_DATE varchar(30) not null  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add A_STATUS enum('WAITING', 'NORMAL', 'MONITOR', 'WARNING', 'OFF_SOFT', 'OFF_HARD', 'DELETED')  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add A_STATUS_INFO varchar(255) not null  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add A_CLASSIFIED varchar(100) not null  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add T_WORKPOINTS varchar(100) not null  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add T_WORKPOINTS_VALUE varchar(100) not null  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add T_WORKPOINTS_TYPE varchar(100) not null  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add T_WORKPOINTS_USER varchar(100) not null  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add T_WORKPOINTS_DATE varchar(100) not null  ; ");
  ZAP_SQL(" alter table USERS2_MARKETING_OVERWIEV add P_ACCOUNT varchar(40) not null  ; ");
//echo "<br><br> Wykonuje <pre> ".$ZAP_SQL." </pre> \n ";







}
if($_GET[STATYSTYKA_WYSWIETL]){

if($_GET[SORT]) $SORT_ORDER="order by $_GET[SORT] desc ";

$ZAP_SQL=" select
USERS2_MARKETING.T_TELBOX_BUILDING_IN , USERS2_MARKETING.M_REWIR,
count(temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL.S_ADDRESS_STREET) as ABONENTOW ,count(USERS2_MARKETING.S_ADDRESS_STREET) as MIESZKAN,
(count(temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL.S_ADDRESS_STREET)/count(USERS2_MARKETING.S_ADDRESS_STREET)*100) as NASYCENIE ,
(count(UM_I_ANKIET.ID)/count(USERS2_MARKETING.S_ADDRESS_STREET)*100) as PR_ANKIET,
count(UM_I_UPC.ID)/count(UM_I_ANKIET.ID)*100 as PR_I_UPC,
count(UM_I_INNY.ID)/count(UM_I_ANKIET.ID)*100 as PR_I_INNY,
count(UM_I_ZAINT.ID)/count(UM_I_ANKIET.ID)*100 as PR_I_ZAINT

from USERS2_MARKETING as USERS2_MARKETING
left join temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL on (temp_USERS2_INTERNET_STATUS_INTERNET_NORMAL.S_ADDRESS_STREET=USERS2_MARKETING.S_ADDRESS_STREET)
left join USERS2_MARKETING as UM_I_ANKIET on (UM_I_ANKIET.ID=USERS2_MARKETING.ID and UM_I_ANKIET.I_BAD_DATE> from_unixtime(unix_timestamp(now())-31536000)   )
left join USERS2_MARKETING as UM_I_UPC on UM_I_UPC.ID=UM_I_ANKIET.ID and UM_I_UPC.I_OPER='UPC'
left join USERS2_MARKETING as UM_I_INNY on UM_I_INNY.ID=UM_I_ANKIET.ID and UM_I_INNY.I_OPER='INNY'
left join USERS2_MARKETING as UM_I_ZAINT on UM_I_ZAINT.ID=UM_I_ANKIET.ID and UM_I_ZAINT.I_OPER_ZAINT
group by USERS2_MARKETING.T_TELBOX_BUILDING_IN
$SORT_ORDER
;
  ";

 ZAP_SQL($ZAP_SQL);
 echo "<table border=1>\n";
  echo "<tr><td><a href=$PHP_SELF?STATYSTYKA_WYSWIETL=$_GET[STATYSTYKA_WYSWIETL]&SORT=T_TELBOX_BUILDING_IN>BUDYNEK</a></td>
       <td><a href=$PHP_SELF?STATYSTYKA_WYSWIETL=$_GET[STATYSTYKA_WYSWIETL]&SORT=M_REWIR>M_REWIR</a></td>
       <td><a href=$PHP_SELF?STATYSTYKA_WYSWIETL=$_GET[STATYSTYKA_WYSWIETL]&SORT=ABONENTOW>ABON_BIALL_NET</a></td>
       <td><a href=$PHP_SELF?STATYSTYKA_WYSWIETL=$_GET[STATYSTYKA_WYSWIETL]&SORT=MIESZKAN>MIESZKAN</a></td>
       <td><a href=$PHP_SELF?STATYSTYKA_WYSWIETL=$_GET[STATYSTYKA_WYSWIETL]&SORT=NASYCENIE>NASYCENIE</a></td>
       <td><a href=$PHP_SELF?STATYSTYKA_WYSWIETL=$_GET[STATYSTYKA_WYSWIETL]&SORT=PR_ANKIET>%ANKIET</a></TD>
       <td><a href=$PHP_SELF?STATYSTYKA_WYSWIETL=$_GET[STATYSTYKA_WYSWIETL]&SORT=PR_I_UPC>%UPC</a></td>
       <td><a href=$PHP_SELF?STATYSTYKA_WYSWIETL=$_GET[STATYSTYKA_WYSWIETL]&SORT=PR_I_INNY>%INNY</a></td>";
echo"  <td><a href=$PHP_SELF?STATYSTYKA_WYSWIETL=$_GET[STATYSTYKA_WYSWIETL]&SORT=PR_I_ZAINT>%ZAINT3</a></td></tr>";
 while($h=mysql_fetch_row($result)) {
  echo "<tr><td>$h[0]</td><td>$h[1]</td><td>$h[2]</td><td>$h[3]</td><td>$h[4]</td><td>$h[5]</td><td>$h[6]</td><td>$h[7]</td><td>$h[8]</td></tr>";
// print_r($h);
 }
echo "</table>\n";


}




if($_GET[NADANIE_PROBLEMOW]) {
echo "<br><hr>NADANIE_PROBLEMOW <form action=$PHP_SELF method=\"GET\">";
echo "<input type=hidden name=ADD value=ADD>";
echo "<input type=hidden name=NADANIE_PROBLEMOW value=1>";
echo "100 rekordow (pokazane przykladowe dane optymalne dla biezacej daty 2007-09-01 oraz prowadzonej akcji \"przedluzenie umow dla istniejacego operatora\")<br>";
echo "  <input type=text name=M_REWIR size=30 value=$_GET[M_REWIR]> Okresl M_REWIR (np: GD.CH.F%)<br>";
echo " <input type=text name=A_PROBLEM_DESC size=50 value=\"$_GET[A_PROBLEM_DESC]\"> Wpisz opis problemu (np: \"TODO20070809HANDL: PRZEDLUZYC UMOWE\")<br>";
echo " <input type=text name=I_OPER_FIN size=50 value=\"$_GET[I_OPER_FIN]\"> Wpisz gorny termin zakonczenia umowy na internet (np: 2007-10-00 )<br>";
echo " <input type=text name=I_BAD_DATE size=50 value=\"$_GET[I_BAD_DATE]\"> Wpisz gorny termin daty waznosci badania danego rekordu (np: 2007-01-01 )<br>";
echo " <input type=text name=I_BAD_DATE_MIN size=50 value=\"$_GET[I_BAD_DATE_MIN]\"> Wpisz dolny termin daty waznosci badania danego rekordu (np: 0000-00-00 )<br>";
echo " <input type=text name=I_OPER size=50 value=\"$_GET[I_OPER]\"> Wpisz operatora biezacego internet dla ktorego chcesz przeprowadzic akcje (np: BN )<br>";
echo "<input type=submit name=ADD value=SZUKAJ><br>";

//if($_GET[I_BAD_DATE_MIN]=="0000-00-00")

$ZAP_SQL="create temporary table TEMP_MARKETING
select  t1.ID , t1.S_ADDRESS_STREET , t1.I_OPER, t1.I_OPER_FIN from USERS2_MARKETING as t1
right join SES_USERS2_A as t2 on t2.S_ADDRESS_STREET=t1.S_ADDRESS_STREET
where
t2.A_STATUS='NORMAL' and
 t1.I_OPER='$_GET[I_OPER]' and
  ( t1.I_OPER_FIN='0000-00-00' or t1.I_OPER_FIN<'$_GET[I_OPER_FIN]' ) and
  ( t1.I_BAD_DATE<='$_GET[I_BAD_DATE]' )  and  ( t1.I_BAD_DATE>='$_GET[I_BAD_DATE_MIN]' )  and
  t1.M_REWIR like '$_GET[M_REWIR]' and t1.A_PROBLEM=''
group by t1.ID
order by t1.I_OPER_FIN

  limit 100 ;";
if($_GET[M_REWIR]) {
 echo "<br> ZAP_SQL <br> $ZAP_SQL ";
 $conn=mysql_pconnect($INTERFACE_ADDR,$SQL_USER,$SQL_USER_PASS);
 if (!$conn) die("ERROR podczas tworzenia polaczenia do bazy $SQL_DATABASE !\n");
 mysql_select_db($SQL_DATABASE) or die("ERROR podczas wyboru bazy R50!");
 $result = mysql_query($ZAP_SQL,$conn) or die("Blad zapytania ZAP_SQL. * $ZAP_SQL *!");
 $result2 = mysql_query("select * from TEMP_MARKETING",$conn) or die("Blad zapytania ZAP_SQL. **!");
// ZAP_SQL("$ZAP_SQL");
 }
//$ZAP_SQL("select * from TEMP_MARKETING");

//print_r($result2);
echo "<table><tr><td>";
while($DWA=mysql_fetch_array($result2)) {



echo "<tr><td>".$DWA[0]."</td><td>".$DWA[1]."</td><td>".$DWA[2]."/".$DWA[3]."</td><td>".$DWA[4]."</td></tr>\n";

 }

echo "</td></tr>\n";


echo "</table>";
echo "<input type=submit name=ADD value=NADAJ_PROBLEMY><br>";
if($_GET[ADD]=="NADAJ_PROBLEMY") {
 echo "<br> NADAJE lub NADALEM PROBLEMY $ADM_RECORD_USER";
 $ZAP_SQL1="update USERS2_MARKETING as t1, TEMP_MARKETING as t2 set
 t1.A_RECORD_UPDATE_AUTHOR='".$_SESSION['ADM_ACCOUNT']."' , t1.A_RECORD_UPDATE_DATE=now() , t1.A_PROBLEM_DATE=now() ,
 t1.A_PROBLEM='UNVERIFIED', t1.A_PROBLEM_DESC='$_GET[A_PROBLEM_DESC]'
 where t1.ID=t2.ID ;";

 $ZAP_SQL2="insert into USERS2_MARKETING_HIST (ID_USERS2,A_RECORD_UPDATE_DATE,A_RECORD_UPDATE_AUTHOR,A_PROBLEM,A_PROBLEM_DATE,A_PROBLEM_DESC)
 select ID,now(),'$ADM_ACCOUNT','UNVERIFIED',now(),'$_GET[A_PROBLEM_DESC]' from TEMP_MARKETING ;";
echo "ZAP_SQL $ZAP_SQL1 <br> $ZAP_SQL2";
if($_SESSION['ADM_ADMIN_LEVEL']>"1") echo "<font color=red><b>".$_SESSION['ADM_ADMIN_LEVEL']." ERROR BRAK UPRAWNIEN <BR></font>"; else$result3 = mysql_query($ZAP_SQL1,$conn) or die("Blad zapytania ZAP_SQL. *$ZAP_SQL*!");
if($_SESSION['ADM_ADMIN_LEVEL']>"1") echo "<font color=red><b>".$_SESSION['ADM_ADMIN_LEVEL']." ERROR BRAK UPRAWNIEN <BR></font>"; else$result4 = mysql_query($ZAP_SQL2,$conn) or die("Blad zapytania ZAP_SQL. *$ZAP_SQL*!");

 }


echo " </form>";
} //EOF IF





if($_GET[RAPORT_DZIALAN_OGOLNY_1]) {
echo "<br><hr>RAPORTOWANIE RAPORT_DZIALAN_OGOLNY_1 <form action=$PHP_SELF method=\"GET\">";
echo "<input type=hidden name=ADD value=ADD>";
echo "<input type=hidden name=RAPORT_DZIALAN_OGOLNY_1 value=1>";
echo "<table border=1><tr><td>";
echo "PODAJ INTERESUJACE CIE REWIRY  , (zakoncz znakiem %) - 500 rekordow</td><td>  <input type=text name=M_REWIR size=30 value=$_GET[M_REWIR]></td><td>  <input type=text name=T_WORKPOINTS_DATE size=30 value=$_GET[T_WORKPOINTS_DATE]></td></tr>";
echo "<tr><td colspan=1><input type=submit name=ADD value=SZUKAJ></td><td>M_REWIR</td><td>ZAINTERES</td><td>Data_Bad</td><td>OPER</td><td>OPER_FIN</td><td>OPER_ZAD</td></tr>";

if($_GET[M_REWIR]) ZAP_SQL(" select t1.M_REWIR,t1.S_ADDRESS_STREET,t2.T_WORKPOINTS_DATE, t2.M_ZRYWKA_DATE, t2.M_ZRYWKA_NUMBER,t2.M_PARAMETRY from BUILDINGS as t1 left join BUILDINGS_HIST as t2 on t1.ID=t2.ID_USERS2 where t2.T_WORKPOINTS_DATE like '".$_GET[T_WORKPOINTS_DATE]."' or t2.M_ZRYWKA_DATE like '".$_GET[T_WORKPOINTS_DATE]."' order by t1.M_REWIR,t1.S_ADDRESS_STREET limit 5000 ; ");


echo "<tr><td>";
while($DWA=mysql_fetch_array($result)) {



echo "<tr><td>".$DWA[M_REWIR]."</td><td>".$DWA[S_ADDRESS_STREET]."</td><td>".$DWA[T_WORKPOINTS_DATE]."/".$DWA[M_ZRYWKA_DATE]."</td><td>".$DWA[M_ZRYWKA_NUMBER]."</td></tr>\n";

 }

echo "</td></tr>\n";

echo "</table>";

} //EOF IF




if($_GET[RAPORT_DZIALAN_OGOLNY_2]) {
echo "<br><hr>RAPORTOWANIE RAPORT_DZIALAN_OGOLNY_2 Podsumowania <form action=$PHP_SELF method=\"GET\">";
echo "<input type=hidden name=ADD value=ADD>";
echo "<input type=hidden name=RAPORT_DZIALAN_OGOLNY_2 value=1>";
echo "<table border=1><tr><td>";
echo "PODAJ INTERESUJACE CIE REWIRY  , (zakoncz znakiem %) - 500 rekordow</td><td> REWIR: <input type=text name=M_REWIR size=30 value=$_GET[M_REWIR]></td><td> OKRES: <input type=text name=T_WORKPOINTS_DATE size=30 value=$_GET[T_WORKPOINTS_DATE]></td></tr>";
echo "<tr><td colspan=1><input type=submit name=ADD value=SZUKAJ></td><td>M_REWIR</td><td>BUDYNKOW</td><td>ULOTEK/PLAK</td><td>BADAN</td><td>OGOLNIE_BADAN</td><td>MIESZKAN</td><td>ABO_I</td><td>ABO_TV</td></tr>";

if($_GET[M_REWIR]) {
 ZAP_SQL(" drop  table if exists temp_M_REWIR_RAPORT_1  ; ");
  ZAP_SQL("
  create temporary table temp_M_REWIR_RAPORT_1
select t1.M_REWIR , sum(t2.M_ZRYWKA_NUMBER like '%ulot%') as ULOTEK , sum(t2.M_ZRYWKA_NUMBER like '%plaka%') as PLAKATOW
  from BUILDINGS as t1
  left join BUILDINGS_HIST as t2 on
  (t1.ID=t2.ID_USERS2 and
   ( t2.M_ZRYWKA_NUMBER like '%ulo%' or  t2.M_ZRYWKA_NUMBER like '%plaka%' )and
   ( t2.T_WORKPOINTS_DATE like '".$_GET[T_WORKPOINTS_DATE]."' or t2.M_ZRYWKA_DATE like '".$_GET[T_WORKPOINTS_DATE]."')
  )

  where t1.M_REWIR like '".$_GET[M_REWIR]."'
  group by t1.M_REWIR order by t1.M_REWIR; ");
 ZAP_SQL("alter table temp_M_REWIR_RAPORT_1 ADD BUDYNKOW int(10), ADD BADAN int(10) ,add OGOLNIE_BADAN int(10) , ADD MIESZKAN int(10), ADD ABONENTOW_I int(10) , ADD ABONENTOW_TV int(10) ; ");
 ZAP_SQL("drop  table if exists temp_M_REWIR_RAPORT_2  ;");
 ZAP_SQL("create temporary table temp_M_REWIR_RAPORT_2 select t1.M_REWIR
   ,count(t4.ID) as MIESZKAN
   from temp_M_REWIR_RAPORT_1  as t1
   left join USERS2_MARKETING as t4 on t1.M_REWIR=t4.M_REWIR
     group by t1.M_REWIR; ");


 ZAP_SQL(" drop  table if exists temp_M_REWIR_RAPORT_BUDYNKOW");
 ZAP_SQL("create  temporary table temp_M_REWIR_RAPORT_BUDYNKOW select M_REWIR,count(ID) as BUDYNKOW from BUILDINGS group by M_REWIR");


 ZAP_SQL("alter table temp_M_REWIR_RAPORT_2 ADD BUDYNKOW int(10), ADD BADAN int(10) , add OGOLNIE_BADAN int(10) , add ABONENTOW_I int(10), add ABONENTOW_TV int(10) ; ");
 ZAP_SQL("drop  table if exists temp_M_REWIR_RAPORT_3  ;");
 ZAP_SQL("create temporary table temp_M_REWIR_RAPORT_3 select t1.M_REWIR
   ,count(t4.ID) as OGOLNIE_BADAN
   from temp_M_REWIR_RAPORT_1  as t1
   left join USERS2_MARKETING as t4 on t1.M_REWIR=t4.M_REWIR
    where ( COALESCE(unix_timestamp(t4.I_BAD_DATE), 0) > unix_timestamp(now())-15552000 or COALESCE(unix_timestamp(t4.T_BAD_DATE), 0) > unix_timestamp(now())-15552000 or COALESCE(unix_timestamp(t4.TV_BAD_DATE), 0) > unix_timestamp(now())-15552000)  group by t4.M_REWIR ;  ");
 ZAP_SQL("update temp_M_REWIR_RAPORT_2,temp_M_REWIR_RAPORT_3 set temp_M_REWIR_RAPORT_2.OGOLNIE_BADAN=temp_M_REWIR_RAPORT_3.OGOLNIE_BADAN where temp_M_REWIR_RAPORT_2.M_REWIR=temp_M_REWIR_RAPORT_3.M_REWIR  ");
 ZAP_SQL("drop  table if exists temp_M_REWIR_RAPORT_3  ;");
 ZAP_SQL("create temporary table temp_M_REWIR_RAPORT_3 select t1.M_REWIR
   ,count(t4.ID) as BADAN
   from temp_M_REWIR_RAPORT_1  as t1
   left join USERS2_MARKETING as t4 on t1.M_REWIR=t4.M_REWIR
    where ( I_BAD_DATE like '".$_GET[T_WORKPOINTS_DATE]."' or T_BAD_DATE like '".$_GET[T_WORKPOINTS_DATE]."' or TV_BAD_DATE like '".$_GET[T_WORKPOINTS_DATE]."'  )  group by t1.M_REWIR ;  ");
 ZAP_SQL("update temp_M_REWIR_RAPORT_2,temp_M_REWIR_RAPORT_3 set temp_M_REWIR_RAPORT_2.BADAN=temp_M_REWIR_RAPORT_3.BADAN where temp_M_REWIR_RAPORT_2.M_REWIR=temp_M_REWIR_RAPORT_3.M_REWIR  ");

 ZAP_SQL("drop  table if exists temp_M_REWIR_RAPORT_3  ;");
 ZAP_SQL("create temporary table temp_M_REWIR_RAPORT_3 select t1.M_REWIR
   ,sum(t4.I_OPER like 'BN' ) as ABONENTOW_I , sum(t4.TV_OPER like 'BN') as ABONENTOW_TV
   from temp_M_REWIR_RAPORT_1  as t1
   left join USERS2_MARKETING as t4 on t1.M_REWIR=t4.M_REWIR
    group by t4.M_REWIR ;  ");
 ZAP_SQL("update temp_M_REWIR_RAPORT_2,temp_M_REWIR_RAPORT_3 set   temp_M_REWIR_RAPORT_2.ABONENTOW_TV=temp_M_REWIR_RAPORT_3.ABONENTOW_TV ,temp_M_REWIR_RAPORT_2.ABONENTOW_I=temp_M_REWIR_RAPORT_3.ABONENTOW_I  where temp_M_REWIR_RAPORT_2.M_REWIR=temp_M_REWIR_RAPORT_3.M_REWIR  ");

// ZAP_SQL("drop  table if exists temp_M_REWIR_RAPORT_3  ;");
// ZAP_SQL("create temporary table temp_M_REWIR_RAPORT_3 select t1.M_REWIR ,
//   count(t4.T_TELBOX_BUILDING_IN ) as BUDYNKOW
//   from temp_M_REWIR_RAPORT_1  as t1
//   left join USERS2_MARKETING as t4 on t1.M_REWIR=t4.M_REWIR
//    group by t4.T_TELBOX_BUILDING_IN ;  ");
// ZAP_SQL("update temp_M_REWIR_RAPORT_2,temp_M_REWIR_RAPORT_3 set temp_M_REWIR_RAPORT_2.BUDYNKOW=temp_M_REWIR_RAPORT_3.BUDYNKOW   where temp_M_REWIR_RAPORT_2.M_REWIR=temp_M_REWIR_RAPORT_3.M_REWIR  ");




// ZAP_SQL("update t1.temp_M_REWIR_RAPORT_2");
  ZAP_SQL("update temp_M_REWIR_RAPORT_1,temp_M_REWIR_RAPORT_2 set
 temp_M_REWIR_RAPORT_1.BADAN=temp_M_REWIR_RAPORT_2.BADAN ,
 temp_M_REWIR_RAPORT_1.OGOLNIE_BADAN=temp_M_REWIR_RAPORT_2.OGOLNIE_BADAN ,  temp_M_REWIR_RAPORT_1.ABONENTOW_TV=temp_M_REWIR_RAPORT_2.ABONENTOW_TV,
 temp_M_REWIR_RAPORT_1.MIESZKAN=temp_M_REWIR_RAPORT_2.MIESZKAN,  temp_M_REWIR_RAPORT_1.ABONENTOW_I=temp_M_REWIR_RAPORT_2.ABONENTOW_I
 where   temp_M_REWIR_RAPORT_1.M_REWIR=temp_M_REWIR_RAPORT_2.M_REWIR ;");
  ZAP_SQL("update temp_M_REWIR_RAPORT_1,temp_M_REWIR_RAPORT_BUDYNKOW set temp_M_REWIR_RAPORT_1.BUDYNKOW=temp_M_REWIR_RAPORT_BUDYNKOW.BUDYNKOW where temp_M_REWIR_RAPORT_1.M_REWIR=temp_M_REWIR_RAPORT_BUDYNKOW.M_REWIR");
  ZAP_SQL("select * from temp_M_REWIR_RAPORT_1");

 }


echo "<tr><td>";
while($DWA=mysql_fetch_array($result)) {


$color_ULOTEK="\"#FFFFFF\"";
$color_BADAN="\"#FFFFFF\"";
$color_ABO_I="\"#FFFFFF\"";
if($DWA[BUDYNKOW]/($DWA[ULOTEK]+$DWA[PLAKATOW]+1)>3) $color_ULOTEK="#FF0000";
if($DWA[MIESZKAN]/($DWA[OGOLNIE_BADAN]+1)>6) $color_BADAN="#FF0000";
if($DWA[MIESZKAN]/($DWA[ABONENTOW_I]+1)>6) $color_ABO_I="#FF0000";

echo "<tr><td colspan=\"2\">".$DWA[M_REWIR] ;
if(!$DWA[M_REWIR]) echo "REKORDY W USERS2_MARKETING DO UPORZADKOWANIA (BRAK BUDYNKOW lub WPROWADZONO BADANIA/ZASOBY z niewlasciwa nazwa ULICY)!!!";
echo "</td><td>".$DWA[BUDYNKOW]."</td><td bgcolor=$color_ULOTEK>".$DWA[ULOTEK]."/".$DWA[PLAKATOW]."</td><td>".$DWA[BADAN]."</td><td bgcolor=$color_BADAN>".$DWA[OGOLNIE_BADAN]."</td><td>".$DWA[MIESZKAN]."</td><td bgcolor=$color_ABO_I>".$DWA[ABONENTOW_I]."</td><td>".$DWA[ABONENTOW_TV]."</td></tr>\n";

 }

echo "</td></tr>\n";

echo "</table>";

} //EOF IF

if ($_GET[ROZNIESIONE_ZRYWKI]) {
	echo "<hr>ROZNIESIONE ZRYWKI\n";

	$DATA=stripslashes($_GET[DATA]);
	if (!ereg("^[[:digit:]]{4}-[[:digit:]]{2}$",$DATA)) unset($DATA);

	$query="
	select
		substring(M_ZRYWKA_DATE,1,7) as DATY
	from
		BUILDINGS_HIST
	where
		T_WORKPOINTS_USER!='N/S;'
		and M_ZRYWKA_DATE like '____-__-%'
	group by
		DATY
	order by
		DATY desc";
	ZAP_SQL($query);
	echo "<form action=\"$PHP_SELF\">\n<input type=hidden name=\"ROZNIESIONE_ZRYWKI\" value=1>\n";
	echo "<select name=\"DATA\">";
	while ($row=mysql_fetch_object($result)) {
		$DATY=$row->DATY;
		echo "<option value=\"$DATY\"";
		if ($DATA==$DATY) echo " selected";
		echo ">$DATY</option>";
	}
	echo "</select>\n";
	echo "<input type=submit value=\"Szukaj\">\n</form>";

	if ($DATA) {
		$query="
		select
			b.ID,
			bh.T_WORKPOINTS_USER,
			bh.M_ZRYWKA_DATE,
			b.S_ADDRESS_STREET,
			bh.M_ZRYWKA_NUMBER,
			bh.A_RECORD_UPDATE_DATE,
			b.M_REWIR
		from
			BUILDINGS b
			join
				BUILDINGS_HIST bh
			on
				b.ID=bh.ID_USERS2
		where
			bh.T_WORKPOINTS_USER!='N/S;'
			and bh.M_ZRYWKA_DATE!='N/S;'
			AND bh.M_ZRYWKA_DATE like '$DATA%'
		order by
			bh.T_WORKPOINTS_USER,
			bh.M_ZRYWKA_DATE";
		ZAP_SQL($query);
		$result_main=$result;
		echo "<table border=1>\n<tr><td>T_WORKPOINTS_USER</td><td>M_ZRYWKA_DATE</td><td>S_ADDRESS_STREET</td><td>RODZAJ</td><td>LICZBA</td></tr>\n";
		while ($row=mysql_fetch_object($result_main)) {
			$T_WORKPOINTS_USER=$row->T_WORKPOINTS_USER;
			$M_ZRYWKA_DATE=$row->M_ZRYWKA_DATE;
			$S_ADDRESS_STREET=$row->S_ADDRESS_STREET;
			$M_ZRYWKA_NUMBER=$row->M_ZRYWKA_NUMBER;
			if ($M_ZRYWKA_NUMBER=="N/S;") {
				$ID=$row->ID;
				$A_RECORD_UPDATE_DATE=$row->A_RECORD_UPDATE_DATE;
				$query="select M_ZRYWKA_NUMBER from BUILDINGS_HIST where ID_USERS2='$ID' and M_ZRYWKA_NUMBER!='N/S;' and A_RECORD_UPDATE_DATE<'$A_RECORD_UPDATE_DATE' order by A_RECORD_UPDATE_DATE desc limit 1";
				ZAP_SQL($query);
				if ($row2=mysql_fetch_object($result)) $M_ZRYWKA_NUMBER=$row2->M_ZRYWKA_NUMBER;
				else $M_ZRYWKA_NUMBER="BLAD!";
			}
			$dane=explode(",",$M_ZRYWKA_NUMBER);
			$RODZAJ=$dane[0];
			if ($dane[2]) $LICZBA=$dane[2]; else $LICZBA=$dane[1];
			echo "<tr><td>$T_WORKPOINTS_USER</td><td>$M_ZRYWKA_DATE</td><td>$S_ADDRESS_STREET</td><td>$RODZAJ</td><td>$LICZBA</td></tr>\n";
			$SUMA[$T_WORKPOINTS_USER][$RODZAJ]+=$LICZBA;
		}
		echo "</table><hr>\n";
		echo "<table border=1>\n<tr><td>T_WORKPOINTS_USER</td><td>RODZAJ</td><td>LICZBA</td></tr>\n";
		foreach ($SUMA as $T_WORKPOINTS_USER => $dane) {
			echo "<tr><td>$T_WORKPOINTS_USER</td><td colspan=2>&nbsp</td></tr>\n";
			foreach ($dane as $RODZAJ => $LICZBA) {
				echo "<tr><td></td><td>$RODZAJ</td><td>$LICZBA</td></tr>\n";
			}
		}
		echo "</table>\n";
	}
} // EOF IF

if ($_GET[ROZNIESIONE_ZRYWKI_2]) {
	echo "<hr>ROZNIESIONE ZRYWKI\n";

	$DATA=stripslashes($_GET[DATA]);
	if (!ereg("^[[:digit:]]{4}-[[:digit:]]{2}$",$DATA)) unset($DATA);

	$query="
	select
		substring(M_ZRYWKA_DATE,1,7) as DATY
	from
		BUILDINGS_HIST
	where
		T_WORKPOINTS_USER!='N/S;'
		and M_ZRYWKA_DATE like '____-__-%'
	group by
		DATY
	order by
		DATY desc";
	ZAP_SQL($query);
	echo "<form action=\"$PHP_SELF\">\n<input type=hidden name=\"ROZNIESIONE_ZRYWKI_2\" value=1>\n";
	echo "<select name=\"DATA\">";
	while ($row=mysql_fetch_object($result)) {
		$DATY=$row->DATY;
		echo "<option value=\"$DATY\"";
		if ($DATA==$DATY) echo " selected";
		echo ">$DATY</option>";
	}
	echo "</select>\n";
	echo "<input type=submit value=\"Szukaj\">\n</form>";

	if ($DATA) {
		$query="
		select
			b.ID,
			bh.T_WORKPOINTS_USER,
			bh.M_ZRYWKA_DATE,
			b.S_ADDRESS_STREET,
			bh.M_ZRYWKA_NUMBER,
			bh.A_RECORD_UPDATE_DATE,
			b.M_REWIR
		from
			BUILDINGS b
			join
				BUILDINGS_HIST bh
			on
				b.ID=bh.ID_USERS2
		where
			bh.T_WORKPOINTS_USER!='N/S;'
			and bh.M_ZRYWKA_DATE!='N/S;'
			AND bh.M_ZRYWKA_DATE like '$DATA%'
		order by
			bh.T_WORKPOINTS_USER,
			bh.M_ZRYWKA_DATE";
		ZAP_SQL($query);
		$result_main=$result;
		echo "<table border=1>\n<tr><td>T_WORKPOINTS_USER</td><td>M_ZRYWKA_DATE</td><td>S_ADDRESS_STREET</td><td>RODZAJ</td><td>LICZBA</td></tr>\n";
		while ($row=mysql_fetch_object($result_main)) {
			$T_WORKPOINTS_USER=$row->T_WORKPOINTS_USER;
			$M_REWIR=$row->M_REWIR;
			$M_ZRYWKA_DATE=$row->M_ZRYWKA_DATE;
			$S_ADDRESS_STREET=$row->S_ADDRESS_STREET;
			$M_ZRYWKA_NUMBER=$row->M_ZRYWKA_NUMBER;
			if ($M_ZRYWKA_NUMBER=="N/S;") {
				$ID=$row->ID;
				$A_RECORD_UPDATE_DATE=$row->A_RECORD_UPDATE_DATE;
				$query="select M_ZRYWKA_NUMBER from BUILDINGS_HIST where ID_USERS2='$ID' and M_ZRYWKA_NUMBER!='N/S;' and A_RECORD_UPDATE_DATE<'$A_RECORD_UPDATE_DATE' order by A_RECORD_UPDATE_DATE desc limit 1";
				ZAP_SQL($query);
				if ($row2=mysql_fetch_object($result)) $M_ZRYWKA_NUMBER=$row2->M_ZRYWKA_NUMBER;
				else $M_ZRYWKA_NUMBER="BLAD!";
			}
			$dane=explode(",",$M_ZRYWKA_NUMBER);
			$RODZAJ=$dane[0];
			if ($dane[2]) $LICZBA=$dane[2]; else $LICZBA=$dane[1];
			echo "<tr><td>$T_WORKPOINTS_USER</td><td>$M_ZRYWKA_DATE</td><td>$S_ADDRESS_STREET</td><td>$RODZAJ</td><td>$LICZBA</td></tr>\n";
			$SUMA[$T_WORKPOINTS_USER][$RODZAJ]+=$LICZBA;
			$SUMA2[$M_REWIR][$RODZAJ]+=$LICZBA;

		}
		echo "</table><hr>\n";
		echo "<table border=1>\n<tr><td>T_WORKPOINTS_USER</td><td>RODZAJ</td><td>LICZBA</td></tr>\n";
		foreach ($SUMA as $T_WORKPOINTS_USER => $dane) {
			echo "<tr><td>$T_WORKPOINTS_USER</td><td colspan=2>&nbsp</td></tr>\n";
			foreach ($dane as $RODZAJ => $LICZBA) {
				echo "<tr><td></td><td>$RODZAJ</td><td>$LICZBA</td></tr>\n";
			}
		}
		echo "</table>\n";
		echo "<table border=1>\n<tr><td>M_REWIR</td><td>RODZAJ</td><td>LICZBA</td></tr>\n";
		foreach ($SUMA2 as $T_WORKPOINTS_USER => $dane) {
			echo "<tr><td>$T_WORKPOINTS_USER</td><td colspan=2>&nbsp</td></tr>\n";
			foreach ($dane as $RODZAJ => $LICZBA) {
				echo "<tr><td></td><td>$RODZAJ</td><td>$LICZBA</td></tr>\n";
			}
		}
		echo "</table>\n";
	}
} // EOF IF



if ($_GET[POPRAWIANIE_DANYCH]) {
	$WRONG=stripslashes($_GET[WRONG]);
	$GOOD=stripslashes($_GET[GOOD]);
	echo "<hr>POPRAWIANIE DANYCH<br><br>\n";
	echo "<form >\n<input type=hidden name=\"POPRAWIANIE_DANYCH\" value=1>\n"; //action=\"$PHP_SELF\"
	echo "<table><tr><td colspan=2 align=center>SKR�TY ULIC:  </td></tr>\n";
	echo "<tr><td>Jest (wpisz np KOP11):</td><td><input type=text size=4 name=\"WRONG\" value=\"".$WRONG."\"</td></tr>\n";
	echo "<tr><td>Winno by� (wpisz np KO11):</td><td><input type=text size=4 name=\"GOOD\" value=\"".$GOOD."\"</td></tr>\n";
	echo "<tr><td colspan=2 align=center><input type=submit name=\"ACT\" value=\"SZUKAJ\"></td></tr></table>\n";
	if ($_GET[ACT]) {
		if (($WRONG)&&($GOOD)) {
			echo "<hr>\n";
			$query="SELECT * FROM USERS2_MARKETING WHERE S_ADDRESS_STREET like '$WRONG%' and S_ADDRESS_STREET REGEXP '".$WRONG."([[:digit:]])*(/)?([[:digit:]])*'";
			echo "<br>$query \n";
			ZAP_SQL($query);
			$result_main=$result;

			while ($row=mysql_fetch_array($result_main)) {
				echo "<br> $row[S_ADDRESS_STREET] $row[I_BAD_DATE] ";
				list($BAD_BUILDING,$BAD_HOUSE)=split('/',$row[S_ADDRESS_STREET]);
//				$BAD_BUILDING=;
				echo "<br> ZLY Adres budynku : $BAD_BUILDING";
				echo "<br> ZLY Adres mieszkania: $BAD_HOUSE ";
				echo "<br> SZUKANY Adres budynku : $GOOD ";
				echo "<br> SZUKANY Adres mieszkania: $BAD_HOUSE";
				   $query2="select * from USERS2_MARKETING where S_ADDRESS_STREET like '$GOOD/$BAD_HOUSE' limit 2";
				   echo "$query2 <br>";
				    ZAP_SQL($query2);
				    $result_slave=$result;
					$row2_num_rows=mysql_num_rows($result_slave);
				    $row2=mysql_fetch_array($result_slave);
				    //print_r($row2);
			            //echo $_SESSION[MYSQL_NUM_ROWS] =

				    if($row2_num_rows==1) {
					//JEDEN REKORD wiec jest OK
					   echo "<br> Jest jeden rekord wiec OK  EOL ";
					//POROWNUJEMY A_RECORD_UPDATE_DATE -- S_OTHER_INFO, P_NAME , P_PHONE
					echo "S A_RECORD_UPDATE_DATE $row[A_RECORD_UPDATE_DATE] $row2[A_RECORD_UPDATE_DATE] <br>";
					if($row[A_RECORD_UPDATE_DATE]>$row2[A_RECORD_UPDATE_DATE]) {
						echo "Wstawiam z rekordu zlego ($BAD_BUILDING/$BAD_HOUSE) S_OTHER_INFO, P_NAME , P_PHONE do prawidlowego ($GOOD/$BAD_HOUSE) <br>";
					       ZAP_SQL("update USERS2_MARKETING as t1, USERS2_MARKETING as t2 set t1.S_OTHER_INFO=t2.S_OTHER_INFO, t1.P_NAME=t2.P_NAME , t1.P_PHONE=t2.P_PHONE where t1.S_ADDRESS_STREET='$GOOD/$BAD_HOUSE' and t2.S_ADDRESS_STREET='$BAD_BUILDING/$BAD_HOUSE'");
					}
					//POROWNUJEMY I_BAD_DATE
					echo "S I_BAD_DATE $row[I_BAD_DATE] $row2[I_BAD_DATE] <br>";
					if($row[I_BAD_DATE]>$row2[I_BAD_DATE]) { //TODO _ I_OPER_FIN jest zle 2007-08-31, dla BN nie powinno sie updatowac
						echo "Wstawiam z rekordu zlego ($BAD_BUILDING/$BAD_HOUSE) I_BAD_DATE, I_OPER , I_OPER_ZAD , I_OPER_FIN , I_OPER_ZAINT do prawidlowego ($GOOD/$BAD_HOUSE) <br>";
					       ZAP_SQL("update USERS2_MARKETING as t1, USERS2_MARKETING as t2 set t1.I_BAD_DATE=t2.I_BAD_DATE, t1.I_OPER=t2.I_OPER , t1.I_OPER_ZAD=t2.I_OPER_ZAD, t1.I_OPER_FIN=t2.I_OPER_FIN, t1.I_OPER_ZAINT=t2.I_OPER_ZAINT  where t1.S_ADDRESS_STREET='$GOOD/$BAD_HOUSE' and t2.S_ADDRESS_STREET='$BAD_BUILDING/$BAD_HOUSE'");
					}
					//POROWNUJEMY T_BAD_DATE
					echo "S T_BAD_DATE $row[T_BAD_DATE] $row2[T_BAD_DATE] <br>";
					if($row[T_BAD_DATE]>$row2[T_BAD_DATE]) { //TODO _ T_OPER_FIN jest zle 2007-08-31, dla BN nie powinno sie updatowac
						echo "Wstawiam z rekordu zlego ($BAD_BUILDING/$BAD_HOUSE) T_BAD_DATE, T_OPER , T_OPER_ZAD , T_OPER_FIN , T_OPER_ZAINT do prawidlowego ($GOOD/$BAD_HOUSE) <br>";
					       ZAP_SQL("update USERS2_MARKETING as t1, USERS2_MARKETING as t2 set t1.T_BAD_DATE=t2.T_BAD_DATE, t1.T_OPER=t2.T_OPER , t1.T_OPER_ZAD=t2.T_OPER_ZAD, t1.T_OPER_FIN=t2.T_OPER_FIN, t1.T_OPER_ZAINT=t2.T_OPER_ZAINT  where t1.S_ADDRESS_STREET='$GOOD/$BAD_HOUSE' and t2.S_ADDRESS_STREET='$BAD_BUILDING/$BAD_HOUSE'");
					}
					//POROWNUJEMY TV_BAD_DATE
					echo "S TV_BAD_DATE $row[TV_BAD_DATE] $row2[TV_BAD_DATE] <br>";
					if($row[TV_BAD_DATE]>$row2[TV_BAD_DATE]) { //TODO _ TV_OPER_FIN jest zle 2007-08-31, dla BN nie powinno sie updatowac
						echo "Wstawiam z rekordu zlego ($BAD_BUILDING/$BAD_HOUSE) TV_BAD_DATE, TV_OPER , TV_OPER_ZAD , TV_OPER_FIN , TV_OPER_ZAINT do prawidlowego ($GOOD/$BAD_HOUSE) <br>";
					       ZAP_SQL("update USERS2_MARKETING as t1, USERS2_MARKETING as t2 set t1.TV_BAD_DATE=t2.TV_BAD_DATE, t1.TV_OPER=t2.TV_OPER , t1.TV_OPER_ZAD=t2.TV_OPER_ZAD, t1.TV_OPER_FIN=t2.TV_OPER_FIN, t1.TV_OPER_ZAINT=t2.TV_OPER_ZAINT  where t1.S_ADDRESS_STREET='$GOOD/$BAD_HOUSE' and t2.S_ADDRESS_STREET='$BAD_BUILDING/$BAD_HOUSE'");
					}
					//POROWNUJEMY BOK_BAD_DATE
					echo "S BOK_BAD_DATE $row[BOK_BAD_DATE] $row2[BOK_BAD_DATE] <br>";
					if($row[BOK_BAD_DATE]>$row2[BOK_BAD_DATE]) { //TODO _ TV_OPER_FIN jest zle 2007-08-31, dla BN nie powinno sie updatowac
						echo "Wstawiam z rekordu zlego ($BAD_BUILDING/$BAD_HOUSE) BOK_BAD_DATE, BOK_ZAD do prawidlowego ($GOOD/$BAD_HOUSE) <br>";
					       ZAP_SQL("update USERS2_MARKETING as t1, USERS2_MARKETING as t2 set t1.BOK_BAD_DATE=t2.BOK_BAD_DATE, t1.BOK_ZAD=t2.BOK_ZAD   where t1.S_ADDRESS_STREET='$GOOD/$BAD_HOUSE' and t2.S_ADDRESS_STREET='$BAD_BUILDING/$BAD_HOUSE'");
					}
					//PRZEWALAMY HISTORIE
					$query="update USERS2_MARKETING_HIST set ID_USERS2='$row2[ID]' where ID_USERS2='$row[ID]'";
					ZAP_SQL($query);
					//KASUJEMY_ZLY_REKORD_STARY!!
					$query="delete from USERS2_MARKETING where ID='$row[ID]'";
					//$query="update  USERS2_MARKETING set A_STATUS='DELETED' where ID='$row[ID]'";
					echo "<br> Kasujemy stary rekord: $query ";
					ZAP_SQL($query);
				    } else if(($row2_num_rows==0)&&($GOOD)) {

				        $query="update USERS2_MARKETING set S_ADDRESS_STREET='$GOOD/$BAD_HOUSE'  where ID='$row[ID]'";
					echo "<br>POPROSTU ZMIENIAMY NAZWE $query ";
					ZAP_SQL($query);
				    } else if(!$GOOD) {
				        echo "<br>KASUJEMY REKORD";
				    }


				echo "<hr>\n";
			}

		}
	}
}




if ($_GET[MAGAZYN_SUPEREDIT]) {
	echo "<hr>MAGAZYN SUPEREDIT\n";
	echo "<br><br>Ptasia grypa jest to zemsta Mc'Donalda na KFC za chorobe wscieklych krow.<br>";

	$DATA=stripslashes($_GET[DATA]);
	if ($DATA!="ALL" && $DATA!="ERROR" && !(ereg("^[[:digit:]]{4}-[[:digit:]]{2}$",$DATA))) unset($DATA);

	$query="
		select
			substring(T_BUY_DATE,1,7) as DATY
		from
			DEVICES
		where
			T_BUY_DATE like '____-__%'
		group by
			DATY
		order by
			DATY desc";

	ZAP_SQL($query);
	echo "<form >\n<input type=hidden name=\"MAGAZYN_SUPEREDIT\" value=1>\n";//action=\"$PHP_SELF\"
	echo "<select name=\"DATA\">\n";

	echo "<option value=\"ALL\"";
	if ($DATA=="ALL") {
		echo " selected";
		$DATA="____-__";
	}
	echo ">ALL</option>\n";

	echo "<option value=\"ERROR\"";
	if ($DATA=="ERROR") {
		echo "selected";
		$NOT="not";
		$DATA="____-__";
	} else unset($not);
	echo ">ERROR</option>\n";

	while ($row=mysql_fetch_object($result)) {
		$DATY=$row->DATY;
		echo "<option value=\"$DATY\"";
		if ($DATA==$DATY) echo " selected";
		echo ">$DATY</option>\n";
	}

	echo "</select>\n";
	echo "<input type=submit value=\"Szukaj\">\n</form>";

	if ($DATA) {
#		$query="
#			select
#				T_NETWORK_SERVER,
#				T_BUY_DATE,
#				F_BILL_DATE,
#				F_BILL_NUMBER,
#				replace(F_BILL_COST,',','.') as F_BILL_COST,
#				T_PRODUCER,
#				T_DEVICE_INFO,
#				T_DEVICE_TYPE,
#				T_DEVICE_SERIAL,
#				S_HW,
#				T_WHEN_CONNECTED,
#				T_TELBOX_NEIGHBOUR_IN,
#				S_ADDRESS_STREET
#			from
#				DEVICES
#			where
#				T_BUY_DATE $NOT like '$DATA%'";
                $query="
			select
				if (T_TELBOX_NEIGHBOUR_IN='BN_magazyn','MAGAZYN',T_NETWORK_SERVER) AS T_NETWORK_SERVER,
				T_BUY_DATE,
				replace(F_BILL_COST,',','.') as F_BILL_COST,
				T_WHEN_CONNECTED,
				T_TELBOX_NEIGHBOUR_IN
			from
				DEVICES
			where
				T_BUY_DATE $NOT like '$DATA%'";

		ZAP_SQL($query);
		for ($i=0;$i<mysql_num_fields($result);$i++) $fields[]=mysql_field_name($result,$i);
		echo "<table border=1><tr>";
		foreach ($fields as $field) echo "<td>$field</td>";
		echo "</tr>\n";
		while ($row=mysql_fetch_array($result)) {
			echo "<tr>";
			foreach ($fields as $field) echo "<td>$row[$field]</td>";
			echo "</tr>\n";
			$sum[$row[T_NETWORK_SERVER]]+=$row[F_BILL_COST];
		}
		echo "</table><hr>\n<table border=1><tr><td>T_NETWORK_SERVER</td><td>F_BILL_COST</td></tr>\n";
		ksort($sum);
		foreach ($sum as $T_NETWORK_SERVER => $F_BILL_COST)
			echo "<tr><td>$T_NETWORK_SERVER</td><td>".number_format($F_BILL_COST,2)."</td></tr>";
		echo "</table>\n";
	}
}




echo "<br> EOF. </body></html>";

$_SESSION[MYSQL_NUM_ROWS]="" ;

?>
