<?php
//ini_set('display_errors',1);
if($_REQUEST ['record']!=null)$_REQUEST ['account_id']=$_REQUEST ['record'];
$r = $GLOBALS ['db']->fetchByAssoc ( $GLOBALS ['db']->query ( "select name,to_vatid,billing_address_city,billing_address_street,account_type from accounts where id='" . $_REQUEST ['account_id'] . "'" ) );
echo $_REQUEST ['account_name'] = $r ['name'];
//echo '<br>'."select name,to_vatid,billing_address_city,billing_address_street,account_type from accounts where id='" . $_REQUEST ['account_id'] . "'";
?>
<h2>Rozliczenia: Strona główna</h2>
<form action="index.php" method="get" name="Search">
	<input type="hidden" name="action" value="index" /> <input
		type="hidden" name="not_matched" value="0" /> <input type="hidden"
		name="module" value="EcmPaymentStates" />
		<link rel="stylesheet" href="include/jQuery/jquery-ui/themes/base/jquery-ui.css">
<script src="include/jQuery/jquery-2.1.0.min.js"></script>
<script src="include/jQuery/jquery-ui/ui/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
#draggable { width: 150px; height: 150px; padding: 0.5em; }
</style>
<script>
$(function() {
$( "div[name=lol]" ).draggable();
});
function hide(obj) {

    var el = document.getElementById(obj);

        el.style.display = 'none';

}
function show(obj,event) {

    var el = document.getElementById(obj);
    el.style.display = 'block';
	var x=event.clientX;
	var y=event.clientY;
	//el.style.position = "absolute";
	//alert(x+' '+y);
    el.style.top = '-'+y+'px'; //or whatever 
    el.style.left = x+'px'; // or whatever

}
</script>	
	<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="Wybierz"
							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">NIP</td>
						<td class="dataField" width="20%" nowrap="nowrap"><input
							name="to_vatid" tabindex="" id="to_vatid" size=""
							value="<?php echo $r['to_vatid'];?>" title=""
							type="text"></td>
						<td class="dataLabel" width="10%" nowrap="nowrap">Dokument nr</td>
						<td class="dataField" width="30%" 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="30%" nowrap="nowrap"><input
							name="value" tabindex="" id="value" size=""
							value="<?php echo $_REQUEST['value'];?>" title="" type="text"></td>
					</tr>
					<tr>
						<td class="dataLabel" width="10%" nowrap="nowrap">Indeks</td>
						<td class="dataField" width="30%" nowrap="nowrap"><input
							name="account_name2" tabindex="" id="account_name2" size="50"
							value="<?php echo $r['index_dbf2'];?>" title=""
							type="text"></td>
						<td class="dataLabel" width="10%" nowrap="nowrap">Miasto</td>
						<td class="dataField" width="20%" nowrap="nowrap"><input
							name="to_vatid" tabindex="" id="to_vatid" size=""
							value="<?php echo $r['billing_address_city'];?>" title=""
							type="text"></td>
						<td class="dataLabel" width="10%" nowrap="nowrap">Ulica</td>
						<td class="dataField" width="30%" nowrap="nowrap"><input
							name="document_no" tabindex="" id="document_no" size=""
							value="<?php echo $r['billing_address_street'];?>" 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></form><form method='post' id='userform' action='modules/EcmPaymentStates/Match.php'>
<?php

include_once ("modules/EcmPaymentStates/helper.php");
// show all
$wh_paid_i = 0;
$wh_paid_p = 0;
// show not mached
if ($_REQUEST ['matched'] == 1) {
	$wh_paid_i = 1;
	$wh_paid_p = 1;
}
// show mached
if ($_REQUEST ['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">';

global $current_language;
echo '<table cellspacing="0" cellpadding="0" border="0" width="100%">';
echo '<tr>';
echo '<td class="listViewThS1" style="width:4px;">&nbsp;</td><td class="listViewThS1" style="width:70px;">Termin płatności</td><td class="listViewThS1" style="width:180px;">Nr Dokumentu</td><td class="listViewThS1" style="width:100px;">Opis</td><td class="listViewThS1" style="width:100px; text-align: right;">Kwota&nbsp&nbsp&nbsp</td>';
echo '</tr></table><div style="height:200px;overflow:auto"><table width="100%">';
if ($_REQUEST ['document_no']){
$where_clause='and name like "'.$_REQUEST ['document_no'].'"';

}
if ($_REQUEST ['value']){
$where_value='and value = "'.unformat_number ( $_REQUEST ['value'] ).'"';
}
if($_REQUEST ['matched']==2){
$where_paid='and paid ="1"';
}
if($_REQUEST ['matched']==0){
$_REQUEST ['not_matched']=2;
}
if($_REQUEST ['matched']==1){
$where_paid='and paid ="0"';
}
if ($_REQUEST ['value'] && is_numeric ( $_REQUEST ['value'] )) {
	$v = "and p.total BETWEEN(" . unformat_number ( $_REQUEST ['value'] - 1 ) . "," . unformat_number ( $_REQUEST ['value'] + 1 ) . ")";
} else
	$v = "";
	$total=0;
	$winien_n_roz=0;
	$winien_roz=0;
$licz=1;
$query="select * from ecmtransactions where parent_id='" . $_REQUEST ['account_id'] . "' and type=0 and deleted='0' ".$where_clause." ".$where_value." ".$where_paid."and payment_date > '2011-12-31' order by date_entered desc";
$w= $GLOBALS ['db']->query ( $query);
//echo "select * from ecmtransactions where parent_id='" . $_REQUEST ['account_id'] . "' and type=0 and deleted='0' ".$where_clause." ".$where_value." order by date_entered desc";
$abc=0;
while($rinv = $GLOBALS ['db']->fetchByAssoc ($w)){
if ($rinv ['payment_date'] < '2008-12-31' && $rinv ['paid'] == 0)
		continue;
$match.="";
	$ab++;
	$total+=$rinv['value'];
	if($rinv ['paid']==0){
		$color = 'color: #FF0000;'; 
		$checkbox = '<input type="checkbox" name="check1[]" value="' . $rinv ['id'] . '" onclick="addValue(this,' . $rinv ['value'] . ',document.getElementById(\'total_wn\'));">';
		$winien_n_roz+=$rinv ['value']; 
	}
	if($rinv['paid']==1){$winien_roz+=$rinv ['value'];$checkbox ="";$color = 'color: #33FF00;';}
	
	if($_REQUEST ['matched']==2){
	    
		$a= $GLOBALS ['db']->query("SELECT a.ecminvoiceout_id as tid,b.name as name,b.id as id,b.value,b.payment_date from ecmpayments2_ecminvoiceouts as a inner join ecmtransactions as b on a.ecminvoiceout_id=b.id where a.ecmpayment_id ='".$rinv['id']."'");
		 if($a->num_rows>0){
		 $show='<a href="#" onClick="show(\'draggable'.$abc.'\',event)"><img src="themes/Sugar5/images/info_inline.gif?s=bed8cd35065048ceebdc639ebe305e2c&c=1"></a>';
			$match.='<div id="draggable'.$abc.'" name="lol" class="ui-widget-content" style="display:none; width:300px;">
    <p style="text-align: left;"><img border="0" src="themes/Sugar/images/close_inline.gif" onClick="hide(\'draggable'.$abc.'\')"></img> Wiązania do '.$rinv['name'].'</p>
<hr><table style="width: 299px;"><tr><td style="text-align: left;">Nazwa</td><td>Kwota</td><td style="text-align: right;">Data</td></tr>';
			while($rinv2 = $GLOBALS ['db']->fetchByAssoc ($a)){
			 
			 $match.='<tr><td style="text-align: left;"><a href="index.php?module=EcmTransactions&action=DetailView&record=' . $rinv2 ['id'] . '">' . $rinv2['name'] . '</a></td><td>'.$rinv2['value'].'</td><td style="text-align: right;">'.$rinv2['payment_date'].'</td></tr>';
			}
			$abc++;
			$match.='</table></div>';
			
		} else { $match.="";$show="";}
	} else {
	$match.="";
	}
	
	$inv = '<a href="index.php?module=EcmTransactions&action=DetailView&record=' . $rinv ['id'] . '">' . $rinv['name'] .'</a>';
	$str = '<tr><td class="oddListRowS1" width="4%">' . $checkbox . ' '.$show.'</td><td class="oddListRowS1" width="15%">' .date("d.m.Y", strtotime($rinv ['payment_date'])). '</td><td class="oddListRowS1" width="23%" > ' . $inv . '</td><td class="oddListRowS1">'.substr($rinv ['description'],0,50).'</td><td class="oddListRowS1" style="text-align: right; ' . $color . '">' . format_number ( $rinv ['value'] ) . '</td></tr>';
	echo $str;
	
//$licz++;
}


echo '</table></div>';

echo '</td><td colspan="5">';
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:25px;">Kwota</td><td class="listViewThS1" style="width:200px; padding-left:20px;text-align:center;">Opis</td><td class="listViewThS1" style="width:80px;">Nr dokumentu</td><td class="listViewThS1" style="width:70px;">Termin płatności</td>';
echo '</tr></table><div style="height:200px;overflow:auto"><table width="100%">';

$ma_n_roz =0;
$ma_roz=0;

$query="select * from ecmtransactions where parent_id='" . $_REQUEST ['account_id'] . "' and type=1 and deleted='0' ".$where_clause." ".$where_value." ".$where_paid."  and payment_date > '2011-12-31' order by date_entered desc";

$w= $GLOBALS ['db']->query ( $query);
//echo "select * from ecmtransactions where parent_id='" . $_REQUEST ['account_id'] . "' and type=1 and deleted='0' ".$where_clause." ".$where_value." order by date_entered desc";
while($rinv = $GLOBALS ['db']->fetchByAssoc ($w)){
$match.="";
		if ($rinv ['payment_date'] < '2008-12-31' && $rinv ['paid'] == 0)
		continue;
	if($_REQUEST ['matched']==2){
		$ab= $GLOBALS ['db']->query("SELECT a.ecminvoiceout_id as tid,b.name as name,b.id as id,b.value,b.payment_date from ecmpayments2_ecminvoiceouts as a inner join ecmtransactions as b on a.ecmpayment_id=b.id where a.ecminvoiceout_id ='".$rinv['id']."'");
		//echo "SELECT a.ecminvoiceout_id as tid,b.name as name,b.id as id from ecmpayments2_ecminvoiceouts as a inner join ecmtransactions as b on a.ecmpayment_id=b.id where a.ecmpayment_id ='".$rinv['id']."'<br>".$a->num_rows."";
		 if($ab->num_rows>0){
		 $abc++;
					 $show='<a href="#" onClick="show(\'draggable'.$abc.'\',event)"><img src="themes/Sugar5/images/info_inline.gif?s=bed8cd35065048ceebdc639ebe305e2c&c=1"></a>';
			$match.='<div id="draggable'.$abc.'" name="lol" class="ui-widget-content" style="display:none; width: 300px;">

    <p style="text-align: left;"><img border="0" src="themes/Sugar/images/close_inline.gif" onClick="hide(\'draggable'.$abc.'\')"></img> Wiązania do '.$rinv['name'].'</p>
</a><hr><table style="width: 299px;"><tr><td style="text-align: left;">Nazwa</td><td>Kwota</td><td style="text-align: right;">Data</td></tr>';
			while($rinv2 = $GLOBALS ['db']->fetchByAssoc ($ab)){
			 $match.='<tr><td style="text-align: left;"><a href="index.php?module=EcmTransactions&action=DetailView&record=' . $rinv2 ['id'] . '">' . $rinv2['name'] . '</a></td><td>'.$rinv2['value'].'</td><td style="text-align: right;">'.$rinv2['payment_date'].'</td></tr>';
			}
			$match.='</table></div>';
		} else { $match.=""; $show='';}
	} else {
	$match.="";
	}
if($rinv ['paid']==0){ $ma_n_roz+=$rinv ['value']; 
$checkbox2 = '<input type="checkbox" name="check2[]" value="' . $rinv ['id'] . '" onclick="addValue(this,' . $rinv ['value'] . ',document.getElementById(\'total_ma\'));">';
		$color = ' color: #FF3333;';
}
if($rinv['paid']==1){$ma_roz+=$rinv ['value'];
	//	$paid = "*";
		$checkbox2 = "";
		$color = ' color: #33FF00;';}
		
$total+=$rinv['value'];
		//$inv = '<a href="index.php?module=EcmPayments2&action=DetailView&record=' . $rinv ['id'] . '">' . $rinv['name'] . '</a>';
	$str = '<tr><td class="oddListRowS1" width="5%">' . $checkbox2 . ' '.$show.'</td><td class="oddListRowS1" style="' . $color . '" width="10%">' . format_number ( $rinv ['value'] ) . '&nbsp&nbsp</td><td class="oddListRowS1" width="28%">'.substr($rinv ['description'],0,50).'</td><td class="oddListRowS1" width="20%"><a href="index.php?module=EcmTransactions&action=DetailView&record=' . $rinv ['id'] . '">' . $rinv ['name'] . '</a></td><td width="10%"">' .date("d.m.Y", strtotime($rinv ['payment_date'])). '</td></tr>';
echo $str;

}
echo '</table></div></td></tr></table>';
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 align="left">
	  <a href="index.php?module=EcmTransactions&action=EditView&parent_id=' . $_REQUEST ['account_id'] . '&type=0&return_module=EcmPaymentStates&return_action=index&return_id='.$_REQUEST ['account_id'].'">	
	  <input type="button" value="Utwórz transakcje Winien"/>
	  </a>
	  </td><td align="right">
	  <a href="index.php?module=EcmTransactions&action=EditView&parent_id=' . $_REQUEST ['account_id'] . '&type=1&return_module=EcmPaymentStates&return_action=index&return_id='.$_REQUEST ['account_id'].'">	
	  <input type="button" value="Utwórz transakcje Ma"/>
	  </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="font-size: 12px;">Nierozliczone: ' . format_number ( $winien_n_roz ) . '</p>';

?>
</td>
						<td style="text-align: center;">
<?php
$wartosc=(($ma_roz + $ma_n_roz) - ($winien_roz + $winien_n_roz));
if($r['account_type']=='rs' || $r['account_type']=='sup'){

if($wartosc>0){
$color='red;';
}
} else {
if($wartosc<0){
$color='red;';
}
}
echo '<p style="color: '.$color.';">';
echo format_number ( $wartosc );
echo '</p>';
echo '<p style="font-size: 12px;">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="font-size: 12px;">Nierozliczone: ' . format_number ( $ma_n_roz ) . '</p>';

?>
</td>
				</table> <input type='submit' id='userform' type="button"  class="button" value="Rozlicz"
				name="match" /></form><input type="submit"
				class="button" value="Pokaż nierozliczone"
				onclick="window.location = '<?php echo "index.php?module=EcmPaymentStates&action=index&account_name=".$_REQUEST['account_name']."&matched=1&account_id=".$_REQUEST['account_id'].""; ?>';"
				name= /> <input type="submit" class="button"
				value="Pokaż wszystko"
				onclick="window.location = '<?php echo "index.php?module=EcmPaymentStates&action=index&account_name=".$_REQUEST['account_name']."&matched=0&account_id=".$_REQUEST['account_id'].""; ?>';" /> <input type="submit" class="button"
				value="Pokaż rozliczone"
				onclick="window.location = '<?php echo "index.php?module=EcmPaymentStates&action=index&account_name=".$_REQUEST['account_name']."&matched=2&account_id=".$_REQUEST['account_id'].""; ?>';" /> <input type="submit" class="button"
				value="Utwórz XLS"
				onclick="document.Search.action.value='CreateXLS';" name="createxls" />
<?php
echo $match;
?>			