<?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']))
{

if($_GET['action']=="incomestatement")
  {
$data=array();
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date="   VoucherDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
    
    }
    else
    {
      $date='';
      $openingDebit="0";
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID="  LocationID=".$_GET['LocationID']." and ";
    }
    else
    {
      $LocationID="";
    }
    if(isset($_GET['Degree']) && $_GET['Degree']!="undefined" && $_GET['Degree']!="" && $_GET['Degree']>0)
    {
      $Degree="".$_GET['Degree'];
    }
    else
    {
      $Degree="2";
    }
    if(isset($_GET['COAID']) && ($_GET['COAID']!="undefined" && $_GET['COAID']!=""))
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $COAID=" COAID like '".$_GET['COAID']."' and ";
      $COAID2=" GLCode like '".$_GET['COAID']."%' and ";
    }
    else
    {
      $COAID="";
      $COAID2="";
    }

        $searchbox=$date.$LocationID;

    $sql="
select sum(debit)-Sum(Credit) as Balance,LedgerName,GLCode,groupcode2,GroupName2,groupcode1,GroupName1,GroupName,Nature,NatureCode,COAID from [vw_BalanceSheet] 
where $searchbox   NatureCode in('5','4') 
group by nature,naturecode,groupname,groupname1,groupcode1,groupcode2,groupname2,
ledgername,GLcode,COAID";
   $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {

      foreach($row as $key=>$value)
      { 
        if($value=="0.00")$value=0;
      $row[$key]= utf8_encode($value);  
      }

    $data[]=$row; 
    }
  //  print_r($data);
    echo json_encode($data); 

  
  }
  if($_GET['action']=="SettleVouchers")
  {
    /*print_r($_POST);
    return;*/
     $master=$_POST['master'];
    $mdata=json_decode($master);
   // print_r($mdata);
  //  return;
    //$detail=array_values($_POST);
    $detail=$_POST['detail'];
    $detail=json_decode($detail);
    $detail=json_decode($detail);
   // print_r($detail);

    $vd=$detail;
    //echo count($vd);
   // return;
    $VoucherDetailID=getMaxId("voucherdetails","ID",$connection);
    for($a=0;$a<1;$a++)
    {
    $InvoiceJson=$vd;//isset($vd[$a])?$vd[$a]:'';
    $InvoiceJson=json_encode($InvoiceJson);
    $VoucherID=isset($mdata->VoucherID)?$mdata->VoucherID:0;

  //update  invoice
  if($InvoiceJson!="")
  $res=updateInvoice1($InvoiceJson,$connection,$VoucherID,$VoucherDetailID);
    }
      //$res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');

/*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');

}*/
echo json_encode($res);
  }

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

      $data=array();  
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" convert(date,InvoiceDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
    
    }
    else
    {
      $date='';
     // $openingDebit="0";
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID="  im.GodownID=".$_GET['LocationID']."  and ";
    }
    else
    {
      $LocationID="";
    }
    $searchbox=$date.$LocationID;
    $sql="select case when im.InvoiceType=5 then 'JOBCARD' when im.InvoiceType=8 then 'SALES' when im.InvoiceType=4 then 'PURCHASE' when im.InvoiceType=3 then 'PURCHASE Return' end  as InvoiceType1,
  acc.COAName,g.Name as Company,g.AdditionalInfo1 as ShortName,im.paid as TotalPaid,Balance,convert(numeric,NetAmount) as NetAmount, convert(numeric,TotalAmount) as TotalAmount,convert(numeric,(TotalAmount-(isNull(DiscountAmount,0)))) as TaxableAmount,convert(numeric,TotalTaxAmount)TotalTaxAmount,convert(numeric,isNull(DiscountAmount,0)) as DiscountAmount,im.KeyField as KeyField,InvoiceID,InvoiceDate,CustomerName from invoicemaster as im
 left outer join accounts as acc on im.SupplierID=acc.COAID
 left outer join Godowns as g on im.GodownID=g.GodownID

  where $searchbox InvoiceStatus=4 and SupplierID=1066 and InvoiceType in(5,8) order by im.GodownID";
    $result=odbc_exec($connection, $sql);//4,3 
    while($row=odbc_fetch_array($result))
    {

    $data['master'][]=$row;
    $InvoiceID=$row['InvoiceID'];
    $sql2="select InvoiceID,inventory.Name as ItemID,convert(numeric,UnitPrice) as UnitPrice,convert(numeric,Qty) as Qty,convert(numeric,Amount) as Amount,convert(numeric,(Amount-(isNull(DiscountAmount,0)))) as TaxableAmount,convert(numeric,isNull(DiscountAmount,0)) as DiscountAmount,convert(numeric,isNull(TaxAmount,0)) as Vat, convert(numeric,NetAmount) as NetAmount from invoicedetail inner join inventory on invoicedetail.ItemID=inventory.ID where InvoiceID=".$InvoiceID;
    $result2=odbc_exec($connection, $sql2);//4,3 
      while($row2=odbc_fetch_array($result2))
      {
        $data['detail'][$InvoiceID][]=$row2;
      }     

    }
  echo json_encode($data);
  
  }
  
  if($_GET['action']=="ProductionSummaryReport")
  {



      $data=array();  
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" InvoiceDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
     $date1=" convert(date,today) between '".$_GET['startdate']." 00:00:00' and '".$_GET['enddate']." 23:59:59' and ";
    }
    else
    {
      $date=" InvoiceDate='".Date("Y-m-d")."' and ";
       $date1="";
     // $openingDebit="0";
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID="  godownid=".$_GET['LocationID']."  and ";
    }
    else
    {
      $LocationID="";
    }
    if(isset($_GET['SupplierID']) && $_GET['SupplierID']!="undefined" && $_GET['SupplierID']!="" && $_GET['SupplierID']>0)
    {
      $SupplierID="  (under in(select under from inventory where under=".$_GET['SupplierID'].") or under=".$_GET['SupplierID'].")  and ";
    }
    else
    {
      $SupplierID="";
    }
    if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined" && $_GET['VoucherNo']!="" && $_GET['VoucherNo']>0)
    {
      $VoucherNo="  ItemID=".$_GET['VoucherNo']."  and ";
      $SupplierID="";
    }
    else
    {
      $VoucherNo="";
    }
//sum(cash) as Cash,sum(CreditCard) as CreditCard,sum(mCard) as mCard 
    $searchbox=$date.$LocationID.$SupplierID.$VoucherNo;
    $searchbox1=$date1.$LocationID.$SupplierID;
        $sql="
 select GodownID,Company,category,Service,convert(numeric(7),sum(qty))as qty ,convert(numeric(7,2),price) as price,0 as GP,convert(numeric(7,2),sum(NetAmount)) as NetAmount from ProductionSummaryReport 
  where  $searchbox 1=1 group by InvoiceDate,GodownID,Company,category,Service,price";
    $result=odbc_exec($connection, $sql);//4,3 
    while($row=odbc_fetch_array($result))
    {

    $data['master'][]=$row;
    
    }
   /* $sql="select sum(Cash) as Cash,sum(CreditCard) as CreditCard,sum(MutakamelaCard) as mCard from dailyreport2 where $searchbox1 1=1 ";
      $result=odbc_exec($connection, $sql);//4,3 
    while($row=odbc_fetch_array($result))
    {
      if(isset($_GET['LocationID']) && $_GET['LocationID']<1)
        $GodownID=0;
      else
        $GodownID=$_GET['LocationID'];
     $data['company'][$GodownID][]=$row;
         
    }*/
  echo json_encode($data);
  
  
  
  }

  //[MaterialSummaryReport]
  if($_GET['action']=="MaterialSummaryReport")
  {




      $data=array();  
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" InvoiceDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
     $date1=" convert(date,today) between '".$_GET['startdate']." 00:00:00' and '".$_GET['enddate']." 23:59:59' and ";
    }
    else
    {
      $date=" InvoiceDate='".Date("Y-m-d")."' and ";
       $date1="";
     // $openingDebit="0";
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID="  godownid=".$_GET['LocationID']."  and ";
    }
    else
    {
      $LocationID="";
    }
    if(isset($_GET['SupplierID']) && $_GET['SupplierID']!="undefined" && $_GET['SupplierID']!="" && $_GET['SupplierID']>0)
    {
      $SupplierID="  (under in(select under from inventory where under=".$_GET['SupplierID'].") or under=".$_GET['SupplierID'].")  and ";
    }
    else
    {
      $SupplierID="";
    }
    if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined" && $_GET['VoucherNo']!="" && $_GET['VoucherNo']>0)
    {
      $VoucherNo="  ItemID=".$_GET['VoucherNo']."  and ";
      $SupplierID="";
    }
    else
    {
      $VoucherNo="";
    }
//sum(cash) as Cash,sum(CreditCard) as CreditCard,sum(mCard) as mCard 
    $searchbox=$date.$LocationID.$SupplierID.$VoucherNo;
    $searchbox1=$date1.$LocationID.$SupplierID;
       $sql="
 select GodownID,Company,category,Service,convert(numeric(7),sum(qty))as qty ,convert(numeric(7,2),price) as price,0 as GP,convert(numeric(7,2),sum(NetAmount)) as NetAmount from MaterialSummaryReport 
  where  $searchbox 1=1 group by Company,GodownID,category,Service,price";
    $result=odbc_exec($connection, $sql);//4,3 
    while($row=odbc_fetch_array($result))
    {

    $data['master'][]=$row;
    
    }
   /* $sql="select sum(Cash) as Cash,sum(CreditCard) as CreditCard,sum(MutakamelaCard) as mCard from dailyreport2 where $searchbox1 1=1 ";
      $result=odbc_exec($connection, $sql);//4,3 
    while($row=odbc_fetch_array($result))
    {
      if(isset($_GET['LocationID']) && $_GET['LocationID']<1)
        $GodownID=0;
      else
        $GodownID=$_GET['LocationID'];
     $data['company'][$GodownID][]=$row;
         
    }*/
  echo json_encode($data);
  
  
  
  
  }
  if($_GET['action']=="PurchaseSummaryReport")
  {


      $data=array();  
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" InvoiceDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
     $date1=" convert(date,today) between '".$_GET['startdate']." 00:00:00' and '".$_GET['enddate']." 23:59:59' and ";
    }
    else
    {
      $date=" InvoiceDate='".Date("Y-m-d")."' and ";
       $date1="";
     // $openingDebit="0";
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID="  godownid=".$_GET['LocationID']."  and ";
    }
    else
    {
      $LocationID="";
    }
    if(isset($_GET['SupplierID']) && $_GET['SupplierID']!="undefined" && $_GET['SupplierID']!="" && $_GET['SupplierID']>0)
    {
      $SupplierID="  (under in(select under from inventory where under=".$_GET['SupplierID'].") or under=".$_GET['SupplierID'].")  and ";
    }
    else
    {
      $SupplierID="";
    }
    if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined" && $_GET['VoucherNo']!="" && $_GET['VoucherNo']>0)
    {
      $VoucherNo="  ItemID=".$_GET['VoucherNo']."  and ";
      $SupplierID="";
    }
    else
    {
      $VoucherNo="";
    }
//sum(cash) as Cash,sum(CreditCard) as CreditCard,sum(mCard) as mCard 
    $searchbox=$date.$LocationID.$SupplierID.$VoucherNo;
    $searchbox1=$date1.$LocationID.$SupplierID;
       $sql="
 select GodownID,Company,category,Service,convert(numeric(7),sum(qty))as qty ,convert(numeric(7,2),price) as price,0 as GP,convert(numeric(7,2),sum(NetAmount)) as NetAmount from PurchaseSummaryReport 
  where  $searchbox 1=1 group by InvoiceDate,GodownID,Company,category,Service,price";
    $result=odbc_exec($connection, $sql);//4,3 
    while($row=odbc_fetch_array($result))
    {

    $data['master'][]=$row;
    
    }
   /* $sql="select sum(Cash) as Cash,sum(CreditCard) as CreditCard,sum(MutakamelaCard) as mCard from dailyreport2 where $searchbox1 1=1 ";
      $result=odbc_exec($connection, $sql);//4,3 
    while($row=odbc_fetch_array($result))
    {
      if(isset($_GET['LocationID']) && $_GET['LocationID']<1)
        $GodownID=0;
      else
        $GodownID=$_GET['LocationID'];
     $data['company'][$GodownID][]=$row;
         
    }*/
  echo json_encode($data);
  
  
  }
  if($_GET['action']=="ServiceSummaryReport")
  {

      $data=array();  
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" InvoiceDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
     $date1=" convert(date,today) between '".$_GET['startdate']." 00:00:00' and '".$_GET['enddate']." 23:59:59' and ";
    }
    else
    {
      $date=" InvoiceDate='".Date("Y-m-d")."' and ";
       $date1="";
     // $openingDebit="0";
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID="  godownid=".$_GET['LocationID']."  and ";
    }
    else
    {
      $LocationID="";
    }
    if(isset($_GET['SupplierID']) && $_GET['SupplierID']!="undefined" && $_GET['SupplierID']!="" && $_GET['SupplierID']>0)
    {
      $SupplierID="  (under in(select under from inventory where under=".$_GET['SupplierID'].") or under=".$_GET['SupplierID'].")  and ";
    }
    else
    {
      $SupplierID="";
    }
    if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined" && $_GET['VoucherNo']!="" && $_GET['VoucherNo']>0)
    {
      $VoucherNo="  ItemID=".$_GET['VoucherNo']."  and ";
      $SupplierID="";
    }
    else
    {
      $VoucherNo="";
    }
//sum(cash) as Cash,sum(CreditCard) as CreditCard,sum(mCard) as mCard 
    $searchbox=$date.$LocationID.$SupplierID.$VoucherNo;
    $searchbox1=$date1.$LocationID.$SupplierID;
        /*$sql="
 select GodownID,Company,category,Service,convert(numeric(7,2),sum(qty))as qty ,convert(numeric(7,2),price) as price,(sum(CostPrice)) as CostPrice,sum(GP) as GP,convert(numeric(7,2),sum(NetAmount)) as NetAmount from SalesSummaryReport 
  where  $searchbox 1=1 group by InvoiceDate,GodownID,Company,category,Service,price,CostPrice";*/
  $sql="select GodownID,Company,category,Service,convert(numeric(7,2),sum(qty))as qty ,convert(numeric(7,2),price) as price,(case when  sum(qty)<0 and sum(CostPrice)>0 then (sum(CostPrice)*-1) else sum(CostPrice) end ) as CostPrice,
case when sum(qty)>0 then (sum(Netamount)-sum(CostPrice)) else (abs(sum(Netamount))-abs(sum(CostPrice)))*-1 end  as GP,convert(numeric(7,2),sum(NetAmount)) as NetAmount 
from SalesSummaryReport where  $searchbox 1=1 group by InvoiceDate,GodownID,Company,category,Service,price,CostPrice";
    $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);//4,3 
    while($row=odbc_fetch_array($result))
    {

    $data['master'][]=$row;
    
    }
    $sql="select sum(Cash) as Cash,sum(CreditCard) as CreditCard,sum(MutakamelaCard) as mCard from dailyreport2 where $searchbox1 1=1 ";
      $result=odbc_exec($connection, $sql);//4,3 
    while($row=odbc_fetch_array($result))
    {
      if(isset($_GET['LocationID']) && $_GET['LocationID']<1)
        $GodownID=0;
      else
        $GodownID=$_GET['LocationID'];
     $data['company'][$GodownID][]=$row;
         
    }
  echo json_encode($data);
  
  }
  if($_GET['action']=="SalesSummaryReport")
  {

      $data=array();  
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" convert(date,InvoiceDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
    
    }
    else
    {
      $date=" convert(date,InvoiceDate)='".Date("Y-m-d")."' and ";
     // $openingDebit="0";
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID="  godownid=".$_GET['LocationID']."  and ";
    }
    else
    {
      $LocationID=" godownid>0  and ";
    }
        if(isset($_GET['SupplierID']) && $_GET['SupplierID']!="undefined" && $_GET['SupplierID']!="" && $_GET['SupplierID']>0)
    {
      $SupplierID="  under in(select under from inventory where under=".$_GET['SupplierID'].")  and ";
    }
    else
    {
      $SupplierID="";
    }
        if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined" && $_GET['VoucherNo']!="" && $_GET['VoucherNo']>0)
    {
      $VoucherNo="  ItemID=".$_GET['VoucherNo']."  and ";
      $SupplierID="";
    }
    else
    {
      $VoucherNo="";
    }
        if(isset($_GET['UserName']) && $_GET['UserName']!="undefined" && $_GET['UserName']!="")
    {
  $UserName="  (UserName='".strtoupper($_GET['UserName'])."' or Cashier='".strtoupper($_GET['UserName'])."')  and ";
      
    }
    else
    {
      $UserName="";
    }
    $searchbox=$date.$LocationID.$SupplierID.$VoucherNo.$UserName;
    
      $sql="select * from salesdetailreport 
  where $searchbox 1=1 order by Company";
    $result=odbc_exec($connection, $sql);//4,3 
    while($row=odbc_fetch_array($result))
    {

    $data['master'][]=$row;
    
    }
  echo json_encode($data);
  
  }
  if($_GET['action']=="SalesReportDM")
  {

      $data=array();  
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" convert(date,InvoiceDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
    
    }
    else
    {
      $date="";// convert(date,InvoiceDate)='".Date("Y-m-d")."' and ";
     // $openingDebit="0";
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID="  im.GodownID=".$_GET['LocationID']."  and ";
    }
    else
    {
      $LocationID="";
    }
        if(isset($_GET['SupplierID']) && $_GET['SupplierID']!="undefined" && $_GET['SupplierID']!="" )
    {
      $SupplierID="  im.CreateLog='".$_GET['SupplierID']."'  and ";
    }
    else
    {
      $SupplierID="";
    }
    $searchbox=$date.$LocationID.$SupplierID;
       $sql="select case when im.InvoiceType=5 then 'JOBCARD' when im.InvoiceType=8 then 'SALES' when im.InvoiceType=4 then 'PURCHASE' when im.InvoiceType=3 then 'PURCHASE Return' end  as InvoiceType1,
  acc.COAName,g.Name as Company,g.AdditionalInfo1 as ShortName,im.paid as TotalPaid,Balance,convert(numeric,NetAmount) as NetAmount, convert(numeric,TotalAmount) as TotalAmount,convert(numeric,(TotalAmount-(isNull(DiscountAmount,0)))) as TaxableAmount,convert(numeric,TotalTaxAmount)TotalTaxAmount,convert(numeric,isNull(DiscountAmount,0)) as DiscountAmount,im.KeyField as KeyField,im.CreateLog as UserName,im.EditLog as Cashier,InvoiceID,InvoiceDate,CustomerName,Notes from invoicemaster as im
 left outer join accounts as acc on im.SupplierID=acc.COAID
 left outer join Godowns as g on im.GodownID=g.GodownID

  where $searchbox  InvoiceType in(5,8) and ItemID=2 and im.active=1 order by im.GodownID";
    $result=odbc_exec($connection, $sql);//4,3 
    while($row=odbc_fetch_array($result))
    {

    $data['master'][]=$row;
    $InvoiceID=$row['InvoiceID'];
    $sql2="select InvoiceID,inventory.Name as ItemID,convert(numeric,UnitPrice) as UnitPrice,convert(numeric,Qty) as Qty,convert(numeric,Amount) as Amount,convert(numeric,(Amount-(isNull(DiscountAmount,0)))) as TaxableAmount,convert(numeric,isNull(DiscountAmount,0)) as DiscountAmount,convert(numeric,isNull(TaxAmount,0)) as Vat, convert(numeric,NetAmount) as NetAmount from invoicedetail left outer join inventory on invoicedetail.ItemID=inventory.ID where InvoiceID=".$InvoiceID;
    $result2=odbc_exec($connection, $sql2);//4,3 
      while($row2=odbc_fetch_array($result2))
      {
        $data['detail'][$InvoiceID][]=$row2;
      }     

    }
  echo json_encode($data);
  
  }
  if($_GET['action']=="SalesOrderSummary")
  {


      $data=array();  
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" InvoiceDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
    
    }
    else
    {
      $date="";// convert(date,InvoiceDate)='".Date("Y-m-d")."' and ";
     // $openingDebit="0";
    } 
    if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined" && $_GET['VoucherNo']!="" && $_GET['VoucherNo']>0)
    {
      $VoucherNo="  im.InvoiceStatus=".$_GET['VoucherNo']."  and ";
    }
    else
    {
      $VoucherNo="";
    }
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID="  im.GodownID=".$_GET['LocationID']."  and ";
    }
    else
    {
      $LocationID="";
    }
        if(isset($_GET['SupplierID']) && $_GET['SupplierID']!="undefined" && $_GET['SupplierID']!="" && $_GET['SupplierID']>0)
    {
      $SupplierID="  im.SupplierID=".$_GET['SupplierID']."  and ";
    }
    else
    {
      $SupplierID="";
    }
            if(isset($_GET['UserName']) && $_GET['UserName']!="undefined" && $_GET['UserName']!="" && $_GET['UserName']>0)
    {
      $UserName="  (im.CreateLog='".$_GET['UserName']."' or im.EditLog='".$_GET['UserName']."')  and ";
      
    }
    else
    {
      $UserName="";
    }
    $searchbox=$date.$LocationID.$SupplierID.$VoucherNo.$UserName;
     $sql="select case when im.InvoiceType=5 then 'JOBCARD' when im.InvoiceType=8 then 'SALES' when im.InvoiceType=4 then 'PURCHASE' when im.InvoiceType=3 then 'PURCHASE Return' end  as InvoiceType1,
  acc.COAName,g.Name as Company,g.AdditionalInfo1 as ShortName,im.paid as TotalPaid,Balance,NetAmount, isnull(TotalAmount,0) as TotalAmount,convert(numeric,(TotalAmount-(isNull(DiscountAmount,0)))) as TaxableAmount,isnull(TotalTaxAmount,0) as TotalTaxAmount,isNull(DiscountAmount,0) as DiscountAmount,im.KeyField as KeyField,im.EditLog as Cashier,InvoiceID,InvoiceDate,DueDate,CustomerName,case when im.InvoiceStatus=1 then 'PENDING' when  im.InvoiceStatus=2 then 'ACCEPTED' when  im.InvoiceStatus=3 then 'REJECTED' when  im.InvoiceStatus=4 then 'CLOSED' end as InvoiceStatus1,im.GodownID as GodownID,im.VoucherDateTime as VoucherDateTime 
   from invoicemaster as im
 left outer join accounts as acc on im.SupplierID=acc.COAID
 left outer join Godowns as g on im.GodownID=g.GodownID

  where $searchbox  InvoiceType in(5,8) order by im.GodownID";
    $result=odbc_exec($connection, $sql);//4,3 
    while($row=odbc_fetch_array($result))
    {

    $data['master'][]=$row;
    $InvoiceID=$row['InvoiceID'];
     $sql2="select InvoiceID,inventory.Name as ItemID,convert(numeric,UnitPrice) as UnitPrice,convert(numeric,Qty) as Qty,isnull(Amount,0) as Amount,(isNull(Amount,0)-(isNull(DiscountAmount,0))) as TaxableAmount,isNull(DiscountAmount,0) as DiscountAmount,isNull(TaxAmount,0) as Vat, NetAmount,(select isnull(sum(qty),0) from stockledger where InvoiceTypeID=58 and itemid=invoicedetail.ItemID and departmentid=8 and ReferenceInvoiceID=invoicedetail.InvoiceID) as Completed,((select isnull(sum(qty),0) from stockledger where InvoiceTypeID=55  and ReferenceItemid=invoicedetail.ItemID and ReferenceInvoiceID=invoicedetail.InvoiceID ) ) as Cutting,((select isnull(sum(qty),0) from stockledger where InvoiceTypeID=56 and itemid=invoicedetail.ItemID and ReferenceInvoiceID=invoicedetail.InvoiceID)) as Finish,((select isnull(sum(qty),0) from stockledger where InvoiceTypeID=57 and itemid=invoicedetail.ItemID and ReferenceInvoiceID=invoicedetail.InvoiceID and Qty>0)) as QC,((select isnull(sum(qty),0) from stockledger where InvoiceTypeID=58 and itemid=invoicedetail.ItemID and ReferenceInvoiceID=invoicedetail.InvoiceID and Qty>0)) as Iron,((select -1*(isnull(sum(qty),0)) from stockledger where InvoiceTypeID=59 and itemid=invoicedetail.ItemID and departmentid=8 and ReferenceInvoiceID=invoicedetail.InvoiceID)) as Delivered from invoicedetail inner join inventory on invoicedetail.ItemID=inventory.ID where InvoiceID=".$InvoiceID;
    $result2=odbc_exec($connection, $sql2);//4,3 
      while($row2=odbc_fetch_array($result2))
      {
        $data['detail'][$InvoiceID][]=$row2;
      }     

    }
  echo json_encode($data);
  
  
  }
  if($_GET['action']=="PurchaseReportJobCard")
  {


      $data=array();  

    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" InvoiceDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
    
    }
    else
    {
      $date=" convert(date,InvoiceDate)='".Date("Y-m-d")."' and ";
     // $openingDebit="0";
    } 
    if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined" && $_GET['VoucherNo']!="" && $_GET['VoucherNo']>0)
    {
      $VoucherNo="  im.InvoiceStatus=".$_GET['VoucherNo']."  and ";
    }
    else
    {
      $VoucherNo="";
    }
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID="  im.GodownID=".$_GET['LocationID']."  and ";
    }
    else
    {
      $LocationID="";
    }
    if(isset($_GET['ProductID']) && $_GET['ProductID']!="undefined" && $_GET['ProductID']!="" && $_GET['ProductID']>0)
    {
      $ProductID="and InvoiceID in (select InvoiceID from  Invoicedetail where ItemID=".$_GET['ProductID']." )";
    }
    else
    {
      $ProductID="";
    }
        if(isset($_GET['SupplierID']) && $_GET['SupplierID']!="undefined" && $_GET['SupplierID']!="" && $_GET['SupplierID']>0)
    {
      $SupplierID="  im.CustomerID=".$_GET['SupplierID']."  and ";
    }
    else
    {
      $SupplierID="";
    }
            if(isset($_GET['UserName']) && $_GET['UserName']!="undefined" && $_GET['UserName']!="" && $_GET['UserName']>0)
    {
      $UserName="  (im.CreateLog='".$_GET['UserName']."' or im.EditLog='".$_GET['UserName']."')  and ";
      
    }
    else
    {
      $UserName="";
    }
    $searchbox=$date.$LocationID.$SupplierID.$VoucherNo.$UserName;
     $sql="select case when im.InvoiceType=5 then 'JOBCARD' when im.InvoiceType=5 then 'SALES' when im.InvoiceType=3 then 'PURCHASE' when im.InvoiceType=4 then 'PURCHASE Return' end  as InvoiceType1,
  acc.COAName,g.Name as Company,g.AdditionalInfo1 as ShortName,im.Paid as TotalPaid,Balance,NetAmount, isnull(TotalAmount,0) as TotalAmount,convert(numeric,(TotalAmount-(isNull(DiscountAmount,0)))) as TaxableAmount,isnull(TotalTaxAmount,0) as TotalTaxAmount,isNull(DiscountAmount,0) as DiscountAmount,im.KeyField as KeyField,im.EditLog as Cashier,InvoiceID,InvoiceDate,CustomerName,case when im.InvoiceStatus=1 then 'PENDING' when  im.InvoiceStatus=2 then 'ACCEPTED' when  im.InvoiceStatus=3 then 'REJECTED' when  im.InvoiceStatus=4 then 'CLOSED' end as InvoiceStatus1,im.GodownID as GodownID,im.InvoiceDate as VoucherDateTime,im.InvoiceType as InvoiceType from Invoicemaster as im
 left outer join accounts as acc on im.SupplierID=acc.COAID
 left outer join Godowns as g on im.GodownID=g.GodownID

  where $searchbox  InvoiceType in(3,4) $ProductID and im.active=1 and im.InvoiceID in (select ReferenceInvoiceID from VoucherMaster where active=1 and VoucherTypeID in (66,71))
  order by im.GodownID";
    $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);//4,3 
    while($row=odbc_fetch_array($result))
    {
     $InvoiceType=$row['InvoiceType'];

    $InvoiceID=$row['InvoiceID'];
    
    if($InvoiceType==3)
      {
    //$row['TaxableAmount']=($row['TaxableAmount']*-1);
    //$row['NetAmount']=($row['NetAmount']*-1);
      }
    $data['master'][]=$row;
    $sql2="select InvoiceID,inventory.Name as ItemID,convert(numeric(7,2),UnitPrice) as UnitPrice,convert(numeric,Qty) as Qty,isnull(Amount,0) as Amount,(isNull(Amount,0)-(isNull(DiscountAmount,0))) as TaxableAmount,isNull(DiscountAmount,0) as DiscountAmount,isNull(TaxAmount,0) as Vat, NetAmount from Invoicedetail inner join inventory on Invoicedetail.ItemID=inventory.ID where  InvoiceID=".$InvoiceID;
    $result2=odbc_exec($connection, $sql2);//4,3 
      while($row2=odbc_fetch_array($result2))
      {
        if($InvoiceType==3)
        {
         $row2['Qty']= ($row2['Qty']*-1);
         $row2['TaxableAmount']=($row2['TaxableAmount']*-1);
         $row2['NetAmount']=($row2['NetAmount']*-1);
         $row2['Amount']=($row2['Amount']*-1);
         $row2['UnitPrice']=($row2['UnitPrice']*-1);
         

         
        }

        $data['detail'][$InvoiceID][]=$row2;
      }     

    }
  echo json_encode($data);
  
  
  }
  if($_GET['action']=="SalesReportJobCard")
  {

      $data=array();  
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" InvoiceDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
    
    }
    else
    {
      $date=" convert(date,InvoiceDate)='".Date("Y-m-d")."' and ";
     // $openingDebit="0";
    } 
    if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined" && $_GET['VoucherNo']!="" && $_GET['VoucherNo']>0)
    {
      $VoucherNo="  im.MobileNumber like '%".$_GET['VoucherNo']."%'  and ";
    }
    else
    {
      $VoucherNo="";
    }
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID="  im.GodownID=".$_GET['LocationID']."  and ";
    }
    else
    {
      $LocationID="";
    }
        if(isset($_GET['SupplierID']) && $_GET['SupplierID']!="undefined" && $_GET['SupplierID']!="" && $_GET['SupplierID']>0)
    {
      $SupplierID="  im.CustomerID=".$_GET['SupplierID']."  and ";
      $SupplierID1="  im.SupplierID=".$_GET['SupplierID']."  and ";
    }
    else
    {
      $SupplierID=" im.CustomerID not in (20) and ";
      $SupplierID1=" im.SupplierID not in (20) and ";

    }
            if(isset($_GET['UserName']) && $_GET['UserName']!="undefined" && $_GET['UserName']!="" && $_GET['UserName']>0)
    {
      $UserName="  (im.SalesmanID='".$_GET['UserName']."' or im.SalesmanID='".$_GET['UserName']."')  and ";
      
    }
    else
    {
      $UserName="";
    }
    if($_SESSION['UserName']=="admin" || $_SESSION['UserName']=="accounts")
    {
      $log="";
    }
  else
  {
    $log=" im.GodownID=".$_SESSION['CompanyID']." and ";
  }

    $searchbox=$date.$LocationID.$SupplierID.$VoucherNo.$UserName.$log;
    $searchbox1=$date.$LocationID.$SupplierID1.$VoucherNo.$UserName.$log;
     $sql="select case when im.InvoiceType=5 then 'JOBCARD' when im.InvoiceType=3 then 'SALES' when im.InvoiceType=24 then 'PURCHASE' when im.InvoiceType=23 then 'PURCHASE Return' end  as InvoiceType1,im.Narration as Narration,  
  acc.COAName,g.Name as Company,g.AdditionalInfo1 as ShortName,im.Received as TotalPaid,Balance,NetAmount, isnull(TotalAmount,0) as TotalAmount,convert(numeric,(TotalAmount-(isNull(DiscountAmount,0)))) as TaxableAmount,isnull(TotalTaxAmount,0) as TotalTaxAmount,isNull(DiscountAmount,0) as DiscountAmount,im.KeyField as KeyField,im.EditLog as Cashier,InvoiceID,InvoiceDate,CustomerName,case when im.InvoiceStatus=1 then 'PENDING' when  im.InvoiceStatus=2 then 'ACCEPTED' when  im.InvoiceStatus=3 then 'REJECTED' when  im.InvoiceStatus=4 then 'CLOSED' end as InvoiceStatus1,im.GodownID as GodownID,convert(date,im.InvoiceDate) as VoucherDateTime,(select (case when sum(sid.StandardPrice3)=0 then (select sum(sumamt) from (select sum(inv.StandardPrice3)*sum(sid2.qty) as sumamt from SalesInvoiceDetail as sid2 inner join inventory as inv
   on inv.ID=sid2.ItemID where invoiceid=im.InvoiceID group by invoiceid,sid2.ItemID) t)  else sum(sid.StandardPrice3) end)   from SalesInvoiceDetail as sid where InvoiceID=im.InvoiceID group by InvoiceID) as Cost,SalesManName,im.MobileNumber as MobileNumber,InvoiceType from Salesinvoicemaster as im
 left outer join accounts as acc on im.CustomerID=acc.COAID
 left outer join Godowns as g on im.GodownID=g.GodownID
 left outer join SalesmanInformation as sl on im.SalesmanID=sl.SalesmanID
   where $searchbox  InvoiceType in(3,11,4) and im.active=1 
union all
select case when im.InvoiceType=5 then 'JOBCARD' when im.InvoiceType=3 then 'SALES' when im.InvoiceType=24 then 'PURCHASE' when im.InvoiceType=23 then 'PURCHASE Return' end  as InvoiceType1,im.Narration as Narration,  
  acc.COAName,g.Name as Company,g.AdditionalInfo1 as ShortName,im.Paid as TotalPaid,Balance,NetAmount, isnull(TotalAmount,0) as TotalAmount,convert(numeric,(TotalAmount-(isNull(DiscountAmount,0)))) as TaxableAmount,isnull(TotalTaxAmount,0) as TotalTaxAmount,isNull(DiscountAmount,0) as DiscountAmount,im.KeyField as KeyField,im.EditLog as Cashier,InvoiceID,InvoiceDate,CustomerName,case when im.InvoiceStatus=1 then 'PENDING' when  im.InvoiceStatus=2 then 'ACCEPTED' when  im.InvoiceStatus=3 then 'REJECTED' when  im.InvoiceStatus=4 then 'CLOSED' end as InvoiceStatus1,im.GodownID as GodownID,convert(date,im.InvoiceDate) as VoucherDateTime,(0) as Cost,SalesManName,im.MobileNumber as MobileNumber,InvoiceType from invoicemaster as im
 left outer join accounts as acc on im.SupplierID=acc.COAID
 left outer join Godowns as g on im.GodownID=g.GodownID
 left outer join SalesmanInformation as sl on im.SalesmanID=sl.SalesmanID
   where $searchbox1  InvoiceType in(61) and im.active=1 order by im.GodownID
   ";
    $result=odbc_exec($connection, $sql);//4,3 
    while($row=odbc_fetch_array($result))
    {

    $data['master'][]=$row;
    $InvoiceID=$row['InvoiceID'];
    if($row['InvoiceType']==61)
    {
        $sql2="select InvoiceID,inventory.Name as ItemID,inventory.barcode as Barcode,convert(numeric,UnitPrice) as UnitPrice,convert(numeric(7,2),Qty*-1) as Qty,isnull((Amount*-1),0) as Amount,(isNull((Amount*-1),0)-(isNull(DiscountAmount,0))) as TaxableAmount,isNull(DiscountAmount,0) as DiscountAmount,isNull(TaxAmount,0) as Vat, (NetAmount*-1) as NetAmount from invoicedetail inner join inventory on invoicedetail.ItemID=inventory.ID where InvoiceID=".$InvoiceID;
    }
  else
  {

    $sql2="select InvoiceID,inventory.Name as ItemID,inventory.barcode as Barcode,convert(numeric,UnitPrice) as UnitPrice,convert(numeric(7,2),Qty) as Qty,isnull(Amount,0) as Amount,(isNull(Amount,0)-(isNull(DiscountAmount,0))) as TaxableAmount,isNull(DiscountAmount,0) as DiscountAmount,isNull(TaxAmount,0) as Vat, NetAmount from Salesinvoicedetail inner join inventory on Salesinvoicedetail.ItemID=inventory.ID where InvoiceID=".$InvoiceID;
  }
    $result2=odbc_exec($connection, $sql2);//4,3 
      while($row2=odbc_fetch_array($result2))
      {
        $data['detail'][$InvoiceID][]=$row2;
      }     

    }
  echo json_encode($data);
  
  }
  if($_GET['action']=='SalesReport')
  {
      $data=array();  
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" convert(date,InvoiceDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
    
    }
    else
    {
      $date=" convert(date,InvoiceDate)='".Date("Y-m-d")."' and ";
     // $openingDebit="0";
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID="  im.GodownID=".$_GET['LocationID']."  and ";
    }
    else
    {
      $LocationID="";
    }
        if(isset($_GET['SupplierID']) && $_GET['SupplierID']!="undefined" && $_GET['SupplierID']!="" && $_GET['SupplierID']>0)
    {
      $SupplierID="  im.SupplierID=".$_GET['SupplierID']."  and ";
    }
    else
    {
      $SupplierID="";
    }
    $searchbox=$date.$LocationID.$SupplierID;
     $sql="select case when im.InvoiceType=5 then 'JOBCARD' when im.InvoiceType=8 then 'SALES' when im.InvoiceType=4 then 'PURCHASE' when im.InvoiceType=3 then 'PURCHASE Return' end  as InvoiceType1,
  acc.COAName,g.Name as Company,g.AdditionalInfo1 as ShortName,im.paid as TotalPaid,Balance,convert(numeric,NetAmount) as NetAmount, convert(numeric,TotalAmount) as TotalAmount,convert(numeric,(TotalAmount-(isNull(DiscountAmount,0)))) as TaxableAmount,convert(numeric,TotalTaxAmount)TotalTaxAmount,convert(numeric,isNull(DiscountAmount,0)) as DiscountAmount,im.KeyField as KeyField,InvoiceID,InvoiceDate,CustomerName from invoicemaster as im
 left outer join accounts as acc on im.SupplierID=acc.COAID
 left outer join Godowns as g on im.GodownID=g.GodownID

  where $searchbox InvoiceStatus=4 and InvoiceType in(5,8) order by im.GodownID";
    $result=odbc_exec($connection, $sql);//4,3 
    while($row=odbc_fetch_array($result))
    {

    $data['master'][]=$row;
    $InvoiceID=$row['InvoiceID'];
    $sql2="select InvoiceID,inventory.Name as ItemID,convert(numeric,UnitPrice) as UnitPrice,convert(numeric,Qty) as Qty,convert(numeric,Amount) as Amount,convert(numeric,(Amount-(isNull(DiscountAmount,0)))) as TaxableAmount,convert(numeric,isNull(DiscountAmount,0)) as DiscountAmount,convert(numeric,isNull(TaxAmount,0)) as Vat, convert(numeric,NetAmount) as NetAmount from invoicedetail inner join inventory on invoicedetail.ItemID=inventory.ID where InvoiceID=".$InvoiceID;
    $result2=odbc_exec($connection, $sql2);//4,3 
      while($row2=odbc_fetch_array($result2))
      {
        $data['detail'][$InvoiceID][]=$row2;
      }     

    }
  echo json_encode($data);
  }
	if($_GET['action']=="InsertChequeList")
	{
      odbc_autocommit($connection, FALSE);
		//$d=json_decode($_POST);
		$d=array_values($_POST);
		$d=array_keys($d[0]);
		//$d=json_decode($d[0]);
		$dd=explode("{",$d[0]);
		//strrchr($value, "}");

		//print_r($dd);
		foreach ($dd as $key => $value) {
			# code...
			//$line= str_replace("}", "", $value);
			$value=str_replace("},","}", $value);
			$std=json_decode("{".$value);
//			print_r($std);
			
    $InvoiceID=isset($std->InvoiceID)?$std->InvoiceID:0;
    $ChequeDetailID=isset($std->ChequeDetailID)?$std->ChequeDetailID:0;
    $BankID=isset($std->BankID)?$std->BankID:0;
    $BankName=isset($std->BankName)?$std->BankName:0;
    $StatusID=isset($std->StatusID)?$std->StatusID:0;
    $Amount=isset($std->Amount)?$std->Amount:0;

    if($StatusID==669)
    {
    	//$StatusID=2;
    	// Deposit Cheque 
    	//bank Debit 
    	// CHEQUE IN HAND CREDIT (299)
    	$CHEQUEINHAND=299;
    	$InvoiceDate=date("Y-m-d H:i:s");
    	$NetAmount=$Amount;
    	$TotalTaxAmount=$Amount;
    	$$ChequeNo='';
    	$ChequeDate='';
    	//get details of voucher from VoucherMaster 
    	$sql="select * from VoucherMaster where VoucherID=".$ChequeDetailID;
    	$result=odbc_exec($connection,$sql);
    	while ($row=odbc_fetch_array($result)) {
    		# code...
    		$VoucherTypeID=$row['VoucherTypeID'];
    		$ReferenceInvoiceID=$row['ReferenceInvoiceID'];
    		$GodownID=$row['LocationID'];
    		$ChequeNo=$row['ChequeNo'];
    		$ChequeDate=$row['ChequeDate'];
    		$ClientBankAccountName=$row['ClientBankAccountName'];

    	}//end while 
$sqlupdate="update VoucherMaster set ChequeTypeStatus=$StatusID  where VoucherID=".$ChequeDetailID;
 odbc_exec($connection, $sqlupdate);
 

    	$VoucherTypeID=7;
    	$AmountDebit=0;
    	$AmountCredit=0;
    	$ReferenceVoucherID=0;
    	$GroupID=0;
    	$InvoiceType=0;
    	$PaymentType='';
    	$fields=array();
       	$VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$connection)+1;//getmaxId("VoucherMaster","VoucherID",$connection)+1;
    	$KeyField="";
      	if($VoucherTypeID==5)
       	{
       		$VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=5",$connection)+1;
       		$VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
       		$VoucherNo="RV-".$VoucherNo;
       	}
       	if($VoucherTypeID==6)
       	{
       		$VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=6",$connection)+1;
       		$VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
       		$VoucherNo="PV-".$VoucherNo;
       	}
       	if($VoucherTypeID==7)
       	{
       		$VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=7",$connection)+1;
       		$VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
       		$VoucherNo="JV-".$VoucherNo;
       	}



    	   $fields['VoucherID']=$VoucherID;
           $fields['VoucherNo']=$VoucherNo;//isset($VoucherNo)?$VoucherNo:0;
           $fields['TotalAmount']=isset($NetAmount)?$NetAmount:0;
           $fields['Active']=1;//isset($Active)?$Active:0;
           $fields['VoucherDate']=isset($InvoiceDate)?$InvoiceDate:null;
           $fields['Narration']=isset($Narration)?$Narration:0;
           $fields['Posted']=1;//isset($Posted)?$Posted:0;
           $fields['IsPostDated']=0;//isset($IsPostDated)?$IsPostDated:0;
           $fields['ChequeNo']=($ChequeNo!="")?$ChequeNo:0;
		$fields['ClientBankAccountName']=($ClientBankAccountName!="")?$ClientBankAccountName:0;
		   $fields['ChequeStatus']=($StatusID!="")?$StatusID:0;
		   $fields['ChequeDate']=($ChequeDate!="")?$ChequeDate:'';
		   $fields['isVoucherReturnCheque']=0;//isset($IsPostDated)?$IsPostDated:0;
           $fields['VoucherTypeID']=$VoucherTypeID;//isset($VoucherTypeID)?$VoucherTypeID:0;
           $fields['PeriodID']=1;//isset($PeriodID)?$PeriodID:0;
           $fields['ReferenceInvoiceID']=isset($ReferenceInvoiceID)?$ReferenceInvoiceID:0;
           $fields['SupplierID']=0;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($SupplierID)?$SupplierID:0;
           $fields['AmountDebit']=isset($AmountDebit)?$AmountDebit:0;
           $fields['AmountCredit']=isset($AmountCredit)?$AmountCredit:0;
           $fields['IsAuto']=1;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['ReferenceVoucherID']=isset($ChequeDetailID)?$ChequeDetailID:0;
           $fields['GroupID']=isset($GroupID)?$GroupID:0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=0;//isset($Cash)?$Cash:0;
		   $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['UserID']=isset($_SESSION['UserID'])?$_SESSION['UserID']:0;
           $fields['VoucherDateTime']=isset($VoucherDateTime)?$VoucherDateTime:date("Y-m-d m:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'';
         //  print_r($fields);
       		InsertVoucherMaster($fields,$InvoiceType,$InvoiceID,$connection);	
       		// insert voucher details 
       		       	$fdetails=array();	
       
       	   $fdetails['VoucherID']=$VoucherID;
           $fdetails['LedgerID']=$BankID;//$d->CustomerLedgerID; DEbit side entry
           	$Debit=$TotalTaxAmount;
           	$Credit=$TotalTaxAmount;
           	$CreditLedgerID=$CHEQUEINHAND;
        
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="Cheque Deposit";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;//company
           $fdetails['ChequeNo']=$ChequeNo;
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="Cheque Deposit";	
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);		  				
       
    }// state id 
	else if($StatusID=="664")
	{
		//Return Cheque 
		//Customer Debit 
		// BANK Accout 

    	$CHEQUEINHAND=299;
    	$InvoiceDate=date("Y-m-d H:i:s");
    	$NetAmount=$Amount;
    	$TotalTaxAmount=$Amount;
    	$$ChequeNo='';
    	$ChequeDate='';
    	//get details of voucher from VoucherMaster 
    	$sql="select *,(select CreditLedgerID from VoucherDetails where VoucherID=$ChequeDetailID) as CreditLedgerID,(select LedgerID from VoucherDetails where VoucherID=$ChequeDetailID) as DebitLedgerID from VoucherMaster where VoucherID=".$ChequeDetailID;
    	$result=odbc_exec($connection,$sql);
    	while ($row=odbc_fetch_array($result)) {
    		# code...
    		$VoucherTypeID=$row['VoucherTypeID'];
    		$ReferenceInvoiceID=$row['ReferenceInvoiceID'];
    		$GodownID=$row['LocationID'];
    		$ChequeNo=$row['ChequeNo'];
    		$ChequeDate=$row['ChequeDate'];
    		$CreditLedgerID=$row['CreditLedgerID'];
    		$ClientBankAccountName=$row['ClientBankAccountName'];

    	}//end while 
    	$sqlupdate="update VoucherMaster set ChequeTypeStatus=$StatusID  where VoucherID=".$ChequeDetailID;
 odbc_exec($connection, $sqlupdate);
 
    	$VoucherTypeID=7;
    	$AmountDebit=0;
    	$AmountCredit=0;
    	$ReferenceVoucherID=0;
    	$GroupID=0;
    	$InvoiceType=0;
    	$PaymentType='';
    	$fields=array();
       	$VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$connection)+1;//getmaxId("VoucherMaster","VoucherID",$connection)+1;
    	$KeyField="";
      	if($VoucherTypeID==5)
       	{
       		$VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=5",$connection)+1;
       		$VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
       		$VoucherNo="RV-".$VoucherNo;
       	}
       	if($VoucherTypeID==6)
       	{
       		$VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=6",$connection)+1;
       		$VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
       		$VoucherNo="PV-".$VoucherNo;
       	}
       	if($VoucherTypeID==7)
       	{
       		$VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=7",$connection)+1;
       		$VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
       		$VoucherNo="JV-".$VoucherNo;
       	}



    	   $fields['VoucherID']=$VoucherID;
           $fields['VoucherNo']=$VoucherNo;//isset($VoucherNo)?$VoucherNo:0;
           $fields['TotalAmount']=isset($NetAmount)?$NetAmount:0;
           $fields['Active']=1;//isset($Active)?$Active:0;
           $fields['VoucherDate']=isset($InvoiceDate)?$InvoiceDate:null;
           $fields['Narration']=isset($Narration)?$Narration:0;
           $fields['Posted']=1;//isset($Posted)?$Posted:0;
           $fields['IsPostDated']=0;//isset($IsPostDated)?$IsPostDated:0;
           $fields['ChequeNo']=($ChequeNo!="")?$ChequeNo:0;
		$fields['ClientBankAccountName']=($ClientBankAccountName!="")?$ClientBankAccountName:0;
		   $fields['ChequeStatus']=($StatusID!="")?$StatusID:0;
		   $fields['ChequeDate']=($ChequeDate!="")?$ChequeDate:'';
		   $fields['isVoucherReturnCheque']=0;//isset($IsPostDated)?$IsPostDated:0;
           $fields['VoucherTypeID']=$VoucherTypeID;//isset($VoucherTypeID)?$VoucherTypeID:0;
           $fields['PeriodID']=1;//isset($PeriodID)?$PeriodID:0;
           $fields['ReferenceInvoiceID']=isset($ReferenceInvoiceID)?$ReferenceInvoiceID:0;
           $fields['SupplierID']=0;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($SupplierID)?$SupplierID:0;
           $fields['AmountDebit']=isset($AmountDebit)?$AmountDebit:0;
           $fields['AmountCredit']=isset($AmountCredit)?$AmountCredit:0;
           $fields['IsAuto']=1;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['ReferenceVoucherID']=isset($ChequeDetailID)?$ChequeDetailID:0;
           $fields['GroupID']=isset($GroupID)?$GroupID:0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=0;//isset($Cash)?$Cash:0;
		   $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['UserID']=isset($_SESSION['UserID'])?$_SESSION['UserID']:0;
           $fields['VoucherDateTime']=isset($VoucherDateTime)?$VoucherDateTime:date("Y-m-d H:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'';
         //  print_r($fields);
       		InsertVoucherMaster($fields,$InvoiceType,$InvoiceID,$connection);	
       		// insert voucher details 
       		       	$fdetails=array();	
       
       	   $fdetails['VoucherID']=$VoucherID;
           $fdetails['LedgerID']=$CreditLedgerID;//$d->CustomerLedgerID; DEbit side entry
           	$Debit=$TotalTaxAmount;
           	$Credit=$TotalTaxAmount;
           	//$CreditLedgerID=$CHEQUEINHAND;
        
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="Cheque Deposit";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$BankID;
           $fdetails['CostCenterID']=$GodownID;//company
           $fdetails['ChequeNo']=$ChequeNo;
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="Cheque Deposit";	
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);		  				
       
    
		
	}
	else if($StatusID=="664")
	{
		//Hold Cheque in case of Return Cheque 
		//CHEQUE IN HAND DEBIT 
		//BANK CREDIT 

    	$CHEQUEINHAND=299;
    	$InvoiceDate=date("Y-m-d H:i:s");
    	$NetAmount=$Amount;
    	$TotalTaxAmount=$Amount;
    	$$ChequeNo='';
    	$ChequeDate='';
    	//get details of voucher from VoucherMaster 
    	$sql="select *,(select CreditLedgerID from VoucherDetails where VoucherID=$ChequeDetailID) as CreditLedgerID,(select LedgerID from VoucherDetails where VoucherID=$ChequeDetailID) as DebitLedgerID from VoucherMaster where VoucherID=".$ChequeDetailID;
    	$result=odbc_exec($connection,$sql);
    	while ($row=odbc_fetch_array($result)) {
    		# code...
    		$VoucherTypeID=$row['VoucherTypeID'];
    		$ReferenceInvoiceID=$row['ReferenceInvoiceID'];
    		$GodownID=$row['LocationID'];
    		$ChequeNo=$row['ChequeNo'];
    		$ChequeDate=$row['ChequeDate'];
    		$CreditLedgerID=$row['CreditLedgerID'];
    		$ClientBankAccountName=$row['ClientBankAccountName'];

    	}//end while 
    	// update the previous Voucher with Cheque Status 
 $sqlupdate="update VoucherMaster set ChequeTypeStatus=$StatusID  where VoucherID=".$ChequeDetailID;
 odbc_exec($connection, $sqlupdate);

    	$VoucherTypeID=7;
    	$AmountDebit=0;
    	$AmountCredit=0;
    	$ReferenceVoucherID=0;
    	$GroupID=0;
    	$InvoiceType=0;
    	$PaymentType='';
    	$fields=array();
       	$VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$connection)+1;//getmaxId("VoucherMaster","VoucherID",$connection)+1;
    	$KeyField="";
      	if($VoucherTypeID==5)
       	{
       		$VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=5",$connection)+1;
       		$VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
       		$VoucherNo="RV-".$VoucherNo;
       	}
       	if($VoucherTypeID==6)
       	{
       		$VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=6",$connection)+1;
       		$VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
       		$VoucherNo="PV-".$VoucherNo;
       	}
       	if($VoucherTypeID==7)
       	{
       		$VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=7",$connection)+1;
       		$VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
       		$VoucherNo="JV-".$VoucherNo;
       	}



    	   $fields['VoucherID']=$VoucherID;
           $fields['VoucherNo']=$VoucherNo;//isset($VoucherNo)?$VoucherNo:0;
           $fields['TotalAmount']=isset($NetAmount)?$NetAmount:0;
           $fields['Active']=1;//isset($Active)?$Active:0;
           $fields['VoucherDate']=isset($InvoiceDate)?$InvoiceDate:null;
           $fields['Narration']=isset($Narration)?$Narration:0;
           $fields['Posted']=1;//isset($Posted)?$Posted:0;
           $fields['IsPostDated']=0;//isset($IsPostDated)?$IsPostDated:0;
           $fields['ChequeNo']=($ChequeNo!="")?$ChequeNo:0;
		$fields['ClientBankAccountName']=($ClientBankAccountName!="")?$ClientBankAccountName:0;
		   $fields['ChequeStatus']=($StatusID!="")?$StatusID:0;
		   $fields['ChequeDate']=($ChequeDate!="")?$ChequeDate:'';
		   $fields['isVoucherReturnCheque']=0;//isset($IsPostDated)?$IsPostDated:0;
           $fields['VoucherTypeID']=$VoucherTypeID;//isset($VoucherTypeID)?$VoucherTypeID:0;
           $fields['PeriodID']=1;//isset($PeriodID)?$PeriodID:0;
           $fields['ReferenceInvoiceID']=isset($ReferenceInvoiceID)?$ReferenceInvoiceID:0;
           $fields['SupplierID']=0;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($SupplierID)?$SupplierID:0;
           $fields['AmountDebit']=isset($AmountDebit)?$AmountDebit:0;
           $fields['AmountCredit']=isset($AmountCredit)?$AmountCredit:0;
           $fields['IsAuto']=1;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['ReferenceVoucherID']=isset($ChequeDetailID)?$ChequeDetailID:0;
           $fields['GroupID']=isset($GroupID)?$GroupID:0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=0;//isset($Cash)?$Cash:0;
		   $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['UserID']=isset($_SESSION['UserID'])?$_SESSION['UserID']:0;
           $fields['VoucherDateTime']=isset($VoucherDateTime)?$VoucherDateTime:date("Y-m-d m:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'';
         //  print_r($fields);
       		InsertVoucherMaster($fields,$InvoiceType,$InvoiceID,$connection);	
       		// insert voucher details 
       		       	$fdetails=array();	
       
       	   $fdetails['VoucherID']=$VoucherID;
           $fdetails['LedgerID']=$CHEQUEINHAND;//$d->CustomerLedgerID; DEbit side entry
           	$Debit=$TotalTaxAmount;
           	$Credit=$TotalTaxAmount;
           	$CreditLedgerID=$CHEQUEINHAND;
        
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="Cheque Deposit";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$BankID;
           $fdetails['CostCenterID']=$GodownID;//company
           $fdetails['ChequeNo']=$ChequeNo;
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="Cheque Deposit";	
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);		  				

	}	

			//."<Br>";
    }//end for loop
	//  $res=array('status'=>"ok",'description'=>'Record Save Sucessfully');
		   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');

}
    echo json_encode($res);	
	
	}//end if insert
		//check if the cheque is approved then insert voucher 

		//else only update the status of cheque 

		//if($statusid==1)

	
	if($_GET['action']=="GetCP_ChequeList")
	{
		$data=array();
		if(isset($_GET['ClientBankAccountName']) && $_GET['ClientBankAccountName']>0)
		{
			$ClientBankAccountName=" ClientBankAccountName like '%".$_GET['ClientBankAccountName']."%' and ";
		}
		else
		{
			$ClientBankAccountName="";
		}	
			
	if((isset($_GET['VoucherDate']) && $_GET['VoucherDate']!="") )
		{
			$date="VoucherDate = '".$_GET['VoucherDate']."' and";
		}
		else
		{
			$date='';
		}
		if((isset($_GET['ChequeDate']) && $_GET['ChequeDate']!="") )
		{
			$ChequeDate="ChequeDate = '".$_GET['ChequeDate']."' and";
		}
		else
		{
			$ChequeDate='';
		}

		if(isset($_GET['ChequeNo']) && $_GET['ChequeNo']>0)
		{
			$ChequeNo=" ChequeNo like '%".$_GET['ChequeNo']."% and ";
		}
		else
		{
			$ChequeNo="";
		}
		if(isset($_GET['Narration']) && $_GET['Narration']>0)
		{
			$Narration=" Narration like '%".$_GET['Narration']."% and ";
		}
		else
		{
			$Narration="";
		}
		if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']>0)
		{
			$VoucherNo=" VoucherNo like '%".$_GET['VoucherNo']."% and ";
		}
		else
		{
			$VoucherNo="";
		}	
		
		if(isset($_GET['ChequeTypeStatus']) && $_GET['ChequeTypeStatus']!="")
		{
			$ChequeTypeStatus=" ChequeTypeStatus=".$_GET['ChequeTypeStatus']." and ";
		}
		else
		{
			$ChequeTypeStatus="";
		}

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

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

		if(isset($_GET['LedgerID']) && $_GET['LedgerID']>0)
		{
			$COAID=" COAID=".$_GET['LedgerID']." and ";
			//$COAID="  LedgerID=".$_GET['COAID']." and ";
		}
		else
		{
			$COAID="";
		}	
$searchbox="".$date."".$LocationID."".$COAID."".$ChequeTypeStatus."".$VoucherNo."".$ClientBankAccountName."".$Narration.$TotalAmount.$ChequeDate;
		$sql="select row_number() over (order by vm.VoucherID) as row_num,vm.voucherid as VoucherID,VoucherDate,vd.Narration as Narration,VoucherNo,totalamount,vm.ChequeNo,pono,vm.dd as ddno,vm.tc as  tcno,
vm.ClientBankAccountName as clientbankname,vm.LocationID as LocationID,isauto,referencevoucherid,vd.LedgerID as COAID,mv.MasterValue as ChequeStatus,
acc.Coaname as VendorName ,vd.ReferenceInvoiceID as InvoiceID,vm.voucherid as ChequeDetailID,
ChequeDate,Debit as TotalChequeAmount,Credit as Balance,TransactionType,g.AdditionalInfo1 as CostCenter
 from vouchermaster as vm 
inner join godowns as g on g.GodownID=vm.LocationID
inner join VoucherDetails as vd on vd.VoucherID=vm.VoucherID
inner join accounts as acc on acc.COAID=vd.CreditLedgerID
left outer join master_values as mv on mv.MasterValueID=vm.ChequeTypeStatus
 where vouchertypeID in(5,6,7) and  vd.LedgerID=299";
 		$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{

		$data[]=$row;	
		}
	echo json_encode($data);

	}
	if($_GET['action']=="getChequeList")
	{
					$data=array();	
		//	$VoucherTypeID=$_GET['VoucherTypeID'];

		if(isset($_GET['ClientBankAccountName']) && $_GET['ClientBankAccountName']>0)
		{
			$ClientBankAccountName=" ClientBankAccountName like '%".$_GET['ClientBankAccountName']."%' and ";
		}
		else
		{
			$ClientBankAccountName="";
		}	
			
	if((isset($_GET['VoucherDate']) && $_GET['VoucherDate']!="") )
		{
			$date="VoucherDate = '".$_GET['VoucherDate']."' and";
		}
		else
		{
			$date='';
		}
		if((isset($_GET['ChequeDate']) && $_GET['ChequeDate']!="") )
		{
			$ChequeDate="ChequeDate = '".$_GET['ChequeDate']."' and";
		}
		else
		{
			$ChequeDate='';
		}

		if(isset($_GET['ChequeNo']) && $_GET['ChequeNo']>0)
		{
			$ChequeNo=" ChequeNo like '%".$_GET['ChequeNo']."% and ";
		}
		else
		{
			$ChequeNo="";
		}
		if(isset($_GET['Narration']) && $_GET['Narration']>0)
		{
			$Narration=" Narration like '%".$_GET['Narration']."% and ";
		}
		else
		{
			$Narration="";
		}
		if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']>0)
		{
			$VoucherNo=" VoucherNo like '%".$_GET['VoucherNo']."% and ";
		}
		else
		{
			$VoucherNo="";
		}	
		
		if(isset($_GET['ChequeTypeStatus']) && $_GET['ChequeTypeStatus']!="")
		{
			$ChequeTypeStatus=" ChequeTypeStatus=".$_GET['ChequeTypeStatus']." and ";
		}
		else
		{
			$ChequeTypeStatus="";
		}

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

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

		if(isset($_GET['LedgerID']) && $_GET['LedgerID']>0)
		{
			$COAID=" COAID=".$_GET['LedgerID']." and ";
			//$COAID="  LedgerID=".$_GET['COAID']." and ";
		}
		else
		{
			$COAID="";
		}		
		$searchbox="".$date."".$LocationID."".$COAID."".$ChequeTypeStatus."".$VoucherNo."".$ClientBankAccountName."".$Narration.$TotalAmount.$ChequeDate;
		$data=array();
	//	$VoucherID=$_GET['VoucherID'];
		$sql="select voucherid,VoucherDate,Narration,VoucherNo,totalamount,ChequeNo,pono,ddno, tcno, clientbankname,LocationID,isauto,referencevoucherid,ChequeDate,Debit,Credit,TransactionType,g.AdditionalInfo1 as CostCenter
			from generalledger 
			inner join godowns as g on g.GodownID=generalledger.LocationID
			where $searchbox 1=1";
		$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{

		$data[]=$row;	
		}
	echo json_encode($data);
	}

  if($_GET['action']=="BalanceSheet3")
  {
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date="   VoucherDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
    
    }
    else
    {
      $date='';
      $openingDebit="0";
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID="  LocationID=".$_GET['LocationID']." and ";
    }
    else
    {
      $LocationID="";
    }
    if(isset($_GET['Degree']) && $_GET['Degree']!="undefined" && $_GET['Degree']!="" && $_GET['Degree']>0)
    {
      $Degree="".$_GET['Degree'];
    }
    else
    {
      $Degree="2";
    }
    if(isset($_GET['COAID']) && ($_GET['COAID']!="undefined" && $_GET['COAID']!=""))
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $COAID=" COAID like '".$_GET['COAID']."' and ";
      $COAID2=" GLCode like '".$_GET['COAID']."%' and ";
    }
    else
    {
      $COAID="";
      $COAID2="";
    }

        $searchbox=$date.$LocationID;

    $sql="
select sum(debit)-Sum(Credit) as Balance,LedgerName,GLCode,groupcode2,GroupName2,groupcode1,GroupName1,GroupName,Nature,NatureCode,COAID from [vw_BalanceSheet] 
where $searchbox   NatureCode not in('5','4')
group by nature,naturecode,groupname,groupname1,groupcode1,groupcode2,groupname2,
ledgername,GLcode,COAID";
   $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {

      foreach($row as $key=>$value)
      { 
        if($value=="0.00")$value=0;
      $row[$key]= utf8_encode($value);  
      }

    $data[]=$row; 
    }
  //  print_r($data);
    echo json_encode($data); 

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

      $data=array();  
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" and  VoucherDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' ";
    
    }
    else
    {
      $date='';
      $openingDebit="0";
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID=" and LocationID=".$_GET['LocationID']."  ";
    }
    else
    {
      $LocationID="";
    }
    if(isset($_GET['Degree']) && $_GET['Degree']!="undefined" && $_GET['Degree']!="" && $_GET['Degree']>0)
    {
      $Degree="".$_GET['Degree'];
    }
    else
    {
      $Degree="2";
    }
    if(isset($_GET['COAID']) && ($_GET['COAID']!="undefined" && $_GET['COAID']!=""))
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $COAID=" COAID like '".$_GET['COAID']."' and";
      $COAID2=" GLCode like '".$_GET['COAID']."%' and ";
    }
    else
    {
      $COAID="";
      $COAID2="";
    }
    $sql="select PLS.*,(PLS.Debit1-PLS.Credit1) as Balance1 from (
  select COAName,COAID,GLCode,Degree,(select GLCode from accounts as  ac where ac.COAID=accounts.under) as ParentCode,0 as OpDebit,0 as OPCredit,
(select ISNULL(sum(Debit),0)  from generalledger where ((ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and degree=5) and 
(accounts.Degree=$Degree or accounts.Degree=1)  $date $LocationID)  as Debit1,
(select ISNULL(sum(Credit),0)  from generalledger where ((ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and degree=5) and
 (accounts.Degree=$Degree or accounts.Degree=1)  $date $LocationID ) as Credit1

       from accounts where GLCode like '1%' 
union
  select COAName,COAID,GLCode,Degree,(select GLCode from accounts as  ac where ac.COAID=accounts.under) as ParentCode,0 as OpDebit,0 as OPCredit,
(select ISNULL(sum(Debit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1) 
$LocationID)  as Debit1,
(select ISNULL(sum(Credit),0) as Credit from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and 
(accounts.Degree=$Degree or accounts.Degree=1 ) $LocationID) as Credit1
  from accounts where GLCode like '2%' 
union
  select COAName,COAID,GLCode,Degree,(select GLCode from accounts as  ac where ac.COAID=accounts.under) as ParentCode,0 as OpDebit,0 as OPCredit,
(select ISNULL(sum(Debit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1) $LocationID)  as Debit1,
(select ISNULL(sum(Credit),0) as Credit from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1 ) $LocationID) as Credit1
  from accounts where GLCode like '3%' )
 as PLS
     where degree<=$Degree
     order by GLCode";
     $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {

      foreach($row as $key=>$value)
      { 
        if($value=="0.00")$value=0;
      $row[$key]= utf8_encode($value);  
      }

    $data[]=$row; 
    }
  //  print_r($data);
    echo json_encode($data); 
  
  }
	if($_GET['action']=="BalanceSheet")
	{
			$data=array();	
		if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
		{
			$date=" VoucherDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
		
		}
		else
		{
			$date='';
			$openingDebit="0";
		}	
		if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
		{
			$LocationID=" and LocationID=".$_GET['LocationID']."  ";
		}
		else
		{
			$LocationID="";
		}
		if(isset($_GET['Degree']) && $_GET['Degree']!="undefined" && $_GET['Degree']!="" && $_GET['Degree']>0)
		{
			$Degree="".$_GET['Degree'];
		}
		else
		{
			$Degree="2";
		}
		if(isset($_GET['COAID']) && ($_GET['COAID']!="undefined" && $_GET['COAID']!=""))
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$COAID=" COAID like '".$_GET['COAID']."' and";
			$COAID2=" GLCode like '".$_GET['COAID']."%' and ";
		}
		else
		{
			$COAID="";
			$COAID2="";
		}
		$sql="select PLS.*,(PLS.Debit1-PLS.Credit1) as Balance1,(PLS.Debit2-PLS.Credit2) as Balance2,(PLS.Debit3-PLS.Credit3) as Balance3,(PLS.Debit4-PLS.Credit4) as Balance4 from (
	select COAName,COAID,GLCode,Degree,(select GLCode from accounts as  ac where ac.COAID=accounts.under) as ParentCode,0 as OpDebit,0 as OPCredit,
(select ISNULL(sum(Debit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode ) and (accounts.Degree=$Degree or accounts.Degree=1) and $date LocationID=1)  as Debit1,
(select ISNULL(sum(Credit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode ) and (accounts.Degree=$Degree or accounts.Degree=1) and $date LocationID=1 ) as Credit1,
(select ISNULL(sum(Debit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode ) and (accounts.Degree=$Degree or accounts.Degree=1) and $date LocationID=2)  as Debit2,
(select ISNULL(sum(Credit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode ) and (accounts.Degree=$Degree or accounts.Degree=1) and $date LocationID=2 ) as Credit2,
(select ISNULL(sum(Debit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode ) and (accounts.Degree=$Degree or accounts.Degree=1) and $date LocationID=3)  as Debit3,
(select ISNULL(sum(Credit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode ) and (accounts.Degree=$Degree or accounts.Degree=1) and $date LocationID=3 ) as Credit3,
(select ISNULL(sum(Debit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode ) and (accounts.Degree=$Degree or accounts.Degree=1) and $date LocationID=4)  as Debit4,
(select ISNULL(sum(Credit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode ) and (accounts.Degree=$Degree or accounts.Degree=1) and $date LocationID=4 ) as Credit4
	     from accounts where GLCode like '1%' 
union
	select COAName,COAID,GLCode,Degree,(select GLCode from accounts as  ac where ac.COAID=accounts.under) as ParentCode,0 as OpDebit,0 as OPCredit,
(select ISNULL(sum(Debit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1) and LocationID=1)  as Debit1,
(select ISNULL(sum(Credit),0) as Credit from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1 ) and LocationID=1) as Credit1,
(select ISNULL(sum(Debit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1) and LocationID=2)  as Debit2,
(select ISNULL(sum(Credit),0) as Credit from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1 ) and LocationID=2) as Credit2,
(select ISNULL(sum(Debit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1) and LocationID=3)  as Debit3,
(select ISNULL(sum(Credit),0) as Credit from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1 ) and LocationID=3) as Credit3,
(select ISNULL(sum(Debit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1) and LocationID=4)  as Debit4,
(select ISNULL(sum(Credit),0) as Credit from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1 ) and LocationID=4) as Credit4
  from accounts where GLCode like '2%' 
union
	select COAName,COAID,GLCode,Degree,(select GLCode from accounts as  ac where ac.COAID=accounts.under) as ParentCode,0 as OpDebit,0 as OPCredit,
(select ISNULL(sum(Debit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1) and LocationID=1)  as Debit1,
(select ISNULL(sum(Credit),0) as Credit from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1 ) and LocationID=1) as Credit1,
(select ISNULL(sum(Debit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1) and LocationID=2)  as Debit2,
(select ISNULL(sum(Credit),0) as Credit from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1 ) and LocationID=2) as Credit2,
(select ISNULL(sum(Debit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1) and LocationID=3)  as Debit3,
(select ISNULL(sum(Credit),0) as Credit from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1 ) and LocationID=3) as Credit3,
(select ISNULL(sum(Debit),0)  from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1) and LocationID=4)  as Debit4,
(select ISNULL(sum(Credit),0) as Credit from generalledger where (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1 ) and LocationID=4) as Credit4
  from accounts where GLCode like '3%' )
 as PLS
	   where degree<=$Degree
	   order by GLCode";
	   $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
		while($row=odbc_fetch_array($result))
		{

			foreach($row as $key=>$value)
			{	
				if($value=="0.00")$value=0;
			$row[$key]= utf8_encode($value);	
			}

		$data[]=$row;	
		}
	//	print_r($data);
		echo json_encode($data); 
	}
	if($_GET['action']=="ProfitLoss")
	{
		$data=array();	
		if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
		{
			$date=" VoucherDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
		
		}
		else
		{
			$date='';
			$openingDebit="0";
		}	
		if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
		{
			$LocationID="  CostCenterID=".$_GET['LocationID']." and ";
		}
		else
		{
			$LocationID="";
		}
		if(isset($_GET['Degree']) && $_GET['Degree']!="undefined" && $_GET['Degree']!="" && $_GET['Degree']>0)
		{
			$Degree="".$_GET['Degree'];
		}
		else
		{
			$Degree="2";
		}
		if(isset($_GET['COAID']) && ($_GET['COAID']!="undefined" && $_GET['COAID']!=""))
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$COAID=" COAID like '".$_GET['COAID']."' and";
			$COAID2=" GLCode like '".$_GET['COAID']."%' and ";
		}
		else
		{
			$COAID="";
			$COAID2="";
		}	
    $searchbox=$COAID2.$LocationID;
		/* $sql="select PLS.*,(PLS.Credit-PLS.Debit) as Balance from (
	select COAName,COAID,GLCode,Degree,(select GLCode from accounts as  ac where ac.COAID=accounts.under) as ParentCode,0 as OpDebit,0 as OPCredit,
	(select sum(Debit)  from generalledger where $date (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode ) and (accounts.Degree=$Degree or accounts.Degree=1) $LocationID)  as Debit,(select sum(Credit) as Credit from generalledger 
	   where $date (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode ) and (accounts.Degree=$Degree or accounts.Degree=1) $LocationID ) as Credit  from accounts where GLCode like '4%' 
union
	select COAName,COAID,GLCode,Degree,(select GLCode from accounts as  ac where ac.COAID=accounts.under) as ParentCode,0 as OpDebit,0 as OPCredit,
	(select sum(Debit)  from generalledger where $date (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1) $LocationID)  as Debit,(select sum(Credit) as Credit from generalledger 
where $date (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and (accounts.Degree=$Degree or accounts.Degree=1 ) $LocationID) as Credit  from accounts where GLCode like '5%' )
 as PLS
	   where degree<=$Degree
	   order by GLCode";*/
     $sql=" select GLCode,COAID,COAName,ParentCode,ParentName,SUM(Debit) as Debit,SUM(credit) as Credit,(SUM(Credit)-SUM(Debit)) as Balance,5 as Degree from GeneralLedger 
     where $searchbox GLCode like '4%' group by COAID, COAName,GLCode,ParentCode,ParentName
     union
      select GLCode,COAID,COAName,ParentCode,ParentName,SUM(Debit) as Debit,SUM(credit) as Credit,(SUM(Credit)-SUM(Debit)) as Balance,5 as Degree from GeneralLedger 
     where  $searchbox GLCode like '5%'   group by COAID, COAName,GLCode,ParentCode,ParentName

     ";
	  $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);	

		$data[]=$row;	
		}
	//	print_r($data);
		echo json_encode($data); 
	}
  if($_GET['action']=="TrialBalance1")
  {

      $data=array();  
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" VoucherDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
    
    }
    else
    {
      $date='';
      $openingDebit="0";
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID=" LocationID=".$_GET['LocationID']." and ";
    }
    else
    {
      $LocationID="";
    }
        if(isset($_GET['Level']) && $_GET['Level']!="undefined" && $_GET['Level']!="" && $_GET['Level']>0)
    {
      $Level=" Accounts.Degree<=".$_GET['Level']." and ";
    }
    else
    {
      $Level="";
    }
    if(isset($_GET['COAID']) && ($_GET['COAID']!="undefined" && $_GET['COAID']!=""))
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $COAID=" Accounts.COAID like '".$_GET['COAID']."' and";
      $COAID2=" Accounts.GLCode like '".$_GET['COAID']."%' and ";
    }
    else
    {
      $COAID="";
      $COAID2="";
    } 
    //?$_GET['SupplierID']:;

  $searchboxopen=$COAID2."".$Level;
  //$searchbox=$COAID."".$LocationID."".$date;
    $searchbox=$LocationID."".$date;
/*    if($date!="")
    {
            $openingDebit="select sum(Debit)  from generalledger where $LocationID  (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and VoucherDate<'".$_GET['startdate']."'";
          $openingCredit="select sum(Credit) as Credit from generalledger 
   where   $LocationID (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and VoucherDate<'".$_GET['startdate']."' or VoucherTypeID=0";
   $opendebitdate="(select sum(trDebit) from trial2 as t3 where $LocationID voucherdate<'".$_GET['startdate']."' 
and (t3.glcode=trial2.glcode or t3.GLCode like trial2.GLCode+'.%')) ";
$opencreditdate="(select sum(trCredit) from trial2 as t3 where  $LocationID voucherdate<'".$_GET['startdate']."' 
and (t3.glcode=trial2.glcode or t3.GLCode like trial2.GLCode+'.%')) ";
    }
    else
    {
/*$opendebitdate="(select sum(trDebit) from trial2 as t3 where $LocationID (t3.glcode=trial2.glcode or t3.GLCode like trial2.GLCode+'.%')) ";
$opencreditdate="(select sum(trCredit) from trial2 as t3 where  $LocationID  
 (t3.glcode=trial2.glcode or t3.GLCode like trial2.GLCode+'.%')) ";
      */
 /*
 $opendebitdate="0";
 $opencreditdate="0";
      $opendate="";
    $openingDebit="select sum(Debit)  from generalledger where $LocationID  (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and VoucherTypeID=0";   
       
    $openingCredit="select sum(Credit) as Credit from generalledger 
   where   $LocationID (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode)  and VoucherTypeID=0";
    //  $openingDebit="0";
      //$openingCredit="0";
    }*/
/*    $sql="select COAName,COAID,GLCode,Degree,(select GLCode from accounts as  ac where ac.COAID=accounts.under) as ParentCode,($openingDebit) as OpDebit,($openingCredit) as OpCredit,
(select sum(Debit)  from generalledger where  $searchbox (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and VoucherTypeID>0 )  as Debit,(select sum(Credit) as Credit from generalledger 
   where  $searchbox (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and VoucherTypeID>0 ) as Credit,
   ((select sum(Debit)  from generalledger where   (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and VoucherTypeID>0 and Active=1 )
   -(select sum(Credit) as Credit from generalledger 
   where   (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and VoucherTypeID>0 and Active=1)) as Balance
     from accounts where $searchboxopen Active=1 order by GLCode";*/
   /*echo $sql="select COAName,COAID,GLCode,Degree,ParentCode,
isnull(sum(opDebit),0)+($opendebitdate) as OpDebit,isnull(sum(opCredit),0)+($opencreditdate) as OpCredit,sum(trDebit) as trDebit1,sum(trcredit) as trCredit1,isnull((select SUM(trDebit) from trial2 as t2 where  $searchbox (t2.GLCode like trial2.GLCode+'.%' or t2.GLCode=trial2.GLCode) ),0) as Debit,
isnull((select SUM(trCredit) from trial2 as t2 where $searchbox (t2.GLCode like trial2.GLCode+'.%' or t2.GLCode=trial2.GLCode) ),0) as Credit,'' as Balance
from trial2 where $searchboxopen  1=1 
group by COAName,COAID,GLCode,Degree,ParentCode";*/
/*$sql="SELECT (select SUM(trDebit) from trial2 as t2 
where   (t2.GLCode like Accounts.GLCode+'.%')) AS Debit1,(select SUM(trCredit) from trial2 as t2 
where   (t2.GLCode like Accounts.GLCode+'.%')) AS Credit1,Accounts.COAName,Accounts.COAID,Accounts.GLCode,Accounts.Degree,
isnull(sum(opDebit),0)+(0) as OpDebit,isnull(sum(opCredit),0)+(0) as OpCredit,
SUM(trDebit) as  Debit,SUM(trCredit) as Credit FROM trial2 

RIGHT OUTER JOIN Accounts ON ACCOUNTS.COAID=TRIAL2.COAID 
where $searchboxopen 1=1 
Group by Accounts.COAName,Accounts.COAID,Accounts.GLCode,Accounts.Degree";
*/
 $sql="select 0 as opDebit,0 as opCredit,case when sum(debit)-sum(credit)<0 then  0 else sum(debit)-sum(credit) end  as Debit,
 case when sum(debit)-sum(credit)>0 then 0 else  sum(credit)-sum(debit) end  as Credit,GLCode,GroupName2,GroupName1,GroupName,Nature,LedgerName,COAID  from vw_trialbalance where $searchbox 1=1 group by COAID,LedgerName,GLCode,GroupName2,GroupCode2,GroupName1,GroupCode1,GroupName,GroupCode,Nature";
    $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);  

    $data['details'][]=$row;  
    }
  //  print_r($data);
    echo json_encode($data);
  
  }
	if($_GET['action']=="TrialBalance")
	{
			$data=array();	
		if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
		{
			$date=" VoucherDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
		
		}
		else
		{
			$date='';
			$openingDebit="0";
		}	
		if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
		{
			$LocationID=" LocationID=".$_GET['LocationID']." and ";
		}
		else
		{
			$LocationID="";
		}
        if(isset($_GET['Level']) && $_GET['Level']!="undefined" && $_GET['Level']!="" && $_GET['Level']>0)
    {
      $Level=" Accounts.Degree<=".$_GET['Level']." and ";
    }
    else
    {
      $Level="";
    }
		if(isset($_GET['COAID']) && ($_GET['COAID']!="undefined" && $_GET['COAID']!=""))
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$COAID=" Accounts.COAID like '".$_GET['COAID']."' and";
			$COAID2=" Accounts.GLCode like '".$_GET['COAID']."%' and ";
		}
		else
		{
			$COAID="";
			$COAID2="";
		}	
		//?$_GET['SupplierID']:;

	$searchboxopen=$COAID2."".$Level;
	//$searchbox=$COAID."".$LocationID."".$date;
		$searchbox=$LocationID."".$date;
		if($date!="")
		{
						$openingDebit="select sum(Debit)  from generalledger where $LocationID  (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and VoucherDate<'".$_GET['startdate']."'";
					$openingCredit="select sum(Credit) as Credit from generalledger 
   where   $LocationID (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and VoucherDate<'".$_GET['startdate']."' or VoucherTypeID=0";
   $opendebitdate="(select sum(trDebit) from trial2 as t3 where $LocationID voucherdate<'".$_GET['startdate']."' 
and (t3.glcode=trial2.glcode or t3.GLCode like trial2.GLCode+'.%')) ";
$opencreditdate="(select sum(trCredit) from trial2 as t3 where  $LocationID voucherdate<'".$_GET['startdate']."' 
and (t3.glcode=trial2.glcode or t3.GLCode like trial2.GLCode+'.%')) ";
		}
		else
		{
/*$opendebitdate="(select sum(trDebit) from trial2 as t3 where $LocationID (t3.glcode=trial2.glcode or t3.GLCode like trial2.GLCode+'.%')) ";
$opencreditdate="(select sum(trCredit) from trial2 as t3 where  $LocationID  
 (t3.glcode=trial2.glcode or t3.GLCode like trial2.GLCode+'.%')) ";
      */
 $opendebitdate="0";
 $opencreditdate="0";
      $opendate="";
    $openingDebit="select sum(Debit)  from generalledger where $LocationID  (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and VoucherTypeID=0";   
       
		$openingCredit="select sum(Credit) as Credit from generalledger 
   where   $LocationID (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode)  and VoucherTypeID=0";
    //	$openingDebit="0";
			//$openingCredit="0";
		}
/*	  $sql="select COAName,COAID,GLCode,Degree,(select GLCode from accounts as  ac where ac.COAID=accounts.under) as ParentCode,($openingDebit) as OpDebit,($openingCredit) as OpCredit,
(select sum(Debit)  from generalledger where  $searchbox (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and VoucherTypeID>0 )  as Debit,(select sum(Credit) as Credit from generalledger 
   where  $searchbox (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and VoucherTypeID>0 ) as Credit,
   ((select sum(Debit)  from generalledger where   (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and VoucherTypeID>0 and Active=1 )
   -(select sum(Credit) as Credit from generalledger 
   where   (ParentCode like accounts.GLCode+'%' or GLcode=accounts.GLCode) and VoucherTypeID>0 and Active=1)) as Balance
     from accounts where $searchboxopen Active=1 order by GLCode";*/
   /*echo $sql="select COAName,COAID,GLCode,Degree,ParentCode,
isnull(sum(opDebit),0)+($opendebitdate) as OpDebit,isnull(sum(opCredit),0)+($opencreditdate) as OpCredit,sum(trDebit) as trDebit1,sum(trcredit) as trCredit1,isnull((select SUM(trDebit) from trial2 as t2 where  $searchbox (t2.GLCode like trial2.GLCode+'.%' or t2.GLCode=trial2.GLCode) ),0) as Debit,
isnull((select SUM(trCredit) from trial2 as t2 where $searchbox (t2.GLCode like trial2.GLCode+'.%' or t2.GLCode=trial2.GLCode) ),0) as Credit,'' as Balance
from trial2 where $searchboxopen  1=1 
group by COAName,COAID,GLCode,Degree,ParentCode";*/

$sql="SELECT (select SUM(trDebit) from trial2 as t2 where   (t2.GLCode like Accounts.GLCode+"."'.%')) AS Debit1,(select SUM(trCredit) from trial2 as t2 
where   (t2.GLCode like Accounts.GLCode+'.%')) AS Credit1,Accounts.COAName,Accounts.COAID,Accounts.GLCode,Accounts.Degree,
isnull(sum(opDebit),0)+(0) as OpDebit,isnull(sum(opCredit),0)+(0) as OpCredit,
SUM(trDebit) as  Debit,SUM(trCredit) as Credit FROM trial2 

RIGHT OUTER JOIN Accounts ON ACCOUNTS.COAID=TRIAL2.COAID 
where $searchboxopen 1=1 
Group by Accounts.COAName,Accounts.COAID,Accounts.GLCode,Accounts.Degree";

   	$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);	

		$data['details'][]=$row;	
		}
	//	print_r($data);
		echo json_encode($data);
  	}
  if($_GET['action']=="CardWiseStatement")
  {

    $data=array();
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" convert(date,Tdate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
      
    }
    else
    {
      $date='';
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID=" LocationID=".$_GET['LocationID']." and ";
    }
    else
    {
      $LocationID="";
    }
    if(isset($_GET['COAID']) && $_GET['COAID']!="undefined" && $_GET['COAID']!="")
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $COAID=" COAID=".$_GET['COAID']." and";
    }
    else
    {
      $COAID="";
    } 
    //?$_GET['SupplierID']:;
  $searchboxopen=$COAID."".$LocationID;
  $searchbox=$COAID."".$LocationID."".$date;
  //$_GET['startdate']="2020-02-01";
    if($_GET['startdate']!="" && $_GET['startdate']!="undefined")
    {

      $sqlopening ="select sum(Debit) as Debit,sum(Credit) as Credit,COAID,(sum(Debit)-sum(Credit)) as balance from  
CardTransaction where $COAID  tdate<'".$_GET['startdate']."'
group by COAID

      ";
     $resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
    while($rowopening=odbc_fetch_array($resultopening))
    {
      $rowopening['Narration']='Opening Balance';
      $data['opening']=$rowopening;
    }

   /*  $sqlopening ="select sum(Debit) as Debit,sum(Credit) as Credit,COAID,(sum(Debit)-sum(Credit)) as balance from  generalledger where $searchboxopen  VoucherDate<'".$_GET['startdate']."'  group by COAID";
     $resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
    while($rowopening=odbc_fetch_array($resultopening))
    {
      $rowopening['Narration']='Opening Balance';
      $data['opening']=$rowopening;
    }
*/
    }//end opening
    else
    {
$sqlopening ="select sum(Debit) as Debit,(sum(Credit)*-1) as Credit,LedgerID,(sum(Debit)-(sum(Credit)*-1)) as balance from  voucherdetails where LedgerID=".$_GET['COAID']." and VoucherID in (select VoucherID from vouchermaster where VoucherTypeID=0)  group by LedgerID
      ";
     $resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
    while($rowopening=odbc_fetch_array($resultopening))
    {
      $rowopening['Narration']='Opening Balance ';
      $data['opening']=$rowopening;
    }      
     
    }

       $sql="select ROW_NUMBER() OVER (ORDER BY [ID])  as row_num,convert(date,tdate) as VoucherDate1,(select COAName from accounts where COAID=generalledger.COAID) as creditaccount,(select COAName from accounts where COAID=generalledger.COAID) as debitaccount,(select Name from inventory where ID=(select top 1 ItemID from InvoiceDetail where InvoiceID=generalledger.InvoiceID)) as ItemName,* from CardTransaction as generalledger  where $searchbox ID>0";
    $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);  
   /* if($row['CardNumber']!="")
    $row['CardNumber']=getCardCodeDecode($row['CardNumber']);*/
  
    $data['details'][]=$row;  
    }
  //  print_r($data);
    echo json_encode($data);
  
  }
  if($_GET['action']=="CustomerLedgerStatement")
  {

    $data=array();
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" convert(date,VoucherDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
      
    }
    else
    {
      $date='';
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID=" LocationID=".$_GET['LocationID']." and ";
    }
    else
    {
      $LocationID="";
    }
    if(isset($_GET['COAID']) && $_GET['COAID']!="undefined" && $_GET['COAID']!="")
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $COAID=" COAID=".$_GET['COAID']." and";
    }
    else
    {
      $COAID="";
    } 
    //?$_GET['SupplierID']:;
  $searchboxopen=$COAID."".$LocationID;
  $searchbox=$COAID."".$LocationID."".$date;
  //$_GET['startdate']="2020-02-01";
    if($_GET['startdate']!="" && $_GET['startdate']!="undefined")
    {

      $sqlopening ="select sum(Debit) as Debit,sum(Credit) as Credit,COAID,(sum(Debit)-sum(Credit)) as balance from  generalledger where $searchboxopen   VoucherTypeID=0 group by COAID
union
select sum(Debit) as Debit,sum(Credit) as Credit,COAID,(sum(Debit)-sum(Credit)) as balance from  
generalledger where $searchbox  VoucherDate<'".$_GET['startdate']."'
group by COAID

      ";
     $resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
    while($rowopening=odbc_fetch_array($resultopening))
    {
      $rowopening['Narration']='Opening Balance';
      $data['opening']=$rowopening;
    }

   /*  $sqlopening ="select sum(Debit) as Debit,sum(Credit) as Credit,COAID,(sum(Debit)-sum(Credit)) as balance from  generalledger where $searchboxopen  VoucherDate<'".$_GET['startdate']."'  group by COAID";
     $resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
    while($rowopening=odbc_fetch_array($resultopening))
    {
      $rowopening['Narration']='Opening Balance';
      $data['opening']=$rowopening;
    }
*/
    }//end opening
    else
    {
$sqlopening ="select sum(Debit) as Debit,(sum(Credit)*-1) as Credit,LedgerID,(sum(Debit)-(sum(Credit)*-1)) as balance from  voucherdetails where LedgerID=".$_GET['COAID']." and VoucherID in (select VoucherID from vouchermaster where VoucherTypeID=0)  group by LedgerID
      ";
     $resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
    while($rowopening=odbc_fetch_array($resultopening))
    {
      $rowopening['Narration']='Opening Balance ';
      $data['opening']=$rowopening;
    }      
     
    }

       $sql="select 
convert(date,VoucherDate) as VoucherDate1,
(select COAName from accounts where COAID=generalledger.COAID) as debitaccount,VoucherID,VoucherDate,COAID,sum(debit) as Debit,sum(credit) as Credit,Narration,VoucherNo,(select AdditionalInfo1 from godowns where godownid=LocationID)  as CostCenter from generalledger  where $searchbox VoucherTypeID>0
group by VoucherID,VoucherDate,COAID,Narration,VoucherNo,LocationID";
    $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);  

    $data['details'][]=$row;  
    }
  //  print_r($data);
    echo json_encode($data);
  
  }
  if($_GET['action']=="LedgerWiseStatement2")
  {

    $data=array();
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" convert(date,VoucherDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
      
    }
    else
    {
      $date='';
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      //$LocationID=" LocationID=".$_GET['LocationID']." and ";
      $LocationID=" (DebitCostCenterID=".$_GET['LocationID']." or CostCenterID=".$_GET['LocationID'].") and ";
    }
    else
    {
      $LocationID="";
    }
    if(isset($_GET['COAID']) && $_GET['COAID']!="undefined" && $_GET['COAID']!="")
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $COAID=" COAID=".$_GET['COAID']." and";
    }
    else
    {
      $COAID="";
    } 
    //?$_GET['SupplierID']:;
  $searchboxopen=$COAID."".$LocationID;
  $searchbox=$COAID."".$LocationID."".$date;
  //$_GET['startdate']="2020-02-01";
    if($_GET['startdate']!="" && $_GET['startdate']!="undefined")
    {

       $sqlopening ="select sum(Debit) as Debit,sum(Credit) as Credit,COAID,(sum(Debit)-sum(Credit)) as balance from  generalledger where $searchboxopen   VoucherTypeID=0 group by COAID
union
select sum(Debit) as Debit,sum(Credit) as Credit,COAID,(sum(Debit)-sum(Credit)) as balance from  
generalledger where $searchboxopen  VoucherDate<'".$_GET['startdate']."'
group by COAID

      ";
     $resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
    while($rowopening=odbc_fetch_array($resultopening))
    {
      $rowopening['Narration']='Opening Balance';
      $data['opening']=$rowopening;
    }

   /*  $sqlopening ="select sum(Debit) as Debit,sum(Credit) as Credit,COAID,(sum(Debit)-sum(Credit)) as balance from  generalledger where $searchboxopen  VoucherDate<'".$_GET['startdate']."'  group by COAID";
     $resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
    while($rowopening=odbc_fetch_array($resultopening))
    {
      $rowopening['Narration']='Opening Balance';
      $data['opening']=$rowopening;
    }
*/
    }//end opening
    else
    {
$sqlopening ="select sum(Debit) as Debit,(sum(Credit)*-1) as Credit,LedgerID,(sum(Debit)-(sum(Credit)*-1)) as balance from  voucherdetails where LedgerID=".$_GET['COAID']." and VoucherID in (select VoucherID from vouchermaster where VoucherTypeID=0)  group by LedgerID
      ";
     $resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
    while($rowopening=odbc_fetch_array($resultopening))
    {
      $rowopening['Narration']='Opening Balance ';
      $data['opening']=$rowopening;
    }      
     
    }

$limit=1000;
  $sqlcount="select count(*) as totalrecord from generalledger  where  $searchbox   VoucherTypeID>0";
$resultcount=odbc_exec($connection, $sqlcount) or die(odbc_error().$sqlcount);
    while($rowcount=odbc_fetch_array($resultcount))
    {
      $totalrecord=$rowcount['totalrecord'];
      $totalpage=ceil($totalrecord/$limit);
      $data['nav']['totalpage']=$totalpage;
      $data['nav']['totalrecord']=$totalrecord;
    }
    $offset=0;
    
      if(isset($_GET['page']) && $_GET['page']!="" && $_GET['page']!="undefined")
      {
        $page=(intval($_GET['page']-1));
      }
      else
      {
        $page=0;
      }
$offset=$page*$limit;
$limit1=$offset+$limit;
$offset=$offset+1;
 $data['nav']['CurrentPage']=($page+1);
 $data['nav']['PreviousPage']=($page-1);

if($page>0)
{
 $sqlopening="select sum(Debit) as Debit,(sum(Credit)*-1) as Credit,sum(debit)-sum(credit) as balance from (select ROW_NUMBER() OVER (ORDER BY [VoucherID])  as row_num,* from generalledger  where  $searchbox   VoucherTypeID>0) generalledger
where  row_num <$offset ";
if(!isset($data['opening']['balance']))$data['opening']['balance']=0;
$resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
    while($rowopening=odbc_fetch_array($resultopening))
    {
      $rowopening['Narration']='Opening Balance ';
      $data['opening']['balance']=$data['opening']['balance']+$rowopening['balance'];
      //$data['opening']['Debit']=$data['opening']['Debit']+$rowopening['Debit'];
     // $data['opening']['Credit']=$data['opening']['Credit']+$rowopening['Credit'];
      $data['opening']['Debit']='';
      $data['opening']['Credit']='';

    }
}
$sql="select * from (select ROW_NUMBER() OVER (ORDER BY [VoucherID])  as row_num,convert(date,VoucherDate,105) as VoucherDate1,
(select top 1 ('CH#: '+Chassisnumber+' - PL#: '+PlateNumber+' Trans # :'+ParkingNo+(select top 1 (select name from inventory where id=ItemID) from InvoiceDetail where InvoiceID=InvoiceMaster.invoiceid)) from
 InvoiceMaster where InvoiceID=generalledger.ReferenceInvoiceID) as InvoiceInfo,(select COAName from accounts where COAID=generalledger.CreditLedgerID) as creditaccount,(select COAName from accounts where COAID=generalledger.LedgerID) as debitaccount,* from generalledger  where  $searchbox   VoucherTypeID>0) generalledger
where  row_num between $offset and $limit1   order by VoucherDate";
/*        $sql="select ROW_NUMBER() OVER (ORDER BY [VoucherID])  as row_num,convert(date,VoucherDate,105) as VoucherDate1,(select top 1 ('CH#: '+Chassisnumber+' - PL#: '+PlateNumber+' Trans # :'+ParkingNo+(select top 1 (select name from inventory where id=ItemID) from InvoiceDetail where InvoiceID=InvoiceMaster.invoiceid)) from InvoiceMaster where InvoiceID=generalledger.ReferenceInvoiceID) as InvoiceInfo,(select COAName from accounts where COAID=generalledger.CreditLedgerID) as creditaccount,(select COAName from accounts where COAID=generalledger.LedgerID) as debitaccount,* from generalledger  where $searchbox VoucherTypeID>0  order by VoucherDate OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY ";*/
    $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
   //print_r(odbc_fetch_array($result));

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

      foreach($row as $key=>$value)
      {
        $row['Narration']=urldecode($row['Narration']);
      
      $row[$key]= utf8_encode($value);  
        }
    $data['details'][]=$row;  
    }
    $sql="select sum(debit) as TotalDebit,sum(credit) as TotalCredit,(sum(debit)-sum(credit)) TotalBalance from generalledger where $searchbox   VoucherTypeID>=0";
     $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
   //print_r(odbc_fetch_array($result));

    while($row=odbc_fetch_array($result))
    {
            foreach($row as $key=>$value)
      {
        
      
      $row[$key]= utf8_encode($value);  
        }
      $data['total']=$row;

    }    
  //  print_r($data);
    echo json_encode($data);
  
  }
  if($_GET['action']=="VATWiseStatement")
  {

    $data=array();
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" convert(date,VoucherDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
      
    }
    else
    {
      $date='';
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID=" LocationID=".$_GET['LocationID']." and ";
    }
    else
    {
      $LocationID="";
    }
    if(isset($_GET['COAID']) && $_GET['COAID']!="undefined" && $_GET['COAID']!="")
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $COAID=" COAID=".$_GET['COAID']." and";
    }
    else
    {
      $COAID="";
    } 
    //?$_GET['SupplierID']:;
  $searchboxopen=$COAID."".$LocationID;
  $searchbox=$COAID."".$LocationID."".$date;
  //$_GET['startdate']="2020-02-01";
    if($_GET['startdate']!="" && $_GET['startdate']!="undefined")
    {

      $sqlopening ="select sum(Debit) as Debit,sum(Credit) as Credit,COAID,(sum(Debit)-sum(Credit)) as balance from  generalledger where $searchboxopen   VoucherTypeID=0 group by COAID
union
select sum(Debit) as Debit,sum(Credit) as Credit,COAID,(sum(Debit)-sum(Credit)) as balance from  
generalledger where $searchbox  VoucherDate<'".$_GET['startdate']."'
group by COAID

      ";
     $resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
    while($rowopening=odbc_fetch_array($resultopening))
    {
      $rowopening['Narration']='Opening Balance';
      $data['opening']=$rowopening;
    }

   /*  $sqlopening ="select sum(Debit) as Debit,sum(Credit) as Credit,COAID,(sum(Debit)-sum(Credit)) as balance from  generalledger where $searchboxopen  VoucherDate<'".$_GET['startdate']."'  group by COAID";
     $resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
    while($rowopening=odbc_fetch_array($resultopening))
    {
      $rowopening['Narration']='Opening Balance';
      $data['opening']=$rowopening;
    }
*/
    }//end opening
    else
    {
$sqlopening ="select sum(Debit) as Debit,(sum(Credit)*-1) as Credit,LedgerID,(sum(Debit)-(sum(Credit)*-1)) as balance from  voucherdetails where LedgerID IN(".$_SESSION['SETTING']['VATSALES'].",".$_SESSION['SETTING']['VATPURCHASE'].") and VoucherID in (select VoucherID from vouchermaster where VoucherTypeID=0)  group by LedgerID
      ";
     $resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
    while($rowopening=odbc_fetch_array($resultopening))
    {
      $rowopening['Narration']='Opening Balance ';
      $data['opening']=$rowopening;
    }      
     
    }

       $sql="select ROW_NUMBER() OVER (ORDER BY [VoucherID])  as row_num,convert(date,VoucherDate,105) as VoucherDate1,'' as InvoiceInfo,(select COAName from accounts where COAID=VATledger.CreditLedgerID) as creditaccount,(select COAName from accounts where COAID=VATledger.LedgerID) as debitaccount,* from VATledger  where $searchbox VoucherTypeID>0 order by VoucherDate";
    $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
   
    while($row=odbc_fetch_array($result))
    {

      foreach($row as $key=>$value)
      {
        $row['Narration']=urldecode($row['Narration']);
      
      $row[$key]= utf8_encode($value);  
        }
    $data['details'][]=$row;  
    }
  //  print_r($data);
    echo json_encode($data);
   
  }
	if($_GET['action']=="LedgerWiseStatement")
	{
		$data=array();
		if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
		{
			$date=" convert(date,VoucherDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
			
		}
		else
		{
			$date='';
		}	
		if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
		{
			$LocationID=" LocationID=".$_GET['LocationID']." and ";
		}
		else
		{
			$LocationID="";
		}
		if(isset($_GET['COAID']) && $_GET['COAID']!="undefined" && $_GET['COAID']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$COAID=" COAID=".$_GET['COAID']." and";
		}
		else
		{
			$COAID="";
		}	
		//?$_GET['SupplierID']:;
	$searchboxopen=$COAID."".$LocationID;
	$searchbox=$COAID."".$LocationID."".$date;
	//$_GET['startdate']="2020-02-01";
		if($_GET['startdate']!="" && $_GET['startdate']!="undefined")
		{

		  $sqlopening ="select sum(Debit) as Debit,sum(Credit) as Credit,COAID,(sum(Debit)-sum(Credit)) as balance from  generalledger where $searchboxopen   VoucherTypeID=0 group by COAID
union
select sum(Debit) as Debit,sum(Credit) as Credit,COAID,(sum(Debit)-sum(Credit)) as balance from  
generalledger where $searchbox  VoucherDate<'".$_GET['startdate']."'
group by COAID

      ";
		 $resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
		while($rowopening=odbc_fetch_array($resultopening))
		{
			$rowopening['Narration']='Opening Balance';
			$data['opening']=$rowopening;
		}

   /*  $sqlopening ="select sum(Debit) as Debit,sum(Credit) as Credit,COAID,(sum(Debit)-sum(Credit)) as balance from  generalledger where $searchboxopen  VoucherDate<'".$_GET['startdate']."'  group by COAID";
     $resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
    while($rowopening=odbc_fetch_array($resultopening))
    {
      $rowopening['Narration']='Opening Balance';
      $data['opening']=$rowopening;
    }
*/
		}//end opening
    else
    {
$sqlopening ="select sum(Debit) as Debit,(sum(Credit)*-1) as Credit,LedgerID,(sum(Debit)-(sum(Credit)*-1)) as balance from  voucherdetails where LedgerID=".$_GET['COAID']." and VoucherID in (select VoucherID from vouchermaster where VoucherTypeID=0)  group by LedgerID
      ";
     $resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
    while($rowopening=odbc_fetch_array($resultopening))
    {
      $rowopening['Narration']='Opening Balance ';
      $data['opening']=$rowopening;
    }      
		 
    }

       $sql="select ROW_NUMBER() OVER (ORDER BY [VoucherID])  as row_num,convert(date,VoucherDate,105) as VoucherDate1,'' as InvoiceInfo,(select COAName from accounts where COAID=generalledger.CreditLedgerID) as creditaccount,(select COAName from accounts where COAID=generalledger.LedgerID) as debitaccount,* from generalledger  where $searchbox VoucherTypeID>0 order by VoucherDate";
		$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
   
    while($row=odbc_fetch_array($result))
		{

			foreach($row as $key=>$value)
      {
        $row['Narration']=urldecode($row['Narration']);
      
			$row[$key]= utf8_encode($value);	
        }
		$data['details'][]=$row;	
		}
	//	print_r($data);
		echo json_encode($data);
	}
  if($_GET['action']=="receiptvouchersym")
  {
    $data=array();
 
     if(isset($_GET['InvoiceID']) && is_numeric($_GET['InvoiceID']))
    {
$InvoiceID=$_GET['InvoiceID'];
    }
    else
    {
      $InvoiceID="";
    }
    if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined")
    {
$VoucherNo="KeyField like '%".$_GET['VoucherNo']. "%' and ";
    }
    else
    {
      $VoucherNo="";
    }
    //

    if(isset($_GET['VoucherID']) && $_GET['VoucherID']!="undefined" && $_GET['VoucherID']!="")
    {
      $VoucherID=" VoucherID=".$_GET['VoucherID']." and ";
    }
    else
    {
      $VoucherID="";
    } 
    //?$_GET['SupplierID']:;
    $CashAccount=$_SESSION['SETTING']['CASHINHAND'];
    $CreditCard=$_SESSION['SETTING']['CREDITCARD'];
  $searchbox="".$InvoiceID."".$VoucherID."".$VoucherNo;
  $Cashcustomer=$_SESSION['SETTING']['CASHCUSTOMERS'];
$sql="  select   SymReceived as TotalPaid,InvoiceID,
 KeyField as SupplierName,
((select CustomerName from invoicemaster where InvoiceID=vd.InvoiceID)+' Card Number: ('+(select CardNumber from CardTransaction where  InvoiceID=vd.InvoiceID)+')') as CustomerName,(select COAID from CardTransaction where  InvoiceID=vd.InvoiceID) as CustomerID  
  ,SupplierID as LedgerID from Invoicemaster as vd where $VoucherID ReferenceInvoiceID=$InvoiceID  ";
  // in (select ReferenceInvoiceID from InvoiceMaster where InvoiceID=$InvoiceID )
//$sql="select * from list_receivable 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)
      $row[$key]= utf8_encode($value);  

    $data[]=$row; 
    }
  //  print_r($data);
    echo json_encode($data);

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




    $data=array();
 
     if(isset($_GET['InvoiceID']) && is_numeric($_GET['InvoiceID']))
    {
$InvoiceID=$_GET['InvoiceID'];
    }
    else
    {
      $InvoiceID="";
    }
    if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined")
    {
$VoucherNo="KeyField like '%".$_GET['VoucherNo']. "%' and ";
    }
    else
    {
      $VoucherNo="";
    }
    //

    if(isset($_GET['VoucherID']) && $_GET['VoucherID']!="undefined" && $_GET['VoucherID']!="")
    {
      $VoucherID=" VoucherID=".$_GET['VoucherID']." and ";
    }
    else
    {
      $VoucherID="";
    } 
    //?$_GET['SupplierID']:;
    $CashAccount=$_SESSION['SETTING']['CASHINHAND'];
    $CreditCard=$_SESSION['SETTING']['CREDITCARD'];
  $searchbox="".$InvoiceID."".$VoucherID."".$VoucherNo;
  $Cashcustomer=$_SESSION['SETTING']['CASHCUSTOMERS'];
 $sql="  select   Debit as TotalPaid,VoucherID,
 (select COAName from Accounts where COAID =vd.LedgerID) as SupplierName,
(select CustomerName from invoicemaster where InvoiceID=$InvoiceID) as CustomerName  
  ,LedgerID from VoucherDetails as vd where $VoucherID voucherid in (
 SELECT VoucherID FROM VoucherMaster where  
 ReferenceInvoiceID =$InvoiceID and VoucherTypeID=7)  and ledgerid in($CashAccount,$CreditCard)  ";
//$sql="select * from list_receivable 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)
      $row[$key]= utf8_encode($value);  

    $data[]=$row; 
    }
  //  print_r($data);
    echo json_encode($data);

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



    $data=array();
 
     if(isset($_GET['InvoiceID']) && is_numeric($_GET['InvoiceID']))
    {
$InvoiceID=$_GET['InvoiceID'];
    }
    else
    {
      $InvoiceID="";
    }
    if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined")
    {
$VoucherNo="KeyField like '%".$_GET['VoucherNo']. "%' and ";
    }
    else
    {
      $VoucherNo="";
    }
    //

    if(isset($_GET['SelectionID']) && $_GET['SelectionID']!="undefined" && $_GET['SelectionID']!="")
    {
      $SelectionID=" GodownID=".$_GET['SelectionID']." and ";
    }
    else
    {
      $SelectionID="";
    } 
    //?$_GET['SupplierID']:;
  $searchbox="".$InvoiceID."".$SelectionID."".$VoucherNo;
      /*$sql="select   VoucherID,Debit as TotalPaid,(select KeyField from invoicemaster where InvoiceID=$InvoiceID) as KeyField1,(select  VoucherDate from VoucherMaster where VoucherID =vd.Voucherid and VoucherTypeID=7) as VoucherDate,(select  CreateLog from VoucherMaster where VoucherID =vd.Voucherid and VoucherTypeID=7) as UserName,(select  VoucherNo from VoucherMaster where VoucherID =vd.Voucherid and VoucherTypeID=7) as VoucherNo,
(select KeyField from InvoiceMaster where invoiceid=(select  ReferenceInvoiceID from VoucherMaster where VoucherID =vd.Voucherid and VoucherTypeID=7)) as KeyField, 
 (select Debit from VoucherDetails as d where voucherid=vd.VoucherID and d.VoucherID=vd.VoucherID and LedgerID=90) as Cash,
 (select Debit from VoucherDetails as d where voucherid=vd.VoucherID and d.VoucherID=vd.VoucherID and LedgerID=98) as CreditCard,
 (select COAName from Accounts where COAID =vd.LedgerID) as SupplierName,
(select CustomerName from invoicemaster where InvoiceID=$InvoiceID) as CustomerName  
  ,LedgerID from VoucherDetails as vd where voucherid in (
 SELECT VoucherID FROM VoucherMaster where SelectionID=(select max(SelectionID) from VoucherMaster where VoucherTypeID=7  and 
 ReferenceInvoiceID in(select InvoiceID from invoicemaster where ReferenceInvoiceID=$InvoiceID)) and ReferenceInvoiceID in (select InvoiceID from invoicemaster where ReferenceInvoiceID=$InvoiceID)
 )
";*/
$CASHCUSTOMERS=$_SESSION['SETTING']['CASHCUSTOMERS'];
$sql=" select   sum(Debit) TotalPaid,
 (select COAName from Accounts where COAID =vd.LedgerID) as SupplierName,
(select CustomerName from invoicemaster where InvoiceID=$InvoiceID) as CustomerName  
  ,LedgerID from VoucherDetails as vd where voucherid in (
 SELECT VoucherID FROM VoucherMaster where SelectionID=(select max(SelectionID) from VoucherMaster where VoucherTypeID=7  and 
 ReferenceInvoiceID in(select InvoiceID from invoicemaster where ReferenceInvoiceID=$InvoiceID)) and ReferenceInvoiceID in (select InvoiceID from invoicemaster where ReferenceInvoiceID=$InvoiceID)
 ) and ledgerid<>$CASHCUSTOMERS
 group by ledgerid ";
//$sql="select * from list_receivable 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)
      $row[$key]= utf8_encode($value);  

    $data[]=$row; 
    }
  //  print_r($data);
    echo json_encode($data);

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


    $data=array();
  if(isset($_GET['SupplierID']) && is_numeric($_GET['SupplierID']))
    {
$SupplierID="SupplierID=".$_GET['SupplierID']. " and ";
    }
    else
    {
      $SupplierID="";
    }
     if(isset($_GET['InvoiceID']) && is_numeric($_GET['InvoiceID']))
    {
$InvoiceID="ReferenceInvoiceID=".$_GET['InvoiceID']. " and ";
    }
    else
    {
      $InvoiceID="";
    }
    if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined")
    {
$VoucherNo="KeyField like '%".$_GET['VoucherNo']. "%' and ";
    }
    else
    {
      $VoucherNo="";
    }
    //
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" convert(date,InvoiceDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
    }
    else
    {
      $date='';
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID=" GodownID=".$_GET['LocationID']." and ";
    }
    else
    {
      $LocationID="";
    }
    if(isset($_GET['COAID']) && $_GET['COAID']!="undefined" && $_GET['COAID']!="")
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $COAID=" SupplierID=".$_GET['COAID']."";
    }
    else
    {
      $COAID="";
    } 
    //?$_GET['SupplierID']:;
        $CashAccount=$_SESSION['SETTING']['CASHINHAND'];
    $CreditCard=$_SESSION['SETTING']['CREDITCARD'];
  $searchbox="".$InvoiceID."".$SupplierID."".$COAID."".$LocationID."".$date."".$VoucherNo;
      $sql="select ROW_NUMBER() OVER (ORDER BY [InvoiceID])  as row_num,InvoiceID,InvoiceID as Checkbox,g.AdditionalInfo1 as Company,g.Name as FullCompany,invoicemaster.KeyField as KeyField,InvoiceDate,DeliveryDate,SymReceived,NetAmount,
Paid as TotalPaid,(NetAmount-Paid) as TotalPending,Balance,SupplierID,(select Top 1 VoucherNo from VoucherMaster where ReferenceInvoiceID =Invoicemaster.InvoiceID and VoucherTypeID=7) as GLCode,(select Distinct KeyField from InvoiceMaster as im where  im.invoiceid= invoicemaster.ReferenceInvoiceID ) as GKeyField,(select sum(Debit) from VoucherDetails where voucherid in(select Voucherid from vouchermaster where ReferenceInvoiceID =Invoicemaster.InvoiceID and VoucherTypeID=7) and LedgerID=$CashAccount) as Cash,(select sum(Debit) from VoucherDetails where voucherid in(select Voucherid from vouchermaster where ReferenceInvoiceID =Invoicemaster.InvoiceID and VoucherTypeID=7) and LedgerID=$CreditCard) as CreditCard,
(select COAName from Accounts where COAID =Invoicemaster.SupplierID) as SupplierName,(select COAName from Accounts where COAID =
(select Under from accounts where COAID=Invoicemaster.SupplierID)) as ParentHead from invoicemaster 
left outer join godowns as g on InvoiceMaster.GodownID=g.GodownID where $searchbox  InvoiceType in(5,9)
";
//$sql="select * from list_receivable 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)
      $row[$key]= utf8_encode($value);  

    $data[]=$row; 
    }
  //  print_r($data);
    echo json_encode($data);

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


    $data=array();
  if(isset($_GET['SupplierID']) && is_numeric($_GET['SupplierID']))
    {
$SupplierID="SupplierID=".$_GET['SupplierID']. " and ";
$SupplierID1="COAID=".$_GET['SupplierID']. " and ";
    }
    else
    {
      $SupplierID="";
      $SupplierID1="";
    }
    if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined")
    {
$VoucherNo="KeyField like '%".$_GET['VoucherNo']. "%' and ";
$VoucherNo1="generalledger.KeyField like '%".$_GET['VoucherNo']. "%' and ";
    }
    else
    {
      $VoucherNo="";
      $VoucherNo1="";
    }
    //
    if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
    {
      $date=" convert(date,VoucherDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
      $date1=" convert(date,VoucherDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
    }
    else
    {
      $date='';
      $date1="";
    } 
    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID=" GodownID=".$_GET['LocationID']." and ";
    }
    else
    {
      $LocationID="";
    }
    if(isset($_GET['showZeroBalance']) && $_GET['showZeroBalance']!="undefined" && $_GET['showZeroBalance']!="" && $_GET['showZeroBalance']==0)
    {
      $showZeroBalance=" (isnull(debit,0)-isnull(paid,0))>0 and ";
    }
    else
    {
      $showZeroBalance="";
    }
    if(isset($_GET['COAID']) && $_GET['COAID']!="undefined" && $_GET['COAID']!="")
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $COAID=" SupplierID=".$_GET['COAID']."";
    }
    else
    {
      $COAID="";
    } 
    //?$_GET['SupplierID']:;
  $searchbox="".$SupplierID."".$COAID."".$LocationID."".$date."".$VoucherNo.$showZeroBalance;
  $searchbox1="".$SupplierID1.$date1."".$showZeroBalance;
     /*$sql="select ROW_NUMBER() OVER (ORDER BY [InvoiceID])  as row_num,InvoiceID,InvoiceID as Checkbox,g.AdditionalInfo1 as Company,g.Name as FullCompany,invoicemaster.KeyField as KeyField,InvoiceDate,DeliveryDate,NetAmount,
Paid as TotalPaid,(NetAmount-Paid) as TotalPending,Balance,SupplierID,(select GLCode from Accounts where COAID =Invoicemaster.SupplierID) as GLCode,
(select COAName from Accounts where COAID =Invoicemaster.SupplierID) as SupplierName,(select COAName from Accounts where COAID =
(select Under from accounts where COAID=Invoicemaster.SupplierID)) as ParentHead from invoicemaster 
inner join godowns as g on InvoiceMaster.GodownID=g.GodownID where $searchbox  InvoiceType in(5,9)
union

select ROW_NUMBER() OVER (ORDER BY VoucherID)  as row_num,VoucherID,VoucherID as Checkbox,g.AdditionalInfo1 as Company,
g.Name as FullCompany,VoucherNo as KeyField,VoucherDate,ChequeDate,TotalAmount,Credit as Paid,0 as TotalPending,0 as Balance,
COAID as SupplierID,GLCode,COAName as SupplierName,(select COAName from Accounts where COAID =
(select Under from accounts where COAID=GeneralLedger.COAID)) as ParentHead
from GeneralLedger 
inner join godowns as g on GeneralLedger.LocationID=g.GodownID where  $searchbox VoucherTypeID in(7)
";*/
 $sql="select * from (select * from list_receivable where $searchbox  under=67 and TotalPending>0 and  (Debit-Paid)>0 and SupplierID not in (20) 
union all 
select ROW_NUMBER() OVER (ORDER BY VoucherID)  as row_num,VoucherID,VoucherID as Checkbox,g.AdditionalInfo1 as Company,g.GodownID as GodownID,ReferenceInvoiceID,
g.Name as FullCompany,VoucherNo as KeyField,convert(date,VoucherDate) as VoucherDate,ChequeDate,sum(Debit) as Debit,sum(Credit) as Credit,case when isnull(
(select Received from SalesInvoiceMaster where invoiceid=GeneralLedger.ReferenceInvoiceID and Invoicetype=3),(sum(Credit)-isnull(
(select sum(Received) from SalesInvoiceMaster where CustomerID=COAID and Invoicetype=3),0)))<0 then sum(Credit) else isnull(
(select Received from SalesInvoiceMaster where invoiceid=GeneralLedger.ReferenceInvoiceID and Invoicetype=3),(sum(Credit)-isnull(
(select sum(Received) from SalesInvoiceMaster where CustomerID=COAID and Invoicetype=3),0))) end   as Paid,(sum(Debit)-isnull(sum(Received),0)) as TotalPending,
0 as Balance,isnull((select isnull(sum(Debit),0) from GeneralLedger as gl where VoucherTypeID=0 and GL.COAID=GeneralLedger.COAID),0) as Opening,
COAID as SupplierID,GLCode,COAName as SupplierName,(select COAName from Accounts where COAID =
(select Under from accounts where COAID=GeneralLedger.COAID)) as ParentHead,generalledger.Under as Under,VoucherTypeID
from GeneralLedger 
left outer join godowns as g on GeneralLedger.LocationID=g.GodownID where  $searchbox1 VoucherTypeID in(7,5) and generalledger.under=67 and  generalledger.COAID not in (20)
group by VoucherID,g.AdditionalInfo1,g.GodownID,ReferenceInvoiceID,g.name,voucherno,Voucherdate,ChequeDate,COAID,GLCode,COAName,generalledger.under,VoucherTypeID )t where TotalPending>0 order by SupplierID,VoucherDate
";

    $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);  

    $data[]=$row; 
    }
  //  print_r($data);
    echo json_encode($data);

  
  
  }
	if($_GET['action']=='AccountPayableList')
	{
		$data=array();
	if(isset($_GET['SupplierID']) && is_numeric($_GET['SupplierID']))
		{
$SupplierID="SupplierID=".$_GET['SupplierID']. " and ";
		}
		else
		{
			$SupplierID="";
		}
		if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined")
		{
$VoucherNo="invoicemaster.KeyField like '%".$_GET['VoucherNo']. "%' and ";
		}
		else
		{
			$VoucherNo="";
		}
		//
		if((isset($_GET['startdate']) && $_GET['startdate']!="undefined" && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
		{
			$date=" InvoiceDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
		}
		else
		{
			$date='';
		}	
		if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
		{
			$LocationID=" invoicemaster.GodownID=".$_GET['LocationID']." and ";
		}
		else
		{
			$LocationID="";
		}
		if(isset($_GET['COAID']) && $_GET['COAID']!="undefined" && $_GET['COAID']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$COAID=" SupplierID=".$_GET['COAID']."";
		}
		else
		{
			$COAID="";
		}	
		//?$_GET['SupplierID']:;
	$searchbox="".$SupplierID."".$COAID."".$LocationID."".$date."".$VoucherNo;
		 $sql="select ROW_NUMBER() OVER (ORDER BY [InvoiceID])  as row_num,InvoiceID,InvoiceID as Checkbox,g.AdditionalInfo1 as Company,g.Name as FullCompany,invoicemaster.KeyField as KeyField,InvoiceDate,DeliveryDate,NetAmount,
Paid as TotalPaid,(NetAmount-Paid) as TotalPending,Balance,SupplierID,(select GLCode from Accounts where COAID =Invoicemaster.SupplierID) as GLCode,
(select COAName from Accounts where COAID =Invoicemaster.SupplierID) as SupplierName,(select COAName from Accounts where COAID =
(select Under from accounts where COAID=Invoicemaster.SupplierID)) as ParentHead from invoicemaster 
inner join godowns as g on InvoiceMaster.GodownID=g.GodownID where $searchbox  InvoiceType in(4) and invoicemaster.active=1 order by SupplierID";
		$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);	

		$data[]=$row;	
		}
	//	print_r($data);
		echo json_encode($data);

	}
	if($_GET['action']=="PostVoucher")
	{
  odbc_autocommit($connection, FALSE);
		$VoucherID=$_GET['VoucherID'];
		$sql="update vouchermaster set posted=1,active=1,EditLog='".$_SESSION['UserName']."',PostDate='".Date("Y-m-d H:i:s")."' where VoucherID=".$VoucherID;
		odbc_exec($connection, $sql);
$sql="update voucherdetails set ISDelete=0 where VoucherID=".$VoucherID;
		odbc_exec($connection, $sql);

$sql="select * from voucherdetails where VoucherID=".$VoucherID;
$result=odbc_exec($connection,$sql);
while($row=odbc_fetch_array($result))
{
	$VoucherDetailID=$row['ID'];
	 $sql="select * from VoucherDetails_InvoiceDetail where VoucherDetailID=".$VoucherDetailID;
	$result1=odbc_exec($connection,$sql);
	while($row1=odbc_fetch_array($result1))
	{
		$InvoiceID=$row1['ReferenceInvoiceID'];
		$sqldelete="delete from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=".$InvoiceID." and VoucherDetailID=".$VoucherDetailID;
					odbc_exec($connection,$sqldelete);
					
$sum=getSum("VoucherDetails_InvoiceDetail","sum(InvoicePaidAmount) as sum","ReferenceInvoiceID",$InvoiceID,$connection);


if($sum>0)
{
$updatesql="update Invoicemaster set Paid=$sum,Balance=(NetAmount-paid),EditLog='".$_SESSION['UserName']."' where InvoiceID=".$InvoiceID;
					odbc_exec($connection,$updatesql) or die(odbc_error().$updatesql);

}
	}	
}
	//  $res=array('status'=>"ok",'description'=>'Record Save Sucessfully');
		//Centralization
 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');

}
    echo json_encode($res);	

	
	
	}
	if($_GET['action']=="DeleteVoucher")
	{
      odbc_autocommit($connection, FALSE);
		$VoucherID=$_GET['VoucherID'];
		$sql="update vouchermaster set active=0,posted=0,DeleteLog='".$_SESSION['UserName']."' where VoucherID=".$VoucherID;
		odbc_exec($connection, $sql);
$sql="update voucherdetails set ISDelete=1 where VoucherID=".$VoucherID;
		odbc_exec($connection, $sql);

$sql="select * from voucherdetails where VoucherID=".$VoucherID;
$result=odbc_exec($connection,$sql);
while($row=odbc_fetch_array($result))
{
	$VoucherDetailID=$row['ID'];
	 $sql="select * from VoucherDetails_InvoiceDetail where VoucherDetailID=".$VoucherDetailID;
	$result1=odbc_exec($connection,$sql);
	while($row1=odbc_fetch_array($result1))
	{
		$InvoiceID=$row1['ReferenceInvoiceID'];
		$sqldelete="delete from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=".$InvoiceID." and VoucherDetailID=".$VoucherDetailID;
					odbc_exec($connection,$sqldelete);
					
$sum=getSum("VoucherDetails_InvoiceDetail","sum(InvoicePaidAmount) as sum","ReferenceInvoiceID",$InvoiceID,$connection);



$updatesql="update Invoicemaster set Paid=$sum,Balance=(NetAmount-paid),EditLog='".$_SESSION['UserName']."' where InvoiceID=".$InvoiceID;
					odbc_exec($connection,$updatesql);

	}	
}
	//  $res=array('status'=>"ok",'description'=>'Record Deleted Sucessfully');
		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');

}
    echo json_encode($res);	

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


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

		//$VoucherTypeID=$_GET['VoucherTypeID'];
		

		if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined")
		{
$VoucherNo="VoucherNo like '%".$_GET['VoucherNo']. "%' and ";
		}
		else
		{
			$VoucherNo="";
		}
		//
if(isset($_GET['VoucherDate']) && $_GET['VoucherDate']!="undefined" && $_GET['VoucherDate']!="") 
		{
			$date=" convert(date,VoucherDate)  ='".$_GET['VoucherDate']."' and ";
		}
		else
		{
			$date='';
		}	
		if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
		{
			$LocationID=" LocationID=".$_GET['LocationID']." and ";
		}
		else
		{
			$LocationID="";
		}
		if(isset($_GET['ChequeNo']) && $_GET['ChequeNo']!="undefined" && $_GET['ChequeNo']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$ChequeNo=" ChequeNo like '%".$_GET['ChequeNo']."%' and ";
		}
		else
		{
			$ChequeNo="";
		}
		if(isset($_GET['DDNo']) && $_GET['DDNo']!="undefined" && $_GET['DDNo']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$DDNo=" DD like '%".$_GET['DDNo']."%' and ";
		}
		else
		{
			$DDNo="";
		}
		if(isset($_GET['PONo']) && $_GET['PONo']!="undefined" && $_GET['PONo']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$PONo=" PONo like '%".$_GET['PONo']."%' and ";
		}
		else
		{
			$PONo="";
		}

		if(isset($_GET['TotalAmount']) && $_GET['TotalAmount']!="undefined" && $_GET['TotalAmount']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$TotalAmount=" TotalAmount=".$_GET['TotalAmount']." and ";
		}
		else
		{
			$TotalAmount="";
		}
//
		if(isset($_GET['BankName']) && $_GET['BankName']!="undefined" && $_GET['BankName']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$BankName=" ClientBankAccountName like '%".$_GET['BankName']."%' and ";
		}
		else
		{
			$BankName="";
		}
				if(isset($_GET['TCNo']) && $_GET['TCNo']!="undefined" && $_GET['TCNo']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$TCNo=" TC like '%".$_GET['TCNo']."%' and ";
		}
		else
		{
			$TCNo="";
		}
		//	
		//?$_GET['SupplierID']:;
	$searchbox="".$BankName."".$ChequeNo."".$LocationID."".$date."".$VoucherNo."".$TCNo."".$DDNo."".$PONo."".$TotalAmount;

		$sql="		select ROW_NUMBER() OVER (ORDER BY [VoucherID])  as row_num,VoucherID,VoucherDate,Narration,VoucherNo,TotalAmount,ChequeNo,PONo,DD,TC,ClientBankAccountName,LocationID,Godowns.Name as Location,'' as col_Action ,'' as CreateByUserName
		from vouchermaster 
		Inner join Godowns on vouchermaster.locationid=godowns.GodownID
		where $searchbox vouchermaster.active=1 and Posted=0";
		$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
		while($row=odbc_fetch_array($result))
		{
     // $row['Narration']
	
					$permission=userrights($Userid,$SideBarID,'[Alter]',$connection);
					if($permission==1)
					{
							$editdata='<i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editMaster(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:deleteMaster(this);"></i>';
					}
					else
					{
							$deldata='';
					}
					$permission=userrights($Userid,$SideBarID,'[Execute]',$connection);
					if($permission==1)
					{
							$exdata='<i class="fa fa-envelope fa-lg" style="text-align: right;color: green;cursor:pointer;" onclick="javascript:PostMaster(this,'.$row["VoucherID"].','.$row["LocationID"].');"></i>';
					}
					else
					{
							$exdata='';
					}
			$row['col_Action']=''.$editdata.'&nbsp;&nbsp;&nbsp;'.$deldata.'&nbsp;&nbsp;&nbsp;'.$exdata;
     /* foreach ($row as $key => $value) {
        # code...
        $row[$key]=htmlspecialchars($value);
      }*/
		$data[]=$row;	
		}//end while 
	//	print_r($data);
			}//end permission
		echo json_encode($data);

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

		
		$VoucherTypeID=$_GET['VoucherTypeID'];
		

	
		//
if(isset($_GET['VoucherDate']) && $_GET['VoucherDate']!="undefined" && $_GET['VoucherDate']!="") 
		{
			$date=" convert(date,VoucherDate) = '".$_GET['VoucherDate']."' and ";
		}
		else
		{
      $date=Date("Y-m-d");
			$date=" VoucherDate='".$date."' and ";
		}	
    if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined")
    {
$VoucherNo="VoucherNo like '%".$_GET['VoucherNo']. "%' and ";
      if((!(isset($_GET['VoucherDate']))) || $_GET['VoucherDate']=="undefined" || $_GET['VoucherDate']=="") 
        $date="";

    }
    else
    {
      $VoucherNo="";
    }
		if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
		{
			$LocationID=" LocationID=".$_GET['LocationID']." and ";
		}
		else
		{
			$LocationID="";
		}
		if(isset($_GET['ChequeNo']) && $_GET['ChequeNo']!="undefined" && $_GET['ChequeNo']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$ChequeNo=" ChequeNo like '%".$_GET['ChequeNo']."%' and ";
		}
		else
		{
			$ChequeNo="";
		}
		if(isset($_GET['DDNo']) && $_GET['DDNo']!="undefined" && $_GET['DDNo']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$DDNo=" DD like '%".$_GET['DDNo']."%' and ";
		}
		else
		{
			$DDNo="";
		}
		if(isset($_GET['PONo']) && $_GET['PONo']!="undefined" && $_GET['PONo']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$PONo=" PONo like '%".$_GET['PONo']."%' and ";
		}
		else
		{
			$PONo="";
		}

		if(isset($_GET['TotalAmount']) && $_GET['TotalAmount']!="undefined" && $_GET['TotalAmount']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$TotalAmount=" TotalAmount=".$_GET['TotalAmount']." and ";
		}
		else
		{
			$TotalAmount="";
		}
//
		if(isset($_GET['BankName']) && $_GET['BankName']!="undefined" && $_GET['BankName']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$BankName=" ClientBankAccountName like '%".$_GET['BankName']."%' and ";
		}
		else
		{
			$BankName="";
		}
				if(isset($_GET['TCNo']) && $_GET['TCNo']!="undefined" && $_GET['TCNo']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$TCNo=" TC like '%".$_GET['TCNo']."%' and ";
		}
		else
		{
			$TCNo="";
		}
		//	
		//?$_GET['SupplierID']:;
	$searchbox="".$BankName."".$ChequeNo."".$LocationID."".$date."".$VoucherNo."".$TCNo."".$DDNo."".$PONo."".$TotalAmount;

		$sql="		select ROW_NUMBER() OVER (ORDER BY [VoucherID])  as row_num,VoucherID,VoucherDate,Narration,VoucherNo,TotalAmount,ChequeNo,PONo,DD,TC,ClientBankAccountName,LocationID,Godowns.Name as Location,'' as col_Action ,'' as CreateByUserName
		from vouchermaster 
		Inner join Godowns on vouchermaster.locationid=godowns.GodownID
		where $searchbox vouchermaster.active=1 and VoucherTypeID=".$VoucherTypeID;
		$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
		while($row=odbc_fetch_array($result))
		{
			/*<i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editMaster(this);"></i> &nbsp;&nbsp;&nbsp; <i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteMaster(this);"></i>&nbsp;&nbsp;*/
                $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:deleteMaster(this);"></i>';
          }
          else
          {
            $deldata='';
          }
	$permission=userrights($Userid,$SideBarID,'[Print]',$connection);
				if($permission==1)
				{
$row['col_Action']='&nbsp;<i class="fa fa-print fa-lg" style="text-align: right;color: green;cursor:pointer;" onclick="javascript:printMaster(this,'.$row["VoucherID"].','.$row["LocationID"].');"></i>';
				}
				else
				{

			$row['col_Action']='&nbsp;';
				}
		 $row['col_Action']=$row['col_Action'].$deldata;
      /*foreach ($row as $key => $value) {
        # code...
        $row[$key]=utf8_encode($value);
      }*/
		$data[]=$row;	
		}//end while
		//}//end while
	}//end permission
	//	print_r($data);
		echo json_encode($data);

	
	}//end getVoucherList

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

	$VoucherTypeID=$_GET['VoucherTypeID'];
	if((isset($_GET['startdate']) && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!=""))
		{
			$date="VoucherDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and";
		}
		else
		{
			$date='';
		}	
		if(isset($_GET['LocationID']) && $_GET['LocationID']>0)
		{
			$LocationID=" LocationID=".$_GET['LocationID']." and ";
		}
		else
		{
			$LocationID="";
		}
		if(isset($_GET['COAID']) && $_GET['COAID']>0)
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$COAID=" and (vd.CreditLedgerID=".$_GET['COAID']." or vd.LedgerID=".$_GET['COAID'].")";
		}
		else
		{
			$COAID="";
		}		
		$searchbox="".$date."".$LocationID;
		$data=array();
	//	$VoucherID=$_GET['VoucherID'];
		$sql="select * from voucherdetails where ledgerid=".$COAID." and voucherid in (select voucherid from vouchermaster where VoucherTypeID=0)";
		$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{

		$data[]=$row;	
		}
		//voucherdetails 
		  $sql="		select CreditLedgerID,acc.COAName as creditledgername,LedgerID as  particularid,acc1.COAName as  particular,vd.CostCenterID,g.additionalinfo1 as costcenter,
		debitcostcenterid,g1.name as debitcostcenter,narration as detailnarration,debit,
		vd.ID,creditcostcentercoaid,debitcostcentercoaid,'' as voucherno,'' as SubDetail,credit,vd.voucherid as VoucherID from voucherdetails  as vd
		inner  join accounts as acc on vd.CreditLedgerID=acc.COAID
		inner  join accounts as acc1 on vd.LedgerID=acc1.COAID
		inner  join Godowns as g on vd.CostCenterID=g.GodownID
		inner  join Godowns as g1 on vd.debitcostcenterid=g1.GodownID where VoucherID in (select VoucherID from Vouchermaster where $searchbox VoucherTypeID=".$VoucherTypeID.") $COAID";
		$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{
$row['VoucherNo']=getnamesingle("Vouchermaster","VoucherNo","VoucherID",$row['VoucherID'],$connection);
$row['VoucherDate']=getnamesingle("Vouchermaster","VoucherDate","VoucherID",$row['VoucherID'],$connection);
		$data['detailitems'][]=$row;	
		}
		

		echo json_encode($data);


		
	
	}
	if($_GET['action']=="GetVouchers")
	{
	$VoucherTypeID=$_GET['VoucherTypeID'];
	if((isset($_GET['startdate']) && $_GET['startdate']!="") && (isset($_GET['enddate']) && $_GET['enddate']!=""))
		{
			$date=" convert(date,VoucherDate) between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
		}
		else
		{
			$date='';
		}	
		if(isset($_GET['LocationID']) && $_GET['LocationID']>0)
		{
			$LocationID=" LocationID=".$_GET['LocationID']." and ";
		}
		else
		{
			$LocationID="";
		}
		if(isset($_GET['COAID']) && $_GET['COAID']>0)
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$COAID=" and (vd.CreditLedgerID=".$_GET['COAID']." or vd.LedgerID=".$_GET['COAID'].")";
		}
		else
		{
			$COAID="";
		}		
		$searchbox="".$date."".$LocationID;
		$data=array();
	//	$VoucherID=$_GET['VoucherID'];
		$sql="select voucherid,voucherdate,narration,voucherno,totalamount,chequeno,pono,DD as ddno ,TC as tcno,ClientBankAccountName as clientbankname,LocationID,isauto,referencevoucherid,ChequeDate
			from vouchermaster  where $searchbox VoucherTypeID=".$VoucherTypeID;
		$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{

		$data[]=$row;	
		}
		//voucherdetails 
		  $sql="		select CreditLedgerID,acc.COAName as creditledgername,LedgerID as  particularid,acc1.COAName as  particular,vd.CostCenterID,g.additionalinfo1 as costcenter,
		debitcostcenterid,g1.name as debitcostcenter,narration as detailnarration,debit,
		vd.ID,creditcostcentercoaid,debitcostcentercoaid,'' as voucherno,'' as SubDetail,credit,vd.voucherid as VoucherID from voucherdetails  as vd
		Left outer  join accounts as acc on vd.CreditLedgerID=acc.COAID
		Left outer  join accounts as acc1 on vd.LedgerID=acc1.COAID
		Left outer  join Godowns as g on vd.CostCenterID=g.GodownID
		Left outer  join Godowns as g1 on vd.debitcostcenterid=g1.GodownID where VoucherID in (select VoucherID from Vouchermaster where $searchbox VoucherTypeID=".$VoucherTypeID.") $COAID";
		$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{
$row['VoucherNo']=getnamesingle("Vouchermaster","VoucherNo","VoucherID",$row['VoucherID'],$connection);
$row['VoucherDate']=getnamesingle("Vouchermaster","VoucherDate","VoucherID",$row['VoucherID'],$connection);
		$data['detailitems'][]=$row;	
		}
		

		echo json_encode($data);


		
	}
  if($_GET['action']=="GetVoucherDetail3")
  {
    $data=array();
    $VoucherNo=$_GET['VoucherID'];
    $VoucherDate=$_GET['VoucherDate'];
$sql="select VoucherDate,vm.TotalAmount as TotalAmount,im.CustomerName as CustomerName,vm.Narration as Narration from InvoiceMaster as im  inner join vouchermaster as vm on vm.ReferenceInvoiceID=im.InvoiceID 
Where VoucherNo='$VoucherNo' and vm.Totalamount>0 and VoucherTypeID=7
";

/*    $sql="select convert(smalldatetime,vm.LastModificationTimeStamp) as VoucherDate,sum(vm.TotalAmount) as TotalAmount,im.CustomerName as CustomerName,'Job Card Payment JobCardNo :$JobCardNo' as Narration
from InvoiceMaster as im  inner join vouchermaster as vm on vm.ReferenceInvoiceID=im.InvoiceID 
where ParkingNo='$JobCardNo' and vm.Totalamount>0 and VoucherTypeID=7 
and convert(smalldatetime,vm.LastModificationTimeStamp)='$VoucherDate' group by convert(smalldatetime,vm.LastModificationTimeStamp),CustomerName";*/
    $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {

    $data[]=$row; 
     }

    echo json_encode($data);

  }

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

		$data=array();
		$VoucherID=$_GET['VoucherID'];
		$sql="select voucherid,voucherdate,narration,voucherno,totalamount,chequeno,pono,DD as ddno ,TC as tcno,ClientBankAccountName as clientbankname,(select customername from invoicemaster where InvoiceID=vouchermaster.ReferenceInvoiceID) as customername,LocationID,isauto,referencevoucherid,ChequeDate
			from vouchermaster  where VoucherNo='".$VoucherID."' and active=1";
		$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{
			foreach ($row as $key => $value) {
				# code...
				$row[$key]=utf8_encode($value);
			}
		$data[]=$row;	
		$VoucherID=$row['voucherid'];
		}
		//voucherdetails 
		$sql="		select CreditLedgerID,acc.COAName as creditledgername,LedgerID as  particularid,acc1.COAName as  particular,vd.CostCenterID,g.name as costcenter,
		debitcostcenterid,g1.name as debitcostcenter,narration as detailnarration,debit,
		vd.ID,creditcostcentercoaid,debitcostcentercoaid,'' as voucherno,''as SubDetail from voucherdetails  as vd
		inner  join accounts as acc on vd.CreditLedgerID=acc.COAID
		inner  join accounts as acc1 on vd.LedgerID=acc1.COAID
		inner  join Godowns as g on vd.CostCenterID=g.GodownID
		inner  join Godowns as g1 on vd.debitcostcenterid=g1.GodownID where VoucherID=".$VoucherID;
		$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{

		$data['detailitems'][]=$row;	
		}
		

		echo json_encode($data);


	
	}
	if($_GET['action']=="GetVoucherDetail")
	{/*
		$data=array();
		$VoucherID=$_GET['VoucherID'];
		$sql="select voucherid,voucherdate,narration,voucherno,totalamount,chequeno,pono,DD as ddno ,TC as tcno,ClientBankAccountName as clientbankname,LocationID,isauto,referencevoucherid,ChequeDate,VoucherTypeID
			from vouchermaster  where VoucherID=".$VoucherID;
		$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{

		$data[]=$row;	
		$VoucherID=$row['voucherid'];
		}
		//voucherdetails 
		$sql="		select CreditLedgerID,CreditLedgerID as creditledgeid,acc.COAName as creditledgername,LedgerID as  particularid,acc1.COAName as  particular,vd.CostCenterID as costcenterid,g.name as costcenter,(select VoucherTypeID from VoucherMaster where VoucherID=$VoucherID) as VoucherTypeID,
		debitcostcenterid,g1.name as debitcostcenter,narration as detailnarration,debit,(select keyfield from invoicemaster where invoiceid in(select ReferenceInvoiceID from VoucherDetails_InvoiceDetail where VoucherID=vd.VoucherID)) as KeyField,
		vd.ID,creditcostcentercoaid,debitcostcentercoaid,'' as voucherno,''as SubDetail from voucherdetails  as vd
		left outer  join accounts as acc on vd.CreditLedgerID=acc.COAID
		left outer  join accounts as acc1 on vd.LedgerID=acc1.COAID
		left outer  join Godowns as g on vd.CostCenterID=g.GodownID
		left outer  join Godowns as g1 on vd.debitcostcenterid=g1.GodownID where VoucherID=".$VoucherID;
		$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{

		$data['detailitems'][]=$row;	
		}
		

		echo json_encode($data);


	*/

    $data=array();
    $VoucherID=$_GET['VoucherID'];
    $sql="select voucherid,voucherdate,narration,voucherno,convert(Numeric(9,2),totalamount) as totalamount,chequeno,pono,DD as ddno ,TC as tcno,ClientBankAccountName as clientbankname,LocationID,isauto,referencevoucherid,ChequeDate,VoucherTypeID
      from vouchermaster  where VoucherID=".$VoucherID;
    $result=odbc_exec($connection, $sql);
    while($row=odbc_fetch_array($result))
    {

    $data[]=$row; 
    $VoucherID=$row['voucherid'];
    }
    //voucherdetails 
    $sql="    select CreditLedgerID,CreditLedgerID as creditledgeid,acc.COAName as creditledgername,LedgerID as  particularid,acc1.COAName as  particular,vd.CostCenterID as costcenterid,g.name as costcenter,(select top 1 VoucherTypeID from VoucherMaster where VoucherID=$VoucherID) as VoucherTypeID,
    debitcostcenterid,g1.name as debitcostcenter,narration as detailnarration,convert(Numeric(9,2),debit) as debit,convert(Numeric(9,2),credit) as credit,(select top 1 keyfield from invoicemaster where invoiceid in(select ReferenceInvoiceID from VoucherDetails_InvoiceDetail where VoucherID=vd.VoucherID)) as KeyField,
    vd.ID,creditcostcentercoaid,debitcostcentercoaid,'' as voucherno,''as SubDetail,Picture1,Picture2,DD,PONO,ChequeNo,InstrumentDate,TC,PaymentType as  BankName from voucherdetails  as vd
    left outer  join accounts as acc on vd.CreditLedgerID=acc.COAID
    left outer join accounts as acc1 on vd.LedgerID=acc1.COAID
    left outer  join Godowns as g on vd.CostCenterID=g.GodownID
    left outer  join Godowns as g1 on vd.debitcostcenterid=g1.GodownID where VoucherID=".$VoucherID;
    $result=odbc_exec($connection, $sql);
    while($row=odbc_fetch_array($result))
    {

    $data['detailitems'][]=$row;  
    }
    

    echo json_encode($data);


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

		$data=array();
		if(isset($_GET['GLStartsWith']))
		{
			$GLCode=$_GET['GLStartsWith'];
		$GLCode=" and acc.GLCode like '".$GLCode."%'";

		}
		else
		{
		$GLCode=" ";			
		}
		 $sql="select COAName,Hierarchy,Under,CostCenterID,acc.COAID as 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,(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,NatureID from accounts as acc where [group]=0 and degree=5 and active=1 $GLCode";	
			$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{

			foreach($row as $key=>$value)
      {
      $row[$key]= htmlspecialchars($value);  
			$row[$key]= utf8_encode($value);	
      }

		$data[]=$row;	
		}
	//	print_r($data);
		echo json_encode($data);

	
	}
  if($_GET['action']=="getCreditVouchers")
  {
      $data=array();
  $SupplierID=(isset($_GET['SupplierID']) && is_numeric($_GET['SupplierID']))?$_GET['SupplierID']:0;
  //$NatureID=(isset($_GET['NatureID']) && is_numeric($_GET['NatureID']))?$_GET['NatureID']:0;

  if(isset($_GET['VoucherID']) && $_GET['VoucherID']>0)
  {
    $VoucherID=$_GET['VoucherID'];
  }
  else
  {
    $VoucherID=0;
  }
  //$under=getnamesingle("accounts","under","COAID",$SupplierID,$connection);
  $sql="
select vm.VoucherID as VoucherID,vd.ID as Checkbox,VoucherNo as VoucherNo ,VoucherDate as InvoiceDate,Credit,'Voucher' as ListType ,
Credit-(select isnull(Sum(InvoicePaidAmount),0) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=vm.VoucherID) as Balance from 
VoucherDetails as vd  inner join VoucherMaster as vm on vm.VoucherID=vd.VoucherID and vd.CreditLedgerID=".$SupplierID." and DetailLocationID is not null  and CreditLedgerID>0";

 $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);  

    $data[]=$row; 
    }
  //  print_r($data);
    echo json_encode($data);

  }
  if($_GET['action']=="DeleteSettleVoucher")
  {
    if(isset($_GET['SettlementID']) && $_GET['SettlementID']!="")
    {
   // $VoucherID=$_GET['VoucherID'];  
    $SettlementID=$_GET['SettlementID'];
    $sql="select * from VoucherDetails_InvoiceDetail where SettlementID=$SettlementID";
     $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {

      //get list of voucher who are settlement 
      // get each voucher reverse with the new amount
      $VID=$row['VoucherDetailID'];
    $VoucherID=$row['VoucherID'];  
    $ReferenceInvoiceID=$row['ReferenceInvoiceID'];
    $deletesql="delete from VoucherDetails_InvoiceDetail where SettlementID=$SettlementID";
          odbc_exec($connection, $deletesql) or die(odbc_error().$deletesql);

        $updatesql="update VoucherDetails set ReciveCurrency=(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where Voucherid=".$VoucherID."),CurrencyValue=(select sum(InvoiceTotalAmount)-sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where Voucherid=".$VoucherID.") where ID=".$VID;
          odbc_exec($connection,$updatesql) or die(odbc_error().$updatesql);
    }
      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');

}
        echo json_encode($res);
  }
}
if($_GET['action']=="VoucherSettleReport")
{

$data=array();
$sql="
  select Vm.VoucherID as VoucherID,vm.VoucherNo as VoucherNo,vm1.VoucherNo as ReferenceVoucherNo,vm.VoucherDate as VoucherDate,InvoiceTotalAmount as Total,InvoicePaidAmount as Paid,InvoiceBalance as Balance,KeyField,vdid.CreateLog as UserName,vm.Narration as Narration,vdid.ReferenceInvoiceID,'' as col_Action,SDate,SettlementID  from VoucherDetails_InvoiceDetail  as vdid inner join 
  VoucherMaster as vm on vm.VoucherID=vdid.VoucherID inner join VoucherMaster as vm1 on vm1.VoucherID=vdid.ReferenceInvoiceID  ";
   $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);  

    $permission=1;
    //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:deleteMaster(this);"></i>';
          }
          else
          {
              $deldata='';
          }

          $row['col_Action']=''.$deldata;
    $data[]=$row; 
    }
  //  print_r($data);
    echo json_encode($data);
  
}
  if($_GET['action']=="getSettledVoucher")
  {

$sql="
  select Vm.VoucherID as VoucherID,vm.VoucherNo as VoucherNo,vm1.VoucherNo as ReferenceVoucherNo,vm.VoucherDate as VoucherDate,InvoiceTotalAmount as Total,InvoicePaidAmount as Paid,InvoiceBalance as Balance,KeyField,vdid.CreateLog as UserName,vm.Narration as Narration,vdid.ReferenceInvoiceID,'' as col_Action,SDate,SettlementID  from VoucherDetails_InvoiceDetail  as vdid inner join 
  VoucherMaster as vm on vm.VoucherID=vdid.VoucherID inner join VoucherMaster as vm1 on vm1.VoucherID=vdid.ReferenceInvoiceID  ";
   $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);  

    $permission=1;
    //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:deleteMaster(this);"></i>';
          }
          else
          {
              $deldata='';
          }

          $row['col_Action']=''.$deldata;
    $data[]=$row; 
    }
  //  print_r($data);
    echo json_encode($data);
  }

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

    //print_r($_GET);

    $data=array();
  $SupplierID=(isset($_GET['SupplierID']) && is_numeric($_GET['SupplierID']))?$_GET['SupplierID']:0;
  $NatureID=(isset($_GET['NatureID']) && is_numeric($_GET['NatureID']))?$_GET['NatureID']:0;

  if(isset($_GET['VoucherID']) && $_GET['VoucherID']>0)
  {
    $VoucherID=$_GET['VoucherID'];
  }
  else
  {
    $VoucherID=0;
  }
  $under=getnamesingle("accounts","under","COAID",$SupplierID,$connection);
  if($under==154)
  {

    $data=array();
  $SupplierID=(isset($_GET['SupplierID']) && is_numeric($_GET['SupplierID']))?$_GET['SupplierID']:0;
    if($VoucherID==0)
    {
/*    $sql="select ROW_NUMBER() OVER (ORDER BY [InvoiceID])  as row_num,InvoiceID,InvoiceID as Checkbox,KeyField,InvoiceDate,DeliveryDate,NetAmount,isNull(TotalFreightByAmount,(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID])) as TotalPaid,
    (NetAmount-isNull(TotalFreightByAmount,(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID]))) as TotalPending,Balance,'Invoice' as ListType from invoicemaster where active=1 and  SupplierID=".$SupplierID." and InvoiceType in(5,8) and GodownID>0 and (NetAmount-isNull(TotalFreightByAmount,0))>0
union all";*/
$sql="
select ROW_NUMBER() OVER (ORDER BY [ID])  as row_num,vm.VoucherID as InvoiceID,vd.ID as Checkbox,VoucherNo as KeyField ,VoucherDate as InvoiceDate,
VoucherDate as DeliveryDate,Debit as NetAmount,ReciveCurrency as TotalPaid,(Debit-ReciveCurrency) as TotalPending,CurrencyValue as Balance,'Voucher' as ListType  from 
VoucherDetails as vd  inner join VoucherMaster as vm on vm.VoucherID=vd.VoucherID and vd.LedgerID=".$SupplierID." and DetailLocationID is not null

    ";
    }
    else
    {
$sql="select ROW_NUMBER() OVER (ORDER BY [InvoiceID])  as row_num,InvoiceID,InvoiceID as Checkbox,
KeyField,InvoiceDate,DeliveryDate,NetAmount,
isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0)
-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0)as TotalPaid,
(NetAmount-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0))
+(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID]) as TotalPending,
  (Balance+(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail 
  where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID])) as Balance,'Invoice' as ListType from invoicemaster
   where SupplierID=$SupplierID and InvoiceType in(5,8) and active=1 and InvoiceStatusID<>5 and  GodownID>0";      
    }
    $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);  

    $data[]=$row; 
    }
  //  print_r($data);
    echo json_encode($data);

  
  }
  else
  {
    $sql="";
    if($NatureID==14)
    {
      /*$sql="select ROW_NUMBER() OVER (ORDER BY [InvoiceID])  as row_num,InvoiceID,InvoiceID as Checkbox,KeyField,InvoiceDate,DeliveryDate,NetAmount,convert(numeric,isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0)
-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0))as TotalPaid,
(NetAmount-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0)) as TotalPending,
  isNull(Balance+(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail 
  where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0) as Balance ,'Invoice' as ListType from invoicemaster where active=1 and SupplierID=".$SupplierID." and InvoiceType in(4)
union all";// invoice*/
      $sql="
select ROW_NUMBER() OVER (ORDER BY [ID])  as row_num,vm.VoucherID as InvoiceID,vd.ID as Checkbox,VoucherNo as KeyField ,VoucherDate as InvoiceDate,
VoucherDate as DeliveryDate,Debit as NetAmount,ReciveCurrency as TotalPaid,(Debit-ReciveCurrency) as TotalPending,CurrencyValue as Balance,'Voucher' as ListType  from 
VoucherDetails as vd  inner join VoucherMaster as vm on vm.VoucherID=vd.VoucherID and vd.LedgerID=".$SupplierID." and  vd.debit>0 and vd.debit<>vd.ReciveCurrency";
    }
    else if($NatureID==15)
    {
     /*$sql="select ROW_NUMBER() OVER (ORDER BY [InvoiceID])  as row_num,InvoiceID,InvoiceID as Checkbox,KeyField,InvoiceDate,DeliveryDate,NetAmount,convert(numeric,isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0)
    
-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0))as TotalPaid,
(NetAmount-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0)) as TotalPending,
  isNull(Balance+(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail 
  where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0) as Balance ,'Invoice' as ListType from invoicemaster where active=1 and SupplierID=".$SupplierID." and InvoiceType in(4)
union all";*/
 $sql="select ROW_NUMBER() OVER (ORDER BY [ID])  as row_num,vm.VoucherID as InvoiceID,vd.ID as Checkbox,VoucherNo as KeyField ,VoucherDate as InvoiceDate,
VoucherDate as DeliveryDate,Credit as NetAmount,ReciveCurrency as TotalPaid,(Credit-ReciveCurrency) as TotalPending,CurrencyValue as Balance,'Voucher' as ListType  from 
VoucherDetails as vd  inner join VoucherMaster as vm on vm.VoucherID=vd.VoucherID and vd.CreditLedgerID=".$SupplierID." and vd.credit>0 and vd.credit<>vd.ReciveCurrency";
    }
    if($sql!="")
    {
    $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);  

    $data[]=$row; 
    }
  }
  //  print_r($data);
    echo json_encode($data);
  }//end else
  
  
  }
	if($_GET['action']=="GetPurchaseInvoiceList")
	{
		$data=array();
	$SupplierID=(isset($_GET['SupplierID']) && is_numeric($_GET['SupplierID']))?$_GET['SupplierID']:0;

  if(isset($_GET['VoucherID']) && $_GET['VoucherID']>0 && $_GET['VoucherID']!="undefined")
  {
    $VoucherID=$_GET['VoucherID'];
  }
  else
  {
    $VoucherID=0;
  }
	$under=getnamesingle("accounts","under","COAID",$SupplierID,$connection);
	if($under==54)
	{

		$data=array();
	$SupplierID=(isset($_GET['SupplierID']) && is_numeric($_GET['SupplierID']))?$_GET['SupplierID']:0;
    if($VoucherID==0)
    {
		$sql="select ROW_NUMBER() OVER (ORDER BY [InvoiceID])  as row_num,InvoiceID,InvoiceID as Checkbox,KeyField,InvoiceDate,'' as DeliveryDate,NetAmount,isNull(Received,(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID])) as TotalPaid,
    (NetAmount-isNull(Received,(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID]))) as TotalPending,Balance,'Invoice' as ListType from SalesInvoiceMaster as InvoiceMaster where active=1 and  CustomerID=".$SupplierID." and InvoiceType in(3,8) and GodownID>0 and (NetAmount-isNull(Received,0))>0";
		}
    else
    {
      if($_GET['Cycle']=="PURCHASE")
     {
 $sql="select ROW_NUMBER() OVER (ORDER BY [InvoiceID])  as row_num,InvoiceID,InvoiceID as Checkbox,
KeyField,InvoiceDate,DeliveryDate,NetAmount,
isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0)
-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0)as TotalPaid,
(NetAmount-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0))
+(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID]) as TotalPending,
  (Balance+(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail 
  where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID])) as Balance,'Invoice' as ListType from invoicemaster
   where SupplierID=$SupplierID and InvoiceType in(4) and active=1 and  GodownID>0";

      }
    else
    {
echo $sql="select ROW_NUMBER() OVER (ORDER BY [InvoiceID])  as row_num,InvoiceID,InvoiceID as Checkbox,
KeyField,InvoiceDate,DeliveryDate,NetAmount,
isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0)
-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0)as TotalPaid,
(NetAmount-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0))
+(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID]) as TotalPending,
  (Balance+(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail 
  where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID])) as Balance,'Invoice' as ListType from invoicemaster
   where SupplierID=$SupplierID and InvoiceType in(4) and active=1 and  GodownID>0";
        }      
    }
    $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);	

		$data[]=$row;	
		}
	//	print_r($data);
		echo json_encode($data);

	
	}
	else
	{
    if(isset($_GET['Cycle']))
    {
if($_GET['Cycle']=="PURCHASE")
      {
        $VoucherTypeID=6;
    $sql="select ROW_NUMBER() OVER (ORDER BY [InvoiceID])  as row_num,InvoiceID,InvoiceID as Checkbox,KeyField,InvoiceDate,'' as DeliveryDate,NetAmount,convert(numeric(12,2),isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID] and SettlementType=$VoucherTypeID),0)
-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID] and SettlementType=$VoucherTypeID),0))as TotalPaid,
(NetAmount-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID] and SettlementType=$VoucherTypeID),0)) as TotalPending,
  isNull(Balance+(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail 
  where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID] and SettlementType=$VoucherTypeID),0) as Balance  from InvoiceMaster as InvoiceMaster where active=1 and SupplierID=".$SupplierID." and InvoiceType in(4)";
      }
   else{
     $sql="select ROW_NUMBER() OVER (ORDER BY [InvoiceID])  as row_num,InvoiceID,InvoiceID as Checkbox,KeyField,InvoiceDate,'' as DeliveryDate,NetAmount,convert(numeric,isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID] and SettlementType=$VoucherTypeID),0)
-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID] and SettlementType=$VoucherTypeID),0))as TotalPaid,
(NetAmount-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID] and SettlementType=$VoucherTypeID),0)) as TotalPending,
  isNull(Balance+(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail 
  where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID] and SettlementType=$VoucherTypeID),0) as Balance  from Salesinvoicemaster as InvoiceMaster where active=1 and CustomerID=".$SupplierID." and InvoiceType in(3)";
   }   
     } 
      else
      {
	 $sql="select ROW_NUMBER() OVER (ORDER BY [InvoiceID])  as row_num,InvoiceID,InvoiceID as Checkbox,KeyField,InvoiceDate,'' as DeliveryDate,NetAmount,convert(numeric,isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0)
-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0))as TotalPaid,
(NetAmount-isNull((select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0)) as TotalPending,
  isNull(Balance+(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail 
  where VoucherID=$VoucherID and ReferenceInvoiceID=InvoiceMaster.[InvoiceID]),0) as Balance  from Salesinvoicemaster as InvoiceMaster where active=1 and CustomerID=".$SupplierID." and InvoiceType in(3)";
    }

		$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);	

		$data[]=$row;	
		}
	//	print_r($data);
		echo json_encode($data);
	//}//end else
}
	}
		if($_GET['action']=="GetSalesInvoiceList")
	{
		$data=array();
	$SupplierID=(isset($_GET['SupplierID']) && is_numeric($_GET['SupplierID']))?$_GET['SupplierID']:0;
		$sql="select ROW_NUMBER() OVER (ORDER BY [InvoiceID])  as row_num,InvoiceID,InvoiceID as Checkbox,KeyField,InvoiceDate,DeliveryDate,NetAmount,Paid as TotalPaid,(NetAmount-Paid) as TotalPending,Balance from invoicemaster where SupplierID=".$SupplierID." and InvoiceType in(5,8)";
		$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);	

		$data[]=$row;	
		}
	//	print_r($data);
		echo json_encode($data);

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

      odbc_autocommit($connection, FALSE);
    //print_r($_POST);
    //$master=array_keys($_POST);
    $master=$_POST['master'];
    $mdata=json_decode($master);
  //  print_r($master);
  //  return;
    //$detail=array_values($_POST);
    $detail=$_POST['detail'];
    $detail=json_decode($detail);
 //   print_r($detail);
  //  return;
    /*$m=$master[0];
    $m="[".str_replace(",\"detail\":", "}]", $m);
     $mdata=json_decode($m);
    $mdata=$mdata[0];
*/
        $VoucherDate=(isset($mdata->VoucherDate) && $mdata->VoucherDate!="") ?str_replace("_000Z","",$mdata->VoucherDate):'';
        $ChequeDate=(isset($mdata->ChequeDate) && $mdata->ChequeDate!="")?str_replace("_000Z","",$mdata->ChequeDate):'';
        if($ChequeDate=='1899-12-31T20:18:48.000Z')$ChequeDate='';
        $Narration=(isset($mdata->Narration) && $mdata->Narration!="") ?$mdata->Narration:'';
        //$Narration=addslashes($Narration);
        $Narration=str_replace("'","&#39;",$Narration); 
        $Narration=htmlspecialchars($Narration);

        $TotalAmount=(isset($mdata->TotalAmount) && $mdata->TotalAmount!="") ? (double) $mdata->TotalAmount:0;
$VoucherTypeID=(isset($mdata->VoucherTypeID) && $mdata->VoucherTypeID!="") ?$mdata->VoucherTypeID:'';
            $ChequeNo=(isset($mdata->ChequeNo) && $mdata->ChequeNo!="") ?$mdata->ChequeNo:'';
            $DD=(isset($mdata->DD) && $mdata->DD!="") ?$mdata->DD:0;
            $PONO=(isset($mdata->PONO) && $mdata->PONO!="") ?$mdata->PONO:0;
            $TC=(isset($mdata->TC) && $mdata->TC!="") ?$mdata->TC:0;
$ClientBankAccountName=(isset($mdata->ClientBankAccountName) && $mdata->ClientBankAccountName!="") ?$mdata->ClientBankAccountName:'';
            $LedgerID=(isset($mdata->LedgerID) && $mdata->LedgerID!="") ?$mdata->LedgerID:0;
$AmountDebit=(isset($mdata->AmountDebit) && $mdata->AmountDebit!="") ?$mdata->AmountDebit:'0';
$AmountCredit=(isset($mdata->AmountCredit) && $mdata->AmountCredit!="") ?$mdata->AmountCredit:'0';
$LocationID=(isset($mdata->LocationID) && $mdata->LocationID!="") ?$mdata->LocationID:0;
$VoucherID=(isset($mdata->VoucherID) && $mdata->VoucherID!="") ?$mdata->VoucherID:0;
$LastModificationTimeStamp=(isset($mdata->LastModificationTimeStamp) && $mdata->LastModificationTimeStamp!="") ?$mdata->LastModificationTimeStamp:'';
$isAuto=(isset($mdata->isAuto) && $mdata->isAuto!="") ?$mdata->isAuto:0;
$referencevoucherid=(isset($mdata->referencevoucherid) && $mdata->referencevoucherid!="") ?$mdata->referencevoucherid:'0';
            $VoucherNo=(isset($mdata->VoucherNo) && $mdata->VoucherNo!="") ?$mdata->VoucherNo:'';
            $PassCode=(isset($mdata->PassCode) && $mdata->PassCode!="") ?$mdata->PassCode:'';
        if($VoucherID>0)
        {
          //update vouchermaster
    $sql="update vouchermaster set ChequeDate='$ChequeDate',VoucherDate='$VoucherDate',
            Narration='$Narration',
            TotalAmount=$TotalAmount,
            ChequeNo='$ChequeNo',
            DD='$DD',
            PONO='$PONO',
            TC='$TC',
            ClientBankAccountName='$ClientBankAccountName',
            LocationID=$LocationID,EditLog='".$_SESSION['UserName']."' where VoucherID=".$VoucherID;
     // return;
            odbc_exec($connection,$sql) or die(odbc_error().$sql);
        }
        else
        {
        if($VoucherTypeID==5)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=5",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
          $VoucherNo="RV-".$VoucherNo;
        }
        if($VoucherTypeID==6)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=6",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
          $VoucherNo="PV-".$VoucherNo;
        }
        if($VoucherTypeID==27)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=27",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
          $VoucherNo="AD-".$VoucherNo;
        }
        if($VoucherTypeID==7)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=7",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
          $VoucherNo="JV-".$VoucherNo;
        }
        if($VoucherTypeID==10)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=10",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
          $VoucherNo="PTC-".$VoucherNo;
        }
        $Posted=1;
  $VoucherID=getMaxId("vouchermaster","VoucherID",$connection)+1;
  //getMaxLocationID("vouchermaster","VoucherID","LocationID=1",$connection)+1;
      $sql="insert into vouchermaster (
      VoucherDate,
            ChequeDate,
            Active,
            PeriodId,
            Posted,
            Narration,
            TotalAmount,
            VoucherTypeID,
            ChequeNo,
            DD,
            PONO,
            TC,
            ClientBankAccountName,
            LedgerID,
            AmountDebit,
            AmountCredit,
            LocationID,
            VoucherID,
            isAuto,
            referencevoucherid,
            VoucherNo,CreateLog

    ) values(
            '$VoucherDate',
            '$ChequeDate',
            1,1,
            $Posted,
            '$Narration',
            $TotalAmount,
            $VoucherTypeID,
            '$ChequeNo',
            '$DD',
            '$PONO',
            '$TC',
            '$ClientBankAccountName',
            $LedgerID,
            $AmountDebit,
            $AmountCredit,
            $LocationID,
            $VoucherID,
            0,
            $referencevoucherid,
            '$VoucherNo','".$_SESSION['UserName']."'
      )";
      odbc_exec($connection,$sql) or die(odbc_error().$sql);
    }//end else code here 
    /*$d=($detail[0]);
    $d=array_keys($d);
    //print_r($d[0]);
    $vd= "[".substr($d[0],0,strpos($d[0], "InvoiceJson")-2)."}]"; 
    $vd=json_decode($vd);*/
  //  print_r($vd[0]);
    //delete previous voucher details 
    $vd=$detail;
    if(count($vd)>0)
    {
     // $VoucherDetailID=getnamewhere("")
    $sqldelete="delete from voucherdetails where VoucherID=".$VoucherID;
    odbc_exec($connection,$sqldelete);
    // insert for voucher details 
  for($a=0;$a<count($vd);$a++)
  { 
     if($vd[$a]->Flag=="D" || $vd[$a]->Flag=="d")
      continue;

    $CreditLedgerID=(isset($vd[$a]->CreditHeadID) && $vd[$a]->CreditHeadID!="")?$vd[$a]->CreditHeadID:0;
    $LedgerID=(isset($vd[$a]->DebitHeadID) && $vd[$a]->DebitHeadID!="")?$vd[$a]->DebitHeadID:0;
    $CostCenterID=(isset($vd[$a]->CostCenterID) && $vd[$a]->CostCenterID!="")?$vd[$a]->CostCenterID:0;
    $CostCenter=(isset($vd[$a]->CostCenter) && $vd[$a]->CostCenter!="")?$vd[$a]->CostCenter:0;
    $CreditCostCenterCOAID=(isset($vd[$a]->CreditRelatedCOAID) && $vd[$a]->CreditRelatedCOAID!="")?$vd[$a]->CreditRelatedCOAID:0;
    $DebitCostCenterID=(isset($vd[$a]->DebitCostCenterID) && $vd[$a]->DebitCostCenterID!="")?$vd[$a]->DebitCostCenterID:0;
    $DebitCostCenter=(isset($vd[$a]->DebitCostCenter) && $vd[$a]->DebitCostCenter!="")?$vd[$a]->DebitCostCenter:0;
    $DebitCostCenterCOAID=(isset($vd[$a]->DebitRelatedCOAID) && $vd[$a]->DebitRelatedCOAID!="")?$vd[$a]->DebitRelatedCOAID:0;
    $Narration=isset($vd[$a]->DetailNarration)?$vd[$a]->DetailNarration:'';
    $Narration=htmlspecialchars($Narration);
    $Narration=str_replace("'","&#39;",$Narration); 
$Picture1=(isset($vd[$a]->Picture1) && $vd[$a]->Picture1!="")?$vd[$a]->Picture1:'';
    $Picture2=(isset($vd[$a]->Picture2) && $vd[$a]->Picture2!="")?$vd[$a]->Picture2:'';

    $ChequeNo=(isset($vd[$a]->ChequeNo) && $vd[$a]->ChequeNo!="")?$vd[$a]->ChequeNo:'';
    $BankName=(isset($vd[$a]->BankName) && $vd[$a]->BankName!="")?$vd[$a]->BankName:'';
    $ChequeDate=(isset($vd[$a]->ChequeDate) && $vd[$a]->ChequeDate!="")?$vd[$a]->ChequeDate:'';

$PONO=(isset($vd[$a]->PONO) && $vd[$a]->PONO!="")?$vd[$a]->PONO:'';
$DD=(isset($vd[$a]->DD) && $vd[$a]->DD!="")?$vd[$a]->DD:'';
$TC=(isset($vd[$a]->TCNo) && $vd[$a]->TCNo!="")?$vd[$a]->TCNo:'';
    //$Narration=addslashes($Narration);
    $Amount=isset($vd[$a]->Amount)?$vd[$a]->Amount:0;
    
    $AmountCredit=isset($vd[$a]->AmountCredit)?$vd[$a]->AmountCredit:0;
    $AmountDebit=isset($vd[$a]->AmountDebit)?$vd[$a]->AmountDebit:0;

    $InvoiceJson=isset($vd[$a]->InvoiceJson)?$vd[$a]->InvoiceJson:'';
   // print_r($InvoiceJson);
    if(strlen($Picture1)>2 ||  strlen($Picture2)>2)
{
    $sql="insert into voucherdetails (
    CreditLedgerID,
    VoucherID, 
    LedgerID,
    ISDelete, 
    CostCenterID, 
    CreditCostCenterCOAID,
    DebitCostCenterID, 
    DebitCostCenterCOAID,
    Narration, 
    Debit,
    Credit,
    ChequeNo,
    InstrumentDate,
    PaymentType,
    Picture1,
    Picture2,
    PONO,
    DD,
    TC

) values(
  $CreditLedgerID,
    $VoucherID, 
    $LedgerID,
    0, 
    $CostCenterID, 
    $CreditCostCenterCOAID,
    $DebitCostCenterID, 
    $DebitCostCenterCOAID,
    '$Narration', 
    $AmountDebit,
    $AmountCredit,
    '".$ChequeNo."',
    '".$ChequeDate."',
    '".$BankName."',
    '".$Picture1."',
    '".$Picture2."',
    '".$PONO."',
    '".$DD."',
    '".$TC."'
  )";
}
else
{
      $sql="insert into voucherdetails (
    CreditLedgerID,
    VoucherID, 
    LedgerID,
    ISDelete, 
    CostCenterID, 
    CreditCostCenterCOAID,
    DebitCostCenterID, 
    DebitCostCenterCOAID,
    Narration, 
    Debit,
    Credit,
    ChequeNo,
    InstrumentDate,
    PaymentType,
    PONO,
    DD,
    TC

) values(
  $CreditLedgerID,
    $VoucherID, 
    $LedgerID,
    0, 
    $CostCenterID, 
    $CreditCostCenterCOAID,
    $DebitCostCenterID, 
    $DebitCostCenterCOAID,
    '$Narration', 
    $AmountDebit,
    $AmountCredit,
    '".$ChequeNo."',
    '".$ChequeDate."',
    '".$BankName."',
    '".$PONO."',
    '".$DD."',
    '".$TC."'
  )";
}
      
  
  odbc_exec($connection,$sql) or die(odbc_error().$sql);
  $VoucherDetailID=getMaxId("voucherdetails","ID",$connection);
  //update  invoice
  if($InvoiceJson!="")
  updateInvoice($InvoiceJson,$connection,$VoucherID,$VoucherDetailID,$VoucherTypeID);
  }//end for a 
    
    }//end details count
//    $res=array('status'=>"ok",'description'=>'Record Save Sucessfully');
  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');

}
    echo json_encode($res); 
  
  }
	if($_GET['action']=="InsertVoucher")
	{
      odbc_autocommit($connection, FALSE);
		//print_r($_POST);
		//$master=array_keys($_POST);
		$master=$_POST['master'];
		$mdata=json_decode($master);
	//	print_r($master);
	//	return;
    //$detail=array_values($_POST);
		$detail=$_POST['detail'];
		$detail=json_decode($detail);
		//print_r($detail);
		/*$m=$master[0];
		$m="[".str_replace(",\"detail\":", "}]", $m);
		 $mdata=json_decode($m);
		$mdata=$mdata[0];
*/
        $VoucherDate=(isset($mdata->VoucherDate) && $mdata->VoucherDate!="") ?str_replace("_000Z","",$mdata->VoucherDate):'';
        $ChequeDate=(isset($mdata->ChequeDate) && $mdata->ChequeDate!="")?str_replace("_000Z","",$mdata->ChequeDate):'';
        if($ChequeDate=='1899-12-31T20:18:48.000Z')$ChequeDate='';
        $Narration=(isset($mdata->Narration) && $mdata->Narration!="") ?$mdata->Narration:'';
        //$Narration=addslashes($Narration);
        $Narration=str_replace("'","&#39;",$Narration); 
        $Narration=htmlspecialchars($Narration);

        $TotalAmount=(isset($mdata->TotalAmount) && $mdata->TotalAmount!="") ? (double) $mdata->TotalAmount:0;
$VoucherTypeID=(isset($mdata->VoucherTypeID) && $mdata->VoucherTypeID!="") ?$mdata->VoucherTypeID:'';
            $ChequeNo=(isset($mdata->ChequeNo) && $mdata->ChequeNo!="") ?$mdata->ChequeNo:'';
            $DD=(isset($mdata->DD) && $mdata->DD!="") ?$mdata->DD:0;
            $PONO=(isset($mdata->PONO) && $mdata->PONO!="") ?$mdata->PONO:0;
            $TC=(isset($mdata->TC) && $mdata->TC!="") ?$mdata->TC:0;
$ClientBankAccountName=(isset($mdata->ClientBankAccountName) && $mdata->ClientBankAccountName!="") ?$mdata->ClientBankAccountName:'';
            $LedgerID=(isset($mdata->LedgerID) && $mdata->LedgerID!="") ?$mdata->LedgerID:'0';
$AmountDebit=(isset($mdata->AmountDebit) && $mdata->AmountDebit!="") ?$mdata->AmountDebit:'0';
$AmountCredit=(isset($mdata->AmountCredit) && $mdata->AmountCredit!="") ?$mdata->AmountCredit:'0';
$LocationID=(isset($mdata->LocationID) && $mdata->LocationID!="") ?$mdata->LocationID:0;
$VoucherID=(isset($mdata->VoucherID) && $mdata->VoucherID!="") ?$mdata->VoucherID:0;
$LastModificationTimeStamp=(isset($mdata->LastModificationTimeStamp) && $mdata->LastModificationTimeStamp!="") ?$mdata->LastModificationTimeStamp:'';
$isAuto=(isset($mdata->isAuto) && $mdata->isAuto!="") ?$mdata->isAuto:0;
$referencevoucherid=(isset($mdata->referencevoucherid) && $mdata->referencevoucherid!="") ?$mdata->referencevoucherid:'0';
            $VoucherNo=(isset($mdata->VoucherNo) && $mdata->VoucherNo!="") ?$mdata->VoucherNo:'';
            $PassCode=(isset($mdata->PassCode) && $mdata->PassCode!="") ?$mdata->PassCode:'';
       	if($VoucherID>0)
       	{
       		//update vouchermaster
    $sql="update vouchermaster set ChequeDate='$ChequeDate',VoucherDate='$VoucherDate',
            Narration='$Narration',
            TotalAmount=$TotalAmount,
            ChequeNo='$ChequeNo',
            DD='$DD',
            PONO='$PONO',
            TC='$TC',
            ClientBankAccountName='$ClientBankAccountName',
            LocationID=$LocationID,EditLog='".$_SESSION['UserName']."' where VoucherID=".$VoucherID;
     // return;
            odbc_exec($connection,$sql) or die(odbc_error().$sql);
       	}
       	else
       	{
       	if($VoucherTypeID==5)
       	{
       		$VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=5",$connection)+1;
       		$VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
       		$VoucherNo="RV-".$VoucherNo;
       	}
       	if($VoucherTypeID==6)
       	{
       		$VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=6",$connection)+1;
       		$VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
       		$VoucherNo="PV-".$VoucherNo;
       	}
       	if($VoucherTypeID==7)
       	{
       		$VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=7",$connection)+1;
       		$VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
       		$VoucherNo="JV-".$VoucherNo;
       	}
        if($VoucherTypeID==10)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=10",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
          $VoucherNo="PTC-".$VoucherNo;
        }
       	$Posted=0;
       	$VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$connection)+1;//getMaxId("vouchermaster","VoucherID",$connection)+1;
		  $sql="insert into vouchermaster (
			VoucherDate,
            ChequeDate,
            Active,
            PeriodId,
            Posted,
            Narration,
            TotalAmount,
            VoucherTypeID,
            ChequeNo,
            DD,
            PONO,
            TC,
            ClientBankAccountName,
            LedgerID,
            AmountDebit,
            AmountCredit,
            LocationID,
            VoucherID,
            isAuto,
            referencevoucherid,
            VoucherNo,CreateLog

		) values(
            '$VoucherDate',
            '$ChequeDate',
            1,1,
            $Posted,
            '$Narration',
            $TotalAmount,
            $VoucherTypeID,
            '$ChequeNo',
            '$DD',
            '$PONO',
            '$TC',
            '$ClientBankAccountName',
            $LedgerID,
            $AmountDebit,
            $AmountCredit,
            $LocationID,
            $VoucherID,
            0,
            $referencevoucherid,
            '$VoucherNo','".$_SESSION['UserName']."'
			)";
			odbc_exec($connection,$sql) or die(odbc_error().$sql);
		}//end else code here 
		/*$d=($detail[0]);
		$d=array_keys($d);
		//print_r($d[0]);
		$vd= "[".substr($d[0],0,strpos($d[0], "InvoiceJson")-2)."}]";	
		$vd=json_decode($vd);*/
	//	print_r($vd[0]);
		//delete previous voucher details 
		$vd=$detail;
		if(count($vd)>0)
		{
     // $VoucherDetailID=getnamewhere("")
		$sqldelete="delete from voucherdetails where VoucherID=".$VoucherID;
		odbc_exec($connection,$sqldelete);
		// insert for voucher details 
	for($a=0;$a<count($vd);$a++)
	{	
    $CreditLedgerID=isset($vd[$a]->CreditHeadID)?$vd[$a]->CreditHeadID:'';
    $LedgerID=isset($vd[$a]->DebitHeadID)?$vd[$a]->DebitHeadID:0;
    $CostCenterID=isset($vd[$a]->CostCenterID)?$vd[$a]->CostCenterID:0;
    $CostCenter=isset($vd[$a]->CostCenter)?$vd[$a]->CostCenter:'';
    $CreditCostCenterCOAID=isset($vd[$a]->CreditRelatedCOAID)?$vd[$a]->CreditRelatedCOAID:'';
    $DebitCostCenterID=isset($vd[$a]->DebitCostCenterID)?$vd[$a]->DebitCostCenterID:0;
    $DebitCostCenter=isset($vd[$a]->DebitCostCenter)?$vd[$a]->DebitCostCenter:0;
    $DebitCostCenterCOAID=isset($vd[$a]->DebitRelatedCOAID)?$vd[$a]->DebitRelatedCOAID:0;
    $Narration=isset($vd[$a]->DetailNarration)?$vd[$a]->DetailNarration:'';
    $Narration=htmlspecialchars($Narration);
    $Narration=str_replace("'","&#39;",$Narration); 

    //$Narration=addslashes($Narration);
    $Amount=isset($vd[$a]->Amount)?$vd[$a]->Amount:0;
    $InvoiceJson=isset($vd[$a]->InvoiceJson)?$vd[$a]->InvoiceJson:'';
   // print_r($InvoiceJson);
      $sql="insert into voucherdetails (
    CreditLedgerID,
    VoucherID, 
    LedgerID,
    ISDelete, 
    CostCenterID, 
    CreditCostCenterCOAID,
    DebitCostCenterID, 
    DebitCostCenterCOAID,
    Narration, 
    Debit,
    Credit

) values(
	$CreditLedgerID,
    $VoucherID, 
    $LedgerID,
    0, 
    $CostCenterID, 
    $CreditCostCenterCOAID,
    $DebitCostCenterID, 
    $DebitCostCenterCOAID,
    '$Narration', 
    $Amount,
    $Amount
	)";
	odbc_exec($connection,$sql) or die(odbc_error().$sql);
	$VoucherDetailID=getMaxId("voucherdetails","ID",$connection);
	//update  invoice
	if($InvoiceJson!="")
	updateInvoice($InvoiceJson,$connection,$VoucherID,$VoucherDetailID,$VoucherTypeID);
	}//end for a 
		
		}//end details count
//	  $res=array('status'=>"ok",'description'=>'Record Save Sucessfully');
	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');

}
  	echo json_encode($res);	
	}//end insert voucher 
   if($_GET['action']=="GetVoucherListOld")
  {

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

    
    $VoucherTypeID=$_GET['VoucherTypeID'];
    

    if(isset($_GET['VoucherNo']) && $_GET['VoucherNo']!="undefined")
    {
$VoucherNo="VoucherNo like '%".$_GET['VoucherNo']. "%' and ";
    }
    else
    {
      $VoucherNo="";
    }
    //

    if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
    {
      $LocationID=" LocationID=".$_GET['LocationID']." and ";
    }
    else
    {
      $LocationID="";
    }
    if(isset($_GET['ChequeNo']) && $_GET['ChequeNo']!="undefined" && $_GET['ChequeNo']!="")
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $ChequeNo=" ChequeNo like '%".$_GET['ChequeNo']."%' and ";
    }
    else
    {
      $ChequeNo="";
    }
    if(isset($_GET['DDNo']) && $_GET['DDNo']!="undefined" && $_GET['DDNo']!="")
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $DDNo=" DD like '%".$_GET['DDNo']."%' and ";
    }
    else
    {
      $DDNo="";
    }
    if(isset($_GET['PONo']) && $_GET['PONo']!="undefined" && $_GET['PONo']!="")
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $PONo=" PONo like '%".$_GET['PONo']."%' and ";
    }
    else
    {
      $PONo="";
    }

    if(isset($_GET['TotalAmount']) && $_GET['TotalAmount']!="undefined" && $_GET['TotalAmount']!="")
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $TotalAmount=" TotalAmount=".$_GET['TotalAmount']." and ";
    }
    else
    {
      $TotalAmount="";
    }
//
    if(isset($_GET['BankName']) && $_GET['BankName']!="undefined" && $_GET['BankName']!="")
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $BankName=" ClientBankAccountName like '%".$_GET['BankName']."%' and ";
    }
    else
    {
      $BankName="";
    }
        if(isset($_GET['TCNo']) && $_GET['TCNo']!="undefined" && $_GET['TCNo']!="")
    {
      //$COAID=" COAID=".$_GET['COAID']." and ";
      $TCNo=" TC like '%".$_GET['TCNo']."%' and ";
    }
    else
    {
      $TCNo="";
    }
    if(isset($_GET['VoucherDate']) && $_GET['VoucherDate']!="undefined" && $_GET['VoucherDate']!="") 
    {
      $date=" convert(date,VoucherDate) = '".$_GET['VoucherDate']."' and ";
    }
    else
    {
      // convert(date,VoucherDate) = '".Date('Y-m-d')."' and 
      if($VoucherNo!="" || $LocationID!="")
      {
    $date="";
      }
      else
      {
      $date="";// convert(date,VoucherDate) = '".Date('Y-m-d')."' and ";
    }
    } 
    //  
    //?$_GET['SupplierID']:;
  $searchbox="".$BankName."".$ChequeNo."".$LocationID."".$date."".$VoucherNo."".$TCNo."".$DDNo."".$PONo."".$TotalAmount;

     $sql=" select ROW_NUMBER() OVER (ORDER BY [VoucherID])  as row_num,VoucherID,convert(Date,VoucherDate) as VoucherDate,Narration,VoucherNo,convert(numeric(9,2),TotalAmount) as TotalAmount,ChequeNo,PONo,DD,TC,ClientBankAccountName,LocationID,Godowns.Name as Location,'' as col_Action ,'' as CreateByUserName
    from vouchermaster 
    Inner join Godowns on vouchermaster.locationid=godowns.GodownID
    where $searchbox vouchermaster.active=1 and VoucherTypeID in(".$VoucherTypeID.")";
    $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      $permission=userrights($Userid,$SideBarID,'[Alter]',$connection);
          if($permission==1)
          {
      $editdata=' <i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editMaster(this);"></i> &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;';
          }
          else
          {
            $editdata="";
          }
          $permission=userrights($Userid,$SideBarID,'[Delete]',$connection);
          if($permission==1)
          {
              $deldata=' &nbsp;&nbsp;&nbsp; <i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteMaster(this);"></i> &nbsp;&nbsp;&nbsp;';
          }
          else
          {
            $deldata='';
          }
  $permission=userrights($Userid,$SideBarID,'[Print]',$connection);
        if($permission==1)
        {
$row['col_Action']='&nbsp;<i class="fa fa-print fa-lg" style="text-align: right;color: green;cursor:pointer;" onclick="javascript:printMaster(this,'.$row["VoucherID"].','.$row["LocationID"].');"></i>';
        }
        else
        {

    //  $row['col_Action']='&nbsp;';
        }
     $row['col_Action']=$row['col_Action'].$deldata.$editdata;
      /*foreach ($row as $key => $value) {
        # code...
        $row[$key]=utf8_encode($value);
      }*/
    $data[]=$row; 
    }//end while
    //}//end while
  }//end permission
  //  print_r($data);
    echo json_encode($data);

  
  
  }
}//end action 

function updateInvoice($InvoiceJson,$connection,$VoucherID,$VoucherDetailID,$VoucherTypeID)
{
  if(is_numeric($VoucherID))
  {
    odbc_autocommit($connection, FALSE);
  
	//$jsondata= substr($d[0],strpos($d[0], "InvoiceJson"),strlen($d[0]));
		//$jsondata=str_replace("InvoiceJson\":\"[", "", $jsondata);
		//$dt=json_decode($jsondata);
		$jsondata= $InvoiceJson;
		//print_r($jsondata);
		$jd=json_decode($jsondata);
 //       print_r($jd);

      if(is_array($jd))
      {
		for($a=0;$a<count($jd);$a++)
		{/*
			$Paid=isset($jd[$a]->Paid)?$jd[$a]->Paid:0;
			$Balance=isset($jd[$a]->Balance)?$jd[$a]->Balance:0;
			$InvoiceID=isset($jd[$a]->InvoiceID)?$jd[$a]->InvoiceID:0;
			$Amount=isset($jd[$a]->Amount)?$jd[$a]->Amount:0;
			   $sql="delete from VoucherDetails_InvoiceDetail where VoucherID=".$VoucherID." and ReferenceInvoiceID=".$InvoiceID;
    odbc_exec($connection,$sql);

					$sql="insert into  VoucherDetails_InvoiceDetail([VoucherID]
      ,[VoucherDetailID]
      ,[ReferenceInvoiceID]
      ,[InvoiceTotalAmount]
      ,[InvoicePaidAmount]
      ,[InvoiceBalance]) 
      values($VoucherID
      ,$VoucherDetailID
      ,$InvoiceID
      ,$Amount
      ,$Paid
      ,$Balance)";
      					odbc_exec($connection,$sql);

$updatesql="update Invoicemaster set Paid=(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=$InvoiceID),Balance=$Balance where InvoiceID=".$InvoiceID;
          odbc_exec($connection,$updatesql);

		*/

      $ListType=isset($jd[$a]->ListType)?$jd[$a]->ListType:"Invoice";
      if($ListType=="Invoice")
      {
            $VID=isset($jd[$a]->InvoiceID)?$jd[$a]->InvoiceID:0;

      $Paid=isset($jd[$a]->Paid)?$jd[$a]->Paid:0;
      $Balance=isset($jd[$a]->Balance)?$jd[$a]->Balance:0;
      $InvoiceID=isset($jd[$a]->InvoiceID)?$jd[$a]->InvoiceID:0;
      $Amount=isset($jd[$a]->Amount)?$jd[$a]->Amount:0;
         $sql="delete from VoucherDetails_InvoiceDetail where VoucherID=".$VoucherID." and ReferenceInvoiceID=".$InvoiceID;
    odbc_exec($connection,$sql);

          $sql="insert into  VoucherDetails_InvoiceDetail([VoucherID]
      ,[VoucherDetailID]
      ,[ReferenceInvoiceID]
      ,[InvoiceTotalAmount]
      ,[InvoicePaidAmount]
      ,[InvoiceBalance],SettlementType) 
      values($VoucherID
      ,$VoucherDetailID
      ,$InvoiceID
      ,$Amount
      ,$Paid
      ,$Balance,$VoucherTypeID)";
                odbc_exec($connection,$sql);
if($VoucherTypeID==5)
{
$updatesql="update SalesInvoicemaster set Received=(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=$InvoiceID),Balance=$Balance where InvoiceID=".$InvoiceID;
          odbc_exec($connection,$updatesql);
}
else if($VoucherTypeID==6)
{
$updatesql="update Invoicemaster set Paid=(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=$InvoiceID),Balance=$Balance where InvoiceID=".$InvoiceID;
          odbc_exec($connection,$updatesql);          
 }
        }
       if($ListType=="Voucher")
      {
        $Paid=isset($jd[$a]->Paid)?$jd[$a]->Paid:0;
      $Balance=isset($jd[$a]->Balance)?$jd[$a]->Balance:0;
      $ReferenceInvoiceID=isset($jd[$a]->InvoiceID)?$jd[$a]->InvoiceID:0;
      $VID=isset($jd[$a]->InvoiceID)?$jd[$a]->Checkbox:0;
      $Amount=isset($jd[$a]->Amount)?$jd[$a]->Amount:0;
         $sql="delete from VoucherDetails_InvoiceDetail where VoucherID=".$VoucherID."";
    //odbc_exec($connection,$sql);

         $sql="insert into  VoucherDetails_InvoiceDetail([VoucherID]
      ,[VoucherDetailID]
      ,[ReferenceInvoiceID]
      ,[InvoiceTotalAmount]
      ,[InvoicePaidAmount]
      ,[InvoiceBalance],SettlementType) 
      values($ReferenceInvoiceID
      ,$VID
      ,$VoucherID
      ,$Amount
      ,$Paid
      ,$Balance,$VoucherTypeID)";
                odbc_exec($connection,$sql) or die(odbc_error().$sql);
                  $updatesql="update VoucherDetails set ReciveCurrency=(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where Voucherid=".$ReferenceInvoiceID."),CurrencyValue=".$Balance." where ID=".$VID;
          odbc_exec($connection,$updatesql) or die(odbc_error().$updatesql);
      } 
    
    }//end for 
      }
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');

}
}
else
{
        $res=array('status'=>"Error",'description'=>'Please Select Voucher');

}
return $res;
}
function updateInvoice1($InvoiceJson,$connection,$VoucherID,$VoucherDetailID)
{
  if(is_numeric($VoucherID))
  {
    odbc_autocommit($connection, FALSE);
  
  //$jsondata= substr($d[0],strpos($d[0], "InvoiceJson"),strlen($d[0]));
    //$jsondata=str_replace("InvoiceJson\":\"[", "", $jsondata);
    //$dt=json_decode($jsondata);
    $jsondata= $InvoiceJson;
    //print_r($jsondata);
    $jd=json_decode($jsondata);
 //       print_r($jd);
$SettlementID=getmaxId("VoucherDetails_InvoiceDetail","SettlementID",$connection)+1;
$where=""; 
$SDate=Date("Y-m-d H:i:s");
       //     $KeyField=generateCode("VoucherDetails_InvoiceDetail","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            
            $KeyField2=str_pad($SettlementID,5,"0",STR_PAD_LEFT);
            $KeyField="STL-".$KeyField2;
       
      if(is_array($jd))
      {
    for($a=0;$a<count($jd);$a++)
    {/*
      $Paid=isset($jd[$a]->Paid)?$jd[$a]->Paid:0;
      $Balance=isset($jd[$a]->Balance)?$jd[$a]->Balance:0;
      $InvoiceID=isset($jd[$a]->InvoiceID)?$jd[$a]->InvoiceID:0;
      $Amount=isset($jd[$a]->Amount)?$jd[$a]->Amount:0;
         $sql="delete from VoucherDetails_InvoiceDetail where VoucherID=".$VoucherID." and ReferenceInvoiceID=".$InvoiceID;
    odbc_exec($connection,$sql);

          $sql="insert into  VoucherDetails_InvoiceDetail([VoucherID]
      ,[VoucherDetailID]
      ,[ReferenceInvoiceID]
      ,[InvoiceTotalAmount]
      ,[InvoicePaidAmount]
      ,[InvoiceBalance]) 
      values($VoucherID
      ,$VoucherDetailID
      ,$InvoiceID
      ,$Amount
      ,$Paid
      ,$Balance)";
                odbc_exec($connection,$sql);

$updatesql="update Invoicemaster set Paid=(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=$InvoiceID),Balance=$Balance where InvoiceID=".$InvoiceID;
          odbc_exec($connection,$updatesql);

    */

      $ListType=isset($jd[$a]->ListType)?$jd[$a]->ListType:"";
      if($ListType=="Invoice")
      {
            $VID=isset($jd[$a]->InvoiceID)?$jd[$a]->Checkbox:0;

      $Paid=isset($jd[$a]->Paid)?$jd[$a]->Paid:0;
      $Balance=isset($jd[$a]->Balance)?$jd[$a]->Balance:0;
      $InvoiceID=isset($jd[$a]->InvoiceID)?$jd[$a]->InvoiceID:0;
      $Amount=isset($jd[$a]->Amount)?$jd[$a]->Amount:0;
         $sql="delete from VoucherDetails_InvoiceDetail where VoucherID=".$VoucherID." and ReferenceInvoiceID=".$InvoiceID;
    odbc_exec($connection,$sql);

          $sql="insert into  VoucherDetails_InvoiceDetail([VoucherID]
      ,[VoucherDetailID]
      ,[ReferenceInvoiceID]
      ,[InvoiceTotalAmount]
      ,[InvoicePaidAmount]
      ,[InvoiceBalance]) 
      values($VoucherID
      ,$VoucherDetailID
      ,$InvoiceID
      ,$Amount
      ,$Paid
      ,$Balance)";
                odbc_exec($connection,$sql);

$updatesql="update Invoicemaster set TotalFreightByAmount=(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where ReferenceInvoiceID=$InvoiceID),Balance=$Balance where InvoiceID=".$InvoiceID;
          odbc_exec($connection,$updatesql);
        }
       if($ListType=="Voucher")
      {
        $Paid=isset($jd[$a]->Paid)?$jd[$a]->Paid:0;
      $Balance=isset($jd[$a]->Balance)?$jd[$a]->Balance:0;
      $ReferenceInvoiceID=isset($jd[$a]->InvoiceID)?$jd[$a]->InvoiceID:0;
      $VID=isset($jd[$a]->InvoiceID)?$jd[$a]->Checkbox:0;
      $Amount=isset($jd[$a]->Amount)?$jd[$a]->Amount:0;

         $sql="delete from VoucherDetails_InvoiceDetail where VoucherID=".$VoucherID."";
    //odbc_exec($connection,$sql);

         $sql="insert into  VoucherDetails_InvoiceDetail([VoucherID]
      ,[VoucherDetailID]
      ,[ReferenceInvoiceID]
      ,[InvoiceTotalAmount]
      ,[InvoicePaidAmount]
      ,[InvoiceBalance],CreateLog,SettlementID,KeyField,SDate) 
      values($ReferenceInvoiceID
      ,$VID
      ,$VoucherID
      ,$Amount
      ,$Paid
      ,$Balance,'".$_SESSION['UserName']."',".$SettlementID.",'".$KeyField."','".$SDate."')";

                odbc_exec($connection,$sql) or die(odbc_error().$sql);
                  $updatesql="update VoucherDetails set ReciveCurrency=(select sum(InvoicePaidAmount) from VoucherDetails_InvoiceDetail where Voucherid=".$ReferenceInvoiceID."),CurrencyValue=".$Balance." where ID=".$VID;
          odbc_exec($connection,$updatesql) or die(odbc_error().$updatesql);
      } 
    
    }//end for 
      }
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');

}
}
else
{
        $res=array('status'=>"Error",'description'=>'Please Select Voucher');

}
return $res;
}
?>