<?php

function getUnderGroupTree($gid,$Tarray)
{
global $db;
//echo "gid---";print_r($gid);
$ID=implode(',',$gid);
//echo "ID---";print_r($ID);
//echo "<br />Tarray--";print_r($Tarray);
	$sql="Select * from accountgroupmaster where MainGroupId in ($ID)"; //echo "<br />".$sql;
	$result=DB_query($sql,$db);
	while($row=DB_fetch_array($result))
	{$array[]=$row['GroupId'];}
	if($array!=''){
	$total_array=array_merge($gid,$array);
	}
	if($Tarray!='' && $array!=''){$final=array_merge($Tarray,$total_array);}else{$final=$total_array;}
	//echo "<br />final---";print_r($final);
	//print_r($array);echo "<br />-----------in function -----------<br />";
	if($array!=''){return getUnderGroupTree($array,$final);}
	else{if($Tarray!='')return array_unique($Tarray);}
}
function GetAccountGroupmaster($mainid)
{
   global $db;
   static $rx=0;
   $q1=DB_query("select * from accountgroupmaster where (GroupId='".$mainid."' or GroupName='".$mainid."')  ",$db);
   while($RVPrefix=DB_fetch_array($q1))
  {
 	if($RVPrefix['MainGroupId']==0)
	{
	    $rx=$RVPrefix['GroupName'];
 	   //break;
	}
	  GetAccountGroupmaster($RVPrefix['MainGroupId']);
  }
    return ($rx);
}
//====================================================================
function GetAll_GroupmasterID($mainid)
{
   global $db;
   static $rx=array();
 $q1=DB_query("select * from accountgroupmaster where MainGroupId='".$mainid."' ",$db);
 while( $RVPrefix=DB_fetch_array($q1))
 {
  	     $rx[]=$RVPrefix['GroupId'];
  	    GetAll_GroupmasterID($RVPrefix['GroupId']);
 }
 
    return ($rx);
}

//***********************************************************************
 	function CategoryShow($pcode, $PcateID, $dashVal)
	{
	    global $db;
		 
		$dashVal = $dashVal . "-";
	    $sqlCate = "select * from accountgroupmaster  where  MainGroupId = '".$PcateID."'";
 		$rsCate  = DB_query($sqlCate,$db);	
 		if(DB_num_rows($rsCate)>0)
		{
			while($rowCate = DB_fetch_array($rsCate))
			{
				$sqlCateSel = "select * from accountgroupmaster where GroupId  =".$rowCate['GroupId']." ";
				$rsCateSel	= DB_query($sqlCateSel,$db);
				$px='';
				 if($rowCate['GroupId']==$pcode)
				 $px="selected";
 		?>
 				<option value="<?php echo $rowCate['GroupId'];?>" <?php echo $px ?>><?php echo $dashVal;?>
				 <?php echo   $rowCate['GroupName'];?> </option>
	   <?php			
				   CategoryShow($pcode,$rowCate['GroupId'], $dashVal);
			}
		}
	}   
//***********************************	
function CategoryShow1($pcode, $PcateID, $dashVal)
	{
	    global $db;
		 
		$dashVal = $dashVal . "-";
	    $sqlCate = "select * from accountgroupmaster  where  MainGroupId = '".$PcateID."'";
 		$rsCate  = DB_query($sqlCate,$db);	
 		if(DB_num_rows($rsCate)>0)
		{
 			while($rowCate = DB_fetch_array($rsCate))
			{
			  $t1=APRGroupWise_TrialBalance($rowCate['GroupId'],'DR');
			  $t2=APRGroupWise_TrialBalance($rowCate['GroupId'],'CR'); 
			  	$link="index.php?route=Account/AccountingReport&modid=".$_REQUEST['modid']."&frmid=".$_REQUEST['frmid']."&tabid=".$_REQUEST['tabid']."&page=APRGroupWise-TrialBalance-1&acc_group=".$rowCate['GroupId']."";
			//$ledger_id=$get_ledger_row['AccountsID'];
			if($t1>0 || $t2>0){
 		?>
				<tr>
					<td width="20%"><a href="<?php echo $link;?>" target="_blank"><?php echo $dashVal.$rowCate['GroupName'] ;?></a>
					<input   size="4"  type="text" value="<?php echo $rowCate['GroupId'];?>">
					</td>
					<td  width="15%"> </td>
					<td  width="15%"><?php echo APRGroupWise_TrialBalance($rowCate['GroupId'],'DR');
					$t11[]=APRGroupWise_TrialBalance($rowCate['GroupId'],'DR');
					 ?></td>
					<td  width="15%"><?php echo APRGroupWise_TrialBalance($rowCate['GroupId'],'CR'); 
					$t22[]=APRGroupWise_TrialBalance($rowCate['GroupId'],'CR');
					?> </td>
					<td  width="15%"> </td>
					<td  width="10%"> </td>
				  </tr>
 				 
	   <?php	}	
				//   CategoryShow1($pcode,$rowCate['GroupId'], $dashVal);
			}
		}
	}   
	
	
//===========================================================================
function SeperateByCommes($x)
{
   if(count($x)>1)
   {
	   $val="";
	   for($i=0;$i<count($x);$i++)
	   {
		  $val.="'".$x[$i]."',";
	   }
	   
	   $val1=substr($val,0,-1);
   }
   else{
    $val1="'".$str."'";
   }
  
   return($val1);
}

//*****************************ACCOUNTING**************************************

function Get_AccountByLedger($LId,$amount_type,$from_date='',$to_date='')
{
  global $db;
if($from_date!='' && $to_date!='')  
{
   $q1=DB_query("select  SUM(B.amount) AS TAmount ,B.ledgerid from  account_book A,account_book_details B where A.id=B.account_bookid and A.Dates between '".str_replace("/","-",$from_date)."' and '".str_replace("/","-",$to_date)."' and  B.ledgerid in (".$LId.") and B.amount_type='".$amount_type."' and A.cancel_status=0  ",$db);
	//echo "select  SUM(B.amount) AS TAmount ,B.ledgerid from  account_book A,account_book_details B where A.id=B.account_bookid and A.Dates between '".str_replace("/","-",$from_date)."' and '".str_replace("/","-",$to_date)."' and  B.ledgerid in (".$LId.") and B.amount_type='".$amount_type."' <br /><br />";
}else{
     $q1=DB_query("select  SUM(B.amount) AS TAmount ,B.ledgerid from  account_book A,account_book_details B where A.id=B.account_bookid and  B.ledgerid in (".$LId.")   and B.amount_type='".$amount_type."'  AND A.Dates>='".$_SESSION['financialYrStart']."' and A.Dates<='".$_SESSION['financialYrEnd']."' and A.cancel_status=0  ",$db);
	//echo "1-----------select  SUM(B.amount) AS TAmount ,B.ledgerid from  account_book A,account_book_details B where A.id=B.account_bookid and  B.ledgerid in (".$LId.")   and B.amount_type='".$amount_type."'  AND A.Dates>='".$_SESSION['financialYrStart']."' and A.Dates<='".$_SESSION['financialYrEnd']."' <br /><br />";
   }
    while( $RVPrefix=DB_fetch_array($q1))
 {
 	 
      return ($RVPrefix['TAmount']);
 }
}
//========To get the total value of excise duty posted in the ledgers through the transactions(Sale & Purcahse)=======
function yearlyETaxAccountByTransactions($taxId,$from_date='',$to_date='')
{
	global $db;
	$return_array='';
	if($from_date!='' && $to_date!='')
	{
		$query1=DB_fetch_array(DB_query("Select SUM(exciseValue) as total_inv_excise from invoice where exciseDuty='".$taxId."' AND invoiceDate>='".str_replace("/","-",$from_date)."' and invoiceDate<='".str_replace("/","-",$to_date)."'",$db));
		$query2=DB_fetch_array(DB_query("Select SUM(A.excise_amt) as total_pur_excise ,A.bill_book_date from  purchase_billbook A where  A.excise='".$taxId."' AND A.bill_book_date>='".str_replace("/","-",$from_date)."' and A.bill_book_date<='".str_replace("/","-",$to_date)."'",$db));
		//echo "<br /><br />2---------Select SUM(B.Excise_Duty_value) as total_pur_excise ,A.bill_book_date from purchase_bill_details B, purchase_billbook A where A.id=B.purch_billbookid and B.Excise_Duty='".$taxId."' AND A.bill_book_date>='".str_replace("/","-",$from_date)."' and A.bill_book_date<='".str_replace("/","-",$to_date)."'";
	}
	else
	{
		$query1=DB_fetch_array(DB_query("Select SUM(exciseValue) as total_inv_excise from invoice where exciseDuty='".$taxId."' AND invoiceDate>='".$_SESSION['financialYrStart']."' and invoiceDate<='".$_SESSION['financialYrEnd']."'",$db));
		$query2=DB_fetch_array(DB_query("Select SUM(A.excise_amt) as total_pur_excise ,A.bill_book_date from  purchase_billbook A where A.excise='".$taxId."' AND A.bill_book_date>='".$_SESSION['financialYrStart']."' and A.bill_book_date<='".$_SESSION['financialYrEnd']."'",$db));


	//echo "Select SUM(B.Excise_Duty_value) as total_pur_excise ,A.bill_book_date from purchase_bill_details B, purchase_billbook A where A.id=B.purch_billbookid and B.Excise_Duty='".$taxId."' AND A.bill_book_date>='".$_SESSION['financialYrStart']."' and A.bill_book_date<='".$_SESSION['financialYrEnd']."' <br />";
	}
	//echo $query2['total_pur_excise'];
	$return_array[]=$query2['total_pur_excise'];
	$return_array[]=$query1['total_inv_excise'];
	return $return_array;
}
//====To get the total value of Sales Tax posted in the ledgers through the transactions(Sale & Purcahse)========================
function yearlySTaxAccountByTransactions($taxId,$from_date='',$to_date='')
{
	global $db;
	$return_array='';
	if($from_date!='' && $to_date!='')

	{
	$query1=DB_fetch_array(DB_query("Select SUM(VatCstValue) as total_inv_vatsct from invoice where VatCst='".$taxId."' AND invoiceDate>='".str_replace("/","-",$from_date)."' and invoiceDate<='".str_replace("/","-",$to_date)."'",$db));
		
	$query2=DB_fetch_array(DB_query("Select SUM(A.taxvalue) as total_pur_vatsct from purchase_billbook A where  A.vat_cst='".$taxId."' AND A.bill_book_date>='".str_replace("/","-",$from_date)."' and A.bill_book_date<='".str_replace("/","-",$to_date)."'",$db));
	}
	else
	{
	$query1=DB_fetch_array(DB_query("Select SUM(VatCstValue) as total_inv_vatsct from invoice where VatCst='".$taxId."' AND invoiceDate>='".$_SESSION['financialYrStart']."' and invoiceDate<='".$_SESSION['financialYrEnd']."'",$db));
	$query2=DB_fetch_array(DB_query("Select SUM(A.taxvalue) as total_pur_vatsct from purchase_billbook A where  A.vat_cst='".$taxId."' AND A.bill_book_date>='".$_SESSION['financialYrStart']."' and A.bill_book_date<='".$_SESSION['financialYrEnd']."'",$db));
	}
	$return_array[]=$query2['total_pur_vatsct'];
	$return_array[]=$query1['total_inv_vatsct'];
	return $return_array;
}
//====================================
function yearlyVendorAccountByTransactions($vendorId,$from_date='',$to_date='')
{
	global $db;
	if($vendorId!=''){
	if($from_date!='' && $to_date!='')
	{
		$query=DB_fetch_array(DB_query("Select SUM(GrandTotal) as purch_total from purchase_billbook where vendor=$vendorId AND bill_book_date>='".str_replace("/","-",$from_date)."' and bill_book_date<='".str_replace("/","-",$to_date)."'",$db));
	//echo "Select SUM(GrandTotal) as purch_total from purchase_billbook where vendor=$vendorId AND bill_book_date>='".str_replace("/","-",$from_date)."' and bill_book_date<='".str_replace("/","-",$to_date)."'";
	}
	else
	{
	//echo "Select SUM(GrandTotal) as purch_total from purchase_billbook where vendor=$vendorId AND bill_book_date>='".$_SESSION['financialYrStart']."' and bill_book_date<='".$_SESSION['financialYrEnd']."'";
		$query=DB_fetch_array(DB_query("Select SUM(GrandTotal) as purch_total from purchase_billbook where vendor=$vendorId AND bill_book_date>='".$_SESSION['financialYrStart']."' and bill_book_date<='".$_SESSION['financialYrEnd']."'",$db));
	}
	return $query['purch_total']; }
}
//************************************
function yearlyClientAccountByTransactions($clientId,$from_date='',$to_date='')
{
	global $db;
	if($clientId!=''){
	if($from_date!='' && $to_date!='')
	{
		$query=DB_fetch_array(DB_query("Select SUM(grandTotal) as inv_total from invoice where client_id=$clientId AND invoiceDate>='".str_replace("/","-",$from_date)."' and invoiceDate<='".str_replace("/","-",$to_date)."'",$db));
	}
	else
	{	
		$query=DB_fetch_array(DB_query("Select SUM(grandTotal) as inv_total from invoice where client_id=$clientId AND invoiceDate>='".$_SESSION['financialYrStart']."' and invoiceDate<='".$_SESSION['financialYrEnd']."'",$db));
	}
	return $query['inv_total']; }
}
//************************************
function yearlyFreightAccountByTransactions($freightLid,$from_date='',$to_date='')
{
	global $db;
	if($freightLid!=''){
	if($from_date!='' && $to_date!='')
	{
		$query=DB_fetch_array(DB_query("Select SUM(freight) as freight_total from purchase_billbook where freight_ledger=$freightLid AND bill_book_date>='".str_replace("/","-",$from_date)."' and bill_book_date<='".str_replace("/","-",$to_date)."'",$db));
	//echo "Select SUM(GrandTotal) as purch_total from purchase_billbook where vendor=$vendorId AND bill_book_date>='".str_replace("/","-",$from_date)."' and bill_book_date<='".str_replace("/","-",$to_date)."'";
	}
	else
	{
		$query=DB_fetch_array(DB_query("Select SUM(freight) as freight_total from purchase_billbook where freight_ledger=$freightLid AND bill_book_date>='".$_SESSION['financialYrStart']."' and bill_book_date<='".$_SESSION['financialYrEnd']."'",$db));
		//echo "Select SUM(freight) as freight_total from purchase_billbook where freight_ledger=$freightLid AND bill_book_date>='".$_SESSION['financialYrStart']."' and bill_book_date<='".$_SESSION['financialYrEnd']."'";
	}
	return $query['freight_total']; }
}
//************************************
function yearlySurchargeAccountByTransactions($surLid,$from_date='',$to_date='')
{
	global $db;
	if($surLid!=''){
	if($from_date!='' && $to_date!='')
	{
		$query=DB_fetch_array(DB_query("Select SUM(sur_oct_amt) as sur_total from purchase_billbook where surcharge_ledger=$surLid AND bill_book_date>='".str_replace("/","-",$from_date)."' and bill_book_date<='".str_replace("/","-",$to_date)."'",$db));
	//echo "Select SUM(GrandTotal) as purch_total from purchase_billbook where vendor=$vendorId AND bill_book_date>='".str_replace("/","-",$from_date)."' and bill_book_date<='".str_replace("/","-",$to_date)."'";
	}
	else
	{
		$query=DB_fetch_array(DB_query("Select SUM(sur_oct_amt) as sur_total from purchase_billbook where surcharge_ledger=$surLid AND bill_book_date>='".$_SESSION['financialYrStart']."' and bill_book_date<='".$_SESSION['financialYrEnd']."'",$db));
		//echo "Select SUM(sur_oct_amt) as sur_total from purchase_billbook where surcharge_ledger=$surLid AND bill_book_date>='".$_SESSION['financialYrStart']."' and bill_book_date<='".$_SESSION['financialYrEnd']."'";
	}
	return $query['sur_total']; }
}
//************************************
function yearlyPkgChargesAccountByTransactions($pkgLid,$from_date='',$to_date='')
{
	global $db;
	if($pkgLid!=''){
	if($from_date!='' && $to_date!='')
	{
		$query=DB_fetch_array(DB_query("Select SUM(pkg_charges) as pkg_total from purchase_billbook where pckg_ledger=$pkgLid AND bill_book_date>='".str_replace("/","-",$from_date)."' and bill_book_date<='".str_replace("/","-",$to_date)."'",$db));
	//echo "Select SUM(GrandTotal) as purch_total from purchase_billbook where vendor=$vendorId AND bill_book_date>='".str_replace("/","-",$from_date)."' and bill_book_date<='".str_replace("/","-",$to_date)."'";
	}
	else
	{
		$query=DB_fetch_array(DB_query("Select SUM(pkg_charges) as pkg_total from purchase_billbook where pckg_ledger=$pkgLid AND bill_book_date>='".$_SESSION['financialYrStart']."' and bill_book_date<='".$_SESSION['financialYrEnd']."'",$db));
		//echo "Select SUM(pkg_charges) as pkg_total from purchase_billbook where pckg_ledger=$pkgLid AND bill_book_date>='".$_SESSION['financialYrStart']."' and bill_book_date<='".$_SESSION['financialYrEnd']."'";
	}
	return $query['pkg_total']; }
}
//***********************************
function yearlyAddChargesAccountByTransactions($addLid,$from_date='',$to_date='')
{
	global $db;
	if($addLid!=''){
	if($from_date!='' && $to_date!='')
	{
		$query=DB_fetch_array(DB_query("Select SUM(add_charges) as add_total from purchase_billbook where insurance_ledger=$addLid AND bill_book_date>='".str_replace("/","-",$from_date)."' and bill_book_date<='".str_replace("/","-",$to_date)."'",$db));
	//echo "Select SUM(GrandTotal) as purch_total from purchase_billbook where vendor=$vendorId AND bill_book_date>='".str_replace("/","-",$from_date)."' and bill_book_date<='".str_replace("/","-",$to_date)."'";
	}
	else
	{
		$query=DB_fetch_array(DB_query("Select SUM(add_charges) as add_total from purchase_billbook where insurance_ledger=$addLid AND bill_book_date>='".$_SESSION['financialYrStart']."' and bill_book_date<='".$_SESSION['financialYrEnd']."'",$db));
		//echo "Select SUM(add_charges) as add_total from purchase_billbook where addcharge_ledger=$addLid AND bill_book_date>='".$_SESSION['financialYrStart']."' and bill_book_date<='".$_SESSION['financialYrEnd']."'";
	}
	return $query['add_total']; }
}
//************************************

function yearlyCessAccountByTransactions($cessid,$from_date='',$to_date='')
{
	global $db;
	if($cessid!=''){
	if($from_date!='' && $to_date!='')
	{
		$query=DB_fetch_array(DB_query("SELECT A.ecess, A.shecess, SUM(A.ecess_amt) AS total_pur_cess1, 
										SUM(A.shecess_amt) AS total_pur_cess2 ,A.bill_book_date from 
										purchase_billbook A where (A.ecess=".$cessid." OR A.shecess=".$cessid.")
										AND A.bill_book_date>='".str_replace("/","-",$from_date)."' 
										AND A.bill_book_date<='".str_replace("/","-",$to_date)."'",$db));
	}
	else
	{
		$query=DB_fetch_array(DB_query("SELECT A.ecess, A.shecess, SUM(A.ecess_amt) AS total_pur_cess1, 
										SUM(A.shecess_amt) AS total_pur_cess2 ,A.bill_book_date from  
										purchase_billbook A where  (A.ecess=".$cessid." OR A.shecess=".$cessid.")
										AND A.bill_book_date>='".$_SESSION['financialYrStart']."' 
										AND A.bill_book_date<='".$_SESSION['financialYrEnd']."'",$db));
		
	}
	if($cessid==$query['ecess'])
	{$cessVal=$query['total_pur_cess1'];}
	elseif($cessid==$query['shecess'])
	{$cessVal=$query['total_pur_cess2'];}
	return $cessVal; }
}

//************************************
function yearlyLedgerPostingByTransactions($ledgerId,$from_date='',$to_date='')
{

	global $db;
	$return_array='';
	if($from_date!='' && $to_date!='')
	{
		$query1=DB_fetch_array(DB_query("Select SUM(basicAmount) as total_inv_basic from invoice where ledger_id=(".$ledgerId.") AND invoiceDate>='".str_replace("/","-",$from_date)."' and invoiceDate<='".str_replace("/","-",$to_date)."'",$db));
		
		$query2=DB_fetch_array(DB_query("Select SUM(total_item_amount) as total_pur_basic from purchase_billbook where ledger=(".$ledgerId.") AND bill_book_date>='".str_replace("/","-",$from_date)."' and bill_book_date<='".str_replace("/","-",$to_date)."'",$db));
	}
	else
	{
		$query1=DB_fetch_array(DB_query("Select SUM(basicAmount) as total_inv_basic from invoice where ledger_id in (".$ledgerId.") AND invoiceDate>='".$_SESSION['financialYrStart']."' and invoiceDate<='".$_SESSION['financialYrEnd']."'",$db));
		$query2=DB_fetch_array(DB_query("Select SUM(total_item_amount) as total_pur_basic from purchase_billbook where ledger in (".$ledgerId.") AND bill_book_date>='".$_SESSION['financialYrStart']."' and bill_book_date<='".$_SESSION['financialYrEnd']."'",$db));
		
	}
	$return_array[]=$query2['total_pur_basic'];
	$return_array[]=$query1['total_inv_basic'];
	
	return $return_array;
}
//************************************
function Get_TotalAccountByLedger($amount_type,$from_date='',$to_date='')
{
   global $db;
 if($from_date!='' && $to_date!='')  
{
     $q1=DB_query("select  SUM(B.amount) AS TAmount ,B.ledgerid  from   account_book A, account_book_details B where A.id=B.account_bookid and  B.amount_type='".$amount_type."' and  A.Dates between '".$from_date."' and '".$to_date."' and  A.cancel_status=0  group by B.amount_type ",$db);
}else{
     $q1=DB_query("select  SUM(B.amount) AS TAmount ,B.ledgerid  from  account_book A, account_book_details B where A.id=B.account_bookid and  B.amount_type='".$amount_type."' and A.cancel_status=0 group by B.amount_type ",$db);
}
    while( $RVPrefix=DB_fetch_array($q1))
 {
  
      return ($RVPrefix['TAmount']);
 }
}

function yearlyRoundOffByTransactions($roundLid,$from_date='',$to_date='')
{
	 global $db;
	 
	 if($from_date!='' && $to_date!='')
	 {
	 	$query3=DB_fetch_array(DB_query("SELECT SUM(round_off) as roundDR FROM purchase_billbook WHERE round_ledger=".$roundLid." AND pluMin='+' AND bill_book_date>='".str_replace("/","-",$from_date)."' and bill_book_date<='".str_replace("/","-",$to_date)."'",$db));
	 	$query4=DB_fetch_array(DB_query("SELECT ABS(SUM(round_off)) as roundCR FROM purchase_billbook WHERE round_ledger=".$roundLid." AND pluMin='-' AND bill_book_date>='".str_replace("/","-",$from_date)."' and bill_book_date<='".str_replace("/","-",$to_date)."'",$db));
	 }
	 else
	 {
	// echo "<br />SELECT SUM(round_off) as roundDR FROM purchase_billbook WHERE round_ledger=".$roundLid." AND round_off>0 AND bill_book_date>='".$_SESSION['financialYrStart']."' and bill_book_date<='".$_SESSION['financialYrEnd']."'";
	//echo "<br />SELECT SUM(round_off) as roundCR FROM purchase_billbook WHERE round_ledger=".$roundLid." AND round_off<0 AND bill_book_date>='".$_SESSION['financialYrStart']."' and bill_book_date<='".$_SESSION['financialYrEnd']."'";
		$query3=DB_fetch_array(DB_query("SELECT SUM(round_off) as roundDR FROM purchase_billbook WHERE round_ledger=".$roundLid." AND pluMin='+' AND bill_book_date>='".$_SESSION['financialYrStart']."' and bill_book_date<='".$_SESSION['financialYrEnd']."'",$db));
	 	$query4=DB_fetch_array(DB_query("SELECT ABS(SUM(round_off)) as roundCR FROM purchase_billbook WHERE round_ledger=".$roundLid." AND pluMin='-' AND bill_book_date>='".$_SESSION['financialYrStart']."' and bill_book_date<='".$_SESSION['financialYrEnd']."'",$db));
		//echo "<br />".$query3['roundDR'];
		//echo "<br />".$query4['roundCR'];		
	 }
	 	$return_array[]=$query3['roundDR'];
		$return_array[]=$query4['roundCR'];
		return $return_array;
}
//******************************************************////






//Function for Balance Sheet for calculating consolidated amount under each group//
function getGroupBalanceSheet($group_id,$from_date='',$to_date='')
{
	global $db;
	//echo "from---".$from_date."to---".$to_date;
	//echo "SELECT GroupId FROM accountgroupmaster WHERE MainGroupId=".$group_id." ";
	$sql1=DB_query("SELECT GroupId FROM accountgroupmaster WHERE MainGroupId=".$group_id." ",$db);
	$ar='';
	$ledger_arr='';
	while($res1=DB_fetch_array($sql1))
	{$ar[]=$res1['GroupId'];}
	//echo $group_id;
	//print_r($ar); echo "<br />";
	if($ar!='')
	{
		$underLevels=getUnderGroupTree($ar,'');
		//echo "underlevels--";print_r($underLevels);echo "<br />";
		if($underLevels!='')
		{$groups=$underLevels;}
		else
		{$groups=$ar;}
		//print_r($groups); echo "<br /><br />";
		$allGroups=$group_id.','.implode(',',$groups);
		 $getDirectLedgers="Select AccountsID from accountledger where UnderGroup in (".$allGroups.")";
		$directLedgersResult=DB_query($getDirectLedgers,$db);
	}
	else
	{
		$getDirectLedgers="Select AccountsID from accountledger where UnderGroup=".$group_id."";
		$directLedgersResult=DB_query($getDirectLedgers,$db);
	}
		
		//echo "<b />****************************************<br />";
		$ledger_arr='';$tot_VoucherDR='';$tot_VoucherCR='';$tot_CR_open='';$tot_DR_open='';$etaxDetails1='';$staxDetails1='';
		$vendorDetails1='';$clientDetails1='';$etaxDRArr='';$etaxCRArr='';$staxDRArr='';$staxCRArr='';$purchCRArr='';$invDRArr='';
		$legderDRArr='';$legderCRArr='';$freightDetails='';$freightDR='';$freightDRArr='';$surDetails='';$surDR='';$surDRArr='';
		$packDetails='';$packDR='';$packDRArr='';$addDetails='';$addDR='';$addDRArr='';$cessDetails='';$cessDRArr='';
		$roundDetails='';$roundDRArray[]='';$roundCRArray[]='';
		
		$a1='';$a2='';$b1='';$b2='';$c1='';$c2='';$d1='';$d2='';
		
		while($directLedgers=DB_fetch_array($directLedgersResult))
		{$ledger_arr[]=$directLedgers['AccountsID'];}
		//echo "-----".$group_id; echo "<br />";
		//echo "ledger_array--";print_r($ledger_arr); echo "<br /><br />";
		
if($ledger_arr!='')
{
			
	$ledger_string=implode(',',$ledger_arr);
	if($from_date!='' && $to_date!='')
	{
		$tot_VoucherDR=Get_AccountByLedger($ledger_string,'DR',$from_date,$to_date);
		$tot_VoucherCR=Get_AccountByLedger($ledger_string,'CR',$from_date,$to_date);
	}else{
	$tot_VoucherDR=Get_AccountByLedger($ledger_string,'DR','','');
	$tot_VoucherCR=Get_AccountByLedger($ledger_string,'CR','','');}
	
	if($from_date!='' && $to_date!=''){
	$tot_CR_open=getLedgerOpenings($ledger_string,'CR',$from_date,$to_date);
	$tot_DR_open=getLedgerOpenings($ledger_string,'DR',$from_date,$to_date);
	}else{
	$tot_CR_open=getLedgerOpenings($ledger_string,'CR','','');
	$tot_DR_open=getLedgerOpenings($ledger_string,'DR','',''); }
	
	
	/*if($etaxDRArr!='')$A1=array_sum($etaxDRArr); //echo "1--";print_r($etaxDRArr); echo "<br />";
	if($etaxCRArr!='')$A2=array_sum($etaxCRArr); //echo "2--";print_r($etaxCRArr);echo "<br />";
	if($staxDRArr!='')$B1=array_sum($staxDRArr); //echo "3--";print_r($staxDRArr);echo "<br />";
	if($staxCRArr!='')$B2=array_sum($staxCRArr); //echo "4--";print_r($staxCRArr);echo "<br />";
	if($purchCRArr!='')$C2=array_sum($purchCRArr); //echo "5--";print_r($purchCRArr);echo "<br />";
	if($invDRArr!='')$C1=array_sum($invDRArr); //echo "6--";print_r($invDRArr);echo "<br />";
	if($legderDRArr!='')$D1=array_sum($legderDRArr);  //echo "7--";print_r($legderDRArr);echo "<br />";
	if($legderCRArr!='')$D2=array_sum($legderCRArr); //echo "8--";print_r($legderCRArr);echo "<br />";
	if($freightDRArr!='')$E1=array_sum($freightDRArr); //echo "9--";print_r($freightDRArr);echo "<br />";
	if($surDRArr!='')$F1=array_sum($surDRArr); //echo "10--";print_r($surDRArr);echo "<br />";
	if($packDRArr!='')$G1=array_sum($packDRArr); //echo "11--";print_r($packDRArr);echo "<br />";
	if($addDRArr!='')$H1=array_sum($addDRArr); //echo "12--";print_r($addDRArr);echo "<br />";
	if($cessDRArr!='')$I1=array_sum($cessDRArr); //echo "13--";print_r($cessDRArr);echo "<br />";
	if($roundDRArray!='')$J1=array_sum($roundDRArray); //echo "13--";print_r($cessDRArr);echo "<br />";
	if($roundCRArray!='')$J2=array_sum($roundCRArray); //echo "13--";print_r($cessDRArr);echo "<br />";
	//echo "<br />----------------<br /><br />";*/



		}
$TD=$tot_VoucherDR;
$TC=$tot_VoucherCR;
	
$return_array[]=$TD;
$return_array[]=$TC;	
$return_array[]=$tot_DR_open;
$return_array[]=$tot_CR_open;
return $return_array;
}
	
function getLedgerOpenings($ledgers,$type,$from_date,$to_date)
{
	global $db;
	global $s;
	$openingvalue='';
	$ledger1=explode(",",$ledgers);
	if(empty($ledger1))
    $ledger1=$ledgers;
for($i=0;$i<count($ledger1);$i++)
{
	$ledgertype=$s->GetFieldValue("accountledger","AccountsID in('".$ledger1[$i]."')","ledgertype");
	if($from_date!='' && $to_date!='')
	{
        
        
		 $query="Select SUM(B.openingBalance) as total_opening from accountledger A inner join accountledger_dtls B on A.AccountsID=B.accountledger_id where A.AccountsID in (".$ledger1[$i].") and B.openingtype='$type' and B.openingdate<='".str_replace('/','-',$to_date)."'";
	    
	 }
	else
	{
	 
		$query="Select SUM(B.openingBalance) as total_opening from accountledger A inner join accountledger_dtls B on A.AccountsID=B.accountledger_id where A.AccountsID in (".$ledger1[$i].") and B.openingtype='$type' ";
	   
	     
	//$query="Select SUM(openingBalance) as total_opening from accountledger where AccountsID in ($ledgers) and openingtype='$type'";
	 }
	$res=DB_query($query,$db);
	$row=DB_fetch_array($res);
   $openingvalue=$openingvalue+$row['total_opening'];
  }
	//echo $query;
	//$res=DB_query($query,$db);
	//$row=DB_fetch_array($res);
	return $openingvalue;
}

function getMonthsBalanceSheet($lid,$month,$yr,$flag='')
{
	global $db;
		
		
		$QUERY11=DB_fetch_array(DB_query("Select vender_client from accountledger where AccountsID=$lid",$db));
		$QUERY22=DB_fetch_array(DB_query("Select taxid from accountledger where AccountsID=$lid",$db));
		$QUERY33=DB_fetch_array(DB_query("Select ledgertype from accountledger where AccountsID=$lid",$db));
		
		$master_party_id=$QUERY11['vender_client'];
		$master_tax_id=$QUERY22['taxid'];
		$ledgertype=$QUERY33['ledgertype'];
		//echo "<br />flag---".$flag;
		//echo "isset---".isset($flag);
//////******* Conditions of dates (User selected period or financial year dates) NOT TO BE INCLUDED IN THE QUERIES**********//
if($flag!='0'){ 
		if(isset($flag)==1 && $flag!=''){
		if($flag==1)
		{
		$cond1="A.Dates between '".str_replace('/','-',$_SESSION['FDATE'])."' and '".str_replace('/','-',$_SESSION['TDATE'])."'";
		//$cond2="A.bill_book_date between '".str_replace('/','-',$_SESSION['FDATE'])."' and '".str_replace('/','-',$_SESSION['TDATE'])."'";
		//$cond3="invoiceDate between '".str_replace('/','-',$_SESSION['FDATE'])."' and '".str_replace('/','-',$_SESSION['TDATE'])."'";
		}
		elseif($flag==2)
		{
		$cond1="A.Dates >= '".str_replace('/','-',$_SESSION['FDATE'])."' and MONTH(A.Dates)=$month";
		//$cond2="A.bill_book_date >= '".str_replace('/','-',$_SESSION['FDATE'])."' and MONTH(A.bill_book_date)=$month";
		//$cond3="invoiceDate >= '".str_replace('/','-',$_SESSION['FDATE'])."' and MONTH(invoiceDate)=$month";
		}
		elseif($flag==3)
		{
		$cond1="A.Dates <= '".str_replace('/','-',$_SESSION['TDATE'])."' and MONTH(A.Dates)=$month";
		//$cond2="A.bill_book_date <= '".str_replace('/','-',$_SESSION['TDATE'])."' and MONTH(A.bill_book_date)=$month";
		//$cond3="invoiceDate <= '".str_replace('/','-',$_SESSION['TDATE'])."' and MONTH(invoiceDate)=$month";
		}
		elseif($flag==4)
		{
		$cond1="MONTH(A.Dates)=$month";
		//$cond2="MONTH(A.bill_book_date)=$month";
		//$cond3="MONTH(invoiceDate)=$month";
		}
		}
		elseif(isset($flag)==1 && $flag=='')
		{
		$cond1="MONTH(A.Dates)='$month' and YEAR(A.Dates)='$yr'";
		//$cond2="MONTH(A.bill_book_date)=$month and YEAR(A.bill_book_date)=$yr";
		//$cond3="MONTH(invoiceDate)=$month and YEAR(invoiceDate)=$yr";
		}
//****************************************************************************************//		
		//echo $cond1."<br />";
		//echo $cond2."<br />";echo $cond3."<br />";
		//echo $ledgertype;
		$getVoucherCR=DB_fetch_array(DB_query("Select SUM(B.amount) as TCRAmount from account_book A, account_book_details B where A.id=B.account_bookid and B.ledgerid=$lid and B.amount_type='CR' and A.cancel_status=0 and $cond1",$db));
		$getVoucherDR=DB_fetch_array(DB_query("Select SUM(B.amount) as TDRAmount from account_book A, account_book_details B where A.id=B.account_bookid and B.ledgerid=$lid and B.amount_type='DR' and A.cancel_status=0 and $cond1",$db));
		
	
	$totalDR=$getVoucherDR['TDRAmount'];
	$totalCR=$getVoucherCR['TCRAmount'];
	
	$return_array[]=$totalDR;
	$return_array[]=$totalCR;
	
	return $return_array; }
}

function monthlyLedgerAccount($ledgerid,$lastmonth,$lastyr,$type,$currmonth,$prevdate='')
{
	global $db;
	if($lastmonth<=9){$mnth="0".$lastmonth;}else{$mnth=$lastmonth;}
	if($mnth=='04')
	{
		$lastFinanceStart=$_SESSION['financialYrStart'];
		$lastFinanceEnd=$_SESSION['financialYrEnd'];
	}
	if($prevdate!='')
	{
		$sql="Select SUM(B.amount) as TAMOUNT from account_book A, account_book_details B where A.id=B.account_bookid
		 and B.ledgerid=$ledgerid and A.Dates between '".$_SESSION['financialYrStart']."' and '".$prevdate."' and B.amount_type='$type'
		  and A.cancel_status=0 "; 
	//echo "<br />111-".$sql;
		$result=DB_query($sql,$db);
		$row=DB_fetch_array($result);
	}else{
	if($currmonth!='04')
	{
		$lastDateofPreviousMonth=date("Y-m-d", strtotime('-1 second',strtotime('+1 month',strtotime(date($mnth).'/01/'.date($lastyr).' 00:00:00'))));
		$sql="Select SUM(B.amount) as TAMOUNT from account_book A, account_book_details B where A.id=B.account_bookid
		 and B.ledgerid=$ledgerid and A.Dates between '".$_SESSION['financialYrStart']."' and '".$lastDateofPreviousMonth."' and B.amount_type='$type' and A.cancel_status=0"; //echo "<br />222-".$sql;
		$result=DB_query($sql,$db);
		$row=DB_fetch_array($result);
		
	}}
	return $row['TAMOUNT'];
}
//****** CONCEPT SIMILAR TO ABOVE
function monthlyLedgerOpenings($ledgerid,$lastmonth,$lastyr,$currmonth,$prevdate='')
{
	global $db;
	if($lastmonth<=9){$mnth="0".$lastmonth;}else{$mnth=$lastmonth;}
	if($mnth=='04')
	{
		$lastFinanceStart=$_SESSION['financialYrStart'];
		$lastFinanceEnd=$_SESSION['financialYrEnd'];
	}
	if($prevdate!='')
	{
		$last_date=$prevdate;
	}
	else
	{
		if($currmonth!='04')
		{
			$last_date=date("Y-m-d", strtotime('-1 second',strtotime('+1 month',strtotime(date($mnth).'/01/'.date($lastyr).' 00:00:00'))));
		}
	}
	$eDRARR='';$eCRARR='';
	$sDRARR='';$sCRARR='';
	$purchCRARR='';$invDRARR='';
	$ledgerDRARR='';$ledgerCRARR='';
	$ledgerDetailsSQL=DB_query("Select * from accountledger where AccountsID in ($ledgerid)",$db);
	while($ledgerDetailRow=DB_fetch_array($ledgerDetailsSQL))
	{
		$ledgertype=$ledgerDetailRow['ledgertype'];
		$master_tax_id=$ledgerDetailRow['taxid'];
		$master_party_id=$ledgerDetailRow['vender_client'];
		if($ledgertype!='')
		{
			if($ledgertype=='excisetax')
			{
				$etaxDetails=yearlyETaxAccountByTransactions($master_tax_id,$_SESSION['financialYrStart'],$last_date);
				$eTaxDR=$etaxDetails[0]; $eDRARR[]=$eTaxDR;
				$eTaxCR=$etaxDetails[1]; $eCRARR[]=$eTaxCR;
			}else{$eTaxDR='';$eTaxCR='';}
			if($ledgertype=='salestax')
			{
				$staxDetails=yearlySTaxAccountByTransactions($master_tax_id,$_SESSION['financialYrStart'],$last_date); 
				$sTaxDR=$staxDetails[0]; $sDRARR[]=$sTaxDR; 
				$sTaxCR=$staxDetails[1]; $sCRARR[]=$sTaxCR;
			}else{$sTaxDR='';$sTaxCR='';}
			if($ledgertype=='vendor')
			{
				$vendorDetails=yearlyVendorAccountByTransactions($master_party_id,$_SESSION['financialYrStart'],$last_date);
				$purchCR=$vendorDetails; $purchCRARR[]=$purchCR;
			}else{$vendorDetails='';$purchCR='';}
			if($ledgertype=='client')
			{
				$clientDetails=yearlyClientAccountByTransactions($master_party_id,$_SESSION['financialYrStart'],$last_date); 
				$invDR=$clientDetails; $invDRARR[]=$invDR;
			}else{$invDR='';}		
		}
		else
		{
			$ledgerPosting=yearlyLedgerPostingByTransactions($ledgerDetailRow['AccountsID'],$_SESSION['financialYrStart'],$last_date); 
			$ledgerDR=$ledgerPosting[0]; $ledgerDRARR[]=$ledgerDR;
			$ledgerCR=$ledgerPosting[1]; $ledgerCRARR[]=$ledgerCR;
		}
	}
	if($eDRARR!='')$aa=array_sum($eDRARR);
	if($eCRARR!='')$bb=array_sum($eCRARR);
	if($sDRARR!='')$cc=array_sum($sDRARR);
	if($sCRARR!='')$dd=array_sum($sCRARR);
	if($invDRARR!='')$ee=array_sum($invDRARR);
	if($purchCRARR!='')$ff=array_sum($purchCRARR);
	if($ledgerDRARR!='')$gg=array_sum($ledgerDRARR);
	if($ledgerCRARR!='')$hh=array_sum($ledgerCRARR);
	
	$TotalOPDR=$aa+$cc+$ee+$gg;
	$TotalOPCR=$bb+$dd+$ff+$hh;
	
	$return_arr[]=$TotalOPDR;
	$return_arr[]=$TotalOPCR;
	
	return $return_arr;
}

 function proffitAndLoss()
 {
 	global $db;
	$table='accountgroupmaster';
	//echo "Select GroupId from accountgroupmaster where GroupName='EXPENSE'";
	$getExpenseId=DB_fetch_array(DB_query("Select GroupId from accountgroupmaster where GroupName='EXPENSE'",$db));
	$ExpenseId=$getExpenseId['GroupId'];
	//getExpenseId=$s->getField($table,'GroupName','EXPENSE','GroupId');
	//echo "select * from $table where NatureOfGroup=$ExpenseId and MainGroupId=0";
	$getUnderGroups=DB_query("select * from $table where NatureOfGroup=$ExpenseId and MainGroupId=0",$db);
		
		while($underGroups=DB_fetch_array($getUnderGroups))
		{
			$x='';
			if($_SESSION['FDATE']!='' && $_SESSION['TDATE']!='')
			{$x=getGroupBalanceSheet($underGroups['GroupId'],$_SESSION['FDATE'],$_SESSION['TDATE']);}
			else{$x=getGroupBalanceSheet($underGroups['GroupId'],'',''); 
					
		}
		unset($_SESSION['down_acc_group']);
		$acc_down_grp=getallundergroups($underGroups['GroupId']);
		if(empty($acc_down_grp))
		  $acc_down_grp[]=$underGroups['GroupId'];
		else
		  array_push($acc_down_grp, $underGroups['GroupId']);
		$opening_pl_expense=getgroupopening($acc_down_grp);
		//echo '<pre>';
			//print_r($opening_pl_expense);
			if($opening_pl_expense[0]==''|| $opening_pl_expense[0]=='')
				{ $x[2]=0;$x[3]=0; }
			if($opening_pl_expense[1]=='DR')
				$x[2]=$opening_pl_expense[0];
			else if($opening_pl_expense[1]=='CR')
				$x[3]=$opening_pl_expense[0];
			//if($x[0]>$x[1]){$LIABDR=$x[0]-$x[1];$LIABDR_ARR[]=$LIABDR;}
			//elseif($x[1]>$x[0]){$LIABCR=$x[1]-$x[0];$LIABCR_ARR[]=$LIABCR;}

			  $tot_expense_deb=$x[0]+$x[2];
			//echo '<br>';
			   $tot_expense_cre=$x[1]+$x[3];

			if($tot_expense_deb>$tot_expense_cre)
				{$LIABDR=$tot_expense_deb-$tot_expense_cre;$LIABDR_ARR[]=$LIABDR;}
			else if($tot_expense_deb<$tot_expense_cre)
				{$LIABCR=$tot_expense_cre-$tot_expense_deb;$LIABCR_ARR[]=$LIABCR;}	
			else		
				{$LIABDR='';$LIABCR='';}
		} 
		
		//echo '<pre>';
		//print_r($LIABDR_ARR);
		//print_r($LIABCR_ARR);
	if($LIABDR_ARR!=''){  $sum1=array_sum($LIABDR_ARR);}
    if($LIABCR_ARR!=''){$sum2=array_sum($LIABCR_ARR);}
    if($sum1>$sum2){$expense=($sum1-$sum2); $expense_type='DR';}else{$expense=($sum2-$sum1);$expense_type='CR';}
 
 	$getIncomeId=DB_fetch_array(DB_query("Select GroupId from accountgroupmaster 
 		where GroupName='INCOME'",$db));
	$IncomeId=$getIncomeId['GroupId'];
 
 		//$getIncomeId=$s->getField($table,'GroupName','INCOME','GroupId');
		//echo "select * from $table where NatureOfGroup=$IncomeId and MainGroupId=0";
	  $getUnderGroups=DB_query("select * from $table where NatureOfGroup=$IncomeId and MainGroupId=0",$db);
		while($underGroups=DB_fetch_array($getUnderGroups))
		{
			if($_SESSION['FDATE']!='' && $_SESSION['TDATE']!='')
			{ $y=getGroupBalanceSheet($underGroups['GroupId'],$_SESSION['FDATE'],$_SESSION['TDATE']);}
			else{ $y=getGroupBalanceSheet($underGroups['GroupId'],'','');}
			
			//if($y[0]>$y[1]){$ASSDR=$y[0]-$y[1];  $ASSDR_ARR[]=$ASSDR;}
			//elseif($y[1]>$y[0]){$ASSCR=$y[1]-$y[0]; $ASSCR_ARR[]=$ASSCR;}

			unset($_SESSION['down_acc_group']);
		$acc_down_grp1=getallundergroups($underGroups['GroupId']);
		if(empty($acc_down_grp1))
		  $acc_down_grp1[]=$underGroups['GroupId'];
		else
		  array_push($acc_down_grp1, $underGroups['GroupId']);
		$opening_pl_income=getgroupopening($acc_down_grp1);
		//echo '<pre>';
		//	print_r($opening_pl_income);
			if($opening_pl_income[0]==''|| $opening_pl_income[0]=='')
				{ $y[2]=0;$y[3]=0; }
			if($opening_pl_income[1]=='DR')
				$y[2]=$opening_pl_income[0];
			else if($opening_pl_income[1]=='CR')
				$y[3]=$opening_pl_income[0];

			$tot_income_deb=$y[0]+$y[2];
			  $tot_income_cre=$y[1]+$y[3];

			if($tot_income_deb>$tot_income_cre)
				{$ASSDR=$tot_income_deb-$tot_income_cre;$ASSDR_ARR[]=$ASSDR;}
			else if($tot_income_deb<$tot_income_cre)
				{$ASSCR=$tot_income_cre-$tot_income_deb;$ASSCR_ARR[]=$ASSCR;}	
			else		
				{$ASSDR='';$ASSCR='';}
			
		} 
 		
 		if($ASSDR_ARR!=''){ $sumA1=array_sum($ASSDR_ARR);}
   if($ASSCR_ARR!=''){ $sumA2=array_sum($ASSCR_ARR);}
  if($sumA1>$sumA2){$income=($sumA1-$sumA2); $income_type='DR'; }else{$income=($sumA2-$sumA1); $income_type='CR';}
 
  if($expense_type==$income_type)
  {
     if($expense_type=='CR')
	 {
	 	$proffit=$expense+$income;
		$proffit_type=$expense_type;
	 }
	 elseif($expense_type=='DR')
	 {
	 	$loss=$expense+$income;
		$loss_type=$expense_type;
	 }
  }
  elseif($expense_type!=$income_type)
  {
  		if($expense>$income)
		{
			$value=$expense-$income;
			$value_type=$expense_type;
		}
		elseif($income>$expense)
		{
			$value=$income-$expense;
			$value_type=$income_type;
		}
		
		if($value_type=='CR')
		{$proffit=$value;$proffit_type=$value_type;}
		elseif($value_type=='DR')
		{$loss=$value;$loss_type=$value_type;}
  }
  else{$loss=''; $loss_type=''; $proffit=''; $proffit_type='';}
 
 $return_array[]=$proffit;
 $return_array[]=$proffit_type;
 $return_array[]=$loss;
 $return_array[]=$loss_type;
 
 return $return_array;
 
 } 


function getledgeropeningyearwise($ledgerid)
{
	 	global $db;
	 	$posted_led='';
	 	$opening_amt='';

	$opening_bal='';
	$opening_type='';
	$dramt='';
	$cramt='';
	 	$sql1=DB_query("select A.AccountsID, B.openingtype,B.openingBalance as openingBalance ,B.openingdate from accountledger_dtls B 
	 inner join accountledger A on  A.AccountsID=B.accountledger_id where A.AccountsID='".$ledgerid."'",$db);
	 	//echo "select * from accountledger where AccountsID='".$ledgerid."'"."<br>";
	while($led_sql1=DB_fetch_assoc($sql1))
	 {
	 

	         $opening_amt[$led_sql1['openingtype']][]=$led_sql1['openingBalance']; 
	        }
	      

	         if(!empty($opening_amt[DR]))
	          $dramt=array_sum($opening_amt[DR]);
	          if(!empty($opening_amt[CR]))
	          $cramt=array_sum($opening_amt[CR]);
	         
	         if($dramt>$cramt)
	         {
	         $opening_bal=$dramt-$cramt;
	         $opening_type='DR';
	         }
	         else
	         {
	         $opening_bal=$cramt-$dramt;   
	         $opening_type='CR';   
             }	
	$led_sql=DB_fetch_assoc(DB_query("select A.AccountsID, B.openingtype,B.openingBalance as openingBalance ,B.openingdate from accountledger_dtls B 
	 inner join accountledger A on  A.AccountsID=B.accountledger_id where A.AccountsID='".$ledgerid."' group by A.AccountsID ",$db));
	//echo $led_sql['openingdate'];
	//echo $led_sql['openingdate'];
	//echo "<br>".$led_sql['openingdate'];
	$open_date=date('Y-m-d', strtotime($led_sql['openingdate']));
	 $strt_date=date('Y-m-d', strtotime($_SESSION['financialYrStart']));
	$end_date=date('Y-m-d', strtotime($_SESSION['financialYrEnd']));
	$posted_led=postedclosingledger_array($ledgerid);

	if($open_date>=$strt_date && $open_date<=$end_date)
		{
            
			$led_opening[]=$opening_bal;
			$led_opening[]=$opening_type;
		}
		else if(!empty($posted_led))
		{
	     if(array_key_exists($led_sql['AccountsID'], $posted_led))
		{
			$led_opening[]=$posted_led[$led_sql['AccountsID']]['manual_closing_amt'];
			$led_opening[]=$posted_led[$led_sql['AccountsID']]['manual_closing_type'];
		}
	}
	else
		{
		$led_opening[]=0;
		//$led_opening[]='DR';
		}
	
	//	print_r($led_opening);
	return $led_opening;
}

function postedclosingledger_array($ledgerid)
{
	global $db;
	$srt_yr=explode('-', $_SESSION['financialYrStart']);
 	$end_yr=explode('-', $_SESSION['financialYrEnd']);
 	$prev_srt_yr1=$srt_yr[0]-1;
 	$prev_end_yr1=$end_yr[0]-1;
 	//echo "select ledgerid,manual_closing_amt,manual_closing_type from acc_fin_yr_closing where start_yr='".$prev_srt_yr1."' and end_yr='".$prev_end_yr1."' and ledgerid='".$ledgerid."' "."<br>";
	$posted_led_sql=DB_query("select ledgerid,manual_closing_amt,manual_closing_type from acc_fin_yr_closing 
		where start_yr='".$prev_srt_yr1."' 
		and end_yr='".$prev_end_yr1."' and ledgerid='".$ledgerid."' ",$db);
	while($posted_led_res1=DB_fetch_assoc($posted_led_sql))
	{
		$posted_led_res[$posted_led_res1['ledgerid']]=$posted_led_res1;
	}
	return $posted_led_res;
}


/* function getledgeropeningyearwise($ledgerid)
{
	 	global $db;
	 	$posted_led='';
	 //	echo "select * from accountledger where AccountsID='".$ledgerid."'"."<br>";
	$led_sql=DB_fetch_assoc(DB_query("select * from accountledger where AccountsID='".$ledgerid."'",$db));
	 $led_sql['ledgertype'];
  
     
       $sql_check_dtls=DB_query("select B.openingtype,B.openingBalance  from accountledger_dtls B  inner join accountledger A on
		           A.AccountsID=B.accountledger_id where A.AccountsID='".$led_sql['AccountsID']."'  ",$db); 
		         
		           while($row_dtls=DB_fetch_array($sql_check_dtls))
			        {
			         $opening_amt[$row_dtls['openingtype']][]=$row_dtls['openingBalance']; 
			        }
         
			          if(!empty($opening_amt[DR]))
			          {
			          $openingDR=array_sum($opening_amt[DR]);
			          $led_opening[DR]=$openingDR;
			          //$led_opening[]='DR';
			          }
			          if(!empty($opening_amt[CR]))
			          {
			          $openingCR=array_sum($opening_amt[CR]);
			          $led_opening[CR]=$openingCR;
			          //$led_opening[]='CR';
                      }  
   
	// echo "<pre>";
     //print_r($led_opening);

	return $led_opening;
}*/

function getallundergroups($groupid)
{
	global $db;
	$group_sql=DB_query("SELECT GroupId FROM accountgroupmaster where  MainGroupId='".$groupid."'",$db) ; 
	while($group_res1=DB_fetch_assoc($group_sql))
		{
		
			$_SESSION['down_acc_group'][]=$group_res1['GroupId'];
			//$dwn_grp_arr[$k]=$groupid;
			getallundergroups($group_res1['GroupId'],$group_res);		
		}	

		return $_SESSION['down_acc_group'];
}
function getgroupopening($group_res)
{
	global $db;
	foreach($group_res as $key => $val)
	{
		//echo "select * from accountledger where UnderGroup='".$val."'";
		//echo "select * from accountledger where CompanyId='".$_SESSION['ACGCompanyId']."' and  UnderGroup='".$val."'";
		$led_sql=DB_query("select * from accountledger where CompanyId='".$_SESSION['ACGCompanyId']."' and  UnderGroup='".$val."'",$db);
		while($led_res=DB_fetch_assoc($led_sql))
		{
			//echo $led_res['AccountsID'];
			$open_array=getledgeropeningyearwise($led_res['AccountsID']);
			if($open_array[0]!=0)
			{
				if($open_array[1]=='DR')
					$open_amt_dr[]=$open_array[0];
				else if($open_array[1]=='CR')	
					$open_amt_cr[]=$open_array[0];
			}
		}

	}
		  if(!empty($open_amt_dr))
		  $tot_dr=array_sum($open_amt_dr);
		  else
		 $tot_dr=0; 	
		if(!empty($open_amt_cr))
		  $tot_cr=array_sum($open_amt_cr);
		else
			$tot_cr=0;
		if($tot_dr<$tot_cr)
			{$final_opening[]=$tot_cr-$tot_dr;
			 $final_opening[]='CR';}		
		elseif($tot_dr>$tot_cr)
			{$final_opening[]=$tot_dr-$tot_cr;
			 $final_opening[]='DR';}
			 
	return $final_opening;
}


function getledgeropeningyearwiseledgerwise($ledgerid)
{
	 	global $db;
	 	$posted_led='';
	 	$opening_amt='';

	$opening_bal='';
	$opening_type='';
	$dramt='';
	$cramt='';
	 	$sql1=DB_query("select A.AccountsID, B.openingtype,B.openingBalance as openingBalance ,B.openingdate from accountledger_dtls B 
	 inner join accountledger A on  A.AccountsID=B.accountledger_id where A.AccountsID='".$ledgerid."'",$db);
	 	//echo "select * from accountledger where AccountsID='".$ledgerid."'"."<br>";
	while($led_sql1=DB_fetch_assoc($sql1))
	 {
	 

	         $opening_amt[$led_sql1['openingtype']][]=$led_sql1['openingBalance']; 
	        }
	      

	         if(!empty($opening_amt[DR]))
	            $dramt=array_sum($opening_amt[DR]);
	          if(!empty($opening_amt[CR]))
	          $cramt=array_sum($opening_amt[CR]);
	         
	         if($dramt>$cramt)
	         {
	         $opening_bal=$dramt-$cramt;
	         $opening_type='DR';
	         }
	         else
	         {
	         $opening_bal=$cramt-$dramt;   
	         $opening_type='CR';   
             }	
               
			$led_opening[]=$opening_bal;
			$led_opening[]=$opening_type;
	
	
		//print_r($led_opening);
	return $led_opening;
}

   ?>  




 