<?php include_once('database_connection.php');
if(!(isset($_SESSION['userid'])))
{
   $res=array('status'=>"Error",'description'=>'Session Expired , Please Login  First ');
   echo json_encode($res);
   return;
}
else
{
  $Userid=$_SESSION['userid'];
}
if(isset($_GET['action']))
{
	$branches=array();
$branches[0][0]='[Makaw_BR-1].dbo.';
$branches[0][1]=2;
$branches[1][0]='[Makaw_BR-2].dbo.';
$branches[1][1]=3;

$branches=getBranches($connection);
$branches1=json_decode($branches);
$branches=$branches1;
	if($_GET['action']=="TransferAccounts")
	{
		$COAID=$_POST['COAID'];
		//get all the branches 
		
/*print_r($branches);
return;*/
					foreach ($branches as $key => $value) {
	
		# code...
	$value1=$value;
   $value=$value->DbName;
   $GodownID=$value1->GodownID;

$Prefix=getnamesingle("Godowns","AdditionalInfo3","GodownID",$GodownID,$connection);	
$Under=getnamesingle("accounts","Under","COAID",$COAID,$connection);	

		$COAID=$_POST['COAID'];
$COAID1=floatval($Prefix)+floatval($COAID);
$Under=floatval($Prefix)+floatval($Under);

$sqlupdate="delete from ".$value."accounts where COAID=".$COAID1;
odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);


					$sql="insert into ".$value."accounts(COAID,Under,Active,
            
            [Group],
            COAName ,
            Degree ,
            NatureID,CreateLog) select $COAID1,$Under,Active,
            [Group],
            COAName ,
            Degree ,
            
            NatureID,CreateLog from accounts where COAID=$COAID and active=1  ";
		odbc_exec($connection,$sql) or die(odbc_error().$sql);
		

				}//end for each 
	}
	if($_GET['action']=="DeleteAccountsGroup")
	{
		$res="";//array();
	odbc_autocommit($connection, FALSE);	
	$SideBarID=$_GET['SideBarID'];		
	$permission=userrights($Userid,$SideBarID,'[Delete]',$connection);
		if($permission==1)
		{
		if(isset($_GET['COAID']) && $_GET['COAID']>0)
			{
				$COAID=$_GET['COAID'];
			
			$sql="select * from accounts where under=$COAID and active=1";
			$result=odbc_exec($connection,$sql);
			if(odbc_num_rows($result)>0)
				{
	 $res=array('status'=>"Error",'description'=>'Can not Delete Accounts , Please Delete Transaction and Under Account Heads First ');
				}
				else
				{
					$sqlupdate="update accounts set active=0 where COAID=$COAID";
					odbc_exec($connection,$sqlupdate);
						 $res=array('status'=>"ok",'description'=>'Record Deleted Sucessfully');
				}

			}
		}

	if (!odbc_error())
{
      odbc_commit($connection);
      if($res=="" || $res==null)
	    $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
}
else
{
      odbc_rollback($connection);
	    $res=array('status'=>"Error",'description'=>'Data Not Updated');

}
		echo json_encode($res);

	}
	if($_GET['action']=="DeleteAccounts")
	{
		$res="";
	odbc_autocommit($connection, FALSE);		
	$SideBarID=$_GET['SideBarID'];		
	$permission=userrights($Userid,$SideBarID,'[Delete]',$connection);
		if($permission==1)
		{

			if(isset($_GET['COAID']) && $_GET['COAID']>0)
			{
				$COAID=$_GET['COAID'];
				$sql=" Select * from voucherdetails where (ledgerid=$COAID or CreditLedgerID=$COAID) and isDelete=0 and 
 voucherid not  in (select voucherid from vouchermaster where LedgerID=$COAID and VoucherTypeid=0)";
				$result=odbc_exec($connection,$sql);
				if(odbc_num_rows($result)>0)
				{
	 $res=array('status'=>"Error",'description'=>'Can not Delete Accounts , Please Delete Transaction First ');
				}
				else
				{
					$sqlupdate="update accounts set active=0 where COAID=$COAID";
					odbc_exec($connection,$sqlupdate);
						//delete opening balance
					$sqlupdate="update VoucherMaster set active=0 where LedgerID=$COAID";
					odbc_exec($connection,$sqlupdate);
					
					//delete opening vouchers
					$sqlupdate="update VoucherDetails set isDelete=0 where (LedgerID=$COAID) ";
					odbc_exec($connection,$sqlupdate);

					$sqlupdate="delete VoucherDetails where (LedgerID=$COAID)";
					odbc_exec($connection,$sqlupdate);

						 $res=array('status'=>"ok",'description'=>'Record Deleted Sucessfully');	 
				}
			}
			else
			{
					$COAID="";
						 $res=array('status'=>"Error",'description'=>'Error Found ');
			}
		}
		else
		{
									 $res=array('status'=>"Error",'description'=>'Sorry,You Dont have Permission to Delete Account ');

		}	
if (!odbc_error())
{
      odbc_commit($connection);
	    if($res=="")
	    $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
}
else
{
      odbc_rollback($connection);
	    $res=array('status'=>"Error",'description'=>'Data Not Updated');

}
		echo json_encode($res);

	}
	if($_GET['action']=="CashCollectionDetails")
	{



		$showAll=0;
		$data=array();
					$today=date("Y-m-d");

			if(isset($_GET['GodownID']) && $_GET['GodownID']>0 && $_GET['GodownID']!="undefined")
			{
				$GodownID=" DebitCostCenterID=".$_GET['GodownID']." and  ";
			}
			else
			{
					$GodownID="";
			}
			if(isset($_GET['BranchID']) && $_GET['BranchID']>0)
			{
		//		$BranchID=" BranchID=".$_GET['BranchID']." and ";
				$BranchID="";
			}
			else
			{
					$BranchID="";
			}
		if(isset($_GET['GLCode']) && $_GET['GLCode']!="" && $_GET['GLCode']!="undefined" && $_GET['GLCode']>0)
			{
				$COAID=" UserName='".$_GET['GLCode']."'  and ";
			$showAll=1;
			}
			else
			{
					$COAID="";
			}
				if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="" && $_GET['VoucherNo']!="undefined")
			{
				$VoucherNo=" VoucherNo like '%".$_GET['VoucherNo']."%' and ";
			}
			else
			{
					$VoucherNo="";
			}	
		if((isset($_GET['startdate']) && $_GET['startdate']!="" && $_GET['startdate']!="undefined") && (isset($_GET['enddate']) && $_GET['enddate']!=""  && $_GET['enddate']!="undefined"))
		{
			$showAll=1;
			$date=" convert(date,VoucherDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
		}
		else
		{
			//$showAll=0;
			$today=date("Y-m-d");
			$date=" convert(date,VoucherDate)='".$today."' and ";
		}
			/*if(isset($_GET['depositdate']) && $_GET['depositdate']!="" && $_GET['depositdate']!="undefined")
			{
				$date=" convert(date,VoucherDate) like '%".$_GET['depositdate']."%' and ";
			}
			else
			{
			$date=" convert(date,VoucherDate)='".$today."' and ";
			}*/
    $CashAccount=$_SESSION['SETTING']['CASHINHAND'];
    $CreditCard=$_SESSION['SETTING']['CREDITCARD'];

		$searchbox=($GodownID."".$COAID."".$date."".$VoucherNo.$BranchID);	
		  /*$sql="select ROW_NUMBER() OVER (partition by im.[GodownID] ORDER BY im.[GodownID]) as row_num,vm.LastModificationTimeStamp as today,im.InvoiceID,
   g.AdditionalInfo1 as Company,g.Name as FullCompany ,AutoVoucherID,mv.MasterValue as VehicleBrand,mv1.MasterValue as VehicleModel, 
   convert(date,InvoiceDate) as InvoiceDate,vm.VoucherNo as VoucherNo, convert(date,vm.VoucherDate) as VoucherDate,im.KeyField as KeyField,
vm.Cash as Cash,im.CreditCard as Card1,im.TotalAmount,
TotalCurrencyAmount,(select sum(debit) from voucherdetails where LedgerID=$CreditCard and VoucherID=vm.VoucherID) as Card,TotalTaxAmount,NetAmount,im.GodownID as GodownID,CustomerName,MobileNumber,PlateNumber,im.CreateLog as CreateLog,im.symReceived as symReceived
from InvoiceMaster as im 
left outer join vouchermaster as vm on im.invoiceid=vm.ReferenceInvoiceID
left outer join MASTER_VALUES as mv on mv.MasterValueID=im.VehicleBrand
left outer join MASTER_VALUES as mv1 on mv1.MasterValueID=im.VehicleModel
inner join godowns as g on im.GodownID=g.GodownID
where $searchbox (InvoiceType in (5,8)  or VoucherTypeID in(7,9)) and (vm.Active=1 or im.Active=1) and im.paid>0 and im.CreateLog='".$_SESSION['UserName']."'
 order by im.GodownID";*/
 //(isnull(card1,0)+isnull(cash,0)+isnull(symReceived,0))
 //CreateLog='".$_SESSION['UserName']."'
 
	
    $CashAccount=$_SESSION['SETTING']['CASHINHAND'];
    $CreditCard=$_SESSION['SETTING']['CREDITCARD'];
 /*  $sql=" select SUM(Credit) as Amount,COAName from GeneralLedger where  $searchbox   COAID=$CashAccount and Credit>0
 group by COAName";*/
          $sql="select sum(Debit) as Amount,COAName,COAID,DebitCostCenterID,(select Name from Godowns where GodownID=DebitCostCenterID) as Location from GeneralLedger where  $searchbox VoucherTypeID in (6,7,12) and Debit>0
 group by COAName,COAID,DebitCostCenterID";
		$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
		while($row=odbc_fetch_array($result))
		{
			foreach ($row as $key => $value) {
				# code...
				$row[$key]=utf8_encode($value);
			}
//			$row[$key]=str_replace("_"," ",$value);
		$data[]=$row;	
		}
	//	print_r($data);
		echo json_encode($data);

	
		
	
	}
	if($_GET['action']=="CashCollectionSummaryEtraffic")
	{



		$showAll=0;
		$data=array();
			if(isset($_GET['GodownID']) && $_GET['GodownID']>0 && $_GET['GodownID']!="undefined")
			{
				$GodownID=" GodownID=".$_GET['GodownID']." and ";
			}
			else
			{
					$GodownID="";
			}

			if(isset($_GET['BranchID']) && $_GET['BranchID']>0)
			{
				//$BranchID=" BranchID=".$_GET['BranchID']." and ";
				$BranchID="";
			}
			else
			{
					$BranchID="";
			}

		if(isset($_GET['GLCode']) && $_GET['GLCode']!="" && $_GET['GLCode']!="undefined" && $_GET['GLCode']>0)
			{
				$COAID=" UserName='".$_GET['GLCode']."'  and ";
			$showAll=1;
			}
			else
			{

					$COAID="";
			}
				if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="" && $_GET['VoucherNo']!="undefined")
			{
				$VoucherNo=" VoucherNo like '%".$_GET['VoucherNo']."%' and ";
			}
			else
			{
					$VoucherNo="";
			}	
		if((isset($_GET['startdate']) && $_GET['startdate']!="" && $_GET['startdate']!="undefined") && (isset($_GET['enddate']) && $_GET['enddate']!=""  && $_GET['enddate']!="undefined"))
		{
			$showAll=1;
			$date=" convert(date,InvoiceDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
		}
		else
		{
			//$showAll=0;
			$today=date("Y-m-d");
			$date=" convert(date,today)='".$today."' and ";
		}
    $CashAccount=$_SESSION['SETTING']['CASHINHAND'];
    $CreditCard=$_SESSION['SETTING']['CREDITCARD'];

		$searchbox=($GodownID."".$COAID."".$date."".$VoucherNo."".$BranchID);	
		  /*$sql="select ROW_NUMBER() OVER (partition by im.[GodownID] ORDER BY im.[GodownID]) as row_num,vm.LastModificationTimeStamp as today,im.InvoiceID,
   g.AdditionalInfo1 as Company,g.Name as FullCompany ,AutoVoucherID,mv.MasterValue as VehicleBrand,mv1.MasterValue as VehicleModel, 
   convert(date,InvoiceDate) as InvoiceDate,vm.VoucherNo as VoucherNo, convert(date,vm.VoucherDate) as VoucherDate,im.KeyField as KeyField,
vm.Cash as Cash,im.CreditCard as Card1,im.TotalAmount,
TotalCurrencyAmount,(select sum(debit) from voucherdetails where LedgerID=$CreditCard and VoucherID=vm.VoucherID) as Card,TotalTaxAmount,NetAmount,im.GodownID as GodownID,CustomerName,MobileNumber,PlateNumber,im.CreateLog as CreateLog,im.symReceived as symReceived
from InvoiceMaster as im 
left outer join vouchermaster as vm on im.invoiceid=vm.ReferenceInvoiceID
left outer join MASTER_VALUES as mv on mv.MasterValueID=im.VehicleBrand
left outer join MASTER_VALUES as mv1 on mv1.MasterValueID=im.VehicleModel
inner join godowns as g on im.GodownID=g.GodownID
where $searchbox (InvoiceType in (5,8)  or VoucherTypeID in(7,9)) and (vm.Active=1 or im.Active=1) and im.paid>0 and im.CreateLog='".$_SESSION['UserName']."'
 order by im.GodownID";*/
 //(isnull(card1,0)+isnull(cash,0)+isnull(symReceived,0))
 //CreateLog='".$_SESSION['UserName']."'
 if($showAll==1)
 {
	$showdate="";//  CreateLog='".$_SESSION['UserName']."' and ";
 }
else
{
	$showdate="";
	//$showdate="  UserName='".$_SESSION['UserName']."' and ";
	//$showdate="  today=convert(date,'".Date("Y-m-d")."') and ";
}
    /*     $sql="
select isnull(SUM(cash),0.0) as Cash,0 as CreditCard,isnull(SUM(mutakamelacard),0.0) as mcard,0 as Paid,0 as NetAmount from [dailyreportEtraffic] where $searchbox   $showdate  1=1";*/
$CashAccount=$_SESSION['SETTING']['CASHINHAND'];
    $CreditCard=$_SESSION['SETTING']['CREDITCARD'];
$sql="select isnull(sum(Cash),0) as Cash,isnull(sum(Creditcard),0)  as CreditCard,sum(MutakamelaCard) as mcard from (
 select InvoiceDate,InvoiceID,(select sum(credit)  from VoucherDetails where creditledgerid=$CashAccount and ReferenceInvoiceID=sim.InvoiceID)as Cash,
  (select sum(credit)  from VoucherDetails where creditledgerid=$CreditCard) as Creditcard,
 0 as MutakamelaCard,'' as SymCardNo ,GodownID 
  from SalesInvoiceMaster as sim 
   where $searchbox   $showdate 
  Active=1 and GodownID>0 
  group by GodownID,InvoiceID,InvoiceDate) as u";
		$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
		while($row=odbc_fetch_array($result))
		{
			foreach ($row as $key => $value) {
				# code...
				$row[$key]=utf8_encode($value);
			}
//			$row[$key]=str_replace("_"," ",$value);
		$data[]=$row;	
		}
	//	print_r($data);
		echo json_encode($data);

	
		
		
	}
	
	if($_GET['action']=="PurchaseSummary")
	{


		$showAll=0;
		$data=array();
			if(isset($_GET['GodownID']) && $_GET['GodownID']>0 && $_GET['GodownID']!="undefined")
			{
				$GodownID=" GodownID=".$_GET['GodownID']." and ";
			}
			else
			{
					$GodownID="";
			}
		if(isset($_GET['GLCode']) && $_GET['GLCode']!="" && $_GET['GLCode']!="undefined" && $_GET['GLCode']>0)
			{
				$COAID=" UserName='".$_GET['GLCode']."'  and ";
			$showAll=1;
			}
			else
			{

					$COAID="";
			}
				if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="" && $_GET['VoucherNo']!="undefined")
			{
				$VoucherNo=" VoucherNo like '%".$_GET['VoucherNo']."%' and ";
			}
			else
			{
					$VoucherNo="";
			}	
		if((isset($_GET['startdate']) && $_GET['startdate']!="" && $_GET['startdate']!="undefined") && (isset($_GET['enddate']) && $_GET['enddate']!=""  && $_GET['enddate']!="undefined"))
		{
			$showAll=1;
			$date=" convert(date,InvoiceDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
		}
		else
		{
			//$showAll=0;
			$today=date("Y-m-d");
			$date=" convert(date,InvoiceDate)='".$today."' and ";
		}
    $CashAccount=$_SESSION['SETTING']['CASHINHAND'];
    $CreditCard=$_SESSION['SETTING']['CREDITCARD'];

		$searchbox=($GodownID."".$COAID."".$date."".$VoucherNo);	
$sql="select isnull(sum(NetAmount),0)  as Purchases from PurchaseSummaryReport where $searchbox 1=1";
				$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
		while($row=odbc_fetch_array($result))
		{
			foreach ($row as $key => $value) {
				# code...
				$row[$key]=utf8_encode($value);
			}
//			$row[$key]=str_replace("_"," ",$value);
		$data[]=$row;	
		}
	//	print_r($data);
		echo json_encode($data);

	}
	if($_GET['action']=="CashCollectionSummary")
	{


		$showAll=0;
		$data=array();
			if(isset($_GET['GodownID']) && $_GET['GodownID']>0 && $_GET['GodownID']!="undefined")
			{
				$GodownID=" GodownID=".$_GET['GodownID']." and ";
			}
			else
			{
					$GodownID="";
			}
			if(isset($_GET['BranchID']) && $_GET['BranchID']>0)
			{
			//	$BranchID=" BranchID=".$_GET['BranchID']." and ";
				$BranchID="";
			}
			else
			{
					$BranchID="";
			}
		if(isset($_GET['GLCode']) && $_GET['GLCode']!="" && $_GET['GLCode']!="undefined" && $_GET['GLCode']>0)
			{
				$COAID=" UserName='".$_GET['GLCode']."'  and ";
			$showAll=1;
			}
			else
			{

					$COAID="";
			}
				if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="" && $_GET['VoucherNo']!="undefined")
			{
				$VoucherNo=" VoucherNo like '%".$_GET['VoucherNo']."%' and ";
			}
			else
			{
					$VoucherNo="";
			}	
		if((isset($_GET['startdate']) && $_GET['startdate']!="" && $_GET['startdate']!="undefined") && (isset($_GET['enddate']) && $_GET['enddate']!=""  && $_GET['enddate']!="undefined"))
		{
			$showAll=1;
			$date=" convert(date,InvoiceDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
		}
		else
		{
			//$showAll=0;
			$today=date("Y-m-d");
			$date=" convert(date,today)='".$today."' and ";
		}
    $CashAccount=$_SESSION['SETTING']['CASHINHAND'];
    $CreditCard=$_SESSION['SETTING']['CREDITCARD'];

		$searchbox=($GodownID."".$COAID."".$date."".$VoucherNo."".$BranchID);	
		  /*$sql="select ROW_NUMBER() OVER (partition by im.[GodownID] ORDER BY im.[GodownID]) as row_num,vm.LastModificationTimeStamp as today,im.InvoiceID,
   g.AdditionalInfo1 as Company,g.Name as FullCompany ,AutoVoucherID,mv.MasterValue as VehicleBrand,mv1.MasterValue as VehicleModel, 
   convert(date,InvoiceDate) as InvoiceDate,vm.VoucherNo as VoucherNo, convert(date,vm.VoucherDate) as VoucherDate,im.KeyField as KeyField,
vm.Cash as Cash,im.CreditCard as Card1,im.TotalAmount,
TotalCurrencyAmount,(select sum(debit) from voucherdetails where LedgerID=$CreditCard and VoucherID=vm.VoucherID) as Card,TotalTaxAmount,NetAmount,im.GodownID as GodownID,CustomerName,MobileNumber,PlateNumber,im.CreateLog as CreateLog,im.symReceived as symReceived
from InvoiceMaster as im 
left outer join vouchermaster as vm on im.invoiceid=vm.ReferenceInvoiceID
left outer join MASTER_VALUES as mv on mv.MasterValueID=im.VehicleBrand
left outer join MASTER_VALUES as mv1 on mv1.MasterValueID=im.VehicleModel
inner join godowns as g on im.GodownID=g.GodownID
where $searchbox (InvoiceType in (5,8)  or VoucherTypeID in(7,9)) and (vm.Active=1 or im.Active=1) and im.paid>0 and im.CreateLog='".$_SESSION['UserName']."'
 order by im.GodownID";*/
 //(isnull(card1,0)+isnull(cash,0)+isnull(symReceived,0))
 //CreateLog='".$_SESSION['UserName']."'
 if($showAll==1)
 {
	$showdate="";//  CreateLog='".$_SESSION['UserName']."' and ";
 }
else
{
	$showdate="";
	//$showdate="  UserName='".$_SESSION['UserName']."' and ";
	//$showdate="  today=convert(date,'".Date("Y-m-d")."') and ";
}
        /* $sql="
select SUM(cash) as Cash,SUM(creditcard) CreditCard,SUM(mutakamelacard) as mcard,sum(Paid) as Paid,SUM(netamount)as NetAmount from dailyreport2 where $searchbox   $showdate  1=1";*/
 /*$sql="select InvoiceDate as today,SUM(Cheque) as Cheque,SUM(convert(numeric(12,2),Voucher1)) as Voucher,SUM(Staff) as Staff,SUM(CompanyCredit) as CompanyCredit, SUM(cash) as Cash,SUM(creditcard) CreditCard,SUM(mutakamelacard) as mcard,sum(Paid) as Paid,SUM(netamount)as NetAmount from dailyreport2 where $searchbox   $showdate  NetAmount<>0   Group by InvoiceDate ";*/
/*$sql="select sum(debit) as Amount,ledgerid from VoucherDetails as vd  left outer join SalesInvoiceMaster as sim
on vd.referenceinvoiceid=sim.invoiceid where ledgerid in (22,21) group by ledgerid";*/
$CashAccount=$_SESSION['SETTING']['CASHINHAND'];
$CreditCard=$_SESSION['SETTING']['CREDITCARD'];
 $sql="select isnull(sum(Cash),0) as Cash,isnull(sum(Creditcard),0)  as CreditCard,sum(MutakamelaCard) as mcard from (
 select InvoiceDate,InvoiceID,(select sum(debit)  from VoucherDetails where ledgerid=$CashAccount and ReferenceInvoiceID=sim.InvoiceID)as Cash,
  (select sum(Debit)  from VoucherDetails where ledgerid=$CreditCard and ReferenceInvoiceID=sim.InvoiceID) as Creditcard,
 0 as MutakamelaCard,'' as SymCardNo ,GodownID 
  from SalesInvoiceMaster as sim 
   where $searchbox   $showdate  
  Active=1 and GodownID>0 
  group by GodownID,InvoiceID,InvoiceDate) as u";

		$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
		while($row=odbc_fetch_array($result))
		{
			foreach ($row as $key => $value) {
				# code...
				$row[$key]=utf8_encode($value);
			}
//			$row[$key]=str_replace("_"," ",$value);
		$data[]=$row;	
		}
	//	print_r($data);
		echo json_encode($data);

	
		
	}
	if($_GET['action']=="DailyCollectionSummary")
	{

		$showAll=0;
		$data=array();
			if(isset($_GET['GodownID']) && $_GET['GodownID']>0)
			{
				$GodownID=" GodownID=".$_GET['GodownID']." and ";
			}
			else
			{
					$GodownID="";
			}
		if(isset($_GET['GLCode']) && $_GET['GLCode']!="" && $_GET['GLCode']!="undefined" && $_GET['GLCode']>0)
			{
				$COAID=" UserName='".$_GET['GLCode']."'  and ";
			$showAll=1;
			}
			else
			{

					$COAID="";
			}
				if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="" && $_GET['VoucherNo']!="undefined")
			{
				$VoucherNo=" VoucherNo like '%".$_GET['VoucherNo']."%' and ";
			}
			else
			{
					$VoucherNo="";
			}	
		if((isset($_GET['startdate']) && $_GET['startdate']!="" && $_GET['startdate']!="undefined") && (isset($_GET['enddate']) && $_GET['enddate']!=""  && $_GET['enddate']!="undefined"))
		{
			$showAll=1;
			$date=" convert(date,today) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
		}
		else
		{
			//$showAll=0;
			$today=date("Y-m-d");
			$date=" convert(date,today)='".$today."' and ";
		}
    $CashAccount=$_SESSION['SETTING']['CASHINHAND'];
    $CreditCard=$_SESSION['SETTING']['CREDITCARD'];

		$searchbox=($GodownID."".$COAID."".$date."".$VoucherNo);	
		  /*$sql="select ROW_NUMBER() OVER (partition by im.[GodownID] ORDER BY im.[GodownID]) as row_num,vm.LastModificationTimeStamp as today,im.InvoiceID,
   g.AdditionalInfo1 as Company,g.Name as FullCompany ,AutoVoucherID,mv.MasterValue as VehicleBrand,mv1.MasterValue as VehicleModel, 
   convert(date,InvoiceDate) as InvoiceDate,vm.VoucherNo as VoucherNo, convert(date,vm.VoucherDate) as VoucherDate,im.KeyField as KeyField,
vm.Cash as Cash,im.CreditCard as Card1,im.TotalAmount,
TotalCurrencyAmount,(select sum(debit) from voucherdetails where LedgerID=$CreditCard and VoucherID=vm.VoucherID) as Card,TotalTaxAmount,NetAmount,im.GodownID as GodownID,CustomerName,MobileNumber,PlateNumber,im.CreateLog as CreateLog,im.symReceived as symReceived
from InvoiceMaster as im 
left outer join vouchermaster as vm on im.invoiceid=vm.ReferenceInvoiceID
left outer join MASTER_VALUES as mv on mv.MasterValueID=im.VehicleBrand
left outer join MASTER_VALUES as mv1 on mv1.MasterValueID=im.VehicleModel
inner join godowns as g on im.GodownID=g.GodownID
where $searchbox (InvoiceType in (5,8)  or VoucherTypeID in(7,9)) and (vm.Active=1 or im.Active=1) and im.paid>0 and im.CreateLog='".$_SESSION['UserName']."'
 order by im.GodownID";*/
 //(isnull(card1,0)+isnull(cash,0)+isnull(symReceived,0))
 //CreateLog='".$_SESSION['UserName']."'
 if($showAll==1)
 {
	$showdate="";//  CreateLog='".$_SESSION['UserName']."' and ";
 }
else
{
	$showdate="";
	$showdate="  UserName='".$_SESSION['UserName']."' and ";
	//$showdate="  today=convert(date,'".Date("Y-m-d")."') and ";
}
          $sql="
select '' as BranchName,KeyField,UserName,SUM(cash) as Cash,SUM(creditcard) CreditCard,SUM(mutakamelacard) as mcard,sum(Paid) as Paid,SUM(netamount)as NetAmount from dailyreport2 where $searchbox   $showdate  NetAmount>0   Group by KeyField,UserName  ";
		$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
		while($row=odbc_fetch_array($result))
		{
			foreach ($row as $key => $value) {
				# code...
				$row[$key]=utf8_encode($value);
			}
//			$row[$key]=str_replace("_"," ",$value);
		$data[]=$row;	
		}
	//	print_r($data);
		echo json_encode($data);

	
	}
	if($_GET['action']=="DailyCollection")
	{
		$showAll=0;
		$data=array();
			if(isset($_GET['GodownID']) && $_GET['GodownID']>0)
			{
				$GodownID=" GodownID=".$_GET['GodownID']." and ";
			}
			else
			{
					$GodownID="";
			}
		if(isset($_GET['GLCode']) && $_GET['GLCode']!="")
			{
				$COAID=" ((CreateLog='".$_GET['GLCode']."' or symCashier='".$_GET['GLCode']."')  or (symCashier='".$_GET['GLCode']."' and symReceived>0)) and ";
			$showAll=1;
			}
			else
			{

					$COAID="";
			}
				if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="" && $_GET['VoucherNo']!="undefined")
			{
				$VoucherNo=" VoucherNo like '%".$_GET['VoucherNo']."%' and ";
			}
			else
			{
					$VoucherNo="";
			}	
		if((isset($_GET['startdate']) && $_GET['startdate']!="" && $_GET['startdate']!="undefined") && (isset($_GET['enddate']) && $_GET['enddate']!=""  && $_GET['enddate']!="undefined"))
		{
			$showAll=1;
			$date=" convert(date,today) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
		}
		else
		{
			//$showAll=0;
			$today=date("Y-m-d");
			$date=" convert(date,today)='".$today."' and ";
		}
    $CashAccount=$_SESSION['SETTING']['CASHINHAND'];
    $CreditCard=$_SESSION['SETTING']['CREDITCARD'];

		$searchbox=($GodownID."".$COAID."".$date."".$VoucherNo);	
		  /*$sql="select ROW_NUMBER() OVER (partition by im.[GodownID] ORDER BY im.[GodownID]) as row_num,vm.LastModificationTimeStamp as today,im.InvoiceID,
   g.AdditionalInfo1 as Company,g.Name as FullCompany ,AutoVoucherID,mv.MasterValue as VehicleBrand,mv1.MasterValue as VehicleModel, 
   convert(date,InvoiceDate) as InvoiceDate,vm.VoucherNo as VoucherNo, convert(date,vm.VoucherDate) as VoucherDate,im.KeyField as KeyField,
vm.Cash as Cash,im.CreditCard as Card1,im.TotalAmount,
TotalCurrencyAmount,(select sum(debit) from voucherdetails where LedgerID=$CreditCard and VoucherID=vm.VoucherID) as Card,TotalTaxAmount,NetAmount,im.GodownID as GodownID,CustomerName,MobileNumber,PlateNumber,im.CreateLog as CreateLog,im.symReceived as symReceived
from InvoiceMaster as im 
left outer join vouchermaster as vm on im.invoiceid=vm.ReferenceInvoiceID
left outer join MASTER_VALUES as mv on mv.MasterValueID=im.VehicleBrand
left outer join MASTER_VALUES as mv1 on mv1.MasterValueID=im.VehicleModel
inner join godowns as g on im.GodownID=g.GodownID
where $searchbox (InvoiceType in (5,8)  or VoucherTypeID in(7,9)) and (vm.Active=1 or im.Active=1) and im.paid>0 and im.CreateLog='".$_SESSION['UserName']."'
 order by im.GodownID";*/
 //(isnull(card1,0)+isnull(cash,0)+isnull(symReceived,0))
 //CreateLog='".$_SESSION['UserName']."'
 if($showAll==1)
 {
	$showdate="";//  CreateLog='".$_SESSION['UserName']."' and ";
 }
else
{
	$showdate="  ((CreateLog='".$_SESSION['UserName']."' or symCashier='".$_SESSION['UserName']."') or  (symCashier='".$_SESSION['UserName']."' and symReceived>0)) and ";
	//$showdate=" and InvoiceDate='".Date("Y-m-d")."'";
}
//(cash>0 or card1>0 or symReceived>0 or  TotalCurrencyAmount>0)
           $sql="
select * from dailyreport where $searchbox   $showdate    order by CreateLog asc ";
		$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
		while($row=odbc_fetch_array($result))
		{
			foreach ($row as $key => $value) {
				# code...
				$row[$key]=utf8_encode($value);
			}
//			$row[$key]=str_replace("_"," ",$value);
		$data[]=$row;	
		}
	//	print_r($data);
		echo json_encode($data);

	}
	if($_GET['action']=="GetGlCode")
	{
		$data=array();
		$Under=$_GET['Under'];
		$sql="select (select  GLCODE from accounts where COAID=$Under)+'.'+convert(varchar,(count(*)+1)) as description from accounts where under=".$Under;
		$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{
		$data['description']=$row['description'];	
		}
	//	print_r($data);
		echo json_encode($data);

	}
	if($_GET['action']=="InsertAccountsonly")
	{

		   		odbc_autocommit($connection, FALSE);
//print_r($_POST['detail']);
$detaildata=$_POST['detail'];
//print_r($detaildata[0]);
//return;
/*
		$master=array_keys($_POST);
		$details=array_values($_POST);
		//print_r($details);
		 $master1="[".str_replace(',"detail":',"}",$master[0])."]";
		//$master=array_keys($master[0]);

		$masterdata=json_decode($master1);
		echo "here".utf8_decode($masterdata[0]->AccountTitle);
*/	//	print_r($masterdata[0]);
		//return;
/*		if(isset($details) && $details[0]!="")
		{
		$detail=array_keys($details[0]);
		 $detail="[".$detail[0]."]";
		$detaildata=json_decode($detail);
		}
		else
		{
			$detaildata="";
		}*/
		//print_r($detaildata);
		$VoucherID=0;
		//print_r($masterdata);
	//$data=$masterdata[0];	
	//print_r($data);
	$under=isset($_POST['Under'])?$_POST['Under']:0;
	$Under=$under;
	$NatureID=isset($_POST['NatureID'])?$_POST['NatureID']:getnamesingle("accounts","NatureID","COAID",$under,$connection);
	$COAID=isset($_POST['COAID'])?$_POST['COAID']:0;
	$Group=isset($_POST['Group'])?$_POST['Group']:0;	
	$Attr1=isset($_POST['Attr1'])?$_POST['Attr1']:'';	
	$Attr2=isset($_POST['Attr2'])?$_POST['Attr2']:'';
	$Attr3=isset($_POST['Attr3'])?$_POST['Attr3']:'';
	$CostCenterID=isset($_POST['CostCenterID'])?$_POST['CostCenterID']:0;	
$Attr17=isset($_POST['Attr17'])?$_POST['Attr17']:'';
$Attr4=isset($_POST['Attr4'])?$_POST['Attr4']:'';
$Attr5=isset($_POST['Attr5'])?$_POST['Attr5']:'';
$Attr6=isset($_POST['Attr6'])?$_POST['Attr6']:'';
$Attr7=isset($_POST['Attr7'])?$_POST['Attr7']:'';
$Attr8=isset($_POST['Attr8'])?$_POST['Attr8']:'';
$Attr9=isset($_POST['Attr9'])?$_POST['Attr9']:'';
$Attr10=isset($_POST['Attr10'])?$_POST['Attr10']:'';
$Attr11=isset($_POST['Attr11'])?str_replace("_", ".",$_POST['Attr11']):'';
$Attr12=isset($_POST['Attr12'])?str_replace("_", " ",$_POST['Attr12']):'';
$Attr13=isset($_POST['Attr13'])?$_POST['Attr13']:'';
$Attr14=isset($_POST['Attr14'])?$_POST['Attr14']:'';
$Attr15=isset($_POST['Attr15'])?$_POST['Attr15']:'';
$Attr16=isset($_POST['Attr16'])?$_POST['Attr16']:'';
$Attr17=isset($_POST['Attr17'])?$_POST['Attr17']:'';
$Attr18=isset($_POST['Attr18'])?$_POST['Attr18']:'';
$Attr19=isset($_POST['Attr19'])?$_POST['Attr19']:'';
$Attr20=isset($_POST['Attr20'])?$_POST['Attr20']:'';
$Attr20=isset($_POST['Attr20'])?$_POST['Attr20']:'';
$ContactPerson1=isset($_POST['ContactPerson1'])?$_POST['ContactPerson1']:'';
$ContactDesignation1=isset($_POST['ContactDesignation1'])?$_POST['ContactDesignation1']:'';

$ContactPerson2=isset($_POST['ContactPerson2'])?$_POST['ContactPerson2']:'';
$ContactDesignation2=isset($_POST['ContactDesignation2'])?$_POST['ContactDesignation2']:'';

$ContactPerson3=isset($_POST['ContactPerson3'])?$_POST['ContactPerson3']:'';
$ContactDesignation3=isset($_POST['ContactDesignation3'])?$_POST['ContactDesignation3']:'';

$FixedAssetAcquireDate=isset($_POST['FixedAssetAcquireDate'])?$_POST['FixedAssetAcquireDate']:'';
$COAName=isset($_POST['AccountTitle'])?$_POST['AccountTitle']:'';
$COAName=urldecode($COAName);

	if(isset($_POST['COAID'])  && $_POST['COAID']!=0 && $_POST['COAID']!="" && $_POST['COAID']!=NULL)
	{
		$GLCode=$_POST['GLCode'];
   $sql="update accounts set Under=".$_POST['Under'].",CostCenterID=".$CostCenterID.",COAName='".str_replace("_"," ", $COAName)."',GLCode='".$GLCode."',   
            Attr2='".urldecode($Attr2)."',
            Attr1='".urldecode($Attr1)."',
            Attr3='".urldecode($Attr3)."',
            Attr4='".urldecode($Attr4)."',
            Attr5='".urldecode($Attr5)."', 
            Attr6='".urldecode($Attr6)."',
            Attr7='".urldecode(str_replace("_"," ",$Attr7))."',
            Attr8='".urldecode($Attr8)."',
            Attr9='".urldecode($Attr9)."',
            Attr10='".urldecode($Attr10)."',
            Attr11='".urldecode($Attr11)."',
            Attr12='".urldecode($Attr12)."',
            Attr13='".urldecode($Attr13)."',
            Attr14='".urldecode($Attr14)."',
            Attr15='".urldecode($Attr15)."',
            Attr16='".urldecode($Attr16)."',
            Attr17='".urldecode(str_replace("_",".",$Attr17))."', 
            Attr18='".urldecode($Attr18)."', 
            Attr19='".urldecode($Attr19)."', 
            Attr20='".urldecode($Attr20)."',
            ContactPerson1='".urldecode($ContactPerson1)."',
            ContactPerson2='".urldecode($ContactPerson2)."',
            ContactPerson3='".urldecode($ContactPerson3)."',   
            ContactDesignation1='".urldecode($ContactDesignation1)."',
            ContactDesignation2='".urldecode($ContactDesignation2)."',
           ContactDesignation3='".urldecode($ContactDesignation3)."',                                             
            FixedAssetAcquireDate='".$FixedAssetAcquireDate."',editLog='".$_SESSION['UserName']."'            
            where COAID=".$_POST['COAID'];
            $LedgerID=$_POST['COAID'];
//           return;
            	odbc_exec($connection, $sql);
       $Degree=getnamesingle("accounts","Degree","COAID",$LedgerID,$connection);	   	
         generateH($Degree,$LedgerID,$connection);       	
	}
	else
	{

	$COAID=getMaxId("accounts","COAID",$connection)+1;
		$ParentCode=getnamesingle("accounts","GLCode","COAID",$under,$connection);
		$NatureID=getnamesingle("accounts","NatureID","COAID",$under,$connection);
		$Degree=getnamesingle("accounts","Degree","COAID",$_POST['Under'],$connection)+1;		
		$GLCode=0;
		//$under=$_POST['Under'];

	/*	[{"Under":"52","CostCenterID":"1","Attr5":"6","AccountTitle":"National_Bank_of_Fujairah-(012001365768)AED","Degree":"undefined","COAID":"83","Attr4":"012001365768","Attr6":"","Attr7":"Dubai","Attr8":"","Attr9":"","Attr10":"00971552972720","Attr11":"muneeb_cheema@nbf_ae","Attr12":"Muneeb_Cheema","Attr13":"AE060380000012001365768","Attr14":"NBFUAEAFDXB","Attr15":"100065112300003","Attr16":"","Attr17":"","NatureID":13}]
*/		
	$GLCode=$ParentCode.".".generateGLCode($under,$NatureID,$connection);
	
            $sql="insert into accounts (COAID,Under,Active ,GLCode,
            CostCenterID ,
            [Group],
            Attr5 ,
            COAName ,
            Degree ,
            Attr1 ,
            Attr2 , 
            Attr3 ,                                   
            Attr4 ,
            Attr6 ,
            Attr7 ,
            Attr8 ,
            Attr9 ,
            Attr10 ,
            Attr11 ,
            Attr12 ,
            Attr13 ,
            Attr14 ,
            Attr15 ,
            Attr16 ,
            Attr17 ,
            Attr18 ,
            Attr19 ,
            Attr20 ,
            ContactPerson1,
            ContactPerson2,
            ContactPerson3,   
            ContactDesignation1,
            ContactDesignation2,
           ContactDesignation3,
            FixedAssetAcquireDate ,                                    
            NatureID,CreateLog)
            values(".$COAID.",".$Under.",1,'".$GLCode."',".
            $CostCenterID.",".
            $Group.",'".
            urldecode($Attr5)."','".
            urldecode($COAName)."',".
            $Degree.",'".
            urldecode($Attr1)."','".
            urldecode($Attr2)."','".
            urldecode($Attr3)."','".                        
            urldecode($Attr4)."','".
            urldecode($Attr6)."','".
            urldecode($Attr7)."','".
            urldecode($Attr8)."','".
            urldecode($Attr9)."','".
            urldecode($Attr10)."','".
            urldecode($Attr11)."','".
            urldecode($Attr12)."','".
            urldecode($Attr13)."','".
            urldecode($Attr14)."','".
            urldecode($Attr15)."','".
            urldecode($Attr16)."','".
            urldecode($Attr17)."','".
            urldecode($Attr18)."','".
            urldecode($Attr19)."','".
			urldecode($Attr20)."','".
			$ContactPerson1."',
            '".$ContactPerson2."',
            '".$ContactPerson3."',   
            '".$ContactDesignation1."',
            '".$ContactDesignation2."',
           '".$ContactDesignation3."','".
			$FixedAssetAcquireDate."',".
            $NatureID.",'".$_SESSION['UserName']."')";

	odbc_exec($connection, $sql);

            generateH($Degree,$COAID,$connection);
$VoucherTypeID=0;
            $PeriodID=1;
            $USERID=0;
            $GROUPID=1;
            $Active=1;
            $TotalAmount=0;
            $ISDepreciationVoucher=0;
            $LocationID=1;
            $LedgerID=$COAID;
            $Narration="Opening Balance";
            $VoucherDate=date("Y-m-d H:i:s");
            $VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$connection)+1;
            if($Group==0)
            {
            $VoucherNo=generateCode("VoucherMaster","VoucherID","VoucherTypeID=0",$connection)+1;
            $VoucherNo="OPV-".str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
            $sqlvmaster="insert into VoucherMaster(VoucherID,VoucherNo,TotalAmount,Active,VoucherDate,Narration,posted,VoucherTypeID,PeriodID,LedgerID,LocationID,ISDepreciationVoucher,USERID,GROUPID) values(".$VoucherID.",'".$VoucherNo."',".$TotalAmount.",".$Active.",'".$VoucherDate."','".$Narration."',1,".$VoucherTypeID.",".$PeriodID.",".$LedgerID.",".$LocationID.",".$ISDepreciationVoucher.",".$USERID.",".$GROUPID.")";
            if(isset($_SESSION['SETTING']['OPENINGBALANCE']) )
			{
				if($_SESSION['SETTING']['OPENINGBALANCE']==true)
            		odbc_exec($connection,$sqlvmaster);
        	}//end opening Setting
        	}
          //  $VoucherID=getMaxId("VoucherMaster","VoucherID",$connection)+1;
            
	}//end else for insert accounts

if($VoucherID!="" && $VoucherID>0)
	{}
	else
	{
			$sql="select * from voucherdetails where ledgerid=".$COAID." and voucherid in(select voucherid from VoucherMaster where vouchermaster.voucherid=voucherid and VoucherTypeID=0)";
			$result=odbc_exec($connection,$sql);
			if(odbc_num_rows($result)<1)
			{
		// if voucher not generated then generate NEW VOUCHER 
		       $VoucherTypeID=0;
            $PeriodID=1;
            $USERID=0;
            $GROUPID=1;
            $Active=1;
            $TotalAmount=0;
            $ISDepreciationVoucher=0;
            $LocationID=1;
            $LedgerID=$COAID;
            $Narration="Opening Balance";
            $VoucherDate=date("Y-m-d m:i:s");
            $VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$connection)+1;//getMaxId("VoucherMaster","VoucherID",$connection)+1;
            if($Group==0)
            {
            $VoucherNo=generateCode("VoucherMaster","","VoucherTypeID=0",$connection)+1;
            $VoucherNo="OPV-".str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
             $sqlvmaster="insert into VoucherMaster(VoucherID,VoucherNo,TotalAmount,Active,VoucherDate,Narration,posted,VoucherTypeID,PeriodID,LedgerID,LocationID,ISDepreciationVoucher,CreateLog,GROUPID) values(".$VoucherID.",'".$VoucherNo."',".$TotalAmount.",".$Active.",'".$VoucherDate."','".$Narration."',1,".$VoucherTypeID.",".$PeriodID.",".$LedgerID.",".$LocationID.",".$ISDepreciationVoucher.",'".$_SESSION['UserName']."',".$GROUPID.")";
           // echo $_SESSION['SETTING']['OPENINGBALANCE'];
           // return;
            if(isset($_SESSION['SETTING']['OPENINGBALANCE']) )
			{
		if($_SESSION['SETTING']['OPENINGBALANCE']==1)
            odbc_exec($connection,$sqlvmaster);
			}//end opening setting
			}
			}
		$v=getnamewhere("VoucherMaster","VoucherID","VoucherTypeID=0 and LedgerID=".$LedgerID,$connection);
		$v=json_decode($v);
		//print_r($v);
		if(isset($v->VoucherID))
		$VoucherID=$v->VoucherID;
		else
		$VoucherID=0;	
		//$VoucherID="select VoucherID from "
	}
	if($Group==0)
	{
	if(isset($_SESSION['SETTING']['OPENINGBALANCE']) )
	{
		if($_SESSION['SETTING']['OPENINGBALANCE']==1)	
			{
		$sql="delete from VoucherDetails where VoucherID=".$VoucherID;
		odbc_exec($connection, $sql);
			}
	}

	for($a=0;$a<count($detaildata);$a++)
	{
	if(isset($detaildata[$a]['CostCenterID']))
	{	
	$CostCenterID=isset($detaildata[$a]['CostCenterID'])?$detaildata[$a]['CostCenterID']:0;
	$Balance=$detaildata[$a]['Balance'];
	if($Balance>=0)
	{
	$Debit=$Balance;
	$Credit=0;
	$CreditLedgerID=0;//owner equity Capital
	$LedgerID=$COAID;
	}
	else
	{
	$Credit= $Balance;
	$Debit=0;	
	$CreditLedgerID=0;//owner equity Capital
	$LedgerID=$COAID;
	}
	

	$AssetAcquireValue=isset($detaildata[$a]['Cost'])?$detaildata[$a]['Cost']:0;
	$AssetSalvageValue=isset($detaildata[$a]['SalvageValue'])?$detaildata[$a]['SalvageValue']:0;
    //$VoucherID=getMaxId("VoucherDetails","VoucherID",$connection)+1;

	//	$keys .=",".$key;
	//	$values .=",".$value;
	   $sql="insert into VoucherDetails(VoucherID,Debit,Credit,DebitCostCenterID,CostCenterID,LedgerID,CreditLedgerID,Narration,isDelete,AssetID,AssetCostCenterID,AssetSalvageValue,AssetAcquireValue) values($VoucherID,$Debit,$Credit,$CostCenterID,$CostCenterID,$LedgerID,$CreditLedgerID,'Opening Balance',0,$LedgerID,$CostCenterID,$AssetSalvageValue,$AssetAcquireValue)";
	if(isset($_SESSION['SETTING']['OPENINGBALANCE']) )
	{
		if($_SESSION['SETTING']['OPENINGBALANCE']==1)
	odbc_exec($connection,$sql) or die(odbc_error().$sql);
	}
	}//end if cost center
	}
	}


	 if (!odbc_error())
	 {
      odbc_commit($connection);
	    $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
	}
else
{
      odbc_rollback($connection);
	    $res=array('status'=>"Error",'description'=>'Record  Not Updated');

}
//  $res=array('status'=>"ok",'description'=>'Record Save Sucessfully');
		echo json_encode($res);
		//echo "<script>window.location='index.php';</script>";
	
	}

	if($_GET['action']=="InsertAccounts")
	{
		   		odbc_autocommit($connection, FALSE);
//print_r($_POST);
		$master=array_keys($_POST);
		$details=array_values($_POST);
		//print_r($details);
		 $master1="[".str_replace(',"detail":',"}",$master[0])."]";
		//$master=array_keys($master[0]);

		$masterdata=json_decode($master1);
//		echo "here".utf8_decode($masterdata[0]->AccountTitle);
	//	print_r($masterdata[0]);
//		return;
		if(isset($details) && $details[0]!="")
		{
		$detail=array_keys($details[0]);
		 $detail="[".$detail[0]."]";
		$detaildata=json_decode($detail);
		}
		else
		{
			$detaildata="";
		}
		//print_r($detaildata);
		$VoucherID=0;
		//print_r($masterdata);
	$data=$masterdata[0];	
	//print_r($data);
	$under=isset($data->Under)?$data->Under:0;
	$NatureID=isset($data->NatureID)?$data->NatureID:getnamesingle("accounts","NatureID","COAID",$under,$connection);
	$COAID=isset($data->COAID)?$data->COAID:0;
	$Group=isset($data->Group)?$data->Group:0;	
	$Attr1=isset($data->Attr1)?$data->Attr1:'';	
	$Attr2=isset($data->Attr2)?$data->Attr2:'';
	$Attr3=isset($data->Attr3)?$data->Attr3:'';
	$CostCenterID=isset($data->CostCenterID)?$data->CostCenterID:0;	
$Attr17=isset($data->Attr17)?$data->Attr17:'';
$Attr4=isset($data->Attr4)?$data->Attr4:'';
$Attr5=isset($data->Attr5)?$data->Attr5:'';
$Attr6=isset($data->Attr6)?$data->Attr6:'';
$Attr7=isset($data->Attr7)?$data->Attr7:'';
$Attr8=isset($data->Attr8)?$data->Attr8:'';
$Attr9=isset($data->Attr9)?$data->Attr9:'';
$Attr10=isset($data->Attr10)?$data->Attr10:'';
$Attr11=isset($data->Attr11)?str_replace("_", ".",$data->Attr11):'';
$Attr12=isset($data->Attr12)?str_replace("_", " ",$data->Attr12):'';
$Attr13=isset($data->Attr13)?$data->Attr13:'';
$Attr14=isset($data->Attr14)?$data->Attr14:'';
$Attr15=isset($data->Attr15)?$data->Attr15:'';
$Attr16=isset($data->Attr16)?$data->Attr16:'';
$Attr17=isset($data->Attr17)?$data->Attr17:'';
$Attr18=isset($data->Attr18)?$data->Attr18:'';
$Attr19=isset($data->Attr19)?$data->Attr19:'';
$Attr20=isset($data->Attr20)?$data->Attr20:'';
$Attr20=isset($data->Attr20)?$data->Attr20:'';
$ContactPerson1=isset($data->ContactPerson1)?$data->ContactPerson1:'';
$ContactDesignation1=isset($data->ContactDesignation1)?$data->ContactDesignation1:'';

$ContactPerson2=isset($data->ContactPerson2)?$data->ContactPerson2:'';
$ContactDesignation2=isset($data->ContactDesignation2)?$data->ContactDesignation2:'';

$ContactPerson3=isset($data->ContactPerson3)?$data->ContactPerson3:'';
$ContactDesignation3=isset($data->ContactDesignation3)?$data->ContactDesignation3:'';

$FixedAssetAcquireDate=isset($data->FixedAssetAcquireDate)?$data->FixedAssetAcquireDate:'';
$COAName=isset($data->AccountTitle)?$data->AccountTitle:'';
$COAName=utf8_decode($COAName);
	if(isset($data->COAID)  && $data->COAID>0 && $data->COAID!=null && $data->COAID!="")
	{
		$Degree=getnamesingle("accounts","Degree","COAID",$data->COAID,$connection);
$data->Under=getnamesingle("accounts","Under","COAID",$data->COAID,$connection);
$data->Under=(isset($data->Under) && $data->Under!="" && $data->Under!=null)?$data->Under:null;
if($Degree==1)
$Under="";	
else
$Under="Under=".$data->Under.",";
   $sql="update accounts set $Under CostCenterID=".$CostCenterID.",COAName='".urldecode(str_replace("_"," ", $COAName))."',
            Attr2='".$Attr2."',
            Attr1='".$Attr1."',
            Attr3='".$Attr3."',
            Attr4='".$Attr4."',
            Attr5='".$Attr5."', 
            Attr6='".$Attr6."',
            Attr7='".str_replace("_"," ",$Attr7)."',
            Attr8='".$Attr8."',
            Attr9='".$Attr9."',
            Attr10='".$Attr10."',
            Attr11='".$Attr11."',
            Attr12='".$Attr12."',
            Attr13='".$Attr13."',
            Attr14='".$Attr14."',
            Attr15='".$Attr15."',
            Attr16='".$Attr16."',
            Attr17='".str_replace("_",".",$Attr17)."', 
            Attr18='".$Attr18."', 
            Attr19='".$Attr19."', 
            Attr20='".$Attr20."',
            ContactPerson1='".$ContactPerson1."',
            ContactPerson2='".$ContactPerson2."',
            ContactPerson3='".$ContactPerson3."',   
            ContactDesignation1='".$ContactDesignation1."',
            ContactDesignation2='".$ContactDesignation2."',
           ContactDesignation3='".$ContactDesignation3."',                                             
            FixedAssetAcquireDate='".$FixedAssetAcquireDate."',editLog='".$_SESSION['UserName']."'            
            where COAID=".$data->COAID;
            $LedgerID=$data->COAID;
            	odbc_exec($connection, $sql) or die(odbc_error().$sql);
            generateH($Degree,$LedgerID,$connection);

	}
	else
	{
	$COAID=getMaxId("accounts","COAID",$connection)+1;
		$ParentCode=getnamesingle("accounts","GLCode","COAID",$under,$connection);
		$NatureID=getnamesingle("accounts","NatureID","COAID",$under,$connection);
		$Degree=getnamesingle("accounts","Degree","COAID",$data->Under,$connection)+1;		
		$GLCode=0;
	/*	[{"Under":"52","CostCenterID":"1","Attr5":"6","AccountTitle":"National_Bank_of_Fujairah-(012001365768)AED","Degree":"undefined","COAID":"83","Attr4":"012001365768","Attr6":"","Attr7":"Dubai","Attr8":"","Attr9":"","Attr10":"00971552972720","Attr11":"muneeb_cheema@nbf_ae","Attr12":"Muneeb_Cheema","Attr13":"AE060380000012001365768","Attr14":"NBFUAEAFDXB","Attr15":"100065112300003","Attr16":"","Attr17":"","NatureID":13}]
*/		
	$GLCode=$ParentCode.".".generateGLCode($under,$NatureID,$connection);
	
            $sql="insert into accounts (COAID,Under,Active ,GLCode,
            CostCenterID ,
            [Group],
            Attr5 ,
            COAName ,
            Degree ,
            Attr1 ,
            Attr2 , 
            Attr3 ,                                   
            Attr4 ,
            Attr6 ,
            Attr7 ,
            Attr8 ,
            Attr9 ,
            Attr10 ,
            Attr11 ,
            Attr12 ,
            Attr13 ,
            Attr14 ,
            Attr15 ,
            Attr16 ,
            Attr17 ,
            Attr18 ,
            Attr19 ,
            Attr20 ,
            ContactPerson1,
            ContactPerson2,
            ContactPerson3,   
            ContactDesignation1,
            ContactDesignation2,
           ContactDesignation3,
            FixedAssetAcquireDate ,                                    
            NatureID,CreateLog)
            values(".$COAID.",".$data->Under.",1,'".$GLCode."',".
            $CostCenterID.",".
            $Group.",'".
            $Attr5."','".
            str_replace("_", " ", $COAName)."',".
            $Degree.",'".
            $Attr1."','".
            $Attr2."','".
            $Attr3."','".                        
            $Attr4."','".
            $Attr6."','".
            $Attr7."','".
            $Attr8."','".
            $Attr9."','".
            $Attr10."','".
            $Attr11."','".
            $Attr12."','".
            $Attr13."','".
            $Attr14."','".
            $Attr15."','".
            $Attr16."','".
            $Attr17."','".
            $Attr18."','".
            $Attr19."','".
			$Attr20."','".
			$ContactPerson1."',
            '".$ContactPerson2."',
            '".$ContactPerson3."',   
            '".$ContactDesignation1."',
            '".$ContactDesignation2."',
           '".$ContactDesignation3."','".
			$FixedAssetAcquireDate."',".
            $NatureID.",'".$_SESSION['UserName']."')";

	odbc_exec($connection, $sql);
            generateH($Degree,$COAID,$connection);            
            $VoucherTypeID=0;
            $PeriodID=1;
            $USERID=0;
            $GROUPID=1;
            $Active=1;
            $TotalAmount=0;
            $ISDepreciationVoucher=0;
            $LocationID=1;
            $LedgerID=$COAID;
            $Narration="Opening Balance";
            $VoucherDate=date("Y-m-d m:i:s");
            $VoucherID=getMaxId("VoucherMaster","VoucherID",$connection)+1;
            //getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$connection)+1;//getMaxId("VoucherMaster","VoucherID",$connection)+1;
            if($Group==0)
            {
            $VoucherNo=generateCode("VoucherMaster","","VoucherTypeID=0",$connection)+1;
            $VoucherNo="OPV-".str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
            $sqlvmaster="insert into VoucherMaster(VoucherID,VoucherNo,TotalAmount,Active,VoucherDate,Narration,posted,VoucherTypeID,PeriodID,LedgerID,LocationID,ISDepreciationVoucher,USERID,GROUPID) values(".$VoucherID.",'".$VoucherNo."',".$TotalAmount.",".$Active.",'".$VoucherDate."','".$Narration."',1,".$VoucherTypeID.",".$PeriodID.",".$LedgerID.",".$LocationID.",".$ISDepreciationVoucher.",".$USERID.",".$GROUPID.")";
            if(isset($_SESSION['SETTING']['OPENINGBALANCE']) )
			{
				if($_SESSION['SETTING']['OPENINGBALANCE']==true)
            		odbc_exec($connection,$sqlvmaster);
        	}//end opening Setting
        	}
	}//end else for insert accounts

	//code for opening 
	//insert voucher master 
	if($VoucherID!="" && $VoucherID>0)
	{}
	else
	{
			$sql="select * from voucherdetails where ledgerid=".$COAID." and voucherid in(select voucherid from VoucherMaster where vouchermaster.voucherid=voucherid and VoucherTypeID=0)";
			$result=odbc_exec($connection,$sql);
			if(odbc_num_rows($result)<1)
			{
		// if voucher not generated then generate NEW VOUCHER 
		       $VoucherTypeID=0;
            $PeriodID=1;
            $USERID=0;
            $GROUPID=1;
            $Active=1;
            $TotalAmount=0;
            $ISDepreciationVoucher=0;
            $LocationID=1;
            $LedgerID=$COAID;
            $Narration="Opening Balance";
            $VoucherDate=date("Y-m-d m:i:s");
            $VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$connection)+1;//getMaxId("VoucherMaster","VoucherID",$connection)+1;
            if($Group==0)
            {
            $VoucherNo=generateCode("VoucherMaster","","VoucherTypeID=0",$connection)+1;
            $VoucherNo="OPV-".str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
            $sqlvmaster="insert into VoucherMaster(VoucherID,VoucherNo,TotalAmount,Active,VoucherDate,Narration,posted,VoucherTypeID,PeriodID,LedgerID,LocationID,ISDepreciationVoucher,CreateLog,GROUPID) values(".$VoucherID.",'".$VoucherNo."',".$TotalAmount.",".$Active.",'".$VoucherDate."','".$Narration."',1,".$VoucherTypeID.",".$PeriodID.",".$LedgerID.",".$LocationID.",".$ISDepreciationVoucher.",'".$_SESSION['UserName']."',".$GROUPID.")";
          //  return;
            if(isset($_SESSION['SETTING']['OPENINGBALANCE']) )
			{
		if($_SESSION['SETTING']['OPENINGBALANCE']==true)
            odbc_exec($connection,$sqlvmaster);
			}//end opening setting
			}
			}
		$v=getnamewhere("VoucherMaster","VoucherID","VoucherTypeID=0 and LedgerID=".$LedgerID,$connection);
		$v=json_decode($v);
		//print_r($v);
		if(isset($v->VoucherID))
		$VoucherID=$v->VoucherID;
		else
		$VoucherID=0;	
		//$VoucherID="select VoucherID from "
	}
	if($Group==0)
	{
	if(isset($_SESSION['SETTING']['OPENINGBALANCE']) )
	{
		if($_SESSION['SETTING']['OPENINGBALANCE']==true || $_SESSION['SETTING']['OPENINGBALANCE']==1)	
			{
		$sql="delete from VoucherDetails where VoucherID=".$VoucherID;
		odbc_exec($connection, $sql);
			}
	}
	/*else
	{
		$sql="delete from VoucherDetails where VoucherID=".$VoucherID;
		odbc_exec($connection, $sql);
	}*/

	for($a=0;$a<count($detaildata);$a++)
	{
	if(isset($detaildata[$a]->CostCenterID))
	{	
	$CostCenterID=isset($detaildata[$a]->CostCenterID)?$detaildata[$a]->CostCenterID:0;
	$Balance=$detaildata[$a]->Balance;
	if($Balance>=0)
	{
	$Debit=$Balance;
	$Credit=0;
	$CreditLedgerID=0;//owner equity Capital
	$LedgerID=$COAID;
	}
	else
	{
	$Credit= $Balance;
	$Debit=0;	
	$CreditLedgerID=0;//owner equity Capital
	$LedgerID=$COAID;
	}
	

	$AssetAcquireValue=isset($detaildata[$a]->Cost)?$detaildata[$a]->Cost:0;
	$AssetSalvageValue=isset($detaildata[$a]->SalvageValue)?$detaildata[$a]->SalvageValue:0;
    //$VoucherID=getMaxId("VoucherDetails","VoucherID",$connection)+1;

	//	$keys .=",".$key;
	//	$values .=",".$value;
	 $sql="insert into VoucherDetails(VoucherID,Debit,Credit,DebitCostCenterID,CostCenterID,LedgerID,CreditLedgerID,Narration,isDelete,AssetID,AssetCostCenterID,AssetSalvageValue,AssetAcquireValue) values($VoucherID,$Debit,$Credit,$CostCenterID,$CostCenterID,$LedgerID,$CreditLedgerID,'Opening Balance',0,$LedgerID,$CostCenterID,$AssetSalvageValue,$AssetAcquireValue)";
	if(isset($_SESSION['SETTING']['OPENINGBALANCE']) )
	{
		if($_SESSION['SETTING']['OPENINGBALANCE']==true || $_SESSION['SETTING']['OPENINGBALANCE']==1)
	odbc_exec($connection,$sql) or die(odbc_error().$sql);
	}
	}//end if cost center
	}
	}
	 if (!odbc_error())
	 {
      odbc_commit($connection);
	    $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
	}
else
{
      odbc_rollback($connection);
	    $res=array('status'=>"Error",'description'=>'Record  Not Updated');

}
//  $res=array('status'=>"ok",'description'=>'Record Save Sucessfully');
		echo json_encode($res);

	}

	if($_GET['action']=="GetOpeningBalance")
	{
		$data=array();
		$COAID=isset($_GET['COAID'])?$_GET['COAID']:0;
		if($COAID>0)
		{
		 $sql="select Debit,Credit,DebitCostCenterID as GodownID,g.Name as GodownName from VoucherDetails as vd 
		right outer join godowns as g on vd.DebitCostCenterID=g.GodownID
		where VoucherID in(select VoucherID  from VoucherMaster where VoucherNo like 'OPV-%') and (LedgerID=".$COAID." and g.active=1 and g.godowntype=0)";			
		}
		else
		{
		$sql="select Debit,Credit,g.GodownID as GodownID,g.Name as GodownName,LedgerID,g.godowntype from VoucherDetails as vd 
		right outer join godowns as g on vd.ledgerid=g.GodownID where g.GodownID between 1 and 4 and g.active=1 and g.godowntype=0";	
		/*echo $sql="select Debit,Credit,DebitCostCenterID as GodownID,g.Name as GodownName from VoucherDetails as vd 
		right outer join godowns as g on vd.DebitCostCenterID=g.GodownID
		where VoucherID in(select VoucherID  from VoucherMaster where VoucherNo like 'OPV-%') and (LedgerID=".$COAID." or gor ,.active=1 and g.godowntype=0)";*/
		}
		$result=odbc_exec($connection, $sql);
		if(odbc_num_rows($result)<1)
		{
$sql="select Debit,Credit,g.GodownID as GodownID,g.Name as GodownName,LedgerID,g.godowntype from VoucherDetails as vd 
		right outer join godowns as g on vd.ledgerid=g.GodownID where g.GodownID between 1 and 4 and g.active=1 and g.godowntype=0";	
		$result=odbc_exec($connection, $sql);			
		}
		while($row=odbc_fetch_array($result))
		{
		$data[]=$row;	
		}
	//	print_r($data);
		echo json_encode($data);

	}
	if($_GET['action']=="AccountsSetup")
	{
		$data=array();
		$SideBarID=$_GET['SideBarID'];
		$permission=userrights($Userid,$SideBarID,'[Display]',$connection);
		if($permission==1)
		{

						
		if(isset($_GET['NatureID']) && $_GET['NatureID']!="")
		{
			$NatureID="NatureID=".$_GET['NatureID']." and ";
		}
		else
		{
			$NatureID=	"";
		}
		if(isset($_GET['Degree']) && $_GET['Degree']!="")
		{
			$Degree="Degree>=".$_GET['Degree']." and ";
		}
		else
		{
			$Degree=	"";
		}
		if(isset($_GET['Group']) && $_GET['Group']!="")
		{
			$Group="GroupID=".$_GET['Group']." and ";
		}
		else
		{
			$Group=	"";
		}
		if(isset($_GET['Under']) && $_GET['Under']!="")
		{
			$Under="Under=".$_GET['Under']." and ";
		}
		else
		{
			$Under=	"";
		}
		//$NatureID=$_GET['NatureID'];
		if(isset($_GET['L2']) && $_GET['L2']!="")
		{
			$L2="L2 like '%".$_GET['L2']."%' and ";
		}
		else
		{
			$L2="";
		}
		if(isset($_GET['L3']) && $_GET['L3']!="")
		{
			$L3="L3 like '%".$_GET['L3']."%' and ";
		}
		else
		{
			$L3="";
		}
		if(isset($_GET['L1']) && $_GET['L1']!="")
		{
			$L1="COAHead like '%".$_GET['L1']."%' and ";
		}
		else
		{
			$L1="";
		}
				if(isset($_GET['Category']) && $_GET['Category']!="")
		{
			$Category="COAHead like '%".$_GET['Category']."%' and ";
		}
		else
		{
			$Category="";
		}

		if(isset($_GET['COAName']) && $_GET['COAName']!="")
		{
			$COAName="COAName like '%".$_GET['COAName']."%' and ";
		}
		else
		{
			$COAName="";
		}
		if(isset($_GET['Attr4']) && $_GET['Attr4']!="")
		{
			$Attr4="Attr4 like '%".$_GET['Attr4']."%' and ";
		}
		else
		{
			$Attr4="";
		}
				if(isset($_GET['Attr10']) && $_GET['Attr10']!="")
		{
			$Attr10="Attr10 like '%".$_GET['Attr10']."%' and ";
		}
		else
		{
			$Attr10="";
		}
				if(isset($_GET['Attr15']) && $_GET['Attr15']!="")
		{
			$Attr15="Attr15 like '%".$_GET['Attr15']."%' and ";
		}
		else
		{
			$Attr15="";
		}
		$searchbox=$COAName.$Attr4.$Attr10.$Attr15.$L1.$L2.$L3.$Group.$Category.$Under.$Degree;
		
		  $sql="select ROW_NUMBER() OVER (ORDER BY [Attr18])  as row_num,COAID,COAName,COAHead,L3,L2,Attr1,GLCode,Degree,GroupID,Under from view_account_list where $searchbox $NatureID Active=1";
		  $filename='cache/'.md5($sql).".txt";
       if (filemtime($filename) < time()-1*1) 
       {		

		  /*$sql="select ROW_NUMBER() OVER (ORDER BY [Attr18])  as row_num,COAName,Hierarchy,Under,CostCenterID,COAID,GLCode,
(select COAName  from accounts as c where c.COAID=acc.Under) as L3,
(select COAName  from accounts as c where c.COAID=(select Under from accounts as cc where cc.COAID=acc.Under)) as L2,
(select COAName  from accounts as c where c.COAID=(select Under from accounts as cc where cc.COAID=(select Under from accounts as ccc where ccc.COAID=acc.Under))) as COAHead,Degree
,'' as col_Action,Attr1,Attr2,Attr3,Attr4,Attr5,Attr6,Attr7,Attr8,Attr9,Attr10,Attr11,Attr12,Attr13,Attr14,Attr15,Attr16,Attr17,Attr18,Attr19,Attr20 from accounts as acc where $searchbox $NatureID";*/
			$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{
			foreach($row as $key=>$value)
			$row[$key]=utf8_encode($value);	

		/*	$row['COAName']=htmlspecialchars($row['COAName']);
			$row['COAHead']=htmlspecialchars($row['COAHead']);
			$row['L2']=htmlspecialchars($row['L2']);
			$row['L3']=htmlspecialchars($row['L3']);						
*/			
			if($row['GroupID']==true)
			{

					$row["col_Action"]='<i class="fa fa-pencil fa-lg" style="text-align: left;color: gray;cursor:pointer;" disabled=true onclick3="javascript:editRow(this);"></i> &nbsp;&nbsp;&nbsp; <i class="fa fa-trash-o fa-lg" disabled=true style="text-align: right;color: gray;cursor:pointer;" onclick3="javascript:deleteRow(this);"></i>';
			}
			else
			{	
			
				$permission=userrights($Userid,$SideBarID,'[Alter]',$connection);
				if($permission==1)
				{
					$editdata='<i class="fa fa-truck fa-lg" style="text-align: left;color: green;cursor:pointer;" title="Transfer Account" onclick="javascript:TransferAccount(this,'.$row['COAID'].');"></i>&nbsp;&nbsp;&nbsp;<i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editRow(this);"></i>';
				}
				else
				{
					$editdata='';
				}
				$permission=userrights($Userid,$SideBarID,'[Delete]',$connection);
				if($permission==1)
				{
					$deldata='<i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteRow(this);"></i>';
				}
				else
				{
					$deldata='';
				}
				//			
			$row["col_Action"]=''.$editdata.' &nbsp;&nbsp; '.$deldata;
			}
		$data[]=$row;	
		}//end while 
			 @unlink($filename);
          $data=json_encode($data);
          file_put_contents($filename, serialize($data));
		echo ($data);
	}
	else
	{	
		 echo $data=unserialize(file_get_contents($filename));	
	}

	}
	//	print_r($data);
		//echo ($data);

	
	}

	if($_GET['action']=="GetAccountsMasterForm")
	{
		$SideBarID=isset($_GET['SideBarID'])?$_GET['SideBarID']:43;

		if(isset($_GET['NatureID']) && $_GET['NatureID']!="")
		{
			$NatureID="NatureID=".$_GET['NatureID']." and ";
		}
		else
		{
			$NatureID=	"";
		}
		if(isset($_GET['Group']) && $_GET['Group']!="")
		{
			$Group="GroupID=".$_GET['Group']." and ";
		}
		else
		{
			$Group=	"";
		}
		if(isset($_GET['Under']) && $_GET['Under']!="")
		{
			$Under="Under=".$_GET['Under']." and ";
		}
		else
		{
			$Under=	"";
		}
		if(isset($_GET['Degree']) && $_GET['Degree']!="")
		{
			$Degree="Degree>=".$_GET['Degree']." and ";
		}
		else
		{
			$Degree=	"";
		}
		//$NatureID=$_GET['NatureID'];
		if(isset($_GET['L2']) && $_GET['L2']!="")
		{
			$L2="L2 like '%".$_GET['L2']."%' and ";
		}
		else
		{
			$L2="";
		}
		if(isset($_GET['L3']) && $_GET['L3']!="")
		{
			$L3="L3 like '%".$_GET['L3']."%' and ";
		}
		else
		{
			$L3="";
		}
		if(isset($_GET['L1']) && $_GET['L1']!="")
		{
			$L1="COAHead like '%".$_GET['L1']."%' and ";
		}
		else
		{
			$L1="";
		}
				if(isset($_GET['Category']) && $_GET['Category']!="")
		{
			$Category="COAHead like '%".$_GET['Category']."%' and ";
		}
		else
		{
			$Category="";
		}

		if(isset($_GET['COAName']) && $_GET['COAName']!="")
		{
			$COAName="COAName like '%".$_GET['COAName']."%' and ";
		}
		else
		{
			$COAName="";
		}
		if(isset($_GET['Attr4']) && $_GET['Attr4']!="")
		{
			$Attr4="Attr4 like '%".$_GET['Attr4']."%' and ";
		}
		else
		{
			$Attr4="";
		}
				if(isset($_GET['Attr10']) && $_GET['Attr10']!="")
		{
			$Attr10="Attr10 like '%".$_GET['Attr10']."%' and ";
		}
		else
		{
			$Attr10="";
		}
				if(isset($_GET['Attr15']) && $_GET['Attr15']!="")
		{
			$Attr15="Attr15 like '%".$_GET['Attr15']."%' and ";
		}
		else
		{
			$Attr15="";
		}
		$searchbox=$COAName.$Attr4.$Attr10.$Attr15.$L1.$L2.$L3.$Group.$Category.$Under.$Degree;
		$data=array();
		  $sql="select * from view_account_list where $searchbox $NatureID Active=1 and Degree>1 order by convert(varchar,GLCode)";
		  /*$sql="select ROW_NUMBER() OVER (ORDER BY [Attr18])  as row_num,COAName,Hierarchy,Under,CostCenterID,COAID,GLCode,
(select COAName  from accounts as c where c.COAID=acc.Under) as L3,
(select COAName  from accounts as c where c.COAID=(select Under from accounts as cc where cc.COAID=acc.Under)) as L2,
(select COAName  from accounts as c where c.COAID=(select Under from accounts as cc where cc.COAID=(select Under from accounts as ccc where ccc.COAID=acc.Under))) as COAHead,Degree
,'' as col_Action,Attr1,Attr2,Attr3,Attr4,Attr5,Attr6,Attr7,Attr8,Attr9,Attr10,Attr11,Attr12,Attr13,Attr14,Attr15,Attr16,Attr17,Attr18,Attr19,Attr20 from accounts as acc where $searchbox $NatureID";*/
   $filename='cache/'.md5($sql).".txt";
       if (filemtime($filename) < time()-1*1) 
	{
			$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{
			foreach($row as $key=>$value)
			$row[$key]=utf8_encode($value);	

			//$row['COAName']=htmlspecialchars($row['COAName']);
/*			$row['COAHead']=htmlspecialchars($row['COAHead']);
			$row['L2']=htmlspecialchars($row['L2']);
			$row['L3']=htmlspecialchars($row['L3']);						
*/		
$permission=userrights($Userid,$SideBarID,'[Alter]',$connection);
if($permission==1 && $row['Degree']>1 || 1==1)
{			
$editdata='<i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editRow(this);"></i>';
}
else
{
	$editdata='';
}
$permission=userrights($Userid,$SideBarID,'[Delete]',$connection);
if($permission==1 && $row['Degree']>1 || 1==1)
{
$deldata='<i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteRow(this);"></i>';
}
else
{
$deldata='';	
}
	$row["col_Action"]=''.$editdata.' &nbsp;&nbsp;&nbsp;'.$deldata;
		$data[]=$row;	
		}//end while
	//	print_r($data);
		 @unlink($filename);
          $data=json_encode($data);
          file_put_contents($filename, serialize($data));
		echo ($data);
	}
	else
	{	
		echo $data=unserialize(file_get_contents($filename));	
	}


	}
	if($_GET['action']=="GetAccountsMasterForm2")
	{
		$data=array();
		if(isset($_GET['GLStartsWith']) && $_GET['GLStartsWith']!="" && $_GET['GLStartsWith']!="undefined")
		{
		$GLCode=$_GET['GLStartsWith'];
		$GLCode="GLCode like '".$GLCode."%' and";
		}
		else
		{
			$GLCode="";
		}
				if(isset($_GET['Group']) && $_GET['Group']!="")
		{
			$Group="acc.[Group]=".$_GET['Group']." and ";
		}
		else
		{
			$Group=	"";
		}
		if(isset($_GET['Degree']) && $_GET['Degree']!="")
		{
			$Degree="acc.Degree>=".$_GET['Degree']." and ";
		}
		else
		{
			$Degree=	"";
		}
		$searchbox=$Group.$GLCode.$Degree;

		 $sql="select ROW_NUMBER() OVER (ORDER BY [Attr18])  as row_num,COAName,Hierarchy,Under,CostCenterID,COAID,GLCode,Degree as Level,
(select COAName  from accounts as c where c.COAID=acc.Under) as L3,
(select COAName  from accounts as c where c.COAID=(select Under from accounts as cc where cc.COAID=acc.Under)) as L2,
(select COAName  from accounts as c where c.COAID=(select Under from accounts as cc where cc.COAID=(select Under from accounts as ccc where ccc.COAID=acc.Under))) as COAHead,(select COAName  from accounts as c where c.COAID=(select Under from accounts as cc where cc.COAID=(select Under from accounts as ccc where ccc.COAID=acc.Under))) as L1
,'' as col_Action,Attr1,Attr2,Attr3,Attr4,Attr5,Attr6,Attr7,Attr8,Attr9,Attr10,Attr11,Attr12,Attr13,Attr14,Attr15,Attr16,Attr17,Attr18,Attr19,Attr20 from accounts as acc where $searchbox acc.Active=1 order by GLCode";
$filename='cache/'.md5($sql).".txt";
       if (filemtime($filename) < time()-1*1) 
       {		

			$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
		while($row=odbc_fetch_array($result))
		{
			foreach($row as $key=>$value)
			$row[$key]=utf8_encode($value);

		/*	$row['COAName']=htmlspecialchars($row['COAName']);
			$row['COAHead']=htmlspecialchars($row['COAHead']);
			$row['L2']=htmlspecialchars($row['L2']);	
			$row['L3']=htmlspecialchars($row['L3']);						
*/	
		$data[]=$row;	
		}
	//	print_r($data);
		//echo json_encode($data);
		 @unlink($filename);
          $data=json_encode($data);
          file_put_contents($filename, serialize($data));
		echo ($data);
	}
	else
	{	
		echo $data=unserialize(file_get_contents($filename));	
	}

	}//end getaccoutmaster

}

function generateH($degree,$COAID,$connection)
{
	$updatesql="";
	if($degree==5)
	{
$updatesql="update accounts set Hierarchy='{'+(select convert(varchar,Under) from accounts as acc3 where acc3.COAID=(select Under from accounts as acc2 where acc2.COAID=(select Under from accounts as  acc1 where acc1.COAID=accounts.under)))+'},{'+(select convert(varchar,Under) from accounts as acc2 where acc2.COAID=(select Under from accounts as  acc1 where acc1.COAID=accounts.under))+'},{'+
(select convert(varchar,Under) from accounts as  acc1 where acc1.COAID=accounts.under)+'},{'+convert(varchar,Under)+
'},{'+convert(varchar,COAID)+'}' from accounts where COAID=$COAID";
	}
	elseif ($degree==4) {
		# code...
$updatesql="update accounts set Hierarchy='{'+(select convert(varchar,Under) from accounts as acc2 where acc2.COAID=(select Under from accounts as  acc1 where acc1.COAID=accounts.under))+'},{'+
(select convert(varchar,Under) from accounts as  acc1 where acc1.COAID=accounts.under)+'},{'+convert(varchar,Under)+
'},{'+convert(varchar,COAID)+'}' from accounts where COAID=$COAID";	
	}
	elseif ($degree==3) {
		# code...
$updatesql="update accounts set Hierarchy='{'+(select convert(varchar,Under) from accounts as  acc1 where acc1.COAID=accounts.under)+'},{'+convert(varchar,Under)+'},{'+convert(varchar,COAID)+'}' from accounts where COAID=$COAID";		
	}
	elseif($degree==2)
	{
		$updatesql="update accounts set Hierarchy='{'+convert(varchar,Under)+'},{'+convert(varchar,COAID)+'}' from accounts where COAID=$COAID";
	}
odbc_exec($connection,$updatesql);
}
?>