<?
session_start();
$brcode = $_SESSION['brcode'];
if(strlen($brcode)<=0)
{
  print "<script> alert('Invalid User'); document.location='ind.php' </script>";
  return;
}

include("../test.php");
include ("../opendb.php");
include ("top.php"); 
?>

<link href="css/printline.css" type="text/css" rel="stylesheet" media="print,screen"  />
<link rel="stylesheet" href="/resources/demos/style.css" />
<link type="text/css" href="../jquery/jquery-ui.min.css" rel="stylesheet" />
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="../jquery/jquery-1.7.min.js"></script>
<script type="text/javascript" src="../jquery/jquery-ui.min.js"></script>
<script type="text/javascript" src="../jquery/jquery.jqEasyCharCounter.min.js"></script>
 <script type="text/javascript">
    var cur=1;
	 var prevcur=0;
	 var gst='';
	 var marginpr='';
	 var custstt='';
	 var shipdistvl='';
	 var shippinvl='';
$(function(){
$(".orderto").live("keydown.autocomplete",function(){
$orderto = $(this);
$row = $orderto.parent().parent();
$(this).autocomplete({
		source: function( request, response ) {
        $.ajax({
			url: "searchcust.php",
			dataType: "json",
			data: "key="+$orderto.val(),
			success: function( data ) {
				response( $.map( data, function( item ) {
					return {
						label: item.orderto+' | '+  item.partname +' | '+  item.price  +' | '+  item.supqty  ,
						value: item.orderto,
						code:item.partname,
							adr:item.price,
							gst:item.supqty,
							marginpr:item.mrgnprc,
						    custstt:item.custstt,
						    shipdistvl:item.shidist,
						    shippinvl:item.shipin,
					}
				}));
			}
		});
	}
	,
	minLength: 2,
	select: function( event, ui ) {
    $row.find('.orderto').val(ui.item.orderto);
	//var cusstr=ui.item.code+','+ui.item.adr+','+ui.item.gst+','+marginpr+','+custstt;
    //cusstr=cusstr.trim();
	//document.f1.addr.value=cusstr;
	 }
	});

});
});
</script>    
<script type="text/javascript">
    var count1=0;
    var cnt=1;
    var cnt1=1;
    var cnt2=1;
    var cnt3=1;
    var cnt4=1;
    var cur=1;
function insRow(event,i1,id2)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    var cur_val=i1.value;
    switch(keyCode)
    {
        case 38:
        var row=i1.parentNode.parentNode.rowIndex;
        var col  =i1.parentNode.cellIndex ;
        document.getElementById('myTable').rows[row-1].cells[col].getElementsByTagName("input")[0].focus();
        break;
        case 40:
        var row=field.parentNode.parentNode.rowIndex;
        var col  =field.parentNode.cellIndex ;
        document.getElementById('myTable').rows[row+1].cells[col].getElementsByTagName("input")[0].focus();
        break;
        case 37:
        var row=field.parentNode.parentNode.rowIndex;
        var col  =field.parentNode.cellIndex ;
        document.getElementById('myTable').rows[row].cells[col-1].getElementsByTagName("input")[0].focus();
	}
    if(id2!="insrowbttn")
    {
        var i2=i1.parentNode.parentNode.rowIndex;
        var i3=parseFloat(i2)+parseFloat(1);
        var rowCounts = document.getElementById('myTable').rows.length;
        var rowCounts1= rowCounts-1;
    }
    else
    {
        var i2=0;
        var rowCounts1=0;
    }
    if(((keyCode == 1) && (i2==rowCounts1))||(cnt==1))
    {
        var rowCount = document.getElementById('myTable').rows.length;
        var rowcount1=parseFloat(rowCount)+parseFloat(1);
//alert(rowCount);
        var x=document.getElementById('myTable').insertRow(rowCount);
        if(rowCount>=1)
        {
            //document.getElementById('insrowbttn').type='hidden';
        }
        var a=x.insertCell(0);
        var aa=x.insertCell(1);
        var aw=x.insertCell(2);
        
        var k;//=this.rowIndex;
        var k1;
        a.innerHTML=cur;
        aa.innerHTML="<input type=text name=partcode[] id=partcode"+cur+"  class='partcode' size=50 autocomplete='off' list='partcodelist' >";
        
            
         //document.getElementById('partcode"+cur+"').value=document.getElementById("orderto").value;
		
            document.getElementById("partcode"+cur).value=document.getElementById("orderto").value;
            aw.innerHTML="<input type='button' onClick='delrow(this)' class='del' id=del"+cur+">";
           
        document.getElementById("orderto").value="";
        document.getElementById("partcode"+cur).focus();
        cur++;
        cnt++;
        var table = document.getElementById("myTable");
        var row = table.rows[index];
        console.log(secondRow.id);
    }
    if(keyCode == 40)
    {
        return handleEnter(this, event);
    }
    if(keyCode == 13)
    {
        var tbl = document.getElementById('myTable');
        var id3=tbl.rows[i3].cells[0].innerHTML;
        document.getElementById("partcode"+id3).focus();
    } 
    

}// end function insrow
</script>
<?
$show=$_REQUEST['show'];
if($show)
{
    $y=$_REQUEST['y'];
    $d=$_REQUEST['d'];
    $m=$_REQUEST['m'];
    $y1=$_REQUEST['y1'];
    $d1=$_REQUEST['d1'];
    $m1=$_REQUEST['m1'];
    $df=$y.'-'.$m.'-'.$d;
    $dt=$y1.'-'.$m1.'-'.$d1;
    $partcode =$_REQUEST['partcode'];
    $i=0;
    $mled_det = "and led IN (";
    foreach($partcode as $a)
    {
     	if($i>0)
			$mled_det .= ",";
		if($a > '')
			$mled_det .= "'$a'";
		$i++;
    }
    //print_r($mled_det);
    /*$ctr=0;
    foreach ($_POST['led_name'] as $leds)
	{
		if($ctr>0)
			$mled_det .= ",";
		if($leds > '')
			$mled_det .= "'$leds'";
		if($leds=='All')
		{
			$mled_det = "";
			break;
		}	
		$ctr++;
	}*/
    if($mled_det>'')
		$mled_det .= ")"; 

    ?>
    <table width=90%" border="1" cellspacing="0" cellpadding="0" class="grid" >
    <center>
    <font face=arial narrow size=3>
    <?print $branch?><br>
    General Ledger<br>for the period of <?print $df." To ".$dt?>
    </center>
    <?
    //$res_led=mysqli_query($db,"select * from ledger where brcode='$brcode' $mled_det order by led");
    $res_led=mysqli_query($db,"select * from ledger where brcode='$brcode' $mled_det");
    echo "select * from ledger where brcode='$brcode' $mled_det";
    //return;
    while($led_row=mysqli_fetch_array($res_led))
    {
        $cd=$led_row['led'];
        $cd=str_replace('~','&',$cd);
        $hd=strtoupper($led_row['led']);
        $re=mysqli_query($db,"select op from ledger where led='$cd' and brcode='$brcode'");
        $opb1=mysqli_fetch_array($re);
        $ssq="select partic from journal2 where brcode='$brcode' and (partic='$cd')";
        $res23=mysqli_query($db,$ssq)or die('jour err:'.mysqli_error($db));
        if(mysqli_num_rows($res23)>0 || $opb1[0]!=0)
        {
            ?>		
            <th colspan=5><font face='arial narrow' size=2 ><b><? print $hd?> 
            <tr><td width=7%><font face='arial narrow' size=3 >Date</td> <td width=62%><font face='arial narrow' size=3 >Vouch/Rec. No. </td><td width=12%><font face='arial narrow' size=3 >Debit </td><td width=12%><font face='arial narrow' size=3 >Credit </td><td width=7%><font face='arial narrow' size=3 >Ref. </td></tr>
            <?
            $cd=$led_row['led'];
            $cd=str_replace('~','&',$cd);
            $tr=0;$tp=0;
            $totdramt=0;$totcramt=0;
            $ssq="select sum(dramt)-sum(cramt) from journal2 where brcode='$brcode' and date<'$df' and (partic='$cd')";
            $res2=mysqli_query($db,$ssq)or die('jour err:'.mysqli_error($db));
            $r2=mysqli_fetch_row($res2);
            $re=mysqli_query($db,"select * from ledger where led='$cd' and brcode='$brcode'");
            $opb=mysqli_fetch_array($re);
            //print 'Type :'.$opb[drcr];
            if($opb['drcr']=='Cr' and $r2[0]<0)
            {
                //$openbal=$opb[op]+abs($r2[0]);print 'op'.$opb[op].' d -op'.$r2[0];
                // following if else is changed ****************************
                if($opb['op']<0)
                    $openbal=$opb['op']+abs($r2[0]);
                else
                    $openbal=$opb['op']+abs($r2[0]);
                //print $opb[op].'--'.$r2[0];
                //**********************************************************
                print "<tr><td></td><td><font face='arial narrow' size=3 > Opening Balance</td><td></td><td align=right><font face='arial narrow' size=3 >".putComa($openbal)."</td><td colspan=2></td>";
                $tp+=$openbal;
            }
            else if($opb['drcr']=='Cr' and $r2[0]>=0)
            {
                $openbal=$opb['op']-$r2[0]; 
                if($openbal>0)
                {
                    print "<tr><td></td><td><font face='arial narrow' size=3 > Opening Balance</td><td></td><td align=right>".putComa($openbal)."</td><td colspan=2></td>";
                    $tp+=$openbal;
                }
                else
                {
                    print "<tr><td></td><td> Opening Balance</td><td align=right>".putComa(abs($openbal))."</td><td colspan=2></td>";
                    $tr+=$openbal;
                }
            
            }
            if($opb['drcr']=='Dr' and $r2[0]>=0)
            {
                if($opb['op']>=0)
                    $openbal= $opb['op'] +abs($r2[0]);
                else
                    $openbal= $opb['op']+$r2[0];
                if($openbal>0)
                {
                    print "<tr><td></td><td> Opening Balance</td><td align=right>".putComa($openbal)."</td><td colspan=2></td>";
                    $tr+=$openbal;
                }
                else
                {
                    print "<tr><td></td><td> Opening Balance</td><td>&nbsp;</td><td align=right>".putComa(abs($openbal))."</td><td colspan=2></td>";
                    $tp+=abs($openbal);
                }
            }
            if($opb['drcr']=='Dr' and $r2[0]<0)
            {
                if($opb['op']>=0)
                    $openbal= $opb['op']+ $r2[0];
                else
                    $openbal= $opb['op']+$r2[0];
                if($openbal>=0)
                {
                    print "<tr><td></td><td> Opening Balance</td><td align=right>".putComa($openbal)."</td><td colspan=2></td>";
                    $tr+=$openbal;
                }
                else
                {
                    print "<tr><td></td><td> Opening Balance</td><td></td><td align=right>".putComa(abs($openbal))."</td><td colspan=2></td>";
                    $tp+=$openbal;
                }
            }
            $sql="select * from journal2 where brcode='$brcode' and partic='$cd' and date>='$df' and date<='$dt'order by date ";

$result=mysqli_query($db,$sql) or die (mysqli_error($db));

while($row=mysqli_fetch_array($result))
{
   if($row['type']=='Cr') //$row[cr]==$cd)
    {
 print "\n<tr><td>".implode('-', array_reverse(explode('-', $row['date'])))."</td><td> &nbsp;&nbsp;  To $row[narr]-($row[j_type])</td><td align=right></td><td align=right>".putComa($row['cramt'])."</td> <td>$row[against]:$row[no]</td>";
//<td align=center><input type=button value='Del' onClick=document.location='deldat.php?code=$row[0]'></td>
print "</tr>";
$totcramt+=$row['cramt'];
  }
 else //if($row[dr]==$cd)
  {
 print "\n<tr><td>".implode('-', array_reverse(explode('-', $row['date'])))."</td><td> By $row[narr]-($row[j_type])</td><td align=right>".putComa($row['dramt'])."</td><td align=right></td> <td>$row[against]:$row[no]</td>";
//<td align=center><input type=button value='Del' onClick=document.location='deldat.php?code=$row[0]'></td>
print "</tr>";

$totdramt+=$row['dramt'];
 }

}
print "<tr><td colspan=2 align=center><B>Total</td>"; 

 $totdramt+=abs($tr);

 //$totcramt+=abs($tp); changed now
$totcramt+=abs($tp);
print "<td align=right><font color=black>".putComa($totdramt)."</td>";
print "<td align=right><font color=black>".putComa(abs($totcramt))."</td><td colspan=2></td></tr>";

/*if($totdramt>=0)
$bal=($totdramt-$totcramt);
else
{$bal=($totdramt+$totcramt); $bal*=-1;}
*/

if(abs($totdramt)>abs($totcramt))
{
$r1=mysqli_query($db,"select $totdramt-$totcramt");
$trow=mysqli_fetch_array($r1);
$bal=abs($trow[0]);
//$bal=(abs($totdramt)-abs($totcramt));
print "\n<tr><td colspan=2 align=center><b><font color=black>Balance</td><td align=right><font color=black><b>".putcoma(abs($bal))."</td><td><font color=black><b> Debit </td><td colspan=2></td></tr>";
}
else if(abs($totdramt)<abs($totcramt))
{
$r11=mysqli_query($db,"select $totcramt-$totdramt");
$trow=mysqli_fetch_array($r11);
$bal=abs($trow[0]);

//$bal=(abs($totcramt)-abs($totdramt)); 

print "\n<tr><td colspan=2 align=center><b><font color=black>Balance</td><td></td><td align=right><font color=black><b>".putcoma(abs($bal))."</td><td><font color=black> <b>Credit </td> </tr>";
}

}
}
//*******************************************************
// if(strtoupper($opb[drcr])=="DR" && $opb[op]<0)
// 	$bal*=-1;
  $bal=number_format($bal,2,'','');
//********************************************************
if($bal>0)
{
//print "\n<tr><td colspan=2 align=center><b><font color=black>Balance</td><td align=right><font color=black><b>".putcoma(abs($bal))."</td><td><font color=black><b> Debit </td><td colspan=2></td></tr>";
}
else
//print "\n<tr><td colspan=2 align=center><b><font color=black>Balance</td><td></td><td align=right><font color=black><b>".putcoma(abs($bal))."</td><td><font color=black> <b>Credit </td> </tr>";


//**************************************************************8888888888888888888888888

?>

</table><br>
<?
return;
} // end main if

?>
<form action='<?print $PHP_SELF?>' method='post' name="f1">
<font style="font-family: 'Trebuchet MS',Verdana,Helvetica,sans-serif; font-size:15px; color:white;">  &nbsp;&nbsp;</font>
<center>
<table cellspacing=1 cellpadding=1 bgcolor='steelblue'>
<font face='arial narrow' size=3 >Transaction Details of <b><? print $cd?> </font>
<tr><td><font color=red>Customer</td><td colspan=4> <input type='text' name='cust' id='orderto' class='orderto' placeholder='Type Customer Name Here' class='orderto' size=100></td><td><input type="button" id='insrowbttn' onclick="insRow(event,this,this.id)" style="color:#6B6B6B;font-weight:bold;font-size:15px;" value="ADD"></td></tr>
<tr><td><label><b>Select Ledgers</label>&nbsp;</td><td>
<table border=1 id="myTable" class='tble1' width=100%>
</table> 
<input type=hidden name=cd value='<?print $cd?>'>
<input type=hidden name=sea value='<?print $sea?>'>
<?
if($d&&$m)
{
?>
<table>
  <tr><td>Date from </td>
      <td>dd<input type=text name='d' size=2 value='<?print $d?>'>
	  mm<input type=text name='m' size=2 value='<?Print $m?>'>
          yy<input type=text name='y' size=4 value='<?Print $y?>'>
      </td></tr>
   <tr>
     <td> To </td>
      <td>dd<input type=text name='d1' size=2 value='<?Print $d1 ?>'>
	  mm<input type=text name='m1' size=2 value='<?Print $m1 ?>'>
          yy<input type=text name='y1' size=4 value='<?Print $y1 ?>'>
      </td>
      <td><input type=submit value='Show' name='show'><input type=submit value='Print' name='prn' ></td>
   </tr>
</table>
<?
}
else
{
?>
<table>
<tr><td>Date from </td>
      <td>dd<input type=text name='d' size=2 value='1'>
	  mm<input type=text name='m' size=2 value='04'>
          yy<input type=text name='y' size=4 value='<?Print (date('Y',time())-1)?>'>
      </td></tr>
   <tr>
     <td> To </td>
      <td>dd<input type=text name='d1' size=2 value='<?Print date('d',time())?>'>
	  mm<input type=text name='m1' size=2 value='<?Print date('m',time())?>'>
          yy<input type=text name='y1' size=4 value='<?Print date('Y',time())?>'>
      </td>
      <td><input type=submit value='Show' name='show'></td>
   </tr>
</table>
<?
}
?>
</table>
</form>