<?php
if ($_GET ['action'] == "index")
	$_REQUEST ['not_matched'] = 1;
if ($_REQUEST ['nott_matched'])
	$_REQUEST ['not_matched'] = $_REQUEST ['nott_matched'];
if ($_REQUEST ['account_id'] == "") {
	$_REQUEST ['account_id'] = 134;
	$_REQUEST ['account_id'] = 134;
}
$r = $GLOBALS ['db']->fetchByAssoc ( $GLOBALS ['db']->query ( "select name from accounts where id='" . $_REQUEST ['account_id'] . "'" ) );
$_REQUEST ['account_name'] = $r ['name'];
?>
<h2>Rozliczenia: Strona główna</h2>
<form action="index.php" method="post" name="Search">
	<input type="hidden" name="action" value="index" /> <input
		type="hidden" name="not_matched" value="0" /> <input type="hidden"
		name="module" value="EcmPaymentStates" />
	<script language="javascript">
var OPT=new Array();
OPT['dec_len']=2;
OPT['sep_1000']=".";
OPT['dec_sep']=",";

var inv = new Array();
var pay = new Array();

function formatNumber(number,add) {
    if(!number) number = 0; 
    number = parseFloat(number);
    var tmp = number.toFixed(OPT['dec_len']);
    var s1 = tmp.substring(0,tmp.length-1-OPT['dec_len']);
    var s2 = tmp.substring(tmp.length-OPT['dec_len'],tmp.length);
    var tmp = '';
    for(var i=s1.length;i>0;i-=3) {
    	tmp = ((i<=3)?"":OPT['sep_1000'])+s1.substring(i-3,i)+tmp;
    }
    s1 = tmp;
    return (s1+OPT['dec_sep']+s2).toString()+((add)?add:'');
} 
function unformatNumber(ufn,add) {
    if(add) {
    	var match = /add/g;
    	ufn = ufn.replace(match,'');
    }
    var match = /Err/g;
    ufn = ufn.replace(match,'');
    if(!ufn) return parseFloat(0);
    var pos = ufn.indexOf(OPT['dec_sep']);
    var s1='', s2='';
    if(pos==-1) { s1 = ufn; s2 = ''; }
	else { s1 = ufn.substring(0,pos); s2 = ufn.substring(pos+1,ufn.length); }
    var pos = -1;
    while((pos = s1.indexOf(OPT['sep_1000'])) != -1)
		s1 = s1.substring(0,pos)+s1.substring(pos+1,s1.length);
    return parseFloat(s1+"."+s2);
}
function addValue(obj,value,inp){
	if(obj.checked==true) {
		inp.innerHTML=formatNumber(parseFloat(unformatNumber(inp.innerHTML))+parseFloat(value));
		if (inp.id=="total_wn")
			inv[obj.value] = 1;
		if (inp.id=="total_ma")
			pay[obj.value] = 1;
		}
	else {
		inp.innerHTML=formatNumber(parseFloat(unformatNumber(inp.innerHTML))-parseFloat(value));
		if (inp.id=="total_wn")
			inv[obj.value] = null;
		if (inp.id=="total_ma")
			pay[obj.value] = null;
		}
	}

function doMach() {
	var invoices="";
		for(var i in inv) {
			if (inv[i]==1)
				invoices+= i+"|";
		}
	
	var payments="";
		for(var i in pay) {
			if (pay[i]==1)
				payments+= i+"|";
		}
	window.location="index.php?to_pdf=1&module=EcmPaymentStates&action=Match&inv="+invoices+"&pay="+payments+"&account_id="+document.getElementById("account_id").value;
}
function addValuePayments(obj,value,inp){
	var cb=document.getElementById("paymentsList").getElementsByTagName("input");
	for(var i=0;i<cb.length;i++){
		if(cb[i].type=="checkbox"){
			cb[i].checked=false;
		}
	}
	obj.checked=true;
	inp.innerHTML=formatNumber(parseFloat(value));
}
</script>
	<table cellspacing="2" cellpadding="2" width="100%" border="0">
		<tr>
			<td width="100%" style="width: 520px;">
				<ul class="tablist">
					<li class="active" id="tab_li_EcmPayments|basic_search"><a
						class="current" id="tab_link_EcmPayments|basic_search" href="#">Podstawowe
							wyszukiwanie</a></li>
				</ul>
				<table width="100%" cellspacing="0" cellpadding="0" border="0"
					style="border-top: 0px none; margin-bottom: 4px" class="tabForm">
					<tr>
						<td class="dataLabel" width="10%" nowrap="nowrap">Kontrahent</td>
						<td class="dataField" width="40%" nowrap="nowrap"><input
							name="account_name" tabindex="" id="account_name" size=""
							value="<?php echo $_REQUEST['account_name'];?>" title=""
							type="text"> <input name="account_id" id="account_id"
							value="<?php echo $_REQUEST['account_id'];?>" type="hidden"> <input
							name="btn_account_name" tabindex="" title="Select [Alt+T]"
							accesskey="T" class="button" value="Select"
							onclick='open_popup("Accounts", 600, 400, "", true, false, {"call_back_function":"set_return","form_name":"Search","field_to_name_array":{"id":"account_id","name":"account_name"}}, "single", true);'
							type="button"></td>
						<td class="dataLabel" width="10%" nowrap="nowrap">Dokument nr</td>
						<td class="dataField" width="40%" nowrap="nowrap"><input
							name="document_no" tabindex="" id="document_no" size=""
							value="<?php echo $_REQUEST['document_no'];?>" title=""
							type="text"></td>
						<td class="dataLabel" width="10%" nowrap="nowrap">Kwota</td>
						<td class="dataField" width="40%" nowrap="nowrap"><input
							name="value" tabindex="" id="value" size=""
							value="<?php echo $_REQUEST['value'];?>" title="" type="text"></td>
					</tr>
				</table> <input tabindex='2' title='Search [Alt+Q]' accessKey='Q'
				class='button' onclick="document.Search.action.value='index';"
				type='submit' name='button' value='Szukaj' id='search_form_submit' />&nbsp;
				<input tabindex='2' title='Clear [Alt+C]' accessKey='C'
				onclick="location.href='index.php?module=EcmPaymentStates&action=index';"
				class='button' type='button' name='clear' value=' Wyczyść ' />
			</td>
		</tr>
	</table>
<?php

include_once ("modules/EcmPaymentStates/helper.php");
// show all
$wh_paid_i = 0;
$wh_paid_p = 0;
// show not mached
if ($_REQUEST ['not_matched'] == 1) {
	$wh_paid_i = 1;
	$wh_paid_p = 1;
}
// show mached
if ($_REQUEST ['not_matched'] == 2) {
	$wh_paid_i = 2;
	$wh_paid_p = 2;
}

echo 'tt:  ' . $wh_paid_p;
echo '<table cellspacing="0" cellpadding="0" border="0" width="100%">';
echo '<tr valign="top"><td colspan="5"><div style="height:400px;overflow:auto">';

global $current_language;
echo '<table cellspacing="0" cellpadding="0" border="0" width="100%">';
echo '<tr>';
echo '<td class="listViewThS1" style="width:6px;">&nbsp;</td><td class="listViewThS1" style="width:6px;">&nbsp;</td><td class="listViewThS1" style="width:100px;">Termin płatności</td><td class="listViewThS1" style="width:180px;">Nazwa</td><td class="listViewThS1" style="width:100px;">Połączona płatność</td><td class="listViewThS1" style="width:100px; text-align: right;">Wartość&nbsp&nbsp&nbsp</td>';
echo '</tr>';
if ($_REQUEST ['value'] && is_numeric ( $_REQUEST ['value'] )) {
	$v = "and p.total BETWEEN(" . unformat_number ( $_REQUEST ['value'] - 1 ) . "," . unformat_number ( $_REQUEST ['value'] + 1 ) . ")";
} else
	$v = "";
$query = "select p.id,p.document_no,p.paid,p.register_date,p.payment_date,p.total,p.ecminvoiceout_id, p.ecmpayment_id from ecmpayments2_ecminvoiceouts as p  inner join ecminvoiceouts as i on p.ecminvoiceout_id=i.id and i.type!='canceled' where p.deleted='0' and p.account_id='" . $_REQUEST ['account_id'] . "' " . $v . " order by p.date_entered desc";

$w = $GLOBALS ['db']->query ( $query );

$winien_roz = 0;
$winien_n_roz = 0;
while ( $r = $GLOBALS ['db']->fetchByAssoc ( $w ) ) {
	
	$str = "";
	if ($r ['register_date'] < '2008-12-31' && $r ['paid'] == 0)
		continue;
		// if($r['type']!='correct'){
	$rinv = $GLOBALS ['db']->fetchByAssoc ( $GLOBALS ['db']->query ( "select description,id from ecmtransactions where id='" . $r ['ecminvoiceout_id'] . "' and type=0" ) );
	if ($r ['paid'] == 0 || ! $r ['paid']) {
		$paid = "&nbsp;";
		$checkbox = '<input type="checkbox" name="check1[]" value="' . $r ['id'] . '" onclick="addValue(this,' . $r ['total'] . ',document.getElementById(\'total_wn\'));">';
		$color = ' color: #FF3333; ';
		$winien_n_roz += $r ['total'];
		$paid_name = '';
	} else {
		$paid = "*";
		$checkbox = "";
		$color = ' color: #33FF00; ';
		$winien_roz += $r ['total'];
		
		// get payment
		$paid_name='';
		$req=$GLOBALS ['db']->query ( "select p.id, p.name from ecmpayments2_ecminvoiceouts_rel as r inner join ecmpayments2 as p on p.id=r.ecmpayment_id where r.ee_id='" . $r ['id'] . "'" );
		while($wyn = $GLOBALS ['db']->fetchByAssoc ( $req )){
		$paid_name .=' <a href="index.php?module=EcmPayments2&action=DetailView&record=' . $wyn ['id'] . '" target="new">' . $wyn ['name'] . '</a><br>';
		}
	}
	$exp = explode ( "-", $r ['register_date'] );
	
	if ($r ['paid'] == 0)
		$arrear += $r ['total'];
	
	if ($r ['ecminvoiceout_id'])
		$inv = '<a href="index.php?module=EcmInvoiceOuts&action=DetailView&record=' . $r ['ecminvoiceout_id'] . '">' . $r ['document_no'] . '</a>';
	else
		$inv = $r ['document_no'];
	
	$str = '<tr><td class="oddListRowS1">' . $checkbox . '</td><td class="oddListRowS1">' . $paid . '</td><td class="oddListRowS1" style="width:158px;">' . $r ['register_date'] . '</td><td class="oddListRowS1" style="width:220px;overflow:hidden">' . $inv . '</td><td class="oddListRowS1">' . $paid_name . '</td><td class="oddListRowS1" style="width:100px; text-align: right; ' . $color . '">' . format_number ( $r ['total'] ) . '&nbsp&nbsp&nbsp</td></tr>';
	
	if ($_REQUEST ['document_no'] && ! eregi ( $_REQUEST ['document_no'], $r ['document_no'] ))
		;
	elseif ($_REQUEST ['document_no'] && eregi ( $_REQUEST ['document_no'], $r ['document_no'] ))
		echo $str;
	elseif (! $_REQUEST ['document_no']) {
		if ($wh_paid_i == 0)
			echo $str;
		elseif ($r ['paid'] == 1 && $wh_paid_i == 2)
			echo $str;
		elseif ($r ['paid'] == 0 && $wh_paid_i == 1)
			echo $str;
	}
	// }
	$total_wn += $r ['total'];
}
echo '</table></div>';
echo '</td><td colspan="5"><div style="height:400px;overflow:auto">';
echo '<table cellspacing="0" cellpadding="0" border="0" width="100%">';
echo '<tr>';
echo '<td class="listViewThS1" style="width:10px;">&nbsp;</td><td class="listViewThS1" style="width:6px;">&nbsp;</td><td class="listViewThS1" style="width:8%;">Wartość</td><td class="listViewThS1" style="width:192px; padding-left:20px;">Opis płatności</td><td class="listViewThS1" style="width:100px;">Data płatności</td><td class="listViewThS1" style="width:25px;">Typ</td>';
echo '</tr>';
$query = "select payment_date,id,description,value,paid,name from ecmtransactions where deleted='0' and parent_id='" . $_REQUEST ['account_id'] . "' and type=1 order by date_entered desc";

$w = $GLOBALS ['db']->query ( $query );
$last_date = "";

$ma_roz = 0;
$ma_n_roz = 0;
while ( $r = $GLOBALS ['db']->fetchByAssoc ( $w ) ) {
	$str = "";
	if ($r ['payment_date'] < '2008-12-31' && $r ['paid'] == 0)
		continue;
	if ($r ['paid'] == 1) {
		$paid = "*";
		$checkbox = "";
		$color = ' color: #33FF00;';
		$ma_roz += $r ['value'];
	} else {
		$paid = "&nbsp;";
		$checkbox = '<input type="checkbox" name="check2[]" value="' . $r ['id'] . '" onclick="addValue(this,' . $r ['value'] . ',document.getElementById(\'total_ma\'));">';
		$color = ' color: #FF3333;';
		$ma_n_roz += $r ['value'];
	}
	if (str_replace ( " ", "", $r ['name'] ) == "" || ! $r ['name'])
		$r ['name'] = "blank";
	if (! $_REQUEST ['document_no'] && $last_date != $r ['payment_date'] && ($r ['paid'] == 0 || ! $wh_paid_p)) {
		if ($wh_paid_p)
			$whp = " and paid='0'";
		else
			$whp = "";
		$rr = $GLOBALS ['db']->fetchByAssoc ( $GLOBALS ['db']->query ( "select sum(value) as sum from ecmtransactions where deleted='0' and parent_id='" . $_REQUEST ['account_id'] . "'" . $whp . " and payment_date='" . $r ['payment_date'] . "' and type=0" ) );
		$sum_total = $rr ['sum'];
	}
	if ($r ['name'] == "blank")
		$desc_name = $r ['description'];
	else
		$desc_name = $r ['name'];
	$str = '<tr><td class="oddListRowS1" style="width:10px;">' . $checkbox . '</td><td class="oddListRowS1" style="width:10px;">' . $paid . '</td><td class="oddListRowS1" style="width:50px; text-align: right; ' . $color . '">' . format_number ( $r ['value'] ) . '&nbsp&nbsp</td><td class="oddListRowS1" style="width:270px;overflow:hidden; padding-left: 25px;"><a href="index.php?module=EcmPayments&action=DetailView&record=' . $r ['id'] . '">' . $desc_name . '</a></td><td class="oddListRowS1" style="width:100px;">' . $r ['payment_date'] . '</td></tr>';
	
	if ($_REQUEST ['document_no'] && ! eregi ( $_REQUEST ['document_no'], $desc_name ))
		;
	elseif ($_REQUEST ['document_no'] && eregi ( $_REQUEST ['document_no'], $desc_name ))
		echo $str;
	elseif (! $_REQUEST ['document_no']) {
		if ($wh_paid_p == 0)
			echo $str;
		elseif ($r ['paid'] == 1 && $wh_paid_p == 2)
			echo $str;
		elseif ($r ['paid'] == 0 && $wh_paid_p == 1)
			echo $str;
	}
	
	$total_ma += $r ['value'];
	if ($r ['paid'] == 0 || ! $wh_paid_p)
		$last_date = $r ['payment_date'];
	if ($r ['paid'] == 0)
		$total_not_paid += $r ['value'];
}
echo '</table></div></td></tr></table></div>';
echo '</td></tr></table>';
echo '<table><tr>';
echo '<td style="text-align: left;" id="total_wn">0,00</td>';
echo '<td style="text-align: right;" id="total_ma">0,00</td>';
echo '</tr></table>';
echo '<table><tr><td>ttt</td><td align="right">
	  <a href="index.php?module=EcmPayments2&action=EditView&parent_id=' . $_REQUEST ['account_id'] . '&return_module=EcmPaymentStates&return_action=index">	
	  <input type="button" value="Utwórz płatność"/>
	  </a>
	  </td></tr></table>';
?>
<table width="100%">
		<tr>
			<td colspan="2" style="font-size: 18px; text-align: center">
				<table cellspacing="3" cellpadding="3" border="0" width="100%"
					style="font-size: 20px; border: 1px solid #cccccc;">
					<tr style="font-weight: bold; background: #e6e6e6;">
						<td style="text-align: center;">Razem Winien</td>
						<td style="text-align: center;">Saldo</td>
						<td style="text-align: center;">Razem Ma</td>
					</tr>
					<tr>
						<td style="text-align: center;">
<?php
// $total_wn-=4635096.97;
echo format_number ( $winien_roz + $winien_n_roz );
echo '<br>';
echo '<p style="color:#FF3333;">Nierozliczone: ' . format_number ( $winien_n_roz ) . '</p>';

?>
</td>
						<td style="text-align: center;">
<?php
echo format_number ( ($ma_roz + $ma_n_roz) - ($winien_roz + $winien_n_roz) );
echo '<br>';
echo '<p style="color:#FF3333;">Nierozliczone: ' . format_number ( $ma_n_roz - $winien_n_roz ) . '</p>';
?>
</td>
						<td style="text-align: center;">
<?php
echo format_number ( $ma_roz + $ma_n_roz );
echo '<br>';
echo '<p style="color:#FF3333;">Nierozliczone: ' . format_number ( $ma_n_roz ) . '</p>';
?>
</td>
					</tr>
				</table> <input type="button" class="button" value="Dopasuj"
				onclick="doMach();" name="match" />&nbsp; <input type="submit"
				class="button" value="Pokaż nie dopasowane"
				onclick="document.Search.action.value='index';document.Search.not_matched.value='1';"
				name="notmatched" /> <input type="submit" class="button"
				value="Pokaż wszystko"
				onclick="document.Search.action.value='index';document.Search.not_matched.value='0';"
				name="matchednotmatched" /> <input type="submit" class="button"
				value="Pokaż dopasowane"
				onclick="document.Search.action.value='index';document.Search.not_matched.value='2';"
				name="matchednotmatched" /> <input type="submit" class="button"
				value="Utwórz XLS"
				onclick="document.Search.action.value='CreateXLS';" name="createxls" />
				</form>