<?php
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
	if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
		header("location: index.html");
		exit();
	}
	
//if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();

include '../db_connect.php';
include '../db_table_select.php';
$today_date=date("Y-m-d");
$sort_key=bookid;
$from_date = $today_date;
$to_date = $today_date;
$qry_part_filter='';
$qry_part='';
$output= array();

function date_formatc($temp_date)
{
list($year, $month, $day) = explode('-', $temp_date);
return "$day/$month/$year";
}

function getMonth($start,$end)
	
	{
 	$start = strtotime($start);
    $startmoyr = date('Y', $start) . date('m', $start);
    $end = strtotime($end);
    $endmoyr = date('Y', $end) . date('m', $end);
	
	$monthArray = array();
	
    while ($startmoyr <= $endmoyr) {
		
		array_push($monthArray,array("month"=>date("F", $start),"year"=>date("Y", $start)));
		
       // echo date("F Y", $start) . "<br>";
        $start = strtotime("+1month", $start);
        $startmoyr = date('Y', $start) . date('m', $start);
		
    }
	return $monthArray;
	
	}

//$cmp_key=$_POST['cmp_key'];

if(!empty($_POST['reportdfrom']))
{
$temp_from_date = $_POST['reportdfrom'];
list($day, $month, $year) = explode('/', $temp_from_date);
$from_date ="$year-$month-$day";
}
if(!empty($_POST['reportdto']))
{
$temp_to_date = $_POST['reportdto'];
list($day, $month, $year) = explode('/', $temp_to_date);	

$to_date ="$year-$month-$day";

}

if($_POST['report_view_type']=="orderinfo")
{
	  
	if ($_POST['report_typewise']=='all'){
		$qry_part='';
		$qrygroupby ='';
		$qrypart = "where orderdate>=STR_TO_DATE('$from_date','%Y-%m-%d') and orderdate<=STR_TO_DATE('$to_date','%Y-%m-%d')  ";
		
		if($_POST['subreport_type']=="orderwise")
		$qrygroupby = ', orderid';
	if($_POST['billedto']!="")
	$qry_part = "and gencode = '$_POST[billedto]'";
	
	if($_POST['report_type']=="allorders"){
		
	$SQLhead = "SELECT orderid, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart $qry_part   group by  `prodname`$qrygroupby  order by `gencode`";
	
		}
	else if($_POST['report_type']=="pending"){
		$SQLhead = "SELECT orderid, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid`  $qrypart  $qry_part   group by  `prodname`$qrygroupby  order by  `gencode` ";
		//WHERE (sordervar.`qnty`-sordervar.`issued`) >0
		}
		
	else if($_POST['report_type']=="inprocess"){
		$SQLhead = "SELECT orderid, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart  $qry_part   group by  `prodname`$qrygroupby  order by  `gencode` ";
		//WHERE (sordervar.`qnty`-sordervar.`issued`) >0
		}
		
	
	 
$result = mysqli_query($con,$SQLhead);
	
if($result)
	{
$count_totalbill=0;
$rowCount=0;
$outputRow = array();

if($_POST['subreport_type']=="orderwise"){
$outputRow['ORDERID']['value'] =  '';
$outputRow['ORDERID']['name'] =  'b_orderid[]';
}
$outputRow['STYLE']['value'] =  '';
$outputRow['STYLE']['name'] =  'b_style[]';


$outputRow['COLOR']['value'] =  '';
$outputRow['COLOR']['name'] =  'b_color[]';

$tprinth=array("S28|S", "S30|M", "S32|L", "S34|XL", "S36|2XL", "S38|3XL", "S40|4XL", "S42|5XL", "S44|6XL", "S46|7XL", "S48|8XL", "S50|9XL", "S52|10XL", "S54|11XL", "S56|12XL");
$tprint=array("S28", "S30", "S32", "S34", "S36", "S38", "S40", "S42", "S44", "S46", "S48", "S50", "S52", "S54", "S56");

	foreach($tprinth as $x ){
		
	$outputRow[$x]['value'] =  '';
	$outputRow[$x]['name'] =  $x.'b_size[]';
	//$outputRow[$x]['total'] =  'yes';
	}

$outputRow['TOTAL']['value'] = '';
$outputRow['TOTAL']['name'] ='b_total[]';
////$outputRow['TOTAL']['total'] =  'yes';


$output['rows'][][] = $outputRow;
$rowCount++;
$qntyvalue=0;
$gencode='';
$sizetotal = array();
$rowvalc=0;
	while($row = mysqli_fetch_array($result))
	{

	$outputRow = array();
	if($_POST['subreport_type']=="orderwise"){
	$outputRow['ORDERID']['value'] =  $row[orderid];
    $outputRow['ORDERID']['name'] =  'b_orderid[]';
	}
	
	$outputRow['STYLE']['value'] =  $row[gencode].' | '.$row[subcat].' | '.$row[cat];
	$outputRow['STYLE']['name'] =  'b_style[]';
	$outputRow['STYLE']['tdClass'] = 'click_bill_pdf links';
	$outputRow['STYLE']['title'] = 'Double Click to View Bill';
	
	if($row[color]==''){
		$row[color]="-";
		}
	
	$outputRow['COLOR']['value'] =  $row[color];
	$outputRow['COLOR']['name'] =  'b_color[]';
	
		if($_POST['report_type']=="allorders")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM sordervar s WHERE s.prodname =  '$row[prodname]' GROUP BY s.prodname";
		}
		else if($_POST['report_type']=="pending")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM sordervar s WHERE s.prodname =  '$row[prodname]' GROUP BY s.prodname";
		}
		else if($_POST['report_type']=="inprocess")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM sordervar s WHERE s.prodname =  '$row[prodname]' GROUP BY s.prodname  ";
		}
	
	$resultval = mysqli_query($con,$SQLcent);
	//if($resultval ){
		$qntyvalue=0;
		$ival=1;
		$gencode=$row[gencode];
		
			while($rowval = mysqli_fetch_array($resultval))
				{	

					$sizeval = trim($rowval['psize']);
						foreach($tprinth as $y )
						{
							$arrval = ltrim($y,"S");
							$arrval1 = substr($arrval,0,2); // for size 28 to 56
							$arrval2 = explode("|",$arrval); // for size S to 9XL
							
							//if($sizeval==$arrval1||$sizeval==$arrval2[1])
								//{
								$outputRow[$y]['value'] =  $rowval[$ival];	
								$outputRow[$y]['name'] =  $y.'b_size[]';
								
								$rowtotalval+=  $rowval[$ival];
								$qntyvalue = $rowval[$ival]; 
								$sizetotal[$y][] =  $qntyvalue;
								
								
								//}
							//	else
							//	{
							//	$outputRow[$y]['value'] =  ''.ltrim($y,"S").'--'.$sizeval;	
							//	$outputRow[$y]['name'] =  'b_size[]';	
							//	}
							$ival++;
									
						}
						
                
			}
			
        
	//}
	
	if($rowtotalval<=0){
		$rowtotalval="-";
		}
	
	$outputRow['TOTAL']['value'] = $rowtotalval;
	$outputRow['TOTAL']['name'] ='b_total[]';
	
	
	$output['test'][][] = $qntyvalue;
	
	$output['rows'][][] = $outputRow;
	$rowCount++;
	$qntyvalue=0; 
	$sizeval='';
	$rowvalc+=$rowtotalval;
	$rowtotalval=0;
	
	//$count_totalbill+=$row[balance];
	
	}//while($row = mysqli_fetch_array($result))
	

	$outputRow = array();
	if($_POST['subreport_type']=="orderwise"){
	$outputRow['ORDERID']['value'] =  '';
    $outputRow['ORDERID']['name'] =  'b_orderid[]';
	}
	
	$outputRow['STYLE']['value'] =  'Total';
	$outputRow['STYLE']['name'] =  'b_style[]';
	
	$outputRow['COLOR']['value'] =  '-';
	$outputRow['COLOR']['name'] =  'b_color[]';
	
	foreach($tprinth as $k){
	$outputRow[$k]['value'] =  array_sum($sizetotal[$k]);
	$outputRow[$k]['name'] =  $k.'b_size[]';	
	}
	
	$outputRow['TOTAL']['value'] = $rowvalc;
	$outputRow['TOTAL']['name'] ='b_total[]';
	
	$output['rows'][][] = $outputRow;
	$rowCount++;
	
	
	//if displayed rows greater than 0 then sum total
	//$count_totalbill=number_format($balance,2);
	
	$output['total_rows'] =$rowCount;
	echo json_encode($output);
	}//if($result)
	else
	echo mysqli_error($con);
		
 //}//if($_POST['report_type']=="pending") end
	}///end if ($_POST['report_typewise']=='all'){
		
	
else if($_POST['report_typewise']=='partyconsignee')
	{
		$qry_part='';
		$firstcol = 'BUYER';
		$secondcol = 'CONSIGNEE';
		$qrygroupby ='';
		$qrypart = "where orderdate>=STR_TO_DATE('$from_date','%Y-%m-%d') and orderdate<=STR_TO_DATE('$to_date','%Y-%m-%d')  ";
	if($_POST['billedto']!="")
	$qry_part = "and buyercode = '$_POST[billedto]'";
	
	if($_POST['subreport_type']=="orderwise")
    $qrygroupby = ', orderid';
	
	if($_POST['report_type']=="allorders"){
	$SQLhead = "SELECT orderid, buyercode as firstcolval, billedto as secondcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart  $qry_part  group by buyercode$qrygroupby,`prodname`, billedto   order by buyercode , billedto, `prodname`";
		}
	else if($_POST['report_type']=="pending"){
		$SQLhead = "SELECT orderid, buyercode as firstcolval, billedto as secondcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart  $qry_part  group by buyercode,`prodname`, billedto   order by buyercode , billedto, `prodname`";
		}
		
	else if($_POST['report_type']=="inprocess"){
		$SQLhead = "SELECT orderid, buyercode as firstcolval, billedto as secondcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid`  $qry_part  group by buyercode,`prodname`, billedto   order by buyercode , billedto, `prodname`";
		}
		
	 
$result = mysqli_query($con,$SQLhead);
	
if($result)
	{
$count_totalbill=0;
$rowCount=0;
$outputRow = array();

if($_POST['subreport_type']=="orderwise"){
$outputRow['ORDERID']['value'] =  '';
$outputRow['ORDERID']['name'] =  'b_orderid[]';
}

$outputRow[$firstcol]['value'] =  '';

$outputRow[$firstcol]['name'] =  'b_buyercode[]';
$outputRow[$firstcol]['count'] =  'yes';

$outputRow[$secondcol]['value'] =  '';
$outputRow[$secondcol]['name'] =  'b_secondcol[]';


$outputRow['STYLE']['value'] =  '';
$outputRow['STYLE']['name'] =  'b_style[]';


$outputRow['COLOR']['value'] =  '';
$outputRow['COLOR']['name'] =  'b_color[]';

$tprinth=array("S28|S", "S30|M", "S32|L", "S34|XL", "S36|2XL", "S38|3XL", "S40|4XL", "S42|5XL", "S44|6XL", "S46|7XL", "S48|8XL", "S50|9XL", "S52|10XL", "S54|11XL", "S56|12XL");
$tprint=array("S28", "S30", "S32", "S34", "S36", "S38", "S40", "S42", "S44", "S46", "S48", "S50", "S52", "S54", "S56");

	foreach($tprinth as $x ){
	$outputRow[$x]['value'] =  '';
	$outputRow[$x]['name'] =  $x.'b_size[]';
	//$outputRow[$x]['total'] =  'yes';
	}


$outputRow['TOTAL']['value'] = '';
$outputRow['TOTAL']['name'] ='b_total[]';
//$outputRow['TOTAL']['total'] =  'yes';


$output['rows'][][] = $outputRow;
$rowCount++;
$buyer = '';
$consignee = '';
$qntyvalue=0;
$sizetotal = array();
$rowvalc=0;
	while($row = mysqli_fetch_array($result))
	{

	$outputRow = array();
	
	if($_POST['subreport_type']=="orderwise"){
    $outputRow['ORDERID']['value'] =  $row[orderid];
    $outputRow['ORDERID']['name'] =  'b_orderid[]';
     }
	
	if ($buyer != $row[firstcolval])
	$outputRow[$firstcol]['value'] =  $row[firstcolval];
	else
	$outputRow[$firstcol]['value'] =  '';
	$outputRow[$firstcol]['name'] =  'b_buyercode[]';
	
	if ($consignee != $row[secondcolval])
	$outputRow[$secondcol]['value'] =  $row[secondcolval];
	else
	$outputRow[$secondcol]['value'] =  '';
    $outputRow[$secondcol]['name'] =  'b_secondcol[]';

	$outputRow['STYLE']['value'] =  $row[gencode].' | '.$row[subcat].' | '.$row[cat];
	$outputRow['STYLE']['name'] =  'b_style[]';
	$outputRow['STYLE']['tdClass'] = 'click_bill_pdf links';
	$outputRow['STYLE']['title'] = 'Double Click to View Bill';
	
	$outputRow['COLOR']['value'] =  $row[color];
	$outputRow['COLOR']['name'] =  'b_color[]';
	
		if($_POST['report_type']=="allorders")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM sordervar s inner join sorderreg on  s.`job_id`  = sorderreg.`orderid` WHERE s.prodname =  '$row[prodname]' and sorderreg.buyercode = '$row[firstcolval]' and sorderreg.billedto = '$row[secondcolval]'   GROUP BY s.prodname ";
		
		}
		else if($_POST['report_type']=="pending")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM  sordervar s inner join sorderreg on  s.`job_id`  = sorderreg.`orderid` WHERE s.prodname =  '$row[prodname]' and sorderreg.buyercode = '$row[firstcolval]' and sorderreg.billedto = '$row[secondcolval]'   GROUP BY s.prodname ";
		}
		else if($_POST['report_type']=="inprocess")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM sordervar s inner join sorderreg on  s.`job_id`  = sorderreg.`orderid` WHERE s.prodname =  '$row[prodname]' and sorderreg.buyercode = '$row[firstcolval]' and sorderreg.billedto = '$row[secondcolval]'   GROUP BY s.prodname ";
		}
	
	$resultval = mysqli_query($con,$SQLcent);
	//if($resultval ){
		
		
			$qntyvalue =0;	
			$ival=1;		
			while($rowval = mysqli_fetch_array($resultval))
				{	
				     
						
						
					$sizeval = trim($rowval['psize']);
						foreach($tprinth as $y )
						{
							$arrval = ltrim($y,"S");
							$arrval1 = substr($arrval,0,2); // for size 28 to 56
							$arrval2 = explode("|",$arrval); // for size S to 9XL
							
							//if($sizeval==$arrval1||$sizeval==$arrval2[1])
							//	{
								$outputRow[$y]['value'] =  $rowval[$ival];	
								$outputRow[$y]['name'] =   $y.'b_size[]';
								
								$rowtotalval+=  $rowval[$ival];
								$qntyvalue = $rowval[$ival]; 
								$sizetotal[$y][] =  $qntyvalue;
							//	}
							/*else{
								$outputRow[$y]['value'] =  '';	
								$outputRow[$y]['name'] =  'b_size[]';
								}*/
								
								//$sizetotal = array($y => $qntyvalue);
							
							$ival++;
						}//foreach($tprinth as $y ) end
						
						//$arrvaltest = $qntyvalue;
					 //$qntyvalue=0; 
						
					
			}
			
        
	//}
	
	$outputRow['TOTAL']['value'] = $rowtotalval;
	$outputRow['TOTAL']['name'] ='b_total[]';
	
	
	$output['test'][][] = $SQLcent;
	
	$output['rows'][][] = $outputRow;
	$rowCount++;
	$qntyvalue=0; 
	$sizeval='';
	$rowvalc+=$rowtotalval;
	$rowtotalval=0;

	
	$buyer=$row[firstcolval];
	$consignee=$row[secondcolval];

	}//while($row = mysqli_fetch_array($result))
	
	$outputRow = array();
	if($_POST['subreport_type']=="orderwise"){
    $outputRow['ORDERID']['value'] =  '';
    $outputRow['ORDERID']['name'] =  'b_orderid[]';
     }
$outputRow[$firstcol]['value'] =  'TOTAL';
$outputRow[$firstcol]['name'] =  'b_buyercode[]';
$outputRow[$firstcol]['count'] =  'yes';

$outputRow[$secondcol]['value'] =  '-';
$outputRow[$secondcol]['name'] =  'b_secondcol[]';

$outputRow['STYLE']['value'] =  '-';
$outputRow['STYLE']['name'] =  'b_style[]';


$outputRow['COLOR']['value'] =  '-';
$outputRow['COLOR']['name'] =  'b_color[]';

foreach($tprinth as $k){
		
$outputRow[$k]['value'] =  array_sum($sizetotal[$k]);
$outputRow[$k]['name'] =  $k.'b_size[]';
	
}

$outputRow['TOTAL']['value'] = $rowvalc;
$outputRow['TOTAL']['name'] ='b_total[]';
////$outputRow['TOTAL']['total'] =  'yes';

$output['rows'][][] = $outputRow;
$rowCount++;
	
	//if displayed rows greater than 0 then sum total
	//$count_totalbill=number_format($balance,2);
	
	$output['total_rows'] =$rowCount;
	echo json_encode($output);
	}//if($result)
	else
	echo mysqli_error($con);
		
	}// end 	else if($_POST['report_typewise']=='partyconsignee')

	
else if($_POST['report_typewise']=='productconsignee')
	{
		$qry_part='';
		$firstcol = 'PRODUCT';
		$secondcol = 'CONSIGNEE';
		$qrygroupby ='';
        $qrypart = "where orderdate>=STR_TO_DATE('$from_date','%Y-%m-%d') and orderdate<=STR_TO_DATE('$to_date','%Y-%m-%d')  ";
		if($_POST['subreport_type']=="orderwise")
        $qrygroupby = ', orderid';
		
	if($_POST['billedto']!="")
	$qry_part = "and gencode = '$_POST[billedto]'";
	
	if($_POST['report_type']=="allorders"){
	$SQLhead = "SELECT orderid, prodname as firstcolval, billedto as secondcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart $qry_part  group by buyercode$qrygroupby,`prodname`, billedto   order by buyercode , billedto, `prodname`";
		}
	else if($_POST['report_type']=="pending"){
		$SQLhead = "SELECT orderid, prodname as firstcolval, billedto as secondcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart $qry_part   group by buyercode$qrygroupby,`prodname`, billedto   order by buyercode , billedto, `prodname`";
		}
		
	else if($_POST['report_type']=="inprocess"){
		$SQLhead = "SELECT orderid, prodname as firstcolval, billedto as secondcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid`  $qrypart $qry_part  group by buyercode$qrygroupby,`prodname`, billedto   order by buyercode , billedto, `prodname`";
		}
		
	 
$result = mysqli_query($con,$SQLhead);
	
if($result)
	{
$count_totalbill=0;
$rowCount=0;
$outputRow = array();

if($_POST['subreport_type']=="orderwise"){
$outputRow['ORDERID']['value'] =  '';
$outputRow['ORDERID']['name'] =  'b_orderid[]';
}

$outputRow[$firstcol]['value'] =  '';
$outputRow[$firstcol]['name'] =  'b_buyercode[]';
$outputRow[$firstcol]['count'] =  'yes';

$outputRow[$secondcol]['value'] =  '';
$outputRow[$secondcol]['name'] =  'b_secondcol[]';


$outputRow['STYLE']['value'] =  '';
$outputRow['STYLE']['name'] =  'b_style[]';


$outputRow['COLOR']['value'] =  '';
$outputRow['COLOR']['name'] =  'b_color[]';

$tprinth=array("S28|S", "S30|M", "S32|L", "S34|XL", "S36|2XL", "S38|3XL", "S40|4XL", "S42|5XL", "S44|6XL", "S46|7XL", "S48|8XL", "S50|9XL", "S52|10XL", "S54|11XL", "S56|12XL");
$tprint=array("S28", "S30", "S32", "S34", "S36", "S38", "S40", "S42", "S44", "S46", "S48", "S50", "S52", "S54", "S56");

	foreach($tprinth as $x ){
	$outputRow[$x]['value'] =  '';
	$outputRow[$x]['name'] =  $x.'b_size[]';
	//$outputRow[$x]['total'] =  'yes';
	}


$outputRow['TOTAL']['value'] = '';
$outputRow['TOTAL']['name'] ='b_total[]';
//$outputRow['TOTAL']['total'] =  'yes';


$output['rows'][][] = $outputRow;
$rowCount++;
$buyer = '';
$consignee = '';
$qntyvalue=0;
$sizetotal = array();
$rowvalc=0;
	while($row = mysqli_fetch_array($result))
	{

	$outputRow = array();
	
	if($_POST['subreport_type']=="orderwise"){
	$outputRow['ORDERID']['value'] =  $row[orderid];
	$outputRow['ORDERID']['name'] =  'b_orderid[]';
	}
	
	if ($buyer != $row[firstcolval])
	$outputRow[$firstcol]['value'] =  $row[firstcolval];
	else
	$outputRow[$firstcol]['value'] =  '';
	$outputRow[$firstcol]['name'] =  'b_buyercode[]';
	
	if ($consignee != $row[secondcolval])
	$outputRow[$secondcol]['value'] =  $row[secondcolval];
	else
	$outputRow[$secondcol]['value'] =  '';
    $outputRow[$secondcol]['name'] =  'b_secondcol[]';

	$outputRow['STYLE']['value'] =  $row[gencode].' | '.$row[subcat].' | '.$row[cat];
	$outputRow['STYLE']['name'] =  'b_style[]';
	$outputRow['STYLE']['tdClass'] = 'click_bill_pdf links';
	$outputRow['STYLE']['title'] = 'Double Click to View Bill';
	
	$outputRow['COLOR']['value'] =  $row[color];
	$outputRow['COLOR']['name'] =  'b_color[]';
	
		if($_POST['report_type']=="allorders")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM sordervar s inner join sorderreg on  s.`job_id`  = sorderreg.`orderid` WHERE s.prodname =  '$row[firstcolval]'  and sorderreg.billedto = '$row[secondcolval]'   GROUP BY s.prodname ";
		
		}
		else if($_POST['report_type']=="pending")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM  sordervar s inner join sorderreg on  s.`job_id`  = sorderreg.`orderid` WHERE s.prodname =  '$row[firstcolval]' and sorderreg.billedto = '$row[secondcolval]'   GROUP BY s.prodname ";
		}
		else if($_POST['report_type']=="inprocess")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM sordervar s inner join sorderreg on  s.`job_id`  = sorderreg.`orderid` WHERE s.prodname =  '$row[firstcolval]'  and sorderreg.billedto = '$row[secondcolval]'   GROUP BY s.prodname ";
		}
	
	$resultval = mysqli_query($con,$SQLcent);
	//if($resultval ){
		
		
			$qntyvalue =0;	
			$ival=1;		
			while($rowval = mysqli_fetch_array($resultval))
				{	
				     
						
						
					$sizeval = trim($rowval['psize']);
						foreach($tprinth as $y )
						{
							$arrval = ltrim($y,"S");
							$arrval1 = substr($arrval,0,2); // for size 28 to 56
							$arrval2 = explode("|",$arrval); // for size S to 9XL
							
							//if($sizeval==$arrval1||$sizeval==$arrval2[1])
							//	{
								$outputRow[$y]['value'] =  $rowval[$ival];	
								$outputRow[$y]['name'] =   $y.'b_size[]';
								
								$rowtotalval+=  $rowval[$ival];
								$qntyvalue = $rowval[$ival]; 
								$sizetotal[$y][] =  $qntyvalue;
							//	}
							/*else{
								$outputRow[$y]['value'] =  '';	
								$outputRow[$y]['name'] =  'b_size[]';
								}*/
								
								//$sizetotal = array($y => $qntyvalue);
							
							$ival++;
						}//foreach($tprinth as $y ) end
						
						//$arrvaltest = $qntyvalue;
					 //$qntyvalue=0; 
						
					
			}
			
        
	//}
	
	$outputRow['TOTAL']['value'] = $rowtotalval;
	$outputRow['TOTAL']['name'] ='b_total[]';
	
	
	$output['test'][][] = $SQLcent;
	
	$output['rows'][][] = $outputRow;
	$rowCount++;
	$qntyvalue=0; 
	$sizeval='';
	$rowvalc+=$rowtotalval;
	$rowtotalval=0;

	
	$buyer=$row[firstcolval];
	$consignee=$row[secondcolval];

	}//while($row = mysqli_fetch_array($result))
	
	$outputRow = array();
	if($_POST['subreport_type']=="orderwise"){
	$outputRow['ORDERID']['value'] =  '';
	$outputRow['ORDERID']['name'] =  'b_orderid[]';
	}
$outputRow[$firstcol]['value'] =  'TOTAL';
$outputRow[$firstcol]['name'] =  'b_buyercode[]';
$outputRow[$firstcol]['count'] =  'yes';

$outputRow[$secondcol]['value'] =  '';
$outputRow[$secondcol]['name'] =  'b_secondcol[]';

$outputRow['STYLE']['value'] =  '';
$outputRow['STYLE']['name'] =  'b_style[]';


$outputRow['COLOR']['value'] =  '';
$outputRow['COLOR']['name'] =  'b_color[]';

foreach($tprinth as $k){
		
$outputRow[$k]['value'] =  array_sum($sizetotal[$k]);
$outputRow[$k]['name'] =  $k.'b_size[]';
	
}

$outputRow['TOTAL']['value'] = $rowvalc;
$outputRow['TOTAL']['name'] ='b_total[]';
//$outputRow['TOTAL']['total'] =  'yes';

$output['rows'][][] = $outputRow;
$rowCount++;
	
	//if displayed rows greater than 0 then sum total
	//$count_totalbill=number_format($balance,2);
	
	$output['total_rows'] =$rowCount;
	echo json_encode($output);
	}//if($result)
	else
	echo mysqli_error($con);
		
	}// end 	else if($_POST['report_typewise']=='partyconsignee')

    
	
else if($_POST['report_typewise']=='productorder')
	{
		$qry_part='';
		$firstcol = 'PRODUCT';
		$secondcol = 'ORDER';
		$qrygroupby ='';
		$qrypart = "where orderdate>=STR_TO_DATE('$from_date','%Y-%m-%d') and orderdate<=STR_TO_DATE('$to_date','%Y-%m-%d')  ";
				
		if($_POST['subreport_type']=="orderwise")
		$qrygroupby = ', orderid';
	if($_POST['billedto']!="")
	$qry_part = "and prodname = '$_POST[billedto]'";
	
	if($_POST['report_type']=="allorders"){
	$SQLhead = "SELECT prodname as firstcolval, orderid as secondcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart  $qry_part  group by buyercode,`prodname`$qrygroupby   order by buyercode , orderid, `prodname`";
		}
	else if($_POST['report_type']=="pending"){
		$SQLhead = "SELECT prodname as firstcolval, orderid as secondcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid`  $qrypart  $qry_part    group by buyercode$qrygroupby, `prodname`, orderid   order by buyercode , orderid, `prodname`";
		}
		
	else if($_POST['report_type']=="inprocess"){
		$SQLhead = "SELECT prodname as firstcolval, orderid as secondcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid`  $qrypart  $qry_part    group by buyercode$qrygroupby,`prodname`, orderid   order by buyercode , orderid, `prodname`";
		}
		
	 
$result = mysqli_query($con,$SQLhead);
	
if($result)
	{
$count_totalbill=0;
$rowCount=0;
$outputRow = array();


$outputRow[$firstcol]['value'] =  '';
$outputRow[$firstcol]['name'] =  'b_buyercode[]';
$outputRow[$firstcol]['count'] =  'yes';

$outputRow[$secondcol]['value'] =  '';
$outputRow[$secondcol]['name'] =  'b_secondcol[]';


$outputRow['STYLE']['value'] =  '';
$outputRow['STYLE']['name'] =  'b_style[]';


$outputRow['COLOR']['value'] =  '';
$outputRow['COLOR']['name'] =  'b_color[]';

$tprinth=array("S28|S", "S30|M", "S32|L", "S34|XL", "S36|2XL", "S38|3XL", "S40|4XL", "S42|5XL", "S44|6XL", "S46|7XL", "S48|8XL", "S50|9XL", "S52|10XL", "S54|11XL", "S56|12XL");
$tprint=array("S28", "S30", "S32", "S34", "S36", "S38", "S40", "S42", "S44", "S46", "S48", "S50", "S52", "S54", "S56");

	foreach($tprinth as $x ){
	$outputRow[$x]['value'] =  '';
	$outputRow[$x]['name'] =  $x.'b_size[]';
	//$outputRow[$x]['total'] =  'yes';
	}


$outputRow['TOTAL']['value'] = '';
$outputRow['TOTAL']['name'] ='b_total[]';
//$outputRow['TOTAL']['total'] =  'yes';


$output['rows'][][] = $outputRow;
$rowCount++;
$buyer = '';
$consignee = '';
$qntyvalue=0;
$sizetotal = array();
$rowvalc=0;
	while($row = mysqli_fetch_array($result))
	{

	$outputRow = array();
	if ($buyer != $row[firstcolval])
	$outputRow[$firstcol]['value'] =  $row[firstcolval];
	else
	$outputRow[$firstcol]['value'] =  '';
	$outputRow[$firstcol]['name'] =  'b_buyercode[]';
	
	
	$outputRow[$secondcol]['value'] =  $row[secondcolval];
	
    $outputRow[$secondcol]['name'] =  'b_secondcol[]';

	$outputRow['STYLE']['value'] =  $row[gencode].' | '.$row[subcat].' | '.$row[cat];
	$outputRow['STYLE']['name'] =  'b_style[]';
	$outputRow['STYLE']['tdClass'] = 'click_bill_pdf links';
	$outputRow['STYLE']['title'] = 'Double Click to View Bill';
	
	$outputRow['COLOR']['value'] =  $row[color];
	$outputRow['COLOR']['name'] =  'b_color[]';
	
		if($_POST['report_type']=="allorders")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM sordervar s inner join sorderreg on  s.`job_id`  = sorderreg.`orderid` WHERE s.prodname =  '$row[firstcolval]'  and sorderreg.orderid = '$row[secondcolval]'   GROUP BY s.prodname ";
		
		}
		else if($_POST['report_type']=="pending")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM  sordervar s inner join sorderreg on  s.`job_id`  = sorderreg.`orderid` WHERE s.prodname =  '$row[firstcolval]' and sorderreg.orderid = '$row[secondcolval]'   GROUP BY s.prodname ";
		}
		else if($_POST['report_type']=="inprocess")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM sordervar s inner join sorderreg on  s.`job_id`  = sorderreg.`orderid` WHERE s.prodname =  '$row[firstcolval]'  and sorderreg.orderid = '$row[secondcolval]'   GROUP BY s.prodname ";
		}
	
	$resultval = mysqli_query($con,$SQLcent);
	//if($resultval ){
		
		
			$qntyvalue =0;	
			$ival=1;		
			while($rowval = mysqli_fetch_array($resultval))
				{	
				     
						
						
					$sizeval = trim($rowval['psize']);
						foreach($tprinth as $y )
						{
							$arrval = ltrim($y,"S");
							$arrval1 = substr($arrval,0,2); // for size 28 to 56
							$arrval2 = explode("|",$arrval); // for size S to 9XL
							
							//if($sizeval==$arrval1||$sizeval==$arrval2[1])
							//	{
								$outputRow[$y]['value'] =  $rowval[$ival];	
								$outputRow[$y]['name'] =   $y.'b_size[]';
								
								$rowtotalval+=  $rowval[$ival];
								$qntyvalue = $rowval[$ival]; 
								$sizetotal[$y][] =  $qntyvalue;
							//	}
							/*else{
								$outputRow[$y]['value'] =  '';	
								$outputRow[$y]['name'] =  'b_size[]';
								}*/
								
								//$sizetotal = array($y => $qntyvalue);
							
							$ival++;
						}//foreach($tprinth as $y ) end
						
						//$arrvaltest = $qntyvalue;
					 //$qntyvalue=0; 
						
					
			}
			
        
	//}
	
	$outputRow['TOTAL']['value'] = $rowtotalval;
	$outputRow['TOTAL']['name'] ='b_total[]';
	
	
	$output['test'][][] = $SQLcent;
	
	$output['rows'][][] = $outputRow;
	$rowCount++;
	$qntyvalue=0; 
	$sizeval='';
	$rowvalc+=$rowtotalval;
	$rowtotalval=0;

	
	$buyer=$row[firstcolval];
	$consignee=$row[secondcolval];

	}//while($row = mysqli_fetch_array($result))
	
	$outputRow = array();
	
$outputRow[$firstcol]['value'] =  'TOTAL';
$outputRow[$firstcol]['name'] =  'b_buyercode[]';
$outputRow[$firstcol]['count'] =  'yes';

$outputRow[$secondcol]['value'] =  '-';
$outputRow[$secondcol]['name'] =  'b_secondcol[]';

$outputRow['STYLE']['value'] =  '-';
$outputRow['STYLE']['name'] =  'b_style[]';


$outputRow['COLOR']['value'] =  '-';
$outputRow['COLOR']['name'] =  'b_color[]';

foreach($tprinth as $k){
		
$outputRow[$k]['value'] =  array_sum($sizetotal[$k]);
$outputRow[$k]['name'] =  $k.'b_size[]';
	
}

$outputRow['TOTAL']['value'] = $rowvalc;
$outputRow['TOTAL']['name'] ='b_total[]';
//$outputRow['TOTAL']['total'] =  'yes';

$output['rows'][][] = $outputRow;
$rowCount++;
	
	//if displayed rows greater than 0 then sum total
	//$count_totalbill=number_format($balance,2);
	
	$output['total_rows'] =$rowCount;
	echo json_encode($output);
	}//if($result)
	else
	echo mysqli_error($con);
		
	}// end 	else if($_POST['report_typewise']=='partyconsignee')

    
	
	
	
else if($_POST['report_typewise']=='partyproduct')
	{   
	     $qrygroupby='';
		$qry_part='';
		$firstcol = 'PRODUCT';
		$secondcol = 'BUYER';
		$qrypart = "where orderdate>=STR_TO_DATE('$from_date','%Y-%m-%d') and orderdate<=STR_TO_DATE('$to_date','%Y-%m-%d')";
		if($_POST['subreport_type']=="orderwise")
		$qrygroupby = ', orderid';
	if($_POST['billedto']!="")
	$qry_part = "and gencode = '$_POST[billedto]' ";
	
	
	if($_POST['report_type']=="allorders"){
	$SQLhead = "SELECT  orderid, gencode as firstcolval, buyercode  as secondcolval, `prodname`,  color, cat, subcat, billedto  FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart $qry_part  group by `prodname`, buyercode$qrygroupby, billedto    order by `prodname`, `buyercode`, billedto ";
		}
	else if($_POST['report_type']=="pending"){
		$SQLhead = "SELECT  orderid, gencode as firstcolval, buyercode  as secondcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart  $qry_part  group by `prodname`, buyercode$qrygroupby   order by `prodname`, `buyercode`  ";
		//WHERE (sordervar.`qnty`-sordervar.`issued`) >0
		}
		
	else if($_POST['report_type']=="inprocess"){
		$SQLhead = "SELECT  orderid, gencode as firstcolval, buyercode  as secondcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart  $qry_part  group by `prodname`, buyercode$qrygroupby   order by `prodname`, `buyercode` ";
		
		//WHERE (sordervar.`qnty`-sordervar.`issued`) >0
		}
		//echo $SQLhead.'---';
	 
$result = mysqli_query($con,$SQLhead);
	
if($result)
	{
$count_totalbill=0;
$rowCount=0;
$tprinth=array("S28|S", "S30|M", "S32|L", "S34|XL", "S36|2XL", "S38|3XL", "S40|4XL", "S42|5XL", "S44|6XL", "S46|7XL", "S48|8XL", "S50|9XL", "S52|10XL", "S54|11XL", "S56|12XL");
$tprint=array("S28", "S30", "S32", "S34", "S36", "S38", "S40", "S42", "S44", "S46", "S48", "S50", "S52", "S54", "S56");


$outputRow = array();

if($_POST['subreport_type']=="orderwise"){
	$outputRow['ORDERID']['value'] =  '';
	$outputRow['ORDERID']['name'] =  'b_orderid[]';
	}

$outputRow[$firstcol]['value'] =  '';
$outputRow[$firstcol]['name'] =  'b_buyercode[]';
$outputRow[$firstcol]['count'] =  'yes';

$outputRow['STYLE']['value'] =  '';
$outputRow['STYLE']['name'] =  'b_style[]';

$outputRow['COLOR']['value'] =  '';
$outputRow['COLOR']['name'] =  'b_color[]';

$outputRow[$secondcol]['value'] =  '';
$outputRow[$secondcol]['name'] =  'b_secondcol[]';

$outputRow['CONSIGNEE']['value'] =  '';
$outputRow['CONSIGNEE']['name'] =  'b_CONSIGNEE[]';


	foreach($tprinth as $x ){
	$outputRow[$x]['value'] =  '';
	$outputRow[$x]['name'] =  $x.'b_size[]';
	//$outputRow[$x]['total'] =  'yes';
	}


$outputRow['TOTAL']['value'] = '';
$outputRow['TOTAL']['name'] ='b_total[]';
//$outputRow['TOTAL']['total'] =  'yes';


$output['rows'][][] = $outputRow;
$rowCount++;






$buyer = '';
$gencode= '';
$color= '';
$consignee = '';
$qntyvalue=0;
$sizetotal = array();
$subtotal = array();
$itemtotal = array();

	while($row = mysqli_fetch_array($result))
	{

	  
	 
	  /************************* Sub Total Start *****************************/
	
	  if ($buyer != $row[secondcolval]&&$buyer!=''){
		$outputRow = array();
		  
	if($_POST['subreport_type']=="orderwise"){
	$outputRow['ORDERID']['value'] =  '';
	$outputRow['ORDERID']['name'] =  'b_orderid[]';
	}
		  
	  $outputRow[$firstcol]['value'] =  'SUB TOTAL';
	  $outputRow[$firstcol]['name'] =  'b_buyercode[]';
	  $outputRow[$firstcol]['count'] =  'yes';
	  
	  
	  $outputRow['STYLE']['value'] =  $gencode;
	  $outputRow['STYLE']['name'] =  'b_style[]';
	  
	  $outputRow['COLOR']['value'] =  '-';
	  $outputRow['COLOR']['name'] =  'b_color[]';
	  
	  $outputRow[$secondcol]['value'] =  '-';
	  $outputRow[$secondcol]['name'] =  'b_secondcol[]';
	  
	  $outputRow['CONSIGNEE']['value'] =  '-';
	  $outputRow['CONSIGNEE']['name'] =  'b_CONSIGNEE[]';
	  
	  foreach($tprinth as $k){
			  
	  $outputRow[$k]['value'] =  array_sum($subtotal[$k]);
	  $outputRow[$k]['name'] =  $k.'b_size[]';
	   		
	  }
	  
	  $outputRow['TOTAL']['value'] = $subtotalrowval;
	  $outputRow['TOTAL']['name'] ='b_total[]';
	  //$outputRow['TOTAL']['total'] =  'yes';
	  unset($subtotal);
	  $subtotal = array();
	  $totalrowvalc+= $subtotalrowval;
	  $subtotalrowval=0;
	  $output['rows'][][] = $outputRow;
	  $rowCount++;
	  }
	 /************************* Sub Total end *****************************/
     
	 /************************* Item Total start *****************************/
	 
	  if ($gencode != $row[firstcolval]&&$gencode!=''){
		$outputRow = array();
		 
	  if($_POST['subreport_type']=="orderwise"){
	$outputRow['ORDERID']['value'] =  '';
	$outputRow['ORDERID']['name'] =  'b_orderid[]';
	}
		  
	  $outputRow[$firstcol]['value'] =  'ITEM TOTAL';
	  $outputRow[$firstcol]['name'] =  'b_buyercode[]';
	  $outputRow[$firstcol]['count'] =  'yes';
	  
	  
	  $outputRow['STYLE']['value'] =  $gencode;
	  $outputRow['STYLE']['name'] =  'b_style[]';
	  
	  $outputRow['COLOR']['value'] =  '-';
	  $outputRow['COLOR']['name'] =  'b_color[]';
	  
	  $outputRow[$secondcol]['value'] =  '-';
	  $outputRow[$secondcol]['name'] =  'b_secondcol[]';
	  
	  $outputRow['CONSIGNEE']['value'] =  '-';
	  $outputRow['CONSIGNEE']['name'] =  'b_CONSIGNEE[]';
	  
	  foreach($tprinth as $k){
			  
	  $outputRow[$k]['value'] =  array_sum($itemtotal[$k]);
	  $outputRow[$k]['name'] =  $k.'b_size[]';
	   		
	  }
	  
	  $outputRow['TOTAL']['value'] = $itemtotalval;
	  $outputRow['TOTAL']['name'] ='b_total[]';
	  //$outputRow['TOTAL']['total'] =  'yes';
	   unset($itemtotal);
	  $itemtotal = array();
	  $itemtotalval=0;
	   
	  $output['rows'][][] = $outputRow;
	  $rowCount++;
	  }
	  /************************* Item Total End *****************************/
	 
	$outputRow = array();
	
	if($_POST['subreport_type']=="orderwise"){
	$outputRow['ORDERID']['value'] =  $row[orderid];
	$outputRow['ORDERID']['name'] =  'b_orderid[]';
	}
	
	if ($gencode  != $row[firstcolval])
	$outputRow[$firstcol]['value'] =  $row[firstcolval];
	else
	$outputRow[$firstcol]['value'] =  '-';
	$outputRow[$firstcol]['name'] =  'b_buyercode[]';
	
	$outputRow['STYLE']['value'] =  $row[prodname];
	$outputRow['STYLE']['name'] =  'b_style[]';
	$outputRow['STYLE']['tdClass'] = 'click_bill_pdf links';
	$outputRow['STYLE']['title'] = 'Double Click to View Bill';
     if($row[color]==''){
		$row[color]='-'; 
		 }

	$outputRow['COLOR']['value'] =  $row[color];
	$outputRow['COLOR']['name'] =  'b_color[]';
	
	
	$outputRow[$secondcol]['value'] =  $row[secondcolval];
    $outputRow[$secondcol]['name'] =  'b_secondcol[]';
    
	$outputRow['CONSIGNEE']['value'] =  $row[billedto].'-'.$row[orderid];
	  $outputRow['CONSIGNEE']['name'] =  'b_CONSIGNEE[]';
	
		if($_POST['report_type']=="allorders")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM sordervar s  inner join sorderreg on  `job_id`  = `orderid`    WHERE s.prodname =  '$row[prodname]' and sorderreg.buyercode = '$row[secondcolval]' and sorderreg.billedto = '$row[billedto]' GROUP BY s.prodname";
		
		}
		else if($_POST['report_type']=="pending")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM sordervar s inner join sorderreg on  `job_id`  = `orderid`    WHERE s.prodname =  '$row[prodname]' and sorderreg.buyercode = '$row[secondcolval]' and sorderreg.billedto = '$row[billedto]' GROUP BY s.prodname ";
		}
		else if($_POST['report_type']=="inprocess")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM sordervar s inner join sorderreg on  `job_id`  = `orderid` WHERE s.prodname =  '$row[prodname]' and sorderreg.buyercode = '$row[secondcolval]' and sorderreg.billedto = '$row[billedto]'  GROUP BY s.prodname";
		}
	
	$resultval = mysqli_query($con,$SQLcent);
	//if($resultval ){
		
		
			$qntyvalue =0;	
			$ival=1;
			
			while($rowval = mysqli_fetch_array($resultval))
				{	
				     
						
						
					$sizeval = trim($rowval['psize']);
						foreach($tprinth as $y )
						{
							$arrval = ltrim($y,"S");
							$arrval1 = substr($arrval,0,2); // for size 28 to 56
							$arrval2 = explode("|",$arrval); // for size S to 9XL
							
							//if($sizeval==$arrval1||$sizeval==$arrval2[1])
							//	{
								$outputRow[$y]['value'] =  $rowval[$ival];	
								$outputRow[$y]['name'] =   $y.'b_size[]';
								
								$rowtotalval+=  $rowval[$ival];
								$qntyvalue = $rowval[$ival]; 
								$sizetotal[$y][] =  $qntyvalue;
								$subtotal[$y][] =  $qntyvalue;
								$itemtotal[$y][] =  $qntyvalue;
							//	}
							/*else{
								$outputRow[$y]['value'] =  '';	
								$outputRow[$y]['name'] =  'b_size[]';
								}*/
								
								//$sizetotal = array($y => $qntyvalue);
							
							$ival++;
						}//foreach($tprinth as $y ) end
						
						//$arrvaltest = $qntyvalue;
					 //$qntyvalue=0; 
						
					
			}
			
        
	//}
	if($rowtotalval<=0){
		$rowtotalval="-";
		}
	
	$outputRow['TOTAL']['value'] = $rowtotalval;
	$outputRow['TOTAL']['name'] ='b_total[]';
	
	
	$output['test'][][] = $SQLcent;
	
	$output['rows'][][] = $outputRow;
	$rowCount++;
	
	
	$qntyvalue=0; 
	$sizeval='';
	$subtotalrowval+=$rowtotalval;
	$itemtotalval+=$rowtotalval;
	$rowtotalval=0;

	
	$buyer		=$row[secondcolval];
	$gencode 	=$row[firstcolval];
	$color 		=$row[color];

	}//while($row = mysqli_fetch_array($result))
	
	$outputRow = array();
	
	if($_POST['subreport_type']=="orderwise"){
	$outputRow['ORDERID']['value'] =  '';
	$outputRow['ORDERID']['name'] =  'b_orderid[]';
	}
	
	$outputRow['PRODUCT']['value'] =  'SUB TOTAL';
	$outputRow['PRODUCT']['name'] =  'b_buyercode[]';

	$outputRow['STYLE']['value'] =  $gencode;
	$outputRow['STYLE']['name'] =  'b_style[]';
	
	$outputRow['COLOR']['value'] =  $color;
	$outputRow['COLOR']['name'] =  'b_color[]';
	
	$outputRow['BUYER']['value'] =  '-';
	$outputRow['BUYER']['name'] =  'b_secondcol[]';
	
	$outputRow['CONSIGNEE']['value'] = '-';
	$outputRow['CONSIGNEE']['name'] =  'b_CONSIGNEE[]';
	
	foreach($tprinth as $k){
	$outputRow[$k]['value'] =  array_sum($subtotal[$k]);
	$outputRow[$k]['name'] =  $k.'b_size[]';	
	}
	
	$outputRow['TOTAL']['value'] = $subtotalrowval;
	$outputRow['TOTAL']['name'] ='b_total[]';
	
    $totalrowvalc+= $subtotalrowval;
	$subtotalrowval=0;
	
	$output['rows'][][] = $outputRow;
	$rowCount++;
	
	 /************************* Item Total start *****************************/
	 
	  if ($gencode != $row[gencode]&&$gencode!=''){
		$outputRow = array();
	 
	  if($_POST['subreport_type']=="orderwise"){
	$outputRow['ORDERID']['value'] =  '';
	$outputRow['ORDERID']['name'] =  'b_orderid[]';
	}
	   
	  $outputRow[$firstcol]['value'] =  'ITEM TOTAL';
	  $outputRow[$firstcol]['name'] =  'b_buyercode[]';
	  $outputRow[$firstcol]['count'] =  'yes';
	  
	  
	  $outputRow['STYLE']['value'] =  $gencode;
	  $outputRow['STYLE']['name'] =  'b_style[]';
	  
	  $outputRow['COLOR']['value'] =  '-';
	  $outputRow['COLOR']['name'] =  'b_color[]';
	  
	  $outputRow[$secondcol]['value'] =  '-';
	  $outputRow[$secondcol]['name'] =  'b_secondcol[]';
	  
	  $outputRow['CONSIGNEE']['value'] =  '-';
	  $outputRow['CONSIGNEE']['name'] =  'b_CONSIGNEE[]';
	  
	  foreach($tprinth as $k){
			  
	  $outputRow[$k]['value'] =  array_sum($itemtotal[$k]);
	  $outputRow[$k]['name'] =  $k.'b_size[]';
	   		
	  }
	  
	  $outputRow['TOTAL']['value'] = $itemtotalval;
	  $outputRow['TOTAL']['name'] ='b_total[]';
	  //$outputRow['TOTAL']['total'] =  'yes';
	   unset($itemtotal);
	  $itemtotal = array();
	  $itemtotalval=0;
	   
	  $output['rows'][][] = $outputRow;
	  $rowCount++;
	  }
	  /************************* Item Total End *****************************/
	
	$outputRow = array();
	
	if($_POST['subreport_type']=="orderwise"){
	$outputRow['ORDERID']['value'] =  '';
	$outputRow['ORDERID']['name'] =  'b_orderid[]';
	}
		
	$outputRow['PRODUCT']['value'] =  'TOTAL';
	$outputRow['PRODUCT']['name'] =  'b_buyercode[]';

	$outputRow['STYLE']['value'] =  '-';
	$outputRow['STYLE']['name'] =  'b_style[]';
	
	$outputRow['COLOR']['value'] =  '-';
	$outputRow['COLOR']['name'] =  'b_color[]';
	
	$outputRow['BUYER']['value'] =  '-';
	$outputRow['BUYER']['name'] =  'b_secondcol[]';
	
	$outputRow['CONSIGNEE']['value'] =  '-';
	$outputRow['CONSIGNEE']['name'] =  'b_CONSIGNEE[]';
	
	foreach($tprinth as $k){
	$outputRow[$k]['value'] =  array_sum($sizetotal[$k]);
	$outputRow[$k]['name'] =  $k.'b_size[]';	
	}
	
	$outputRow['TOTAL']['value'] = $totalrowvalc;
	$outputRow['TOTAL']['name'] ='b_total[]';

	
	$output['rows'][][] = $outputRow;
	$rowCount++;
	
	$output['total_rows'] =$rowCount;
	echo json_encode($output);
	}//if($result)
	else
	echo mysqli_error($con);
		
}// end 	else if($_POST['report_typewise']=='partyproduct')

	
	else
	{
		
	if($_POST['report_typewise']=='partywise')
	{
		$qry_part='';
		$firstcol = 'BUYER';
		$qrygroupby ='';
		$qrypart = "where orderdate>=STR_TO_DATE('$from_date','%Y-%m-%d') and orderdate<=STR_TO_DATE('$to_date','%Y-%m-%d')  ";
				
		if($_POST['subreport_type']=="orderwise")
		$qrygroupby = ', orderid';
	    if($_POST['billedto']!="")
		$qry_part = "and buyercode = '$_POST[billedto]'";
		
	
	if($_POST['report_type']=="allorders"){
		$SQLhead = "SELECT orderid,buyercode as firstcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart $qry_part   group by buyercode, `prodname`$qrygroupby  order by buyercode, `prodname`";
		}
	else if($_POST['report_type']=="pending"){
	$SQLhead = "SELECT orderid,`prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`),sizesetcode FROM `sordervar` inner join prodreg on prodname = code $qrypart $qry_part    group by `prodname` $qrygroupby ";
	// WHERE (sordervar.`qnty`-sordervar.`issued`) >0
		}
		
	else if($_POST['report_type']=="inprocess"){
	$SQLhead = "SELECT orderid,`prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`),sizesetcode FROM `sordervar` inner join prodreg on prodname = code $qrypart $qry_part  group by `prodname`$qrygroupby ";
	//WHERE (sordervar.`qnty`-sordervar.`issued`) >0 
		}
		
		
	}	

	else if($_POST['report_typewise']=='consignee')
	{
		$qry_part='';
		$firstcol = 'CONSIGNEE';
		
		$qrygroupby ='';
		$qrypart = "where orderdate>=STR_TO_DATE('$from_date','%Y-%m-%d') and orderdate<=STR_TO_DATE('$to_date','%Y-%m-%d')  ";
				
		if($_POST['subreport_type']=="orderwise")
		$qrygroupby = ', orderid';
		
	if($_POST['billedto']!="")
	$qry_part = "where billedto = '$_POST[billedto]'";
	
	if($_POST['report_type']=="allorders"){
	$SQLhead = "SELECT orderid, billedto as firstcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart $qry_part   group by buyercode, `prodname`$qrygroupby  order by buyercode, billedto, `prodname`";
		}
	else if($_POST['report_type']=="pending"){
		$SQLhead = "SELECT orderid, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`),sizesetcode FROM `sordervar` inner join prodreg on prodname = code  $qrypart $qry_part  group by `prodname`$qrygroupby ";
		//WHERE (sordervar.`qnty`-sordervar.`issued`) >0
		}
		
	else if($_POST['report_type']=="inprocess"){
		$SQLhead = "SELECT orderid, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`),sizesetcode FROM `sordervar` inner join prodreg on prodname = code  $qrypart $qry_part  group by `prodname`$qrygroupby ";
		//WHERE (sordervar.`qnty`-sordervar.`issued`) >0
		}
		
		
		
	}
	
	else if($_POST['report_typewise']=='citywise'){
		$qry_part='';
		$firstcol = 'CITY';
		
		$qrygroupby ='';
		$qrypart = "where orderdate>=STR_TO_DATE('$from_date','%Y-%m-%d') and orderdate<=STR_TO_DATE('$to_date','%Y-%m-%d')  ";
				
		if($_POST['subreport_type']=="orderwise")
		$qrygroupby = ', orderid';
		
		if($_POST['billedto']!="")
	    $qry_part = "where cmpcity = '$_POST[billedto]'";
	
	if($_POST['report_type']=="allorders"){
	$SQLhead = "SELECT orderid, cmpcity as firstcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` inner join commst  on buyercode = compid $qrypart $qry_part   group by cmpcity, `prodname`$qrygroupby  order by buyercode, `prodname`";
		}
	else if($_POST['report_type']=="pending"){
		$SQLhead = "SELECT orderid, cmpcity as firstcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` inner join commst  on buyercode = compid $qrypart $qry_part   group by cmpcity, `prodname`  order by buyercode, `prodname`";
		//WHERE (sordervar.`qnty`-sordervar.`issued`) >0
		}
		
	else if($_POST['report_type']=="inprocess"){
		$SQLhead = "SELECT orderid, cmpcity as firstcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` inner join commst  on buyercode = compid $qrypart $qry_part   group by cmpcity, `prodname`$qrygroupby  order by buyercode, `prodname`";
		//WHERE (sordervar.`qnty`-sordervar.`issued`) >0
		}
		
	}
	
		else if($_POST['report_typewise']=='agentwise'){
		$firstcol = 'AGENT';
		
		$qrygroupby ='';
		$qrypart = "where orderdate>=STR_TO_DATE('$from_date','%Y-%m-%d') and orderdate<=STR_TO_DATE('$to_date','%Y-%m-%d')  ";
				
		if($_POST['subreport_type']=="orderwise")
		$qrygroupby = ', orderid';
		
		if($_POST['billedto']!="")
		$qry_part = "and agentcode = '$_POST[billedto]'";
	
	if($_POST['report_type']=="allorders"){
	$SQLhead = "SELECT orderid, agentcode as firstcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart $qry_part   group by agentcode, `prodname`$qrygroupby  order by buyercode, `prodname`";
		}
	else if($_POST['report_type']=="pending"){
		$SQLhead = "SELECT orderid, agentcode as firstcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart $qry_part   group by agentcode, `prodname`$qrygroupby  order by buyercode, `prodname`";
		//WHERE (sordervar.`qnty`-sordervar.`issued`) >0
		}
		
		
	else if($_POST['report_type']=="inprocess"){
		$SQLhead = "SELECT agentcode as firstcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart $qry_part   group by agentcode, `prodname`$qrygroupby  order by buyercode, `prodname`";
		//WHERE (sordervar.`qnty`-sordervar.`issued`) >0
		}
		
	}
	
else if($_POST['report_typewise']=='distributor'){
		$firstcol = 'DISTRIBUTOR';
		
		$qrygroupby ='';
		$qrypart = "where orderdate>=STR_TO_DATE('$from_date','%Y-%m-%d') and orderdate<=STR_TO_DATE('$to_date','%Y-%m-%d')  ";
				
		if($_POST['subreport_type']=="orderwise")
		$qrygroupby = ', orderid';
		
		if($_POST['billedto']!="")
	    $qry_part = "and distr = '$_POST[billedto]'";
	
	if($_POST['report_type']=="allorders"){
	$SQLhead = "SELECT distr as firstcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart $qry_part group by agentcode, `prodname`$qrygroupby  order by distr, `prodname`";
		}
	else if($_POST['report_type']=="pending"){
		$SQLhead = "SELECT distr as firstcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart $qry_part  group by agentcode, `prodname`$qrygroupby  order by distr, `prodname`";
		//WHERE (sordervar.`qnty`-sordervar.`issued`) >0
		}
		
		
	else if($_POST['report_type']=="inprocess"){
		$SQLhead = "SELECT distr as firstcolval, `prodname`, gencode, color, cat, subcat, Sum(sordervar.`qnty`-sordervar.`issued`), sizesetcode FROM `sordervar` inner join prodreg on prodname = code inner join sorderreg on  sordervar.`job_id`  = sorderreg.`orderid` $qrypart $qry_part group by agentcode, `prodname`  order by distr, `prodname`";
		//WHERE (sordervar.`qnty`-sordervar.`issued`) >0
		}
		
	}
	 
$result = mysqli_query($con,$SQLhead);
	
if($result)
	{
$count_totalbill=0;
$rowCount=0;
$outputRow = array();

if($_POST['subreport_type']=="orderwise"){
$outputRow['ORDERID']['value'] =  '';
$outputRow['ORDERID']['name'] =  'b_orderid[]';
}

$outputRow[$firstcol]['value'] =  '';
$outputRow[$firstcol]['name'] =  'b_buyercode[]';
$outputRow[$firstcol]['count'] =  'yes';

$outputRow['STYLE']['value'] =  '';
$outputRow['STYLE']['name'] =  'b_style[]';


$outputRow['COLOR']['value'] =  '';
$outputRow['COLOR']['name'] =  'b_color[]';

$tprinth=array("S28|S", "S30|M", "S32|L", "S34|XL", "S36|2XL", "S38|3XL", "S40|4XL", "S42|5XL", "S44|6XL", "S46|7XL", "S48|8XL", "S50|9XL", "S52|10XL", "S54|11XL", "S56|12XL");
$tprint=array("S28", "S30", "S32", "S34", "S36", "S38", "S40", "S42", "S44", "S46", "S48", "S50", "S52", "S54", "S56");

	foreach($tprinth as $x ){
	$outputRow[$x]['value'] =  '';
	$outputRow[$x]['name'] =  $x.'b_size[]';
	//$outputRow[$x]['total'] =  'yes';
	}


$outputRow['TOTAL']['value'] = '';
$outputRow['TOTAL']['name'] ='b_total[]';
//$outputRow['TOTAL']['total'] =  'yes';


$output['rows'][][] = $outputRow;
$rowCount++;
$buyer = '';
$qntyvalue=0;
$sizetotal = array();
$rowvalc=0;
	while($row = mysqli_fetch_array($result))
	{
		
		
		if ($buyer != $row[firstcolval]&&$buyer != ''){
			
			$outputRow = array();
			
			if($_POST['subreport_type']=="orderwise"){
            $outputRow['ORDERID']['value'] =  '';
            $outputRow['ORDERID']['name'] =  'b_orderid[]';
            }
			
			$outputRow[$firstcol]['tdClass'] = 'removtot';
			$outputRow[$firstcol]['value'] =  'TOTAL';
			$outputRow[$firstcol]['name'] =  'b_buyercode[]';
			
			$outputRow['STYLE']['tdClass'] = 'removtot';
			$outputRow['STYLE']['value'] =  '-';
			$outputRow['STYLE']['name'] =  'b_style[]';
			
			$outputRow['COLOR']['tdClass'] = 'removtot';
			$outputRow['COLOR']['value'] =  '-';
			$outputRow['COLOR']['name'] =  'b_color[]';
			
			
			
			foreach($tprinth as $k ){
			
			$outputRow[$k]['tdClass'] = 'removtot';	
			$outputRow[$k]['value'] =  array_sum($subtotal[$k]);
			$outputRow[$k]['name'] =  $k.'b_size[]';
			
			}
			
			$outputRow['TOTAL']['tdClass'] = 'removtot';
			$outputRow['TOTAL']['value'] = $subtotalrowval;
			$outputRow['TOTAL']['name'] ='b_total[]';
			
			  unset($subtotal);
			  $subtotal = array();
			  $totalrowvalc+= $subtotalrowval;
			  $subtotalrowval=0;
			
			$output['rows'][][] = $outputRow;
			$rowCount++;	
			
			
			
		}
		
		
		

	$outputRow = array();
	
	if($_POST['subreport_type']=="orderwise"){
            $outputRow['ORDERID']['value'] =  $row[orderid];
            $outputRow['ORDERID']['name'] =  'b_orderid[]';
            }
	
	if ($buyer != $row[firstcolval])
	$outputRow[$firstcol]['value'] =  $row[firstcolval];
	else
	$outputRow[$firstcol]['value'] =  '';
	$outputRow[$firstcol]['name'] =  'b_buyercode[]';

	$outputRow['STYLE']['value'] =  $row[gencode].' | '.$row[subcat].' | '.$row[cat];
	$outputRow['STYLE']['name'] =  'b_style[]';
	$outputRow['STYLE']['tdClass'] = 'click_bill_pdf links';
	$outputRow['STYLE']['title'] = 'Double Click to View Bill';
	
	$outputRow['COLOR']['value'] =  $row[color];
	$outputRow['COLOR']['name'] =  'b_color[]';
	
	$subQuery='';
	$subQuery1 ='';
	if($_POST['report_typewise']=='partywise')
	{
	$subQuery = "and sorderreg.buyercode = '$row[firstcolval]'";
	}
	else if($_POST['report_typewise']=='consignee')
	{
	$subQuery = "and sorderreg.billedto = '$row[firstcolval]'";
	}
	
	else if($_POST['report_typewise']=='agentwise')
	{
	$subQuery = "and sorderreg.agentcode = '$row[firstcolval]'";
	}
	else if($_POST['report_typewise']=='distributor'){
	$subQuery = "and sorderreg.distr = '$row[firstcolval]'";	
	}
		if($_POST['report_type']=="allorders")
		{
			//$SQLcent = "SELECT `size` as psize, sum(qnty) as qnty FROM `sordervar` where prodname = '$row[prodname]' group by size order by `entryid`  ";
			
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM sordervar s inner join sorderreg on  `job_id`  = `orderid`    WHERE s.prodname =  '$row[prodname]' $subQuery  GROUP BY s.prodname";
		}
		else if($_POST['report_type']=="pending")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM sordervar s inner join sorderreg on  `job_id`  = `orderid` WHERE s.prodname =  '$row[prodname]' $subQuery   group by s.prodname ";
		}
		else if($_POST['report_type']=="inprocess")
		{
			$SQLcent = "SELECT s.prodname, SUM( IF( TRIM(s.size) =  'S' || TRIM(s.size) =  '28', s.qnty, 0 ) ) S, SUM( IF( TRIM(s.size) =  'M' || TRIM(s.size) =  '30', s.qnty, 0 ) ) M, SUM( IF( TRIM(s.size) =  'L' || TRIM(s.size) =  '32', s.qnty, 0 ) ) L, SUM( IF( TRIM(s.size) =  'XL' || TRIM(s.size) =  '34', s.qnty, 0 ) ) XL, SUM( IF( TRIM(s.size) =  '2XL' || TRIM(s.size) =  '36', s.qnty, 0 ) ) 2XL, SUM( IF( TRIM(s.size) =  '3XL' || TRIM(s.size) =  '38', s.qnty, 0 ) ) 3XL, SUM( IF( TRIM(s.size) =  '4XL' || TRIM(s.size) =  '40', s.qnty, 0 ) ) 4XL, SUM( IF( TRIM(s.size) =  '5XL' || TRIM(s.size) =  '42', s.qnty, 0 ) ) 5XL, SUM( IF( TRIM(s.size) =  '6XL' || TRIM(s.size) =  '44', s.qnty, 0 ) ) 6XL, SUM( IF( TRIM(s.size) =  '7XL' || TRIM(s.size) =  '46', s.qnty, 0 ) ) 7XL, SUM( IF( TRIM(s.size) =  '8XL' || TRIM(s.size) =  '48', s.qnty, 0 ) ) 8XL, SUM( IF( TRIM(s.size) =  '9XL' || TRIM(s.size) =  '50', s.qnty, 0 ) ) 9XL, SUM( IF( TRIM(s.size) =  '10XL' || TRIM(s.size) =  '52', s.qnty, 0 ) ) 10XL, SUM( IF( TRIM(s.size) =  '11XL' || TRIM(s.size) =  '54', s.qnty, 0 ) ) 11XL, SUM( IF( TRIM(s.size) =  '12XL' || TRIM(s.size) =  '56', s.qnty, 0 ) ) 12XL FROM sordervar s inner join sorderreg on  `job_id`  = `orderid` WHERE s.prodname =  '$row[prodname]' $subQuery and (`qnty`-`pissued`) >0 group by s.prodname ";
		}
	
	$resultval = mysqli_query($con,$SQLcent);
	//if($resultval ){
		
				$qntyvalue=0;
				$ival=1;		
			while($rowval = mysqli_fetch_array($resultval))
				{	

					$sizeval = trim($rowval['size']);
						foreach($tprinth as $y)
						{
							$arrval = ltrim($y,"S");
							$arrval1 = substr($arrval,0,2); // for size 28 to 56
							$arrval2 = explode("|",$arrval); // for size S to 9XL
							
							//if($sizeval==$arrval1||$sizeval==$arrval2[1])
								//{
								$outputRow[$y]['value'] =  $rowval[$ival];	
								$outputRow[$y]['name'] =  $y.'b_size[]';
								
								$rowtotalval+=  $rowval[$ival];
								$qntyvalue = $rowval[$ival]; 
								$sizetotal[$y][] =  $qntyvalue;
								$subtotal[$y][] =  $qntyvalue;
								//}
							//else{
							//	$outputRow[$y]['value'] =  $y;	
							//	$outputRow[$y]['name'] =  'b_size[]';
							//	}
							$ival++;								
						}//foreach($tprinth as $y ) end
						
						
					
				}
			
       /* if($ival<15){
			for($x=$ival; $x<=$ival; )
						{
			$outputRow['TOTAL']['value'] = $rowtotalval;
	        $outputRow['TOTAL']['name'] ='b_total[]';
						}
			}*/
	//}
	
	$outputRow['TOTAL']['value'] = $rowtotalval;
	$outputRow['TOTAL']['name'] ='b_total[]';
	
	
	//$output['test'][][] = $SQLcent;
	
	$output['rows'][][] = $outputRow;
	$rowCount++;
	$qntyvalue=0; 
	$sizeval='';
	$subtotalrowval+=$rowtotalval;
	$rowvalc+=$rowtotalval;
	$rowtotalval=0;
	$buyer=$row[firstcolval];

	}//while($row = mysqli_fetch_array($result))
	
	$outputRow = array();
	
	if($_POST['subreport_type']=="orderwise"){
            $outputRow['ORDERID']['value'] =  '';
            $outputRow['ORDERID']['name'] =  'b_orderid[]';
            }
			$outputRow[$firstcol]['tdClass'] = 'removtot';
			$outputRow[$firstcol]['value'] =  'TOTAL';
			$outputRow[$firstcol]['name'] =  'b_buyercode[]';
			
			$outputRow['STYLE']['tdClass'] = 'removtot';
			$outputRow['STYLE']['value'] =  '-';
			$outputRow['STYLE']['name'] =  'b_style[]';
			
			$outputRow['COLOR']['tdClass'] = 'removtot';
			$outputRow['COLOR']['value'] =  '-';
			$outputRow['COLOR']['name'] =  'b_color[]';
			
			
			
			foreach($tprinth as $k ){
			
			$outputRow[$k]['tdClass'] = 'removtot';	
			$outputRow[$k]['value'] =  array_sum($subtotal[$k]);
			$outputRow[$k]['name'] =  $k.'b_size[]';
			
			}
			
			$outputRow['TOTAL']['tdClass'] = 'removtot';
			$outputRow['TOTAL']['value'] = $subtotalrowval;
			$outputRow['TOTAL']['name'] ='b_total[]';
			
			  unset($subtotal);
			  $subtotal = array();
			  $totalrowvalc+= $subtotalrowval;
			  $subtotalrowval=0;
			
			$output['rows'][][] = $outputRow;
			$rowCount++;	
	
$outputRow = array();
$outputRow[$firstcol]['tdClass'] = 'removtot';
$outputRow[$firstcol]['value'] =  'TOTAL';
$outputRow[$firstcol]['name'] =  'b_buyercode[]';

$outputRow['STYLE']['tdClass'] = 'removtot';
$outputRow['STYLE']['value'] =  '-';
$outputRow['STYLE']['name'] =  'b_style[]';

$outputRow['COLOR']['tdClass'] = 'removtot';
$outputRow['COLOR']['value'] =  '-';
$outputRow['COLOR']['name'] =  'b_color[]';



	foreach($tprinth as $k ){
		
	$outputRow[$k]['tdClass'] = 'removtot';	
	$outputRow[$k]['value'] =  array_sum($sizetotal[$k]);
	$outputRow[$k]['name'] =  $k.'b_size[]';
	
	}

$outputRow['TOTAL']['tdClass'] = 'removtot';
$outputRow['TOTAL']['value'] = $rowvalc;
$outputRow['TOTAL']['name'] ='b_total[]';


$output['rows'][][] = $outputRow;
$rowCount++;
	
	//if displayed rows greater than 0 then sum total
	//$count_totalbill=number_format($balance,2);
	
	$output['total_rows'] =$rowCount;
	echo json_encode($output);
	}//if($result)
	else
	echo mysqli_error($con);
		
	}
}


else if($_POST['report_view_type']=="jobreg")
{
	
	if($_POST['report_type']=="alljobs"){
	$SQLhead = "select jobreg.jobid as 'JOBID', batchno as 'BATCHNO', refno as 'REFNO', prodcode as 'PRODCODE', gencode as 'STYLE', DATE_FORMAT(`issdate`,'%d/%m/%Y') as 'ISSDATE', DATE_FORMAT(`divdate`,'%d/%m/%Y') 'DIVDATE', jobcode as 'JOBCODE', transport as 'TRANSPORT', Supervisor as 'SUPERVISOR', scontact 'SUP. CONTACT', jobreg.status AS 'JOB STATUS' from  jobreg inner join jobregdet on jobreg.jobid = jobregdet.jobid inner join prodreg on code = prodcode  order by jobid desc ";
		}
	else if($_POST['report_type']=="Pendingjobs"){
		$SQLhead = "select jobreg.jobid as 'JOBID', batchno as 'BATCHNO', refno as 'REFNO', prodcode as 'PRODCODE', gencode as 'STYLE', DATE_FORMAT(`issdate`,'%d/%m/%Y') as 'ISSDATE', DATE_FORMAT(`divdate`,'%d/%m/%Y') 'DIVDATE', jobcode as 'JOBCODE', transport as 'TRANSPORT', Supervisor as 'SUPERVISOR', scontact 'SUP. CONTACT', jobreg.status AS 'JOB STATUS' from  jobreg inner join jobregdet on jobreg.jobid = jobregdet.jobid inner join prodreg on code = prodcode where jobreg.status != '70' order by jobid desc  ";
		}
		else if($_POST['report_type']=="compltjobs"){
		$SQLhead = "select jobreg.jobid as 'JOBID', batchno as 'BATCHNO', refno as 'REFNO', prodcode as 'PRODCODE', gencode as 'STYLE', DATE_FORMAT(`issdate`,'%d/%m/%Y') as 'ISSDATE', DATE_FORMAT(`divdate`,'%d/%m/%Y') 'DIVDATE', jobcode as 'JOBCODE', transport as 'TRANSPORT', Supervisor as 'SUPERVISOR', scontact 'SUP. CONTACT', jobreg.status AS 'JOB STATUS' from  jobreg inner join jobregdet on jobreg.jobid = jobregdet.jobid inner join prodreg on code = prodcode  where jobreg.status = '70'  order by jobid desc ";
		}
	
	 
	$result = mysqli_query($con,$SQLhead);
	
	if($result)
	{

	$i=0;
	$count_totalbill=0;

$output['total_rows'] =mysqli_num_rows($result);

while($book_info_row=mysqli_fetch_assoc($result))
{
	$sqlRow = $book_info_row;

	$index = 0;
	//$outputRow['value'] = $bill_info_row;	
	foreach ($sqlRow as $key=>$value) {	
		
	/* 
	 * start
	 * getting field name of table
	*/	
    $outputRow[$key]['value'] = $value;
	
	addDataBaseName($outputRow,$book_info,$index,$key,'',1);
	
	//mysqli_field_seek($book_info,$index);
	$index++;
  	//$fieldinfo=mysqli_fetch_field($book_info);
	//$outputRow[$key]['name'] = $fieldinfo->orgname;
	$field_orgname = $outputRow[$key]['name'];
	
	/* 
	 * end
	*/
	
	
	//adding class
	
	addClassName($outputRow,$key);
	
	if($key == 'JOBID')
	{
		
	addFooterCounter($outputRow,$key);
		$outputRow[$key]['tdClass'] = 'srno links';
		$outputRow[$key]['title'] = 'Double Click Add or Remove Duty Slip';
	}
		$statusArray = $_SESSION[SESS_STATUSARR];
	if($key == 'JOB STATUS')
	{
		if($value!='')
     $outputRow[$key]['value'] = $statusArray[$value];
	 else
	 $outputRow[$key]['value'] = '';
	}
		
	$totalKeyArray = array( 'TOTAL' , 'DISCOUNT AMT',  'NETAMOUNT',  'VAT', 'GRAND TOTAL', 'PAID');
	
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
		
	}
	
	$output['rows'][][] = $outputRow;	
	} // while ends
}
	
	

echo json_encode($output);		
	
}

else if($_POST['report_view_type']=="jobregold")
{
if ($_POST['report_typewise']=='all'){
		if($_POST['billedto']=="")
		$qry_part = "where byercode = '$_POST[billedto]'";
	
	if($_POST['report_type']=="alljobs"){
	$SQLhead = "SELECT jobbername, `prodcode`,  jobreg.jobid, colorcode, cat, shortdesc, Sum(jobvar.`qnty`-jobvar.`issued`), sizeset FROM `jobvar` inner join jobregdet on prodname = prodcode inner join jobreg on  jobvar.`job_id`  = jobreg.`jobid`  group by jobbername, `prodname`  order by jobbername, `prodname`";
		}
	else if($_POST['report_type']=="Pendingjobs"){
		$SQLhead = "SELECT `prodname`, gencode, color, cat, subcat, Sum(jobvar.`qnty`-jobvar.`issued`),sizesetcode FROM `jobvar` inner join prodreg on prodname = code WHERE (jobvar.`qnty`-jobvar.`issued`) >0 group by `prodname` ";
		}
		
	else if($_POST['report_type']=="compltjobs"){
		$SQLhead = "SELECT `prodname`, gencode, color, cat, subcat, Sum(jobvar.`qnty`-jobvar.`issued`),sizesetcode FROM `jobvar` inner join prodreg on prodname = code WHERE (jobvar.`qnty`-jobvar.`issued`) >0 group by `prodname` ";
		}
}
	
	 
$result = mysqli_query($con,$SQLhead);
	
if($result)
	{
$count_totalbill=0;
$rowCount=0;
$outputRow = array();

$outputRow['STYLE']['value'] =  '';
$outputRow['STYLE']['name'] =  'b_style[]';

$outputRow['JOBID']['value'] =  '';
$outputRow['JOBID']['name'] =  'b_jobid[]';
	
$outputRow['COLOR']['value'] =  '';
$outputRow['COLOR']['name'] =  'b_color[]';

$tprinth=array("S28|S", "S30|M", "S32|L", "S34|XL", "S36|2XL", "S38|3XL", "S40|4XL", "S42|5XL", "S44|6XL", "S46|7XL", "S48|8XL", "S50|9XL", "S52|10XL", "S54|11XL", "S56|12XL");
$tprint=array("S28", "S30", "S32", "S34", "S36", "S38", "S40", "S42", "S44", "S46", "S48", "S50", "S52", "S54", "S56");

	foreach($tprinth as $x ){
	$outputRow[$x]['value'] =  '';
	$outputRow[$x]['name'] =  'b_size[]';
	$outputRow[$x]['total'] =  'yes';
	}

$outputRow['TOTAL']['value'] = '';
$outputRow['TOTAL']['name'] ='b_total[]';
//$outputRow['TOTAL']['total'] =  'yes';


$output['rows'][][] = $outputRow;
$rowCount++;
$qntyvalue=0;
$sizetotal = array();
	while($row = mysqli_fetch_array($result))
	{

	$outputRow = array();
	
	
	$outputRow['STYLE']['value'] =  $row[prodcode].' | '.$row[shortdesc].' | '.$row[cat];
	$outputRow['STYLE']['name'] =  'b_style[]';
	$outputRow['STYLE']['tdClass'] = 'click_bill_pdf links';
	$outputRow['STYLE']['title'] = 'Double Click to View Bill';
	
	$outputRow['JOBID']['value'] =  $row[jobid];
	$outputRow['JOBID']['name'] =  'b_jobid[]';
	
	$outputRow['COLOR']['value'] =  $row[colorcode];
	$outputRow['COLOR']['name'] =  'b_color[]';
	
		if($_POST['report_type']=="alljobs")
		{
			$SQLcent = "SELECT `size` as psize, sum(qnty) as qnty FROM `jobvar` where prodname = '$row[prodcode]' group by size order by `entryid`  ";
		}
		else if($_POST['report_type']=="Pendingjobs")
		{
			$SQLcent = "SELECT `size` as psize, sum(qnty) as qnty FROM `jobvar` where job_id = '$row[jobid]' and  prodname = '$row[prodname]' and (`qnty`-`issued`) >0 group by size order by `entryid` ";
		}
		else if($_POST['report_type']=="compltjobs")
		{
			$SQLcent = "SELECT `size` as psize, sum(qnty) as qnty FROM `jobvar` where job_id = '$row[jobid]' and  prodname = '$row[prodname]' and (`qnty`-`pissued`) >0 group by size order by `entryid`  ";
		}
	
	$resultval = mysqli_query($con,$SQLcent);
	//if($resultval ){
		$qntyvalue=0;
			while($rowval = mysqli_fetch_array($resultval))
				{	

					$sizeval = trim($rowval['psize']);
						foreach($tprinth as $y )
						{
							$arrval = ltrim($y,"S");
							$arrval1 = substr($arrval,0,2); // for size 28 to 56
							$arrval2 = explode("|",$arrval); // for size S to 9XL
							
							if($sizeval==$arrval1||$sizeval==$arrval2[1])
								{
								$outputRow[$y]['value'] =  $rowval['qnty'];	
								$outputRow[$y]['name'] =  'b_size[]';
								
								$rowtotalval+=  $rowval['qnty'];
								$qntyvalue = $rowval['qnty']; 
								$sizetotal[$y][] =  $qntyvalue;
								
								
								}
							//	else
							//	{
							//	$outputRow[$y]['value'] =  ''.ltrim($y,"S").'--'.$sizeval;	
							//	$outputRow[$y]['name'] =  'b_size[]';	
							//	}
								
						}

			}
			
        
	//}
	
	$outputRow['TOTAL']['value'] = $rowtotalval;
	$outputRow['TOTAL']['name'] ='b_total[]';
	
	
	$output['test'][][] = $SQLcent;
	
	$output['rows'][][] = $outputRow;
	$rowCount++;
	$qntyvalue=0; 
	$sizeval='';
	$rowtotalval=0;
	//$count_totalbill+=$row[balance];
	}//while($row = mysqli_fetch_array($result))
	
		$outputRow = array();
	


$outputRow['STYLE']['value'] =  'Total';
$outputRow['STYLE']['name'] =  'b_style[]';

$outputRow['JOBID']['value'] =  '';
$outputRow['JOBID']['name'] =  'b_jobid[]';

$outputRow['COLOR']['value'] =  '';
$outputRow['COLOR']['name'] =  'b_color[]';

foreach($tprinth as $k){
		
$outputRow[$k]['value'] =  array_sum($sizetotal[$k]);
$outputRow[$k]['name'] =  'b_size[]';
	
}

$outputRow['TOTAL']['value'] = '';
$outputRow['TOTAL']['name'] ='b_total[]';
//$outputRow['TOTAL']['total'] =  'yes';

$output['rows'][][] = $outputRow;
$rowCount++;
	
	
	//if displayed rows greater than 0 then sum total
	//$count_totalbill=number_format($balance,2);
	
	$output['total_rows'] =$rowCount;
	echo json_encode($output);
	}//if($result)
	else
	echo mysqli_error($con);
		
 //}//if($_POST['report_type']=="pending") end
	}///end if ($_POST['report_typewise']=='all'){
	

else if($_POST['report_view_type']=="Invoiceinfo")
{
	if($_POST['report_type']=="allinv"){
	$SQLhead = "SELECT `orderid` as 'INVOICE NO', DATE_FORMAT(`orderdate`,'%d/%m/%Y') as 'INVOICE DATE', `ordertype` as 'ORDER TYPE', `buyercode` as 'BUYER CODE', `billedto`, `shipto` as 'SHIPTO', `agentcode` as 'AGENTCODE', `packinglistno` as 'PACKINGLIST NO', `ptotal` as 'TOTAL' , `pdiscount` as 'DISCOUNT', `disamt` as 'DISCOUNT AMT', `pnamount` as 'NETAMOUNT', `vat` as 'VAT', `grtotal` as 'GRAND TOTAL',    `paid` as 'PAID' FROM `sinvoicereg` ";
		}
	else if($_POST['report_type']=="pendinginv"){
		$SQLhead = "SELECT `orderid` as 'INVOICE NO', DATE_FORMAT(`orderdate`,'%d/%m/%Y') as 'INVOICE DATE', `ordertype` as 'ORDER TYPE', `buyercode` as 'BUYER CODE', `billedto`, `shipto` as 'SHIPTO', `agentcode` as 'AGENTCODE', `packinglistno` as 'PACKINGLIST NO', `ptotal` as 'TOTAL' , `pdiscount` as 'DISCOUNT', `disamt` as 'DISCOUNT AMT', `pnamount` as 'NETAMOUNT', `vat` as 'VAT', `grtotal` as 'GRAND TOTAL',    `paid` as 'PAID' FROM `sinvoicereg` where  (grtotal - paid)>0 ";
		}
		else if($_POST['report_type']=="paidinv"){
		$SQLhead = "SELECT `orderid` as 'INVOICE NO', DATE_FORMAT(`orderdate`,'%d/%m/%Y') as 'INVOICE DATE', `ordertype` as 'ORDER TYPE', `buyercode` as 'BUYER CODE', `billedto`, `shipto` as 'SHIPTO', `agentcode` as 'AGENTCODE', `packinglistno` as 'PACKINGLIST NO', `ptotal` as 'TOTAL' , `pdiscount` as 'DISCOUNT', `disamt` as 'DISCOUNT AMT', `pnamount` as 'NETAMOUNT', `vat` as 'VAT', `grtotal` as 'GRAND TOTAL',    `paid` as 'PAID' FROM `sinvoicereg` where (grtotal - paid)=0  ";
		}
	$sql = "$SQLhead"; 
	 
	$result = mysqli_query($con,$sql);
	
	if($result)
	{

	$i=0;
	$count_totalbill=0;
		

		

$output['total_rows'] =mysqli_num_rows($result);

while($book_info_row=mysqli_fetch_assoc($result))
{
	$sqlRow = $book_info_row;

	$index = 0;
	//$outputRow['value'] = $bill_info_row;	
	foreach ($sqlRow as $key=>$value) {	
		
	/* 
	 * start
	 * getting field name of table
	*/	
    $outputRow[$key]['value'] = $value;
	
	addDataBaseName($outputRow,$book_info,$index,$key,'',1);
	
	//mysqli_field_seek($book_info,$index);
	$index++;
  	//$fieldinfo=mysqli_fetch_field($book_info);
	//$outputRow[$key]['name'] = $fieldinfo->orgname;
	$field_orgname = $outputRow[$key]['name'];
	
	/* 
	 * end
	*/
	
	
	//adding class
	
	addClassName($outputRow,$key);
	
	
		
	if($key == 'bookid')
	{
		
	addFooterCounter($outputRow,$key);
		$outputRow[$key]['tdClass'] = 'srno links';
		$outputRow[$key]['title'] = 'Double Click Add or Remove Duty Slip';
	}
		
	$totalKeyArray = array( 'TOTAL' , 'DISCOUNT AMT',  'NETAMOUNT',  'VAT', 'GRAND TOTAL', 'PAID');
	
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
		
	}
	
	$output['rows'][][] = $outputRow;	
	} // while ends
}
	
	

echo json_encode($output);																								

}//billing if ends





else if($_POST['report_view_type']=="veh_rep")
{
if($_POST['report_type']=="book_mis")
{
if($_SESSION['SESS_BRANCH']!='HO')
	$qry_part_filter="and branch like '$_SESSION[SESS_BRANCH]'";
	
	
if(!empty($_POST['vehno']))
$qry_part="where dutydate between '$from_date' and '$to_date' and vehno='$_POST[vehno]' and $bookingreg.fny = '$_SESSION[SESS_FNY]' $qry_part_filter order by dutydate";
else
$qry_part="where dutydate between '$from_date' and '$to_date' and $bookingreg.fny = '$_SESSION[SESS_FNY]' $qry_part_filter order by dutydate";



if($dri_duty_det=mysqli_query($con,"SELECT DATE_FORMAT(dutydate,'%d/%m/%Y') as dutydate, bookid, vehno, driver, billedto, $bookingreg.bookedby, dutytype, package, DATE_FORMAT( sttime,  '%H.%i') AS sttime, DATE_FORMAT( clgtime,  '%H.%i') AS clgtime, SUBSTRING_INDEX( tottime,  ':', 2 ) AS tottime, exhr,exkm,stkm,clgkm,$bookingreg.billno as billno,vehicle,tamount,$bookingreg.usedby,totkm,daamt,naamt,(m1value+m2value+m3value) as misctot,parking,srrate,optstax,opttoll FROM $bookingreg inner join $billreg on $bookingreg.billno=$billreg.billno inner join commst on $bookingreg.billedto=commst.compid $qry_part"))
{

while($dri_duty_det_row=mysqli_fetch_array($dri_duty_det))
{
	$stamt=0;
	$totamount=$dri_duty_det_row[tamount];
	//if(($dri_duty_det_row[opttoll])==0)
	$totamount=$dri_duty_det_row[tamount]-$dri_duty_det_row[parking];
	
	if(($dri_duty_det_row[optstax])==1)
	$staxstatus="Y";
	else
	$staxstatus="N";
	
if(($dri_duty_det_row[srrate])>5)
	{
	 $stamt=number_format(round((($totamount)*0.40)*$dri_duty_det_row[srrate]*0.01),2, '.', '');
	
	}
	else
	 $stamt=number_format(round(($totamount)*$dri_duty_det_row[srrate]*0.01),2, '.', '');
	 
	 $surchg=number_format(round($stamt*3*0.01),2, '.', '');
	 $totalamount=number_format(round($surchg+$stamt+$dri_duty_det_row[tamount]),2, '.', '');

$fdate_qry=mysqli_query($con,"SELECT  MAX( FDATE ) AS fdate from  fuelreg where VEHNO in ($dri_duty_det_row[vehno])");
$fdate_row=mysqli_fetch_row($fdate_qry);
$fdate= clean($con,$fdate_row[0]);

$outputRow = array();
$outputRow['Booking Id']['value'] = "$dri_duty_det_row[bookid]";
$outputRow['Client Name']['value'] = "$dri_duty_det_row[billedto]";
$outputRow['Duty Date']['value'] = "$dri_duty_det_row[dutydate]";
$outputRow['Used By']['value'] = "$dri_duty_det_row[usedby]";
$outputRow['Duty Type']['value'] = "$dri_duty_det_row[package]";
$outputRow['Vehicle']['value'] = "$dri_duty_det_row[vehicle]-$dri_duty_det_row[vehno]";
$outputRow['Driver']['value'] = "$dri_duty_det_row[driver]";
$outputRow['Start Time']['value'] = "$dri_duty_det_row[sttime]";
$outputRow['End Time']['value'] = "$dri_duty_det_row[clgtime]";
$outputRow['Total Time']['value'] = "$dri_duty_det_row[tottime]";
$outputRow['Start Km']['value'] = "$dri_duty_det_row[stkm]";
$outputRow['End Km']['value'] = "$dri_duty_det_row[clgkm]";
$outputRow['Total Kms']['value'] = "$dri_duty_det_row[totkm]";
$outputRow['Extra Hrs']['value'] = "$dri_duty_det_row[exhr]";
$outputRow['Extra Kms']['value'] = "$dri_duty_det_row[exkm]";
$outputRow['DA Amount']['value'] = "$dri_duty_det_row[daamt]";
$outputRow['NA Amount']['value'] = "$dri_duty_det_row[naamt]";
$outputRow['Misc. Amount']['value'] = "$dri_duty_det_row[misctot]";
$outputRow['Net Amount']['value'] = "$totamount";
$outputRow['Parking Toll']['value'] = "$dri_duty_det_row[parking]";
$outputRow['Duty Amount']['value'] = "$dri_duty_det_row[tamount]";
$outputRow['Ser. Tax Status']['value'] = "$staxstatus";
$outputRow['Ser. Tax Rate.']['value'] = "$dri_duty_det_row[srrate]";
$outputRow['Ser. Tax Amt.']['value'] = "$stamt";
$outputRow['Sur Chg. Amt.']['value'] = "$surchg";
$outputRow['Total Amount']['value'] = "$totalamount";
$outputRow['Billno']['value'] = "$dri_duty_det_row[billno]";
$output['rows'][][] = $outputRow;
$rowCount++;

	}
addTotalRows($output,$rowCount);
}
else 
    $output[error] = mysqli_error($con);
	
	echo json_encode($output);

}

///start of maint report 

else if($_POST['report_type']=='maint'){
	if ($mas_rec = mysqli_query($con,"select entryid,VEHNO,DATE_FORMAT(SERDATE,  '%d/%m/%Y' ) as SDATE,AGENCY,SERODOM,DLVODOM,DUEODOM,DATE_FORMAT(DUEDATE,  '%d/%m/%Y' ) as DDATE, PCOST, SCOST, AMOUNT,remarks from vehdetails where  SERDATE between '$from_date' and '$to_date' ORDER BY SERDATE, VEHNO, SERDATE;")) {
    if (mysqli_num_rows($mas_rec) > 0 ||1==1) {
        $print = 1;
		
     

        $dacount = 0;
		$i=0;
		$rowCount = 0;
        while ($mas_rec_row = mysqli_fetch_array($mas_rec)) {
			$outputRow = array();
			$outputRow['VEHNO']['value'] = "$mas_rec_row[VEHNO]";	
			addCustomName($outputRow,'VEHNO','VEHNO[]');
			addFooterCounter($outputRow,'VEHNO');
			
			$outputRow['DATE']['value'] = "$mas_rec_row[SDATE]";
			addCustomName($outputRow,'DATE','SDATE[]');
			
			$outputRow['AGENCY']['value'] = "$mas_rec_row[AGENCY]";
			addCustomName($outputRow,'AGENCY','AGENCY[]');
			
			$outputRow['SER. KLM.']['value'] = "$mas_rec_row[SERODOM]";
			addCustomName($outputRow,'SER. KLM.','SERODOM[]');
			
			$outputRow['DLV. KLM.']['value'] = "$mas_rec_row[DLVODOM]";
			addCustomName($outputRow,'DLV. KLM.','DLVODOM[]');
			
			$outputRow['DUE KLM.']['value'] = "$mas_rec_row[DUEODOM]";
			addCustomName($outputRow,'DUE KLM.','DUEODOM[]');
			
			$outputRow['DUE DATE']['value'] = "$mas_rec_row[DDATE]";
			addCustomName($outputRow,'DUE DATE','DDATE[]');
			
			$outputRow['PART COST']['value'] = "$mas_rec_row[PCOST]";
			addCustomName($outputRow,'PART COST','PCOST[]');
			
			$outputRow['SER. COST']['value'] = "$mas_rec_row[SCOST]";
			addCustomName($outputRow,'SER. COST','SCOST[]');
			
			$outputRow['Amount']['value'] = "$mas_rec_row[AMOUNT]";
			addCustomName($outputRow,'Amount','AMOUNT[]');
			
			$outputRow['Remark']['value'] = "$mas_rec_row[remarks]";
			addCustomName($outputRow,'Remark','REMARK[]');
			
			$output['rows'][][] = $outputRow;
			$rowCount++;
			
        

$i++;
$count_totalbill+=$mas_rec_row[AMOUNT];
        }//while ($mas_rec_row end
$count_totalbill=number_format($count_totalbill,2);

        addTotalRows($output,$rowCount);
    } //if (mysqli_num_rows($mas_rec) end
	else
		$output[error] = "NO RECORD FOUND...";
} //if (($mas_rec end
else
     $output[error] = mysqli_error($con);
	
	echo json_encode($output);


}
///end of maint report




// start of Vehicle summary
else if($_POST['report_type']=="vehiclemis")
{
	$rowCount = 0;
	if(!empty($_POST['vehno']))
	{
	$monthArray = getMonth($from_date,$to_date);

	foreach($monthArray as $val)
	{
		
	// getting sales total
	$sales_sum=mysqli_query($con,"SELECT MONTHNAME(dutydate) as billmonth, SUM( tamount ) AS billing FROM $bookingreg where MONTHNAME(dutydate) like '$val[month]' and YEAR(dutydate) like '$val[year]' and $bookingreg.cmp = '$_SESSION[SESS_CMPC]' and $bookingreg.fny = '$_SESSION[SESS_FNY]' and vehno like '$_POST[vehno]'");
	$sales_sum_row=mysqli_fetch_assoc($sales_sum);
	$sales=$sales_sum_row['billing'];
	
	
	// getting fuelling total
	$fuelling_sum=mysqli_query($con,"SELECT sum(amount) as fuelling FROM `fuelreg`  where  MONTHNAME(fdate) like '$val[month]' and YEAR(fdate) like '$val[year]' and cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]' and VEHNO like '$_POST[vehno]'");
	$fuelling_row=mysqli_fetch_assoc($fuelling_sum);
	$fuelling=$fuelling_row['fuelling'];
	
	// getting services total
	$services_sum=mysqli_query($con,"SELECT sum(amount) as services FROM `vehdetails` where  MONTHNAME(serdate) like '$val[month]' and YEAR(serdate) like '$val[year]' and cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]' and VEHNO like '$_POST[vehno]'");
	$services_row=mysqli_fetch_assoc($services_sum);
	$services=$services_row['services'];
	
	// getting Salary total
	
	$salary_sum=mysqli_query($con,"SELECT sum(totamount) as salary FROM `vchreg` inner join ledgerreg on  agnstref = ledger where alias  like '$_POST[vehno]' and  MONTHNAME(vchdate) like '$veh_reg_row[billmonth]' and vchtype = 'PAYMENT' and comcode like 'WAGES%'  and vchreg.cmp = '$_SESSION[SESS_CMPC]' and vchreg.fny = '$_SESSION[SESS_FNY]'");
	
	$salary_row=mysqli_fetch_assoc($salary_sum);
	$salary=$salary_row['salary'];
	
	// getting finance total
	
	$finance_sum=mysqli_query($con,"SELECT sum(instamount) as finance FROM `vehreg` where  STR_TO_DATE('$val[year]-$val[month]','%Y-%M') between inststartdate and instenddate");
	
	$finance_row=mysqli_fetch_assoc($finance_sum);
	$finance=$finance_row['finance'];
	
	// getting others total
	
	$others_sum=mysqli_query($con,"SELECT sum(totamount) as others FROM `vchreg` inner join `ledgerreg` on agnstref = ledger where alias like '$_POST[vehno]' and  MONTHNAME(vchdate) like '$veh_reg_row[billmonth]' and vchtype = 'PAYMENT' and comcode not in  (select ledger from ledgerreg where ledtype like 'LOAN%')  and comcode not like 'DIESEL%' and comcode not like 'REPAIRS%' and comcode not like 'WAGES%' and ledtype != 'FUEL ACCOUNT' and vchreg.cmp = '$_SESSION[SESS_CMPC]' and vchreg.fny = '$_SESSION[SESS_FNY]'");
	
	$others_row=mysqli_fetch_assoc($others_sum);
	$others=$others_row['others'];



	
	$netamount=$sales-($fuelling+$services+$finance+$salary+$others);
	
	$outputRow = array();
	$outputRow['MONTH']['value']="$val[month]";
	addFooterCounter($outputRow,'MONTH');
	$outputRow['Billing']['value']=number_format($sales,2, '.', '');
	addFooterTotal($outputRow,'Billing');
	$outputRow['Fuelling']['value']=number_format($fuelling,2, '.', '');
	addFooterTotal($outputRow,'Fuelling');
	$outputRow['Services']['value']=number_format($services,2, '.', '');
	addFooterTotal($outputRow,'Services');
	$outputRow['Finance']['value']=number_format($finance,2, '.', '');
	addFooterTotal($outputRow,'Finance');
	$outputRow['Salary']['value']=number_format($salary,2, '.', '');
	addFooterTotal($outputRow,'Salary');
	$outputRow['Others']['value']=number_format($others,2, '.', '');
	addFooterTotal($outputRow,'Others');
	$outputRow['Net Amount']['value']=number_format($netamount,2, '.', '');
	addFooterTotal($outputRow,'Net Amount');
	$output['rows'][][] = $outputRow;
	$rowCount++;

	}//for each ends
	

	} // vehno not empty ends
	else{
		
		$monthArray = getMonth($from_date,$to_date);
		$month = '';
		$year = '';
		
		foreach($monthArray as $val)
		{
			$month .= "'$val[month]',";
			$year .= "'$val[year]',";
		}
		
		$month=rtrim($month, ",");
		$year=rtrim($year, ",");
		

$sqlQry = "select vehcode as vehno from vehreg where Vehstatus <> 'SOLD';";		

$sqlRes=mysqli_query($con,"$sqlQry");

while($sqlResRow=mysqli_fetch_array($sqlRes))
{
	$vehList = $sqlResRow;
	

//$sales_sum=mysqli_query($con,"SELECT vehno, SUM( tamount ) AS billing FROM $bookingreg where dutydate between '$from_date' and '$to_date' and $bookingreg.cmp = '$_SESSION[SESS_CMPC]' and $bookingreg.fny = '$_SESSION[SESS_FNY]' GROUP BY vehno");
//
//while($veh_reg_row=mysqli_fetch_array($sales_sum))
//{
	
	// getting sales total
	$sales_sum=mysqli_query($con,"SELECT MONTHNAME(dutydate) as billmonth, SUM( tamount ) AS billing FROM $bookingreg where MONTHNAME(dutydate) in ($month) and YEAR(dutydate) in ($year) and $bookingreg.cmp = '$_SESSION[SESS_CMPC]' and $bookingreg.fny = '$_SESSION[SESS_FNY]' and vehno like '$vehList[vehno]'");
	$sales_sum_row=mysqli_fetch_assoc($sales_sum);
	$sales=$sales_sum_row['billing'];
	
	// getting fuelling total
	$fuelling_sum=mysqli_query($con,"SELECT sum(amount) as fuelling FROM `fuelreg`  where  MONTHNAME(fdate) in ($month) and YEAR(fdate) in ($year) and cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]' and VEHNO like '$vehList[vehno]'");
	$fuelling_row=mysqli_fetch_assoc($fuelling_sum);
	$fuelling=$fuelling_row['fuelling'];
	
	// getting services total
	$services_sum=mysqli_query($con,"SELECT sum(amount) as services FROM `vehdetails` where  MONTHNAME(serdate) in ($month) and YEAR(serdate)  in ($year) and cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]' and VEHNO like '$vehList[vehno]'");
	$services_row=mysqli_fetch_assoc($services_sum);
	$services=$services_row['services'];
	
		// getting Salary total
	
	$salary_sum=mysqli_query($con,"SELECT sum(totamount) as salary FROM `vchreg` inner join ledgerreg on  agnstref = ledger where alias like '$veh_reg_row[vehno]' and  vchdate between '$from_date' and '$to_date' and vchtype = 'PAYMENT' and comcode like 'WAGES%'  and vchreg.cmp = '$_SESSION[SESS_CMPC]' and vchreg.fny = '$_SESSION[SESS_FNY]'
	");
	
	$salary_row=mysqli_fetch_assoc($salary_sum);
	$salary=$salary_row['salary'];
	
			// getting finance total
	
	$finance_sum=mysqli_query($con,"SELECT sum(instamount) as finance FROM `vehreg` where instenddate >= '$from_date' and  inststartdate  <= '$to_date' and vehcode like '$vehList[vehno]'");
	
	$finance_row=mysqli_fetch_assoc($finance_sum);
	$finance=$finance_row['finance'];
	
	
		// getting others total
	
	$others_sum=mysqli_query($con,"SELECT sum(totamount) as others FROM `vchreg` inner join `ledgerreg` on agnstref = ledger where alias like '$veh_reg_row[vehno]' and  vchdate between '$from_date' and '$to_date' and vchtype = 'PAYMENT' and comcode not in  (select ledger from ledgerreg where ledtype like 'LOAN%') and comcode not like 'DIESEL%' and comcode not like 'REPAIRS%' and comcode not like 'WAGES%' and ledtype != 'FUEL ACCOUNT' and vchreg.cmp = '$_SESSION[SESS_CMPC]' and vchreg.fny = '$_SESSION[SESS_FNY]'");
	
	$others_row=mysqli_fetch_assoc($others_sum);
	$others=$others_row['others'];
	
	
	$netamount=$sales-($fuelling+$services+$finance+$salary+$others);
	$outputRow = array();
	$outputRow['Veh No.']['value']="$vehList[vehno]";
	addFooterCounter($outputRow,'Veh No.');
	$outputRow['Billing']['value']=number_format($sales,2, '.', '');
	addFooterTotal($outputRow,'Billing');
	$outputRow['Fuelling']['value']=number_format($fuelling,2, '.', '');
	addFooterTotal($outputRow,'Fuelling');
	$outputRow['Services']['value']=number_format($services,2, '.', '');
	addFooterTotal($outputRow,'Services');
	$outputRow['Finance']['value']=number_format($finance,2, '.', '');
	addFooterTotal($outputRow,'Finance');
	$outputRow['Salary']['value']=number_format($salary,2, '.', '');
	addFooterTotal($outputRow,'Salary');
	$outputRow['Others']['value']=number_format($others,2, '.', '');
	addFooterTotal($outputRow,'Others');
	$outputRow['Net Amount']['value']=number_format($netamount,2, '.', '');
	addFooterTotal($outputRow,'Net Amount');
	$output['rows'][][] = $outputRow;
	$rowCount++;

	}
	


	} // vehno not empty ends
	
	addTotalRows($output,$rowCount);
	
echo json_encode($output);
}
//end of Vehicle sammary	

// Start With jSuccesss
else if($_POST['report_type']=="jSuccesss"){

if($_POST['vehno']!="")
{
	if($_POST['report_type']=="jSuccesss")
$qry_part= "where vehno='".$_POST['vehno']."'";
}
else
$qry_part="";

/*echo "<table  id='table_report_view'  cellspacing='0' width='100%'' ><thead><tr><th><textarea>Vehicle No.</textarea></th><th><textarea>Model</textarea></th><th><textarea>Vehicle Type</textarea></th><th><textarea>PUC</textarea></th><th><textarea>Fitness</textarea></th><th><textarea>TAX</textarea></th><th><textarea>Authorized</textarea></th><th><textarea>Permit</textarea></th><th><textarea>Insurance</textarea></th><th><textarea>Maintenance</textarea></th></tr></thead>";

echo "<tfoot class='tablefooter'><tr><td><textarea>Total</textarea></td><td><textarea count='nor'></textarea></td><td><textarea  ></textarea></td><td><textarea  ></textarea></td><td><textarea  ></textarea></td><td><textarea  ></textarea ></td><td><textarea  ></textarea></td><td><textarea  ></textarea></td><td><textarea  ></textarea></td><td><textarea  ></textarea></td></tr></tfoot><tbody>";*/

$veh_reg=mysqli_query($con,"SELECT  vehno, vehicle,mfgdate,
CASE WHEN taxrendate <= CURDATE() 
THEN  DATE_FORMAT(taxrendate, '%d/%m/%Y')
END AS taxrendate, 
CASE WHEN fitnessdate <= CURDATE() 
THEN  DATE_FORMAT(fitnessdate, '%d/%m/%Y')
END AS fitnessdate,
CASE WHEN insrendate <= CURDATE() 
THEN DATE_FORMAT(insrendate, '%d/%m/%Y')
END AS insrendate, 
CASE WHEN permitdate <= CURDATE() 
THEN DATE_FORMAT(permitdate, '%d/%m/%Y')
END AS permitdate, 
CASE WHEN authdate <= CURDATE() 
THEN DATE_FORMAT(authdate, '%d/%m/%Y')
END AS authdate, 
CASE WHEN pucdate <= CURDATE() 
THEN DATE_FORMAT(pucdate, '%d/%m/%Y')
END AS pucdate,
CASE WHEN lserdate <= CURDATE() 
THEN DATE_FORMAT(lserdate, '%d/%m/%Y')
END AS lserdate
FROM vehreg
WHERE taxrendate <= CURDATE() -7
OR insrendate <= CURDATE() -7
OR permitdate <= CURDATE() -7
OR authdate <= CURDATE() -7
OR pucdate <= CURDATE() -7 
OR fitnessdate <= CURDATE() -7
OR lserdate <= CURDATE() -7");

$rowCount = 0;
while($veh_reg_row=mysqli_fetch_array($veh_reg))
{
	$outputRow['Vehicle No.']['value']="$veh_reg_row[vehno]";
$outputRow['Model']['value']="$veh_reg_row[vehicle]";
$outputRow['Vehicle Type']['value']="$veh_reg_row[taxrendate]";
$outputRow['PUC']['value']="$veh_reg_row[pucdate]";
$outputRow['Fitness']['value']="$veh_reg_row[fitnessdate]";
$outputRow['TAX']['value']="$veh_reg_row[taxrendate]";
$outputRow['Authorized']['value']="$veh_reg_row[authdate]";
$outputRow['Permit']['value']="$veh_reg_row[permitdate]";
$outputRow['Insurance']['value']="$veh_reg_row[insrendate]";
$outputRow['Maintenance']['value']="$veh_reg_row[lserdate]";
$output['rows'][][] = $outputRow;
			$rowCount++;
//echo  "<tr><td><textarea>$veh_reg_row[vehno]</textarea></td><td><textarea>$veh_reg_row[mfgdate]</textarea></td><td><textarea>$veh_reg_row[vehicle]</textarea></td><td><textarea>$veh_reg_row[pucdate]</textarea></td><td><textarea>$veh_reg_row[fitnessdate]</textarea></td><td><textarea>$veh_reg_row[taxrendate]</textarea></td><td><textarea>$veh_reg_row[authdate]</textarea></td><td><textarea>$veh_reg_row[permitdate]</textarea></td><td><textarea>$veh_reg_row[insrendate]</textarea></td><td><textarea>$veh_reg_row[lserdate]</textarea></td></tr>";
	} // while ends
	addTotalRows($output,$rowCount);
	echo json_encode($output);
}
// Start With jSuccesss


else
{
if($_POST['vehno']!="")
{
	if($_POST['report_type']=="inforunning")
$qry_part= "where vehno='".$_POST['vehno']."'";
}
else
$qry_part="";

$veh_reg=mysqli_query($con,"select  vehno, vehicle, DATE_FORMAT(taxrendate,  '%d/%m/%Y' ) as taxrendate, DATE_FORMAT(insrendate,  '%d/%m/%Y' ) as insrendate, DATE_FORMAT(fitnessdate,  '%d/%m/%Y' ) as fitnessdate, DATE_FORMAT(authdate,  '%d/%m/%Y' ) as authdate, kmfueled, DATE_FORMAT(permitdate,  '%d/%m/%Y' ) as permitdate, serkm,DATE_FORMAT(fueldate,  '%d/%m/%Y' ) as fueldate, nextseron, lserdate from vehreg $qry_part order by vehno desc ");
$rowCount = 0;
while($veh_reg_row=mysqli_fetch_array($veh_reg))
{
	
	
	

$outputRow['VehNo']['value']="$veh_reg_row[vehno]";
$outputRow['VehType']['value']="$veh_reg_row[vehicle]";
$outputRow['TaxRenDate']['value']="$veh_reg_row[taxrendate]";
$outputRow['InsRenDate']['value']="$veh_reg_row[insrendate]";
$outputRow['FitnessRenDate']['value']="$veh_reg_row[fitnessdate]";
$outputRow['AuthRenDate']['value']="$veh_reg_row[authdate]";
$outputRow['PermitRenDate']['value']="$veh_reg_row[permitdate]";
$outputRow['ServicedKm']['value']="$veh_reg_row[serkm]";
$outputRow['NextServiceDue']['value']="$veh_reg_row[nextseron]";
$outputRow['LastServiceDate']['value']="$veh_reg_row[lserdate]";
$outputRow['Fuel Date']['value']="$veh_reg_row[fueldate]";
$outputRow['Fuel Km.']['value']="$veh_reg_row[kmfueled]";
$output['rows'][][] = $outputRow;
			$rowCount++;


	}
addTotalRows($output,$rowCount);
	echo json_encode($output);
}

}

else if($_POST['report_view_type']=="reprint_bill")
{

if($_POST['report_type']=="bill")
{
	if(empty($_POST['billedto']))
$qry_part="where billdate between '$from_date' and '$to_date'   order by CONVERT(srno, SIGNED INTEGER) desc";
else
$qry_part="where billdate between '$from_date' and '$to_date' and billto='$_POST[billedto]'  order by CONVERT(srno, SIGNED INTEGER) desc";
	
	$reprint_bill=mysqli_query($con,"select  srno as 'SRNO.', billno as 'BILLNO', billto as 'BILLEDTO',  DATE_FORMAT(billdate,  '%d/%m/%Y' ) as 'BILLEDDATE', name as 'COMPANY NAME', bookedby AS 'BOOKEDBY', usedby as 'GUESTNAME', basicamount as 'BASICAMT', srrate as 'SERTAXRATE', sramount as 'SERTAXAMT', educess as 'K.K.CESS', seducess as 'S.B.CESS', total as 'TOTAL' from $billreg $qry_part");
	$count_totalbill=0;
	$output['total_rows'] =mysqli_num_rows($reprint_bill);
	while($reprint_bill_row=mysqli_fetch_assoc($reprint_bill))
	{
		
		$index = 0;
		//$outputRow['value'] = $bill_info_row;	
		foreach ($reprint_bill_row as $key=>$value) {	
			
		/* 
		 * start
		 * getting field name of table
		*/	
		$outputRow[$key]['value'] = $value;
		
		mysqli_field_seek($reprint_bill,$index);
		$index++;
		$fieldinfo=mysqli_fetch_field($reprint_bill);
		$outputRow[$key]['name'] = $fieldinfo->orgname;
		$field_orgname = $outputRow[$key]['name'];
		/* 
		 * end
		*/
		
		
		//adding class
		$class = '';
		if (is_numeric($value))
		$class = 'number ';
		
		$outputRow[$key]['tdClass'] = $class;
		
		
		
		if($field_orgname == 'srno')
		{
		$outputRow[$key]['count'] = 'yes';
		$outputRow[$key]['tdClass'] = 'srno links';
		$outputRow[$key]['title'] = 'Double Click Add or Remove Bill';
		}
		else
		$outputRow[$key]['count'] = 'no';
			
		$totalKeyArray = array('total','basicamount','sramount','educess','seducess');
		
		if(in_array($field_orgname,$totalKeyArray))
		$outputRow[$key]['total'] = 'yes';
		else
		$outputRow[$key]['total'] = 'no';
		
	
		
		}
		
		$output['rows'][][] = $outputRow;
	
		$count_totalbill+=$reprint_bill_row[total];
	}
		 
		$count_totalbill=number_format($count_totalbill,2);
}
else if($_POST['report_type']=="dutyslip")
{

if(empty($_POST['billedto']))
$qry_part="dutydate between '$from_date' and '$to_date' and fny = '$_SESSION[SESS_FNY]'  order by dutydate desc";
else
$qry_part="dutydate between '$from_date' and '$to_date' and billedto='$_POST[billedto]' and fny = '$_SESSION[SESS_FNY]' order by dutydate desc";



if(!$book_info=mysqli_query($con,"select  bookid,billedto,bookedby,city,DATE_FORMAT(repdate,'%d/%m/%Y') as repdate,TIME_FORMAT(sttime,'%H:%i') as sttime,TIME_FORMAT(clgtime,'%H:%i') as clgtime,tottime,exhr,exhrrate,stkm,clgkm,totkm,exkm,dutytype,parking,usedby,insstatus,vehicle,vehno,driver,drivermob,days,remarks,billno,TIME_FORMAT(reptime,'%H:%i') as reptime,package,vendor,status from $bookingreg where $qry_part "))
die('Error:'.mysqli_error($con));

$output['total_rows'] =mysqli_num_rows($book_info);

while($book_info_row=mysqli_fetch_assoc($book_info))
{
	$sqlRow = $book_info_row;

$index = 0;
	//$outputRow['value'] = $bill_info_row;	
	foreach ($sqlRow as $key=>$value) {	
		
	/* 
	 * start
	 * getting field name of table
	*/	
    $outputRow[$key]['value'] = $value;
	
	addDataBaseName($outputRow,$book_info,$index,$key,'',1);
	
	//mysqli_field_seek($book_info,$index);
	$index++;
  	//$fieldinfo=mysqli_fetch_field($book_info);
	//$outputRow[$key]['name'] = $fieldinfo->orgname;
	$field_orgname = $outputRow[$key]['name'];
	
	/* 
	 * end
	*/
	
	
	//adding class
	
	addClassName($outputRow,$key);
	
	
		
	if($key == 'bookid')
	{
		
	addFooterCounter($outputRow,$key);
		$outputRow[$key]['tdClass'] = 'srno links';
		$outputRow[$key]['title'] = 'Double Click Add or Remove Duty Slip';
	}
		
	$totalKeyArray = array('parking');
	
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
		
	}
	
	$output['rows'][][] = $outputRow;	
	} // while ends
}
	
	

echo json_encode($output);
		}	
		//reprint add conditionend
		//reprint info if ends

	

else if($_POST['report_view_type']=="dri_duty_det")
{

 if($_POST['report_type']=="musterroll"){
       $qrypart="";
        if(!empty($_POST[driver])){
    $qrypart=" and musterroll.Ecode Like'$_POST[driver]%'";}
       
    
	if (($mas_rec = mysqli_query($con,"select musterroll.EntryID as EntryID,musterroll.Ecode,DATE_FORMAT( Pdate,  '%d/%m/%Y' ) as Pdate,DATE_FORMAT( rdate,  '%d/%m/%Y' ) as rdate,DATE_FORMAT(Intime,  '%H:%i' ) as Intime,DATE_FORMAT(Outtime,  '%H:%i' ) as Outtime,Tottime,det1,det2,det3,det4,det5,det6,det7,det8,det9,otallowance, otallowance*det5 as otamt from `musterroll` Left join empinfo on `musterroll`.Ecode=empinfo.EName  where Pdate between '$from_date' and '$to_date' $qrypart  order by Pdate,Intime ;"))) {
    //if (mysqli_num_rows($mas_rec) > 0) {
        $print = 1;
        $dacount = 0;
		addTotalRows($output,mysqli_num_rows($mas_rec));	
        while ($mas_rec_row = mysqli_fetch_assoc($mas_rec)) {
		$index = 0;
	foreach ($mas_rec_row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$mas_rec,$index,$key,'r_',1);
	$index++;
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);
		
	//add Footer Counter to Column
	if($key == 'EntryID')
	{
	addFooterCounter($outputRow,$key);
	addClassName($outputRow,$key,'EntryID');
	}
		
	//add Footer Total to Column
	$totalKeyArray = array();
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
	}
	
	$output['rows'][][] = $outputRow;
	}

		}	

	else 
		$output[error] = mysqli_error($con);
	
	echo json_encode($output);
}  


else if($_POST['report_type']=="inhouse"){
       $qrypart="";
        if(!empty($_POST[driver]))
		{
			$qrypart=" and br.driver Like '$_POST[driver]%'";
		}
       
    
	if (($mas_rec = mysqli_query($con,"SELECT br.driver, bookid,dutydate as ddate, DATE_FORMAT(dutydate,'%d/%m/%Y') as dutydate, billedto,usedby, bookedby,  br.`vehicle`, br.vehno, DATE_FORMAT( dutydate,'%d/%m/%Y')  as Startdate, DATE_FORMAT(rdate,'%d/%m/%Y') as Enddate,  br.dutytype, package, SUBSTRING_INDEX(sttime, ':', 2 ) AS sttime, SUBSTRING_INDEX( clgtime,  ':', 2 )AS clgtime, SUBSTRING_INDEX( tottime,  ':', 2 ) AS tottime,`stkm`,`clgkm`,`totkm`,parking, '' as `extrabef`, '' as `sundayextra`, '' as `secdutyamt`, bi.reptime as drireptime , bi.closetime as driclosetime,bi.otallowance,bi.daallowance,bi.other1,bi.other2,bi.holidays FROM $bookingreg as br  inner join empinfo as bi on  br.driver=bi.ECode where dutydate between '$from_date' and '$to_date' $qrypart and br.status NOT IN ('CANCELLED','VOID')  order by br.driver,ddate,sttime ;"))) {
    //if (mysqli_num_rows($mas_rec) > 0) {
        $print = 1;
        $dacount = 0;
		$rowCount = 0;
        while ($mas_rec_row = mysqli_fetch_array($mas_rec)) {
			$overTimePerHour =0;
			$outStationAlwPerDay=0;
			$mas_rec_row[Enddate]=str_replace("/","-","$mas_rec_row[Enddate]");
			$mas_rec_row[Startdate]=str_replace("/","-","$mas_rec_row[Startdate]");
			//add code for proper calculation of OT
			
			$driverDutyTimeStart	=	$mas_rec_row[drireptime];
			$driverDutyTimeEnd 		= 	$mas_rec_row[driclosetime];
			if(substr($mas_rec_row[dutytype],0,3)!='OUT'){
			$overTimePerHour		=	$mas_rec_row[otallowance];}
			else{
			$outStationAlwPerDay	=	$mas_rec_row[daallowance];}
			$earlyGoingBef6			=	$mas_rec_row[other1];
			$comingAfter4			=	$mas_rec_row[daallowance];
			$holidayExtraDA			=	$mas_rec_row[holidays];
			$secondDutyExtra		= 	$mas_rec_row[other2];
           
			$overTimeAmt			= 	0;
			$overTime				=	0;
			$daAmt					=	0;
			$earlyRepLateGoingAmt	=	0;
			
			$holidayExtraDAAmt		=	0;

			$mas_rec_row[sttime]=str_replace(":",".","$mas_rec_row[sttime]");
			$mas_rec_row[clgtime]=str_replace(":",".","$mas_rec_row[clgtime]");
			$driverDutyTimeStart=str_replace(":",".","$driverDutyTimeStart");
			$driverDutyTimeEnd=str_replace(":",".","$driverDutyTimeEnd");
			
			if($mas_rec_row[sttime]<$driverDutyTimeStart&&(substr($mas_rec_row[dutytype],0,3)!='OUT'))
			{
				
				$secondDutyChecktemp=str_replace("/","-","$secondDutyCheck");					
						if("$secondDutyChecktemp"=="$mas_rec_row[Startdate]")
						{ 
							if($secondDutyCheckStTime>$mas_rec_row[sttime]&&$driverDutyTimeStart>$secondDutyCheckClgTime)  
							{
								$driverDutyTimeStart =  $driverDutyTimeStart;	
								
							}
						}
				
				$totmin=0;
				$texhr=number_format($mas_rec_row[sttime], 2, '.', '');
				list($hr,$min) = explode('.', $texhr);
				            if($min<=0)
							$totmin=0;
							else if($min>0&&$min<=15)
							$totmin=25;
							else if($min>15&&$min<=30)
							$totmin=50;
							else if($min>30&&$min<=45)
							$totmin=75;
							else if($min>45)
							$hr=$hr+1;
							$totmin/=100;
                            $hr = $hr + $totmin;
							$hr = number_format($hr, 2, '.', '');
				$overTime = number_format(($driverDutyTimeStart - $hr), 2, '.', '');
				//if($overTimePerHour>0)
				//$overTimeAmt = $overTime*$overTimePerHour;
				
			}
			
			$dayDiff = (strtotime($mas_rec_row[Enddate])-strtotime($mas_rec_row[Startdate]))/(24*60*60);  // if there is diff in closing and end date
			$tempCloseTime = $mas_rec_row[clgtime];
			$tempCloseTime += $dayDiff*24;
			if($tempCloseTime>$driverDutyTimeEnd&&(substr($mas_rec_row[dutytype],0,3)!='OUT'))
			{   
			
						$secondDutyChecktemp=str_replace("/","-","$secondDutyCheck");					
						if("$secondDutyChecktemp"=="$mas_rec_row[Startdate]")
						{ 
							if($tempCloseTime>$secondDutyCheckClgTime&&$secondDutyCheckClgTime>$driverDutyTimeEnd)  
							{
								$driverDutyTimeEnd =  $secondDutyCheckClgTime;	
								
							}
						}
						$etotmin=0; 
			             $etexhr=number_format($tempCloseTime, 2, '.', '');
				         list($ehr,$emin) = explode('.', $etexhr);
				            if($emin<=0)
							$etotmin=0;
							else if($emin>0&&$emin<=15)
							$etotmin=25;
							else if($emin>15&&$emin<=30)
							$etotmin=50;
							else if($emin>30&&$emin<=45)
							$etotmin=75;
							else if($emin>45)
							$ehr=$ehr+1;
							$etotmin/=100;
                            $ehr = $ehr + $etotmin;
							$ehr = number_format($ehr, 2, '.', '');
				            $driverDutyTimeEnd = number_format($driverDutyTimeEnd, 2, '.', '');
				$overTime += number_format(($ehr - $driverDutyTimeEnd), 2, '.', '');
				//if($overTimePerHour>0)
				//$overTimeAmt += ($overTime*$overTimePerHour);
			}
			
			if($overTimePerHour>0)
				$overTimeAmt += ($overTime*$overTimePerHour);
			
			

			if($mas_rec_row[dutytype]=='OUTSTATION'||$mas_rec_row[dutytype]=='OUT-STATION')
			{
				$daAmt = $outStationAlwPerDay;
			}
			
			if($dayDiff>0&&$tempCloseTime>4)
			{
				$daAmt += $outStationAlwPerDay;
			}

			if(($mas_rec_row[sttime]<6))
			{
				$earlyRepLateGoingAmt = $earlyGoingBef6;
			}

			if($dayDiff>0&&$tempCloseTime>1&&$tempCloseTime<4)
			{
				$earlyRepLateGoingAmt += $earlyGoingBef6;
			}


			if (date("D", strtotime($mas_rec_row[Startdate])) == "Sun"||date("D", strtotime($mas_rec_row[Enddate])) == "Sun")
			{
				$holidayExtraDAAmt = $holidayExtraDA;
			}

			

			
			
			
			$mas_rec_row[Enddate]=str_replace("-","/","$mas_rec_row[Enddate]");
			$mas_rec_row[Startdate]=str_replace("-","/","$mas_rec_row[Startdate]");

			if("$secondDutyCheck"=="$mas_rec_row[Startdate]")
			{
				$secondDutyExtraAmt	=	$secondDutyExtra;
			}
			else{
				$secondDutyExtraAmt	= 0;
				}	
				
			$outputRow = array();
			
			$outputRow['Driver']['value'] = $mas_rec_row[driver];
			addFooterCounter($outputRow,'Driver');
			
			$outputRow['DUTY DATE']['value'] = $mas_rec_row[bookid];
			
			$outputRow['DUTY DATE']['value'] = $mas_rec_row[dutydate];
			
			$outputRow['Billed To']['value'] = $mas_rec_row[billedto];
			
			$outputRow['Used By']['value'] = $mas_rec_row[usedby];
			
			$outputRow['Booked By']['value'] = $mas_rec_row[bookedby];
			
			$outputRow['Vehicle']['value'] = $mas_rec_row[vehicle];
			
			$outputRow['Vehno']['value'] = $mas_rec_row[vehno];
			
			$outputRow['StartDate']['value'] = $mas_rec_row[Startdate];
			
			$outputRow['EndDate']['value'] = $mas_rec_row[Enddate];
			
			$outputRow['DutyType']['value'] = $mas_rec_row[dutytype];
			
			$outputRow['Package']['value'] = $mas_rec_row[package];
			
			$outputRow['Sttime']['value'] = $mas_rec_row[sttime];
			
			$outputRow['ClgTime']['value'] = $mas_rec_row[clgtime];
			
			$outputRow['TotTime']['value'] = $mas_rec_row[tottime];
			
			$outputRow['Stkm']['value'] = $mas_rec_row[stkm];
			
			$outputRow['Clgkm']['value'] = $mas_rec_row[clgkm];
			
			$outputRow['Totkm']['value'] = $mas_rec_row[totkm];
			addFooterTotal($outputRow,'Totkm');
			
			$outputRow['PARKING']['value'] = $mas_rec_row[parking];
			addFooterTotal($outputRow,'PARKING');
			addClassName($outputRow,'PARKING');
			
			$outputRow['OTHR']['value'] = $overTime;
			
			$outputRow['OTAMT']['value'] = $overTimeAmt;
			addFooterTotal($outputRow,'OTAMT');
			addClassName($outputRow,'OTAMT');
			
			
			$outputRow['OUT DA']['value'] = $daAmt;
			
			$outputRow['Extra Bef Late']['value'] = $earlyRepLateGoingAmt;
			
			$outputRow['Sunday Extra']['value'] = $holidayExtraDAAmt;
			
			$outputRow['2nd Duty Amt']['value'] = $secondDutyExtraAmt;
		
			$secondDutyCheck		=	$mas_rec_row[Startdate];
			 $secondDutyCheckStTime=$mas_rec_row[sttime];
				 $secondDutyCheckClgTime=$tempCloseTime;
			$output['rows'][][] = $outputRow;
			$rowCount++;
        } // while ends
		addTotalRows($output,$rowCount);
		
        //echo "</tbody></table>### ";
 //   } else
 //       echo "No Record Found..";
} else
    $output[error] = mysqli_error($con);
	
	echo json_encode($output);
} // end driverdutydetails -> inhouse


else if($_POST['report_type']=="coach"){
       $qrypart="";
        if(!empty($_POST[driver])){
    $qrypart=" and $bookingreg.driver Like'$_POST[driver]%'";}
       $sql = "SELECT br.driver, bookid,dutydate as ddate, DATE_FORMAT(dutydate,'%d/%m/%Y') as dutydate, billedto,usedby, bookedby,  br.`vehicle`, br.vehno, DATE_FORMAT( dutydate,'%d/%m/%Y')  as Startdate, DATE_FORMAT(rdate,'%d/%m/%Y') as Enddate,  br.dutytype, package, SUBSTRING_INDEX(sttime, ':', 2 ) AS sttime, SUBSTRING_INDEX( clgtime,  ':', 2 )AS clgtime, SUBSTRING_INDEX( tottime,  ':', 2 ) AS tottime,`stkm`,`clgkm`,`totkm`,parking, '' as `extrabef`, '' as `sundayextra`, '' as `secdutyamt`, dr.da1 as otamt , dr.ca as otallowance, dr.da as othr  FROM $bookingreg as br inner join vehreg as vr on br.vehno = vr.vehcode inner join dareg as dr on  br.dutytype=dr.dutytype where dutydate between '$from_date' and '$to_date' $qrypart and status NOT IN ('CANCELLED','VOID')  order by ddate,sttime ;";
    
	if (($mas_rec = mysqli_query($con,$sql))) {
    //if (mysqli_num_rows($mas_rec) > 0) {
       
        $dacount = 0;
		$rowCount = 0;
        while ($mas_rec_row = mysqli_fetch_array($mas_rec)) {	
			$mas_rec_row[Enddate]=str_replace("/","-","$mas_rec_row[Enddate]");
			$mas_rec_row[Startdate]=str_replace("/","-","$mas_rec_row[Startdate]");
			$daafter1 = 0;
			//if Duty Closes on next day after 1 AM add OTAMT from database to DA
			if(strtotime($mas_rec_row[Enddate])>strtotime($mas_rec_row[Startdate]))
			{
				$mas_rec_row[clgtime]=str_replace(":",".","$mas_rec_row[clgtime]");
				if($mas_rec_row[clgtime]>01.00)
				{
					$daafter1= $mas_rec_row[otamt];
				}
				$mas_rec_row[clgtime]=str_replace(".",":","$mas_rec_row[clgtime]");
				
			}
			$mas_rec_row[Enddate]=str_replace("-","/","$mas_rec_row[Enddate]");
			$mas_rec_row[Startdate]=str_replace("-","/","$mas_rec_row[Startdate]");
					
					
					
			$outputRow = array();
			
			$outputRow['Driver']['value'] = $mas_rec_row[driver];
			addFooterCounter($outputRow,'Driver');
			
			$outputRow['DUTY DATE']['value'] = $mas_rec_row[bookid];
			
			$outputRow['DUTY DATE']['value'] = $mas_rec_row[dutydate];
			
			$outputRow['Billed To']['value'] = $mas_rec_row[billedto];
			
			$outputRow['Used By']['value'] = $mas_rec_row[usedby];
			
			$outputRow['Booked By']['value'] = $mas_rec_row[bookedby];
			
			$outputRow['Vehicle']['value'] = $mas_rec_row[vehicle];
			
			$outputRow['Vehno']['value'] = $mas_rec_row[vehno];
			
			$outputRow['StartDate']['value'] = $mas_rec_row[Startdate];
			
			$outputRow['EndDate']['value'] = $mas_rec_row[Enddate];
			
			$outputRow['DutyType']['value'] = $mas_rec_row[dutytype];
			
			$outputRow['Package']['value'] = $mas_rec_row[package];
			
			$outputRow['Sttime']['value'] = $mas_rec_row[sttime];
			
			$outputRow['ClgTime']['value'] = $mas_rec_row[clgtime];
			
			$outputRow['TotTime']['value'] = $mas_rec_row[tottime];
			
			$outputRow['Stkm']['value'] = $mas_rec_row[stkm];
			
			$outputRow['Clgkm']['value'] = $mas_rec_row[clgkm];
			
			$outputRow['Totkm']['value'] = $mas_rec_row[totkm];
			addFooterTotal($outputRow,'Totkm');
			
			$outputRow['PARKING']['value'] = $mas_rec_row[parking];
			addFooterTotal($outputRow,'PARKING');
			addClassName($outputRow,'PARKING');
			
			$outputRow['OTHR']['value'] = $mas_rec_row[othr];
			
			$outputRow['OTRATE']['value'] = $mas_rec_row[otallowance] ;
			
			$outputRow['OTAMT']['value'] = $daafter1;
			addFooterTotal($outputRow,'OTAMT');
			addClassName($outputRow,'OTAMT');
			
			
			
			
			$outputRow['Extra Bef Late']['value'] = $mas_rec_row[extrabef];
			
			$outputRow['Sunday Extra']['value'] = $mas_rec_row[sundayextra];
			
			$outputRow['2nd Duty Amt']['value'] = $mas_rec_row[secdutyamt];
			
			$output['rows'][][] = $outputRow;
			$rowCount++;
			
			
        }//while ends
		addTotalRows($output,$rowCount);
		
		
       // echo "</tbody></table>### ";
 //   } else
 //       echo "No Record Found..";
} else
    $output[error] = mysqli_error($con);
	
	echo json_encode($output);
}  // end driverdutydetails -> coach
  

else if($_POST['report_type']=="car"){
       $qrypart="";
        if(!empty($_POST[driver])){
    $qrypart=" and $bookingreg.driver Like'$_POST[driver]%'";}
       $sql = "SELECT br.driver, bookid,dutydate as ddate, DATE_FORMAT(dutydate,'%d/%m/%Y') as dutydate, billedto,usedby, bookedby,  br.`vehicle`, br.vehno, DATE_FORMAT( dutydate,'%d/%m/%Y')  as Startdate, DATE_FORMAT(rdate,'%d/%m/%Y') as Enddate,  br.dutytype, package, SUBSTRING_INDEX(sttime, ':', 2 ) AS sttime, SUBSTRING_INDEX( clgtime,  ':', 2 )AS clgtime, SUBSTRING_INDEX( tottime,  ':', 2 ) AS tottime,`stkm`,`clgkm`,`totkm`,parking, '' as `extrabef`, '' as `sundayextra`, '' as `secdutyamt`, bi.reptime as drireptime , bi.closetime as driclosetime,bi.otallowance,bi.daallowance,bi.other1,bi.other2,bi.holidays FROM $bookingreg as br inner join vehreg as vr on br.vehno = vr.vehcode inner join empinfo as bi on  br.driver=bi.ECode where dutydate between '$from_date' and '$to_date' $qrypart and br.status NOT IN ('CANCELLED','VOID')  order by br.driver,ddate,sttime ;";
    
	if (($mas_rec = mysqli_query($con,$sql))) {
    //if (mysqli_num_rows($mas_rec) > 0) {
        $print = 1;
       
        $dacount = 0;
		$rowCount = 0;
        while ($mas_rec_row = mysqli_fetch_array($mas_rec)) {	
			$mas_rec_row[Enddate]=str_replace("/","-","$mas_rec_row[Enddate]");
			$mas_rec_row[Startdate]=str_replace("/","-","$mas_rec_row[Startdate]");
			
			$driverDutyTimeStart	=	$mas_rec_row[drireptime];
			$driverDutyTimeEnd 		= 	$mas_rec_row[driclosetime];
			$overTimePerHour		=	$mas_rec_row[otallowance];
			$outStationAlwPerDay	=	$mas_rec_row[daallowance];
			$earlyGoingBef6			=	$mas_rec_row[other1];
			$comingAfter4			=	$mas_rec_row[daallowance];
			$holidayExtraDA			=	$mas_rec_row[holidays];
			$secondDutyExtra		= 	$mas_rec_row[other2];

			$overTimeAmt			= 	0;
			$overTime				=	0;
			$daAmt					=	0;
			$earlyRepLateGoingAmt		=	0;
			//$secondDutyExtraAmt		=	0;
			$holidayExtraDAAmt		=	0;

			$mas_rec_row[sttime]=str_replace(":",".","$mas_rec_row[sttime]");
			$mas_rec_row[clgtime]=str_replace(":",".","$mas_rec_row[clgtime]");
			$driverDutyTimeStart=str_replace(":",".","$driverDutyTimeStart");
			$driverDutyTimeEnd=str_replace(":",".","$driverDutyTimeEnd");
			
			if($mas_rec_row[sttime]<$driverDutyTimeStart)
			{
				$overTime = $driverDutyTimeStart - $mas_rec_row[sttime];
				if($overTimePerHour>0)
				$overTimeAmt = $overTime*$overTimePerHour;
			}
			
			$dayDiff = (strtotime($mas_rec_row[Enddate])-strtotime($mas_rec_row[Startdate]))/(24*60*60);  // if there is diff in closing and end date
			$tempCloseTime = $mas_rec_row[clgtime];
			$tempCloseTime += $dayDiff*24;
			if($tempCloseTime>$driverDutyTimeEnd)
			{
				
				$overTime += ($tempCloseTime - $driverDutyTimeEnd);
				if($overTimePerHour>0)
				$overTimeAmt += ($overTime*$overTimePerHour);
			}

			if($mas_rec_row[dutytype]=='OUTSTATION'||$mas_rec_row[dutytype]=='OUT-STATION')
			{
				$daAmt = $outStationAlwPerDay;
			}
			
			if($dayDiff>0&&$tempCloseTime>4)
			{
				$daAmt += $outStationAlwPerDay;
			}

			if(($mas_rec_row[sttime]>6))
			{
				$earlyRepLateGoingAmt = $earlyGoingBef6;
			}

			if($dayDiff>0&&$tempCloseTime>1&&$tempCloseTime<4)
			{
				$earlyRepLateGoingAmt += $earlyGoingBef6;
			}


			if (date("D", strtotime($mas_rec_row[Startdate])) == "Sun"||date("D", strtotime($mas_rec_row[Enddate])) == "Sun")
			{
				$holidayExtraDAAmt = $holidayExtraDA;
			}

			

			
			
			/*if(strtotime($mas_rec_row[Enddate])>strtotime($mas_rec_row[Startdate]))
			{
				$mas_rec_row[clgtime]=str_replace(":",".","$mas_rec_row[clgtime]");
				if($mas_rec_row[clgtime]>01.00)
				{
					$daafter1= $mas_rec_row[otamt];
				}
				$mas_rec_row[clgtime]=str_replace(".",":","$mas_rec_row[clgtime]");
				
			}*/
			$mas_rec_row[Enddate]=str_replace("-","/","$mas_rec_row[Enddate]");
			$mas_rec_row[Startdate]=str_replace("-","/","$mas_rec_row[Startdate]");

			if("$secondDutyCheck"=="$mas_rec_row[Startdate]")
			{
				$secondDutyExtraAmt	=	$secondDutyExtra;
			}
					
           
					
			$outputRow = array();
			
			$outputRow['Driver']['value'] = $mas_rec_row[driver];
			addFooterCounter($outputRow,'Driver');
			
			$outputRow['DUTY DATE']['value'] = $mas_rec_row[bookid];
			
			
			$outputRow['DUTY DATE']['value'] = $mas_rec_row[dutydate];
			
			$outputRow['Billed To']['value'] = $mas_rec_row[billedto];
			
			$outputRow['Used By']['value'] = $mas_rec_row[usedby];
			
			$outputRow['Booked By']['value'] = $mas_rec_row[bookedby];
			
			$outputRow['Vehicle']['value'] = $mas_rec_row[vehicle];
			
			$outputRow['Vehno']['value'] = $mas_rec_row[vehno];
			
			$outputRow['StartDate']['value'] = $mas_rec_row[Startdate];
			
			$outputRow['EndDate']['value'] = $mas_rec_row[Enddate];
			
			$outputRow['DutyType']['value'] = $mas_rec_row[dutytype];
			
			$outputRow['Package']['value'] = $mas_rec_row[package];
			
			$outputRow['Sttime']['value'] = $mas_rec_row[sttime];
			
			$outputRow['ClgTime']['value'] = $mas_rec_row[clgtime];
			
			$outputRow['TotTime']['value'] = $mas_rec_row[tottime];
			
			$outputRow['Stkm']['value'] = $mas_rec_row[stkm];
			
			$outputRow['Clgkm']['value'] = $mas_rec_row[clgkm];
			
			$outputRow['Totkm']['value'] = $mas_rec_row[totkm];
			addFooterTotal($outputRow,'Totkm');
			
			$outputRow['PARKING']['value'] = $mas_rec_row[parking];
			addFooterTotal($outputRow,'PARKING');
			addClassName($outputRow,'PARKING');
			
			$outputRow['OTHR']['value'] = $overTime;
			
			$outputRow['OTRATE']['value'] = $overTimePerHour ;
			
			$outputRow['OTAMT']['value'] = $overTimeAmt;
			addFooterTotal($outputRow,'OTAMT');
			addClassName($outputRow,'OTAMT');
			
			$outputRow['DA']['value'] = $daAmt;
			
			
			
			$outputRow['Extra Bef Late']['value'] = $earlyRepLateGoingAmt;
			
			$outputRow['Sunday Extra']['value'] = $holidayExtraDAAmt;
			
			$outputRow['2nd Duty Amt']['value'] = $secondDutyExtraAmt;
			
			$output['rows'][][] = $outputRow;
			$rowCount++;

			$secondDutyCheck		=	$mas_rec_row[Startdate];
        } // while ends
		addTotalRows($output,$rowCount);
		
        //echo "</tbody></table>### ";
 //   } else
 //       echo "No Record Found..";
} else
    $output[error] = mysqli_error($con);
	
	echo json_encode($output);
}  // end driverdutydetails -> car




else{
if(empty($_POST['driver']))
{
	
	$qry_part="where dutydate between '$from_date' and '$to_date' and fny = '$_SESSION[SESS_FNY]'  order by dutydate";
	
}
else
{

$qry_part="where dutydate between '$from_date' and '$to_date' and driver='$_POST[driver]' and fny = '$_SESSION[SESS_FNY]' order by dutydate ";

}



if($dri_duty_det=mysqli_query($con,"SELECT DATE_FORMAT(dutydate,'%d/%m/%Y') as dutydate, bookid, vehno, driver, billedto,usedby, bookedby, dutytype, package, DATE_FORMAT( sttime,  '%H.%i') AS sttime, DATE_FORMAT( clgtime,  '%H.%i') AS clgtime, SUBSTRING_INDEX( tottime,  ':', 2 ) AS tottime, exhr,daamt,naamt,parking,m1value+m2value+m3value as misc
FROM $bookingreg $qry_part"))
{
$count_srno=0;
$count_totalbill=0;
$count_subtotal=0;
$count_sertax=0;
$count_surcharge=0;
$count_hcess=0;

addTotalRows($output,mysqli_num_rows($dri_duty_det));	
while($dri_duty_det_row=mysqli_fetch_assoc($dri_duty_det))
{

$index = 0;
	foreach ($dri_duty_det_row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$dri_duty_det,$index,$key,'r_',1);
	$index++;
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);
		
	//add Footer Counter to Column
	if($key == 'bookid')
	{
	addFooterCounter($outputRow,$key);
	addClassName($outputRow,$key,'bookid');
	addClassName($outputRow,$key,'links');
	$outputRow[$key]['links'] = "carrental_entry.php?bookid=$value,870,660";
	}
		
	//add Footer Total to Column
	$totalKeyArray = array('daamt','naamt','parking','misc');
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
	}
	
	$output['rows'][][] = $outputRow;
	}
}

else 
		$output[error] = mysqli_error($con);
	
	echo json_encode($output);
		}	

}



else if($_POST['report_view_type']=="veh_info_allduty")
{

if($_POST['report_type']=="vendorpayout"){
	
if(!empty($_POST['vehno']))
$qry_part="where dutydate between '$from_date' and '$to_date' and vehno='$_POST[vehno]' and fny = '$_SESSION[SESS_FNY]' order by dutydate";
else
$qry_part="where dutydate between '$from_date' and '$to_date' and fny = '$_SESSION[SESS_FNY]' order by dutydate";

//$output['total_rows'] ='dsds0';	

if($dri_duty_det=mysqli_query($con,"SELECT bookid as 'BRN NO.',  DATE_FORMAT(dutydate,'%d/%m/%Y') as 'DUTY DATE', vehno as 'VEH NO.',vendor as 'VENDOR', DRIVER, billedto as 'CLIENT NAME', BOOKEDBY, DUTYTYPE, package, DATE_FORMAT( sttime,  '%H.%i') AS sttime, DATE_FORMAT( clgtime,  '%H.%i') AS clgtime, SUBSTRING_INDEX( tottime,  ':', 2 ) AS tottime, exhr,exkm,stkm,clgkm,billno as 'BILL NO.',vehicle,tamount as 'DUTY AMOUNT',usedby as 'GUEST NAME',totkm,parking FROM $bookingreg $qry_part "))
{

	addTotalRows($output,mysqli_num_rows($dri_duty_det));	

while($dri_duty_det_row=mysqli_fetch_assoc($dri_duty_det))
{
	
	$index = 0;
	foreach ($dri_duty_det_row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$dri_duty_det,$index,$key,'b_',1);
	$index++;
	$field_orgname = $outputRow[$key]['name'];
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);
		
	//add Footer Counter to Column
	if($key == 'BRN NO.')
	{
	addFooterCounter($outputRow,$key);
	addCustomName($outputRow,$key,'b_srno[]');
	addClassName($outputRow,$key,'links');
	$outputRow[$key]['links'] = "carrental_entry.php?bookid=$value,870,660";
	}
	
	if($key == 'DUTY DATE')
	{
	addCustomName($outputRow,$key,'b_bdate[]');
	}
	
	if($key == 'BILL NO.')
	{ 
	addCustomName($outputRow,$key,'BILL NO.[]');
	addClassName($outputRow,$key,'BILL NO');
	}
		
	//add Footer Total to Column
	$totalKeyArray = array('DUTY AMOUNT','parking','totkm');
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
	}
	
	$output['rows'][][] = $outputRow;	
}


		}	

	else 
		$output[error] = mysqli_error($con);
	
	echo json_encode($output);
	
	}//if($_POST['report_type']=="vendorpayout"){
		
 else if($_POST['report_type']=="revenueshare"){
	
if(!empty($_POST['vehno']))
$qry_part="where dutydate between '$from_date' and '$to_date' and $bookingreg.vehno='$_POST[vehno]' and $bookingreg.fny = '$_SESSION[SESS_FNY]' and compid = bookingreg.vendor  and `vehicle` = vehtype and bookingreg.package = ratemaster.package order by dutydate";
else
$qry_part="where dutydate between '$from_date' and '$to_date' and $bookingreg.fny = '$_SESSION[SESS_FNY]'   and `vehicle` = vehtype and bookingreg.package = ratemaster.package order by dutydate";

/*$output['test'] ="SELECT bookid as 'SR No.',  DATE_FORMAT(dutydate,'%d/%m/%Y') as 'Date', billno as 'Bill No', billedto as 'Company', vehno as 'Car No', DRIVER as 'Driver Name', drivermob as 'Mob No', vendor as 'Vendor', $bookingreg.city as 'City', $bookingreg.package as 'Package', stkm as 'St.Km', clgkm as 'Cl.Km',  DATE_FORMAT( sttime,  '%H.%i') AS 'St.Time', DATE_FORMAT( clgtime,  '%H.%i') AS 'Cl.Time',SUBSTRING_INDEX( tottime,  ':', 2 ) AS 'Total Hrs', totkm as 'Total Km', (tamount-parking)  as 'Billed Amount', revdisc as 'Revenue Share', ((tamount-parking)*revdisc*0.01) as 'Vendor Share', parking as 'Toll Parking', ((tamount-parking)*revdisc*0.01) + parking as 'Net payable' FROM $bookingreg inner join ratemaster on compid = $bookingreg.vendor   $qry_part ";	*/

if($dri_duty_det=mysqli_query($con,"SELECT bookid as 'SR No.',  DATE_FORMAT(dutydate,'%d/%m/%Y') as 'Date', billno as 'Bill No', billedto as 'Company', vehno as 'Car No', DRIVER as 'Driver Name', drivermob as 'Mob No', vendor as 'Vendor', $bookingreg.city as 'City', $bookingreg.package as 'Package', stkm as 'St.Km', clgkm as 'Cl.Km',  DATE_FORMAT( sttime,  '%H.%i') AS 'St.Time', DATE_FORMAT( clgtime,  '%H.%i') AS 'Cl.Time',SUBSTRING_INDEX( tottime,  ':', 2 ) AS 'Total Hrs', totkm as 'Total Km', (tamount-parking)  as 'Billed Amount', revdisc as 'Revenue Share', ((tamount-parking)*revdisc*0.01) as 'Vendor Share', parking as 'Toll Parking', ((tamount-parking)*revdisc*0.01) + parking as 'Net payable' FROM $bookingreg inner join ratemaster on compid = $bookingreg.vendor   $qry_part "))
{

	addTotalRows($output,mysqli_num_rows($dri_duty_det));	

while($dri_duty_det_row=mysqli_fetch_assoc($dri_duty_det))
{
	
	$index = 0;
	foreach ($dri_duty_det_row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$dri_duty_det,$index,$key,'b_',1);
	$index++;
	$field_orgname = $outputRow[$key]['name'];
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);
		
	//add Footer Counter to Column
	if($key == 'SR No.')
	{
	addFooterCounter($outputRow,$key);
	addCustomName($outputRow,$key,'b_srno[]');
	addClassName($outputRow,$key,'links');
	$outputRow[$key]['links'] = "carrental_entry.php?bookid=$value,870,660";
	}
	
	if($key == 'DUTY DATE')
	{
	addCustomName($outputRow,$key,'b_bdate[]');
	}
		
	//add Footer Total to Column
	$totalKeyArray = array('b_Billed Amount[]','b_Vendor Share[]','b_parking[]','b_Net payable[]');
	if(in_array($field_orgname,$totalKeyArray))
	addFooterTotal($outputRow,$key);
	}
	
	$output['rows'][][] = $outputRow;	
}


		}	

	else 
		$output[error] = mysqli_error($con);
	
	echo json_encode($output);
	
	}//else if($_POST['report_type']=="revenueshare"){
	
}	//veh_info_allduty if ends

else if($_POST['report_view_type']=="veh_hire_inf")
{

if($_SESSION['SESS_BRANCH']!='HO')
	$qry_part_filter="and branch like '$_SESSION[SESS_BRANCH]'";

 
if($_POST['report_type']=="default")
{

if(!empty($_POST['vendor']))

$qry_part="where dutydate between '$from_date' and '$to_date' and vendor='$_POST[vendor]' and $bookingreg.fny = '$_SESSION[SESS_FNY]' $qry_part_filter order by dutydate";
else
$qry_part="where dutydate between '$from_date' and '$to_date' and $bookingreg.fny = '$_SESSION[SESS_FNY]' $qry_part_filter order by dutydate";

$sql="SELECT DATE_FORMAT(dutydate,'%d/%m/%Y') as dutydate, bookid, vendor, vehno, driver, billedto, $bookingreg.bookedby as bookedby, dutytype, package, DATE_FORMAT( sttime,  '%H.%i') AS sttime, DATE_FORMAT( clgtime,  '%H.%i') AS clgtime, SUBSTRING_INDEX( tottime,  ':', 2 ) AS tottime, exhr,exkm,stkm,clgkm,$bookingreg.vehicle,$bookingreg.usedby,totkm,daamt,naamt,(m1value+m2value+m3value) as misctot,parking,tamount ,$bookingreg.billno as billno FROM $bookingreg  $qry_part";


 
if($dri_duty_det=mysqli_query($con,$sql))
{	
$count_totalbill=0;
$rowCount  = mysqli_num_rows($dri_duty_det);
while($dri_duty_det_row=mysqli_fetch_assoc($dri_duty_det))
{
$index = 0;
	foreach ($dri_duty_det_row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$dri_duty_det,$index,$key);
	$index++;
	$field_orgname = $outputRow[$key]['name'];
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);

	//add Footer Counter to Column
	if($field_orgname == 'bookid')
	{
	addFooterCounter($outputRow,$key);
	}	
	



	}
	$output['rows'][][] = $outputRow;	
	$count_totalbill+=$dri_duty_det_row[tamount];
}
	$count_totalbill=number_format($count_totalbill,2);
	if(1==1)
	{
	$outputRow = array();
	
	$outputRow['dutydate']['value'] = '12';
	$outputRow['bookid']['value'] = '';
	$outputRow['vendor']['value'] = '';
	$outputRow['dutydate']['value'] = '';
	$outputRow['vehno']['value'] = '';
	$outputRow['driver']['value'] = '';
	$outputRow['billedto']['value'] = '';
	$outputRow['bookedby']['value'] = '';
	$outputRow['dutytype']['value'] = '';
	$outputRow['package']['value'] = '';
	$outputRow['sttime']['value'] = '';
	$outputRow['clgtime']['value'] = '';
	$outputRow['tottime']['value'] = '';
	$outputRow['exhr']['value'] = '';
	$outputRow['exkm']['value'] = '';
	$outputRow['stkm']['value'] = '';
	$outputRow['clgkm']['value'] = '';
	$outputRow['vehicle']['value'] = '';
	$outputRow['usedby']['value'] = '';
	$outputRow['totkm']['value'] = 'Vendor';
	$outputRow['daamt']['value'] = 'Total Trips';
	$outputRow['naamt']['value'] = 'Total Amount';
	$outputRow['misctot']['value'] = 'Total';
	$outputRow['parking']['value'] = '';
	$outputRow['tamount']['value'] = '';
	$outputRow['billno']['value'] = '';
	$output['rows'][][] = $outputRow;
	$rowCount++;
	
	


	}
	else echo mysqli_error($con);
	
	if(!empty($_POST['vendor']))
$qry_part="where dutydate between '$from_date' and '$to_date' and vendor='$_POST[vendor]' and $bookingreg.fny = '$_SESSION[SESS_FNY]' group by vendor order by dutydate";
else
$qry_part="where dutydate between '$from_date' and '$to_date' and $bookingreg.fny = '$_SESSION[SESS_FNY]' group by vendor order by dutydate";

$sql_grp = "SELECT '' as dutydate,'' as bookid,'' as vendor, '' as vehno,'' as driver,'' as billedto,'' as bookedby,'' as dutytype,'' as package,'' as sttime,'' as clgtime, '' as tottime,'' as exhr,'' as exkm,'' as stkm,'' as clgkm,'' as vehicle,'' as usedby,vendor as totkm,count(bookid) as daamt,sum(tamount) as naamt,(m1value+m2value+m3value) as misctot,'' as parking,'' as tamount,'' as billno FROM $bookingreg  $qry_part";

if($dri_duty_det=mysqli_query($con,$sql_grp))
{
	$rowCount  .=mysqli_num_rows($dri_duty_det);
	while($dri_duty_det_row=mysqli_fetch_assoc($dri_duty_det))
		{
			$index = 0;
	foreach ($dri_duty_det_row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$dri_duty_det,$index,$key);
	$index++;
	$field_orgname = $outputRow[$key]['name'];
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);			
		}
	$output['rows'][][] = $outputRow;
	}



//echo "</tbody></table>###Net Total Amount = $count_totalbill";

		}
		addTotalRows($output,$rowCount);	
}		
else 
		$output[error] = mysqli_error($con);
	
	echo json_encode($output);

}

else if($_POST['report_type']=="book_mis")
{
 if($_SESSION['SESS_BRANCH']!='HO')
	$qry_part_filter="and branch like '$_SESSION[SESS_BRANCH]'";
 
if(!empty($_POST['vendor']))
$qry_part="where dutydate between '$from_date' and '$to_date' and vendor='$_POST[vendor]' and $bookingreg.fny = '$_SESSION[SESS_FNY]' $qry_part_filter order by dutydate";
else
$qry_part="where dutydate between '$from_date' and '$to_date' and $bookingreg.fny = '$_SESSION[SESS_FNY]' $qry_part_filter order by dutydate";


if($dri_duty_det=mysqli_query($con,"SELECT DATE_FORMAT(dutydate,'%d/%m/%Y') as dutydate, bookid, vendor, vehno, driver, billedto, $bookingreg.bookedby, dutytype, package, DATE_FORMAT( sttime,  '%H.%i') AS sttime, DATE_FORMAT( clgtime,  '%H.%i') AS clgtime, SUBSTRING_INDEX( tottime,  ':', 2 ) AS tottime, exhr,exkm,stkm,clgkm,$bookingreg.billno as billno,$bookingreg.vehicle,tamount,$bookingreg.usedby,totkm,daamt,naamt,(m1value+m2value+m3value) as misctot,parking,srrate,optstax,opttoll FROM $bookingreg inner join $billreg on $bookingreg.billno=$billreg.billno inner join commst on $bookingreg.billedto=commst.compid $qry_part"))
{
$count_totalbill=0;
while($dri_duty_det_row=mysqli_fetch_array($dri_duty_det))
{
	$stamt=0;
	$totamount=$dri_duty_det_row[tamount];
	if(($dri_duty_det_row[opttoll])==0)
	$totamount=$dri_duty_det_row[tamount]-$dri_duty_det_row[parking];
	
	if(($dri_duty_det_row[optstax])==1)
	$staxstatus="Y";
	else
	$staxstatus="N";
	
if(($dri_duty_det_row[srrate])>5)
	{
	 $stamt=number_format(round((($totamount)*0.40)*$dri_duty_det_row[srrate]*0.01),2, '.', '');
	
	}
	else
	 $stamt=number_format(round(($totamount)*$dri_duty_det_row[srrate]*0.01),2, '.', '');
	 
	 $surchg=number_format(round($stamt*3*0.01),2, '.', '');
	 $totalamount=number_format(round($surchg+$stamt+$dri_duty_det_row[tamount]),2, '.', '');

	$outputRow = array();
	

	$outputRow['Booking Id']['value'] = $dri_duty_det_row[bookid];
	
	$outputRow['Client Name']['value'] = $dri_duty_det_row[billedto];
	
	$outputRow['Duty Date']['value'] = $dri_duty_det_row[dutydate];
	
	$outputRow['Used By']['value'] = $dri_duty_det_row[usedby];
	
	$outputRow['Duty Type']['value'] = $dri_duty_det_row[package];
	
	$outputRow['Vendor']['value'] = $dri_duty_det_row[vendor];
	
	$outputRow['Vehicle']['value'] = "$dri_duty_det_row[vehicle]-$dri_duty_det_row[vehno]";
	
	$outputRow['Driver']['value'] = $dri_duty_det_row[driver];
	
	$outputRow['Start Time']['value'] = $dri_duty_det_row[sttime];
	
	$outputRow['End Time']['value'] = $dri_duty_det_row[clgtime];
	
	$outputRow['Total Time']['value'] = $dri_duty_det_row[tottime];
	
	$outputRow['Start Km']['value'] = $dri_duty_det_row[stkm];
	
	$outputRow['End Km']['value'] = $dri_duty_det_row[clgkm];

	$outputRow['Total Kms']['value'] = $dri_duty_det_row[totkm];
	
	$outputRow['Extra Hrs']['value'] = $dri_duty_det_row[exhr];
	
	$outputRow['Extra Kms']['value'] = $dri_duty_det_row[exkm];
	
	$outputRow['DA Amount']['value'] = $dri_duty_det_row[daamt];
	
	$outputRow['NA Amount']['value'] = $dri_duty_det_row[naamt];
	
	$outputRow['Misc. Amount']['value'] = $dri_duty_det_row[misctot];
	
	$outputRow['Net Amount']['value'] =$totamount;
	
	$outputRow['Parking Toll']['value'] = $dri_duty_det_row[parking];
	
	$outputRow['Duty Amount']['value'] = $dri_duty_det_row[tamount];
	
	$outputRow['Ser. Tax Status']['value'] =$staxstatus;
	
	$outputRow['Ser. Tax Rate.']['value'] = $dri_duty_det_row[srrate];
	
	$outputRow['Ser. Tax Amt.']['value'] = $stamt;
	
	$outputRow['Sur Chg. Amt.']['value'] = $surchg;
	
	$outputRow['Total Amount']['value'] = $totalamount;
	
	$outputRow['Billno']['value'] = $dri_duty_det_row[billno];

	
	$output['rows'][][] = $outputRow;
	$rowCount++;

$count_totalbill+=$totalamount;
	}//end of while loop
	$count_totalbill=number_format($count_totalbill,2);
	if($count_totalbill!=0)
	{
	
	$outputRow = array();
	

	$outputRow['Booking Id']['value'] = '';
	
	$outputRow['Client Name']['value'] = '';
	
	$outputRow['Duty Date']['value'] = '';
	
	$outputRow['Used By']['value'] = '';
	
	$outputRow['Duty Type']['value'] = '';
	
	$outputRow['Vendor']['value'] = '';
	
	$outputRow['Vehicle']['value'] ='';
	
	$outputRow['Driver']['value'] = '';
	
	$outputRow['Start Time']['value'] = '';
	
	$outputRow['End Time']['value'] = '';
	
	$outputRow['Total Time']['value'] ='';
	
	$outputRow['Start Km']['value'] = '';
	
	$outputRow['End Km']['value'] = '';

	$outputRow['Total Kms']['value'] = '';
	
	$outputRow['Extra Hrs']['value'] = '';
	
	$outputRow['Extra Kms']['value'] = '';
	
	$outputRow['DA Amount']['value'] = '';
	
	$outputRow['NA Amount']['value'] = '';
	
	$outputRow['Misc. Amount']['value'] = '';
	
	$outputRow['Net Amount']['value'] ='';
	
	$outputRow['Parking Toll']['value'] = '';
	
	$outputRow['Duty Amount']['value'] = '';
	
	$outputRow['Ser. Tax Status']['value'] ='Vendor';
	
	$outputRow['Ser. Tax Rate.']['value'] = 'Total Trips';
	
	$outputRow['Ser. Tax Amt.']['value'] = 'Total Amount';
	
	$outputRow['Sur Chg. Amt.']['value'] = 'Total :';
	
	$outputRow['Total Amount']['value'] = $count_totalbill;
	
	$outputRow['Billno']['value'] = '';

	
	$output['rows'][][] = $outputRow;
	$rowCount++;
	}
	else echo mysqli_error($con);
	
		if(!empty($_POST['vendor']))
$qry_part="where dutydate between '$from_date' and '$to_date' and vendor='$_POST[vendor]' and $bookingreg.fny = '$_SESSION[SESS_FNY]' group by vendor order by dutydate";
else
$qry_part="where dutydate between '$from_date' and '$to_date' and $bookingreg.fny = '$_SESSION[SESS_FNY]' group by vendor order by dutydate";

$sql_grp = "SELECT vendor , count(bookid) as totaltrips, sum(tamount) as totalamt FROM $bookingreg  $qry_part";
if($dri_duty_det=mysqli_query($con,$sql_grp))
{
	while($dri_duty_det_row=mysqli_fetch_array($dri_duty_det))
		{
			
			$outputRow = array();
	

	$outputRow['Booking Id']['value'] = '';
	
	$outputRow['Client Name']['value'] = '';
	
	$outputRow['Duty Date']['value'] = '';
	
	$outputRow['Used By']['value'] = '';
	
	$outputRow['Duty Type']['value'] = '';
	
	$outputRow['Vendor']['value'] = '';
	
	$outputRow['Vehicle']['value'] ='';
	
	$outputRow['Driver']['value'] = '';
	
	$outputRow['Start Time']['value'] = '';
	
	$outputRow['End Time']['value'] = '';
	
	$outputRow['Total Time']['value'] ='';
	
	$outputRow['Start Km']['value'] = '';
	
	$outputRow['End Km']['value'] = '';

	$outputRow['Total Kms']['value'] = '';
	
	$outputRow['Extra Hrs']['value'] = '';
	
	$outputRow['Extra Kms']['value'] = '';
	
	$outputRow['DA Amount']['value'] = '';
	
	$outputRow['NA Amount']['value'] = '';
	
	$outputRow['Misc. Amount']['value'] = '';
	
	$outputRow['Net Amount']['value'] ='';
	
	$outputRow['Parking Toll']['value'] = '';
	
	$outputRow['Duty Amount']['value'] = '';
	
	$outputRow['Ser. Tax Status']['value'] =$dri_duty_det_row[vendor];
	
	$outputRow['Ser. Tax Rate.']['value'] = $dri_duty_det_row[totaltrips];
	
	$outputRow['Ser. Tax Amt.']['value'] = $dri_duty_det_row[totalamt];
	
	$outputRow['Sur Chg. Amt.']['value'] = '';
	
	$outputRow['Total Amount']['value'] ='';
	
	$outputRow['Billno']['value'] = '';

	
	$output['rows'][][] = $outputRow;
	$rowCount++;
			
		}
	
	}

	

addTotalRows($output,$rowCount);
		}	

	
else 
		$output[error] = mysqli_error($con);
	
	echo json_encode($output);

}

else if($_POST['report_type']=="misbills")
{
	

	if(empty($_POST['billedto']))
	{
		$qry_part="billdate between '$from_date' and '$to_date' and fny = '$_SESSION[SESS_FNY]' and trim(bookregno)!=''";
	}
	else
	{
		$qry_part="billdate between '$from_date' and '$to_date'  and billto='$_POST[billedto]' and fny = '$_SESSION[SESS_FNY]' and trim(bookregno)!=''";
		
		}
		
		
		/*
*sorting reports based on field
*/
if(!empty($_POST['sort_value']))
$qry_part.=" order by ".$_POST['sort_value'];
else
$qry_part.=" order by srno";
		
	if($bill_info=mysqli_query($con,"select srno,billno,DATE_FORMAT(billdate,'%d/%m/%Y') as billdate,billto,disrate,disamount,total,name,(tollamount+tp_withtax) as tollamount,$billreg.daamount,basicamount,miscamount,(sramount+educess+seducess) as sramt,bookregno from $billreg where  $qry_part"))
	{
		
		$count_totalbill=0;
		$rowCount=0;
		while($bill_info_row=mysqli_fetch_array($bill_info))
			{
			

$outputRow = array();
$outputRow['BILLNO']['value'] = $bill_info_row[billno];
$outputRow['BILLDATE']['value'] = $bill_info_row[billdate];
$outputRow['BILLED TO']['value'] = $bill_info_row[billto];
$outputRow['Basic Amount']['value'] =$bill_info_row[basicamount];
$outputRow['discount%']['value'] = $bill_info_row[disrate];
$outputRow['discount']['value'] = $bill_info_row[disamount];
$outputRow['Parking']['value'] = $bill_info_row[tollamount];
$outputRow['DA/NA']['value'] = $bill_info_row[daamount];
$outputRow['MISC Amt']['value'] = $bill_info_row[miscamount];
$outputRow['Ser Tax']['value'] = $bill_info_row[sramt];
$outputRow['AMOUNT']['value'] = $bill_info_row[total];


	
$count_totalbill+=$bill_info_row[total];

$bookids=$bill_info_row[bookregno];
if(substr($bookids,-1)==','){
$bookids=substr_replace($bookids,"",-1);
}

	if($bill_info_add=mysqli_query($con,"select bookid,vehicle,vehno,city,driver,vendor,usedby,dutyrate,guestid,DATE_FORMAT(dutydate,'%d/%m/%Y') as dutydate,TIME_FORMAT(sttime,'%H:%i') as sttime,TIME_FORMAT(clgtime,'%H:%i') as clgtime,tottime,stkm,ref,clgkm,totkm,exkm,exkmamt,exhr,exhramt,parking,m1value+m2value+m3value as misc,daamt,naamt,tamount from $bookingreg where bookid in ($bookids)"))
	{   
		$count=1;
		while($bill_info_add_row=mysqli_fetch_array($bill_info_add))
{		
if($count!=1)
	{

$outputRow['BILLNO']['value'] = '';
$outputRow['BILLDATE']['value'] = '';
$outputRow['BILLED TO']['value'] = '';
$outputRow['Basic Amount']['value'] = '';
$outputRow['discount%']['value'] = '';
$outputRow['discount']['value'] = '';
$outputRow['Parking']['value'] = '';
$outputRow['DA/NA']['value'] = '';
$outputRow['MISC Amt']['value'] = '';
$outputRow['Ser Tax']['value'] = '';
$outputRow['AMOUNT']['value'] = '';

    }


$outputRow['Booking Id']['value'] = $bill_info_add_row[bookid];
$outputRow['Pax Name']['value'] = $bill_info_add_row[usedby];
$outputRow['Veh Type']['value'] = $bill_info_add_row[vehicle];
$outputRow['Veh No']['value'] = $bill_info_add_row[vehno];
$outputRow['Driver']['value'] = $bill_info_add_row[driver];
$outputRow['Vendor']['value'] = $bill_info_add_row[vendor];
$outputRow['Location']['value'] = $bill_info_add_row[city];
$outputRow['Used Date']['value'] = $bill_info_add_row[dutydate];
$outputRow['Str Tm']['value'] = $bill_info_add_row[sttime];
$outputRow['End Time']['value'] = $bill_info_add_row[clgtime];
$outputRow['Tot Time']['value'] = $bill_info_add_row[tottime];
$outputRow['Str KMS']['value'] = $bill_info_add_row[stkm];
$outputRow['End KMS']['value'] = $bill_info_add_row[clgkm];
$outputRow['Tot KMS']['value'] = $bill_info_add_row[totkm];
$outputRow['Ex. Hrs']['value'] = $bill_info_add_row[exhr];
$outputRow['Ex. Kms']['value'] = $bill_info_add_row[exkm];
$outputRow['Duty Amount']['value'] = $bill_info_add_row[dutyrate];
$outputRow['Total Amount']['value'] = $bill_info_add_row[tamount];
$output['rows'][][] = $outputRow;
$rowCount++;


$count++;

}

}//bill info add if add ends
	else echo mysqli_error($con);
}//bill info while ends
	$count_totalbill=number_format($count_totalbill,2);
	if($count_totalbill!=0)
	{

$outputRow['BILLNO']['value'] = 'Vendor';
$outputRow['BILLDATE']['value'] = 'Total Trips';
$outputRow['BILLED TO']['value'] = 'Total Amount';
$outputRow['Basic Amount']['value'] = '';
$outputRow['discount%']['value'] = '';
$outputRow['discount']['value'] = '';
$outputRow['Parking']['value'] = '';
$outputRow['DA/NA']['value'] = '';
$outputRow['MISC Amt']['value'] = '';
$outputRow['Ser Tax']['value'] = '';
$outputRow['AMOUNT']['value'] = '';
$outputRow['Booking Id']['value'] = '';
$outputRow['Pax Name']['value'] = '';
$outputRow['Veh Type']['value'] = '';
$outputRow['Veh No']['value'] = '';
$outputRow['Driver']['value'] = '';
$outputRow['Vendor']['value'] = '';
$outputRow['Location']['value'] = '';
$outputRow['Used Date']['value'] = '';
$outputRow['Str Tm']['value'] = '';
$outputRow['End Time']['value'] = '';
$outputRow['Tot Time']['value'] = '';
$outputRow['Str KMS']['value'] = '';
$outputRow['End KMS']['value'] = '';
$outputRow['Tot KMS']['value'] = '';
$outputRow['Ex. Hrs']['value'] = '';
$outputRow['Ex. Kms']['value'] = '';
$outputRow['Duty Amount']['value'] = 'Total:';
$outputRow['Total Amount']['value'] = $count_totalbill;
$output['rows'][][] = $outputRow;
$rowCount++;

	}
	else echo mysqli_error($con);
	
		if(!empty($_POST['vendor']))
$qry_part="where billno in (select billno from $billreg where billdate between '$from_date' and '$to_date') and vendor='$_POST[vendor]' and $bookingreg.fny = '$_SESSION[SESS_FNY]' group by vendor order by dutydate";
else
$qry_part="where billno in (select billno from $billreg where billdate between '$from_date' and '$to_date') and $bookingreg.fny = '$_SESSION[SESS_FNY]' group by vendor order by dutydate";

$sql_grp = "SELECT vendor , count(bookid) as totaltrips, sum(tamount) as totalamt FROM $bookingreg $qry_part";
if($dri_duty_det=mysqli_query($con,$sql_grp))
{
	while($dri_duty_det_row=mysqli_fetch_array($dri_duty_det))
		{
		

$outputRow['BILLNO']['value'] = $dri_duty_det_row[vendor];
$outputRow['BILLDATE']['value'] = $dri_duty_det_row[totaltrips];
$outputRow['BILLED TO']['value'] = $dri_duty_det_row[totalamt];
$outputRow['Basic Amount']['value'] = '';
$outputRow['discount%']['value'] = '';
$outputRow['discount']['value'] = '';
$outputRow['Parking']['value'] = '';
$outputRow['DA/NA']['value'] = '';
$outputRow['MISC Amt']['value'] = '';
$outputRow['Ser Tax']['value'] = '';
$outputRow['AMOUNT']['value'] = '';
$outputRow['Booking Id']['value'] = '';
$outputRow['Pax Name']['value'] = '';
$outputRow['Veh Type']['value'] = '';
$outputRow['Veh No']['value'] = '';
$outputRow['Driver']['value'] = '';
$outputRow['Vendor']['value'] = '';
$outputRow['Location']['value'] = '';
$outputRow['Used Date']['value'] = '';
$outputRow['Str Tm']['value'] = '';
$outputRow['End Time']['value'] = '';
$outputRow['Tot Time']['value'] = '';
$outputRow['Str KMS']['value'] = '';
$outputRow['End KMS']['value'] = '';
$outputRow['Tot KMS']['value'] = '';
$outputRow['Ex. Hrs']['value'] = '';
$outputRow['Ex. Kms']['value'] = '';
$outputRow['Duty Amount']['value'] = '';
$outputRow['Total Amount']['value'] = '';
$output['rows'][][] = $outputRow;
$rowCount++;

			
		}
	
	}

	
	addTotalRows($output,$rowCount);
		}	//bill info if ends
	else $output[error] = mysqli_error($con);
	
	echo json_encode($output);
	}//mis bills ends
	
	
else if($_POST['report_type']=="vendorpofit"){
	
	if(!empty($_POST['vendor']))
$qry_part="where dutydate between '$from_date' and '$to_date' and vendor='$_POST[vendor]' and $bookingreg.fny = '$_SESSION[SESS_FNY]'  order by dutydate";
else
$qry_part="where dutydate between '$from_date' and '$to_date' and $bookingreg.fny = '$_SESSION[SESS_FNY]'  order by dutydate";
	
	
	$sql = "SELECT $bookingreg.billno as 'BILL NO.', tamount as 'TOTAL AMT', Vbillno as 'VBILL NO.',  Vnetamount as 'VTOTAL AMT' FROM $bookingreg  $qry_part";
	 
	
	$result = mysqli_query($con,$sql);
	
	if($result)
	{
	$i=0;
	$count_totalbill=0;
	addTotalRows($output,mysqli_num_rows($result));
	while($row = mysqli_fetch_assoc($result))
	{
		
		$index = 0;
	foreach ($row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$result,$index,$key,'b_',1);
	$index++;
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);
		
	//add Footer Counter to Column
   if($key == 'BILL NO.')
	{
	addFooterCounter($outputRow,$key);
	addClassName($outputRow,$key,'BILL NO.');
	 addClassName($outputRow,$key,'links');
	}
		
	//add Footer Total to Column
	$totalKeyArray = array('TOTAL AMT','VTOTAL AMT');
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
	}
	$output['rows'][][] = $outputRow;
	$i++;
	$count_totalbill+=$row[total];
	}
	//if displayed rows greater than 0 then sum total
	$count_totalbill=number_format($count_totalbill,2);

	}
	else
	$output[error] = mysqli_error($con);
	
	echo json_encode($output);
	
}	
	

}//end of veh_hire_inf

else if($_POST['report_view_type']=="cov_lett")
{

if(empty($_POST['billedto']))
$qry_part="billdate between '$from_date' and '$to_date' and fny = '$_SESSION[SESS_FNY]' ";
else
$qry_part="billdate between '$from_date' and '$to_date'  and billto='$_POST[billedto]' and fny = '$_SESSION[SESS_FNY]' ";
if(!empty($_POST['filter_type_value'])){
	$selsrno=rtrim($_POST['filter_type_value'],",");
	$qry_part.= " and srno in ($selsrno)";
}

if($bill_info=mysqli_query($con,"select srno as 'SR. NO.' , billno as 'Bill No.', DATE_FORMAT(billdate,'%d/%m/%Y') as 'Bill Date', bookdate as 'Book Date',	billto,	name, bookedby, usedby as 'USED BY', basicamount, tollamount, daamount,	disrate, disamount,	  srrate, sramount, educess, totalamt, seducess, prcharge, total as TOTAL, expst	 from $billreg where $qry_part  order by CONVERT(srno, SIGNED INTEGER) "))
{	


	addTotalRows($output,mysqli_num_rows($bill_info));	
while($bill_info_row=mysqli_fetch_assoc($bill_info))
{
	

		$index = 0;
	foreach ($bill_info_row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$bill_info,$index,$key,'r_',1);
	$index++;
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);
		
	//add Footer Counter to Column
	if($key == 'SR. NO.')
	{
	addFooterCounter($outputRow,$key);
	addClassName($outputRow,$key,'srno');
	 addClassName($outputRow,$key,'links');
	}
	
	//add Class to Column
	if($key == 'Bill No.')
	{
	addClassName($outputRow,$key,'billno');
	}
	
	//add Class to Column
	if($key == 'Bill Date')
	{
	addClassName($outputRow,$key,'billdate');
	}
	
	//add Class to Column
	if($key == 'USED BY')
	{
	addClassName($outputRow,$key,'usedby');
	}
	
	//add Class to Column
	if($key == 'TOTAL')
	{
	addClassName($outputRow,$key,'total');
	}
	
		//add Class to Column
	if($key == 'Book Date')
	{
	addClassName($outputRow,$key,'bookdate');
	}
		
	//add Footer Total to Column
	$totalKeyArray = array('basicamount','tollamount','daamount','	disrate','disamount','	  srrate','sramount','educess','totalamt','seducess','prcharge','TOTAL');
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
	}
	
	$output['rows'][][] = $outputRow;
	}

		}	

	else 
		$output[error] = mysqli_error($con);
	
	echo json_encode($output);
}


else if($_POST['report_view_type']=="led_det")
{
	
  if($_POST['report_type']=="SALES"){
	  $qry_part = "";
	  if(!empty($_POST['billedto']))
	  $qry_part = "and buyercode='$_POST[billedto]'";
	  
	  $sql = "select  orderid as 'VCH NO',DATE_FORMAT(orderdate,'%d/%m/%Y')  as 'BILL DATE',buyercode as 'BILLED TO',orderid as 'BILL NO','SALES' as VCHTYPE,FORMAT(grtotal,2) as 'DEBIT' ,FORMAT(paid,2) as 'CREDIT',expst as 'STATUS' from $billreg  INNER JOIN commst
	  ON $billreg.buyercode=commst.compid
	  where orderdate between '$from_date' and '$to_date'  $qry_part   order by CONVERT(orderid, SIGNED INTEGER)"; 
	  
	  $result = mysqli_query($con,$sql);
	  
	  if($result&&mysqli_num_rows($result)>0)
	  {
	  $i=0;
	  $count_totalbill=0;
	  addTotalRows($output,mysqli_num_rows($result));
	  while($row = mysqli_fetch_assoc($result))
	  {
		  $index = 0;
	  foreach ($row as $key=>$value) {			
	  $outputRow[$key]['value'] = $value;	
	  
	  /* 
	   * start
	   * getting field name of table
	  */	
	  addDataBaseName($outputRow,$result,$index,$key,'b_',1);
	  $index++;
	  /* 
	   * end
	  */
		  
	  //adding number class
	  addClassName($outputRow,$key);
		  
	  //add Footer Counter to Column
	  if($key == 'VCH NO')
	  {
	  addFooterCounter($outputRow,$key);
	  addClassName($outputRow,'VCH NO','click_bill_pdf');
       addClassName($outputRow,'VCH NO','links');
	  }
		  
	  //add Footer Total to Column
	  $totalKeyArray = array('DEBIT','CREDIT');
	  if(in_array($key,$totalKeyArray))
	  addFooterTotal($outputRow,$key);
	  }
	  
	  $output['rows'][][] = $outputRow;
	  $i++;
	  $count_totalbill+=$row[total];
	  }
	  //if displayed rows greater than 0 then sum total
	  $count_totalbill=number_format($count_totalbill,2);
  
	  }
	  else
	  $output[error] = mysqli_error($con);
	  
	  echo json_encode($output);
	  
  }
  
  else if($_POST['report_type']=="salesummery"){
	  $qry_part = "";
	  if(!empty($_POST['billedto'])){
	  $qry_part = "and buyercode='$_POST[billedto]'";
	  
	  $sql = "select  $billreg.srno as 'SR NO',DATE_FORMAT($billreg.orderdate,'%d/%m/%Y') as 'BILL DATE',$billreg.buyercode as 'BILLED TO',$billreg.orderid as 'BILL NO','SALES' as VCHTYPE,FORMAT($billreg.grtotal,2) as 'DEBIT' ,FORMAT($billreg.paid,2) as 'CREDIT',vchreg.vchno as 'VCH NO',vchreg.bill_no as 'CHEQUE NO',DATE_FORMAT(vchreg.invdate,'%d/%m/%Y') as 'CQ. DATE', vchreg.account as ACCOUNT, $billreg.expst as 'STATUS' 
	  from $billreg  
	  INNER JOIN commst ON $billreg.buyercode=commst.compid 
	  INNER JOIN vchdetails ON $billreg.orderid=vchdetails.billno
	  INNER JOIN vchreg ON vchreg.vchno=vchdetails.vchno
	  where 
	  orderdate between '$from_date' and '$to_date' 
	   
	  $qry_part   
	  order by CONVERT(srno, SIGNED INTEGER)"; 
	  
	// $output['test'] =  $sql;
	  
	  $result = mysqli_query($con,$sql);
	  
	  if($result&&mysqli_num_rows($result)>0)
	  {
	  $i=0;
	  $count_totalbill=0;
	  addTotalRows($output,mysqli_num_rows($result));
	  while($row = mysqli_fetch_assoc($result))
	  {
		  $index = 0;
	  foreach ($row as $key=>$value) {			
	  $outputRow[$key]['value'] = $value;	
	  /* 
	   * start
	   * getting field name of table
	  */	
	  addDataBaseName($outputRow,$result,$index,$key,'b_',1);
	  $index++;
	  /* 
	   * end
	  */
		  
	  //adding number class
	  addClassName($outputRow,$key);
		  
	  //add Footer Counter to Column
	  if($key == 'SR NO')
	  {
	  addFooterCounter($outputRow,$key);
	  addClassName($outputRow,'SR NO','click_bill_pdf');
      addClassName($outputRow,'SR NO','links');
	  }
		  
	  //add Footer Total to Column
	  $totalKeyArray = array('DEBIT','CREDIT');
	  if(in_array($key,$totalKeyArray))
	  addFooterTotal($outputRow,$key);
	  }
	  
	  $output['rows'][][] = $outputRow;
	  $i++;
	  $count_totalbill+=$row[total];
	  }
	  //if displayed rows greater than 0 then sum total
	  $count_totalbill=number_format($count_totalbill,2);
  
	  }
	  else
	  $output[error] = mysqli_error($con);
	  
	  echo json_encode($output);
	  }
	  else{
		  
		  
		  // INNER JOIN commst ON $billreg.billto=commst.compid 
	$sql = "select buyercode AS  'BILLEDTO', COUNT( * ) AS  'TOTAL INV', SUM( grtotal ) AS  'DEBIT', SUM( paid ) AS  'CREDIT', SUM( grtotal ) - SUM( paid ) AS 'TOTAL' from $billreg where orderdate between '$from_date' and '$to_date'   group by buyercode "; 
	  
	 $output['test'] =  $sql;
	  
	  $result = mysqli_query($con,$sql);
	  
	  if($result&&mysqli_num_rows($result)>0)
	  {
	  $i=0;
	  $count_totalbill=0;
	  addTotalRows($output,mysqli_num_rows($result));
	  while($row = mysqli_fetch_assoc($result))
	  {
		  $index = 0;
	  foreach ($row as $key=>$value) {			
	  $outputRow[$key]['value'] = $value;	
	  /* 
	   * start
	   * getting field name of table
	  */	
	  addDataBaseName($outputRow,$result,$index,$key,'b_',1);
	  $index++;
	  /* 
	   * end
	  */
		  
	  //adding number class
	  addClassName($outputRow,$key);
		  
	  //add Footer Counter to Column
	  if($key == 'BILLEDTO')
	  {
	  addFooterCounter($outputRow,$key);
	  addClassName($outputRow,'BILLEDTO','billdet_view');
      addClassName($outputRow,'BILLEDTO','links');
	  }
		  
	  //add Footer Total to Column
	  $totalKeyArray = array('DEBIT','CREDIT','TOTAL');
	  if(in_array($key,$totalKeyArray))
	  addFooterTotal($outputRow,$key);
	  }
	  
	  $output['rows'][][] = $outputRow;
	  $i++;
	  $count_totalbill+=$row[TOTAL];
	  }
	  //if displayed rows greater than 0 then sum total
	  $count_totalbill=number_format($count_totalbill,2);
  
	  }
	  else
	  $output[error] = mysqli_error($con);
	  
	  echo json_encode($output); 
		  
		  
		  
		  
		  
		  }
	  
  }

else if($_POST['report_type']=="PURCHASE"){
	
	$qry_part = "";
	if(!empty($_POST['billedto']))
	$qry_part = "and comcode='$_POST[billedto]'";
	
	$sql = "select  vchno  as 'VCH NO', DATE_FORMAT(vchdate,'%d/%m/%Y') as 'BILL DATE', comcode as 'BILLED TO', bill_no as 'BILL NO', 'PURCHASE' as VCHTYPE, ser_tax as 'SER. TAX', educess as 'S.B.CESS', seducess as 'K.K.CESS', FORMAT(totamount,2) as DEBIT, FORMAT(paid,2) as CREDIT, expst as STATUS from purcreg INNER JOIN commst ON purcreg.comcode=commst.compid where vchdate  between '$from_date' and '$to_date'  and purcreg.cmp='$_SESSION[SESS_CMPC]'   and purcreg.fny = '$_SESSION[SESS_FNY]' $qry_part "; 
	
	$result = mysqli_query($con,$sql);
	
	if($result)
	{
	$i=0;
	$count_totalbill=0;
	addTotalRows($output,mysqli_num_rows($result));
	while($row = mysqli_fetch_assoc($result))
	{
		
			$index = 0;
	foreach ($row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$result,$index,$key,'b_',1);
	$index++;
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);
		
	//add Footer Counter to Column
	if($key == 'VCH NO')
	{
	addFooterCounter($outputRow,$key);
	addClassName($outputRow,$key,'links');
	$outputRow[$key]['links'] = "vch_entry.php?mode=PURCHASE&vchno=$value,870,660";
	}
		
	//add Footer Total to Column
	$totalKeyArray = array('DEBIT','CREDIT','K.K.CESS','S.B.CESS','SER. TAX');
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
	}
	
	$output['rows'][][] = $outputRow;
	$i++;
	$count_totalbill+=$row[total];
	}
	//if displayed rows greater than 0 then sum total
	$count_totalbill=number_format($count_totalbill,2);


	}
	else
	echo $output[error] = mysqli_error($con);
	
	echo json_encode($output);
	
}

else if($_POST['report_type']=="RECEIPT"){
	
	$qry_part = "";
	if(!empty($_POST['billedto']))
	$qry_part = "and vchreg.comcode='$_POST[billedto]'";
	
	
	$sql = "select vchno as 'VCH NO',DATE_FORMAT(vchdate,'%d/%m/%Y') as 'BILL DATE',refno as 'Ref no',agnstref as 'Agnst Ref.',ledger as 'BILLED TO',account as ACCOUNT, 'RECEIPT' as VCHTYPE,totamount as DEBIT,paid as CREDIT,narration as NARRATION, vchreg.expst as STATUS  from vchreg LEFT JOIN ledgerreg 	ON vchreg.comcode=ledgerreg.alias
	where vchdate  between '$from_date' and '$to_date'  and vchreg.cmp='$_SESSION[SESS_CMPC]'   and vchreg.fny = '$_SESSION[SESS_FNY]' AND VCHTYPE = 'RECEIPT' $qry_part;";
	 
	
	$result = mysqli_query($con,$sql);
	
	if($result)
	{
	$i=0;
	$count_totalbill=0;
	addTotalRows($output,mysqli_num_rows($result));
	while($row = mysqli_fetch_assoc($result))
	{
		
		$index = 0;
	foreach ($row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$result,$index,$key,'b_',1);
	$index++;
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);
		
	//add Footer Counter to Column
	if($key == 'VCH NO')
	{
	addFooterCounter($outputRow,$key);
	addClassName($outputRow,$key,'VCH NO');
	addClassName($outputRow,$key,'links');
	$outputRow[$key]['links'] = "vch_entry.php?mode=RECEIPT&vchno=$value,870,660";
	}
		
	//add Footer Total to Column
	$totalKeyArray = array('DEBIT','CREDIT','STATUS');
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
	}
	$output['rows'][][] = $outputRow;
	$i++;
	$count_totalbill+=$row[total];
	}
	//if displayed rows greater than 0 then sum total
	$count_totalbill=number_format($count_totalbill,2);
	

//echo "</tbody></table>### ";
	}
	else
	$output[error] = mysqli_error($con);
	
	echo json_encode($output);
	
}

else if($_POST['report_type']=="PAYMENT"){
	$qry_part = "";
	if(!empty($_POST['billedto']))
	$qry_part = "and vchreg.comcode='$_POST[billedto]'";
	
	
	$sql = "select vchno as 'VCH NO',DATE_FORMAT(vchdate,'%d/%m/%Y') as 'BILL DATE',ledger as 'BILLED FROM',account as ACCOUNT, 'PAYMENT' as VCHTYPE,totamount as 'DEBIT',paid as CREDIT ,vchreg.expst as STATUS from vchreg LEFT JOIN ledgerreg 	ON vchreg.comcode=ledgerreg.alias
	where vchdate  between '$from_date' and '$to_date'  and vchreg.cmp='$_SESSION[SESS_CMPC]'   and vchreg.fny = '$_SESSION[SESS_FNY]' AND VCHTYPE = 'PAYMENT' $qry_part;";
	
	
	$result = mysqli_query($con,$sql);
	
	if($result)
	{
	
	$i=0;
	$count_totalbill=0;
	addTotalRows($output,mysqli_num_rows($result));
	while($row = mysqli_fetch_assoc($result))
	{
		
		$index = 0;
	foreach ($row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$result,$index,$key,'b_',1);
	$index++;
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);
		
	//add Footer Counter to Column
	if($key == 'VCH NO')
	{
	addFooterCounter($outputRow,$key);
	addClassName($outputRow,$key,'VCH NO');
	addClassName($outputRow,$key,'links');
	$outputRow[$key]['links'] = "vch_entry.php?mode=PAYMENT&vchno=$value,870,660";
	}
		
	//add Footer Total to Column
	$totalKeyArray = array('DEBIT','CREDIT','STATUS');
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
	}
	
	$output['rows'][][] = $outputRow;

	$i++;
	$count_totalbill+=$row[total];
	}
	//if displayed rows greater than 0 then sum total
	$count_totalbill=number_format($count_totalbill,2);
	}
	else
	$output[error] = mysqli_error($con);
	
	echo json_encode($output);
	
}

else if($_POST['report_type']=="JOURNAL"){
	$qry_part = "";
	if(!empty($_POST['billedto']))
	$qry_part = "and vchreg.comcode='$_POST[billedto]'";
	
	$sql = "select vchno as 'VCH NO',DATE_FORMAT(vchdate,'%d/%m/%Y') as 'BILL DATE',ledger as 'BILLED FROM',account as ACCOUNT, 'JOURNAL' as VCHTYPE,totamount as 'DEBIT',paid as CREDIT ,vchreg.expst as STATUS from vchreg LEFT JOIN ledgerreg 	ON vchreg.comcode=ledgerreg.alias
	where vchdate  between '$from_date' and '$to_date'  and vchreg.cmp='$_SESSION[SESS_CMPC]'   and vchreg.fny = '$_SESSION[SESS_FNY]' AND VCHTYPE = 'JOURNAL' $qry_part;";
	
	
	$result = mysqli_query($con,$sql);
	
	if($result)
	{
	$i=0;
	$count_totalbill=0;
	addTotalRows($output,mysqli_num_rows($result));
	while($row = mysqli_fetch_assoc($result))
	{
		
		$index = 0;
	foreach ($row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$result,$index,$key,'b_',1);
	$index++;
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);
		
	//add Footer Counter to Column
	if($key == 'VCH NO')
	{
	addFooterCounter($outputRow,$key);
	addClassName($outputRow,$key,'VCH NO');
	addClassName($outputRow,$key,'links');
	$outputRow[$key]['links'] = "vch_entry.php?mode=JOURNAL&vchno=$value,870,660";
	}
		
	//add Footer Total to Column
	$totalKeyArray = array('DEBIT','CREDIT','STATUS');
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
	}
	
	$output['rows'][][] = $outputRow;
	$i++;
	$count_totalbill+=$row[total];
	}
	//if displayed rows greater than 0 then sum total
	$count_totalbill=number_format($count_totalbill,2);


	}
	else
	$output[error] = mysqli_error($con);
	
	echo json_encode($output);
	
}


else if($_POST['report_type']=="CONTRA"){
	$qry_part = "";
	if(!empty($_POST['billedto']))
	$qry_part = "and vchreg.comcode='$_POST[billedto]'";
	
	$sql = "select vchno as 'VCH NO',DATE_FORMAT(vchdate,'%d/%m/%Y') as 'BILL DATE',ledger as 'BILLED FROM',account as ACCOUNT, 'JOURNAL' as VCHTYPE,totamount as 'DEBIT',paid as CREDIT ,vchreg.expst as STATUS from vchreg LEFT JOIN ledgerreg 	ON vchreg.comcode=ledgerreg.alias
	where vchdate  between '$from_date' and '$to_date'  and vchreg.cmp='$_SESSION[SESS_CMPC]'   and vchreg.fny = '$_SESSION[SESS_FNY]' AND VCHTYPE = 'CONTRA' $qry_part;";
	
	
	$result = mysqli_query($con,$sql);
	
	if($result)
	{
	$i=0;
	$count_totalbill=0;
	addTotalRows($output,mysqli_num_rows($result));
	while($row = mysqli_fetch_assoc($result))
	{
		
		$index = 0;
	foreach ($row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$result,$index,$key,'b_',1);
	$index++;
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);
		
	//add Footer Counter to Column
	if($key == 'VCH NO')
	{
	addFooterCounter($outputRow,$key);
	addClassName($outputRow,$key,'VCH NO');
	addClassName($outputRow,$key,'links');
	$outputRow[$key]['links'] = "vch_entry.php?mode=CONTRA&vchno=$value,870,660";
	}
		
	//add Footer Total to Column
	$totalKeyArray = array('DEBIT','CREDIT','STATUS');
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
	}
	
	$output['rows'][][] = $outputRow;
	$i++;
	$count_totalbill+=$row[total];
	}
	//if displayed rows greater than 0 then sum total
	$count_totalbill=number_format($count_totalbill,2);


	}
	else
	$output[error] = mysqli_error($con);
	
	echo json_encode($output);
	
}


else if($_POST['report_type']=="TrialBalance"){
	$rowCount = 0;
	
	//echo "<table  id='table_report_view'  cellspacing='0' width='100%''><thead> <tr><th><textarea name='b_Parti[]'>Particulars</textarea></th><th><textarea name='b_damoun[]'>Dr. Amount</textarea></th><th><textarea name='b_camount[]'>Cr. Amount</textarea></th> </tr></thead> ";
	
	$account = "CASH A/C";
        $i=0;
		$crtotal=0;
		$drtotal=0;
	$count_totalbill=0;
        $balance = 0;
		$rowCount = 0;
	
    //echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** CASH BALANCE **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['Particulars']['value'] = "** CASH BALANCE **";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] ='';
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] = '';
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$recdsql = "SELECT sum(`totamount`) as recd FROM `vchreg` WHERE account = 'CASH' and vchtype IN ('RECEIPT','JOURNAL') and fny = '$_SESSION[SESS_FNY]' GROUP by account ";
	$result_rec = mysqli_query($con,$recdsql);
	$rowrec = mysqli_fetch_assoc($result_rec);
	$recived = $rowrec['recd']; 
	
	
	$widrawalsql = "SELECT sum(totamount) as widra FROM `vchreg` where vchtype = 'CONTRA' and account = 'CASH' and fny = '$_SESSION[SESS_FNY]'";
	$result_widra = mysqli_query($con,$widrawalsql);
	$rowwidra = mysqli_fetch_assoc($result_widra);
	$widrawal = $rowwidra['widra']; 
	
	
	$paidsql ="SELECT account,  sum(`totamount`) as paid FROM `vchreg` WHERE account = 'CASH' and vchtype = 'PAYMENT' and fny = '$_SESSION[SESS_FNY]' group by account";
	$result_pai = mysqli_query($con,$paidsql);
	$rowpai = mysqli_fetch_assoc($result_pai);
	$paid = $rowpai['paid']; 
	
	$depositsql = "SELECT sum(totamount) as deposit FROM `vchreg` where vchtype = 'CONTRA' and comcode = 'CASH' and fny = '$_SESSION[SESS_FNY]'";
	$result_depos = mysqli_query($con,$depositsql);
	$rowdepos = mysqli_fetch_assoc($result_depos);
	$deposit = $rowdepos['deposit']; 
	
	
	$balance = ($recived + $widrawal) - ($paid + $deposit);
	$dramount=0;
	$cramount=0;
	if($balance>0){
		$dramount = $balance;
		
		}
		else {
			$cramount = $balance;
			}
	
	
	
	
	//echo "<tr><td ><textarea name='b_Parti[]'>$account : ($recived $widrawal) ($paid $deposit)</textarea></td><td><textarea name='b_damoun[]'>".abs($dramount)."</textarea></td><td><textarea name='b_camount[]'>".abs($cramount)."</textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['Particulars']['value'] = "$account : ($recived $widrawal) ($paid $deposit)";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = abs($dramount);
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] = abs($cramount);
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$crtotal+=abs($cramount);
	$drtotal+=abs($dramount);
	
	$bank = "SELECT DISTINCT(ledger) as bank FROM `ledgerreg` WHERE ledger != 'CASH' and ledtype = 'CASHBANK' ";
	$result_bank = mysqli_query($con,$bank);
	
	if($result_bank){
		//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** BANK BALANCE **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
		
		
		$outputRow = array();
	$outputRow['Particulars']['value'] = "** BANK BALANCE **";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = abs($dramount);
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] = abs($cramount);
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
		
	while($rowbank = mysqli_fetch_array($result_bank))
	{
		$bankled = $rowbank['bank'];
		$recdbanksql = "SELECT  sum(`totamount`) as recd FROM `vchreg` WHERE  vchtype IN ('RECEIPT','JOURNAL') and fny = '$_SESSION[SESS_FNY]' and account = '$bankled'";
	$bankrec = mysqli_query($con,$recdbanksql);
	$rowrecbank = mysqli_fetch_assoc($bankrec);
	$recbank = $rowrecbank['recd']; 
	
	$depositsql = "SELECT sum(totamount) as deposit FROM `vchreg` where vchtype = 'CONTRA' and account = '$bankled' and fny = '$_SESSION[SESS_FNY]'";
	$result_depos = mysqli_query($con,$depositsql);
	$rowdepos = mysqli_fetch_assoc($result_depos);
	$bankdeposit = $rowdepos['deposit']; 
	
	
	$paidbanksql = "SELECT  sum(`totamount`) as paid FROM `vchreg` WHERE vchtype = 'PAYMENT' and fny = '$_SESSION[SESS_FNY]' and account = '$bankled'";
	$bankpay = mysqli_query($con,$paidbanksql);
	$rowpaybank = mysqli_fetch_assoc($bankpay);
	$paybank = $rowpaybank['paid']; 
	
	$widrawalsql = "SELECT sum(totamount) as widra FROM `vchreg` where vchtype = 'CONTRA' and comcode = '$bankled' and fny = '$_SESSION[SESS_FNY]'";
	$result_widra = mysqli_query($con,$widrawalsql);
	$rowwidra = mysqli_fetch_assoc($result_widra);
	$bankwidrawal = $rowwidra['widra'];
	
	$bankbalance = ($recbank + $bankdeposit)  - ($paybank + $bankwidrawal);
	$dramount=0;
	$cramount=0;
	if($bankbalance>0){
		$dramount = $bankbalance;
		
		}
		else {
			$cramount = $bankbalance;
			}

	//echo "<tr><td ><textarea name=' b_Parti[]'>$rowbank[bank] : ($recbank $bankdeposit) ($paybank $bankwidrawal)</textarea></td><td><textarea name='b_damoun[]'>".abs($dramount)."</textarea></td><td><textarea name='b_camount[]'>".abs($cramount)."</textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['Particulars']['value'] = "$rowbank[bank] : ($recbank $bankdeposit) ($paybank $bankwidrawal)";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = abs($dramount);
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] = abs($cramount);
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$crtotal+= abs($cramount);
	$drtotal+= abs($dramount);
	}
	}
		//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** SALES & INCOME **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
		
		$outputRow = array();
	$outputRow['Particulars']['value'] = "** SALES & INCOME **";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = '';
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] ='';
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
		
	$salesac = "SELECT DISTINCT(ledger) as salesac FROM `ledgerreg` WHERE  ledtype = 'SALES ACCOUNT' ";
	$result_sales = mysqli_query($con,$salesac);
	$rowsalesac = mysqli_fetch_assoc($result_sales);
	$salesacled = $rowsalesac['salesac'];
	

		
		$sales = "SELECT  sum(`total`) as debit from $billreg WHERE   fny = '$_SESSION[SESS_FNY]'";
	
	$salesresult = mysqli_query($con,$sales);
	$row_sales = mysqli_fetch_assoc($salesresult);
	
	$totalsales = $row_sales['debit'];
	
	
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>$salesacled</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'>$totalsales</textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['Particulars']['value'] = "$salesacled";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = '';
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] =$totalsales;
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$crtotal+= $totalsales;
	
	$incomeled = "SELECT DISTINCT(ledger) as incomeac FROM `ledgerreg` WHERE  ledtype  like '%INCOME' ";
	$result_incomeled = mysqli_query($con,$incomeled);

	if($result_incomeled){
	while($rowincomeled = mysqli_fetch_array($result_incomeled))
	{
		
	$incomeled = $rowincomeled['incomeac'];
	
		$income = "SELECT  sum(`totamount`) as income from vchreg WHERE   vchtype IN  ('RECEIPT', 'JOURNAL') and comcode = '$incomeled' and fny = '$_SESSION[SESS_FNY]'";
	
	$incomeresult = mysqli_query($con,$income);
	$row_income = mysqli_fetch_assoc($incomeresult);
	
	$total = $row_income['income'];
	
	
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>$salesacled</textarea></td><td><textarea name='b_damoun[]'>$total</textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	$outputRow = array();
	$outputRow['Particulars']['value'] = "$salesacled";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = $total;
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] ='';
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$drtotal+= $total;
	}
	}
	
		//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** PURCHASE & EXPENCES **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
		
		$outputRow = array();
	$outputRow['Particulars']['value'] = "** PURCHASE & EXPENCES **";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = '';
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] ='';
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$purchac = "SELECT DISTINCT(ledger) as purchaseac FROM `ledgerreg` WHERE  ledtype = 'PURCHASE ACCOUNT' ";
	$result_purch = mysqli_query($con,$purchac);
	$rowpurch = mysqli_fetch_assoc($result_purch);
	$purchaseled = $rowpurch['purchaseac'];
	
		
		
		$expences = "SELECT  sum(`totamount`) as credit from purcreg WHERE vchtype = 'PURCHASE' and account = '$purchaseled' and fny = '$_SESSION[SESS_FNY]'";
	
	$expencesresult = mysqli_query($con,$expences);
	$row_expences = mysqli_fetch_assoc($expencesresult);
	
	$totalcredit = $row_expences['credit'];

	
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>$purchaseled</textarea></td><td><textarea name='b_damoun[]'>$totalcredit</textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['Particulars']['value'] = "$purchaseled";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = $totalcredit;
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] ='';
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$drtotal+=$totalcredit;
	
	$expenseac = "SELECT DISTINCT(ledger) as expenceac FROM `ledgerreg` WHERE  ledtype  like '%EXPENSE' ";
	$result_expenseled = mysqli_query($con,$expenseac);

	if($result_bank){
	while($rowexpenseled = mysqli_fetch_array($result_expenseled))
	{
		
	$expenseled = $rowexpenseled['expenceac'];
	$totalexpense = 0;
        $totalpurcexpense = 0;
        $totalexp = 0;
		
		$otherexpense = "SELECT  sum(`totamount`) as expense from vchreg WHERE   vchtype in ('PAYMENT','JOURNAL') and comcode = '$expenseled' and fny = '$_SESSION[SESS_FNY]'";
	
	$result_expense = mysqli_query($con,$otherexpense);
	$row_expense = mysqli_fetch_assoc($result_expense);
	
	$totalexpense = $row_expense['expense'];

         $otherexpensejv = "SELECT  sum(`totamount`) as expensejv from vchreg WHERE   vchtype in ('JOURNAL') and account = '$expenseled' and fny = '$_SESSION[SESS_FNY]'";
	
	$result_expensejv = mysqli_query($con,$otherexpensejv);
	$row_expensejv = mysqli_fetch_assoc($result_expensejv);
	
	$totalexpensejv = $row_expensejv['expensejv'];

        $purcexpense = "SELECT  sum(`totamount`) as purcexpense from purcreg WHERE  account = '$expenseled' and fny = '$_SESSION[SESS_FNY]'";
	
	$result_purcexpense = mysqli_query($con,$purcexpense);
	$row_purcexpense = mysqli_fetch_assoc($result_purcexpense);
	
	$totalpurcexpense = $row_purcexpense['purcexpense'];
	
	$totalexp = $totalexpense  + $totalpurcexpense + $totalexpensejv;
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>$expenseled ($totalexpense) ($totalpurcexpense) ($totalexpensejv)</textarea></td><td><textarea name='b_damoun[]'>$totalexp</textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['Particulars']['value'] = "$expenseled ($totalexpense) ($totalpurcexpense) ($totalexpensejv)";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = $totalexp;
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] ='';
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	
	$drtotal+=$totalexp;
	

	
	}
	}
	
		//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** DEBTORS **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
		
		$outputRow = array();
	$outputRow['Particulars']['value'] = "** DEBTORS **";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = '';
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] ='';
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
		

       $debtorrec = "SELECT  sum(`totamount`) as recpt from vchreg WHERE   vchtype in ('RECEIPT') and fny = '$_SESSION[SESS_FNY]' and comcode IN (SELECT alias from ledgerreg where ledtype =  'SUNDRY DEBTORS') ";
	
	$result_debtrec = mysqli_query($con,$debtorrec);
	$row_debtrec = mysqli_fetch_assoc($result_debtrec);
	
	$totdebtrec = $row_debtrec['recpt'];
        $totaldebtors = $totalsales - $totdebtrec;
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>SUNDRY DEBTORS A/C SUMMARY ($totalsales) ($totdebtrec)</textarea></td><td><textarea name='b_damoun[]'>$totaldebtors </textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['Particulars']['value'] = "SUNDRY DEBTORS A/C SUMMARY ($totalsales) ($totdebtrec)";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = $totaldebtors;
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] ='';
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$drtotal+=$totaldebtors;
	
	
	//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** CREDITORS **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['Particulars']['value'] = "** CREDITORS **";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = '';
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] ='';
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$purchases = "SELECT  sum(`totamount`) as purchase from purcreg WHERE vchtype = 'PURCHASE' and comcode IN (SELECT alias from ledgerreg where ledtype =  'SUNDRY CREDITORS')  and fny = '$_SESSION[SESS_FNY]'";
	
	$purchasesresult = mysqli_query($con,$purchases);
	$row_purchases = mysqli_fetch_assoc($purchasesresult);
	
	$totalpurchase = $row_purchases['purchase'];

        $purchasejv = "SELECT  sum(`totamount`) as purchasejv from vchreg WHERE   vchtype = 'JOURNAL' and account IN (SELECT alias from ledgerreg where ledtype =  'SUNDRY CREDITORS')  and fny = '$_SESSION[SESS_FNY]'";
	
		$purchasejvresult = mysqli_query($con,$purchasejv);
		$row_purchasejv = mysqli_fetch_assoc($purchasejvresult);
		$totalpurchasejv = $row_purchasejv['purchasejv'];

         
$debtorpay = "SELECT  sum(`totamount`) as paymt from vchreg WHERE   vchtype in ('PAYMENT') and fny = '$_SESSION[SESS_FNY]' and comcode IN (SELECT alias from ledgerreg where ledtype =  'SUNDRY CREDITORS') ";
	
	$result_debtpay = mysqli_query($con,$debtorpay);
	$row_debtpay = mysqli_fetch_assoc($result_debtpay);
	
	$totdebtpay = $row_debtpay['paymt'];
	
	
	
	$debtorrecd = "SELECT  sum(`totamount`) as paid from vchreg WHERE   vchtype in ('RECEIPT') and fny = '$_SESSION[SESS_FNY]' and comcode IN (SELECT alias from ledgerreg where ledtype =  'SUNDRY CREDITORS') ";
	
	$result_debtrecd = mysqli_query($con,$debtorrecd);
	$row_debtrecd = mysqli_fetch_assoc($result_debtrecd);
	
	$totdebtrecd = $row_debtrecd['paid'];
	
	
	
	
	

        $totalcreditors = ($totalpurchase + $totalpurchasejv)  - ($totdebtpay - $totdebtrecd) ;
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>SUNDRY CREDITORS A/C SUMMARY($totalpurchase)($totalpurchasejv)($totdebtpay) ($totdebtrecd)</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'>$totalcreditors</textarea></td></tr>";
	
		
	$outputRow = array();
	$outputRow['Particulars']['value'] = "SUNDRY CREDITORS A/C SUMMARY($totalpurchase)($totalpurchasejv)($totdebtpay) ($totdebtrecd)";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = '';
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] =$totalcreditors;
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$crtotal+=$totalcreditors;
	
	
	//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** CAPITAL ACCOUNTS **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['Particulars']['value'] = "** CAPITAL ACCOUNTS **";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = '';
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] ='';
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$capitalled = "SELECT DISTINCT(ledger) as capital FROM `ledgerreg` WHERE  ledtype  LIKE 'CAPITAL%' ";
	$result_capitalled = mysqli_query($con,$capitalled);

	if($result_capitalled){
	while($rowcapitalled = mysqli_fetch_array($result_capitalled))
	{
		
		$capitalled = $rowcapitalled['capital'];
		$capital = "SELECT  sum(`totamount`) as caprecd from vchreg WHERE   vchtype IN ('RECEIPT', 'JOURNAL') and comcode = '$capitalled' and fny = '$_SESSION[SESS_FNY]'";
	
		$capitalresult = mysqli_query($con,$capital);
		$row_capital = mysqli_fetch_assoc($capitalresult);
		$totalcapital = $row_capital['caprecd'];

                $capitalpay = "SELECT  sum(`totamount`) as cappay from vchreg WHERE   vchtype = 'PAYMENT' and comcode = '$capitalled' and fny = '$_SESSION[SESS_FNY]'";
	
		$capitalpayresult = mysqli_query($con,$capitalpay);
		$row_capitalpay = mysqli_fetch_assoc($capitalpayresult);
		$totalcapitalpay = $row_capitalpay['cappay'];

                $capitaljvpay = "SELECT  sum(`totamount`) as capjvpay from vchreg WHERE   vchtype = 'JOURNAL' and account= '$capitalled' and fny = '$_SESSION[SESS_FNY]'";
	
		$capitaljvpayresult = mysqli_query($con,$capitaljvpay);
		$row_capitaljvpay = mysqli_fetch_assoc($capitaljvpayresult);
		$totalcapitaljvpay = $row_capitaljvpay['capjvpay'];

               
                $capitalbal = ($totalcapital +$totalcapitaljvpay) - ($totalcapitalpay);

                 $dramount=0;
	        $cramount=0;
	        if($capitalbal>0){
		$cramount = $capitalbal;
		
		}
		else {
			$dramount = $capitalbal;
			}
	
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>$capitalled ($totalcapital) ($totalcapitalpay)($totalcapitaljvpay)</textarea></td><td><textarea name='b_damoun[]'>".abs($dramount)."</textarea></td><td><textarea name='b_camount[]'>".abs($cramount)."</textarea></td></tr>";
	$outputRow = array();
	$outputRow['Particulars']['value'] = "$capitalled ($totalcapital) ($totalcapitalpay)($totalcapitaljvpay)";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = abs($dramount);
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] =abs($cramount);
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	
	$crtotal+=abs($cramount);
	$drtotal+=abs($dramount);
	
	}
	}
	
	//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** FIXED ASSETS ACCOUNT **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['Particulars']['value'] = "** FIXED ASSETS ACCOUNT **";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = '';
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] ='';
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$fixedled = "SELECT DISTINCT(ledger) as fixedled FROM `ledgerreg` WHERE  ledtype  LIKE 'FIXED%' ";
	$result_fixedled = mysqli_query($con,$fixedled);

	if($result_fixedled){
	while($rowfixedled = mysqli_fetch_array($result_fixedled))
	{
		
		$fixedled = $rowfixedled['fixedled'];
		$fixed = "SELECT  sum(`totamount`) as fixed from vchreg WHERE   vchtype IN ('PURCHASE', 'JOURNAL')  and account = '$fixedled' and fny = '$_SESSION[SESS_FNY]'";
	
		$fixedresult = mysqli_query($con,$fixed);
		$row_fixed = mysqli_fetch_assoc($fixedresult);
		$totalfixed = $row_fixed['fixed'];

               $fixedpayqry = "SELECT  sum(`totamount`) as fixedpay from vchreg WHERE   vchtype IN ('JOURNAL')  and comcode = '$fixedled' and fny = '$_SESSION[SESS_FNY]'";
	
		$fixedpayresult = mysqli_query($con,$fixedpayqry);
		$row_fixedpay = mysqli_fetch_assoc($fixedpayresult);
		$totalfixedpay = $row_fixedpay['fixedpay'];
                
                $fixedbalance = $totalfixed + $totalfixedpay;
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>$fixedled ($totalfixed) ($totalfixedpay)</textarea></td><td><textarea name='b_damoun[]'>$fixedbalance</textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
		
	$outputRow = array();
	$outputRow['Particulars']['value'] = "$fixedled ($totalfixed) ($totalfixedpay)";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = $fixedbalance;
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] ='';
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$drtotal+=$fixedbalance;
	}
	}
	
	//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** INVESTMENT ACCOUNTS **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['Particulars']['value'] = "** INVESTMENT ACCOUNTS **";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = '';
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] ='';
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$Investmentled = "SELECT DISTINCT(ledger) as Investmentled FROM `ledgerreg` WHERE  ledtype  LIKE 'INVESTMENT%' ";
	$result_Investmentled = mysqli_query($con,$Investmentled);

	if($result_Investmentled){
	while($rowInvestmentled = mysqli_fetch_array($result_Investmentled))
	{
		
		$Investmentled = $rowInvestmentled['Investmentled'];
		$Investment = "SELECT  sum(`totamount`) as Investment from vchreg WHERE   vchtype in ( 'RECEIPT' , 'PAYMENT') and comcode = '$Investmentled' and fny = '$_SESSION[SESS_FNY]'";
	
		$Investmentresult = mysqli_query($con,$Investment);
		$row_Investment = mysqli_fetch_assoc($Investmentresult);
		$totalInvestment = $row_Investment['Investment'];
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>$Investmentled</textarea></td><td><textarea name='b_damoun[]'>$totalInvestment</textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['Particulars']['value'] = "$Investmentled";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = $totalInvestment;
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] ='';
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$drtotal+=$totalInvestment;
	}
	}
	
	//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** LOAN/ADVANCES ACCOUNTS **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['Particulars']['value'] = "** LOAN/ADVANCES ACCOUNTS **";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = '';
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] ='';
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	
	$loanled = "SELECT DISTINCT(ledger) as loanled FROM `ledgerreg` WHERE  ledtype  LIKE 'LOAN%' ";
	$result_loanled = mysqli_query($con,$loanled);

	if($result_loanled){
	while($rowloanled = mysqli_fetch_array($result_loanled))
	{
		
			$loanled = $rowloanled['loanled'];
		$loan = "SELECT  sum(`totamount`) as loan from vchreg WHERE   vchtype = 'RECEIPT' and comcode = '$loanled' and fny = '$_SESSION[SESS_FNY]'";
	
		$loanresult = mysqli_query($con,$loan);
		$row_loan = mysqli_fetch_assoc($loanresult);
		$totalloan = $row_loan['loan'];

                $jvloan = "SELECT  sum(`totamount`) as jvloan from vchreg WHERE   vchtype = 'JOURNAL' and comcode = '$loanled' and fny = '$_SESSION[SESS_FNY]'";
	
		$jvloanresult = mysqli_query($con,$jvloan);
		$row_jvloan = mysqli_fetch_assoc($jvloanresult);
		$totaljvloan = $row_jvloan['jvloan'];

               $loanaccjv = "SELECT  sum(`totamount`) as loanaccjv from vchreg WHERE   vchtype in ('JOURNAL') and account = '$loanled' and fny = '$_SESSION[SESS_FNY]'";
	
	$result_loanaccjv = mysqli_query($con,$loanaccjv);
	$row_loanaccjv = mysqli_fetch_assoc($result_loanaccjv);
	
	$totalloanaccjv = $row_loanaccjv['loanaccjv'];
		
		$loanpaid = "SELECT  sum(`totamount`) as loanpaid from vchreg WHERE   vchtype = 'PAYMENT' and comcode = '$loanled' and fny = '$_SESSION[SESS_FNY]'";
	
		$loanpaidresult = mysqli_query($con,$loanpaid);
		$row_loanpaid = mysqli_fetch_assoc($loanpaidresult);
		$totalloanpaid = $row_loanpaid['loanpaid'];
		
		$balanceloan = ($totalloan + $totaljvloan) -($totalloanpaid+$totalloanaccjv) ;
		
		$dramount=0;
	$cramount=0;
	if($balanceloan>0){
		$cramount = $balanceloan;
		
		}
		else {
			$dramount = $balanceloan;
			}
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>$loanled ($totalloan) ($totaljvloan) ($totalloanaccjv) ($totalloanpaid)</textarea></td><td><textarea name='b_damoun[]'>".abs($dramount)."</textarea></td><td><textarea name='b_camount[]'>".abs($cramount)."</textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['Particulars']['value'] = "$loanled ($totalloan) ($totaljvloan) ($totalloanaccjv) ($totalloanpaid)";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = abs($dramount);
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] =abs($cramount);
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	$crtotal+=abs($cramount);
	$drtotal+=abs($dramount);
	}
	}
	//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>TOTAL</textarea></td><td><textarea name='b_damoun[]'>$drtotal</textarea></td><td><textarea name='b_camount[]'>$crtotal</textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['Particulars']['value'] = "TOTAL";
	addCustomName($outputRow,'Particulars','b_Parti[]');
	$outputRow['Dr. Amount']['value'] = $drtotal;
	addCustomName($outputRow,'Dr. Amount','b_damoun[]');
	$outputRow['Cr. Amount']['value'] =$crtotal;
	addCustomName($outputRow,'Cr. Amount','b_camount[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;

$count_totalbill = $drtotal - $crtotal;

//echo "</tbody></table>###Net Tally = $count_totalbill";
addTotalRows($output,$rowCount);

echo json_encode($output);


	
	
	//echo mysqli_error($con);
	
}



///// balance sheet start

if($_POST['report_type']=="balancesheet"){
	
	$i=0;
	$j = 0;
	$liab_acc = array();
	$liab_bal = array();
	$liab_tot = array();
	$asset_acc = array();
	$asset_bal = array();
	$asset_tot = array();
	
	#start of Liabilities
	
	
	/*
	*Start od Capital Account
	*/
	//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** CAPITAL ACCOUNTS **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	$sum_liab =0;
	array_push($liab_acc,'CAPITAL ACCOUNTS :');
	array_push($liab_bal,'');
	$i++;
	//$j++;
	$capitalled = "SELECT DISTINCT(ledger) as capital FROM `ledgerreg` WHERE  ledtype  LIKE 'CAPITAL%' ";
	$result_capitalled = mysqli_query($con,$capitalled);

	if($result_capitalled){
	while($rowcapitalled = mysqli_fetch_array($result_capitalled))
	{
		
		$capitalled = $rowcapitalled['capital'];
		$capital = "SELECT  sum(`totamount`) as caprecd from vchreg WHERE   vchtype IN ('RECEIPT', 'JOURNAL') and comcode = '$capitalled' and fny = '$_SESSION[SESS_FNY]'";
	
		$capitalresult = mysqli_query($con,$capital);
		$row_capital = mysqli_fetch_assoc($capitalresult);
		$totalcapital = $row_capital['caprecd'];

                $capitalpay = "SELECT  sum(`totamount`) as cappay from vchreg WHERE   vchtype = 'PAYMENT' and comcode = '$capitalled' and fny = '$_SESSION[SESS_FNY]'";
	
		$capitalpayresult = mysqli_query($con,$capitalpay);
		$row_capitalpay = mysqli_fetch_assoc($capitalpayresult);
		$totalcapitalpay = $row_capitalpay['cappay'];
		
		 $capitaljvpay = "SELECT  sum(`totamount`) as capjvpay from vchreg WHERE   vchtype = 'JOURNAL' and account= '$capitalled' and fny = '$_SESSION[SESS_FNY]'";
	
		$capitaljvpayresult = mysqli_query($con,$capitaljvpay);
		$row_capitaljvpay = mysqli_fetch_assoc($capitaljvpayresult);
		$totalcapitaljvpay = $row_capitaljvpay['capjvpay'];

                $capitalbal = $totalcapital+ $totalcapitaljvpay - $totalcapitalpay;

               /*  $dramount=0;
	        $cramount=0;
			
	        if($capitalbal>0){
		$cramount = $capitalbal;
		
		}
		else {
			$dramount = $capitalbal;
			}*/
			
		$balsheet[0][0][$capitalled]=$capitalbal;
		//echo "i ->".$i."|";
		$liab_acc[$i] = $capitalled;
		$liab_bal[$i] = $capitalbal;
		$sum_liab += $capitalbal;
		$i++;
		//echo "i ->".$i."|";
	//echo "<tr><td ><textarea name=' b_Parti[]'>$capitalled ($totalcapital) ($totalcapitalpay)</textarea></td><td><textarea name='b_damoun[]'>".abs($dramount)."</textarea></td><td><textarea name='b_camount[]'>".abs($cramount)."</textarea></td></tr>";
	
	
	
	}
	}
	$liab_tot[--$i]= $sum_liab;
	$i++;
	/*
	*End of Capital Account
	*/
	
	/*
	*Start of Loan Account
	*/
	
	//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** LOAN/ADVANCES ACCOUNTS **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	$sum_liab =0;
	array_push($liab_acc,'LOANS & ADVANCES :');
	$i++;
	//$j++;
	
	$loanled = "SELECT DISTINCT(ledger) as loanled FROM `ledgerreg` WHERE  ledtype  LIKE 'LOAN%' ";
	$result_loanled = mysqli_query($con,$loanled);

	if($result_loanled){
	while($rowloanled = mysqli_fetch_array($result_loanled))
	{
		
			$loanled = $rowloanled['loanled'];
		$loan = "SELECT  sum(`totamount`) as loan from vchreg WHERE   vchtype = 'RECEIPT' and comcode = '$loanled' and fny = '$_SESSION[SESS_FNY]'";
	
		$loanresult = mysqli_query($con,$loan);
		$row_loan = mysqli_fetch_assoc($loanresult);
		$totalloan = $row_loan['loan'];

                $jvloan = "SELECT  sum(`totamount`) as jvloan from vchreg WHERE   vchtype = 'JOURNAL' and comcode = '$loanled' and fny = '$_SESSION[SESS_FNY]'";
	
		$jvloanresult = mysqli_query($con,$jvloan);
		$row_jvloan = mysqli_fetch_assoc($jvloanresult);
		$totaljvloan = $row_jvloan['jvloan'];
		
		$loanpaid = "SELECT  sum(`totamount`) as loanpaid from vchreg WHERE   vchtype = 'PAYMENT' and comcode = '$loanled' and fny = '$_SESSION[SESS_FNY]'";
	
		$loanpaidresult = mysqli_query($con,$loanpaid);
		$row_loanpaid = mysqli_fetch_assoc($loanpaidresult);
		$totalloanpaid = $row_loanpaid['loanpaid'];
		
		$balanceloan = ($totalloan + $totaljvloan) -$totalloanpaid ;
		
		$dramount=0;
	$cramount=0;
	if($balanceloan>0){
		$cramount = $balanceloan;
		
		}
		else {
			$dramount = $balanceloan;
			}
	
	
	$balsheet[0][1][$loanled]=abs($cramount);
	$liab_acc[$i] = $loanled;
		$liab_bal[$i] = abs($cramount);
		$sum_liab += abs($cramount);
		$i++;
	//echo "<tr><td ><textarea name=' b_Parti[]'>$loanled ($totalloan $totaljvloan) ($totalloanpaid)</textarea></td><td><textarea name='b_damoun[]'>".abs($dramount)."</textarea></td><td><textarea name='b_camount[]'>".abs($cramount)."</textarea></td></tr>";
	}
	}
	$liab_tot[--$i]= $sum_liab;
	$i++;

	
	
	/*
	*End of Loan Account
	*/
	
	/*
	*Start of SUNDRY DEBTORS
	*/
	
	$sales = "SELECT  sum(`total`) as debit from $billreg WHERE   fny = '$_SESSION[SESS_FNY]'";
	
	$salesresult = mysqli_query($con,$sales);
	$row_sales = mysqli_fetch_assoc($salesresult);
	
	$totalsales = $row_sales['debit'];
	
	//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** DEBTORS **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";

       $debtorrec = "SELECT  sum(`totamount`) as recpt from vchreg WHERE   vchtype in ('RECEIPT') and fny = '$_SESSION[SESS_FNY]' and comcode IN (SELECT alias from ledgerreg where ledtype =  'SUNDRY DEBTORS') ";
	
	$result_debtrec = mysqli_query($con,$debtorrec);
	$row_debtrec = mysqli_fetch_assoc($result_debtrec);
	
	$totdebtrec = $row_debtrec['recpt'];
        $totaldebtors = $totalsales - $totdebtrec;
		
	if($totaldebtors<0)	
	{
		$sum_liab =0;
	array_push($liab_acc,'SUNDRY DEBTORS :');
	$i++;
		$liab_acc[$i] = "SUNDRY DEBTORS A/C SUMMARY";
		$liab_tot[$i] = abs($totaldebtors);
		$sum_liab += abs($totaldebtors);
		$i++;	
	}
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>SUNDRY DEBTORS A/C SUMMARY</textarea></td><td><textarea name='b_damoun[]'>$totaldebtors </textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	/*
	*End of SUNDRY DEBTORS
	*/
	
	/*
	*Start of SUNDRY CREDITORS
	*/

	
	$expences = "SELECT  sum(`totamount`) as credit from purcreg WHERE vchtype = 'PURCHASE'  and fny = '$_SESSION[SESS_FNY]' and comcode in (select alias from ledgerreg where ledtype = 'SUNDRY CREDITORS')";
	
	$expencesresult = mysqli_query($con,$expences);
	$row_expences = mysqli_fetch_assoc($expencesresult);
	
	$totalcredit = $row_expences['credit'] ;
	
	
	 $purchasejv = "SELECT  sum(`totamount`) as purchasejv from vchreg WHERE   vchtype = 'JOURNAL' and account IN (SELECT alias from ledgerreg where ledtype =  'SUNDRY CREDITORS')  and fny = '$_SESSION[SESS_FNY]'";
	
		$purchasejvresult = mysqli_query($con,$purchasejv);
		$row_purchasejv = mysqli_fetch_assoc($purchasejvresult);
		$totalpurchasejv = $row_purchasejv['purchasejv'];
	
	$debtorpay = "SELECT  sum(`totamount`) as recpt from vchreg WHERE   vchtype in ('PAYMENT') and fny = '$_SESSION[SESS_FNY]' and comcode IN (SELECT alias from ledgerreg where ledtype =  'SUNDRY CREDITORS') ";
	
	$result_debtpay = mysqli_query($con,$debtorpay);
	$row_debtpay = mysqli_fetch_assoc($result_debtpay);
	
	$totdebtpay = $row_debtpay['recpt'];
	
	
	$debtorrecd = "SELECT  sum(`totamount`) as paid from vchreg WHERE   vchtype in ('RECEIPT') and fny = '$_SESSION[SESS_FNY]' and comcode IN (SELECT alias from ledgerreg where ledtype =  'SUNDRY CREDITORS') ";
	
	$result_debtrecd = mysqli_query($con,$debtorrecd);
	$row_debtrecd = mysqli_fetch_assoc($result_debtrecd);
	
	$totdebtrecd = $row_debtrecd['paid'];
	
        $totalcreditors = ($totalpurchasejv + $totalcredit) - ( $totdebtpay-$totdebtrecd );
		
		if($totalcreditors>0)	
	{
		$sum_liab =0;
	array_push($liab_acc,'SUNDRY CREDITORS :');
	$i++;
	
		$liab_acc[$i] = "SUNDRY CREDITORS A/C SUMMARY($totalcredit) ($totdebtpay)";
		$liab_tot[$i] = ($totalcreditors);
		$sum_liab += abs($totalcreditors);
		$i++;	
	}
	
	
	/*
	*End of SUNDRY CREDITORS
	*/
	
	
	/*
	*Start of Bank Account
	*/
		
	
	$bank = "SELECT DISTINCT(ledger) as bank FROM `ledgerreg` WHERE ledger != 'CASH' and ledtype = 'CASHBANK' ";
	$result_bank = mysqli_query($con,$bank);
	
	if($result_bank){
		//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** BANK BALANCE **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	while($rowbank = mysqli_fetch_array($result_bank))
	{
		$bankled = $rowbank['bank'];
		$recdbanksql = "SELECT  sum(`totamount`) as recd FROM `vchreg` WHERE  vchtype IN ('RECEIPT','JOURNAL') and fny = '$_SESSION[SESS_FNY]' and account = '$bankled'";
	$bankrec = mysqli_query($con,$recdbanksql);
	$rowrecbank = mysqli_fetch_assoc($bankrec);
	$recbank = $rowrecbank['recd']; 
	
	$depositsql = "SELECT sum(totamount) as deposit FROM `vchreg` where vchtype = 'CONTRA' and account = '$bankled' and fny = '$_SESSION[SESS_FNY]'";
	$result_depos = mysqli_query($con,$depositsql);
	$rowdepos = mysqli_fetch_assoc($result_depos);
	$bankdeposit = $rowdepos['deposit']; 
	
	
	$paidbanksql = "SELECT  sum(`totamount`) as paid FROM `vchreg` WHERE vchtype = 'PAYMENT' and fny = '$_SESSION[SESS_FNY]' and account = '$bankled'";
	$bankpay = mysqli_query($con,$paidbanksql);
	$rowpaybank = mysqli_fetch_assoc($bankpay);
	$paybank = $rowpaybank['paid']; 
	
	$widrawalsql = "SELECT sum(totamount) as widra FROM `vchreg` where vchtype = 'CONTRA' and comcode = '$bankled' and fny = '$_SESSION[SESS_FNY]'";
	$result_widra = mysqli_query($con,$widrawalsql);
	$rowwidra = mysqli_fetch_assoc($result_widra);
	$bankwidrawal = $rowwidra['widra'];
	
	$bankbalance = ($recbank + $bankdeposit)  - ($paybank + $bankwidrawal);
	$dramount=0;
	$cramount=0;
	if($bankbalance>0){
		$dramount = $bankbalance;
		
		}
		else {
			$cramount = $bankbalance;
			}
	
	
	$balsheet[1][3][$rowbank[bank]]=$bankbalance;
	if($bankbalance<0)
	{
	$liab_acc[$i] = $rowbank[bank];
		$liab_tot[$i] =$bankbalance;
		$i++;
	}
	//echo "<tr><td ><textarea name=' b_Parti[]'>$rowbank[bank] : ($recbank $bankdeposit) ($paybank $bankwidrawal)</textarea></td><td><textarea name='b_damoun[]'>".abs($dramount)."</textarea></td><td><textarea name='b_camount[]'>".abs($cramount)."</textarea></td></tr>";
	
	}
	}
	
	/*
	*End of Bank Account
	*/
	
	
	#End of Liabilities
	
	
	
	
	#start of Assets
	
	
	/*
	*Start of Fixed Assets
	*/
	//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** FIXED ASSETS ACCOUNT **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	$sum_asset =0;
	array_push($asset_acc,'FIXED ASSETS :');
	$i++;
	$j++;
	
	$fixedled = "SELECT DISTINCT(ledger) as fixedled FROM `ledgerreg` WHERE  ledtype  LIKE 'FIXED%' ";
	$result_fixedled = mysqli_query($con,$fixedled);

	if($result_fixedled){
	while($rowfixedled = mysqli_fetch_array($result_fixedled))
	{
		
		$fixedled = $rowfixedled['fixedled'];
		$fixed = "SELECT  sum(`totamount`) as fixed from vchreg WHERE   vchtype in ('PURCHASE','JOURNAL') and comcode = '$fixedled' and fny = '$_SESSION[SESS_FNY]'";
	
		$fixedresult = mysqli_query($con,$fixed);
		$row_fixed = mysqli_fetch_assoc($fixedresult);
		$totalfixed = $row_fixed['fixed'];
	
		$balsheet[1][0][$fixedled]=$totalfixed;
		$asset_acc[$j] = $fixedled;
		$asset_bal[$j] = $totalfixed;
		$sum_asset += $totalfixed;
		$j++;
	//echo "<tr><td ><textarea name=' b_Parti[]'>$fixedled</textarea></td><td><textarea name='b_damoun[]'>$totalfixed</textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	}
	}
	$asset_tot[--$j]= $sum_asset;
	$j++;
	
	/*
	*eND of Fixed Assets
	*/
	
	/*
	*Start of INVESTMENT ACCOUNTS
	*/
	
		//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** INVESTMENT ACCOUNTS **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
		$sum_asset =0;
	array_push($asset_acc,'DEPOSITS / INVESTMENTS :');
	$i++;
	$j++;
	
	$Investmentled = "SELECT DISTINCT(ledger) as Investmentled FROM `ledgerreg` WHERE  ledtype  LIKE 'INVESTMENT%' ";
	$result_Investmentled = mysqli_query($con,$Investmentled);

	if($result_Investmentled){
	while($rowInvestmentled = mysqli_fetch_array($result_Investmentled))
	{
		
		$Investmentled = $rowInvestmentled['Investmentled'];
		$Investment = "SELECT  sum(`totamount`) as Investment from vchreg WHERE   vchtype in ( 'RECEIPT' , 'PAYMENT') and comcode = '$Investmentled' and fny = '$_SESSION[SESS_FNY]'";
	
		$Investmentresult = mysqli_query($con,$Investment);
		$row_Investment = mysqli_fetch_assoc($Investmentresult);
		$totalInvestment = $row_Investment['Investment'];
		
		$balsheet[1][1][$Investmentled]=$totalInvestment;
		$asset_acc[$j] = $Investmentled;
		$asset_bal[$j] = $totalInvestment;
		$sum_asset += $totalInvestment;
		$j++;
	//echo "<tr><td ><textarea name=' b_Parti[]'>$Investmentled</textarea></td><td><textarea name='b_damoun[]'>$totalInvestment</textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	}
	}
	$asset_tot[--$j]= $sum_asset;
	$j++;
	/*
	*eND of INVESTMENT ACCOUNTS
	*/
	
		/*
	*Start of Loan Account
	*/
	
	//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** LOAN/ADVANCES ACCOUNTS **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	$sum_asset =0;
	array_push($asset_acc,'LOANS & ADVANCES :');
	$i++;
	$j++;
	$loanled = "SELECT DISTINCT(ledger) as loanled FROM `ledgerreg` WHERE  ledtype  LIKE 'LOAN%' ";
	$result_loanled = mysqli_query($con,$loanled);

	if($result_loanled){
	while($rowloanled = mysqli_fetch_array($result_loanled))
	{
		
			$loanled = $rowloanled['loanled'];
		$loan = "SELECT  sum(`totamount`) as loan from vchreg WHERE   vchtype = 'RECEIPT' and comcode = '$loanled' and fny = '$_SESSION[SESS_FNY]'";
	
		$loanresult = mysqli_query($con,$loan);
		$row_loan = mysqli_fetch_assoc($loanresult);
		$totalloan = $row_loan['loan'];

                $jvloan = "SELECT  sum(`totamount`) as jvloan from vchreg WHERE   vchtype = 'JOURNAL' and comcode = '$loanled' and fny = '$_SESSION[SESS_FNY]'";
	
		$jvloanresult = mysqli_query($con,$jvloan);
		$row_jvloan = mysqli_fetch_assoc($jvloanresult);
		$totaljvloan = $row_jvloan['jvloan'];
		
		$loanpaid = "SELECT  sum(`totamount`) as loanpaid from vchreg WHERE   vchtype = 'PAYMENT' and comcode = '$loanled' and fny = '$_SESSION[SESS_FNY]'";
	
		$loanpaidresult = mysqli_query($con,$loanpaid);
		$row_loanpaid = mysqli_fetch_assoc($loanpaidresult);
		$totalloanpaid = $row_loanpaid['loanpaid'];
		
		$balanceloan = ($totalloan + $totaljvloan) -$totalloanpaid ;
		
		$dramount=0;
	$cramount=0;
	  if($balanceloan>0){
		$cramount = $balanceloan;
		
		}
		else {
			$dramount = $balanceloan;
			}
	
	
	$balsheet[1][2][$loanled]=abs($dramount);
	$asset_acc[$j] = $loanled;
		$asset_bal[$j] =abs($dramount);
		$sum_asset += abs($dramount);
		$j++;
	//echo "<tr><td ><textarea name=' b_Parti[]'>$loanled ($totalloan $totaljvloan) ($totalloanpaid)</textarea></td><td><textarea name='b_damoun[]'>".abs($dramount)."</textarea></td><td><textarea name='b_camount[]'>".abs($cramount)."</textarea></td></tr>";
	}
	}

	$asset_tot[--$j]= $sum_asset;
	$j++;
	
	/*
	*End of Loan Account
	*/
	
	
	
		
	/*
	*Start of SUNDRY DEBTORS
	*/
	
	$sales = "SELECT  sum(`total`) as debit from $billreg WHERE   fny = '$_SESSION[SESS_FNY]'";
	
	$salesresult = mysqli_query($con,$sales);
	$row_sales = mysqli_fetch_assoc($salesresult);
	
	$totalsales = $row_sales['debit'];
	
	//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** DEBTORS **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";

       $debtorrec = "SELECT  sum(`totamount`) as recpt from vchreg WHERE   vchtype in ('RECEIPT') and fny = '$_SESSION[SESS_FNY]' and comcode IN (SELECT alias from ledgerreg where ledtype =  'SUNDRY DEBTORS') ";
	
	$result_debtrec = mysqli_query($con,$debtorrec);
	$row_debtrec = mysqli_fetch_assoc($result_debtrec);
	
	$totdebtrec = $row_debtrec['recpt'];
        $totaldebtors = $totalsales - $totdebtrec;
		
	if($totaldebtors>0)	
	{
		$sum_asset =0;
	array_push($asset_acc,'SUNDRY DEBTORS :');
	$j++;
		$asset_acc[$j] = "SUNDRY DEBTORS A/C SUMMARY";
		$asset_tot[$j] = abs($totaldebtors);
		$sum_asset += abs($totaldebtors);
		$j++;	
	}
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>SUNDRY DEBTORS A/C SUMMARY</textarea></td><td><textarea name='b_damoun[]'>$totaldebtors </textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	/*
	*End of SUNDRY DEBTORS
	*/
	
	/*
	*Start of SUNDRY CREDITORS
	*/

	
	$expences = "SELECT  sum(`totamount`) as credit from purcreg WHERE vchtype = 'PURCHASE'  and fny = '$_SESSION[SESS_FNY]' and comcode in (select alias from ledgerreg where ledtype = 'SUNDRY CREDITORS')";
	
	$expencesresult = mysqli_query($con,$expences);
	$row_expences = mysqli_fetch_assoc($expencesresult);
	
	$totalcredit = $row_expences['credit'] ;
	
	$debtorpay = "SELECT  sum(`totamount`) as recpt from vchreg WHERE   vchtype in ('PAYMENT') and fny = '$_SESSION[SESS_FNY]' and comcode IN (SELECT alias from ledgerreg where ledtype =  'SUNDRY CREDITORS') ";
	
	$result_debtpay = mysqli_query($con,$debtorpay);
	$row_debtpay = mysqli_fetch_assoc($result_debtpay);
	
	$totdebtpay = $row_debtpay['recpt'];
        $totalcreditors = $totalcredit - $totdebtpay ;
		
		if($totalcreditors<0)	
	{
		$sum_asset =0;
	array_push($asset_acc,'SUNDRY CREDITORS :');
	$j++;
	
		$asset_acc[$j] = "SUNDRY CREDITORS A/C SUMMARY($totalcredit) ($totdebtpay)";
		$asset_tot[$j] = ($totalcreditors);
		$sum_asset += abs($totalcreditors);
		$j++;	
	}
	
	
	/*
	*End of SUNDRY CREDITORS
	*/
	
	
	
	/*
	*Start of Cash Account
	*/
	//echo "<table  id='table_report_view'  cellspacing='0' width='100%''><thead><tr><th colspan='3' ><textarea name='b_Parti[]'>L I A B I L I T I E S</textarea></th><th><textarea name='b_camount[]'>A S S E T S</textarea></th> </tr></thead> ";
	
	
	$account = "CASH A/C";
        $i=0;
	$count_totalbill=0;
        $balance = 0;
	
   // echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** CASH BALANCE **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	$recdsql = "SELECT sum(`totamount`) as recd FROM `vchreg` WHERE account = 'CASH' and vchtype IN ('RECEIPT','JOURNAL') and fny = '$_SESSION[SESS_FNY]' GROUP by account ";
	$result_rec = mysqli_query($con,$recdsql);
	$rowrec = mysqli_fetch_assoc($result_rec);
	$recived = $rowrec['recd']; 
	
	
	$widrawalsql = "SELECT sum(totamount) as widra FROM `vchreg` where vchtype = 'CONTRA' and account = 'CASH' and fny = '$_SESSION[SESS_FNY]'";
	$result_widra = mysqli_query($con,$widrawalsql);
	$rowwidra = mysqli_fetch_assoc($result_widra);
	$widrawal = $rowwidra['widra']; 
	
	
	$paidsql ="SELECT account,  sum(`totamount`) as paid FROM `vchreg` WHERE account = 'CASH' and vchtype = 'PAYMENT' and fny = '$_SESSION[SESS_FNY]' group by account";
	$result_pai = mysqli_query($con,$paidsql);
	$rowpai = mysqli_fetch_assoc($result_pai);
	$paid = $rowpai['paid']; 
	
	$depositsql = "SELECT sum(totamount) as deposit FROM `vchreg` where vchtype = 'CONTRA' and comcode = 'CASH' and fny = '$_SESSION[SESS_FNY]'";
	$result_depos = mysqli_query($con,$depositsql);
	$rowdepos = mysqli_fetch_assoc($result_depos);
	$deposit = $rowdepos['deposit']; 
	
	
	$balance = ($recived + $widrawal) - ($paid + $deposit);
	$dramount=0;
	$cramount=0;
	if($balance>0){
		$dramount = $balance;
		
		}
		else {
			$cramount = $balance;
			}
	
	
	$balsheet[1][2][$account]=$balance;
	$asset_acc[$j] = $account;
		$asset_tot[$j] =$balance;
	$j++;
	//echo "<tr><td ><textarea name=' b_Parti[]'>$account : ($recived $widrawal) ($paid $deposit)</textarea></td><td><textarea name='b_damoun[]'>".abs($dramount)."</textarea></td><td><textarea name='b_camount[]'>".abs($cramount)."</textarea></td></tr>";
	
	
	/*
	*End of Cash Account
	*/

	/*
	*Start of Bank Account
	*/
		
	
	$bank = "SELECT DISTINCT(ledger) as bank FROM `ledgerreg` WHERE ledger != 'CASH' and ledtype = 'CASHBANK' ";
	$result_bank = mysqli_query($con,$bank);
	
	if($result_bank){
		//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** BANK BALANCE **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	while($rowbank = mysqli_fetch_array($result_bank))
	{
		$bankled = $rowbank['bank'];
		$recdbanksql = "SELECT  sum(`totamount`) as recd FROM `vchreg` WHERE  vchtype IN ('RECEIPT','JOURNAL') and fny = '$_SESSION[SESS_FNY]' and account = '$bankled'";
	$bankrec = mysqli_query($con,$recdbanksql);
	$rowrecbank = mysqli_fetch_assoc($bankrec);
	$recbank = $rowrecbank['recd']; 
	
	$depositsql = "SELECT sum(totamount) as deposit FROM `vchreg` where vchtype = 'CONTRA' and account = '$bankled' and fny = '$_SESSION[SESS_FNY]'";
	$result_depos = mysqli_query($con,$depositsql);
	$rowdepos = mysqli_fetch_assoc($result_depos);
	$bankdeposit = $rowdepos['deposit']; 
	
	
	$paidbanksql = "SELECT  sum(`totamount`) as paid FROM `vchreg` WHERE vchtype = 'PAYMENT' and fny = '$_SESSION[SESS_FNY]' and account = '$bankled'";
	$bankpay = mysqli_query($con,$paidbanksql);
	$rowpaybank = mysqli_fetch_assoc($bankpay);
	$paybank = $rowpaybank['paid']; 
	
	$widrawalsql = "SELECT sum(totamount) as widra FROM `vchreg` where vchtype = 'CONTRA' and comcode = '$bankled' and fny = '$_SESSION[SESS_FNY]'";
	$result_widra = mysqli_query($con,$widrawalsql);
	$rowwidra = mysqli_fetch_assoc($result_widra);
	$bankwidrawal = $rowwidra['widra'];
	
	$bankbalance = ($recbank + $bankdeposit)  - ($paybank + $bankwidrawal);
	$dramount=0;
	$cramount=0;
	if($bankbalance>0){
		$dramount = $bankbalance;
		
		}
		else {
			$cramount = $bankbalance;
			}
	
	
	$balsheet[1][3][$rowbank[bank]]=$bankbalance;
	
	$asset_acc[$j] = $rowbank[bank];
		$asset_tot[$j] =$bankbalance;
		$j++;
	//echo "<tr><td ><textarea name=' b_Parti[]'>$rowbank[bank] : ($recbank $bankdeposit) ($paybank $bankwidrawal)</textarea></td><td><textarea name='b_damoun[]'>".abs($dramount)."</textarea></td><td><textarea name='b_camount[]'>".abs($cramount)."</textarea></td></tr>";
	
	}
	}
	
	/*
	*End of Bank Account
	*/
	

$rowCount = 0;

//echo "<table  id='table_report_view'  cellspacing='0' width='100%''><thead> <tr><th><textarea name='b_Liabilities[]'>L I A B I L I T I E S</textarea></th><th><textarea name='b_Lamount[]'></textarea></th><th><textarea name='b_Ltotal[]'></textarea></th><th><textarea name='b_Asset[]'>A S S E T S</textarea></th><th><textarea name='b_Aamount[]'></textarea></th><th><textarea name='b_Atotal[]'></textarea></th></tr></thead>";
/*
//echo "<tr>";
//echo count($balsheet[1][2]); 
foreach ($balsheet[0] as $v2) {
   // foreach ($v1 as $v2) {
         foreach ($v2 as $k3 => $v3) {
        echo "$k3 -> $v3|";
   // }
    }
}
echo  "--------------------------------------------------------|";
foreach ($balsheet[1] as $v2) {
   // foreach ($v1 as $v2) {
         foreach ($v2 as $k3 => $v3) {
        echo "$k3 -> $v3|";
   // }
    }
}
*/
$liab_count = count($liab_acc);
$asset_count = count($asset_acc);

$count = $liab_count;
if($count<$asset_count)
$count = $asset_count;

for($k=0;$k<=$count;$k++)
{
	if(is_numeric($liab_bal[$k]))
	$curr_liabbal = number_format($liab_bal[$k],2);
	else
	$curr_liabbal = $liab_bal[$k];
	
	if(is_numeric($asset_bal[$k]))
	$curr_assetbal = number_format($asset_bal[$k],2);
	else
	$curr_assetbal = $asset_bal[$k];
	
	if(is_numeric($liab_tot[$k]))
	$curr_liabtot = number_format($liab_tot[$k],2);
	else
	$curr_liabtot = $liab_tot[$k];
	
	if(is_numeric($asset_tot[$k]))
	$curr_assettot = number_format($asset_tot[$k],2);
	else
	$curr_assettot = $asset_tot[$k];
	
	//echo "<tr><td><textarea name='b_Liabilities[]' style='text-align:left'>$liab_acc[$k]</textarea></td><td><textarea name='b_Lamount[]' style='text-align:right'>$curr_liabbal</textarea></td><td><textarea name='b_Ltotal[]' style='text-align:right'>$curr_liabtot</textarea></td><td><textarea name='b_Asset[]' style='text-align:left' >$asset_acc[$k]</textarea></td><td><textarea name='b_Aamount[]' style='text-align:right'>$curr_assetbal</textarea></td><td><textarea name='b_Atotal[]' style='text-align:right'>$curr_assettot</textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['L I A B I L I T I E S']['value'] = $liab_acc[$k];
	addCustomName($outputRow,'L I A B I L I T I E S','b_Liabilities[]');
	$outputRow['SUB LIABILITIES']['value'] = $curr_liabbal;
	addCustomName($outputRow,'SUB LIABILITIES','b_Lamount[]');
	$outputRow['TOTAL LIABILITIES']['value'] = $curr_liabtot;
	addCustomName($outputRow,'TOTAL LIABILITIES','b_Lamount[]');
	$outputRow['A S S E T S']['value'] = $asset_acc[$k];
	addCustomName($outputRow,'A S S E T S','b_Asset[]');
	$outputRow['SUB ASSETS']['value'] = $curr_assetbal;
	addCustomName($outputRow,'SUB ASSETS','b_Aamount[]');
	$outputRow['TOTAL ASSETS']['value'] = $curr_assettot;
	addCustomName($outputRow,'TOTAL ASSETS','b_Atotal[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;
	
	}
	
	//echo "<tr><td><textarea name='b_Liabilities[]' style='text-align:left'>Total</textarea></td><td><textarea name='b_Lamount[]' style='text-align:right'></textarea></td><td><textarea name='b_Ltotal[]' style='text-align:right'>".number_format(array_sum($liab_tot),2)."</textarea></td><td><textarea name='b_Asset[]' style='text-align:left' >Total</textarea></td><td><textarea name='b_Aamount[]' style='text-align:right'></textarea></td><td><textarea name='b_Atotal[]' style='text-align:right'>".number_format(array_sum($asset_tot),2)."</textarea></td></tr>";
	
	$outputRow = array();
	$outputRow['L I A B I L I T I E S']['value'] = '';
	addCustomName($outputRow,'L I A B I L I T I E S','b_Liabilities[]');
	$outputRow['SUB LIABILITIES']['value'] = '';
	addCustomName($outputRow,'SUB LIABILITIES','b_Lamount[]');
	$outputRow['TOTAL LIABILITIES']['value'] = number_format(array_sum($liab_tot),2);
	addCustomName($outputRow,'TOTAL LIABILITIES','b_Lamount[]');
	$outputRow['A S S E T S']['value'] = '';
	addCustomName($outputRow,'A S S E T S','b_Asset[]');
	$outputRow['SUB ASSETS']['value'] = '';
	addCustomName($outputRow,'SUB ASSETS','b_Aamount[]');
	$outputRow['TOTAL ASSETS']['value'] = number_format(array_sum($asset_tot),2);
	addCustomName($outputRow,'TOTAL ASSETS','b_Atotal[]');
	
	$rowCount++;
	$output['rows'][][] = $outputRow;





/*
*remaining

		echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** SALES & INCOME **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	$salesac = "SELECT DISTINCT(ledger) as salesac FROM `ledgerreg` WHERE  ledtype = 'SALES ACCOUNT' ";
	$result_sales = mysqli_query($con,$salesac);
	$rowsalesac = mysqli_fetch_assoc($result_sales);
	$salesacled = $rowsalesac['salesac'];
	

		
		$sales = "SELECT  sum(`total`) as debit from $billreg WHERE   fny = '$_SESSION[SESS_FNY]'";
	
	$salesresult = mysqli_query($con,$sales);
	$row_sales = mysqli_fetch_assoc($salesresult);
	
	$totalsales = $row_sales['debit'];
	
	
	
	echo "<tr><td ><textarea name=' b_Parti[]'>$salesacled</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'>$totalsales</textarea></td></tr>";
	
	$incomeled = "SELECT DISTINCT(ledger) as incomeac FROM `ledgerreg` WHERE  ledtype  like '%INCOME' ";
	$result_incomeled = mysqli_query($con,$incomeled);

	if($result_incomeled){
	while($rowincomeled = mysqli_fetch_array($result_incomeled))
	{
		
	$incomeled = $rowincomeled['incomeac'];
	
		$income = "SELECT  sum(`totamount`) as income from vchreg WHERE   vchtype IN  ('RECEIPT', 'JOURNAL') and comcode = '$incomeled' and fny = '$_SESSION[SESS_FNY]'";
	
	$incomeresult = mysqli_query($con,$income);
	$row_income = mysqli_fetch_assoc($incomeresult);
	
	$total = $row_income['income'];
	
	
	
	echo "<tr><td ><textarea name=' b_Parti[]'>$salesacled</textarea></td><td><textarea name='b_damoun[]'>$total</textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	}
	}
	
		echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** PURCHASE & EXPENCES **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	$purchac = "SELECT DISTINCT(ledger) as purchaseac FROM `ledgerreg` WHERE  ledtype = 'PURCHASE ACCOUNT' ";
	$result_purch = mysqli_query($con,$purchac);
	$rowpurch = mysqli_fetch_assoc($result_purch);
	$purchaseled = $rowpurch['purchaseac'];
	
		
		
		$expences = "SELECT  sum(`totamount`) as credit from purcreg WHERE vchtype = 'PURCHASE' and account = '$purchaseled' and fny = '$_SESSION[SESS_FNY]'";
	
	$expencesresult = mysqli_query($con,$expences);
	$row_expences = mysqli_fetch_assoc($expencesresult);
	
	$totalcredit = $row_expences['credit'];

	
	
	echo "<tr><td ><textarea name=' b_Parti[]'>$purchaseled</textarea></td><td><textarea name='b_damoun[]'>$totalcredit</textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	$expenseac = "SELECT DISTINCT(ledger) as expenceac FROM `ledgerreg` WHERE  ledtype  like '%EXPENSE' ";
	$result_expenseled = mysqli_query($con,$expenseac);

	if($result_bank){
	while($rowexpenseled = mysqli_fetch_array($result_expenseled))
	{
		
	$expenseled = $rowexpenseled['expenceac'];
	$totalexpense = 0;
        $totalpurcexpense = 0;
        $totalexp = 0;
		
		$otherexpense = "SELECT  sum(`totamount`) as expense from vchreg WHERE   vchtype in ('PAYMENT','JOURNAL') and comcode = '$expenseled' and fny = '$_SESSION[SESS_FNY]'";
	
	$result_expense = mysqli_query($con,$otherexpense);
	$row_expense = mysqli_fetch_assoc($result_expense);
	
	$totalexpense = $row_expense['expense'];

        $purcexpense = "SELECT  sum(`totamount`) as purcexpense from purcreg WHERE  account = '$expenseled' and fny = '$_SESSION[SESS_FNY]'";
	
	$result_purcexpense = mysqli_query($con,$purcexpense);
	$row_purcexpense = mysqli_fetch_assoc($result_purcexpense);
	
	$totalpurcexpense = $row_purcexpense['purcexpense'];
	
	$totalexp = $totalexpense  + $totalpurcexpense;
	
	echo "<tr><td ><textarea name=' b_Parti[]'>$expenseled ($totalexpense) ($totalpurcexpense)</textarea></td><td><textarea name='b_damoun[]'>$totalexp</textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	

	
	}
	}
	
		echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** DEBTORS **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";

       $debtorrec = "SELECT  sum(`totamount`) as recpt from vchreg WHERE   vchtype in ('RECEIPT') and fny = '$_SESSION[SESS_FNY]' and comcode IN (SELECT alias from ledgerreg where ledtype =  'SUNDRY DEBTORS') ";
	
	$result_debtrec = mysqli_query($con,$debtorrec);
	$row_debtrec = mysqli_fetch_assoc($result_debtrec);
	
	$totdebtrec = $row_debtrec['recpt'];
        $totaldebtors = $totalsales - $totdebtrec;
	
	echo "<tr><td ><textarea name=' b_Parti[]'>SUNDRY DEBTORS A/C SUMMARY</textarea></td><td><textarea name='b_damoun[]'>$totaldebtors </textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	
	
	echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** CREDITORS **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";

$debtorpay = "SELECT  sum(`totamount`) as recpt from vchreg WHERE   vchtype in ('PAYMENT') and fny = '$_SESSION[SESS_FNY]' and comcode IN (SELECT alias from ledgerreg where ledtype =  'SUNDRY CREDITORS') ";
	
	$result_debtpay = mysqli_query($con,$debtorpay);
	$row_debtpay = mysqli_fetch_assoc($result_debtpay);
	
	$totdebtpay = $row_debtpay['recpt'];
        $totalcreditors = $totalcredit - $totdebtpay ;
	
	echo "<tr><td ><textarea name=' b_Parti[]'>SUNDRY CREDITORS A/C SUMMARY</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'>$totalcreditors</textarea></td></tr>";
	
	
	
		

	

	
	
echo "</tbody></table>###Net Total Amount = $count_totalbill";
	*/
	
	//echo mysqli_error($con);
	addTotalRows($output,$rowCount);
echo json_encode($output);	
}



//// balance sheet end



else if($_POST['report_type']=="cashbank")
{
	
	if(!empty($_POST['billedto'])){
		
          $cashbank = "SELECT DISTINCT(ledger) as bank FROM `ledgerreg` WHERE ledger = '$_POST[billedto]' and ledtype = 'CASHBANK' ";
	}
		  else
		{  
		   $cashbank = "SELECT DISTINCT(ledger) as bank FROM `ledgerreg` WHERE  ledtype = 'CASHBANK' ";
		}
        
	

	
	$cbresult = mysqli_query($con,$cashbank);
	
	if($cbresult)
	{
	//echo "<table  id='table_report_view'  cellspacing='0' width='100%''><thead> <tr><th><textarea name=' b_srno[]'>VCHNO</textarea></th><th><textarea name='b_billdate[]'>VCHDATE</textarea></th><th><textarea name='b_billedto[]'>REFNO</textarea></th><th><textarea name='b_billno[]'>INV/INST</textarea></th><th><textarea name='b_bookedby[]'>VCHTYPE</textarea></th><th><textarea name='b_usedby[]'>FROM</textarea></th><th><textarea name='b_location[]'>ACCOUNT</textarea></th><th><textarea name='b_total[]'>DRAMOUNT</textarea></th> <th><textarea name='b_paid[]'>CRAMOUNT</textarea></th><th align='center' ><textarea  name='b_balance[]'>NARRATION</textarea></th> </tr></thead>";


	//echo "<tfoot><tr><td><textarea name='b_billdate[]'>TOTAL</textarea></td><td><textarea name='b_billto[]' count='nor'></textarea></td><td><textarea name='b_billn[]'></textarea></td><td><textarea name='b_bookedby[]'></textarea></td><td><textarea name='b_usedby[]'></textarea></td><td><textarea name='b_location[]'></textarea></td><td><textarea name='b_total[]'></textarea></td><td><textarea name='b_paid[]' count='yes'></textarea></td><td><textarea name='b_balance[]' count='yes'></textarea></td><td><textarea name='b_balance[]' ></textarea></td></tr></tfoot>";

//echo "<tbody>";
	$i=0;
	$count_totalbill=0;

	
	while($rowcb = mysqli_fetch_array($cbresult))
	{
		
		
			$outputRow = array();
		$outputRow['VCHNO']['value']=$rowcb[bank];
		addCustomName($outputRow,'VCHNO','b_billdate[]');
		addFooterCounter($outputRow,'VCHNO');
		
		$outputRow['VCHDATE']['value']='';
		addCustomName($outputRow,'VCHDATE','b_billto[]');
		
		$outputRow['REFNO']['value']='';
		addCustomName($outputRow,'REFNO','b_billn[]');
		
		$outputRow['INVINST']['value']='';
		addCustomName($outputRow,'REFNO','b_bookedby[]');
		
		$outputRow['VCHTYPE']['value']='';
		addCustomName($outputRow,'VCHTYPE','b_usedby[]');
		
		$outputRow['FROM']['value']='';
		addCustomName($outputRow,'FROM','b_location[]');
		
		$outputRow['ACCOUNT']['value']='';
		addCustomName($outputRow,'ACCOUNT','b_total[]');
		
		$outputRow['DRAMOUNT']['value']='';
		addCustomName($outputRow,'DRAMOUNT','b_paid[]');
		addFooterTotal($outputRow,'DRAMOUNT');
		addClassName($outputRow,'DRAMOUNT');
		
		$outputRow['CRAMOUNT']['value']='';
		addCustomName($outputRow,'CRAMOUNT','b_balance[]');
		addFooterTotal($outputRow,'CRAMOUNT');
		addClassName($outputRow,'CRAMOUNT');
		
		$outputRow['NARRATION']['value']='';
		addCustomName($outputRow,'NARRATION','b_balance[]');

		$output['rows'][][] = $outputRow;
		$rowCount++;
		
         // echo "<tr><td><textarea name='b_billdate[]'>$rowcb[bank]</textarea></td><td><textarea name='b_billto[]'></textarea></td><td><textarea name='b_billn[]'></textarea></td><td><textarea name='b_bookedby[]'></textarea></td><td><textarea name='b_usedby[]'></textarea></td><td><textarea name='b_location[]'></textarea></td><td><textarea name='b_total[]'></textarea></td><td><textarea name='b_paid[]'></textarea></td><td><textarea name='b_balance[]' ></textarea></td><td><textarea name='b_balance[]' ></textarea></td></tr>";



     $cashbanksql="SELECT VCHNO, VCHDATE, REFNO, BILL_NO as `INVINST`, VCHTYPE, COMCODE AS `FROM`, ACCOUNT, TOTAMOUNT AS DRAMOUNT, '' AS CRAMOUNT, NARRATION  FROM `vchreg` WHERE `vchtype` in ('RECEIPT','JOURNAL') AND ACCOUNT LIKE '$rowcb[bank]' AND FNY = '$_SESSION[SESS_FNY]' UNION ALL  SELECT VCHNO, VCHDATE, REFNO, BILL_NO, VCHTYPE, COMCODE AS `FROM`, ACCOUNT, TOTAMOUNT AS DRAMOUNT, '' AS CRAMOUNT, NARRATION  FROM `vchreg` WHERE `vchtype` in ('CONTRA') AND ACCOUNT LIKE '$rowcb[bank]' AND FNY = '$_SESSION[SESS_FNY]' UNION ALL SELECT VCHNO, VCHDATE, REFNO, BILL_NO, VCHTYPE, COMCODE AS `FROM`, ACCOUNT, '' AS DRAMOUNT, TOTAMOUNT AS CRAMOUNT, NARRATION  FROM `vchreg` WHERE `vchtype` in ('PAYMENT') AND ACCOUNT LIKE '$rowcb[bank]' AND FNY = '$_SESSION[SESS_FNY]' UNION ALL  SELECT VCHNO, VCHDATE, REFNO, BILL_NO, VCHTYPE, COMCODE AS `FROM`, ACCOUNT, '' AS DRAMOUNT, TOTAMOUNT AS CRAMOUNT, NARRATION  FROM `vchreg` WHERE `vchtype` in ('CONTRA') AND COMCODE LIKE '$rowcb[bank]' AND FNY = '$_SESSION[SESS_FNY]'";

  $cashbankresult = mysqli_query($con,$cashbanksql);
	while($cashbankrow = mysqli_fetch_array($cashbankresult))
	{
	if($cashbankresult)
	{
        if($cashbankrow['DRAMOUNT']>0){
				$balance=$balance+$cashbankrow['DRAMOUNT'];
				
				}
			if($cashbankrow['CRAMOUNT']>0){
				$balance=$balance-$cashbankrow['CRAMOUNT'];
				
				}
			
			$billbalance = $cashbankrow['DRAMOUNT'] -$cashbankrow['CRAMOUNT'];

		$outputRow = array();
		$outputRow['VCHNO']['value']=$cashbankrow[VCHNO];
		addCustomName($outputRow,'VCHNO','b_billdate[]');
		addFooterCounter($outputRow,'VCHNO');
		
		$outputRow['VCHDATE']['value']=$cashbankrow[VCHDATE];
		addCustomName($outputRow,'VCHDATE','b_billto[]');
		
		$outputRow['REFNO']['value']=$cashbankrow[REFNO];
		addCustomName($outputRow,'REFNO','b_billn[]');
		
		$outputRow['INVINST']['value']=$cashbankrow[INVINST];
		addCustomName($outputRow,'REFNO','b_bookedby[]');
		
		$outputRow['VCHTYPE']['value']=$cashbankrow[VCHTYPE];
		addCustomName($outputRow,'VCHTYPE','b_usedby[]');
		
		$outputRow['FROM']['value']=$cashbankrow[FROM];
		addCustomName($outputRow,'FROM','b_location[]');
		
		$outputRow['ACCOUNT']['value']=$cashbankrow[ACCOUNT];
		addCustomName($outputRow,'ACCOUNT','b_total[]');
		
		$outputRow['DRAMOUNT']['value']=$cashbankrow[DRAMOUNT];
		addCustomName($outputRow,'DRAMOUNT','b_paid[]');
		addFooterTotal($outputRow,'DRAMOUNT');
		addClassName($outputRow,'DRAMOUNT');
		
		$outputRow['CRAMOUNT']['value']=$cashbankrow[CRAMOUNT];
		addCustomName($outputRow,'CRAMOUNT','b_balance[]');
		addFooterTotal($outputRow,'CRAMOUNT');
		addClassName($outputRow,'CRAMOUNT');
		
		$outputRow['NARRATION']['value']=$cashbankrow[NARRATION];
		addCustomName($outputRow,'NARRATION','b_balance[]');

		$output['rows'][][] = $outputRow;
		$rowCount++;
	//echo "<tr><td><textarea name='b_billdate[]'>$cashbankrow[VCHNO]</textarea></td><td><textarea name='b_billto[]'>$cashbankrow[VCHDATE]</textarea></td><td><textarea name='b_billn[]'>$cashbankrow[REFNO]</textarea></td><td><textarea name='b_bookedby[]'>$cashbankrow[INVINST]</textarea></td><td><textarea name='b_usedby[]'>$cashbankrow[VCHTYPE]</textarea></td><td><textarea name='b_location[]'>$cashbankrow[FROM]</textarea></td><td><textarea name='b_total[]'>$cashbankrow[ACCOUNT]</textarea></td><td><textarea name='b_paid[]'>$cashbankrow[DRAMOUNT]</textarea></td><td><textarea name='b_balance[]' >$cashbankrow[CRAMOUNT]</textarea></td><td><textarea name='b_balance[]' >$cashbankrow[NARRATION]</textarea></td></tr>";
	$i++;
	
	}
	}
	//if displayed rows greater than 0 then sum total
	$count_totalbill=number_format($balance,2);
	


	}
	//echo "</tbody></table>### ";
	addTotalRows($output,$rowCount);
	}
	
	else
	$output[error] = mysqli_error($con);
	
	echo json_encode($output);
	}


// cash bank book end	


// start of outstantding receipt

 else if($_POST['report_type']=="PEDRECEIPT"){
	$queryparty="";
        $count_totalbill=0;
	if(!empty($_POST['billedto']))
	{
		$queryparty= " AND billto = '$_POST[billedto]' ";
	}
		
		/*addtitional filter */	
if(!empty($_POST['filter_type_value'])&&$_POST['filter_type_book_info']=='acc')	
$qry_part_filter=" and $_POST[filter_type_book_info] like '%$_POST[filter_type_value]%' ";
else
$qry_part_filter='';
		
	



$sqlQry = "SELECT distinct($billreg.buyercode) 
FROM $billreg  inner join commst
on buyercode=compid
where orderdate>=STR_TO_DATE('$from_date','%Y-%m-%d') 
and orderdate<=STR_TO_DATE('$to_date','%Y-%m-%d') 
and $billreg.cmp = '$_SESSION[SESS_CMPC]' 
and $billreg.fny = '$_SESSION[SESS_FNY]' 
$queryparty $qry_part_filter
UNION 
distinct SELECT distinct(buyercode) 
FROM $prebillreg inner join commst
on buyercode=compid
where orderdate>=STR_TO_DATE('$from_date','%Y-%m-%d') 
and orderdate<=STR_TO_DATE('$to_date','%Y-%m-%d') 
and $prebillreg.cmp = '$_SESSION[SESS_CMPC]' 
and $prebillreg.fny = '$prefny' 
$queryparty $qry_part_filter 
ORDER BY buyercode";

//$output['sql']= $sqlQry ;
if(!$get_cmp=mysqli_query($con,$sqlQry))
{
$output[error] = mysqli_error($con);
}
	
	$rowCount = 0 ;	
while($get_cmp_row=mysqli_fetch_array($get_cmp))
{
	
	 $partytotal=0;
	if(!empty($get_cmp_row['billto'])){
		if($_POST['sort_value']=="cf"){
         $getreccfvalue = mysqli_query($con," select sum(amount) as amount from vchdetails where vchno in (SELECT vchno FROM `vchreg` where comcode like '$get_cmp_row[billto]' and  vchdate<STR_TO_DATE('$from_date','%Y-%m-%d') and  vchreg.cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]'  and vchtype='RECEIPT' ) and paytype in ('advance', 'On account')");
        //$getreccfvalue = mysqli_query($con,"SELECT sum(totamount) as cfrec FROM `vchreg` where comcode like '$get_cmp_row[billto]' and  vchdate<STR_TO_DATE('$from_date','%Y-%m-%d') and  vchreg.cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]'  and vchtype='RECEIPT' and agnstref = 'Advance'");
	
	if ($getreccfrow =  mysqli_fetch_assoc($getreccfvalue)){
		$cfrecvalue = $getreccfrow['cfrec'];}
	else{
		$cfrecvalue = 0;}
// Pre CF		
		$getprebillcfvalue = mysqli_query($con,"SELECT sum(total) as cfbill FROM $prebillreg where buyercode like '$get_cmp_row[billto]'  and orderdate<STR_TO_DATE('$from_date','%Y-%m-%d') and cmp = '$_SESSION[SESS_CMPC]' and total - paid > 0 ");
	
	if ($getprebillcfrow =  mysqli_fetch_assoc($getprebillcfvalue)){
		$cfprebillvalue = $getprebillcfrow['cfbill'];}
	else{
		$cfprebillvalue = 0;}
// end		
		
		$getbillcfvalue = mysqli_query($con,"SELECT sum(total) as cfbill FROM $billreg where buyercode like '$get_cmp_row[billto]'  and orderdate<STR_TO_DATE('$from_date','%Y-%m-%d') and cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]' and total - paid > 0 ");
	
	if ($getbillcfrow =  mysqli_fetch_assoc($getbillcfvalue)){
		$cfbillvalue = $getbillcfrow['cfbill'];}
	else{
		$cfbillvalue = 0;}
		}
		else{
			$cfrecvalue = 0;
			$cfbillvalue = 0;
			}
			
	$age = 0;
	
	if(!empty($_POST['filter_type_value'])&&$_POST['filter_type_book_info']=='age')	
	{
		$age = clean($con,$_POST['filter_type_value']);	
	}
	
			
	
	
	// Getting Bills
		
	$sql = "
	select orderid,orderdate,buyercode,orderid, '' as bookedby, '' as usedby, '' as usedcity,grtotal, paid as paid, if (paid > 0, grtotal- paid, grtotal) as balance ,DATEDIFF( CURDATE( ) , orderdate ) as ages
	from $prebillreg 
	INNER JOIN commst 
	ON $prebillreg.buyercode=commst.compid 
	where orderdate between '$from_date' and '$to_date' and $prebillreg.cmp='$_SESSION[SESS_CMPC]' and $prebillreg.fny = '$prefny' and buyercode like '$get_cmp_row[buyercode]' and grtotal - paid > 0 and DATEDIFF( CURDATE( ) , orderdate ) >= $age
	 UNION ALL 
	 select orderid,orderdate,buyercode,orderid, '' as bookedby, '' as usedby, '' as usedcity,grtotal, paid   as paid, if (paid > 0, grtotal- paid, grtotal) as balance ,DATEDIFF( CURDATE( ) , orderdate ) as ages
	 from $billreg 
	 INNER JOIN commst ON $billreg.buyercode=commst.compid 
	 where orderdate between '$from_date' and '$to_date' and $billreg.cmp='$_SESSION[SESS_CMPC]' and $billreg.fny = '$_SESSION[SESS_FNY]' and buyercode like '$get_cmp_row[buyercode]' and grtotal - paid > 0  and DATEDIFF( CURDATE( ) , orderdate ) >= $age
	 UNION ALL 
	 select vchno as srno, vchdate as billdate, comcode as billto, refno as billno, '' as bookedby, '' as usedby, '' as usedcity, '' as total, totamount as paid,'' as balance,'' as ages  
	 from vchreg 
	 where vchdate between '$from_date' and '$to_date' and vchreg.cmp='$_SESSION[SESS_CMPC]'   and vchreg.fny = '$_SESSION[SESS_FNY]' and comcode like '$_POST[billedto]' and agnstref = 'Advance' and vchtype ='RECEIPT' order by billdate, srno;"; 
	//$output['sql']= $sql ;
	$result = mysqli_query($con,$sql);
	
	if($result)
	{

	$i=0;
	
//Display CF Values
//$balance=$cfbillvalue-$cfrecvalue;
$balance=($cfbillvalue+$cfprebillvalue)-$cfrecvalue;
$partytotal=$balance;


$outputRow = array();
$outputRow['SR. NO.']['value'] =  $get_cmp_row[billto];
$outputRow['SR. NO.']['links'] =  "mastercmpedit.php?compid=$get_cmp_row[buyercode],720,420";
$outputRow['SR. NO.']['tdClass'] = 'srno links';
addCustomName($outputRow,'SR. NO.','b_srno[]');
addFooterCounter($outputRow,'SR. NO.');



$outputRow['Bill Date']['value'] =  '-';
$outputRow['Bill Date']['tdClass'] =  'billdate';
addCustomName($outputRow,'Bill Date','b_billdate[]');

$outputRow['Bill No']['value'] =  'CF';
$outputRow['Bill No']['tdClass'] =  'billno';
addCustomName($outputRow,'Bill No','b_billno[]');

$outputRow['Used By']['value'] =  '-';
$outputRow['Used By']['tdClass'] =  'usedby';
addCustomName($outputRow,'Used By','b_usedby[]');

$outputRow['Used City']['value'] =  '-';
$outputRow['Used City']['tdClass'] =  'usedcity';
addCustomName($outputRow,'Used City','b_usedcity[]');


$outputRow['Booked By']['value'] =  '-';
$outputRow['Booked By']['tdClass'] =  'bookedby';
addCustomName($outputRow,'Booked By','b_bookedby[]');


$outputRow['Total']['value'] =  number_format($cfbillvalue,2);
$outputRow['Total']['tdClass'] = 'total';
addCustomName($outputRow,'Total','b_total[]');

$outputRow['Paid']['value'] =  number_format($cfrecvalue,2);
$outputRow['Paid']['tdClass'] =  'paid';
addCustomName($outputRow,'Paid','b_paid[]');

$outputRow['Bill Balance']['value'] =  number_format($balance,2);
$outputRow['Bill Balance']['tdClass'] = 'billbalance';
addCustomName($outputRow,'Bill Balance','b_balance[]');

$outputRow['Due Days']['value'] =  '-';
addClassName($outputRow,'Due Days','duedays');
addCustomName($outputRow,'Due Days','b_ages[]');


$output['rows'][][] = $outputRow;
$rowCount++;

	while($row = mysqli_fetch_array($result))
	{


        if($row['total']>0){
				$balance=$balance+$row['total'];
				
				}
			if($row['paid']>0){
				$balance=$balance-$row['paid'];
				
				}
			
			$billbalance = $row[grtotal] -$row[paid];


			$outputRow['SR. NO.']['value'] =  $row[orderid];
			$outputRow['SR. NO.']['links'] =  "";
			addCustomName($outputRow,'SR. NO.','b_srno[]');
			addFooterCounter($outputRow,'SR. NO.');
			
			$outputRow['Bill Date']['value'] =  date_formatc($row['orderdate']);
			addCustomName($outputRow,'Bill Date','b_billdate[]');
			
			$outputRow['Bill No']['value'] =  $row[orderid];
			addCustomName($outputRow,'Bill No','b_billno[]');
			
			$outputRow['Used By']['value'] =  $row[usedby];
			addCustomName($outputRow,'Used By','b_usedby[]');
			
			$outputRow['Used City']['value'] =  $row[usedcity];
			addCustomName($outputRow,'Used City','b_usedcity[]');
			
			$outputRow['Booked By']['value'] =  $row[bookedby];
			addCustomName($outputRow,'Booked By','b_bookedby[]');
			
			
			
			$outputRow['Total']['value'] =  number_format($row['grtotal'],2);
			addCustomName($outputRow,'Total','b_total[]');
			
			$outputRow['Paid']['value'] =  number_format($row['paid'],2);
			addCustomName($outputRow,'Paid','b_paid[]');
			
			$outputRow['Bill Balance']['value'] =  number_format($billbalance,2);
			addCustomName($outputRow,'Bill Balance','b_balance[]');
			addFooterTotal($outputRow,'Bill Balance');
			
			$outputRow['Due Days']['value'] =  $row[ages];
			addCustomName($outputRow,'Due Days','b_ages[]');
			
			$output['rows'][][] = $outputRow;
			$rowCount++;
	
	$i++;
	
         $partytotal=$balance;
	}
	
	
	//if displayed rows greater than 0 then sum total
	//$count_totalbill=number_format($count_totalbill,2);
	
     $color='style="background-color: #D6A7AB;text-align:right;font-size: 12px;"';
	 $font='style="font-weight: bold;font-size: 13px;"';
	 
	 
   

 $onaccount = mysqli_query($con," select sum(amount - cramount) as amount from vchdetails where vchno in (SELECT vchno FROM `vchreg` where comcode like '$get_cmp_row[billto]' and  vchreg.cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]'  and vchtype='RECEIPT' ) and paytype in ('advance', 'On account') and amount-cramount > 0 ");
if ($onaccontrow =  mysqli_fetch_assoc($onaccount)){
		$onaccontvalue = $onaccontrow['amount'];}
	else{
		$onaccontvalue = 0;}
if($onaccontvalue!=0){
$penbalance= $partytotal -$onaccontvalue;

	$outputRow['SR. NO.']['value'] =  '-';
	addCustomName($outputRow,'SR. NO.','b_srno[]');
	
	$outputRow['Bill Date']['value'] =  '-';
	addCustomName($outputRow,'billdate','b_billdate[]');
	
	$outputRow['Bill No']['value'] =  '-';
	addCustomName($outputRow,'billno','b_billno[]');
	
	$outputRow['Used By']['value'] =  '-';
	addCustomName($outputRow,'Used By','b_usedby[]');
	
	$outputRow['Used City']['value'] =  '-';
	addCustomName($outputRow,'Used City','b_usedcity[]');
	
	$outputRow['Booked By']['value'] =  '-';
	addCustomName($outputRow,'Booked By','b_bookedby[]');
	
	
	$outputRow['Total']['value'] =  '-';
	addCustomName($outputRow,'Total','b_total[]');
	
	$outputRow['Paid']['value'] =  'Bill Total';
	addCustomName($outputRow,'Paid','b_paid[]');
	
	$outputRow['Bill Balance']['value'] = number_format($partytotal,2);
	addCustomName($outputRow,'Bill Balance','b_balance[]');
	
	$outputRow['Due Days']['value'] =  '-';
	addCustomName($outputRow,'Due Days','b_ages[]');
	
	$output['rows'][][] = $outputRow;
	$rowCount++;


$onaccdet = mysqli_query($con," select vchdetails.vchno, vchdate,paytype,(vchdetails.amount - vchdetails.cramount) as amount from vchdetails inner join  `vchreg` on vchdetails.vchno = vchreg.vchno where comcode like '$get_cmp_row[billto]' and  vchreg.cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]'  and vchreg.vchtype='RECEIPT'  and paytype in ('advance', 'On account') and vchdetails.amount-vchdetails.cramount > 0 ");

while($onaccdet_row = mysqli_fetch_array($onaccdet))
	{
		 
	
	$outputRow['SR. NO.']['value'] =  $onaccdet_row[vchno];
		addCustomName($outputRow,'SR. NO.','b_srno[]');
		
		
		$outputRow['Bill Date']['value'] =  date_formatc($onaccdet_row[vchdate]);
		addCustomName($outputRow,'Bill Date','b_billdate[]');
		
		$outputRow['Bill No']['value'] =  $onaccdet_row[paytype];
		addCustomName($outputRow,'Bill No','b_billno[]');
		
		$outputRow['Used By']['value'] =  '-';
		addCustomName($outputRow,'Used By','b_usedby[]');
		
		$outputRow['Used City']['value'] =  '-';
		addCustomName($outputRow,'Used City','b_usedcity[]');
		
		$outputRow['Booked By']['value'] =  '-';
		addCustomName($outputRow,'Booked By','b_bookedby[]');
		
		
		
		$outputRow['Total']['value']=  '-';
		addCustomName($outputRow,'Total','b_total[]');
		
		$outputRow['Paid']['value'] =  $onaccdet_row[amount];
		addCustomName($outputRow,'Paid','b_paid[]');
		
		$outputRow['Bill Balance']['value'] = '-';
		addCustomName($outputRow,'bill Balance','b_balance[]');
		
		$outputRow['Due Days']['value'] =  '-';
		addClassName($outputRow,'Due Days','duedays');
		addCustomName($outputRow,'Due Days','b_ages[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
		
		}
		



		$outputRow['SR. NO.']['value'] =  '-';
		addCustomName($outputRow,'SR. NO.','b_srno[]');
		
		$outputRow['Bill Date']['value'] =  '-';
		addCustomName($outputRow,'Bill Date','b_billdate[]');
		
		$outputRow['Bill No']['value'] =  '-';
		addCustomName($outputRow,'Bill No','b_billno[]');
		
		$outputRow['Used By']['value'] =  '-';
		addCustomName($outputRow,'Used By','b_usedby[]');
		
		$outputRow['Used City']['value'] =  '-';
		addCustomName($outputRow,'Used City','b_usedcity[]');
		
		$outputRow['Booked By']['value'] =  '-';
		addCustomName($outputRow,'Booked By','b_bookedby[]');
			
		
		$outputRow['Total']['value']=  '-';
		addCustomName($outputRow,'Total','b_total[]');
		
		$outputRow['Paid']['value'] =  'On Account';
		addCustomName($outputRow,'Paid','b_paid[]');
		
		$outputRow['Bill Balance']['value'] = number_format($onaccontvalue,2);
		addCustomName($outputRow,'Bill Balance','b_balance[]');
		
		$outputRow['Due Days']['value'] =  '-';
		addCustomName($outputRow,'Due Days','b_ages[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
	
	
	
	
	$outputRow['SR. NO.']['value'] =  '-';
	addCustomName($outputRow,'SR. NO.','b_srno[]');
	
	$outputRow['Bill Date']['value'] =  '-';
	addCustomName($outputRow,'Bill Date','b_billdate[]');
	
	$outputRow['Bill No']['value'] =  '-';
	addCustomName($outputRow,'Bill No','b_billno[]');
	
	$outputRow['Used By']['value'] =  '-';
	addCustomName($outputRow,'Used By','b_usedby[]');
	
	$outputRow['Used City']['value'] =  '-';
	addCustomName($outputRow,'Used City','b_usedcity[]');
	
	$outputRow['Booked By']['value'] =  '-';
	addCustomName($outputRow,'Booked By','b_bookedby[]');
	
	
	$outputRow['Total']['value'] =  '-';
	addCustomName($outputRow,'Total','b_total[]');
	
	$outputRow['Paid']['value']=  'Balance';
	addCustomName($outputRow,'Paid','b_paid[]');
	
	$outputRow['Bill Balance']['value'] = number_format($penbalance,2);
	addCustomName($outputRow,'Bill Balance','b_balance[]');
	
	$outputRow['Due Days']['value'] =  '-';
	addCustomName($outputRow,'Due Days','b_ages[]');	
	
	$output['rows'][][] = $outputRow;
	$rowCount++;
}

else {
	$penbalance= $partytotal;
	}
	}
	else
	echo mysqli_error($con);
	}

	
	$outputRow['SR. NO.']['value'] =  '-';
	addCustomName($outputRow,'SR. NO.','b_srno[]');
	
	$outputRow['Bill Date']['value'] =  '';
	addCustomName($outputRow,'Bill Date','b_billdate[]');
	
	$outputRow['Bill No']['value'] =  '';
	addCustomName($outputRow,'Bill No','b_billno[]');
	
	$outputRow['Used By']['value'] =  '';
	addCustomName($outputRow,'Used By','b_usedby[]');
	
	$outputRow['Used City']['value'] =  '';
	addCustomName($outputRow,'Used City','b_usedcity[]');
	
	$outputRow['Booked By']['value'] =  '';
	addCustomName($outputRow,'Booked By','b_bookedby[]');

	
	$outputRow['Total']['value'] =  '';
	addCustomName($outputRow,'Total','b_total[]');
	
	$outputRow['Paid']['value'] =  'Total';
	addCustomName($outputRow,'Paid','b_paid[]');
	
	$outputRow['Bill Balance']['value'] = number_format($penbalance,2);
	addCustomName($outputRow,'Bill Balance','b_balance[]');
	
	
	$outputRow['Due Days']['value'] =  '';
	addCustomName($outputRow,'Due Days','b_ages[]');	

	
	$output['rows'][][] = $outputRow;
	$rowCount++;
	$count_totalbill+=$penbalance;
}
$displaynone='style="display: none"';

	$outputRow['SR. NO.']['value'] =  '-';
	addCustomName($outputRow,'SR. NO.','b_srno[]');
	
	$outputRow['Bill Date']['value'] =  '';
	addCustomName($outputRow,'Bill Date','b_billdate[]');
	
	$outputRow['Bill No']['value'] =  '';
	addCustomName($outputRow,'Bill No','b_billno[]');
	
	$outputRow['Used By']['value'] =  '';
	addCustomName($outputRow,'Used By','b_usedby[]');
	
	$outputRow['Used City']['value'] =  '';
	addCustomName($outputRow,'Used City','b_usedcity[]');
	
	$outputRow['Booked By']['value'] =  '';
	addCustomName($outputRow,'Booked By','b_bookedby[]');
	
	
	
	$outputRow['Total']['value'] =  '';
	addCustomName($outputRow,'Total','b_total[]');
	
	$outputRow['Paid']['value'] =  'Balance';
	addCustomName($outputRow,'Paid','b_paid[]');
	
	$outputRow['Bill Balance']['value'] = number_format($count_totalbill,2);
	addCustomName($outputRow,'Bill Balance','b_balance[]');
	
	$outputRow['Due Days']['value'] =  '';
	addCustomName($outputRow,'Due Days','b_ages[]');
	
	
	
	$output['rows'][][] = $outputRow;
	$rowCount++;
	
	$output['total_rows'] =$rowCount;	
	
echo json_encode($output);
}


// start of outstantding Payment

 else if($_POST['report_type']=="PEDPAYMENT"){
	$queryparty="";
        $count_totalbill=0;
	if(!empty($_POST['billedto'])){
		$queryparty= "AND comcode = '$_POST[billedto]'";}
		
	
	$get_cmp=mysqli_query($con,"SELECT comcode, SUM( totamount ) AS total, SUM( paid ) AS payment, SUM(totamount)-SUM(paid) as balance, SUM(basic_amt) as basic, SUM(toll_park) as toll, SUM(ser_tax+educess+seducess) as stamount, misamt FROM purcreg where vchdate>=STR_TO_DATE('$from_date','%Y-%m-%d') and vchdate<=STR_TO_DATE('$to_date','%Y-%m-%d') and purcreg.cmp = '$_SESSION[SESS_CMPC]' and purcreg.fny = '$_SESSION[SESS_FNY]' $queryparty GROUP BY comcode");
	


	/*echo "<table  id='table_report_view'  cellspacing='0' width='100%''><thead> <tr>
	<th><textarea name='b_srno[]' >VCH NO</textarea></th>
	<th><textarea name='b_billdate[]'>BILL DATE</textarea></th>
	<th><textarea name='b_billno[]'>BILL NO</textarea></th>
	<th><textarea name='b_bookedby[]'>BOOKED BY</textarea></th>
	<th><textarea name='b_usedby[]'>USED BY</textarea></th>
	<th><textarea name='b_location[]'>LOCATION</textarea></th>
	<th><textarea name='b_total[]'>DEBIT</textarea></th>
	 <th><textarea name='b_paid[]'>CREDIT</textarea></th>
	 <th align='center' ><textarea  name='b_balance[]'>PENDING</textarea></th>
	 </tr></thead>";
    
      echo "<tfoot><tr>
	<td><textarea name='b_srno[]'>Total</textarea></td>
	<td><textarea name='b_billdate[]' count='nor'></textarea></td>
	<td><textarea name='b_billno[]'></textarea></td>
	<td><textarea name='b_bookedby[]'></textarea></td>
	<td><textarea name='b_usedby[]'></textarea></td>
	<td><textarea name='b_location[]'></textarea></td>
	<td><textarea name='b_total[]' count='yes'></textarea></td>
	<td><textarea name='b_paid[]'></textarea></td>
	<td><textarea  name='b_balance[]' count='last'></textarea></td></tr> </tfoot>";
	echo "</tbody>";*/
while($get_cmp_row=mysqli_fetch_array($get_cmp))
{
	
	 $partytotal=0;
	if(!empty($get_cmp_row['comcode'])){
		if($_POST['sort_value']=="cf"){
         $getreccfvalue = mysqli_query($con," select sum(amount) as amount from vchdetails where vchno in (SELECT vchno FROM `vchreg` where comcode like '$get_cmp_row[comcode]' and  vchdate<STR_TO_DATE('$from_date','%Y-%m-%d') and  vchreg.cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]'  and vchtype='PAYMENT' ) and paytype in ('advance', 'On account')");
        //$getreccfvalue = mysqli_query($con,"SELECT sum(totamount) as cfrec FROM `vchreg` where comcode like '$get_cmp_row[comcode]' and  vchdate<STR_TO_DATE('$from_date','%Y-%m-%d') and  vchreg.cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]'  and vchtype='RECEIPT' and agnstref = 'Advance'");
	
	if ($getreccfrow =  mysqli_fetch_assoc($getreccfvalue)){
		$cfrecvalue = $getreccfrow['cfrec'];}
	else{
		$cfrecvalue = 0;}
		
		
		$getbillcfvalue = mysqli_query($con,"SELECT sum(totamount) as cfbill FROM purcreg where comcode like '$get_cmp_row[comcode]'  and vchdate <STR_TO_DATE('$from_date','%Y-%m-%d') and cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]' and totamount - paid > 0 ");
	
	if ($getbillcfrow =  mysqli_fetch_assoc($getbillcfvalue)){
		$cfbillvalue = $getbillcfrow['cfbill'];}
	else{
		$cfbillvalue = 0;}
		}
		else{
			$cfrecvalue = 0;
			$cfbillvalue = 0;
			}
	
	$sql = "select vchno, vchdate, comcode, bill_no, totamount as total, paid as paid, if (paid > 0, totamount- paid, totamount) as balance from purcreg INNER JOIN ledgerreg ON purcreg.comcode=ledgerreg.alias where vchdate between '$from_date' and '$to_date' and vchtype ='PURCHASE' and purcreg.cmp='$_SESSION[SESS_CMPC]' and purcreg.fny = '$_SESSION[SESS_FNY]' and comcode like '$get_cmp_row[comcode]' and totamount - paid > 0 UNION ALL select vchno as srno, vchdate as billdate, comcode as billto, refno as billno, totamount as total, paid as paid,'' as balance from vchreg where vchdate between '$from_date' and '$to_date' and vchreg.cmp='$_SESSION[SESS_CMPC]'   and vchreg.fny = '$_SESSION[SESS_FNY]' and comcode like '$get_cmp_row[comcode]'  and vchtype ='PAYMENT' order by vchdate;"; 
	
	$result = mysqli_query($con,$sql);
	
	if($result)
	{

	$i=0;
	
//Display CF Values
$balance=$cfbillvalue-$cfrecvalue;
$partytotal=$balance;
		

		$outputRow = array();
		$outputRow['VCH NO']['value'] = "$get_cmp_row[comcode]";
		addCustomName($outputRow,'VCH NO','b_srno[]');
		addFooterCounter($outputRow,'VCH NO');
		
		$outputRow['BILL DATE']['value'] = "";
		addCustomName($outputRow,'BILL DATE','b_billdate[]');

		$outputRow['BILL NO']['value'] = "";
		addCustomName($outputRow,'BILL NO','b_billno[]');

		$outputRow['BOOKED BY']['value'] = "";
		addCustomName($outputRow,'BOOKED BY','b_bookedby[]');

		$outputRow['USED BY']['value'] = "";
		addCustomName($outputRow,'USED BY','b_usedby[]');

		$outputRow['LOCATION']['value'] = "";
		addCustomName($outputRow,'LOCATION','b_location[]');

		$outputRow['DEBIT']['value'] =number_format($cfbillvalue,2);
		addCustomName($outputRow,'DEBIT','b_total[]');

		$outputRow['CREDIT']['value'] = number_format($cfrecvalue,2);
		addCustomName($outputRow,'CREDIT','b_paid[]');

		$outputRow['PENDING']['value'] = number_format($balance,2);
		addCustomName($outputRow,'PENDING','b_balance[]');

		
		$output['rows'][][] = $outputRow;
		$rowCount++;

	while($row = mysqli_fetch_array($result))
	{


        if($row['total']>0){
				$balance=$balance+$row['total'];
				
				}
			if($row['paid']>0){
				$balance=$balance-$row['paid'];
				
				}
			
			$billbalance = $row[total] -$row[paid];


	/*echo "<tr>
	<td ><textarea name='b_srno[]' class='srno'>$row[entryid]</textarea></td>
	<td><textarea name='b_billdate[]' class='billdate'>".date_formatc($row['vchdate'])."</textarea></td>
	<td><textarea name='b_billno[]' class='billno'>$row[vchno]</textarea></td>
	<td><textarea name='b_bookedby[]' >$row[bookedby]</textarea></td>
	<td><textarea name='b_usedby[]' class='usedby'>$row[usedby]</textarea></td>
	<td><textarea name='b_location[]'>$row[usedcity]</textarea></td>
	<td><textarea name='b_total[]' class='total'>".number_format($row['total'],2)."</textarea></td>
	<td><textarea name='b_paid[]'>".number_format($row['paid'],2)."</textarea></td>
	<td><textarea name='b_balance[]' class='total'>".number_format($billbalance,2)."</textarea></td></tr>";*/
	
	
		$outputRow = array();
		$outputRow['VCH NO']['value'] = "$row[entryid]";
		addCustomName($outputRow,'VCH NO','b_srno[]');
		addFooterCounter($outputRow,'VCH NO');
		
		$outputRow['BILL DATE']['value'] =date_formatc($row['vchdate']);
		addCustomName($outputRow,'BILL DATE','b_billdate[]');

		$outputRow['BILL NO']['value'] = "$row[vchno]";
		addCustomName($outputRow,'BILL NO','b_billno[]');

		$outputRow['BOOKED BY']['value'] = "$row[bookedby]";
		addCustomName($outputRow,'BOOKED BY','b_bookedby[]');

		$outputRow['USED BY']['value'] = "$row[usedby]";
		addCustomName($outputRow,'USED BY','b_usedby[]');

		$outputRow['LOCATION']['value'] = "$row[usedcity]";
		addCustomName($outputRow,'LOCATION','b_location[]');

		$outputRow['DEBIT']['value'] =number_format($row['total'],2);
		addCustomName($outputRow,'DEBIT','b_total[]');

		$outputRow['CREDIT']['value'] =number_format($row['paid'],2);
		addCustomName($outputRow,'CREDIT','b_paid[]');

		$outputRow['PENDING']['value'] = number_format($billbalance,2);
		addCustomName($outputRow,'PENDING','b_balance[]');

		
		$output['rows'][][] = $outputRow;
		$rowCount++;
	$i++;
	
         $partytotal=$balance;
	}
	
	
	//if displayed rows greater than 0 then sum total
	//$count_totalbill=number_format($count_totalbill,2);
	
     $color='style="background-color: #D6A7AB;text-align:right;font-size: 12px;"';
	 $font='style="font-weight: bold;font-size: 13px;"';
	

 $onaccount = mysqli_query($con," select sum(amount - cramount) as amount from vchdetails where vchno in (SELECT vchno FROM `vchreg` where comcode like '$get_cmp_row[billto]' and  vchreg.cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]'  and vchtype='RECEIPT' ) and paytype in ('advance', 'On account') and amount-cramount > 0 ");
if ($onaccontrow =  mysqli_fetch_assoc($onaccount)){
		$onaccontvalue = $onaccontrow['amount'];}
	else{
		$onaccontvalue = 0;}
if($onaccontvalue!=0){
$penbalance= $partytotal -$onaccontvalue;

	
		$outputRow = array();
		$outputRow['VCH NO']['value'] = "";
		addCustomName($outputRow,'VCH NO','b_srno[]');
		addFooterCounter($outputRow,'VCH NO');
		
		$outputRow['BILL DATE']['value'] = "";
		addCustomName($outputRow,'BILL DATE','b_billdate[]');

		$outputRow['BILL NO']['value'] = "";
		addCustomName($outputRow,'BILL NO','b_billno[]');

		$outputRow['BOOKED BY']['value'] = "";
		addCustomName($outputRow,'BOOKED BY','b_bookedby[]');

		$outputRow['USED BY']['value'] = "";
		addCustomName($outputRow,'USED BY','b_usedby[]');

		$outputRow['LOCATION']['value'] = "";
		addCustomName($outputRow,'LOCATION','b_location[]');

		$outputRow['DEBIT']['value'] ="";
		addCustomName($outputRow,'DEBIT','b_total[]');

		$outputRow['CREDIT']['value'] ="Bill Total";
		addCustomName($outputRow,'CREDIT','b_paid[]');

		$outputRow['PENDING']['value'] =number_format($partytotal,2);
		addCustomName($outputRow,'PENDING','b_balance[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;

	
	
	if(!$onaccdet = mysqli_query($con," select vchdetails.vchno, vchdate,paytype,(vchdetails.amount - vchdetails.cramount) as amount from vchdetails inner join  `vchreg` on vchdetails.vchno = vchreg.vchno where comcode like '$get_cmp_row[billto]' and  vchreg.cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]'  and vchreg.vchtype='RECEIPT'  and paytype in ('advance', 'On account') and vchdetails.amount-vchdetails.cramount > 0 "))
	{
		$output[error] = mysqli_error($con);	
	}

while($onaccdet_row = mysqli_fetch_array($onaccdet))
	{
		$outputRow = array();
		$outputRow['VCH NO']['value'] = "$onaccdet_row[vchno]";
		addCustomName($outputRow,'VCH NO','b_srno[]');
		addFooterCounter($outputRow,'VCH NO');
		
		$outputRow['BILL DATE']['value'] = date_formatc($onaccdet_row[vchdate]);
		addCustomName($outputRow,'BILL DATE','b_billdate[]');

		$outputRow['BILL NO']['value'] = "$onaccdet_row[paytype]";
		addCustomName($outputRow,'BILL NO','b_billno[]');

		$outputRow['BOOKED BY']['value'] = "";
		addCustomName($outputRow,'BOOKED BY','b_bookedby[]');

		$outputRow['USED BY']['value'] = "";
		addCustomName($outputRow,'USED BY','b_usedby[]');

		$outputRow['LOCATION']['value'] = "";
		addCustomName($outputRow,'LOCATION','b_location[]');

		$outputRow['DEBIT']['value'] ="";
		addCustomName($outputRow,'DEBIT','b_total[]');

		$outputRow['CREDIT']['value'] ="$onaccdet_row[amount]";
		addCustomName($outputRow,'CREDIT','b_paid[]');

		$outputRow['PENDING']['value'] ="";
		addCustomName($outputRow,'PENDING','b_balance[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
	}
	
		$outputRow = array();
		$outputRow['VCH NO']['value'] = "";
		addCustomName($outputRow,'VCH NO','b_srno[]');
		addFooterCounter($outputRow,'VCH NO');
		
		$outputRow['BILL DATE']['value'] = "";
		addCustomName($outputRow,'BILL DATE','b_billdate[]');

		$outputRow['BILL NO']['value'] = "";
		addCustomName($outputRow,'BILL NO','b_billno[]');

		$outputRow['BOOKED BY']['value'] = "";
		addCustomName($outputRow,'BOOKED BY','b_bookedby[]');

		$outputRow['USED BY']['value'] = "";
		addCustomName($outputRow,'USED BY','b_usedby[]');

		$outputRow['LOCATION']['value'] = "";
		addCustomName($outputRow,'LOCATION','b_location[]');

		$outputRow['DEBIT']['value'] ="";
		addCustomName($outputRow,'DEBIT','b_total[]');

		$outputRow['CREDIT']['value'] ="On Account";
		addCustomName($outputRow,'CREDIT','b_paid[]');

		$outputRow['PENDING']['value'] =number_format($onaccontvalue,2);
		addCustomName($outputRow,'PENDING','b_balance[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
	
	
	
	
	$outputRow = array();
		$outputRow['VCH NO']['value'] = "";
		addCustomName($outputRow,'VCH NO','b_srno[]');
		addFooterCounter($outputRow,'VCH NO');
		
		$outputRow['BILL DATE']['value'] = "";
		addCustomName($outputRow,'BILL DATE','b_billdate[]');

		$outputRow['BILL NO']['value'] = "";
		addCustomName($outputRow,'BILL NO','b_billno[]');

		$outputRow['BOOKED BY']['value'] = "";
		addCustomName($outputRow,'BOOKED BY','b_bookedby[]');

		$outputRow['USED BY']['value'] = "";
		addCustomName($outputRow,'USED BY','b_usedby[]');

		$outputRow['LOCATION']['value'] = "";
		addCustomName($outputRow,'LOCATION','b_location[]');

		$outputRow['DEBIT']['value'] ="";
		addCustomName($outputRow,'DEBIT','b_total[]');

		$outputRow['CREDIT']['value'] ="Balance";
		addCustomName($outputRow,'CREDIT','b_paid[]');

		$outputRow['PENDING']['value'] =number_format($penbalance,2);
		addCustomName($outputRow,'PENDING','b_balance[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
	
}

else {
	$penbalance= $partytotal;
	}
	}
	else
	echo mysqli_error($con);
	}

	
	$outputRow = array();
		$outputRow['VCH NO']['value'] = "";
		addCustomName($outputRow,'VCH NO','b_srno[]');
		addFooterCounter($outputRow,'VCH NO');
		
		$outputRow['BILL DATE']['value'] = "";
		addCustomName($outputRow,'BILL DATE','b_billdate[]');

		$outputRow['BILL NO']['value'] = "";
		addCustomName($outputRow,'BILL NO','b_billno[]');

		$outputRow['BOOKED BY']['value'] = "";
		addCustomName($outputRow,'BOOKED BY','b_bookedby[]');

		$outputRow['USED BY']['value'] = "";
		addCustomName($outputRow,'USED BY','b_usedby[]');

		$outputRow['LOCATION']['value'] = "";
		addCustomName($outputRow,'LOCATION','b_location[]');

		$outputRow['DEBIT']['value'] ="";
		addCustomName($outputRow,'DEBIT','b_total[]');

		$outputRow['CREDIT']['value'] ="Total";
		addCustomName($outputRow,'CREDIT','b_paid[]');

		$outputRow['PENDING']['value'] =number_format($penbalance,2);
		addCustomName($outputRow,'PENDING','b_balance[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
	$count_totalbill+=$penbalance;
	
	
}
$displaynone='style="display: none"';

	
	$outputRow = array();
		$outputRow['VCH NO']['value'] = "";
		addCustomName($outputRow,'VCH NO','b_srno[]');
		addFooterCounter($outputRow,'VCH NO');
		
		$outputRow['BILL DATE']['value'] = "";
		addCustomName($outputRow,'BILL DATE','b_billdate[]');

		$outputRow['BILL NO']['value'] = "";
		addCustomName($outputRow,'BILL NO','b_billno[]');

		$outputRow['BOOKED BY']['value'] = "";
		addCustomName($outputRow,'BOOKED BY','b_bookedby[]');

		$outputRow['USED BY']['value'] = "";
		addCustomName($outputRow,'USED BY','b_usedby[]');

		$outputRow['LOCATION']['value'] = "";
		addCustomName($outputRow,'LOCATION','b_location[]');

		$outputRow['DEBIT']['value'] ="";
		addCustomName($outputRow,'DEBIT','b_total[]');

		$outputRow['CREDIT']['value'] ="Total";
		addCustomName($outputRow,'CREDIT','b_paid[]');

		$outputRow['PENDING']['value'] =number_format($count_totalbill,2);
		addCustomName($outputRow,'PENDING','b_balance[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
	
//echo "</tbody></table>### ";
	addTotalRows($output,$rowCount);
	
	echo json_encode($output);
}
//// end of outstanding payment

// Report for tdsreport start

elseif($_POST['report_type']=="tdsreport"){
	if(!empty($_POST['billedto'])){
	
$sql = "select  `vchno`, `refno`, `vchdate`, `comcode`, `bill_no`, `account` , `basic_amt` , `toll_park` , `ser_tax` , `educess` , `seducess` , `misamt` , `dramount`  , `sortpayment`,  `subtotal` , `tdsamt`, `totamount`  FROM `purcreg` where comcode = '$_POST[billedto]'   ;"; 
	
	
	$result = mysqli_query($con,$sql);
	
	if($result)
	{
	
	$i=0;
	$count_totalbill=0;
//Display CF Values
//$balance=$cfbillvalue-$cfrecvalue;
		

$outputRow = array();

$outputRow['VCH NO']['value']="";
addCustomName($outputRow,'VCH NO','b_vchno[]');
addFooterCounter($outputRow,'VCH NO');

$outputRow['REF NO']['value']="";
addCustomName($outputRow,'REF NO','b_refno[]');

$outputRow['BILL DATE']['value']="";
addCustomName($outputRow,'BILL DATE','b_vchdate[]');

$outputRow['COMPANY']['value']="";
addCustomName($outputRow,'COMPANY','b_comcode[]');

$outputRow['BILL NO']['value']="";
addCustomName($outputRow,'BILL NO','b_bill_no[]');

$outputRow['ACCOUNT']['value']="";
addCustomName($outputRow,'ACCOUNT','b_account[]');

$outputRow['BASIC AMT']['value']="";
addCustomName($outputRow,'BASIC AMT','b_basic_amt[]');
addFooterTotal($outputRow,'BASIC AMT');

$outputRow['TOLL PARKING']['value']="";
addCustomName($outputRow,'TOLL PARKING','b_toll_park[]');
addFooterTotal($outputRow,'TOLL PARKING');

$outputRow['SERVICE TAX']['value']="";
addCustomName($outputRow,'SERVICE TAX','b_ser_tax[]');
addFooterTotal($outputRow,'SERVICE TAX');

$outputRow['K.K.CESS']['value']=""; 
addCustomName($outputRow,'K.K.CESS','b_educess[]');
addFooterTotal($outputRow,'K.K.CESS');

$outputRow['S.B.CESS']['value']="";
addCustomName($outputRow,'S.B.CESS','b_seducess[]');
addFooterTotal($outputRow,'S.B.CESS');

$outputRow['MISCAMT']['value']="";
addCustomName($outputRow,'MISCAMT','b_misamt[]');
addFooterTotal($outputRow,'MISCAMT');

$outputRow['AMOUNT']['value']="";
addCustomName($outputRow,'AMOUNT','b_dramount[]');
addFooterTotal($outputRow,'AMOUNT');

$outputRow['DEDUCTION']['value']="";
addCustomName($outputRow,'DEDUCTION','b_sortpayment[]');
addFooterTotal($outputRow,'DEDUCTION');

$outputRow['SUB TOTAL']['value']="";
addCustomName($outputRow,'SUB TOTAL','b_subtotal[]');
addFooterTotal($outputRow,'SUB TOTAL');

$outputRow['TDS']['value']="";
addCustomName($outputRow,'TDS','b_tdsamt[]');
addFooterTotal($outputRow,'TDS');

$outputRow['NET AMOUNT']['value']="";
addCustomName($outputRow,'NET AMOUNT','b_totamount[]');
addFooterTotal($outputRow,'NET AMOUNT');

$rowCount++;
$output['rows'][][] = $outputRow;

	while($row = mysqli_fetch_array($result))
	{


        //if($row['total']>0){
				//$balance=$balance+$row['total'];
				
				//}
			//if($row['paid']>0){
			//	$balance=$balance-$row['paid'];
				
			//	}
			
			//$billbalance = $row[total] -$row[paid];

	
$outputRow = array();



$outputRow['VCH NO']['value']="$row[vchno]";
addCustomName($outputRow,'VCH NO','b_vchno[]');
addFooterCounter($outputRow,'VCH NO');

$outputRow['REF NO']['value']=$row[refno];
addCustomName($outputRow,'REF NO','b_refno[]');

$outputRow['BILL DATE']['value']=date_formatc($row[vchdate]);
addCustomName($outputRow,'BILL DATE','b_vchdate[]');

$outputRow['COMPANY']['value']=$row[comcode];
addCustomName($outputRow,'COMPANY','b_comcode[]');

$outputRow['BILL NO']['value']=$row[bill_no];
addCustomName($outputRow,'BILL NO','b_bill_no[]');

$outputRow['ACCOUNT']['value']=$row[account];
addCustomName($outputRow,'ACCOUNT','b_account[]');

$outputRow['BASIC AMT']['value']=$row[basic_amt];
addCustomName($outputRow,'BASIC AMT','b_basic_amt[]');

$outputRow['TOLL PARKING']['value']=$row[toll_park];
addCustomName($outputRow,'TOLL PARKING','b_toll_park[]');

$outputRow['SERVICE TAX']['value']=$row[ser_tax];
addCustomName($outputRow,'SERVICE TAX','b_ser_tax[]');

$outputRow['K.K.CESS']['value']=$row[educess]; 
addCustomName($outputRow,'K.K.CESS','b_educess[]');
addFooterTotal($outputRow,'K.K.CESS');

$outputRow['S.B.CESS']['value']=$row[seducess];
addCustomName($outputRow,'S.B.CESS','b_seducess[]');
addFooterTotal($outputRow,'S.B.CESS');

$outputRow['MISCAMT']['value']=$row[misamt];
addCustomName($outputRow,'MISCAMT','b_misamt[]');
addFooterTotal($outputRow,'MISCAMT');

$outputRow['AMOUNT']['value']=$row[dramount];
addCustomName($outputRow,'AMOUNT','b_dramount[]');
addFooterTotal($outputRow,'AMOUNT');

$outputRow['DEDUCTION']['value']=$row[sortpayment];
addCustomName($outputRow,'DEDUCTION','b_sortpayment[]');
addFooterTotal($outputRow,'DEDUCTION');

$outputRow['SUB TOTAL']['value']=$row[subtotal];
addCustomName($outputRow,'SUB TOTAL','b_subtotal[]');
addFooterTotal($outputRow,'SUB TOTAL');

$outputRow['TDS']['value']=$row[tdsamt];
addCustomName($outputRow,'TDS','b_tdsamt[]');
addFooterTotal($outputRow,'TDS');

$outputRow['NET AMOUNT']['value']=$row[totamount];
addCustomName($outputRow,'NET AMOUNT','b_totamount[]');
addFooterTotal($outputRow,'NET AMOUNT');


$rowCount++;
$output['rows'][][] = $outputRow;


	$i++;
	//$count_totalbill+=$row[balance];
	}
	//if displayed rows greater than 0 then sum total
	//$count_totalbill=number_format($balance,2);
	

//echo "</tbody></table>### ";
addTotalRows($output,$rowCount);
	}
	else
	$output[error] = mysqli_error($con);
	}
else 
$output[error] = "Please Select Ledger !!!";

echo json_encode($output);
}///
// report for tds end

elseif($_POST['report_type']=="PEDPAYMENT"){
	if(empty($_POST['billedto']))
$qry_part="vchdate between '$from_date' and '$to_date' and fny = '$_SESSION[SESS_FNY]'   order by vchno ";
else
$qry_part="vchdate between '$from_date' and '$to_date' and fny = '$_SESSION[SESS_FNY]'   and comcode='$_POST[billedto]' order by vchno  ";


if($bill_info=mysqli_query($con,"select refno as 'Bill No',vchreg.vchno as 'Vch No',DATE_FORMAT(vchdate,'%d/%m/%Y') as 'Vch Date', comcode as account as Account, paid as Paid, if (paid > 0,totamount- paid, totamount) as Balance,narration as Narration, totamount from vchreg  where vchtype='PURCHASE' and totamount - paid > 0 and $qry_part  "))
{	
//echo "<table  id='table_report_view'  cellspacing='0' width='100%''><thead><th><textarea name='r_billno[]'>Bill No</textarea></th><th width='5%'><textarea name='r_vchno[]'>Vch No</textarea></th><th><textarea name='r_vchdate[]'>Vch Date</textarea></th><th><textarea name='r_account[]'>Account</textarea></th><th><textarea name='r_amount[]'>Amount</textarea></th><th><textarea name='r_paid[]'>Paid</textarea></th><th><textarea name='r_balance[]'>Balance</textarea></th><th width='25%'><textarea name='r_narration[]'>Narration</textarea></th></tr></thead>";

//echo  "<tfoot><tr><td><textarea name='r_billno[]'>Total</textarea></td><td width='5%'><textarea name='r_vchno[]'  count='nor'></textarea></td><td><textarea name='r_vchdate[]'></textarea></td><td><textarea name='r_account[]'></textarea></td><td><textarea name='r_amount[]' style='text-align:center' count='yes'></textarea></td><td><textarea name='r_paid[]' style='text-align:center' count='yes'></textarea></td><td><textarea name='r_balance[]' style='text-align:center' count='yes'></textarea></td><td width='25%'><textarea name='r_narration[]' style='text-align:center' ></textarea></td></tr></tfoot>";
//echo"<tbody>";

$count_totalbill=0;
addTotalRows($output,mysqli_num_rows($bill_info));
while($bill_info_row=mysqli_fetch_array($bill_info))
{
	
   $index = 0;
	foreach ($bill_info_row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$bill_info,$index,$key,'b_',1);
	$index++;
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);
		
	//add Footer Counter to Column
	if($key == 'Bill No')
	{
	addFooterCounter($outputRow,$key);
	}
		
	//add Footer Total to Column
	$totalKeyArray = array('Paid','Balance');
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
	}
	
	$output['rows'][][] = $outputRow;          


//echo  "<tr><td><a href='mastercmpedit.php?compid=$get_cmp_row[billto]' onClick='positionedPopup(this.href,630,350);return false'><textarea name='r_billno[]'>$bill_info_row[billno]</textarea></td></a><td width='5%'><textarea name='r_vchno[]'>$bill_info_row[vchno]</textarea></td><td><textarea name='r_vchdate[]'>$bill_info_row[vchdate]</textarea></td><td><textarea name='r_account[]'>$bill_info_row[account]</textarea></td><td><textarea name='r_amount[]' style='text-align:center'>$bill_info_row[totamount]</textarea></td><td><textarea name='r_paid[]' style='text-align:center'>$bill_info_row[paid]</textarea></td><td><textarea name='r_balance[]' style='text-align:center'>$bill_info_row[balance]</textarea></td><td width='25%'><textarea name='r_narration[]' style='text-align:center'>$bill_info_row[narration]</textarea></td></tr>";
	$count_totalbill+=$bill_info_row[totamount];
	}
	//if displayed rows greater than 0 then sum total
	$count_totalbill=number_format($count_totalbill,2);
//echo "</tbody></table>### ";
}
else
$output[error] = mysqli_error($con);
	
	echo json_encode($output);

}
//outstand salespurchase start
else if($_POST['report_type']=="salepurcsummery")
{
	
	$stRate = '5.8'; //default service tax
	$sqlQry = "select code from master where mstype = 'STP' and `desc` = 'ST RATE' and cmp = '$_SESSION[SESS_CMPC]' and branch= '$_SESSION[SESS_BRANCH]'";
	
	 
 
if($sqlRes=mysqli_query($con,$sqlQry))
 {
		$sqlRow = mysqli_fetch_assoc($sqlRes);
		
		$stRate = $sqlRow[code]; 
	}
 
 $qryPart = "";


 
 if(!empty($_POST[billedto]))
 $qryPart = "and  billedto = '$_POST[billedto]'";
 
	 $sqlQry = "select billedto , count(bookid) as bookidcnt,  sum(tamount) as  salesgamt,sum(Vtamount) as  purcgamt  from $bookingreg where $bookingreg.cmp='$_SESSION[SESS_CMPC]' and $bookingreg.fny = '$_SESSION[SESS_FNY]' and dutydate between '$from_date' and '$to_date' $qryPart  group by billedto"; 
	$rowCount = 0;
	
if (($mas_rec = mysqli_query($con,$sqlQry))) {
    if (mysqli_num_rows($mas_rec) > 0) {
		
		$outputRow = array();
		
		$outputRow['SR. NO']['value'] = '';
		addFooterCounter($outputRow,'SR. NO');
		addCustomName($outputRow,'SR. NO','srno[]');
		
		$outputRow['BILLED TO']['value'] = "";
		addCustomName($outputRow,'BILLED TO','billedto[]');
		
		$outputRow['TOTAL BOOKINGS']['value'] = "";
		addCustomName($outputRow,'TOTAL BOOKINGS','totinv[]');
		
		$outputRow['TOTAL AMOUNT SALES']['value'] = "";
		addCustomName($outputRow,'TOTAL AMOUNT SALES','gsamt[]');
		addFooterTotal($outputRow,'TOTAL AMOUNT SALES');
		
		$outputRow['S. TAX']['value'] = "S A L E S";
		addCustomName($outputRow,'S. TAX','stax[]');
		addFooterTotal($outputRow,'S. TAX');
		
		$outputRow['GROSS AMOUNT SALES']['value'] = "";
		addCustomName($outputRow,'GROSS AMOUNT SALES','nsamt[]');
		addFooterTotal($outputRow,'GROSS AMOUNT SALES');
		
		$outputRow['GROSS AMOUNT PURC']['value'] = "";
		addCustomName($outputRow,'GROSS AMOUNT PURC','gpamt[]');
		addFooterTotal($outputRow,'GROSS AMOUNT PURC');
		
		$outputRow['TDS']['value'] = "P U R C H A S E";
		addCustomName($outputRow,'TDS','tds[]');
		addFooterTotal($outputRow,'TDS');
		
		$outputRow['NET AMOUNT PURC']['value'] = "";
		addCustomName($outputRow,'NET AMOUNT PURC','npamt[]');
		addFooterTotal($outputRow,'NET AMOUNT PURC');
		
		$outputRow['INHOUSE']['value'] = "";	
		addCustomName($outputRow,'INHOUSE','bal[]');
		addFooterTotal($outputRow,'INHOUSE');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
     		
		
        while ($mas_rec_row = mysqli_fetch_assoc($mas_rec)) {
			
		$salesGrossAmt = $mas_rec_row[salesgamt];
		$serTax = $salesGrossAmt*$stRate*0.01;
		$netAmountSales = $salesGrossAmt + $serTax;
		$purcGrossAmt = $mas_rec_row[purcgamt];
		$tdsAmount = $purcGrossAmt*0.01;
		$netAmountPurc = $purcGrossAmt - $tdsAmount;
		$balance = $salesGrossAmt-$purcGrossAmt ;
		
		
		
		$outputRow = array();
		
		$outputRow['SR. NO']['value'] = $rowCount ;
		//addFooterCounter($outputRow,'SI NO');
		addCustomName($outputRow,'SR. NO','srno[]');
		
		$outputRow['BILLED TO']['value'] = "$mas_rec_row[billedto] ";
		addCustomName($outputRow,'BILLED TO','billedto[]');
		addClassName($outputRow,'BILLED TO','billdet_view');
		
		$outputRow['TOTAL BOOKINGS']['value'] = "$mas_rec_row[bookidcnt]";
		addCustomName($outputRow,'TOTAL BOOKINGS','totinv[]');
		
		$outputRow['TOTAL AMOUNT SALES']['value'] = "$salesGrossAmt";
		addCustomName($outputRow,'TOTAL AMOUNT SALES','gsamt[]');
		
		
		$outputRow['S. TAX']['value'] = number_format($serTax,2);
		addCustomName($outputRow,'S. TAX','stax[]');
		
		
		$outputRow['GROSS AMOUNT SALES']['value'] = number_format($netAmountSales,2);
		addCustomName($outputRow,'GROSS AMOUNT SALES','nsamt[]');
		
		$outputRow['GROSS AMOUNT PURC']['value'] = "$purcGrossAmt";
		addCustomName($outputRow,'GROSS AMOUNT PURC','gpamt[]');
		
		$outputRow['TDS']['value'] = "$tdsAmount";
		addCustomName($outputRow,'TDS','tds[]');
		
		$outputRow['NET AMOUNT PURC']['value'] = number_format($netAmountPurc,2);
		addCustomName($outputRow,'NET AMOUNT PURC','npamt[]');
		
		$outputRow['INHOUSE']['value'] = "$balance";	
		addCustomName($outputRow,'INHOUSE','bal[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
	}
   
           
		addTotalRows($output,$rowCount);
    } 
	else
        $output[error] ="No Record Found..";
} else
    $output[error] = mysqli_error($con);
	
	echo json_encode($output);
}
//End salespurchase Summery


//outstand Summery start
else if($_POST['report_type']=="outstandsummery")
{
$cfrecvalue = 0;
$cfbillvalue = 0;
	
$sqlQry="select $billreg.billno as billno,'INVOICE' as ref , DATE_FORMAT(billdate,'%d/%m/%Y') as billdate, total, ''  as totamount,'' as sortpayment , '' as tds  
from $billreg  where total - paid > 0 and billdate>=STR_TO_DATE('$from_date','%Y-%m-%d') and billdate<=STR_TO_DATE('$to_date','%Y-%m-%d')   and $billreg.cmp='$_SESSION[SESS_CMPC]' and $billreg.fny = '$_SESSION[SESS_FNY]' and billto like '$_POST[billedto]' union all select $prebillreg.billno as billno,'INVOICE' as ref ,DATE_FORMAT(billdate,'%d/%m/%Y') as billdate, total, ''  as totamount,'' as sortpayment , '' as tds from $prebillreg where total - paid > 0 and billdate>=STR_TO_DATE('$from_date','%Y-%m-%d') and billdate<=STR_TO_DATE('$to_date','%Y-%m-%d')   and $prebillreg.cmp='$_SESSION[SESS_CMPC]' and $prebillreg.fny = '$prefny' and billto like '$_POST[billedto]'  
union all select  refno, account  as ref,  DATE_FORMAT(vchdate,'%d/%m/%Y') as vchdate,'' as total, totamount,sortpayment as sortpayment, `tdsamt` as tds 
from  vchreg where vchno in (select vchno from vchdetails where paytype in ('Advance','On Account')) and vchreg.cmp='$_SESSION[SESS_CMPC]' and vchreg.fny = '$_SESSION[SESS_FNY]' and comcode like '$_POST[billedto]' and vchtype = 'RECEIPT' order by billdate";
	
	//$output['sql'] = $sqlQry;
	
if (($mas_rec = mysqli_query($con,$sqlQry))) {
    if (mysqli_num_rows($mas_rec) > 0) {
     
		$balance=$cfbillvalue-$cfrecvalue;
		
		
		$outputRow = array();
		
		$outputRow['BILL NO']['value'] = "CF";
		addFooterCounter($outputRow,'BILL NO');
		addCustomName($outputRow,'BILL NO','vchno[]');
		
		$outputRow['DATE']['value'] = "";
		addCustomName($outputRow,'DATE','vchdate[]');
		
		$outputRow['AMOUNT']['value'] = "$cfbillvalue";
		addCustomName($outputRow,'AMOUNT','vchtype[]');
		addFooterTotal($outputRow,'AMOUNT');
		
		$outputRow['RECEIVED']['value'] = "$cfrecvalue";
		addCustomName($outputRow,'RECEIVED','comcode[]');
		addFooterTotal($outputRow,'RECEIVED');
		
		$outputRow['REF']['value'] = "";
		addCustomName($outputRow,'REF','comcode[]');
		
		$outputRow['ON DATE']['value'] = "";
		addCustomName($outputRow,'ON DATE','account[]');
		
		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','refno[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
		

      $netpmt='';
			

        while ($mas_rec_row = mysqli_fetch_array($mas_rec)) {
			
			//$balance=$mas_rec_row['total']-$mas_rec_row['totamount'];
			
			if($mas_rec_row['total']>0){
				$balance=$balance+$mas_rec_row['total'];
				
				}
			if($mas_rec_row['totamount']>0){
				$balance=$balance-$mas_rec_row['totamount'];
				
				}
			
			$billbalance = $mas_rec_row[total] -$mas_rec_row[totamount];
			
			$outputRow = array();
		
		$outputRow['BILL NO']['value'] = $mas_rec_row[billno];
		addFooterCounter($outputRow,'BILL NO');
		addCustomName($outputRow,'BILL NO','vchno[]');
		
		$outputRow['DATE']['value'] =$mas_rec_row[billdate];
		addCustomName($outputRow,'DATE','vchdate[]');
		
		$outputRow['AMOUNT']['value'] = $mas_rec_row[total];
		addCustomName($outputRow,'AMOUNT','vchtype[]');
		addFooterTotal($outputRow,'AMOUNT');
		
		$outputRow['RECEIVED']['value'] =$mas_rec_row[totamount];
		addCustomName($outputRow,'RECEIVED','comcode[]');
		addFooterTotal($outputRow,'RECEIVED');
		
		$outputRow['REF']['value'] = $mas_rec_row[refno];
		addCustomName($outputRow,'REF','comcode[]');
		
		$outputRow['ON DATE']['value'] = $mas_rec_row[vchdate];
		addCustomName($outputRow,'ON DATE','account[]');
		
		$outputRow['BALANCE']['value'] = number_format($billbalance,2);
		addCustomName($outputRow,'BALANCE','refno[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
	
 
      

	}
   
       
      
		addTotalRows($output,$rowCount);
      //  echo "</tbody></table>### ";
    } 
	else
        $output[error] ="No Record Found..";
} else
    $output[error] = mysqli_error($con);
	
	echo json_encode($output);
}
//End outstand Summery



//Debtors Summery start
else if($_POST['report_type']=="debtorssummery")
{

	$getreccfvalue = mysqli_query($con,"SELECT sum(dramount) as cfrec FROM `vchreg` where comcode like '$_POST[billedto]' and  vchdate<STR_TO_DATE('$from_date','%Y-%m-%d') and cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]'  and vchtype='RECEIPT'");
	
	if ($getreccfrow =  mysqli_fetch_assoc($getreccfvalue)){
		$cfrecvalue = $getreccfrow['cfrec'];}
	else{
		$cfrecvalue = 0;}
		
		
		$getbillcfvalue = mysqli_query($con,"SELECT sum(total) as cfbill FROM `$billreg` where billto like '$_POST[billedto]'  and billdate<STR_TO_DATE('$from_date','%Y-%m-%d') and cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]'");
	
	if ($getbillcfrow =  mysqli_fetch_assoc($getbillcfvalue)){
		$cfbillvalue = $getbillcfrow['cfbill'];}
	else{
		$cfbillvalue = 0;}

	
$sqlQry="select $billreg.billno as billno,billto as account , bookregno as ref, DATE_FORMAT(billdate,'%d/%m/%Y')  as bdate, DATE_FORMAT(billdate,'%d/%m/%Y') as billdate, total as billed, ''  as recd,'' as sortpayment , '' as tds 
 from $billreg  
 where billdate>=STR_TO_DATE('$from_date','%Y-%m-%d') and billdate<=STR_TO_DATE('$to_date','%Y-%m-%d')   and $billreg.cmp='$_SESSION[SESS_CMPC]' and $billreg.fny = '$_SESSION[SESS_FNY]' and billto like '$_POST[billedto]' 
 union all 
 select  refno as billno, account, agnstref  as ref, DATE_FORMAT(vchdate,'%d/%m/%Y') as bdate, DATE_FORMAT(vchdate,'%d/%m/%Y') as billdate,'' as billed, totamount as recd,sortpayment as sortpayment, `tdsamt` as tds 
 from  vchreg 
 where vchdate>=STR_TO_DATE('$from_date','%Y-%m-%d') and vchdate<=STR_TO_DATE('$to_date','%Y-%m-%d')   and vchreg.cmp='$_SESSION[SESS_CMPC]' and vchreg.fny = '$_SESSION[SESS_FNY]' and comcode like '$_POST[billedto]' and vchtype = 'RECEIPT' order by bdate";
	
if (($mas_rec = mysqli_query($con,$sqlQry))) {
    if (mysqli_num_rows($mas_rec) > 0) {
    

		$balance=$cfbillvalue-$cfrecvalue;
		

		$outputRow = array();
		$outputRow['BILL NO']['value'] = "CF";
		addCustomName($outputRow,'BILL NO','b_paid[]');
		addFooterCounter($outputRow,'BILL NO');
		
       	$outputRow['ACCOUNT']['value'] = "";
		addCustomName($outputRow,'ACCOUNT','b_paid[]');
		
		
		$outputRow['REF']['value'] = "";
		addCustomName($outputRow,'REF','b_paid[]');
		
		$outputRow['DATE']['value'] = "";
		addCustomName($outputRow,'DATE','b_paid[]');
		
		$outputRow['AMOUNT']['value'] = "$cfbillvalue";
		addCustomName($outputRow,'AMOUNT','b_paid[]');
		addFooterTotal($outputRow,'AMOUNT');
		
		$outputRow['RECEIVED']['value'] = "$cfrecvalue";
		addCustomName($outputRow,'RECEIVED','b_paid[]');
		addFooterTotal($outputRow,'RECEIVED');
		
		$outputRow['DISCOUNT']['value'] = "";
		addCustomName($outputRow,'DISCOUNT','b_paid[]');
		addFooterTotal($outputRow,'DISCOUNT');
		
		$outputRow['TDS']['value'] = "";
		addCustomName($outputRow,'TDS','b_paid[]');
		addFooterTotal($outputRow,'TDS');
		
		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;

      $netpmt='';
			

        while ($mas_rec_row = mysqli_fetch_array($mas_rec)) {
			
			//$balance=$mas_rec_row['billed']-$mas_rec_row['recd'];
			
			if($mas_rec_row['billed']>0){
				$balance=$balance+$mas_rec_row['billed'];
				
				}
			if($mas_rec_row['recd']>0){
				$balance=$balance-($mas_rec_row['recd']+$mas_rec_row['sortpayment']+$mas_rec_row['tds']);
				
				}
			
			$billbalance = $mas_rec_row['billed'] -($mas_rec_row['recd']+$mas_rec_row['sortpayment']+$mas_rec_row['tds']);
			
	
	
		$outputRow = array();
		$outputRow['BILL NO']['value'] = "$mas_rec_row[billno]";
		addCustomName($outputRow,'BILL NO','b_paid[]');
		addFooterCounter($outputRow,'BILL NO');
		
       	$outputRow['ACCOUNT']['value'] = "$mas_rec_row[account]";
		addCustomName($outputRow,'ACCOUNT','b_paid[]');
		
		$outputRow['REF']['value'] = "$mas_rec_row[ref]";
		addCustomName($outputRow,'REF','b_paid[]');
		
		$outputRow['DATE']['value'] = "$mas_rec_row[billdate]";
		addCustomName($outputRow,'DATE','b_paid[]');
		
		$outputRow['AMOUNT']['value'] = "$mas_rec_row[billed]";
		addCustomName($outputRow,'AMOUNT','b_paid[]');
		
		$outputRow['RECEIVED']['value'] = "$mas_rec_row[recd]";
		addCustomName($outputRow,'RECEIVED','b_paid[]');
		
		$outputRow['DISCOUNT']['value'] = "$mas_rec_row[sortpayment]";
		addCustomName($outputRow,'DISCOUNT','b_paid[]');
		
		$outputRow['TDS']['value'] = "$mas_rec_row[tds]";
		addCustomName($outputRow,'TDS','b_paid[]');
		
		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
		
		
          
      

	}
   
      

		$outputRow = array();
		$outputRow['BILL NO']['value'] = "CF";
		addCustomName($outputRow,'BILL NO','b_paid[]');
		addFooterCounter($outputRow,'BILL NO');
		
       	$outputRow['ACCOUNT']['value'] = "";
		addCustomName($outputRow,'ACCOUNT','b_paid[]');
		
		$outputRow['REF']['value'] = "";
		addCustomName($outputRow,'REF','b_paid[]');
		
		$outputRow['DATE']['value'] = "";
		addCustomName($outputRow,'DATE','b_paid[]');
		
		$outputRow['AMOUNT']['value'] = "$cfbillvalue";
		addCustomName($outputRow,'AMOUNT','b_paid[]');
		
		$outputRow['RECEIVED']['value'] = "$cfrecvalue";
		addCustomName($outputRow,'RECEIVED','b_paid[]');
		
		$outputRow['DISCOUNT']['value'] = "";
		addCustomName($outputRow,'DISCOUNT','b_paid[]');
		
		$outputRow['TDS']['value'] = "OutStanding Balance";
		addCustomName($outputRow,'TDS','b_paid[]');
		
		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;


      


		addTotalRows($output,$rowCount);
       // echo "<tbody></table>### ";
    } 
	else
        $output[error] = "No Record Found..";
} else
    echo $output[error] = mysqli_error($con);
	
	echo json_encode($output);
}
//End Debtors Summery


//start Creditors Summery
else if($_POST['report_type']=="creditorssummery")
{

	$getreccfvalue = mysqli_query($con,"SELECT sum(dramount) as cfrec FROM `vchreg` where comcode like '$_POST[billedto]' and  vchdate<STR_TO_DATE('$from_date','%Y-%m-%d') and cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]'  and vchtype = 'PAYMENT'");
	
	if ($getreccfrow =  mysqli_fetch_assoc($getreccfvalue)){
		$cfrecvalue = $getreccfrow['cfrec'];}
	else{
		$cfrecvalue = 0;}
		
		
		$getbillcfvalue = mysqli_query($con,"SELECT sum(dramount) as cfbill FROM `purcreg` where comcode like '$_POST[billedto]'  and vchdate<=STR_TO_DATE('$from_date','%Y-%m-%d') and cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]'  and vchtype = 'PURCHASE'");
	
	if ($getbillcfrow =  mysqli_fetch_assoc($getbillcfvalue)){
		$cfbillvalue = $getbillcfrow['cfbill'];}
	else{
		$cfbillvalue = 0;}

	
$sqlQry="SELECT purcreg.bill_no AS billno, 'INVOICE' as ref , DATE_FORMAT(vchdate,'%d/%m/%Y') AS billdate,  `totamount` AS billed, narration as narration,  '' AS recd,'' as paid, tdsamt as tds,vchtype  FROM purcreg WHERE vchdate >= STR_TO_DATE( '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND purcreg.cmp =  '$_SESSION[SESS_CMPC]' AND purcreg.fny =  '$_SESSION[SESS_FNY]' AND comcode LIKE  '$_POST[billedto]' AND vchtype =  'PURCHASE' UNION ALL SELECT refno as billno, account as ref , DATE_FORMAT(vchdate,'%d/%m/%Y') AS billdate,  totamount  AS billed, narration as narration, '' AS recd,'' as paid, tdsamt as tds,vchtype  FROM vchreg WHERE vchdate >= STR_TO_DATE( '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND vchreg.cmp =  '$_SESSION[SESS_CMPC]' AND vchreg.fny =  '$_SESSION[SESS_FNY]' AND account LIKE  '$_POST[billedto]' AND vchtype =  'JOURNAL' UNION ALL SELECT refno as billno, account as ref , DATE_FORMAT(vchdate,'%d/%m/%Y') AS billdate,  '' AS billed,narration as narration, totamount AS recd,'' as paid, tdsamt as tds,vchtype  FROM vchreg WHERE vchdate >= STR_TO_DATE( '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND vchreg.cmp =  '$_SESSION[SESS_CMPC]' AND vchreg.fny =  '$_SESSION[SESS_FNY]' AND comcode LIKE  '$_POST[billedto]' AND vchtype =  'PAYMENT' UNION ALL SELECT refno as billno, account as ref , DATE_FORMAT(vchdate,'%d/%m/%Y') AS billdate,  '' AS billed, narration as narration,'' as recd, totamount AS paid, tdsamt as tds,vchtype  FROM vchreg WHERE vchdate >= STR_TO_DATE( '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) 
AND vchreg.cmp =  '$_SESSION[SESS_CMPC]' AND vchreg.fny =  '$_SESSION[SESS_FNY]' AND comcode LIKE  '$_POST[billedto]' AND  vchtype  =  'RECEIPT' ORDER BY billdate";
	
	$output['test'] = $sqlQry;
	
if (($mas_rec = mysqli_query($con,$sqlQry))) {
    if (mysqli_num_rows($mas_rec) > 0) {
   

		$balance=$cfbillvalue-$cfrecvalue;


	$outputRow = array();
		$outputRow['BILL NO']['value'] = "CF";
		addCustomName($outputRow,'BILL NO','b_paid[]');
		addFooterCounter($outputRow,'BILL NO');
		
       	$outputRow['ACCOUNT']['value'] = "";
		addCustomName($outputRow,'ACCOUNT','b_paid[]');
		
		$outputRow['REF']['value'] = "";
		addCustomName($outputRow,'REF','b_paid[]');
		
		$outputRow['DATE']['value'] = "$cfbillvalue";
		addCustomName($outputRow,'DATE','b_paid[]');
		
		$outputRow['AMOUNT']['value'] = "$cfrecvalue";
		addCustomName($outputRow,'AMOUNT','b_paid[]');
		
		$outputRow['RECEIVED']['value'] = "$cfrecvalue";
		addCustomName($outputRow,'RECEIVED','b_paid[]');
		
		$outputRow['DISCOUNT']['value'] = "";
		addCustomName($outputRow,'DISCOUNT','b_paid[]');
		
		$outputRow['TDS']['value'] = "";
		addCustomName($outputRow,'TDS','b_paid[]');
		
		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		$outputRow['NARRATION']['value'] = "$balance";
		addCustomName($outputRow,'NARRATION','b_paid[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
			
      $netpmt='';
			

        while ($mas_rec_row = mysqli_fetch_array($mas_rec)) {
			
			$billbalance=$mas_rec_row['billed']-($mas_rec_row['recd']+$mas_rec_row['tds']);
			
			if($mas_rec_row['billed']>0){
				$balance=$balance+$mas_rec_row['billed'];
				
				}
			if($mas_rec_row['recd']>0){
				$balance=$balance-($mas_rec_row['recd']+$mas_rec_row['tds']);
				
				}
				if($mas_rec_row['paid']>0){
				$balance=$balance+$mas_rec_row['paid']+$mas_rec_row['tds'];
				
				}
					$outputRow = array();
		$outputRow['BILL NO']['value'] = "$mas_rec_row[billno]";
		addCustomName($outputRow,'BILL NO','b_paid[]');
		addFooterCounter($outputRow,'BILL NO');
		
       	$outputRow['ACCOUNT']['value'] = "$mas_rec_row[account]";
		addCustomName($outputRow,'ACCOUNT','b_paid[]');
		
		$outputRow['REF']['value'] = "$mas_rec_row[ref]";
		addCustomName($outputRow,'REF','b_paid[]');
		
		$outputRow['DATE']['value'] = "$mas_rec_row[billdate]";
		addCustomName($outputRow,'DATE','b_paid[]');
		
		$outputRow['AMOUNT']['value'] = "$mas_rec_row[billed]";
		addCustomName($outputRow,'AMOUNT','b_paid[]');
		
		$outputRow['RECEIVED']['value'] = "$mas_rec_row[recd]";
		addCustomName($outputRow,'RECEIVED','b_paid[]');
		
		$outputRow['DISCOUNT']['value'] = "$mas_rec_row[sortpayment]";
		addCustomName($outputRow,'DISCOUNT','b_paid[]');
		
		$outputRow['TDS']['value'] = "$mas_rec_row[tds]";
		addCustomName($outputRow,'TDS','b_paid[]');
		
		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		$outputRow['NARRATION']['value'] = "$mas_rec_row[narration]";
		addCustomName($outputRow,'NARRATION','b_paid[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
			
		}//while ($mas_rec_row = mysqli_fetch_array($mas_rec)) {
		
		
	
		$outputRow = array();
		$outputRow['BILL NO']['value'] = "";
		addCustomName($outputRow,'BILL NO','b_paid[]');
		addFooterCounter($outputRow,'BILL NO');
		
       	$outputRow['ACCOUNT']['value'] = "";
		addCustomName($outputRow,'ACCOUNT','b_paid[]');
		
		$outputRow['REF']['value'] = "";
		addCustomName($outputRow,'REF','b_paid[]');
		
		$outputRow['DATE']['value'] = "";
		addCustomName($outputRow,'DATE','b_paid[]');
		
		$outputRow['AMOUNT']['value'] = "";
		addCustomName($outputRow,'AMOUNT','b_paid[]');
		
		$outputRow['RECEIVED']['value'] = "";
		addCustomName($outputRow,'RECEIVED','b_paid[]');
		
		$outputRow['DISCOUNT']['value'] = "";
		addCustomName($outputRow,'DISCOUNT','b_paid[]');
		
		$outputRow['TDS']['value'] = "Total Balance";
		addCustomName($outputRow,'TDS','b_paid[]');
		
		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		$outputRow['NARRATION']['value'] = "";
		addCustomName($outputRow,'NARRATION','b_paid[]');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;

        
        addTotalRows($output,$rowCount);
    }// if (mysqli_num_rows($mas_rec) > 0) 
	else
        $output[error] = "No Record Found..";
} 
else
     echo $output[error] = mysqli_error($con);
	
	echo json_encode($output);
	}
//End Creditors Summery




//start expense Summery
else if($_POST['report_type']=="expensesummery")
{
	//AND comcode like '$_POST[billedto]'

//AND account like '$_POST[billedto]'

if(empty($_POST['billedto'])){
$qry_part="";
$qry_partacc="";}
else{
$qry_part="AND comcode like '$_POST[billedto]'";
$qry_partacc="AND account like '$_POST[billedto]'";}

$sqlQry="SELECT vchno, purcreg.refno AS billno,  'INVOICE' AS ref, comcode as account,  DATE_FORMAT(vchdate,'%d/%m/%Y') AS billdate, narration,  `totamount` AS billed FROM purcreg WHERE vchdate >= STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) $qry_partacc AND purcreg.cmp = '$_SESSION[SESS_CMPC]' AND purcreg.fny = '$_SESSION[SESS_FNY]' AND account like '$_POST[billedto]' AND vchtype =  'PURCHASE' UNION ALL SELECT vchno, refno AS billno, account AS ref, comcode as account, DATE_FORMAT(vchdate,'%d/%m/%Y') AS billdate, narration, totamount AS billed FROM vchreg WHERE vchdate >= STR_TO_DATE('$from_date',  '%Y-%m-%d')  AND vchdate <= STR_TO_DATE( '$to_date',  '%Y-%m-%d' ) $qry_part AND vchreg.cmp =  '$_SESSION[SESS_CMPC]' AND vchreg.fny =  '$_SESSION[SESS_FNY]'  AND  vchtype in ('PAYMENT','JOURNAL')  ORDER BY billdate, vchno";

	
	
if (($mas_rec = mysqli_query($con,$sqlQry))) {
    if (mysqli_num_rows($mas_rec) > 0) {

		$balance=$cfbillvalue-$cfrecvalue;

		$outputRow = array();
		$outputRow['Vchno']['value'] = "CF";
		addCustomName($outputRow,'Vchno','b_paid[]');
		addFooterCounter($outputRow,'BILL NO');
		
       		$outputRow['Billno']['value'] = "";
		addCustomName($outputRow,'Billno','b_paid[]');
		
		$outputRow['REF']['value'] = "";
		addCustomName($outputRow,'REF','b_paid[]');
		
		$outputRow['Account']['value'] = "";
		addCustomName($outputRow,'Account','b_paid[]');
		
		$outputRow['Billdate']['value'] = "$cfbillvalue";
		addCustomName($outputRow,'Billdate','b_paid[]');
		
		$outputRow['Narration']['value'] = "$cfrecvalue";
		addCustomName($outputRow,'Narration','b_paid[]');
		
		$outputRow['Billed']['value'] = "";
		addCustomName($outputRow,'Billed','b_paid[]');
		
		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
		
			
      $netpmt='';
			

        while ($mas_rec_row = mysqli_fetch_array($mas_rec)) {
			
			if($mas_rec_row['billed']>0){
				$balance=$balance+$mas_rec_row['billed'];
				
				}

		$outputRow = array();
		$outputRow['Vchno']['value'] = "$mas_rec_row[vchno]";
		addCustomName($outputRow,'Vchno','b_paid[]');
		addFooterCounter($outputRow,'BILL NO');
		
       		$outputRow['Billno']['value'] = "$mas_rec_row[billno]";
		addCustomName($outputRow,'Billno','b_paid[]');
		
		$outputRow['REF']['value'] = "$mas_rec_row[ref]";
		addCustomName($outputRow,'REF','b_paid[]');
		
		$outputRow['Account']['value'] = "$mas_rec_row[account]";
		addCustomName($outputRow,'Account','b_paid[]');
		
		$outputRow['Billdate']['value'] = "$mas_rec_row[billdate]";
		addCustomName($outputRow,'Billdate','b_paid[]');
		
		$outputRow['Narration']['value'] = "$mas_rec_row[narration]";
		addCustomName($outputRow,'Narration','b_paid[]');
		
		$outputRow['Billed']['value'] = "$mas_rec_row[billed]";
		addCustomName($outputRow,'Billed','b_paid[]');
		
		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
  }


		
				$outputRow = array();
		$outputRow['Vchno']['value'] = "";
		addCustomName($outputRow,'Vchno','b_paid[]');
		addFooterCounter($outputRow,'BILL NO');
		
       		$outputRow['Billno']['value'] = "";
		addCustomName($outputRow,'Billno','b_paid[]');
		
		$outputRow['REF']['value'] = "";
		addCustomName($outputRow,'REF','b_paid[]');
		
		$outputRow['Account']['value'] = "";
		addCustomName($outputRow,'Account','b_paid[]');
		
		$outputRow['Billdate']['value'] = "";
		addCustomName($outputRow,'Billdate','b_paid[]');
		
		$outputRow['Narration']['value'] = "";
		addCustomName($outputRow,'Narration','b_paid[]');
		
		$outputRow['Billed']['value'] = "Total Balance";
		addCustomName($outputRow,'Billed','b_paid[]');
		
		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
		
        addTotalRows($output,$rowCount);
    } 
	else
          $output[error] = "No Record Found..";
} else
   $output[error] = mysqli_error($con);
	
	echo json_encode($output);
	}
//End expense Summery



//start cashbank Summery
else if($_POST['report_type']=="cashbanksummery")
{
	
	$getreccfvalue = mysqli_query($con,"SELECT sum(dramount) as cfrec FROM `vchreg` where comcode like '$_POST[billedto]' and  vchdate<STR_TO_DATE('$from_date','%Y-%m-%d') and cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]' AND Account LIKE  '$_POST[billedto]' and vchtype='RECEIPT'");
	
	if ($getreccfrow =  mysqli_fetch_assoc($getreccfvalue)){
		$cfrecvalue = $getreccfrow['cfrec'];}
	else{
		$cfrecvalue = 0;}
		
		
		$getbillcfvalue = mysqli_query($con,"SELECT sum(dramount) as cfbill FROM `vchreg` where comcode like '$_POST[billedto]'  and vchdate<STR_TO_DATE('$to_date','%Y-%m-%d') and cmp = '$_SESSION[SESS_CMPC]' and fny = '$_SESSION[SESS_FNY]' AND Account LIKE  '$_POST[billedto]' and vchtype='PAYMENT'");
	
	if ($getbillcfrow =  mysqli_fetch_assoc($getbillcfvalue)){
		$cfbillvalue = $getbillcfrow['cfbill'];}
	else{
		$cfbillvalue = 0;}

	
$sqlQry="SELECT vchno,  `vchdate` AS billdate, vchreg.refno AS inst, comcode AS ref, narration,  `totamount` AS recd,  '' AS paid FROM vchreg WHERE vchdate >= STR_TO_DATE( '$from_date',  '%Y-%m-%d' )  AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND vchreg.cmp =  '$_SESSION[SESS_CMPC]' AND vchreg.fny =  '$_SESSION[SESS_FNY]' AND Account LIKE  '$_POST[billedto]' AND vchtype =  'RECEIPT' UNION ALL SELECT vchno,  `vchdate` AS billdate, vchreg.refno AS inst, comcode AS ref, narration,  `totamount`  AS recd, '' AS paid FROM vchreg WHERE vchdate >= STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND vchreg.cmp = '$_SESSION[SESS_CMPC]' AND vchreg.fny =  '$_SESSION[SESS_FNY]' AND ACCOUNT LIKE  '$_POST[billedto]' AND vchtype =  'CONTRA' UNION ALL SELECT vchno,  `vchdate` AS billdate, vchreg.refno AS inst, comcode AS ref, narration,  '' AS recd,  `totamount` AS paid FROM vchreg WHERE vchdate >= STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND vchreg.cmp = '$_SESSION[SESS_CMPC]' AND vchreg.fny =  '$_SESSION[SESS_FNY]' AND ACCOUNT LIKE  '$_POST[billedto]' AND vchtype =  'PAYMENT' UNION ALL SELECT vchno,  `vchdate` AS billdate, vchreg.refno AS inst, comcode AS ref, narration,  '' AS recd,  `totamount` AS paid FROM vchreg WHERE vchdate >= STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND vchreg.cmp = '$_SESSION[SESS_CMPC]' AND vchreg.fny =  '$_SESSION[SESS_FNY]' AND comcode LIKE  '$_POST[billedto]' AND vchtype =  'CONTRA' ORDER BY billdate , vchno";


	
	$output['query'][][]= $sqlQry;
	
if (($mas_rec = mysqli_query($con,$sqlQry))) {
    if (mysqli_num_rows($mas_rec) > 0) {
		
		
        /*echo "<table id='table_report_view'  width='100%' cellspacing='0'><thead><tr>
		<th width='8%'>VCHNO</th>
		<th width='10%'>BILLDATE</th>
		<th width='8%'>INST NO</th>
		<th width='8%'>REF</th>
		<th width='18%'>NARRATIONS</th>
		<th width='13%'>RECD</th>
		<th width='10%'>PAID</th>
		<th width='10%'>BALANCE</th>
		</tr></thead>";

		  echo "<tfoot><tr>
		<td width='8%'><textarea name='vchno' class='vchno'>TOTAL</textarea></td>
		<td width='10%'><textarea name='comcode' class='comcode' count='nor'></textarea></td>			
		<td width='8%'><textarea name='vchdate' class='vchdate' ></textarea></td>
		<td width='8%'><textarea name='vchtype' class='vchtype' ></textarea></td>
		<td width='18%'><textarea name='comcode' class='comcode' ></textarea></td>
		<td width='13%'><textarea name='sortpayment' class='sortpayment' count='yes'></textarea></td>
		<td width='10%'><textarea name='account' class='account' count='yes'></textarea></td>
		<td width='10%'><textarea name='refno' class='refno'></textarea></td>
		</tr></tfoot>";
		echo "<tbody>";*/

		$balance=$cfbillvalue-$cfrecvalue;
		
		$outputRow = output();
		$outputRow['VCHNO']['value'] = "CF";
		addCustomName($outputRow,'VCHNO','b_paid[]');
		addFooterCounter($outputRow,'VCHNO');
		
       		$outputRow['BILLDATE']['value'] = "";
		addCustomName($outputRow,'BILLDATE','b_paid[]');
		
		$outputRow['INST NO']['value'] = "";
		addCustomName($outputRow,'INST NO','b_paid[]');
		
		$outputRow['REF']['value'] = "";
		addCustomName($outputRow,'REF','b_paid[]');
		
		$outputRow['NARRATIONS']['value'] = "";
		addCustomName($outputRow,'NARRATIONS','b_paid[]');
		
		$outputRow['RECD']['value'] = "";
		addCustomName($outputRow,'RECD','b_paid[]');
		
		$outputRow['PAID']['value'] = "";
		addCustomName($outputRow,'PAID','b_paid[]');
		
		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		
		$output['rows'][][] = $outputRow;
		$rowCount++;

		/*	echo "<tr>
<td width='8%'><textarea name='vchno' class='vchno'>CF</textarea></td>
<td width='10%'><textarea name='comcode' class='comcode'></textarea></td>			
<td width='8%'><textarea name='vchdate' class='vchdate' ></textarea></td>
<td width='8%'><textarea name='vchtype' class='vchtype' $statusStyle>$cfbillvalue</textarea></td>
<td width='18%'><textarea name='comcode' class='comcode'>$cfrecvalue</textarea></td>
<td width='13%'><textarea name='account' class='account'></textarea></td>
<td width='10%'><textarea name='account' class='account'></textarea></td>
<td width='10%'><textarea name='refno' class='refno'>$balance</textarea></td>

</tr>";*/
      $netpmt='';
			

        while ($mas_rec_row = mysqli_fetch_array($mas_rec)) {
			
		
			
			if($mas_rec_row['recd']>0){
				$balance=$balance+$mas_rec_row['recd'];
				
				}
			if($mas_rec_row['paid']>0){
				$balance=$balance-$mas_rec_row['paid'];
				
				}
			$outputRow = output();
		$outputRow['VCHNO']['value'] = "$mas_rec_row[vchno]";
		addCustomName($outputRow,'VCHNO','b_paid[]');
		addFooterCounter($outputRow,'VCHNO');
		
       		$outputRow['BILLDATE']['value'] = "$mas_rec_row[billdate]";
		addCustomName($outputRow,'BILLDATE','b_paid[]');
		
		$outputRow['INST NO']['value'] = "$mas_rec_row[inst]";
		addCustomName($outputRow,'INST NO','b_paid[]');
		
		$outputRow['REF']['value'] = "$mas_rec_row[ref]";
		addCustomName($outputRow,'REF','b_paid[]');
		
		$outputRow['NARRATIONS']['value'] = "$mas_rec_row[narration]";
		addCustomName($outputRow,'NARRATIONS','b_paid[]');
		
		$outputRow['RECD']['value'] = "$mas_rec_row[recd]";
		addCustomName($outputRow,'RECD','b_paid[]');
		
		$outputRow['PAID']['value'] = "$mas_rec_row[paid]";
		addCustomName($outputRow,'PAID','b_paid[]');
		
		$outputRow['BALANCE']['value'] = "$balance]";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
			
			
	
     /* echo "<tr>
<td width='8%'><textarea name='vchno' class='vchno'>$mas_rec_row[vchno]</textarea></td>
<td width='10%'><textarea name='comcode' class='comcode'>$mas_rec_row[billdate]</textarea></td>			
<td width='8%'><textarea name='vchdate' class='vchdate' >$mas_rec_row[inst]</textarea></td>
<td width='8%'><textarea name='vchtype' class='vchtype' $statusStyle>$mas_rec_row[ref]</textarea></td>
<td width='18%'><textarea name='comcode' class='comcode'>$mas_rec_row[narration]</textarea></td>
<td width='13%'><textarea name='account' class='account'>$mas_rec_row[recd]</textarea></td>
<td width='10%'><textarea name='account' class='account'>$mas_rec_row[paid]</textarea></td>
<td width='10%'><textarea name='refno' class='refno'>$balance</textarea></td>

</tr>";*/
      
      

	}
	
	$balance=$cfbillvalue-$cfrecvalue;
		
		$outputRow = output();
		$outputRow['VCHNO']['value'] = "";
		addCustomName($outputRow,'VCHNO','b_paid[]');
		addFooterCounter($outputRow,'VCHNO');
		
       		$outputRow['BILLDATE']['value'] = "";
		addCustomName($outputRow,'BILLDATE','b_paid[]');
		
		$outputRow['INST NO']['value'] = "";
		addCustomName($outputRow,'INST NO','b_paid[]');
		
		$outputRow['REF']['value'] = "";
		addCustomName($outputRow,'REF','b_paid[]');
		
		$outputRow['NARRATIONS']['value'] = "";
		addCustomName($outputRow,'NARRATIONS','b_paid[]');
		
		$outputRow['RECD']['value'] = "";
		addCustomName($outputRow,'RECD','b_paid[]');
		
		$outputRow['PAID']['value'] = "Total Balance";
		addCustomName($outputRow,'PAID','b_paid[]');
		
		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		
		$output['rows'][][] = $outputRow;
		$rowCount++;

       /*  echo "<tr>
<td width='8%'><textarea name='vchno' class='vchno'> </textarea></td>			
<td width='10%'><textarea name='comcode' class='comcode'> </textarea></td>
<td width='8%'><textarea name='vchdate' class='vchdate' > </textarea></td>
<td width='8%'><textarea name='vchtype' class='vchtype' $statusStyle> </textarea></td>
<td width='18%'><textarea name='comcode' class='comcode'> </textarea></td>
<td width='13%'><textarea name='comcode' class='comcode'> </textarea></td>
<td width='10%'><textarea name='account' class='account'>Total Balance</textarea></td>
<td width='10%'><textarea name='refno' class='refno'>$balance</textarea></td>

</tr>";*/
        addTotalRows($output,$rowCount);
    } 
	else
        $output[error] = "No Record Found..";
} else
    echo $output[error] = mysqli_error($con);
	
	echo json_encode($output);
	}
//End cashbank Summery







//start servicestaxsummery Summery
else if($_POST['report_type']=="servicestaxsummery")
{   
  
		
	if($_POST['billedto']=="SERVICE TAX RECD FROM CLIENT"){
		$sqlQry="SELECT srno as vchno,  billno, DATE_FORMAT(billdate,'%d/%m/%Y') as billdate, billto as billedto,totalamt as billamt, sramount, educess, seducess, sramount + educess + seducess AS total,  '' AS paid FROM $billreg inner join commst on $billreg.billto=commst.compid   where $billreg.optstax=1 AND billdate >= STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND billdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND $billreg.cmp = '$_SESSION[SESS_CMPC]' AND $billreg.fny =  '$_SESSION[SESS_FNY]'
UNION ALL SELECT vchno, bill_no AS billno, DATE_FORMAT(vchdate,'%d/%m/%Y') as billdate, account AS billedto, '' as billamt,  totamount AS sramount,  '' AS educess,  '' AS seducess,  '' AS total, totamount AS paid
FROM vchreg WHERE  vchdate >= STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND vchreg.cmp = '$_SESSION[SESS_CMPC]' AND vchreg.fny =  '$_SESSION[SESS_FNY]' AND comcode = 'SERVICE TAX RECD  FROM CLIENT' ORDER BY billdate";
			}
	elseif($_POST['billedto']=="SERVICE TAX PAID TO CLIENT"){
		$sqlQry="SELECT refno as vchno, bill_no as billno, DATE_FORMAT(vchdate,'%d/%m/%Y') as billdate, comcode as billedto,basic_amt as billamt, '' AS sramount, '' as educess, '' as seducess, ser_tax AS total,  '' AS paid FROM purcreg   where  vchdate >= STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND purcreg.cmp = '$_SESSION[SESS_CMPC]' AND purcreg.fny =  '$_SESSION[SESS_FNY]'
UNION ALL SELECT vchno, bill_no AS billno, DATE_FORMAT(vchdate,'%d/%m/%Y') as billdate, comcode AS billedto,'' as billamt,   '' AS sramount,  '' AS educess,  '' AS seducess,  '' AS total, totamount AS paid
FROM vchreg WHERE  vchdate >= STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND vchreg.cmp = '$_SESSION[SESS_CMPC]' AND vchreg.fny =  '$_SESSION[SESS_FNY]' AND account = 'SERVICE TAX PAID TO CLIENT' ORDER BY billdate";
						}
else{
$sqlQry="SELECT srno as vchno,  billno, DATE_FORMAT(billdate,'%d/%m/%Y') as billdate, billto as billedto,totalamt as billamt, sramount, educess, seducess, sramount + educess + seducess AS total,  '' AS paid FROM $billreg inner join commst on $billreg.billto=commst.compid   where $billreg.optstax=1 AND billdate >= STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND billdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND $billreg.cmp = '$_SESSION[SESS_CMPC]' AND $billreg.fny =  '$_SESSION[SESS_FNY]'
UNION ALL SELECT refno as vchno, bill_no as billno, DATE_FORMAT(vchdate,'%d/%m/%Y') as billdate, comcode as billedto,basic_amt as billamt,'' AS sramount, '' as educess, '' as seducess, '' AS total,  ser_tax AS paid FROM purcreg   where  vchdate >= STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND purcreg.cmp = '$_SESSION[SESS_CMPC]' AND purcreg.fny =  '$_SESSION[SESS_FNY]'
UNION ALL SELECT vchno, bill_no AS billno, DATE_FORMAT(vchdate,'%d/%m/%Y') as billdate, comcode AS billedto, basic_amt as billamt,  '' AS sramount,  '' AS educess,  '' AS seducess,  '' AS total, totamount AS paid
FROM vchreg WHERE  vchdate >= STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND vchreg.cmp = '$_SESSION[SESS_CMPC]' AND vchreg.fny =  '$_SESSION[SESS_FNY]' AND comcode = 'SERVICE TAX RECD FROM CLIENT'  and vchtype LIKE 'PAYMENT' ORDER BY billdate";
}
//echo $sqlQry;	
if (($mas_rec = mysqli_query($con,$sqlQry))) {
    if (mysqli_num_rows($mas_rec) > 0) {
      

		$balance=$cfbillvalue-$cfrecvalue;


			$outputRow = array();
		$outputRow['VCHNO']['value'] = "CF";
		addCustomName($outputRow,'VCHNO','b_paid[]');
		addFooterCounter($outputRow,'VCHNO');
		
       		$outputRow['BILLNO']['value'] = "";
		addCustomName($outputRow,'BILLNO','b_paid[]');
		
		$outputRow['BILLDATE']['value'] = "";
		addCustomName($outputRow,'BILLDATE','b_paid[]');
		
		$outputRow['BILLEDTO']['value'] = "$cfbillvalue";
		addCustomName($outputRow,'BILLEDTO','b_paid[]');
		
		$outputRow['BILL AMT.']['value'] = "";
		addCustomName($outputRow,'BILL AMT.','b_paid[]');
		addFooterTotal($outputRow,'BILL AMT.');
		
		$outputRow['SRAMOUNT']['value'] = "$cfrecvalue";
		addCustomName($outputRow,'SRAMOUNT','b_paid[]');
		addFooterTotal($outputRow,'SRAMOUNT');
		
		$outputRow['K.K.CESS']['value'] = "";
		addCustomName($outputRow,'K.K.CESS','b_paid[]');
		addFooterTotal($outputRow,'K.K.CESS');
		
		$outputRow['S.B.CESS']['value'] = "";
		addCustomName($outputRow,'S.B.CESS','b_paid[]');
		addFooterTotal($outputRow,'S.B.CESS');
		
		$outputRow['TOTAL']['value'] = "";
		addCustomName($outputRow,'TOTAL','b_paid[]');
        addFooterTotal($outputRow,'TOTAL');
		
		$outputRow['PAID']['value'] = "";
		addCustomName($outputRow,'PAID','b_paid[]');
        addFooterTotal($outputRow,'PAID');
		
		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
			
      $netpmt='';
			


        while ($mas_rec_row = mysqli_fetch_array($mas_rec)) {
			
		$billbalance=$mas_rec_row['total']-$mas_rec_row['paid'];
			
			if($mas_rec_row['total']>0){
				$balance=$balance+$mas_rec_row['total'];
				
				}
			if($mas_rec_row['paid']>0){
				$balance=$balance-$mas_rec_row['paid'];
				
				}
			
					$outputRow = array();
		$outputRow['VCHNO']['value'] = "$mas_rec_row[vchno]";
		addCustomName($outputRow,'VCHNO','b_paid[]');
		addFooterCounter($outputRow,'VCHNO');
		
       		$outputRow['BILLNO']['value'] = "$mas_rec_row[billno]";
		addCustomName($outputRow,'BILLNO','b_paid[]');
		
		$outputRow['BILLDATE']['value'] = "$mas_rec_row[billdate]";
		addCustomName($outputRow,'BILLDATE','b_paid[]');
		
		$outputRow['BILLEDTO']['value'] = "$mas_rec_row[billedto]";
		addCustomName($outputRow,'BILLEDTO','b_paid[]');
		
		$outputRow['BILL AMT.']['value'] = "$mas_rec_row[billamt]";
		addCustomName($outputRow,'BILL AMT.','b_paid[]');
		
		$outputRow['SRAMOUNT']['value'] = "$mas_rec_row[sramount]";
		addCustomName($outputRow,'SRAMOUNT','b_paid[]');
		
		$outputRow['K.K.CESS']['value'] = "$mas_rec_row[educess]";
		addCustomName($outputRow,'K.K.CESS','b_paid[]');
		
		$outputRow['S.B.CESS']['value'] = "$mas_rec_row[seducess]";
		addCustomName($outputRow,'S.B.CESS','b_paid[]');
		
		$outputRow['TOTAL']['value'] = "$mas_rec_row[total]";
		addCustomName($outputRow,'TOTAL','b_paid[]');

		$outputRow['PAID']['value'] = "$mas_rec_row[paid]";
		addCustomName($outputRow,'PAID','b_paid[]');

		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
			
	
    
      
      

	}
	
			$outputRow = array();
		$outputRow['VCHNO']['value'] = "";
		addCustomName($outputRow,'VCHNO','b_paid[]');
		addFooterCounter($outputRow,'VCHNO');
		
       		$outputRow['BILLNO']['value'] = "";
		addCustomName($outputRow,'BILLNO','b_paid[]');
		
		$outputRow['BILLDATE']['value'] = "";
		addCustomName($outputRow,'BILLDATE','b_paid[]');
		
		$outputRow['BILLEDTO']['value'] = "$cfbillvalue";
		addCustomName($outputRow,'BILLEDTO','b_paid[]');
		
		$outputRow['BILL AMT.']['value'] = "$cfrecvalue";
		addCustomName($outputRow,'BILL AMT.','b_paid[]');
		
		$outputRow['SRAMOUNT']['value'] = "$cfrecvalue";
		addCustomName($outputRow,'SRAMOUNT','b_paid[]');
		
		$outputRow['K.K.CESS']['value'] = "";
		addCustomName($outputRow,'K.K.CESS','b_paid[]');
		
		$outputRow['S.B.CESS']['value'] = "";
		addCustomName($outputRow,'S.B.CESS','b_paid[]');
		
		$outputRow['TOTAL']['value'] = "";
		addCustomName($outputRow,'TOTAL','b_paid[]');

		$outputRow['PAID']['value'] = "Total Balance";
		addCustomName($outputRow,'PAID','b_paid[]');

		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		
		$output['rows'][][] = $outputRow;
		$rowCount++;

   
       addTotalRows($output,$rowCount);
    } 
	else
          $output[error] = "No Record Found..";
} else
    $output[error] = mysqli_error($con);
	
	echo json_encode($output);
	}
//End servicestaxsummery Summery



//start servicestaxsummery Summery
else if($_POST['report_type']=="servicetax")
{   
  
		
	
$sqlQry="SELECT srno as vchno,  billno, DATE_FORMAT(billdate,'%d/%m/%Y') as billdate, billto as billedto,totalamt as billamt, sramount, educess as educess, seducess as seducess, sramount + educess + seducess AS total,  '' AS paid FROM $billreg inner join commst on $billreg.billto=commst.compid   where $billreg.optstax=1 AND billdate >= STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND billdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND $billreg.cmp = '$_SESSION[SESS_CMPC]' AND $billreg.fny =  '$_SESSION[SESS_FNY]' UNION ALL SELECT refno as vchno, bill_no as billno, DATE_FORMAT(vchdate,'%d/%m/%Y') as billdate, comcode as billedto,basic_amt as billamt,'' AS ser_tax, educess as educess, seducess as seducess, ser_tax + educess + seducess AS total,  ser_tax AS paid FROM purcreg   where  vchdate >= STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND purcreg.cmp = '$_SESSION[SESS_CMPC]' AND purcreg.fny =  '$_SESSION[SESS_FNY]' UNION ALL SELECT vchno, bill_no AS billno, DATE_FORMAT(vchdate,'%d/%m/%Y') as billdate, comcode AS billedto, basic_amt as billamt,  '' AS sramount,  '' AS educess,  '' AS seducess,  '' AS total, totamount AS paid FROM vchreg WHERE  vchdate >= STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND vchreg.cmp = '$_SESSION[SESS_CMPC]' AND vchreg.fny =  '$_SESSION[SESS_FNY]' AND comcode = 'SERVICE TAX RECD FROM CLIENT'  and vchtype LIKE 'PAYMENT' ORDER BY billdate";

//echo $sqlQry;	
if (($mas_rec = mysqli_query($con,$sqlQry))) {
    if (mysqli_num_rows($mas_rec) > 0) {
      

		$balance=$cfbillvalue-$cfrecvalue;


			$outputRow = array();
		$outputRow['VCHNO']['value'] = "CF";
		addCustomName($outputRow,'VCHNO','b_paid[]');
		addFooterCounter($outputRow,'VCHNO');
		
       		$outputRow['BILLNO']['value'] = "";
		addCustomName($outputRow,'BILLNO','b_paid[]');
		
		
		$outputRow['BILLDATE']['value'] = "";
		addCustomName($outputRow,'BILLDATE','b_paid[]');

		
		$outputRow['BILLEDTO']['value'] = "$cfbillvalue";
		addCustomName($outputRow,'BILLEDTO','b_paid[]');
		
		$outputRow['BILL AMT.']['value'] = "";
		addCustomName($outputRow,'BILL AMT.','b_paid[]');
		addFooterTotal($outputRow,'BILL AMT.');
		
		$outputRow['SRAMOUNT']['value'] = "$cfrecvalue";
		addCustomName($outputRow,'SRAMOUNT','b_paid[]');
		addFooterTotal($outputRow,'SRAMOUNT');
		
		$outputRow['S.B.CESS']['value'] = "";
		addCustomName($outputRow,'S.B.CESS','b_paid[]');
		addFooterTotal($outputRow,'S.B.CESS');
		
		$outputRow['K.K.CESS']['value'] = "";
		addCustomName($outputRow,'K.K.CESS','b_paid[]');
		addFooterTotal($outputRow,'K.K.CESS');
		
		$outputRow['TOTAL']['value'] = "";
		addCustomName($outputRow,'TOTAL','b_paid[]');
        addFooterTotal($outputRow,'TOTAL');
		
		$outputRow['PAID']['value'] = "";
		addCustomName($outputRow,'PAID','b_paid[]');
		

		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
			
      $netpmt='';
			


        while ($mas_rec_row = mysqli_fetch_array($mas_rec)) {
			
		$billbalance=$mas_rec_row['total']-$mas_rec_row['paid'];
			
			if($mas_rec_row['total']>0){
				$balance=$balance+$mas_rec_row['total'];
				
				}
			if($mas_rec_row['paid']>0){
				$balance=$balance-$mas_rec_row['paid'];
				
				}
			
					$outputRow = array();
		$outputRow['VCHNO']['value'] = "$mas_rec_row[vchno]";
		addCustomName($outputRow,'VCHNO','b_paid[]');
		addFooterCounter($outputRow,'VCHNO');
		
       		$outputRow['BILLNO']['value'] = "$mas_rec_row[billno]";
		addCustomName($outputRow,'BILLNO','b_paid[]');
		
		$outputRow['BILLDATE']['value'] = "$mas_rec_row[billdate]";
		addCustomName($outputRow,'BILLDATE','b_paid[]');
		
		$outputRow['BILLEDTO']['value'] = "$mas_rec_row[billedto]";
		addCustomName($outputRow,'BILLEDTO','b_paid[]');
		
		$outputRow['BILL AMT.']['value'] = "$mas_rec_row[billamt]";
		addCustomName($outputRow,'BILL AMT.','b_paid[]');
		
		$outputRow['SRAMOUNT']['value'] = "$mas_rec_row[sramount]";
		addCustomName($outputRow,'SRAMOUNT','b_paid[]');
		
		$outputRow['S.B.CESS']['value'] = "$mas_rec_row[educess]";
		addCustomName($outputRow,'S.B.CESS','b_paid[]');
		
		$outputRow['K.K.CESS']['value'] = "$mas_rec_row[seducess]";
		addCustomName($outputRow,'K.K.CESS','b_paid[]');
		
		$outputRow['TOTAL']['value'] = "$mas_rec_row[total]";
		addCustomName($outputRow,'TOTAL','b_paid[]');

		$outputRow['PAID']['value'] = "$mas_rec_row[paid]";
		addCustomName($outputRow,'PAID','b_paid[]');

		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
			
	
    
      
      

	}
	
			$outputRow = array();
		$outputRow['VCHNO']['value'] = "";
		addCustomName($outputRow,'VCHNO','b_paid[]');
		addFooterCounter($outputRow,'VCHNO');
		
       		$outputRow['BILLNO']['value'] = "";
		addCustomName($outputRow,'BILLNO','b_paid[]');
		
		$outputRow['BILLDATE']['value'] = "";
		addCustomName($outputRow,'BILLDATE','b_paid[]');
		
		$outputRow['BILLEDTO']['value'] = "$cfbillvalue";
		addCustomName($outputRow,'BILLEDTO','b_paid[]');
		
		$outputRow['BILL AMT.']['value'] = "$cfrecvalue";
		addCustomName($outputRow,'BILL AMT.','b_paid[]');
		
		$outputRow['SRAMOUNT']['value'] = "$cfrecvalue";
		addCustomName($outputRow,'SRAMOUNT','b_paid[]');
		
		$outputRow['S.B.CESS']['value'] = "$mas_rec_row[educess]";
		addCustomName($outputRow,'S.B.CESS','b_paid[]');
		
		$outputRow['K.K.CESS']['value'] = "$mas_rec_row[seducess]";
		addCustomName($outputRow,'K.K.CESS','b_paid[]');
		
		$outputRow['TOTAL']['value'] = "";
		addCustomName($outputRow,'TOTAL','b_paid[]');

		$outputRow['PAID']['value'] = "Total Balance";
		addCustomName($outputRow,'PAID','b_paid[]');

		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		
		$output['rows'][][] = $outputRow;
		$rowCount++;

   
       addTotalRows($output,$rowCount);
    } 
	else
          $output[error] = "No Record Found..";
} else
    $output[error] = mysqli_error($con);
	
	echo json_encode($output);
	}
//End servicestaxsummery Summery





//start tdssummery Summery
else if($_POST['report_type']=="tdssummery")
{
	
  if($_POST['billedto']=="TDS DEDUCTED BY CLIENTS"){
	  
	$sqlQry="SELECT vchno, bill_no AS billno, DATE_FORMAT(vchdate,'%d/%m/%Y') as vchdate, comcode AS billfrom,   cramount AS tds,  tdsamt,  '' AS paid from vchreg where  vchdate >=  	STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' ) AND vchreg.cmp = '$_SESSION[SESS_CMPC]' AND vchreg.fny =  '$_SESSION[SESS_FNY]'  AND vchtype = 'PURCHASE' and tdsamt > 0 ";	
	
  }
  else{
	$qry_part=" ";	
	if($_POST['billedto']=="TDS DEDUCTED NON/COMP (SUPPLIER)"){
	$qry_part="AND cramount = '1' ";}
	elseif($_POST['billedto']=="TDS DEDUCTED COM. SUPPLIER"){
	$qry_part="AND cramount = '2' ";
	  }
	  
$sqlQry="SELECT vchno, bill_no AS billno, DATE_FORMAT(vchdate,'%d/%m/%Y') as vchdate, comcode AS billfrom,   cramount AS tds,  tdsamt,  '' AS paid from purcreg where  vchdate >= STR_TO_DATE(  '$from_date',  '%Y-%m-%d' ) AND vchdate <= STR_TO_DATE(  '$to_date',  '%Y-%m-%d' )  and tdsamt > 0 AND purcreg.cmp = '$_SESSION[SESS_CMPC]' AND purcreg.fny =  '$_SESSION[SESS_FNY]'  AND vchtype = 'PURCHASE' $qry_part";
	
}
$output['test'] = $sqlQry;
if (($mas_rec = mysqli_query($con,$sqlQry))) {
    if (mysqli_num_rows($mas_rec) > 0) {
        
			$outputRow = array();
		$outputRow['VCHNO']['value'] = "CF";
		addCustomName($outputRow,'VCHNO','b_paid[]');
		addFooterCounter($outputRow,'VCHNO');
		
       		$outputRow['BILLNO']['value'] = "";
		addCustomName($outputRow,'BILLNO','b_paid[]');
		
		$outputRow['BILLDATE']['value'] = "";
		addCustomName($outputRow,'BILLDATE','b_paid[]');
		
		$outputRow['BILLEDTO']['value'] = "$cfbillvalue";
		addCustomName($outputRow,'BILLEDTO','b_paid[]');
		
		$outputRow['TDS']['value'] = "$cfrecvalue";
		addCustomName($outputRow,'TDS','b_paid[]');
		
		
		$outputRow['TDSAMOUNT']['value'] = "";
		addCustomName($outputRow,'TDSAMOUNT','b_paid[]');
		addFooterTotal($outputRow,'TDSAMOUNT');
		
		$outputRow['BALANCE']['value'] = "";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		addFooterTotal($outputRow,'BALANCE');
		
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
      $netpmt='';
			

        while ($mas_rec_row = mysqli_fetch_array($mas_rec)) {
			
		
			
			if($mas_rec_row['tdsamt']>0){
				$balance=$balance+$mas_rec_row['tdsamt'];
				
				}
			
	  
	  	$outputRow = array();
		$outputRow['VCHNO']['value'] = "$mas_rec_row[vchno]";
		addCustomName($outputRow,'VCHNO','b_paid[]');
		addFooterCounter($outputRow,'VCHNO');
		
       		$outputRow['BILLNO']['value'] = "$mas_rec_row[billno]";
		addCustomName($outputRow,'BILLNO','b_paid[]');
		
		$outputRow['BILLDATE']['value'] = "$mas_rec_row[vchdate]";
		addCustomName($outputRow,'BILLDATE','b_paid[]');
		
		$outputRow['BILLEDTO']['value'] = "$mas_rec_row[billfrom]";
		addCustomName($outputRow,'BILLEDTO','b_paid[]');
		
		$outputRow['TDS']['value'] = "$mas_rec_row[tds]";
		addCustomName($outputRow,'TDS','b_paid[]');
		
		$outputRow['TDSAMOUNT']['value'] = "$mas_rec_row[tdsamt]";
		addCustomName($outputRow,'TDSAMOUNT','b_paid[]');
		
		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
      

	}

       			

		$outputRow = array();
		$outputRow['VCHNO']['value'] = "";
		addCustomName($outputRow,'VCHNO','b_paid[]');
		addFooterCounter($outputRow,'VCHNO');
		
       		$outputRow['BILLNO']['value'] = "";
		addCustomName($outputRow,'BILLNO','b_paid[]');
		
		$outputRow['BILLDATE']['value'] = "";
		addCustomName($outputRow,'BILLDATE','b_paid[]');
		
		$outputRow['BILLEDTO']['value'] = "$cfbillvalue";
		addCustomName($outputRow,'BILLEDTO','b_paid[]');
		
		$outputRow['TDS']['value'] = "$cfrecvalue";
		addCustomName($outputRow,'TDS','b_paid[]');
		
		$outputRow['TDSAMOUNT']['value'] = "Total Balance";
		addCustomName($outputRow,'TDSAMOUNT','b_paid[]');
		
		$outputRow['BALANCE']['value'] = "$balance";
		addCustomName($outputRow,'BALANCE','b_paid[]');
		
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
        
		addTotalRows($output,$rowCount);
    } 
	else
         $output[error] =  "No Record Found..";
} else
    $output[error] = mysqli_error($con);
	
	echo json_encode($output);
	}
//End tdssummery Summery








/// pln report start


else if($_POST['report_type']=="PNLSTATEMEMT"){

		
		$outputRow = array();
		$outputRow['Particulars']['value'] = "* SALES & INCOME **";
		addCustomName($outputRow,'Particulars','b_Parti[]');
		addFooterCounter($outputRow,'Particulars');
		
       		$outputRow['Dr. Amount']['value'] = "";
		addCustomName($outputRow,'Dr. Amount','b_damoun[]');
		addFooterTotal($outputRow,'Dr. Amount');
		
		$outputRow['Cr. Amount']['value'] = "";
		addCustomName($outputRow,'Cr. Amount','b_camount[]');	
		addFooterTotal($outputRow,'Cr. Amount');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
		
	$salesac = "SELECT DISTINCT(ledger) as salesac FROM `ledgerreg` WHERE  ledtype = 'SALES ACCOUNT' ";
	$result_sales = mysqli_query($con,$salesac);
	$rowsalesac = mysqli_fetch_assoc($result_sales);
	$salesacled = $rowsalesac['salesac'];
	

		
		$sales = "SELECT  sum(`total`) as debit from $billreg WHERE   fny = '$_SESSION[SESS_FNY]'";
	
	$salesresult = mysqli_query($con,$sales);
	$row_sales = mysqli_fetch_assoc($salesresult);
	
	$totalsales = $row_sales['debit'];
	
	
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>$salesacled</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'>$totalsales</textarea></td></tr>";
	
		$outputRow = array();
		$outputRow['Particulars']['value'] = "$salesacled";
		addCustomName($outputRow,'Particulars','b_Parti[]');
		addFooterCounter($outputRow,'Particulars');
		
       		$outputRow['Dr. Amount']['value'] = "";
		addCustomName($outputRow,'Dr. Amount','b_damoun[]');
		
		
		$outputRow['Cr. Amount']['value'] = "$totalsales";
		addCustomName($outputRow,'Cr. Amount','b_camount[]');	
		addFooterTotal($outputRow,'Cr. Amount');
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
	
	$incomeled = "SELECT DISTINCT(ledger) as incomeac FROM `ledgerreg` WHERE  ledtype  like '%INCOME' ";
	$result_incomeled = mysqli_query($con,$incomeled);

	if($result_incomeled){
	while($rowincomeled = mysqli_fetch_array($result_incomeled))
	{
		
	$incomeled = $rowincomeled['incomeac'];
	
		$income = "SELECT  sum(`totamount`) as income from vchreg WHERE   vchtype IN  ('RECEIPT', 'JOURNAL') and comcode = '$incomeled' and fny = '$_SESSION[SESS_FNY]'";
	
	$incomeresult = mysqli_query($con,$income);
	$row_income = mysqli_fetch_assoc($incomeresult);
	
	$total = $row_income['income'];
	
	
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>$salesacled</textarea></td><td><textarea name='b_damoun[]'>$total</textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	
	$outputRow = array();
		$outputRow['Particulars']['value'] = "$salesacled";
		addCustomName($outputRow,'Particulars','b_Parti[]');
		addFooterCounter($outputRow,'Particulars');
		
       		$outputRow['Dr. Amount']['value'] = "$total";
		addCustomName($outputRow,'Dr. Amount','b_damoun[]');
		
		$outputRow['Cr. Amount']['value'] = "";
		addCustomName($outputRow,'Cr. Amount','b_camount[]');	
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
	}
	}
	
		//echo "<tr><td ><textarea name=' b_Parti[]' style='font-size: 14px;'>** PURCHASE & EXPENCES **</textarea></td><td><textarea name='b_damoun[]'></textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
		
		$outputRow = array();
		$outputRow['Particulars']['value'] = "** PURCHASE & EXPENCES **";
		addCustomName($outputRow,'Particulars','b_Parti[]');
		addFooterCounter($outputRow,'Particulars');
		
       		$outputRow['Dr. Amount']['value'] = "";
		addCustomName($outputRow,'Dr. Amount','b_damoun[]');
		
		$outputRow['Cr. Amount']['value'] = "";
		addCustomName($outputRow,'Cr. Amount','b_camount[]');	
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
	
	$purchac = "SELECT DISTINCT(ledger) as purchaseac FROM `ledgerreg` WHERE  ledtype = 'PURCHASE ACCOUNT' ";
	$result_purch = mysqli_query($con,$purchac);
	$rowpurch = mysqli_fetch_assoc($result_purch);
	$purchaseled = $rowpurch['purchaseac'];
	
		
		
		$expences = "SELECT  sum(`totamount`) as credit from purcreg WHERE vchtype = 'PURCHASE' and account = '$purchaseled' and fny = '$_SESSION[SESS_FNY]'";
	
	$expencesresult = mysqli_query($con,$expences);
	$row_expences = mysqli_fetch_assoc($expencesresult);
	
	$totalcredit = $row_expences['credit'];

	
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>$purchaseled</textarea></td><td><textarea name='b_damoun[]'>$totalcredit</textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	$outputRow = array();
		$outputRow['Particulars']['value'] = "$purchaseled";
		addCustomName($outputRow,'Particulars','b_Parti[]');
		addFooterCounter($outputRow,'Particulars');
		
       		$outputRow['Dr. Amount']['value'] = "$totalcredit";
		addCustomName($outputRow,'Dr. Amount','b_damoun[]');
		
		$outputRow['Cr. Amount']['value'] = "";
		addCustomName($outputRow,'Cr. Amount','b_camount[]');	
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
		
	$bank = "SELECT DISTINCT(ledger) as bank FROM `ledgerreg` WHERE ledger != 'CASH' and ledtype = 'CASHBANK' ";
	$result_bank = mysqli_query($con,$bank);
	$expenseac = "SELECT DISTINCT(ledger) as expenceac FROM `ledgerreg` WHERE  ledtype  like '%EXPENSE' ";
	$result_expenseled = mysqli_query($con,$expenseac);

	if($result_bank){
	while($rowexpenseled = mysqli_fetch_array($result_expenseled))
	{
		
	$expenseled = $rowexpenseled['expenceac'];
	$totalexpense = 0;
        $totalpurcexpense = 0;
        $totalexp = 0;
		
		$otherexpense = "SELECT  sum(`totamount`) as expense from vchreg WHERE   vchtype in ('PAYMENT','JOURNAL') and comcode = '$expenseled' and fny = '$_SESSION[SESS_FNY]'";
	
	$result_expense = mysqli_query($con,$otherexpense);
	$row_expense = mysqli_fetch_assoc($result_expense);
	
	$totalexpense = $row_expense['expense'];

        $purcexpense = "SELECT  sum(`totamount`) as purcexpense from purcreg WHERE  account = '$expenseled' and fny = '$_SESSION[SESS_FNY]'";
	
	$result_purcexpense = mysqli_query($con,$purcexpense);
	$row_purcexpense = mysqli_fetch_assoc($result_purcexpense);
	
	$totalpurcexpense = $row_purcexpense['purcexpense'];
	
	$totalexp = $totalexpense  + $totalpurcexpense;
	
	//echo "<tr><td ><textarea name=' b_Parti[]'>$expenseled ($totalexpense) ($totalpurcexpense)</textarea></td><td><textarea name='b_damoun[]'>$totalexp</textarea></td><td><textarea name='b_camount[]'></textarea></td></tr>";
	
	$outputRow = array();
		$outputRow['Particulars']['value'] = "$expenseled ($totalexpense) ($totalpurcexpense)";
		addCustomName($outputRow,'Particulars','b_Parti[]');
		addFooterCounter($outputRow,'Particulars');
		
       		$outputRow['Dr. Amount']['value'] = "$totalexp";
		addCustomName($outputRow,'Dr. Amount','b_damoun[]');
		
		$outputRow['Cr. Amount']['value'] = "";
		addCustomName($outputRow,'Cr. Amount','b_camount[]');	
		
		$output['rows'][][] = $outputRow;
		$rowCount++;
	
	

	
	}
	}
	
		

		addTotalRows($output,$rowCount);
	
	
	//echo mysqli_error($con);
	
	echo json_encode($output);
	
}


/// creditreport start


else if($_POST['report_type']=="CREDITREPORT"){
if($sqlRes=mysqli_query($con,"SELECT compid,name,`limit`,usedlimit FROM commst where type like 'CUSTOMER' order by compid"))			
			{
				$rowCount=0;
			while($sqlResRow=mysqli_fetch_assoc($sqlRes))
			{
				
				$outputRow = array();
				$outputRow['COMPID']['value'] =$sqlResRow['compid'];
				addClassName($outputRow,'Name of Client');
				addFooterCounter($outputRow,'Name of Client');
				
				$outputRow['Name of Client']['value'] =$sqlResRow['name'];
				
				$outputRow['Credit Limit']['value'] =$sqlResRow['limit'];
				addClassName($outputRow,'Credit Limit');
				$outputRow['Used Limit']['value'] =$sqlResRow['usedlimit'];
				addClassName($outputRow,'Used Limit');
				$outputRow['CL Exceeded By']['value'] =$sqlResRow['usedlimit']-$sqlResRow['limit'];
				addClassName($outputRow,'CL Exceeded By');
				$outputRow['CL Increased By']['value'] =$sqlResRow['usedlimit']/$sqlResRow['limit']*100;
				addClassName($outputRow,'CL Increased By');
				
				$output['rows'][][] = $outputRow;
				$rowCount++;
			
			
			}//while 
			} //if
	
	else $output[error] = mysqli_error($con);
	
	addTotalRows($output,$rowCount);
	
	echo json_encode($output);
	
}

/// creditreport ends

}

else if($_POST['report_view_type']=="fuel")
{
				if($_POST['report_type']=="fuelregister"){
	
			if($book_info=mysqli_query($con,"select  VEHNO,DRIVER,OPENKM,CLOSEKM,TOTALKM,LITERFILLED,CPL,FDATE,FUELFILLEDBY,EntryDate,AMOUNT from fuelreg where FDATE between  '$from_date' and '$to_date'"))
			
			{
				addTotalRows($output,mysqli_num_rows($book_info));
			while($book_info_row=mysqli_fetch_assoc($book_info))
			{
				
				$index = 0;
	foreach ($book_info_row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$book_info,$index,$key,'',1);
	$index++;
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);
		
	//add Footer Counter to Column
	if($key == 'VEHNO')
	{
	addFooterCounter($outputRow,$key);
	}
		
	//add Footer Total to Column
	$totalKeyArray = array('AMOUNT');
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
	}
	
	$output['rows'][][] = $outputRow;
			
			
			}//while 
			//echo "</tbody></table>### ";
			} //if
	
	else $output[error] = mysqli_error($con);
	
	echo json_encode($output);
	
			}


else if($_POST['report_type']=="fuelsumm"){
		
/*
echo "<table  id='table_report_view'  cellspacing='0' width='100%'><thead><tr><th><textarea name='vehno[]'>VEHNO</textarea></th><th><textarea name='DRIVER[]'>DRIVER</textarea></th><th><textarea name='driver[]'>FUELING</textarea></th><th><textarea name='openkm[]'>LITERS</textarea></th><th><textarea name='closekm[]'>KM</textarea></th><th><textarea name='totalkm[]'>AVG</textarea></th></tr></thead>";

echo "<tfoot class='tablefooter'><tr><td><textarea name='vehno[]'>Total</textarea></td><td><textarea name='DRIVER[]' count='nor'></textarea></td><td><textarea name='driver[]'></textarea></td><td><textarea name='openkm[]'></textarea></td><td><textarea name='closekm[]'></textarea></td><td><textarea name='totalkm[]'></textarea></td></tr></tfoot><tbody>";*/
		
		
	if($book_info=mysqli_query($con,"select VEHNO,DRIVER,count(VEHNO) as FUELING,sum(LITERFILLED) as LITERS,sum(TOTALKM) as KM,FORMAT((sum(TOTALKM)/sum(LITERFILLED)) ,2) as AVG  from fuelreg where  FDATE between '$from_date' and '$to_date' and ISCLOSED='1' group by VEHNO  ORDER BY VEHNO; "))
	
	{
		addTotalRows($output,mysqli_num_rows($book_info));
	while($book_info_row=mysqli_fetch_assoc($book_info))
	{
			$index = 0;
	foreach ($book_info_row as $key=>$value) {			
	$outputRow[$key]['value'] = $value;	
	/* 
	 * start
	 * getting field name of table
	*/	
	addDataBaseName($outputRow,$book_info,$index,$key,'',1);
	$index++;
	/* 
	 * end
	*/
		
	//adding class
	addClassName($outputRow,$key);
		
	//add Footer Counter to Column
	if($key == 'VEHNO')
	{
	addFooterCounter($outputRow,$key);
	}
		
	//add Footer Total to Column
	$totalKeyArray = array('SUMLITERFILLED','SUMTOTALKM','AVG');
	if(in_array($key,$totalKeyArray))
	addFooterTotal($outputRow,$key);
	}
	
	$output['rows'][][] = $outputRow;
		
		
/*	$book_info_row[AVG]  = number_format($book_info_row[AVG], 2, '.', '');
	echo "<tr><td><textarea name='vehno[]' >$book_info_row[VEHNO]</textarea></td><td><textarea name='DRIVER[]' >$book_info_row[DRIVER]</textarea></td><td><textarea name='driver[]' >$book_info_row[FUELING]</textarea></td><td><textarea name='openkm[]' >$book_info_row[SUMLITERFILLED]</textarea></td><td><textarea name='closekm[]' >$book_info_row[SUMTOTALKM]</textarea></td><td><textarea name='totalkm[]' >$book_info_row[AVG]</textarea></td></tr>";	*/
	}//while
	//echo "</tbody></table>### ";
		}//if
		
		else $output[error] = mysqli_error($con);
	
	echo json_encode($output);
		
	}
	
	}//else if($_POST['report_view_type']=="fuel") end







///log start here

else if($_POST['report_view_type']=="log")
{
   if($_POST['report_type']=="all"){
	
	if(empty($_POST['billedto']))
$qry_part="";
else
$qry_part="and det4 like '%$_POST[billedto]%' ";
	
	if($book_info=mysqli_query($con,"select  `id` as ID, `entrydate` as 'Entry Date', `det1`, `det2`, `det3`, `det4`, `det5`, `det6`, `det7`, `det8`, `det9`, `det10`, `det11`, `det12`, `status`  from logtable where entrydate between  '$from_date' and '$to_date' $qry_part order by id desc"))

{
	$output['total_rows'] =mysqli_num_rows($bill_info);	

while($book_info_row=mysqli_fetch_assoc($book_info))
{
	$index = 0;
	foreach ($book_info_row as $key=>$value) {	
		
	/* 
	 * start
	 * getting field name of table
	*/	
    $outputRow[$key]['value'] = $value;	
	addDataBaseName($outputRow,$book_info,$index,$key,'',1);
	$index++;
  	
	/* 
	 * end
	*/
	
	
	if (is_numeric($value))
	$outputRow[$key]['tdClass'] = 'number';
	
	

	

	
	}
	
	$output['rows'][][] = $outputRow;	

	}
	
	echo json_encode($output);
	}
	else echo mysqli_error($con);
	
	$count_totalbill=number_format($count_totalbill,2);
	
	
	}




if($_POST['report_type']=="smslog"){

/*echo "<table  id='table_report_view'  cellspacing='0' width='100%''  ><thead><tr><th><textarea name='det1[]'>BOOK ID</textarea></th><th><textarea name='det1[]'>MOBILE SEND</textarea></th><th><textarea name='det2[]' >MOBILE REC</textarea></th><th><textarea name='det3[]' >MSG SEND</textarea></th><th><textarea name='det4[]' >MSG REC</textarea></th><th><textarea name='det5[]' >STATUS</textarea></th><th><textarea name='det6[]' >TIME STAMP</textarea></th></tr></thead>";

echo "<tfoot class='tablefooter'><tr><td><textarea name='det1[]'>Total</textarea></td><td><textarea name='det1[]' count='nor'></textarea></td><td><textarea name='det2[]' ></textarea></td><td><textarea name='det3[]' ></textarea></td><td><textarea name='det4[]' ></textarea></td><td><textarea name='det5[]' ></textarea></td><td><textarea name='det6[]' ></textarea></td></tr></tfoot><tbody>";*/
	
	if(empty($_POST['billedto']))
$qry_part="";
else
$qry_part="and bookid like '%$_POST[billedto]%' ";
	
	if($book_info=mysqli_query($con,"select  id as 'ID', bookid as 'BOOKID', mobsent as 'SEND SMS NO', mobrev as 'RECV. SMS NO', msgsent as 'MESSAGE SENT', msgrecv as 'MESSAGE Received', status as STATUS, DATE_FORMAT(timestamp, '%d/%m/%Y') as TIMESTAMP  from smslog where timestamp between  '$from_date' and '$to_date' $qry_part"))

{
	$output['total_rows'] =mysqli_num_rows($bill_info);	
	$index = 0;
while($book_info_row=mysqli_fetch_assoc($book_info))
{
//for($i=0;$i<100;$i++)	
/*echo "<tr><td><textarea name='det1[]' >$book_info_row[bookid]</textarea></td><td><textarea name='det1[]' >$book_info_row[mobsent]</textarea></td><td><textarea name='det2[]' >$book_info_row[mobrev]</textarea></td><td><textarea name='det3[]' >$book_info_row[msgsent]</textarea></td><td><textarea name='det4[]' >$book_info_row[msgrecv]</textarea></td><td><textarea name='det5[]' >$book_info_row[status]</textarea></td><td><textarea name='det6[]' >$book_info_row[timestamp]</textarea></td></tr>";	
*/	
$index = 0;
foreach ($book_info_row as $key=>$value) {	
		
	/* 
	 * start
	 * getting field name of table
	*/	
    $outputRow[$key]['value'] = $value;
	
	addDataBaseName($outputRow,$book_info,$index,$key,'',1);
	$index++;
  	
	/* 
	 * end
	*/
	
	
	if (is_numeric($value))
	$outputRow[$key]['tdClass'] = 'number';
	
	

	

	
	}
	
	
	$output['rows'][][] = $outputRow;	

	}
	
	echo json_encode($output);
	}
	else echo mysqli_error($con);
	
	}

}



else if($_POST['report_view_type']=="master")
{

		if($_POST['report_type']=="empinfo"){
			if($result_emp=mysqli_query($con,"SELECT * FROM  `empinfo` order by EntryID"))
			{
		
		echo "<table id='table_report_view'  width='2800' cellspacing='0'><thead><tr><th style='display:none'>EntryID</th><th>ECode</th><th >Password</th><th >CMP</th><th >Name</th><th >DOB</th><th >Address</th><th >Age</th><th>EDEmployed</th><th >Designation</th><th >Department</th><th >Status</th><th >Gender</th><th >CivilStatus</th>
		<th >ContactNumber</th><th >reptime</th><th >closetime</th><th >salary</th><th>holidays</th><th >other1</th><th >other2</th><th >HRA</th><th >Conveyance</th><th >Medical</th><th >Bonus</th><th>basicsalary</th><th >otallowance</th><th >daallowance</th><th >cpf</th><th >clic</th><th >epf</th><th >elic</th><th >pTax</th></thead><tbody>";
			
			while($row=mysqli_fetch_array($result_emp))
			{
		echo "<tr><td style='display:none'><textarea name='EntryID'>$row[EntryID]</textarea></td><td><textarea name='ECode' class='ECode'>$row[ECode]</textarea></td><td><input type='password' name='password' class='pwd nocaps' style='height:100%' value='$row[password]'/></td><td><textarea name='CMP' class='CMP'>$row[CMP]</textarea></td><td><textarea name='EName' class='EName' >$row[EName]</textarea></td><td><textarea name='EBdate' class='EBdate'>$row[EBdate]</textarea></td><td><textarea name='EAddress' class='EAddress'>$row[EAddress]</textarea></td><td><textarea name='EAge' class='EAge'>$row[EAge]</textarea></td><td><textarea name='EDEmployed' class='EDEmployed'>$row[EDEmployed]</textarea></td><td><textarea name='Designation' class='Designation'>$row[Designation]</textarea></td><td><textarea name='Department' class='Department'>$row[Department]</textarea></td><td><textarea name='Status' class='Status'>$row[Status]</textarea></td><td><textarea name='EGender' class='EGender'>$row[EGender]</textarea></td><td><textarea name='ECivilStatus' class='ECivilStatus'>$row[ECivilStatus]</textarea></td><td><textarea name='ContactNumber' class='ContactNumber'>$row[ContactNumber]</textarea></td><td><textarea name='reptime' class='reptime'>$row[reptime]</textarea></td><td><textarea name='closetime' class='closetime'  >$row[closetime]</textarea></td><td><textarea name='salary' class='salary'>$row[salary]</textarea></td><td><textarea name='holidays' class='holidays'>$row[holidays]</textarea></td><td><textarea name='other1' class='other1'>$row[other1]</textarea></td><td><textarea name='other2' class='other2'>$row[other2]</textarea></td><td><textarea name='HRA' class='HRA'>$row[HRA]</textarea></td><td><textarea name='Conveyance' class='Conveyance'>$row[Conveyance]</textarea></td><td><textarea name='Medical' class='Medical'>$row[Medical]</textarea></td><td><textarea name='Bonus' class='Bonus'>$row[Bonus]</textarea></td><td><textarea name='basicsalary' class='basicsalary'>$row[basicsalary]</textarea></td><td><textarea name='otallowance' class='otallowance'>$row[otallowance]</textarea></td><td><textarea name='daallowance' class='daallowance'>$row[daallowance]</textarea></td><td><textarea name='cpf' class='cpf'  >$row[cpf]</textarea></td><td><textarea name='clic' class='clic'>$row[clic]</textarea></td><td><textarea name='epf' class='epf'>$row[epf]</textarea></td><td><textarea name='elic' class='elic'>$row[elic]</textarea></td><td><textarea name='pTax' class='pTax'>$row[pTax]</textarea></td></tr>";
				}	
			 echo "</tbody></table>";
			}
			 
			else echo "Error:".mysqli_error($con);
		}

		elseif($_POST['report_type']=="ratemaster"){
			
			if($result_emp=mysqli_query($con,"SELECT * FROM  `ratemaster` where compid='$_POST[compid]' order by compid "))
			{
		
		echo "<table id='table_report_view' class='ratemst' width='100%' cellspacing='0'><thead><tr><th >COMPID</th><th >VEHTYPE</th><th >CITY</th><th >PACKAGE</th><th >PKG RATE</th><th >DARATE</th><th >NARATE</th><th >GARAGE</th><th >EXHRRATE</th><th >EXKMRATE</th><th >AVG.KMPL</th><th >FL Diff</th><th >Effdate</th><th width='5%'></th><th width='5%'></th></tr></thead><tbody>";
			
			while($row=mysqli_fetch_array($result_emp))
			{
		echo "<tr><td style='display:none'><textarea name='ID' class='ID'>$row[entryid]</textarea></td><td><textarea name='compid' class='compid'>$row[compid]</textarea></td><td><textarea name='vehtype' class='vehtype'>$row[vehtype]</textarea></td><td><textarea name='city' class='city'>$row[city]</textarea></td><td><textarea name='package' class='package'>$row[package]</textarea></td><td><textarea name='pkgrate' class='pkgrate'>$row[pkgrate]</textarea></td><td><textarea name='darate' class='darate'>$row[darate]</textarea></td> <td><textarea name='narate' class='narate'>$row[narate]</textarea></td> <td><textarea name='garage' class='garage'>$row[garage]</textarea></td><td><textarea name='exhrrate' class='exhrrate'>$row[exhrrate]</textarea></td><td><textarea name='exkmrate' class='exkmrate'>$row[exkmrate]</textarea></td><td><textarea name='avgkmpl' class='avgkmpl'>$row[vhavg]</textarea></td><td><textarea name='flsrg' class='flsrg'>$row[flsrg]</textarea></td><td><textarea name='effdate' class='effdate' id='effdate'>$row[effdate]</textarea></td><td width='5%'> <div> <input type='button' name='prod_save' id='rate_master_edit' class='filter_table' style='display:none' value='Save' /></div></td><td align='center' width='5%'><input type='button'    class='delete_master_rate delete_row' value='X' /></td></tr>";
				}	
			 echo "</tbody></table>";
			}
			 
			else echo "Error:".mysqli_error($con);
		}


		  elseif($_POST['report_type']=="companymst"){
			  $qry_part='';
			  if(isset($_POST[billedto])&&!empty($_POST[billedto]))
			  {
				  $qry_part= "where compid like '%$_POST[billedto]%'";
				  }
			  if($result_emp=mysqli_query($con,"SELECT * FROM  `commst` $qry_part order by compid"))
			  {
		  
		  echo "<table id='table_report_view' class='cmpmst' width='100%' cellspacing='0'><thead><tr><th >COMPID</th><th >NAME</th><th >ADDRESS</th><th >CITY</th><th >S.TAX OPTION</th><th >TOLL OPTION</th><th>TDS</th><th >TELEPHONE</th><th >EMAIL</th><th >CONT. PERSON</th><th >TYPE</th><th width='5%'></th><th width='5%'></th></tr></thead><tbody>";
			  
			  while($row=mysqli_fetch_array($result_emp))
			  {
		  echo "<tr><td style='display:none'><textarea name='ID' class='ID'>$row[id]</textarea></td><td><a href='mastercmpedit.php?ID=$row[id]' onClick='positionedPopup(this.href,630,580);return false'><textarea name='compid' class='compid'>$row[compid]</textarea></a></td><td><textarea name='name' class='name'>$row[name]</textarea></td><td><textarea name='address' class='address'>$row[address]</textarea></td><td><textarea name='city' class='city'>$row[cmpcity]</textarea></td><td><textarea name='optstax' class='optstax'>$row[optstax]</textarea></td><td><textarea name='opttoll' class='opttoll'>$row[opttoll]</textarea></td><td><textarea name='tds' class='tds'>$row[tds]</textarea></td><td><textarea name='telephone' class='telephone'>$row[telephone]</textarea></td><td><textarea name='email' class='email nocaps'>$row[email]</textarea></td><td><textarea name='conper' class='conper'>$row[conper]</textarea></td><td><textarea name='type' class='type'>$row[type]</textarea></td><td width='5%'> <div> <input type='button' name='prod_save' id='cmp_master_edit' class='filter_table' style='display:none' value='Save' /></div></td><td align='center' width='5%'><input type='button' class='delete_master_cmp delete_row' value='X' /></td></tr>";
				  }	
			   echo "</tbody></table>";
			  }
			   
			  else echo "Error:".mysqli_error($con);
		  }	
	}
	
	
else if($_POST['report_view_type']=="getreporttype")
{
	

		
/*
echo "<table  id='table_report_view'  cellspacing='0' width='100%'><thead><tr><th><textarea name='vehno[]'>VEHNO</textarea></th><th><textarea name='DRIVER[]'>DRIVER</textarea></th><th><textarea name='driver[]'>FUELING</textarea></th><th><textarea name='openkm[]'>LITERS</textarea></th><th><textarea name='closekm[]'>KM</textarea></th><th><textarea name='totalkm[]'>AVG</textarea></th></tr></thead>";

echo "<tfoot class='tablefooter'><tr><td><textarea name='vehno[]'>Total</textarea></td><td><textarea name='DRIVER[]' count='nor'></textarea></td><td><textarea name='driver[]'></textarea></td><td><textarea name='openkm[]'></textarea></td><td><textarea name='closekm[]'></textarea></td><td><textarea name='totalkm[]'></textarea></td></tr></tfoot><tbody>";*/
		
	$sql_qry ="select det as 'REPORTDESC' , det1 as 'REPORTCODE' from master where mstype = 'ACC' and cmp = '$_SESSION[SESS_CMPC]' and branch like '$_SESSION[SESS_BRANCH]' and `desc` = 'REPORTS' and code ='$_SESSION[SESS_MEMBER_ID]'";	
		
	if($sql_results=mysqli_query($con,$sql_qry))
	
	{
		$num_rows = mysqli_num_rows($sql_results);
		if($num_rows==0)
		{
			$sql_qry ="select det as 'REPORTDESC' , det1 as 'REPORTCODE' from master where mstype = 'ACC' and cmp = '$_SESSION[SESS_CMPC]' and branch like '$_SESSION[SESS_BRANCH]' and `desc` = 'REPORTS' and code ='DEFAULT'";
			$sql_results=mysqli_query($con,$sql_qry);
		}
		
	while($sql_rows=mysqli_fetch_assoc($sql_results))
	{
		
	
	$output['rows'][] = $sql_rows;
		
	}
	}
		
		else 
		$output[error] = mysqli_error($con);
		
	
	echo json_encode($output);
		
	} //else if($_POST['report_view_type']=="getreporttype") ends
	

	
	
  



function addDataBaseName(&$outputRow,$sqlResult,$index,$key=null,$prefix='',$array=0)
{
	if($array==1)
	{
		$suffix = '[]';
	}
	mysqli_field_seek($sqlResult,$index);
	$fieldinfo=mysqli_fetch_field($sqlResult);
	if($fieldinfo->orgname)
		$outputRow[$key]['name'] = $prefix.$fieldinfo->orgname.$suffix;
	else
		$outputRow[$key]['name'] = $prefix.$fieldinfo->name.$suffix;
}

function addCustomName(&$outputRow,$key,$name)
{
			$outputRow[$key]['name'] = $name;
}


function addClassName(&$outputRow,$key=null,$class=null)
{
	if($class==null)
	{
		if($key!=null)
		{
			if(is_numeric(str_replace(',', '', $outputRow[$key]['value'])))
			$outputRow[$key]['tdClass'] = 'number';
		}
	}
	else
	{	
		if(!empty($outputRow[$key]['tdClass']))
		{
			$class = ' '.$class;
		}
		$outputRow[$key]['tdClass'] .= $class;
	}
}

function addFooterCounter(&$outputRow,$key=null)
{
	if($key!=null)
	$outputRow[$key]['count'] = 'yes';
}

function addFooterTotal(&$outputRow,$key=null)
{
	//if($key!=null)
	$outputRow[$key]['total'] = 'yes';
}

function addTotalRows(&$output,$totalrows)
{
	$output['total_rows'] =$totalrows;
}

mysqli_close($con);









?>