<?
session_start();
$brcode=$_SESSION['brcode'];
$user=$_SESSION['user'];
include("opendb.php");
date_default_timezone_set('Asia/Kolkata');
$dt=date("Y-m-d H:i:s");
if(strlen($brcode)<=0)
{
	print "<script> alert('Invalid User'); parent.document.location='../../index.html' </script>";
	 return;
}
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
    $ip = $_SERVER['HTTP_CLIENT_IP'];
    }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
    $ip = $_SERVER['REMOTE_ADDR'];
}

$tbl='tmpallotreceipt'.$brcode.$user;
mysqli_query($db,"drop table IF EXISTS $tbl");
mysqli_query($db,"CREATE TABLE IF NOT EXISTS $tbl like allotreceipt");
mysqli_query($db,"delete from $tbl");


$jvno   = $_REQUEST['jvno'];
$amount = $_REQUEST['amount'];
$typ    = $_REQUEST['typ'];
$cname  = $_REQUEST['cname'];
$prevyear  = $_REQUEST['prevyear'];
$cname = str_replace("|"," ",$cname);
$acqry=mysqli_query($db,"select acfrom from acperiod");
$acrow=mysqli_fetch_array($acqry);
$acfrmdt=$acrow[0];
if($jvno==0)
{
    $jvqry=mysqli_query($db,"select led from ledger where brcode='$brcode' and code='$cname'");
    $jvrow=mysqli_fetch_array($jvqry);
    $cust=$jvrow[0];
}
else
{
    $jvqry=mysqli_query($db,"select date,jvno,partic,cramt,j_type from journal2 where brcode='$brcode' and jvno='$jvno' and cramt>0 and partic = '$cname'");
    $jvrow=mysqli_fetch_array($jvqry);
    $cust=$jvrow[2];
}

if($amount=='')
    $amount = 0;
if(isset($_POST['update']))
{
    echo "test";
}
else
{
	$sql32 = "select invno from allotreceipt where brcode='$brcode' and customer = '$cust' and (crjvno <= 0 or crjvno IS NULL)";
	//print $sql32;
	$res32=mysqli_query($db,$sql32);
	$brrow32=mysqli_fetch_array($res32);
	if(strlen($brrow32[0])>0)
	{
		print "<script> alert('Found old data. It will be deleted'); </script>";
		mysqli_query($db,"delete from allotreceipt where brcode='$brcode' and customer = '$cust' and (jvno <= 0 or jvno IS NULL)");
	}
}

//**** Previous year
$i=0;
if(strlen($prevyear)>0)
{
$sql = "SELECT * FROM gen4psnauto_psn_ampleicher2425.journal2 where partic='$cust' and brcode = '$brcode' and dramt>0";

$res=mysqli_query($db,$sql);
print "<form name='f1' action='' method=post>";
print "<table><tr><th>Open Paid Invoices of $cust Previous Year</th></table>	";
print "<table >";

print "<tr><th>Invoice No.</th><th width='90'>Date</th><th>Amount</th><th>Payment Received</th><th>Remarks</th>";
$i=1;
$mval = $amount;

$ledqry=mysqli_query($db,"select led,op,drcr,code from gen4psnauto_psn_ampleicher2425.ledger where brcode='$brcode' and led = '$cust' and drcr = 'Dr' and op>0");
while($ledrow=mysqli_fetch_array($ledqry))
{
    $brres22=mysqli_query($db,"select sum(amtreceived) from allotreceipt where brcode='$brcode' and customer = '$cust' and drjvno = '0'");
    
    $brrow22=mysqli_fetch_array($brres22);
    //$mamt = $ledrow[1]-($brrow22[0]);
    $mamt = $ledrow[1];
   // $mamt=$ledrow[1];
    $df=implode('-', array_reverse(explode('-', $acfrmdt)));

    
}
while($row=mysqli_fetch_array($res))
{
	$brres22=mysqli_query($db,"select sum(amtreceived) from allotreceipt where brcode='$brcode' and customer = '$cust' and drjvno = '$row[jvno]'");
	
	$minvno = trim(substr($row['narr'],12,20));
    $brres23=mysqli_query($db,"select sum(cramt) from gen4psnauto_psn_ampleicher2425.journal2 where brcode='$brcode' and partic = '$cust' and no = '$minvno' and against= 'sp invoice'");
    $brrow23=mysqli_fetch_array($brres23);
	$brrow22=mysqli_fetch_array($brres22);
	
	$mamt = $row['dramt']-($brrow22[0]+$brrow23[0]);
//echo $brrow22[0];
//echo "<br>";
	if($mamt > 0)
	{
		$df=implode('-', array_reverse(explode('-', $row['date'])));
		print "<tr><td>".$row['narr']."</td><td>$df</td><td>".$mamt."</td>";
		print "<input type=hidden name='invno[]' id='invno$i' value='$row[narr]'>";
		print "<input type=hidden name='invdate[]' id='invdate$i' value='$row[date]'>";
		print "<input type=hidden name='invamount[]' id='invamount$i' value='$mamt'>";
		print "<input type=hidden name='jvtp[]' id='jvtp$i' value='$typ'>";
		print "<input type=hidden name='jvno' id='jvno' value='$jvno'>";
		print "<input type=hidden name='biltyp[]' id='biltyp$i' value='PAID'>";
		print "<input type=hidden name='drjvn[]' id='drjvn$i' value='$row[jvno]'>";
		print "<input type=hidden name='custname[]' id='custname$i' value='$cname'>";
		if($mval>$mamt)
			$mval1 = $mamt;
		else
			$mval1 = $mval;
		print "<td><input type=text name='amt[]' id='amt$i' value = $mval1 size=8 align='right' onkeyup='calculate(this.id)' onChange='updvalue(this.value,this.id)'></td><td><input type=text name='remark[]' id='remark$i' size=12></td>";
		$mval = $mval - $mamt;
		if($mval <0) $mval = 0;
			print "</tr>";
		$i++;
	}
}

}
//**** Current year
$sql = "SELECT * FROM journal2 where partic='$cust' and brcode = '$brcode' and dramt>0";
$res=mysqli_query($db,$sql);
print "<form name='f1' action='' method=post>";
print "<table><tr><th>Open Paid Invoices of $cust</th></table>	";
print "<table >";

print "<tr><th>Invoice No.</th><th width='90'>Date</th><th>Amount</th><th>Payment Received</th><th>Remarks</th><th>Adj Entry</th>";
//$i=1;
//
if($prevyear<='')
    $mval = $amount;
$ledqry=mysqli_query($db,"select led,op,drcr,code from ledger where brcode='$brcode' and led = '$cust' and drcr = 'Dr' and op>0");
while($ledrow=mysqli_fetch_array($ledqry))
{
    $brres22=mysqli_query($db,"select sum(amtreceived) from allotreceipt where brcode='$brcode' and customer = '$cust' and drjvno = '0'");
    $brrow22=mysqli_fetch_array($brres22);
    
   if($prevyear)
    {
        $mamt = $mval;
    }
    else
    {
        $mamt = $ledrow[1]-($brrow22[0]);
    }
    if($ledrow[2]=='Dr') 
    {
        $mopbal = $ledrow[1]; 
    }
    else 
    {
        $mopbal = $ledrow[1]*-1;
    }
    $mopbal=$ledrow[1]-($brrow22[0]);
    $df=implode('-', array_reverse(explode('-', $acfrmdt)));
    print "<tr><td>OP</td><td>$df</td><td>".$mopbal."</td>";
		print "<input type=hidden name='invno[]' id='invno$i' value='OP'>";
		print "<input type=hidden name='invdate[]' id='invdate$i' value='$acfrmdt'>";
		print "<input type=hidden name='invamount[]' id='invamount$i' value='$mamt'>";
		print "<input type=hidden name='jvtp[]' id='jvtp$i' value='$typ'>";
		print "<input type=hidden name='jvno' id='jvno' value='0'>";
		print "<input type=hidden name='biltyp[]' id='biltyp$i' value='PAID'>";
		print "<input type=hidden name='drjvn[]' id='drjvn$i' value='0'>";
		//print "$mval>$mamt";
		if($mval>$mamt)
			$mval1 = $mamt;
		else
			$mval1 = $mval;
		print "<td><input type=text name='amt[]' id='amt$i' value = $mval1 size=8 align='right' onkeyup='calculate(this.id)' onChange='updvalue(this.value,this.id)'></td><td><input type=text name='remark[]' id='remark$i' size=12></td><td><input type=text name='adjamt[]' id='adjamt$i' value = '0' size=8 align='right' onChange='updvalue(this.value,this.id)'></td>";
		$mval = $mval - $mamt;
		if($mval <0) $mval = 0;
			print "</tr>";
			$i++;
			
     $sql = "insert into $tbl (invno,customer,receiptno,invdate,invamount,amtreceived,rec_date,remarks,brcode,user,entrydate,paymenttype,crjvno,biltyp,drjvno,adjamt) values ('OP','$cust','0','$acfrmdt','$mamt','$mval1','$dt','$remark','$brcode','$user','".date("Y-m-d")."','$typ','$jvno','PAID','0',0)";
			    //print $sql;			
			    //exit;
			    mysqli_query($db,$sql); 
    
}
while($row=mysqli_fetch_array($res))
{
	$brres22=mysqli_query($db,"select sum(amtreceived) from allotreceipt where brcode='$brcode' and customer = '$cust' and drjvno = '$row[jvno]'");
	
	$minvno = trim(substr($row['narr'],12,20));
    $brres23=mysqli_query($db,"select sum(cramt) from journal2 where brcode='$brcode' and partic = '$cust' and no = '$minvno' and against= 'sp invoice'");
    $brrow23=mysqli_fetch_array($brres23);


	$brrow22=mysqli_fetch_array($brres22);
	
	$mamt = $row['dramt']-($brrow22[0]+$brrow23[0]);
//echo $brrow22[0];
//echo "<br>";
	if($mamt > 0)
	{
	    
	    
	   
	    
	    
	    
	    
	    
	    
	    
		$df=implode('-', array_reverse(explode('-', $row['date'])));
		print "<tr><td>".$row['narr']."</td><td>$df</td><td>".$mamt."</td>";
		print "<input type=hidden name='invno[]' id='invno$i' value='$row[narr]'>";
		print "<input type=hidden name='invdate[]' id='invdate$i' value='$row[date]'>";
		print "<input type=hidden name='invamount[]' id='invamount$i' value='$mamt'>";
		print "<input type=hidden name='jvtp[]' id='jvtp$i' value='$typ'>";
		print "<input type=hidden name='jvno' id='jvno' value='$jvno'>";
		print "<input type=hidden name='biltyp[]' id='biltyp$i' value='PAID'>";
		print "<input type=hidden name='drjvn[]' id='drjvn$i' value='$row[jvno]'>";
		print "<input type=hidden name='custname[]' id='custname$i' value='$cname'>";
		if($mval>$mamt)
			$mval1 = $mamt;
		else
			$mval1 = $mval;
		print "<td><input type=text name='amt[]' id='amt$i' value = '$mval1' size=8 align='right' onkeyup='calculate(this.id)' onChange='updvalue(this.value,this.id)'></td><td><input type=text name='remark[]' id='remark$i' size=12 onChange='updvalue(this.value,this.id)'></td><td><input type=text name='adjamt[]' id='adjamt$i' value = '0' size=8 align='right' onChange='updvalue(this.value,this.id)'></td>";
		
		$sql = "insert into $tbl (invno,customer,receiptno,invdate,invamount,amtreceived,rec_date,remarks,brcode,user,entrydate,paymenttype,crjvno,biltyp,drjvno) values ('$row[narr]','$cust','0','$row[date]','$mamt','$mval1','$dt','$remark','$brcode','$user','".date("Y-m-d")."','$typ','$jvno','PAID','$row[jvno]')";
			    //print $sql;			
			    //exit;
			    mysqli_query($db,$sql); 
		
		$mval = $mval - $mamt;
		if($mval <0) $mval = 0;
			print "</tr>";
		$i++;
	}
}
?>
<tr><td >Total</td><td ><input type='text' name='prt_total' id='prt_total' readonly value='<? echo $amount ?>'></td><td></td><td ><input type='text' name='amttotal' id='amttotal' readonly value='0'></td></tr>
		    </table>

<table><tr><td colspan='5' align='right'><input type='submit' name='update' value='UPDATE' onclick="updateentry()" ></td></tr></table>
</form>



<style type="text/css">
table {
  width: 100%;
  font-size: 0.923em;
  margin: 0 0 10px;
  border: 1px solid #bebfb9;
  font-family: calibri;
}
table td,
table th {
  vertical-align: middle;
  padding: 8px 10px;
  border: 0;
  color: #000;
}
tr.even,
tr.odd {
  border-width: 0 1px 0 1px;
  border-style: solid;
  border-color: #bebfb9;
  background: #f3f4ee;
}
tr.odd {
  background: #fff;
}
tr.drag {
  background: #fe7;
}
tr.drag-previous {
  background: #ffb;
}
table th {
  text-transform: uppercase;
  background: #e1e2dc;
  font-weight: bold;
  font-family: calibri;
  border-width: 1px;
  border-style: solid;
  border-color: #bebfb9;
  padding: 3px 10px;
}
table th.active {
  background: #bdbeb9;
}
table th a {
  display: block;
  position: relative;
}
table th.active a {
  padding: 0 25px 0 0; /* LTR */
}
table th.active img {
  position: absolute;
  top: 3px;
  right: 3px;
}
table td.active {
  background: #e9e9dd;
}
table tr.odd td.active {
  background: #f3f4ee;
}
table tr.selected td.active,
table tr.selected td {
  background: #ffc;
  border-color: #eeb;
}
table.system-status-report tr {
  border-bottom: 1px solid #ccc;
}
table.system-status-report tr.ok {
  color: #255b1e;
  background-color: #e5ffe2;
}
table.system-status-report tr.info {
  color: #040f37;
  background-color: #bdf;
}
table.system-status-report tr.warning {
  color: #840;
  background-color: #fffce5;
}
table.system-status-report tr.error {
  color: #8c2e0b;
  background-color: #fef5f1;
}
</style>
<script>
function updvalue(str,str1)
{
    //alert(str1);
     var thenum = str1.match(/\d+$/)[0];
    // alert(thenum);
    var id1=thenum;
    if(id1<='')
    {
        id1='';
    }
    
    //alert(str1);
    //if(id1.length==0)
    //{
        //str=0;
    //}
    //var id1=str1;
 
   
    var remrkval=document.getElementById("remark"+id1).value;
    var amtval=document.getElementById("amt"+id1).value;
    var jvnoval=document.getElementById("jvno").value;
    var drjvnval=document.getElementById("drjvn"+id1).value;
    var adjamtval=document.getElementById("adjamt"+id1).value;
    //alert(cnameval);
    var prt_totalval=document.getElementById("prt_total").value;    
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            //alert(xmlhttp.responseText);
            document.getElementById("strtxt").innerHTML=xmlhttp.responseText;
            //document.getElementById("hsncode"+id1).value=document.getElementById("hsncd").value;
        }
    }
    
    var url="sventry.php?remark="+remrkval+"&&amt="+amtval+"&&drjvn="+drjvnval+"&&prt_total="+prt_totalval+"&&jvno="+jvnoval+"&&adjamt="+adjamtval;
   // alert(url);
    xmlhttp.open("GET",url,true);
//alert(url);
//xmlhttp.open("GET","sventry.php?entqty="+entqty+"&&hsncod="+hsncod+"&&itemcd="+itemcd+"&&pricevl="+pricevl+"&&itmrwid="+itmrwid+"&&discvl="+discvl,true);
xmlhttp.send();
    
}
function calculate(did)
{
    var k=0;
    var sumvl=0;
                var ups = document.getElementsByName('amt[]'), sum = 0, k;
                for(k = ups.length; k--;)
				{
					if(ups[k].value)
					{
						sum += parseFloat(ups[k].value, 10);
					}
				}
				sumvl=sum.toFixed(2);
				document.getElementById('amttotal').value=sumvl;
					if(parseFloat(sumvl)>parseFloat(document.getElementById('prt_total').value))
					{
					    alert('total enteterd exceeds');
					    document.getElementById(did).value=0;
					}
}
function valid()
{
	if(confirm('Do you want to save?'))
		return true;
	else
		return false;
}
function updateentry()
{
   
	//var url="sventry1.php";
	//window.location=url,true;
	window.close();
window.open('sventry1.php'); 
}
</script>