<?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'];
}
/*
odbc_autocommit($conn, FALSE);

if (!odbc_error())
      odbc_commit($conn);
else
      odbc_rollback($conn);

*/
if(isset($_GET['action']))
{
	$data=array();
	$ProductBaseType=$_GET['ProductBaseType'];

	$InvoiceID=0;

	if($_GET['action']=="DeletePurchaseInvoice")
	{
		//odbc_autocommit($connection,FALSE);
		odbc_autocommit($connection, FALSE);
			$InvoiceID=$_GET['InvoiceID'];	
			$CurrentInvoiceTypeID=$_GET['CurrentInvoiceTypeID'];

			        //$InvoiceID=$_GET['InvoiceID'];
        $sql="update InvoiceMaster set Active=0 where InvoiceID=".$InvoiceID;
        odbc_exec($connection,$sql);

        $sql="update invoiceDetail set IsDelete=1 where InvoiceID=".$InvoiceID;
        odbc_exec($connection,$sql);

        if($CurrentInvoiceTypeID==6)
        {
        	
        }

        //delete Voucher and Stock 
        $sql="update VoucherMaster set Active=0 where ReferenceInvoiceID=".$InvoiceID;
        odbc_exec($connection,$sql);

        $sql="delete from voucherdetails  where ReferenceInvoiceID=".$InvoiceID;
        odbc_exec($connection,$sql);

        $sql="delete from StockLedger  where InvoiceTypeID=".$CurrentInvoiceTypeID." and  InvoiceID=".$InvoiceID;
        odbc_exec($connection,$sql);
        //end code 
	 if (!odbc_error())
	 {
      odbc_commit($connection);
	    $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
	}
else
{
      odbc_rollback($connection);
	    $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

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

		$data=array();
		//odbc_autocommit($connection, FALSE);

		$InvoiceType=$_GET['InvoiceType'];
		$data=array();
		$searchbox="";
if(isset($_GET['SupplierID']) && is_numeric($_GET['SupplierID']))
		{
$SupplierID="SupplierID=".$_GET['SupplierID']. " and ";
		}
		else
		{
			$SupplierID="";
		}
		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=" TransDate 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['DepartmentID']) && $_GET['DepartmentID']!="undefined" && $_GET['DepartmentID']!="" && $_GET['DepartmentID']>0)
		{
			$DepartmentID="DepartmentID=".$_GET['DepartmentID']." and ";
		}
		else
		{
			$DepartmentID="";
		}
		
		if(isset($_GET['COAID']) && $_GET['COAID']!="undefined" && $_GET['COAID']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$COAID=" ItemID=".$_GET['COAID']." and ";
		}
		else
		{
			$COAID="";
		}	
		//?$_GET['SupplierID']:;
	$searchbox="".$SupplierID."".$COAID."".$LocationID."".$date."".$VoucherNo."".$DepartmentID;		
$searchboxopen="".$SupplierID."".$COAID."".$LocationID."".$VoucherNo."".$DepartmentID;		
	/*$sqlopening="select sum(qty),GodownID,Name,ItemID from viewStockLedger where $searchbox 1=1
group by GodownID,Name,ItemID";
	$resultopening=odbc_exec($connection, $sqlopening) or die(odbc_error().$sqlopening);
  while ($rowopening = odbc_fetch_array($resultopening)) {
	foreach($rowopening as $key=>$value)
	{	
		$rowopening[$key]=utf8_encode($value);
  	}//end while
  	$rowopening['InvoiceDate']=str_replace('00:00:00.000','',$_GET['startdate']) ;
	$data[]=$rowopening;
  		 
	}*/
	/*if($_GET['startdate']<Date("Y-m-d") && $_GET['startdate']!="")
	$sql="select (select sum(qty) from viewStockLedger vsl where vsl.TransDate < '2022-02-01' and vsl.itemid=masterview.ItemID and vsl.GodownID=masterview.GodownID) as Opening,* from viewStockLedger as masterview where $searchbox 1=1 order by GodownID ";	
	else*/
	 //$sql="select 0 as Opening,* from viewStockLedger where $searchbox 1=1 order by GodownID ";
		if($_GET['startdate']<Date("Y-m-d") && $_GET['startdate']!="")
		{
$sql="select * from (
select * from (
select '' as Sender,ITEMID,sum(Qty) as Qty,0 as InvoiceTypeID,'Opening' as Reference,0 as InvoiceID,'Opening' as Remarks,GodownID,'".$_GET['startdate']."' as TransDate,
0 as Rate,Name,0 as StandardPrice2,Department,'' as UnitName from viewStockLedger where TransDate<'".$_GET['startdate']."' and $searchboxopen 1=1
group by GodownID,Name,ItemID,Department) ta
Union All 
select (select top 1 isnull(Department,'') as Sender from ViewStockLedger as vsl1 where vsl1.InvoiceID=ViewStockLedger.InvoiceID and vsl1.ID!=ViewStockLedger.ID and vsl1.itemID=ViewStockLedger.ItemID) as Sender,ITEMID,Qty,InvoiceTypeID,Reference,InvoiceID,Remarks,GodownID,TransDate,Rate,Name,StandardPrice2,Department,UnitName from
 viewStockLedger where  $searchbox 1=1) vsl
 order by GodownID,TransDate,InvoiceID";
}
else
{
	$sql="select 0 as Opening,* from viewStockLedger where $searchbox 1=1 order by GodownID ";
}
	$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);
  	}//end while
  	$row['InvoiceDate']=str_replace('00:00:00.000','', $row['TransDate']) ;
	$data[]=$row;
  		 
	}
echo json_encode($data);
	
	}
	if($_GET['action']=="PendingSupplies")
	{
		$InvoiceType=$_GET['InvoiceType'];
		$data=array();
		$searchbox="";
if(isset($_GET['SupplierID']) && is_numeric($_GET['SupplierID']))
		{
$SupplierID="SupplierID=".$_GET['SupplierID']. " and ";
		}
		else
		{
			$SupplierID="";
		}
		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=" InvoiceDate between '".$_GET['startdate']."' and '".$_GET['enddate']."' and ";
		}
		else
		{
			$date='';
		}	
		if(isset($_GET['LocationID']) && $_GET['LocationID']!="undefined" && $_GET['LocationID']!="" && $_GET['LocationID']>0)
		{
			$LocationID="CompanyID=".$_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 InvoiceID,Qty,ReceivedQty,ItemID,inv.Name as Product,inv.barcode as Barcode,cat.Name as Category,(select KeyField from invoicemaster where InvoiceMaster.InvoiceID=ids.InvoiceID) as KeyField,(select InvoiceDate from invoicemaster where InvoiceMaster.InvoiceID=ids.InvoiceID) as InvoiceDate,(select COAName from accounts where COAID =(select SupplierID from invoicemaster where InvoiceMaster.InvoiceID=ids.InvoiceID)) as SupplierName,(select Name from Godowns as g where g.GodownID=(select GodownID   from InvoiceMaster where InvoiceMaster.InvoiceMaster.ids.InvoiceID )) as  from InvoiceDetail as ids
inner join inventory as inv on inv.ID=ids.ItemID
inner join inventory as cat on cat.ID=inv.Under
where InvoiceID in (
select InvoiceID from invoicemaster where $searchbox  InvoiceType  in(100)	)";*/
	$sql="select * from view_list_pendingSupplies where $searchbox InvoiceType=$InvoiceType";	
   $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);
  	}//end while
	$data[]=$row;
  		 
	}
echo json_encode($data);
	}	
	if($_GET['action']=="ApproveRequestedItem")
	{
//		print_r($_POST);
//			echo  $_POST['ApprovalQty'];
		   		odbc_autocommit($connection, FALSE);	
	$ApprovalQty=$_POST['ApprovalQty'];
    $ApprovalRemarks=$_POST['ApprovalRemarks'];
    $TransactionID=$_POST['TransactionID'];
    $ItemID=$_POST['ItemID'];
    $InvoiceStatus=$_POST['InvoiceStatus'];
    $InvoiceID=$_POST['InvoiceID'];

    $updatesql="update invoicedetail set StockQty=".$ApprovalQty.",ApprovalRemarks='".$ApprovalRemarks."' where TransactionID=".$TransactionID." and ItemID=".$ItemID;
    odbc_exec($connection,$updatesql);

     $updateinvoice="update invoicemaster set InvoiceStatus=2 where invoiceid=$InvoiceID and not Exists (select * from InvoiceDetail where InvoiceID=$InvoiceID and StockQty is  null)";
odbc_exec($connection,$updateinvoice);
if (!odbc_error())
	 {
      odbc_commit($connection);
	    $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
	}
else
{
      odbc_rollback($connection);
	    $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

}
		echo json_encode($res);
  
			
	}
	if($_GET['action']=="GetMaterialRequestApproval")
	{
		$data=array();
		$InvoiceNo=$_GET['InvoiceNo'];
		$InvoiceType=$_GET['InvoiceType'];
		 $sql="   select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.Name as CompanyShortForm,InvoiceDate,i.KeyField as KeyField,'' as CreateByUserName,i.InvoiceID,DeliveryDate,i.Narration as Narration,g.Name as Department,g.godownid as supplier,c.Name as Location,InvoiceStatus,'' as col_Action ,inv.AdditionalInfo2 as ProductCode,Inv.Name as ItemName,d.narration as Specification,d.QTY as RequiredQty,d.ReceivedQty as ReceivedQty,d.StockQty as ApprovalQty,Inv.ID ItemID,d.TransactionID as TransactionID
   from InvoiceMaster as i left outer join godowns  as g on i.Shipperid=g.GodownID
   left outer join godowns as c on c.GodownID=i.GodownID
   left outer join invoicedetail as d on d.InvoiceID=i.InvoiceID
   left outer join Inventory as inv on inv.ID=d.ItemID
   where i.keyfield='".$InvoiceNo."' and InvoiceType=".$InvoiceType;
	$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  while ($row = odbc_fetch_array($result)) {
    	foreach ($row as $key => $value) {
    		# code...
    		$row[$key]=utf8_encode($value);
    	}
	$data[]=$row;
  		}//end while
  		
  		echo json_encode($data); 

	}
if($_GET['action']=="MRQApprove")
	{
		$data=array();
		$InvoiceType=$_GET['InvoiceType'];
if(isset($_GET['SupplierID']) && is_numeric($_GET['SupplierID']))
		{
$SupplierID="SupplierID=".$_GET['SupplierID']. " and ";
		}
		else
		{
			$SupplierID="";
		}
if(isset($_GET['ReferenceNo']) && $_GET['ReferenceNo']!="undefined" && $_GET['ReferenceNo']!="")
		{
$ReferenceNo="i.KeyField like '%".$_GET['ReferenceNo']. "%' and ";
		}
		else
		{
			$ReferenceNo="";
		}
		//
		if(isset($_GET['DeliveryDate']) && $_GET['DeliveryDate']!="undefined" && $_GET['DeliveryDate']!="")
		{
			$date=" convert(date,DeliveryDate) = '".$_GET['DeliveryDate']."' and ";
		}
		else
		{
			$date='';
		}	
		if(isset($_GET['GodownID']) && $_GET['GodownID']!="undefined" && $_GET['GodownID']!="" && $_GET['GodownID']>0)
		{
			$GodownID="i.GodownID=".$_GET['GodownID']." and ";
		}
		else
		{
			$GodownID="";
		}
		if(isset($_GET['BillDate']) && $_GET['BillDate']!="undefined" && $_GET['BillDate']!="")
		{
			//$COAID=" COAID=".$_GET['COAID']." and ";
			$BillDate=" convert(date,InvoiceDate)='".$_GET['BillDate']."' and ";
		}
		else
		{
			$BillDate="";
		}	
		//?$_GET['SupplierID']:;
	$searchbox="".$SupplierID."".$BillDate."".$GodownID."".$date."".$ReferenceNo;		
		 $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.Name as Company,c.AdditionalInfo1 as CompanyShortForm,InvoiceDate,i.KeyField as KeyField,'' as CreateByUserName,InvoiceID,DeliveryDate,Narration,g.Name as Department,g.godownid as supplier,c.godownid as godownid,InvoiceStatus,'' as col_Action 
   from InvoiceMaster as i left outer join godowns  as g on i.Shipperid=g.GodownID
   inner join godowns as c on c.GodownID=i.GodownID
   where $searchbox InvoiceType=".$InvoiceType." and InvoiceStatus=1";
	$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  while ($row = odbc_fetch_array($result)) {
      /*  $row['col_Action']='<i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editMaster(this,\''.$row["InvoiceID"].'\');"></i>&nbsp;&nbsp;&nbsp;  <i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteMaster(this,\''.$row["InvoiceID"].'\');"></i>';*/
       // $row['ItemName']=htmlspecialchars($row['ItemName']);
      //  $row['ProductCategoryName']=getnamesingle("inventory","Name","Under",$row['ProductCategoryName'],$connection);
      // $row['CompanyShortForm']=getnamesingle("Godowns","Keyfield","GodownID",$row['CompanyShortForm'],$connection);
       // $row['Code']=htmlentities($row['Code']);
	$data[]=$row;
  		}//end while
  		
  		echo json_encode($data); 

	}
	if($_GET['action']=='searchlist')
	{
		$data=array();
			// get searching parameters 
		$InvoiceType=$_GET['InvoiceType'];
			$SideBarID=$_GET['SideBarID'];		
	$permission=userrights($Userid,$SideBarID,'[Display]',$connection);
	if($permission==1)
	{
		if(isset($_GET['Company']) && trim($_GET['Company'])!="")
		{
		$Item=$_GET['Company'];
		$ItemName="c.Name like '%".$Item."%' and ";
		}
		else
		{
	$ItemName="";
		}
		if(isset($_GET['Department']) && trim($_GET['Department'])!="")
		{
		$ItemDepartment=$_GET['Department'];
		$Department="g.Name like '%".$ItemDepartment."%' and ";
		}
		else
		{
		$Department="";
		}
		if(isset($_GET['DeliveryDate']) && trim($_GET['DeliveryDate'])!="")
		{
		$ItemDeliveryDate=$_GET['DeliveryDate'];
		$DeliveryDate="convert(date,DeliveryDate) ='".$ItemDeliveryDate."' and ";
		}
		else
		{
		$DeliveryDate="";
		}
		
		if(isset($_GET['BillDate']) && trim($_GET['BillDate'])!="")
		{
		$ItemBillDate=$_GET['BillDate'];
		$BillDate="convert(date,InvoiceDate) ='".$ItemBillDate."' and ";
		}
		else
		{
		$BillDate="";
		}
		if(isset($_GET['AddtionalInfo5']) && trim($_GET['AddtionalInfo5'])!="")
		{
		$ItemAddtionalInfo5=$_GET['AddtionalInfo5'];
		$AddtionalInfo5="i.AddtionalInfo5 like '%".$ItemAddtionalInfo5."%' and ";
		}
		else
		{
		$AddtionalInfo5="";
		}
		if(isset($_GET['Code']) && trim($_GET['Code'])!="")
		{
		$ItemCode=$_GET['Code'];
		$Code="i.AdditionalInfo2 like '%".$ItemCode."%' and ";
		}
		else
		{
		$Code="";
		}
		if(isset($_GET['Keyfield']) && trim($_GET['Keyfield'])!="")
		{
		$ItemKeyfield=$_GET['Keyfield'];
		$Keyfield="i.keyfield like '%".$ItemKeyfield."%' and ";
		}
		else
		{
		$Keyfield="";
		}
		if(isset($_GET['ReferenceNo']) && trim($_GET['ReferenceNo'])!="")
		{
		$ItemKeyfield=$_GET['ReferenceNo'];
		$Keyfield="i.keyfield like '%".$ItemKeyfield."%' and ";
		}
		else
		{
		$Keyfield="";
		}
			
		if(isset($_GET['supplier']) && trim($_GET['supplier'])!="")
		{
		$Itemsupplier=$_GET['supplier'];
		$supplier="i.supplier like '%".$Itemsupplier."%' and ";
		}
		else
		{
		$supplier="";
		}
		
		$searchbox=$ItemName."".$Department."".$DeliveryDate."".$AddtionalInfo5."".$Code."".$Keyfield."".$BillDate;

		/*if(!isset($_GET['all']))*/
		if($_SESSION['UserName']=="admin" || $_SESSION['UserName']=="ADMIN")
			   $sql="  select ROW_NUMBER() OVER (
            ORDER BY [InvoiceType]
   ) row_num,c.Name as Location,convert(date,InvoiceDate) as InvoiceDate,i.KeyField as KeyField,i.CreateLog as CreateByUserName,InvoiceID,DeliveryDate,Narration,g.Name as Department,InvoiceID,InvoiceStatus,(
   case when InvoiceStatus=1 then 'PENDING' when  InvoiceStatus=2 then 'ACCEPTED'   when InvoiceStatus=3 then 'REJECTED'  when InvoiceStatus=4 then 'CLOSED' end ) as OrderStatus,'' as col_Action,InvoiceDate,i.CreateLog as CreateLog 
   from InvoiceMaster as i left outer join godowns  as g on i.Shipperid=g.GodownID
   inner join godowns as c on c.GodownID=i.GodownID
   where ".$searchbox." InvoiceType=".$InvoiceType." order by i.KeyField ";
   else
    $sql="  select ROW_NUMBER() OVER (
            ORDER BY [InvoiceType]
   ) row_num,c.Name as Company,c.AdditionalInfo1 as Location,convert(date,InvoiceDate) as InvoiceDate,i.KeyField as KeyField,'' as CreateByUserName,InvoiceID,DeliveryDate,Narration,g.Name as Department,InvoiceID,InvoiceStatus,(
   case when InvoiceStatus=1 then 'PENDING' when  InvoiceStatus=2 then 'ACCEPTED'   when InvoiceStatus=3 then 'REJECTED'  when InvoiceStatus=4 then 'CLOSED' end ) as OrderStatus,'' as col_Action,InvoiceDate 
   from InvoiceMaster as i left outer join godowns  as g on i.Shipperid=g.GodownID
   inner join godowns as c on c.GodownID=i.GodownID
   where ".$searchbox." InvoiceType=".$InvoiceType." and i.CreateLog='".$_SESSION['UserName']."' order by i.KeyField";	
		
   $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,\''.$row["InvoiceID"].'\');"></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,\''.$row["InvoiceID"].'\');"></i>';
				}
				 else
  {
$deldata='';
  }

  //check invoice status 
 if($row["InvoiceStatus"]==1)
 {
        $row['col_Action']=''.$editdata.'&nbsp;&nbsp;&nbsp; '.$deldata;
 }
 else
{
	$printdata='<i class="fa fa-print-o fa-lg" style="text-align: right;color: green;cursor:pointer;" onclick="javascript:printMaster(this,\''.$row["InvoiceID"].'\');"></i>';

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

	}//end search list 

	if($_GET['action']=="MRQLIST")
	{
	$data=array();
	$InvoiceType=$_GET['InvoiceType'];
	$SideBarID=$_GET['SideBarID'];		
	$permission=userrights($Userid,$SideBarID,'[Display]',$connection);
	if($permission==1)
	{
		if(isset($_GET['InvoiceID']))
		{
			$InvoiceID=$_GET['InvoiceID'];
/*	  $sql="  select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.Name as CompanyShortForm,invoicedate,i.KeyField as keyfield,'' as CreateByUserName,invoiceid,deliverydate,narration,g.Name as Department,g.godownid as supplier,c.godownid as godownid,InvoiceStatus,'' as col_Action ,billno,totalamount,discountamount,totaltaxamount as taxamount,netamount,shippingmethod,ispriceinclusivetax,ispriceperunit,vatoption,ReferenceInvoiceID,(select Keyfield from InvoiceMaster as im where im.InvoiceID=i.ReferenceInvoiceID) as ReferenceInvoiceNo,PurchaseLedgerID,VATLedgerID,i.SupplierID as supplierid
   from InvoiceMaster as i left outer join godowns  as g on i.Shipperid=g.GodownID
   inner join godowns as c on c.GodownID=i.GodownID
   where InvoiceType=".$InvoiceType." and InvoiceID=$InvoiceID";*/
   if($_SESSION['UserName']=="admin" || $_SESSION['UserName']=="Admin")
 $sql="select * from view_MRQ_LIST where InvoiceType=".$InvoiceType." and active=1 and InvoiceID=".$InvoiceID;
else
 $sql="select * from view_MRQ_LIST where InvoiceType=".$InvoiceType." and active=1 and InvoiceID=".$InvoiceID." and CreateLog='".$_SESSION['UserName']."' order by invoiceid desc";
   $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  while ($row = odbc_fetch_array($result)) {
  	if($row['InvoiceStatus']==1 && $_SESSION['UserName']==$row['CreateLog'])
  	{
        $row['col_Action']='<i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editMaster(this,\''.$row["invoiceid"].'\');"></i>&nbsp;&nbsp;&nbsp;  <i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteMaster(this,\''.$row["invoiceid"].'\');"></i>&nbsp;<i class="fa fa-print fa-lg" style="text-align: left;color: green;cursor:pointer;" onclick="javascript:printMaster(this,'.$row["godownid"].',
        '.$row["invoiceid"].'\');"></i>';
        //$row['Notes']=htmlspecialchars($row['Notes']);
       $row['Notes']=utf8_decode($row['Notes']); 
      //  $row['ProductCategoryName']=getnamesingle("inventory","Name","Under",$row['ProductCategoryName'],$connection);
      // $row['CompanyShortForm']=getnamesingle("Godowns","Keyfield","GodownID",$row['CompanyShortForm'],$connection);
       // $row['Code']=htmlentities($row['Code']);
    
  		}
  		else
  		{
 $row['col_Action']='&nbsp;<i class="fa fa-print fa-lg" style="text-align: left;color: green;cursor:pointer;" onclick="javascript:printMaster(this,'.$row["godownid"].',
        '.$row["invoiceid"].'\');"></i>';        
//$InvoiceID="";
    	}
    	    foreach ($row as $key => $value) {
        	# code...
        	$row[$key]=utf8_encode($value);
        }
    $data ['allinvoice'][]=$row;
  		}//end while

   if($InvoiceID!="")
  	{
  	  $sql="   select i.ID as itemid,i.name as itemname,i.barcode as barcode,cast(d.unitprice as numeric(7,2)) as unitprice,qty,amount,cast(d.vatpercent as numeric(7,2)) as vatpercent,cast(VATAmount as numeric(7,2)) as vatamount,cast(discountpercent as numeric(7,2)) as discountpercent,cast(discountamount as numeric(7,2)) as discountamount,'' as partnumber ,d.Attr1 as specification,(select ide.Name from inventory as ide where  ide.ID=i.under) as category,d.Attr2 as partnumber,netamount,d.Attr3 as JobCardItem,d.Attr4 as Attr4,
   ReferenceInvoiceID,ReferenceTransactionID,d.[guid] as guid,ParentGUid as referenceguid,
   d.Narration as detailnarration,transactionid,d.StockQty as StockQty,d.itemjson as itemjson,
    i.keyfield as itemkeyfield,i.AdditionalInfo2 as code,Make as brand,Rating as color,Model as size  from invoiceDetail as d left outer join inventory as i on i.ID=d.ItemID
   
   where InvoiceID=".$InvoiceID;
  		 $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  			while ($row = odbc_fetch_array($result)) {
  				  foreach ($row as $key => $value) {
        	# code...
        	$row[$key]=utf8_encode($value);
        }
  		$data['detailitems'][]=$row;
  							}//end while
  	}//end if invoice id 
		echo json_encode($data); 

		}
		else
		{
if(isset($_GET['Company']) && trim($_GET['Company'])!="")
		{
		$Item=$_GET['Company'];
		$ItemName="c.Name like '%".$Item."%' and ";
		}
		else
		{
	$ItemName="";
		}
		if(isset($_GET['Department']) && trim($_GET['Department'])!="" && $_GET['Department']!="1")
		{
		$ItemDepartment=$_GET['Department'];
		$Department="g.Name like '%".$ItemDepartment."%' and ";
		}
		else
		{
		$Department="";
		}
		if(isset($_GET['DeliveryDate']) && trim($_GET['DeliveryDate'])!="")
		{
		$ItemDeliveryDate=$_GET['DeliveryDate'];
		$DeliveryDate="convert(date,DeliveryDate) ='".$ItemDeliveryDate."' and ";
		}
		else
		{
		$DeliveryDate="";
		}
		
		if(isset($_GET['BillDate']) && trim($_GET['BillDate'])!="")
		{
		$ItemBillDate=$_GET['BillDate'];
		$BillDate="convert(date,InvoiceDate) ='".$ItemBillDate."' and ";
		}
		else
		{
				if($_GET['Department']=="1")
				$BillDate="";
					else
				{
           date_default_timezone_set("Asia/Muscat");
         /*  	if($InvoiceType==4)
$BillDate="";           		
           	else	*/
		$BillDate=" InvoiceDate='".Date("Y-m-d")."' and ";
        //  $BillDate="InvoiceDate>=DATEADD(month, -1, GETDATE()) and ";
				}
		}
		if(isset($_GET['AddtionalInfo5']) && trim($_GET['AddtionalInfo5'])!="")
		{
		$ItemAddtionalInfo5=$_GET['AddtionalInfo5'];
		$AddtionalInfo5="i.AddtionalInfo5 like '%".$ItemAddtionalInfo5."%' and ";
		}
		else
		{
		$AddtionalInfo5="";
		}
		if(isset($_GET['Code']) && trim($_GET['Code'])!="")
		{
		$ItemCode=$_GET['Code'];
		$Code="i.AdditionalInfo2 like '%".$ItemCode."%' and ";
		}
		else
		{
		$Code="";
		}
		if(isset($_GET['Keyfield']) && trim($_GET['Keyfield'])!="")
		{
		$ItemKeyfield=$_GET['Keyfield'];
		$Keyfield="keyfield like '%".$ItemKeyfield."%' and ";
		}
		else
		{
		$Keyfield="";
		}
		if(isset($_GET['ReferenceNo']) && trim($_GET['ReferenceNo'])!="")
		{
		$ItemKeyfield=$_GET['ReferenceNo'];
		$Keyfield="keyfield like '%".$ItemKeyfield."%' and ";
		}
		else
		{
		$Keyfield="";
		}
		if(isset($_GET['Narration']) && trim($_GET['Narration'])!="")
		{
		$Narration=$_GET['Narration'];
		$Narration="Narration like '%".$Narration."%' and ";
		}
		else
		{
		$Narration="";
		}
			
		if(isset($_GET['supplier']) && trim($_GET['supplier'])!="")
		{
		$Itemsupplier=$_GET['supplier'];
		$supplier="i.supplier like '%".$Itemsupplier."%' and ";
		}
		else
		{
		$supplier="";
		}
		
		$searchbox=$ItemName."".$Department."".$DeliveryDate."".$AddtionalInfo5."".$Code."".$Keyfield."".$BillDate.$Narration;
	 /* $sql="  select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.Name as CompanyShortForm,InvoiceDate,i.KeyField as KeyField,'' as CreateByUserName,InvoiceID,DeliveryDate,Narration,g.Name as Department,InvoiceID,InvoiceStatus,'' as col_Action,InvoiceDate ,c.godownid as godownid,totalamount,discountamount,totaltaxamount as taxamount,netamount
   from InvoiceMaster as i left outer join godowns  as g on i.Shipperid=g.GodownID
   inner join godowns as c on c.GodownID=i.GodownID
   where InvoiceType=".$InvoiceType;*/
   //echo "here";
   //if(isset($_GET['all']))
   if($_SESSION['UserName']=="admin" || $_SESSION['UserName']=="ADMIN")
		 $sql="select * from view_MRQ_LIST2 where $searchbox active=1 and  InvoiceType=".$InvoiceType;
	else
	$sql="select * from view_MRQ_LIST2 where $searchbox active=1 and  InvoiceType=".$InvoiceType;	
/*$sql="select * from view_MRQ_LIST2 where $searchbox active=1 and  InvoiceType=".$InvoiceType." and CreateLog='".$_SESSION['UserName']."'";*/

   $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  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,\''.$row["InvoiceID"].'\');"></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,\''.$row["InvoiceID"].'\');"></i>';
				}
else
{
	$deldata='';
}				
 	$permission=userrights($Userid,$SideBarID,'[Delete]',$connection);
				if($permission==1)
				{
$printdata='<i class="fa fa-print fa-lg" style="text-align: right;color: green;cursor:pointer;" onclick="javascript:printMaster(this,'.$row["godownid"].',\''.$row["InvoiceID"].'\');"></i>';
				}
else
{
	$printdata='';
}				
//
//
if($row['InvoiceStatus']==1)
        $row['col_Action']=''.$editdata.'&nbsp;&nbsp;&nbsp;'.$deldata.'  &nbsp;&nbsp;&nbsp;  '.$printdata;
else
        $row['col_Action']='&nbsp;&nbsp;&nbsp;'.$printdata;

       // $row['ItemName']=htmlspecialchars($row['ItemName']);
      //  $row['ProductCategoryName']=getnamesingle("inventory","Name","Under",$row['ProductCategoryName'],$connection);
      // $row['CompanyShortForm']=getnamesingle("Godowns","Keyfield","GodownID",$row['CompanyShortForm'],$connection);
       // $row['Code']=htmlentities($row['Code']);

	$InvoiceID=$row['InvoiceID'];
	//code for some changes HERE 
if($InvoiceID!="")
  	{
  	   $sql1="   select i.ID as itemid,i.name as itemname,i.barcode as barcode,cast(d.unitprice as numeric(7,2)) as unitprice,qty,amount,cast(d.vatpercent as numeric(7,2)) as vatpercent,cast(VATAmount as numeric(7,2)) as vatamount,cast(discountpercent as numeric(7,2)) as discountpercent,cast(discountamount as numeric(7,2)) as discountamount,'' as partnumber ,d.Attr1 as specification,(select ide.Name from inventory as ide where  ide.ID=i.under) as category,d.Attr2 as partnumber,netamount,d.Attr3 as JobCardItem,d.Attr4 as Attr4,
   ReferenceInvoiceID,ReferenceTransactionID,d.[guid] as guid,ParentGUid as referenceguid,
   d.Narration as detailnarration,transactionid,d.StockQty as StockQty,d.itemjson as itemjson,
    i.keyfield as itemkeyfield,i.AdditionalInfo2 as code,Make as brand,Rating as color,Model as size  from invoiceDetail as d left outer join inventory as i on i.ID=d.ItemID
   
   where InvoiceID=".$InvoiceID;
  		 $result1=odbc_exec($connection, $sql1) or die(odbc_error().$sql1);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  		 if(odbc_num_rows($result1)>0)
  		 {
  			while ($row1 = odbc_fetch_array($result1)) {
  				  foreach ($row1 as $key => $value) {
        	# code...
        	$row1[$key]=utf8_encode($value);
        }
  		$row['detailitems'][]=$row1;
  		}//end while
  			}//end if 
  			else
  			{
  			$row['detailitems']='';
  			}
	$data[]=$row;
  		
  		
  		}//end else 
  	}//end permission
  		// code ofr details
  		//print_r($data);
//	code for item search 
  		echo json_encode($data); 
  		}//end MRQ LIST
}
}
if($_GET['action']=="getitem_customer")
{
	


		if(isset($_GET['ID']))
		{
			$ID=$_GET['ID'];
$sql="select Name as ItemName,Under as ProductCategoryID,Barcode,AdditionalInfo2 as Code,Make as Brand,Rating as Color,Model as Size,CompanyID as CompanyID,'' as col_Action,ID,UnitID,Attr1,AdditionalInfo3,AdditionalInfo5,Barcode,cast(StandardPrice3 as numeric(7,2)) as CostPrice,cast(StandardPrice2 as numeric(7,2)) as WholeSalePrice,cast(StandardPrice1 as numeric(7,2)) as RetailPrice,cast(MinPriceLevel as numeric(7,2)) as MinPriceLevel,cast(CommisionPercent as numeric(7,2)) as CommisionPercent,cast(CommisionAmount as numeric(7,2)) as CommisionAmount,cast(MinQtyLevel as numeric(7,2)) as MinQtyLevel,cast(MaxQtyLevel as numeric(7,2)) as MaxQtyLevel,KeyField,ShowInPurchases,ShowInSales,IsFixedAsset,ShowInStock,IsNonStockAble,Details,LastModificationTimeStamp,cast(VATPercent as numeric(7,2)) as VATPercent,AdditionalInfo2,AdditionalInfo1 from inventory where ID=$ID";// offset $start rows fetch next $limit rows only";
		}
		else
		{
		$start=0;
		$limit=10;
		if(isset($_GET['ItemName']))
		{
		$Item=$_GET['ItemName'];
		$ItemName="i.Name like '%".$Item."%' and ";
		}
		else
		{
	$ItemName="";
		}
		if(isset($_GET['Barcode']) && trim($_GET['Barcode'])!="")
		{
		$ItemBarcode=$_GET['Barcode'];
		$Barcode="i.Barcode like '%".$ItemBarcode."%' and ";
		}
		else
		{
		$Barcode="";
		}
		if(isset($_GET['Under']) && trim($_GET['Under'])!="")
		{
		$ItemUnder=$_GET['Under'];
		$Under="i.Under =".$ItemUnder." and ";
		}
		else
		{
		$Under="";
		}
		if(isset($_GET['AddtionalInfo5']) && trim($_GET['AddtionalInfo5'])!="")
		{
		$ItemAddtionalInfo5=$_GET['AddtionalInfo5'];
		$AddtionalInfo5="i.AddtionalInfo5 like '%".$ItemAddtionalInfo5."%' and ";
		}
		else
		{
		$AddtionalInfo5="";
		}
		if(isset($_GET['Code']) && trim($_GET['Code'])!="")
		{
		$ItemCode=$_GET['Code'];
		$Code="i.AdditionalInfo2 like '%".$ItemCode."%' and ";
		}
		else
		{
		$Code="";
		}

		$searchbox=$ItemName."".$Barcode."".$Under."".$AddtionalInfo5."".$Code;
/*
		 $sql="select   ROW_NUMBER() OVER (
      PARTITION BY [CompanyID]
      ORDER BY [CompanyID]
   ) row_num,i.Name as ItemName,i.Under as ProductCategoryName,i.Barcode as Barcode,i.AdditionalInfo2 as Code,i.Make as Brand,i.Rating as Color,i.Model as Size,c.Name as CompanyShortForm,'' as col_Action,ID,Attr1,i.AdditionalInfo3,i.AdditionalInfo5,Barcode,cast(StandardPrice3 as numeric) as CostPrice,cast(StandardPrice2 as numeric) as WholeSalePrice,cast(StandardPrice1 as numeric) as RetailPrice,cast(VATPercent as numeric) as VATPercent,'ok' as status from inventory as i inner join godowns as c on c.GodownID=i.CompanyID where  ".$searchbox." i.[group]=0 and   ProductBaseType='".$ProductBaseType."'  order by CompanyID";*/
  // if(isset($_GET['all']))
   if(isset($_GET['checkstock']))
   {
   	$stocksql="";// and (select isnull(sum(stock),0) from stockposition where itemid=i.ID)>0";

   	$GodownID=" and GodownID=".$_GET['GodownID'];
   }
   else
   {
   	$stocksql="";
   	$GodownID="";
    }
    $sql="   select   ROW_NUMBER() OVER (
      PARTITION BY i.[CompanyID]
      ORDER BY i.[CompanyID]
   ) row_num,i.Name as ItemName,j.Name as ProductCategoryName,i.under,i.Barcode as Barcode,i.AdditionalInfo2 as Code,i.CompanyID as CompanyID,
   i.Make as Brand,i.Rating as Color,i.Model as Size,c.Name as CompanyShortForm,'' as col_Action,
   i.ID as ID,i.Attr1 as Attr1,i.AdditionalInfo3,i.AdditionalInfo5,cast(i.StandardPrice3 as numeric) as CostPrice,convert(numeric(7,2),
   isnull((select top 1 StandardPrice2 from inventory_details where ItemID in (select ID from inventory where Barcode like '%".$ItemBarcode."%')),i.StandardPrice2)) as WholeSalePrice,cast(i.StandardPrice1 as numeric) as RetailPrice,(select isnull(sum(Qty),0) from viewStockLedger where itemid=i.ID $GodownID) as balance,
   cast(i.VATPercent as numeric) as VATPercent,'ok' as status 
   from inventory as i 
   inner join godowns as c on c.GodownID=i.CompanyID
   left join inventory_details as ind on ind.ItemID=i.ID
      left outer join Inventory as j on j.ID=i.Under where  ".$searchbox." i.active=1 and  i.[group]=0  $stocksql  order by i.CompanyID";
      //and   i.ProductBaseType='".$ProductBaseType."'
   // offset $start rows fetch next $limit rows only";
 /*     else
$sql="   select   ROW_NUMBER() OVER (
      PARTITION BY i.[CompanyID]
      ORDER BY i.[CompanyID]
   ) row_num,i.Name as ItemName,j.Name as ProductCategoryName,i.under,i.Barcode as Barcode,i.AdditionalInfo2 as Code,i.CompanyID as CompanyID,
   i.Make as Brand,i.Rating as Color,i.Model as Size,c.Name as CompanyShortForm,'' as col_Action,
   i.ID as ID,i.Attr1 as Attr1,i.AdditionalInfo3,i.AdditionalInfo5,cast(i.StandardPrice3 as numeric) as CostPrice,
   cast(i.StandardPrice2 as numeric) as WholeSalePrice,cast(i.StandardPrice1 as numeric) as RetailPrice,
   cast(i.VATPercent as numeric) as VATPercent,'ok' as status 
   from inventory as i 
   inner join godowns as c on c.GodownID=i.CompanyID
      left outer join Inventory as j on j.ID=i.Under where  ".$searchbox." i.[group]=0 and   i.ProductBaseType='".$ProductBaseType."' and CreateLog='".$_SESSION['UserName']."'  order by i.CompanyID";*/
		}

   $data=array();
//echo $sql;
	$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  while ($row = odbc_fetch_array($result)) {
        $row['col_Action']='<i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editMaster(this,'.$row["ID"].');"></i>&nbsp;&nbsp;&nbsp;  <i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteMaster(this,'.$row["ID"].');"></i>';
        $row['ItemName']=utf8_encode($row['ItemName']);
      //  $row['ProductCategoryName']=getnamesingle("inventory","Name","Under",$row['ProductCategoryName'],$connection);
      // $row['CompanyShortForm']=getnamesingle("Godowns","AdditionalInfo1","GodownID",$row['CompanyShortForm'],$connection);
        $row['Code']=utf8_encode($row['Code']);

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

	
  		

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



		if(isset($_GET['ID']))
		{
			$ID=$_GET['ID'];
$sql="select Name as ItemName,Under as ProductCategoryID,Barcode,AdditionalInfo2 as Code,Make as Brand,Rating as Color,Model as Size,CompanyID as CompanyID,'' as col_Action,ID,UnitID,Attr1,AdditionalInfo3,AdditionalInfo5,Barcode,cast(StandardPrice3 as numeric(7,2)) as CostPrice,cast(StandardPrice2 as numeric(7,2)) as WholeSalePrice,cast(StandardPrice1 as numeric(7,2)) as RetailPrice,cast(MinPriceLevel as numeric(7,2)) as MinPriceLevel,cast(CommisionPercent as numeric(7,2)) as CommisionPercent,cast(CommisionAmount as numeric(7,2)) as CommisionAmount,cast(MinQtyLevel as numeric(7,2)) as MinQtyLevel,cast(MaxQtyLevel as numeric(7,2)) as MaxQtyLevel,KeyField,ShowInPurchases,ShowInSales,IsFixedAsset,ShowInStock,IsNonStockAble,Details,LastModificationTimeStamp,cast(VATPercent as numeric(7,2)) as VATPercent,AdditionalInfo2,AdditionalInfo1 from inventory where ID=$ID";// offset $start rows fetch next $limit rows only";
		}
		else
		{
		$start=0;
		$limit=10;
		if(isset($_GET['ItemName']))
		{
		$Item=$_GET['ItemName'];
		$ItemName="i.Name like '%".$Item."%' or ";
		}
		else
		{
	$ItemName="";
		}
		if(isset($_GET['Barcode']) && trim($_GET['Barcode'])!="")
		{
		$ItemBarcode=$_GET['Barcode'];
		$Barcode="i.Barcode like '%".$ItemBarcode."%' and ";
		}
		else
		{
		$Barcode="";
		}
		if(isset($_GET['Under']) && trim($_GET['Under'])!="")
		{
		$ItemUnder=$_GET['Under'];
		$Under="i.Under =".$ItemUnder." and ";
		}
		else
		{
		$Under="";
		}
		if(isset($_GET['AddtionalInfo5']) && trim($_GET['AddtionalInfo5'])!="")
		{
		$ItemAddtionalInfo5=$_GET['AddtionalInfo5'];
		$AddtionalInfo5="i.AddtionalInfo5 like '%".$ItemAddtionalInfo5."%' and ";
		}
		else
		{
		$AddtionalInfo5="";
		}
		if(isset($_GET['Code']) && trim($_GET['Code'])!="")
		{
		$ItemCode=$_GET['Code'];
		$Code="i.AdditionalInfo2 like '%".$ItemCode."%' and ";
		}
		else
		{
		$Code="";
		}

		$searchbox=$ItemName."".$Barcode."".$Under."".$AddtionalInfo5."".$Code;
/*
		 $sql="select   ROW_NUMBER() OVER (
      PARTITION BY [CompanyID]
      ORDER BY [CompanyID]
   ) row_num,i.Name as ItemName,i.Under as ProductCategoryName,i.Barcode as Barcode,i.AdditionalInfo2 as Code,i.Make as Brand,i.Rating as Color,i.Model as Size,c.Name as CompanyShortForm,'' as col_Action,ID,Attr1,i.AdditionalInfo3,i.AdditionalInfo5,Barcode,cast(StandardPrice3 as numeric) as CostPrice,cast(StandardPrice2 as numeric) as WholeSalePrice,cast(StandardPrice1 as numeric) as RetailPrice,cast(VATPercent as numeric) as VATPercent,'ok' as status from inventory as i inner join godowns as c on c.GodownID=i.CompanyID where  ".$searchbox." i.[group]=0 and   ProductBaseType='".$ProductBaseType."'  order by CompanyID";*/
  // if(isset($_GET['all']))
   if(isset($_GET['checkstock']))
   {
   	$stocksql="";// and (select isnull(sum(stock),0) from stockposition where itemid=i.ID)>0";

   	$GodownID=" and GodownID=".$_GET['GodownID'];
   }
   else
   {
   	$stocksql="";
   	$GodownID="";
    }
     $sql="   select   ROW_NUMBER() OVER (
      PARTITION BY i.[CompanyID]
      ORDER BY i.[CompanyID]
   ) row_num,i.Name as ItemName,j.Name as ProductCategoryName,i.under,i.Barcode as Barcode,i.AdditionalInfo2 as Code,i.CompanyID as CompanyID,
   i.Make as Brand,i.Rating as Color,i.Model as Size,c.Name as CompanyShortForm,'' as col_Action,
   i.ID as ID,i.Attr1 as Attr1,i.AdditionalInfo3,i.AdditionalInfo5,cast(i.StandardPrice3 as numeric) as CostPrice,
   cast(i.StandardPrice2 as numeric) as WholeSalePrice,cast(i.StandardPrice1 as numeric) as RetailPrice,(select isnull(sum(Qty),0) from viewStockLedger where itemid=i.ID $GodownID) as balance,
   cast(i.VATPercent as numeric) as VATPercent,'ok' as status 
   from inventory as i 
   inner join godowns as c on c.GodownID=i.CompanyID
      left outer join Inventory as j on j.ID=i.Under where  (".$searchbox." 1=1) and i.active=1 and  i.[group]=0 and i.degree>1 and isnull(i.IsFixedAsset,0)=0  $stocksql  order by i.CompanyID";
      //and   i.ProductBaseType='".$ProductBaseType."'
   // offset $start rows fetch next $limit rows only";
 /*     else
$sql="   select   ROW_NUMBER() OVER (
      PARTITION BY i.[CompanyID]
      ORDER BY i.[CompanyID]
   ) row_num,i.Name as ItemName,j.Name as ProductCategoryName,i.under,i.Barcode as Barcode,i.AdditionalInfo2 as Code,i.CompanyID as CompanyID,
   i.Make as Brand,i.Rating as Color,i.Model as Size,c.Name as CompanyShortForm,'' as col_Action,
   i.ID as ID,i.Attr1 as Attr1,i.AdditionalInfo3,i.AdditionalInfo5,cast(i.StandardPrice3 as numeric) as CostPrice,
   cast(i.StandardPrice2 as numeric) as WholeSalePrice,cast(i.StandardPrice1 as numeric) as RetailPrice,
   cast(i.VATPercent as numeric) as VATPercent,'ok' as status 
   from inventory as i 
   inner join godowns as c on c.GodownID=i.CompanyID
      left outer join Inventory as j on j.ID=i.Under where  ".$searchbox." i.[group]=0 and   i.ProductBaseType='".$ProductBaseType."' and CreateLog='".$_SESSION['UserName']."'  order by i.CompanyID";*/
		}

   $data=array();
//echo $sql;
	$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  while ($row = odbc_fetch_array($result)) {
        $row['col_Action']='<i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editMaster(this,'.$row["ID"].');"></i>&nbsp;&nbsp;&nbsp;  <i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteMaster(this,'.$row["ID"].');"></i>';
        $row['ItemName']=utf8_encode($row['ItemName']);
        $row['ProductCategoryName']=utf8_encode($row['ProductCategoryName']);
        
        $row['ItemName']=htmlspecialchars($row['ItemName']);

      //  $row['ProductCategoryName']=getnamesingle("inventory","Name","Under",$row['ProductCategoryName'],$connection);
      // $row['CompanyShortForm']=getnamesingle("Godowns","AdditionalInfo1","GodownID",$row['CompanyShortForm'],$connection);
      //  $row['Code']=utf8_encode($row['Code']);
        $row['Code']=utf8_encode($row['Code']);

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

	
  		


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

		if(isset($_GET['ID']))
		{
			$ID=$_GET['ID'];
$sql="select Name as ItemName,Under as ProductCategoryID,Barcode,AdditionalInfo2 as Code,Make as Brand,Rating as Color,Model as Size,CompanyID as CompanyID,'' as col_Action,ID,UnitID,Attr1,AdditionalInfo3,AdditionalInfo5,Barcode,cast(StandardPrice3 as numeric(7,2)) as CostPrice,cast(StandardPrice2 as numeric(7,2)) as WholeSalePrice,cast(StandardPrice1 as numeric(7,2)) as RetailPrice,cast(MinPriceLevel as numeric(7,2)) as MinPriceLevel,cast(CommisionPercent as numeric(7,2)) as CommisionPercent,cast(CommisionAmount as numeric(7,2)) as CommisionAmount,cast(MinQtyLevel as numeric(7,2)) as MinQtyLevel,cast(MaxQtyLevel as numeric(7,2)) as MaxQtyLevel,KeyField,ShowInPurchases,ShowInSales,IsFixedAsset,ShowInStock,IsNonStockAble,Details,LastModificationTimeStamp,cast(VATPercent as numeric(7,2)) as VATPercent,AdditionalInfo2,AdditionalInfo1 from inventory where ID=$ID";// offset $start rows fetch next $limit rows only";
		}
		else
		{
		$start=0;
		$limit=10;
		if(isset($_GET['ItemName']))
		{
		$Item=$_GET['ItemName'];
		$ItemName="i.Name like '%".$Item."%' and ";
		}
		else
		{
	$ItemName="";
		}
		if(isset($_GET['Barcode']) && trim($_GET['Barcode'])!="")
		{
		$ItemBarcode=$_GET['Barcode'];
		$Barcode="i.Barcode like '%".$ItemBarcode."%' and ";
		}
		else
		{
		$Barcode="";
		}
		if(isset($_GET['Under']) && trim($_GET['Under'])!="")
		{
		$ItemUnder=$_GET['Under'];
		$Under="i.Under =".$ItemUnder." and ";
		}
		else
		{
		$Under="";
		}
		if(isset($_GET['AddtionalInfo5']) && trim($_GET['AddtionalInfo5'])!="")
		{
		$ItemAddtionalInfo5=$_GET['AddtionalInfo5'];
		$AddtionalInfo5="i.AddtionalInfo5 like '%".$ItemAddtionalInfo5."%' and ";
		}
		else
		{
		$AddtionalInfo5="";
		}
		if(isset($_GET['Code']) && trim($_GET['Code'])!="")
		{
		$ItemCode=$_GET['Code'];
		$Code="i.AdditionalInfo2 like '%".$ItemCode."%' and ";
		}
		else
		{
		$Code="";
		}

		$searchbox=$ItemName."".$Barcode."".$Under."".$AddtionalInfo5."".$Code;
/*
		 $sql="select   ROW_NUMBER() OVER (
      PARTITION BY [CompanyID]
      ORDER BY [CompanyID]
   ) row_num,i.Name as ItemName,i.Under as ProductCategoryName,i.Barcode as Barcode,i.AdditionalInfo2 as Code,i.Make as Brand,i.Rating as Color,i.Model as Size,c.Name as CompanyShortForm,'' as col_Action,ID,Attr1,i.AdditionalInfo3,i.AdditionalInfo5,Barcode,cast(StandardPrice3 as numeric) as CostPrice,cast(StandardPrice2 as numeric) as WholeSalePrice,cast(StandardPrice1 as numeric) as RetailPrice,cast(VATPercent as numeric) as VATPercent,'ok' as status from inventory as i inner join godowns as c on c.GodownID=i.CompanyID where  ".$searchbox." i.[group]=0 and   ProductBaseType='".$ProductBaseType."'  order by CompanyID";*/
  // if(isset($_GET['all']))
   if(isset($_GET['checkstock']))
   {
   	$stocksql="";// and (select isnull(sum(stock),0) from stockposition where itemid=i.ID)>0";

   	$GodownID=" and GodownID=".$_GET['GodownID'];
   }
   else
   {
   	$stocksql="";
   	$GodownID="";
    }
    $sql="   select   ROW_NUMBER() OVER (
      PARTITION BY i.[CompanyID]
      ORDER BY i.[CompanyID]
   ) row_num,i.Name as ItemName,j.Name as ProductCategoryName,i.under,i.Barcode as Barcode,i.AdditionalInfo2 as Code,i.CompanyID as CompanyID,
   i.Make as Brand,i.Rating as Color,i.Model as Size,c.Name as CompanyShortForm,'' as col_Action,
   i.ID as ID,i.Attr1 as Attr1,i.AdditionalInfo3,i.AdditionalInfo5,cast(i.StandardPrice3 as numeric) as CostPrice,
   cast(i.StandardPrice2 as numeric) as WholeSalePrice,cast(i.StandardPrice1 as numeric) as RetailPrice,(select isnull(sum(Qty),0) from viewStockLedger where itemid=i.ID $GodownID) as balance,
   cast(i.VATPercent as numeric) as VATPercent,'ok' as status ,i.UnitID as UnitID
   from inventory as i 
   inner join godowns as c on c.GodownID=i.CompanyID
      left outer join Inventory as j on j.ID=i.Under where  ".$searchbox." i.active=1 and  i.[group]=0  $stocksql  order by i.CompanyID";
      //and   i.ProductBaseType='".$ProductBaseType."'
   // offset $start rows fetch next $limit rows only";
 /*     else
$sql="   select   ROW_NUMBER() OVER (
      PARTITION BY i.[CompanyID]
      ORDER BY i.[CompanyID]
   ) row_num,i.Name as ItemName,j.Name as ProductCategoryName,i.under,i.Barcode as Barcode,i.AdditionalInfo2 as Code,i.CompanyID as CompanyID,
   i.Make as Brand,i.Rating as Color,i.Model as Size,c.Name as CompanyShortForm,'' as col_Action,
   i.ID as ID,i.Attr1 as Attr1,i.AdditionalInfo3,i.AdditionalInfo5,cast(i.StandardPrice3 as numeric) as CostPrice,
   cast(i.StandardPrice2 as numeric) as WholeSalePrice,cast(i.StandardPrice1 as numeric) as RetailPrice,
   cast(i.VATPercent as numeric) as VATPercent,'ok' as status 
   from inventory as i 
   inner join godowns as c on c.GodownID=i.CompanyID
      left outer join Inventory as j on j.ID=i.Under where  ".$searchbox." i.[group]=0 and   i.ProductBaseType='".$ProductBaseType."' and CreateLog='".$_SESSION['UserName']."'  order by i.CompanyID";*/
		}

   $data=array();
//echo $sql;
	$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  while ($row = odbc_fetch_array($result)) {
        $row['col_Action']='<i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editMaster(this,'.$row["ID"].');"></i>&nbsp;&nbsp;&nbsp;  <i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteMaster(this,'.$row["ID"].');"></i>';
        $row['ItemName']=utf8_encode($row['ItemName']);
      //  $row['ProductCategoryName']=getnamesingle("inventory","Name","Under",$row['ProductCategoryName'],$connection);
      // $row['CompanyShortForm']=getnamesingle("Godowns","AdditionalInfo1","GodownID",$row['CompanyShortForm'],$connection);
        $row['Code']=utf8_encode($row['Code']);

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

	
  		}

// code for item cbo 
   	if($_GET['action']=="optionview")
	{
	//print_r($_GET);
	$ProductBaseType=$_GET['ProductBaseType'];
	if(isset($_GET['ItemName']))
	{
		$Item=$_GET['ItemName'];
	$ItemName="Name like '%".$Item."%' and ";
	}
	else
	{
$ItemName="";
	}	
$data=array();
 $sql="select  
ID ,Name as ItemName,Barcode,(select isnull(sum(stock),0) from stockposition where itemid=Inventory.ID) as balance  FROM Inventory   where  ".$ItemName." [group]=0 and ProductBaseType='$ProductBaseType' ";
	$result=odbc_exec($connection, $sql);
  while ($row = odbc_fetch_array($result)) {
        $row['ItemName']=utf8_encode($row['ItemName']);
        //htmlspecialchars($row['ItemName']);
    $data []=$row;

  }
 // print_r($data);
   echo json_encode($data);
   	}//end action view
   	if($_GET['action']=="INSERTMRQ2")
   	{
   	/*	$Code='VOUCHER_POST';
   		$SidebarID=67;
   		$degree=2;*/

//echo CheckPolicy($Userid,$SidebarID,$Code,$degree,$connection);
//return; 
   		odbc_autocommit($connection, FALSE);


   		$master=array();
   		//print_r($_POST);
   	//	return;
			$master=$_POST['data'];
			$details=$_POST['details'];
			$masterdata=$master;//$master[0];
			//$masterdata=urlencode($masterdata);
			//$detaildata=$details[0];
		/*	print_r($details);
			return;*/
			//var_dump($_POST);
			/*$masterdata=str_replace(',"detail":', "}]",$masterdata);
			$masterdata="[".$masterdata;*/
			$mrmaster1=(json_decode($master));//ok
			//$mrmaster=$mrmaster1[0];
			//echo "master data<br>";
			//echo ($mrmaster1);
			$mrmaster=$mrmaster1;	
		//	$mrmaster=$_POST['data'];
			//$d=$detaildata;
			////print_r($d);
		//	$d[0]=str_replace("{\"ItemTable\":[","",$d[0]);
			//print_r($mrmaster);
			// $dd="[".$d[0]."]";
		$details=str_replace("{\"ItemTable\":[","",$details);
			$mrdetail=json_decode($details);
		/*	print_r($mrdetail);
			return;*/

			$mrdetail=json_decode($_POST['details']);
			$ShipperID =isset($mrmaster->ShipperID)?$mrmaster->ShipperID:0;
            $GodownID =isset($mrmaster->GodownID)?$mrmaster->GodownID:0;
            $SupplierID =isset($mrmaster->SupplierID)?$mrmaster->SupplierID:0;
            $SupplierName =isset($mrmaster->SupplierName)?$mrmaster->SupplierName:'';
 $Location =(isset($mrmaster->Location) && $mrmaster->Location>0)?$mrmaster->Location:0;
      		
            $Narration =isset($mrmaster->Narration)?$mrmaster->Narration:'';
            $Narration=str_replace('_',' ',$Narration);
            $Narration=str_replace('.',' ',$Narration);
            $InvoiceType =isset($mrmaster->InvoiceType)?$mrmaster->InvoiceType:0;
            $QuoteReference =isset($mrmaster->QuoteReference)?$mrmaster->QuoteReference:null;
            $Notes =isset($_POST['Notes'])?$_POST['Notes']:'';
            $Notes=str_replace('_',' ',$Notes);
            $Notes=str_replace('+',' ',$Notes);
            $Notes=htmlspecialchars($Notes);
            //echo "<br>here".$Notes;
            //print_r($mrmaster);
            		//	return;

            $DueDate =isset($mrmaster->DeliveryDate)?$mrmaster->DeliveryDate:'';
            $InvoiceDate =isset($mrmaster->BillDate)?$mrmaster->BillDate:'';
      $InvoiceDate=$InvoiceDate." ".Date("H:i:s");
            $InvoiceID =isset($mrmaster->InvoiceID)?$mrmaster->InvoiceID:0;
            $PurchaseLedgerID =isset($mrmaster->DebitToHeadID)?$mrmaster->DebitToHeadID:0;
            $VATLedgerID =isset($mrmaster->VATLedgerID)?$mrmaster->VATLedgerID:0;
            $TotalAmount =str_replace('_','.',isset($mrmaster->TotalAmt)?$mrmaster->TotalAmt:0);
            $DiscountAmount =str_replace('_','.',isset($mrmaster->TotalDisountAmount)?$mrmaster->TotalDisountAmount:0);
            $TotalTaxAmount =str_replace('_','.',isset($mrmaster->TotalTaxAmount)?$mrmaster->TotalTaxAmount:0);
            $InculsiveAmount =str_replace('_','.',isset($mrmaster->InculsiveAmount)?$mrmaster->InculsiveAmount:0);
            $NetAmount =str_replace('_','.',isset($mrmaster->NetAmount)?$mrmaster->NetAmount:0);
            if(!is_numeric($NetAmount))
            $NetAmount=0;
            if(!is_numeric($TotalAmount))
            $TotalAmount=0;
            if(!is_numeric($TotalTaxAmount))
            $TotalTaxAmount=0;	
			if(!is_numeric($InculsiveAmount))
            $InculsiveAmount=0;   
			if(!is_numeric($DiscountAmount))
            $DiscountAmount=0;                 

            $Active=1;
            $InvoiceStatus=1;
            $KeyField="";
            $ChallanNo="0";
            $ItemID='0';
            $EditMode=0;
            $BillNO=$QuoteReference;
            $GRNno="0";
            $ReferenceInvoiceID="0";
            $ReferenceInvoiceID =isset($mrmaster->ReferenceInvoiceID)?$mrmaster->ReferenceInvoiceID:0;
            //if($InvoiceType==6 || $InvoiceType==16)$GodownID=getnamesingle("invoicemaster","GodownID","InvoiceID",$ReferenceInvoiceID,$connection);
            $BiltyNo='0';
            $ItemID='';
            $InvoiceStatusID=1;
            $DeliveryDate=$DueDate;

           // $SideBarID = $mrmaster->SideBarID;
            $InvoiceID =(isset($mrmaster->InvoiceID))?$mrmaster->InvoiceID:0;
            if($InvoiceID==0 || $InvoiceID=="")
            $InvoiceID=getmaxId("InvoiceMaster","InvoiceID",$connection)+1;
        	//if($InvoiceType==1)
           $exp="InvoiceType=".$InvoiceType;
           $num= generateCode("InvoiceMaster","InvoiceID",$exp,$connection)+1;
           $num=str_pad($num,5,"0",STR_PAD_LEFT);
           if($InvoiceType==1)
           $KeyField="MRQ-".date("ym").$num;
       	else if($InvoiceType==100)
       	 $KeyField="LPO-".date("ym").$num;
       		else if($InvoiceType==2)
       	 $KeyField="REC-".date("ym").$num;	
       	 else if($InvoiceType==4)
       	 $KeyField="PI-".date("ym").$num;
       	else if($InvoiceType==3)
       	 $KeyField="PR-".date("ym").$num;
       	else if($InvoiceType==6)
       	 $KeyField="GR-".$num;
       	else if($InvoiceType==16)
       	 $KeyField="ST-RET-".date("ym").$num;       	
       	else if($InvoiceType==7)
       	 $KeyField="DIS-".date("ym").$num;
       	else if($InvoiceType==17)
       	 $KeyField="DRN-".date("ym").$num;

$mrmaster->KeyField=$KeyField;
            $PassCode = isset($mrmaster->PassCode)?$mrmaster->PassCode:'';
              $sql="select * from invoicemaster where invoiceid=".$InvoiceID;
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>1)
            {

          $sql="update invoicemaster set InvoiceDate='$InvoiceDate',Narration='$Narration',GodownID='$GodownID',DeliveryDate='$DueDate',PurchaseLedgerID=".$PurchaseLedgerID.",VATLedgerID=".$VATLedgerID.",SupplierID=".$SupplierID.",ReferenceInvoiceID=".$ReferenceInvoiceID.",BillNO='".$QuoteReference."',NetAmount=".$NetAmount.",TotalTaxAmount=".$TotalTaxAmount.",TotalAmount=".$TotalAmount.",Notes='$Notes',EditLog='".$_SESSION['UserName']."',ShipperID=$ShipperID  where InvoiceID=".$InvoiceID;      	
            //delete preivous record 
          //return;
          

            $sqldelete="delete from invoicedetail where InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sqldelete);

              if($InvoiceType==6)
            { 

$sqlGT="update GoodsTransferMaster set InvoiceDate='$InvoiceDate',Narration='$Narration',GodownID='$GodownID',ToGodownID=$ShipperID,SupplierID=".$SupplierID.",ReferenceInvoiceID=".$ReferenceInvoiceID.",BillNO='".$QuoteReference."',TotalAmount=".$TotalAmount.",EditLog='".$_SESSION['UserName']."',ShipperID=$ShipperID,datamode=0  where InvoiceID=".$InvoiceID; 
odbc_exec($connection,$sqlGT);
//            $sqldelete="delete from GoodsTransferDetail where InvoiceID=".$InvoiceID;
  //          odbc_exec($connection,$sqldelete);
        	}
$GTInvoiceID=0;
            }
            else
            {
            //	return;
            // insert query for invoice master 
            	$sqldelete="delete from invoicemaster where invoiceid=".$InvoiceID;
        	            odbc_exec($connection,$sqldelete);

            	  $sqldelete="delete from invoicedetail where InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sqldelete);

  
             $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
			,TotalAmount
           ,DiscountAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
       	   ,DeliveryDate
           ,InvoiceStatus
           ,Notes
           ,VATLedgerID
           ,PurchaseLedgerID,CreateLog
       ) values (".$InvoiceID.",'".
			$InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",".$ChallanNo
           .",'".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
			.",".$TotalAmount
           .",".$DiscountAmount
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$ShipperID
           .",".$BiltyNo
           .",'".$DueDate."'
           ,".$InvoiceStatusID
       	   .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,'".$Notes."'
           ,".$VATLedgerID."
           ,".$PurchaseLedgerID.",'".$_SESSION['UserName']."')";
$GTInvoiceID=0;
                if($InvoiceType==6)
            {
            	$PeriodID=1;

  $sqldelete="delete from GoodsTransferMaster where ReferenceInvoiceID=".$InvoiceID;
            odbc_exec($connection,$sqldelete);

           // 	getmaxId("GoodsTransferMaster","*","",)
            $GTInvoiceID=getmaxId("GoodsTransferMaster","InvoiceID",$connection)+1;
      $sqldelete="delete from StockLedger where InvoiceTypeid=6 and InvoiceID=".$GTInvoiceID;
            odbc_exec($connection,$sqldelete);

            	//InvoiceType set 2 for old system
           $sql1="insert into GoodsTransferMaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ToGodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
			,TotalAmount
           ,DiscountAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,PeriodID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,CreateLog,datamode
       ) values  (".$GTInvoiceID.",'".
			$InvoiceDate."'
           ,'".$Narration."'
           ,2,".$Active
           .",".$SupplierID
           .",".$GodownID
           .",".$ShipperID
           .",".$ChallanNo
           .",'".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
			.",".$TotalAmount
           .",".$DiscountAmount
           .",".$NetAmount
           .",".$InvoiceID
           .",".$ShipperID
           .",".$PeriodID
           .",".$BiltyNo
           .",'".$DueDate."'                 	   
           ,".$InvoiceStatus."
           ,'".$_SESSION['UserName']."',0)";
           odbc_exec($connection,$sql1) or die(odbc_error().$sql1);
           $sqltablemaster="update TablesMaster set LastID=$InvoiceID where TableID=50";
           odbc_exec($connection,$sqltablemaster) or die(odbc_error().$sqltablemaster);
       		}
           //end code for good transfer 
       		}//end else for insert 
           odbc_exec($connection,$sql) or die(odbc_error().$sql);
           //code for Good Transfer 
       
           if($InvoiceType==4 || $InvoiceType==3)
           {
           	if($InvoiceType==3)
           	{
           		$PurchaseReturnLedgerID=$_SESSION['SETTING']['PURCHASERETURN'];//;json_decode(getnamewhere("master_values","Code","MasterValue='PURCHASERETURN'",$connection));	
          // $PurchaseReturnLedgerID=$PurchaseReturnLedgerID->COAID;
       		}
           else
           	{
           	$PurchaseLedgerID=$_SESSION['SETTING']['PURCHASES'];//json_decode(getnamewhere("master_values","Code","MasterValue='PURCHASES'",$connection));
          // 	$PurchaseLedgerID=$PurchaseLedgerID->COAID;
           	}
           	$Posted=1;
           	$IsPostDated=1;
			$LedgerID=$SupplierID;
           	$AmountDebit=0;
           	$AmountCredit=0;
           	$Active=1;
           	$PeriodID=1;
           	$IsAuto=1;
           	$Cash=0;
           	$ContractID=0;
           	$VoucherDateTime=date("Y-m-d m:i:s");
           	$PaymentType="Credit";
           	$ReferenceInvoiceID=$InvoiceID;
           	$ReferenceVoucherID=0;
           	$VoucherPostDateTime=0;
           	$VoucherToBePosted=1;
           	$MultiVoucher=0;
           	$UserID=0;
           	$GroupID=1;
           	$LocationID=$GodownID;
           	$VoucherTypeID=71;
           	$VoucherDate=$InvoiceDate;
           	//$TotalAmount=$TotalAmount
           	$sql="select * from VoucherMaster where VoucherTypeID in (71,72) and  ReferenceInvoiceID=".$ReferenceInvoiceID;
           	$result=odbc_exec($connection,$sql);
           	$VoucherID=0;
           	if(odbc_num_rows($result)>0)
           	{
           		$row=odbc_fetch_array($result);
           		$VoucherID=$row['VoucherID'];
           	$sql="update VoucherMaster set TotalAmount=".$NetAmount.",EditLog='".$_SESSION['UserName']."' where ReferenceInvoiceID=".$ReferenceInvoiceID;
           	odbc_exec($connection,$sql) or die(odbc_error().$sql);	
           	}
           	else
           	{
           	$VoucherID=getMaxId("VoucherMaster","VoucherID",$connection)+1;
           	//getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$connection)+1;
           	if($InvoiceType==4)
           	{
           	$where="VoucherTypeID=71";	
           	$VoucherNo=generateCode("VoucherMaster","VoucherNo",$where,$connection)+1;

           	//getnamesingle("TablesMaster","LastID","TableID","71",$connection)+1;
           	$VoucherNo2=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
           	$VoucherNo="PIV-".$VoucherNo2;
           	$ACNarration='AUTO VOUCHER for DOC: '.$VoucherNo.' from Purchase Invoice';
           	$VoucherTypeID=71;
           	}
           	if($InvoiceType==3)
           	{
           	$where="VoucherTypeID=72";           		
//           	$VoucherNo=getnamesingle("TablesMaster","LastID","TableID","72",$connection)+1;
            $VoucherNo=generateCode("VoucherMaster","VoucherNo",$where,$connection)+1;
 
           	$VoucherNo2=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
           	$VoucherNo="PR-".$VoucherNo2;
           	$ACNarration='AUTO VOUCHER for DOC: '.$VoucherNo.' from Purchase Return Invoice';
           	$VoucherTypeID=72;
           	}
           	$VoucherDateTime=date("Y-m-d H:i:s");
           	//insert into voucher 
           	$sql="INSERT INTO [dbo].[VoucherMaster]
           ([VoucherID]
           ,[VoucherNo]
           ,[TotalAmount]
           ,[Active]
           ,[VoucherDate]
           ,[Narration]
           ,[Posted]
           ,[IsPostDated]
           ,[VoucherTypeID]
           ,[PeriodID]
           ,[ReferenceInvoiceID]
           ,[LedgerID]
           ,[AmountDebit]
           ,[AmountCredit]
           ,[IsAuto]
           ,[LocationID]
           ,[ReferenceVoucherID]
           ,[GroupID]
           ,[MultiVoucher]
           ,[VoucherToBePosted]
           ,[Cash]
           ,[ContractID]
           ,[UserID]
           ,[VoucherDateTime]
           ,[PaymentType],CreateLog)
     VALUES($VoucherID
           ,'$VoucherNo'
           ,$NetAmount
           ,$Active
           ,'$VoucherDate'
           ,'$ACNarration'
           ,$Posted
           ,$IsPostDated
           ,$VoucherTypeID
           ,$PeriodID
           ,$ReferenceInvoiceID
           ,$SupplierID
           ,$AmountDebit
           ,$AmountCredit
           ,$IsAuto
           ,$LocationID
           ,$ReferenceVoucherID
           ,$GroupID
           ,$MultiVoucher
           ,$VoucherToBePosted
           ,$Cash
           ,$ContractID
           ,$UserID
           ,'$VoucherDateTime'
           ,'$PaymentType','".$_SESSION['UserName']."'

     )

           	";
            odbc_exec($connection,$sql) or die(odbc_error().$sql);	
           	}
           // enter for voucher detail 
           	//delete previous record 
           	$sqldelete="delete from voucherdetails where ReferenceInvoiceID=".$ReferenceInvoiceID;
           	//odbc_exec($connection,$sqldelete);
            //Purchase 
            $TransactionType="PURCHASE A/C";
            $Debit=$TotalAmount;
            $Credit=$TotalAmount;
            if($InvoiceType==3)
            $CreditLedgerID=$PurchaseReturnLedgerID;//$SupplierID; credit
            else
            $CreditLedgerID=$SupplierID;//$SupplierID;
            $CostCenterID=$GodownID;
            $IsDelete=0;
            $DebitCostCenterID=$GodownID;
            $Narrationdetail="Narration details here";
            if($InvoiceType==3)
            $LedgerID=$SupplierID;//debit
            else 
            $LedgerID=$PurchaseLedgerID;

        	

              $sqldetail="INSERT INTO [dbo].[VoucherDetails]
           ([VoucherID]
           ,[LedgerID]
           ,[Debit]
           ,[Credit]
           ,[Narration]
           ,[ReferenceInvoiceID]
           ,[CreditLedgerID]
           ,[CostCenterID]
           ,[IsDelete]
           ,[DebitCostCenterID]
           ,[TransactionType])
     VALUES($VoucherID
           ,$LedgerID
           ,$Debit
           ,$Credit
           ,'$Narrationdetail'
           ,$ReferenceInvoiceID
           ,$CreditLedgerID
           ,$CostCenterID
           ,$IsDelete
           ,$DebitCostCenterID
           ,'$TransactionType')";
 odbc_exec($connection,$sqldetail) or die(odbc_error().$sqldetail);	


/*code for 

 Inventory (Debit )
 Purchase (CREDIT)

 */
if($InvoiceType==4)
{
	$SidebarID=44;
	$degree=1;
	$Userid="";
	$Code='INVENTORY_POST';
	if(CheckPolicy($Userid,$SidebarID,$Code,$degree,$connection)==1)
	{
$InventoryLedgerID=$_SESSION['SETTING']['INVENTORY'];
             $sqldetail="INSERT INTO [dbo].[VoucherDetails]
           ([VoucherID]
           ,[LedgerID]
           ,[Debit]
           ,[Credit]
           ,[Narration]
           ,[ReferenceInvoiceID]
           ,[CreditLedgerID]
           ,[CostCenterID]
           ,[IsDelete]
           ,[DebitCostCenterID]
           ,[TransactionType])
     VALUES($VoucherID
           ,$InventoryLedgerID
           ,$Debit
           ,$Credit
           ,'$Narrationdetail'
           ,$ReferenceInvoiceID
           ,$LedgerID
           ,$CostCenterID
           ,$IsDelete
           ,$DebitCostCenterID
           ,'$TransactionType')";
 odbc_exec($connection,$sqldetail) or die(odbc_error().$sqldetail);	
 	}//end check policy
 //end code for purchase credit 
}
if($InvoiceType==3)
{
	$SidebarID=44;
	$degree=1;
	$Userid="";
	$Code='INVENTORY_POST';
	if(CheckPolicy($Userid,$SidebarID,$Code,$degree,$connection)==1)
	{
$InventoryLedgerID=$_SESSION['SETTING']['INVENTORY'];
             $sqldetail="INSERT INTO [dbo].[VoucherDetails]
           ([VoucherID]
           ,[LedgerID]
           ,[Debit]
           ,[Credit]
           ,[Narration]
           ,[ReferenceInvoiceID]
           ,[CreditLedgerID]
           ,[CostCenterID]
           ,[IsDelete]
           ,[DebitCostCenterID]
           ,[TransactionType])
     VALUES($VoucherID
           ,$PurchaseReturnLedgerID
           ,$Debit
           ,$Credit
           ,'$Narrationdetail'
           ,$ReferenceInvoiceID
           ,$InventoryLedgerID
           ,$CostCenterID
           ,$IsDelete
           ,$DebitCostCenterID
           ,'$TransactionType')";
 odbc_exec($connection,$sqldetail) or die(odbc_error().$sqldetail);	
 	}
 //end code for purchase credit 
}
            $TransactionType="VAT A/C";
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
            if($InvoiceType==3)
            $CreditLedgerID=$VATLedgerID;//purchase return VAT CREDIT	
            else	
            $CreditLedgerID=$SupplierID;//$SupplierID purchases Supplier credit
            $CostCenterID=$GodownID;
            $IsDelete=0;
            $DebitCostCenterID=$GodownID;
            $Narrationdetail="Purchases Narration details here";
            if($InvoiceType==3)
            $LedgerID=$SupplierID;//$VATLedgerID;// supplier debit
        	else
        	$LedgerID=$VATLedgerID;	//purchase VAT Debit
             $sqldetail="INSERT INTO [dbo].[VoucherDetails]
           ([VoucherID]
           ,[LedgerID]
           ,[Debit]
           ,[Credit]
           ,[Narration]
           ,[ReferenceInvoiceID]
           ,[CreditLedgerID]
           ,[CostCenterID]
           ,[IsDelete]
           ,[DebitCostCenterID]
           ,[TransactionType])
     VALUES($VoucherID
           ,$LedgerID
           ,$Debit
           ,$Credit
           ,'$Narrationdetail'
           ,$ReferenceInvoiceID
           ,$CreditLedgerID
           ,$CostCenterID
           ,$IsDelete
           ,$DebitCostCenterID
           ,'$TransactionType')";
            odbc_exec($connection,$sqldetail) or die(odbc_error().$sqldetail);	
           }//end if invoicetype=4 and 3
            // detail fields
            //delete preivous record 
              $sql="delete from invoiceDetail where InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sql);
            if($InvoiceType==6)
            { 
            //$sql="delete from GoodsTransferDetail where InvoiceID=".$InvoiceID;
            //odbc_exec($connection,$sql);
        	}
       //     print_r($_REQUEST);
            for($a=0;$a<count($mrdetail);$a++)
            {
            $Flag =isset($mrdetail[$a]->Flag)?$mrdetail[$a]->Flag:'';
            if($Flag!="D")
            {
//
            	if($InvoiceType==4)
            	{
			/*	$ItemID=isset($mrdetail[$a]->ItemID)?$mrdetail[$a]->ItemID:0;
				$ItemName =isset($mrdetail[$a]->ItemName)?$mrdetail[$a]->ItemName:'';
            $Color =isset($mrdetail[$a]->Color)?$mrdetail[$a]->Color:'';
            $Size =isset($mrdetail[$a]->Size)?$mrdetail[$a]->Size:'';
            $Barcode =isset($mrdetail[$a]->Barcode)?$mrdetail[$a]->Barcode:'';
            $Category =isset($mrdetail[$a]->Category)?$mrdetail[$a]->Category:'';
            $Brand =isset($mrdetail[$a]->Brand)?$mrdetail[$a]->Brand:'';
            $Item_KeyField =isset($mrdetail[$a]->KeyField)?$mrdetail[$a]->KeyField:'';*/
/*$StockQty=getStockBalance($ItemID,0,$InvoiceDate,$connection);//current stock
$OpeningQty=getnamesingle("Inventoryopeningbalance","Qty","ID",$ItemID,$connection);
$StockQty=floatval($StockQty)+floatval($OpeningQty);

        if(($StockQty=="" || $StockQty==0) && ($OpeningQty=="" || $OpeningQty==0))
        $StockQty1=1;
        else
        $StockQty1=$StockQty;

$CostPrice=getCostPrice($ItemID,0,$InvoiceDate,$connection);
if($CostPrice==0 || $CostPrice=="")
$CostPrice=getnamesingle("Inventory","StandardPrice3","ID",$ItemID,$connection);

        	$OldValue=$StockQty1*$CostPrice;
        	$NewValue=$Qty*$UnitPrice;
        	$Totalvalue=$OldValue+$NewValue;
        	$TotalQty=($Qty+$StockQty);
        	$NewCostPrice=$Totalvalue/$TotalQty;
*/}
else
{/*
	$Totalvalue=0;
	$TotalQty=0;
	$StockQty=$Qty;
	$NewCostPrice=$UnitPrice;

*/}
            
            	//Item_ItemID
            $ItemID =isset($mrdetail[$a]->Item_ItemID)?$mrdetail[$a]->Item_ItemID:'0';
            $JobCardItem=isset($mrdetail[$a]->JobCardItem)?$mrdetail[$a]->JobCardItem:'';
            /*if($JobCardItem!="")$ItemID=getnamesingle("Inventory","ID","Name","'".$JobCardItem."'",$connection);*/ 
            if($ItemID=="")$ItemID=0;
            $ItemName =isset($mrdetail[$a]->Item_ItemName)?$mrdetail[$a]->Item_ItemName:'';

            $Color =isset($mrdetail[$a]->Item_Color)?$mrdetail[$a]->Item_Color:'';
            $Size =isset($mrdetail[$a]->Item_Size)?$mrdetail[$a]->Item_Size:'';
            $Barcode =isset($mrdetail[$a]->Item_Barcode)?$mrdetail[$a]->Item_Barcode:'';
            $Category =isset($mrdetail[$a]->Item_Category)?$mrdetail[$a]->Item_Category:'';
            $Brand =isset($mrdetail[$a]->Item_Brand)?$mrdetail[$a]->Item_Brand:'';
            $Item_KeyField =isset($mrdetail[$a]->Item_KeyField)?$mrdetail[$a]->Item_KeyField:'';
            
            $UnitPrice =(isset($mrdetail[$a]->Rate) && $mrdetail[$a]->Rate!="")?$mrdetail[$a]->Rate:0;
            $StockQty =isset($mrdetail[$a]->StockQty)?$mrdetail[$a]->StockQty:0;
            $ItemTable =isset($mrdetail[$a]->ItemTable)?$mrdetail[$a]->ItemTable:'';
            $Qty =isset($mrdetail[$a]->Qty)?$mrdetail[$a]->Qty:0;
   $ReceivedQty=(isset($mrdetail[$a]->ReceivedQty) && $mrdetail[$a]->ReceivedQty!="")?(double)$mrdetail[$a]->ReceivedQty:0;
    $Amount =(isset($mrdetail[$a]->Amount) && $mrdetail[$a]->Amount>0)?$mrdetail[$a]->Amount:($ReceivedQty*$UnitPrice);
            $DiscountPercent =(isset($mrdetail[$a]->Discount) && $mrdetail[$a]->Discount>=0)?(double)$mrdetail[$a]->Discount:0;
            $TaxPercent =(isset($mrdetail[$a]->VAT) && $mrdetail[$a]->VAT>0)?(double)$mrdetail[$a]->VAT:0;
            $NetAmount =(isset($mrdetail[$a]->NetAmount) && $mrdetail[$a]->NetAmount>0)?$mrdetail[$a]->NetAmount:0;
            $TaxAmount =(isset($mrdetail[$a]->VATAmount) && $mrdetail[$a]->VATAmount>0)?$mrdetail[$a]->VATAmount:0;
            $DiscountAmount =(isset($mrdetail[$a]->DiscountAmount) && $mrdetail[$a]->DiscountAmount>0)?$mrdetail[$a]->DiscountAmount:0;
            $Attr2 =isset($mrdetail[$a]->PartNumber)?$mrdetail[$a]->PartNumber:'';
            $Attr1 =isset($mrdetail[$a]->Specification)?$mrdetail[$a]->Specification:'';
            $Narration =isset($mrdetail[$a]->Narration)?$mrdetail[$a]->Narration:'';
            $ReferenceTransactionID =isset($mrdetail[$a]->ReferenceTransactionID)?$mrdetail[$a]->ReferenceTransactionID:'';
            $JobCardItem =isset($mrdetail[$a]->JobCardItem)?$mrdetail[$a]->JobCardItem:'';
            $TransactionID =isset($mrdetail[$a]->TransactionID)?$mrdetail[$a]->TransactionID:'';
            $VATPercent=$TaxPercent;
            $VATAmount=$TaxAmount;
            $UnitID=1;
            $TotalNetAmount=0;
            if($ReferenceTransactionID>0)
            {
            	if($InvoiceType==100 || $InvoiceType==4)
            	{
            		$istatus=4;
            	}	
            	else
            	{
            		$istatus=2;
            	}
            	 $sqlupdateinvoice="update invoicedetail set ReceivedQty=(isnull(ReceivedQty,0)+$Qty) where TransactionID=".$ReferenceTransactionID;
            	
            	odbc_exec($connection, $sqlupdateinvoice);
             	$sqlupdatestatus="update invoicemaster set InvoiceStatus=$istatus where invoiceid in(select invoiceid from invoiceDetail where TransactionID=".$ReferenceTransactionID.")";
            	odbc_exec($connection, $sqlupdatestatus);
            	$ReferenceInvoiceID=getnamesingle("InvoiceDetail","InvoiceID","TransactionID",$ReferenceTransactionID,$connection);
            if($ReferenceInvoiceID>0)
            {
            	$sqlcheck="select * from invoiceDetail where invoiceid=$ReferenceInvoiceID and (qty-receivedQty)>0";//check remainig quantity 
            	$resultcheck=odbc_exec($connection,$sqlcheck);
            	if(odbc_num_rows($resultcheck)<1)
            	{
            		//update Invoice
            		$updatelpo="update InvoiceMaster set InvoiceStatus=4 where InvoiceID=$ReferenceInvoiceID";
            		odbc_exec($connection,$updatelpo);
            	}
            }

            }
            else
            {
            	$ReferenceTransactionID=0;
            }
            //str_replace("'"," inch ",$ItemName)

            
            $idesc="";
              $TransactionID=getmaxId("invoiceDetail","TransactionID",$connection)+1;
               $sql="insert into invoicedetail (
InvoiceID
           ,ItemID
           ,UnitPrice
           ,QTY
           ,Amount
           ,UnitID
           ,NetAmount
           ,TaxPercent
           ,TaxAmount
           ,Narration
           ,TotalNetAmount
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4           
           ,VATPercent
           ,VATAmount
           ,DiscountPercent
           ,DiscountAmount
           ,ReceivedQty
           ,ReferenceTransactionID
        ) values("
		   .$InvoiceID."
           ,".$ItemID."
           ,".$UnitPrice."
           ,".$Qty."
           ,".$Amount."
           ,".$UnitID."
           ,".$NetAmount."
           ,".$TaxPercent."
           ,".$TaxAmount."
           ,'".str_replace('_',' ',$Narration)."'
           ,".$TotalNetAmount."
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$JobCardItem."'
           ,'".$idesc."'
           ,".$VATPercent."
           ,".$VATAmount."
           ,".$DiscountPercent."
           ,".$DiscountAmount."
           ,".$ReceivedQty."
           ,".$ReferenceTransactionID.           
    			")";
        	odbc_exec($connection, $sql) or die(odbc_error().$sql);

/*if($InvoiceType==4 && $EditMode==0 && $InvoiceDate==Date("Y-m-d"))
{
$sql="update Inventory set StandardPrice1=$NewCostPrice where ID=$ItemID";
odbc_exec($connection, $sql) or die(odbc_error().$sql);
}*/


        	if($InvoiceType==6)
        	{
        	//	$GTInvoiceID=0;
        		$idesc="";
        		if($GTInvoiceID==0)
        		$GTInvoiceID=getmaxId("GoodsTransferMaster","InvoiceID",$connection);
        		
        		  $sql="insert into GoodsTransferDetail (
InvoiceID,ItemID,UnitPrice,QTY,Amount
           ,UnitID
           ,Narration
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4   
        )values(".$GTInvoiceID."
           ,".$ItemID."
           ,".$UnitPrice."
           ,".$Qty."
           ,".$Amount."
           ,".$UnitID."
            ,'".str_replace('_',' ',$Narration)."'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$JobCardItem."'
           ,'".$idesc."')";
        	odbc_exec($connection, $sql) or die(odbc_error().$sql);
        	}
        	}//end if flag
        	}//end for loop

//$InvoiceType==2  ||  GRN DISABLE direct PURCHASE 
        		if($InvoiceType==4 || $InvoiceType==7)
        	insertStock2($InvoiceID,$mrmaster,$mrdetail,$InvoiceType,$connection);
        else if($InvoiceType==3)
        	StockOut($InvoiceID,$mrmaster,$mrdetail,$InvoiceType,$connection);
        else if($InvoiceType==6 )
        	insertGoodTransfer($GTInvoiceID,$mrmaster,$mrdetail,$InvoiceType,$connection);
        else if(($InvoiceType!=1 && $InvoiceType!=100 && $InvoiceType!=3 && $InvoiceType!=4) )
        	insertStockTransfer($InvoiceID,$mrmaster,$mrdetail,$InvoiceType,$connection);

        	if (!odbc_error())
      odbc_commit($connection);
else
      odbc_rollback($connection);
//            		$res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
        $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
		echo json_encode($res);
            
   	} 	
   	if($_GET['action']=="INSERTMRQ")
   	{
   		odbc_autocommit($connection, FALSE);


   		$master=array();
   	//	print_r($_POST);
			$master=array_keys($_POST);
			$details=array_values($_POST);
			$masterdata=$master[0];
			//$masterdata=urlencode($masterdata);
			$detaildata=$details[0];
			//print_r($_POST);
			//var_dump($_POST);
			$masterdata=str_replace(',"detail":', "}]",$masterdata);
			$masterdata="[".$masterdata;
			$mrmaster1=(json_decode($masterdata));//ok
			$mrmaster=$mrmaster1[0];
			$d=array_keys($detaildata);
			////print_r($d);
			$d[0]=str_replace("{\"ItemTable\":[","",$d[0]);
			//print_r($mrmaster);
			 $dd="[".$d[0]."]";
			$mrdetail=json_decode($dd);
			//print_r($mrdetail);
			//$mrdetail=json_decode($_POST['details']);
			$ShipperID =isset($mrmaster->ShipperID)?$mrmaster->ShipperID:0;
            $GodownID =isset($mrmaster->GodownID)?$mrmaster->GodownID:0;
            $SupplierID =isset($mrmaster->SupplierID)?$mrmaster->SupplierID:0;
            $SupplierName =isset($mrmaster->SupplierName)?$mrmaster->SupplierName:'';
            $Location =isset($mrmaster->Location)?$mrmaster->Location:0;
      		
            $Narration =isset($mrmaster->Narration)?$mrmaster->Narration:'';
            $Narration=str_replace('_',' ',$Narration);
            $Narration=str_replace('.',' ',$Narration);
            $InvoiceType =isset($mrmaster->InvoiceType)?$mrmaster->InvoiceType:0;
            $QuoteReference =isset($mrmaster->QuoteReference)?$mrmaster->QuoteReference:null;
            $Notes =isset($mrmaster->Notes)?urlencode($mrmaster->Notes):'';
           // $Notes=urlencode($Notes);
          //  echo "<br>here".$Notes;
           // 			return;

            $DueDate =isset($mrmaster->DeliveryDate)?$mrmaster->DeliveryDate:'';
            $InvoiceDate =isset($mrmaster->BillDate)?$mrmaster->BillDate:'';
            $InvoiceID =isset($mrmaster->InvoiceID)?$mrmaster->InvoiceID:0;
            $PurchaseLedgerID =isset($mrmaster->DebitToHeadID)?$mrmaster->DebitToHeadID:0;
            $VATLedgerID =isset($mrmaster->VATLedgerID)?$mrmaster->VATLedgerID:0;
            $TotalAmount =str_replace('_','.',isset($mrmaster->TotalAmt)?$mrmaster->TotalAmt:0);
            $DiscountAmount =str_replace('_','.',isset($mrmaster->TotalDisountAmount)?$mrmaster->TotalDisountAmount:0);
            $TotalTaxAmount =str_replace('_','.',isset($mrmaster->TotalTaxAmount)?$mrmaster->TotalTaxAmount:0);
            $InculsiveAmount =str_replace('_','.',isset($mrmaster->InculsiveAmount)?$mrmaster->InculsiveAmount:0);
            $NetAmount =str_replace('_','.',isset($mrmaster->NetAmount)?$mrmaster->NetAmount:0);
            if(!is_numeric($NetAmount))
            $NetAmount=0;
            if(!is_numeric($TotalAmount))
            $TotalAmount=0;
            if(!is_numeric($TotalTaxAmount))
            $TotalTaxAmount=0;	
			if(!is_numeric($InculsiveAmount))
            $InculsiveAmount=0;   
			if(!is_numeric($DiscountAmount))
            $DiscountAmount=0;                 


            $Active=1;
            $InvoiceStatus=1;
            $KeyField="";
            $ChallanNo="0";
            $ItemID='0';
            $BillNO=$QuoteReference;
            $GRNno="0";
            $ReferenceInvoiceID="0";
            $ReferenceInvoiceID =isset($mrmaster->ReferenceInvoiceID)?$mrmaster->ReferenceInvoiceID:0;
            if($InvoiceType==6 || $InvoiceType==16)$GodownID=getnamesingle("invoicemaster","GodownID","InvoiceID",$ReferenceInvoiceID,$connection);
            $BiltyNo='0';
            $ItemID='';
            $InvoiceStatusID=1;
            $DeliveryDate=$DueDate;

           // $SideBarID = $mrmaster->SideBarID;
            $InvoiceID =isset($mrmaster->InvoiceID)?$mrmaster->InvoiceID:0;
            if($InvoiceID==0)
            $InvoiceID=getmaxId("InvoiceMaster","InvoiceID",$connection)+1;
        	//if($InvoiceType==1)
           $exp="InvoiceType=".$InvoiceType;
           $num= generateCode("InvoiceMaster","InvoiceID",$exp,$connection)+1;
           $num=str_pad($num,5,"0",STR_PAD_LEFT);
           if($InvoiceType==1)
           $KeyField="MRQ-".date("ym").$num;
       	else if($InvoiceType==100)
       	 $KeyField="LPO-".date("ym").$num;
       		else if($InvoiceType==2)
       	 $KeyField="REC-".date("ym").$num;	
       	 else if($InvoiceType==4)
       	 $KeyField="PI-".date("ym").$num;
       	else if($InvoiceType==3)
       	 $KeyField="PR-".date("ym").$num;
       	else if($InvoiceType==6)
       	 $KeyField="ST-ISS-".date("ym").$num;
       	else if($InvoiceType==16)
       	 $KeyField="ST-RET-".date("ym").$num;       	
       	else if($InvoiceType==7)
       	 $KeyField="DIS-".date("ym").$num;
       	else if($InvoiceType==17)
       	 $KeyField="DRN-".date("ym").$num;

            $PassCode = isset($mrmaster->PassCode)?$mrmaster->PassCode:'';
             $sql="select * from invoicemaster where invoiceid=".$InvoiceID;
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {

         $sql="update invoicemaster set InvoiceDate='$InvoiceDate',Narration='$Narration',GodownID='$GodownID',DeliveryDate='$DueDate',PurchaseLedgerID=".$PurchaseLedgerID.",VATLedgerID=".$VATLedgerID.",SupplierID=".$SupplierID.",ReferenceInvoiceID=".$ReferenceInvoiceID.",BillNO='".$QuoteReference."',NetAmount=".$NetAmount.",TotalTaxAmount=".$TotalTaxAmount.",TotalAmount=".$TotalAmount.",Notes='$Notes',EditLog='".$_SESSION['UserName']."',ShipperID=$ShipperID  where InvoiceID=".$InvoiceID;      	
            //delete preivous record 
            $sqldelete="delete from invoicedetail where InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sqldelete);
            }
            else
            {
            // insert query for invoice master 
             $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
			,TotalAmount
           ,DiscountAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
       	   ,DeliveryDate
           ,InvoiceStatus
           ,Notes
           ,VATLedgerID
           ,PurchaseLedgerID,CreateLog
       ) values (".$InvoiceID.",'".
			$InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",".$ChallanNo
           .",'".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
			.",".$TotalAmount
           .",".$DiscountAmount
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$ShipperID
           .",".$BiltyNo
           .",'".$DueDate."'
           ,".$InvoiceStatusID
       	   .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,'".$Notes."'
           ,".$VATLedgerID."
           ,".$PurchaseLedgerID.",'".$_SESSION['UserName']."')";
       		}//end else for insert 
           odbc_exec($connection,$sql) or die(odbc_error().$sql);
           if($InvoiceType==4 || $InvoiceType==3)
           {
           	if($InvoiceType==3)
           	{
           		$PurchaseReturnLedgerID=$_SESSION['SETTING']['PURCHASERETURN'];//;json_decode(getnamewhere("master_values","Code","MasterValue='PURCHASERETURN'",$connection));	
          // $PurchaseReturnLedgerID=$PurchaseReturnLedgerID->COAID;
       		}
           else
           	{
           	$PurchaseLedgerID=$_SESSION['SETTING']['PURCHASES'];//json_decode(getnamewhere("master_values","Code","MasterValue='PURCHASES'",$connection));
          // 	$PurchaseLedgerID=$PurchaseLedgerID->COAID;
           	}
           	$Posted=1;
           	$IsPostDated=1;
			$LedgerID=$SupplierID;
           	$AmountDebit=0;
           	$AmountCredit=0;
           	$Active=1;
           	$PeriodID=1;
           	$IsAuto=1;
           	$Cash=0;
           	$ContractID=0;
           	$VoucherDateTime=date("Y-m-d m:i:s");
           	$PaymentType="Credit";
           	$ReferenceInvoiceID=$InvoiceID;
           	$ReferenceVoucherID=0;
           	$VoucherPostDateTime=0;
           	$VoucherToBePosted=1;
           	$MultiVoucher=0;
           	$UserID=0;
           	$GroupID=1;
           	$LocationID=$GodownID;
           	$VoucherTypeID=71;
           	$VoucherDate=$InvoiceDate;
           	//$TotalAmount=$TotalAmount
           	$sql="select * from VoucherMaster where ReferenceInvoiceID=".$ReferenceInvoiceID;
           	$result=odbc_exec($connection,$sql);
           	$VoucherID=0;
           	if(odbc_num_rows($result)>0)
           	{
           		$row=odbc_fetch_array($result);
           		$VoucherID=$row['VoucherID'];
           	$sql="update VoucherMaster set TotalAmount=".$NetAmount.",EditLog='".$_SESSION['UserName']."' where ReferenceInvoiceID=".$ReferenceInvoiceID;
           	odbc_exec($connection,$sql) or die(odbc_error().$sql);	
           	}
           	else
           	{
           	$VoucherID=getmaxId("VoucherMaster","VoucherID",$connection)+1;
           	if($InvoiceType==4)
           	{
           	$where="VoucherTypeID=71";	
           	$VoucherNo=generateCode("VoucherMaster","VoucherNo",$where,$connection)+1;

           	//getnamesingle("TablesMaster","LastID","TableID","71",$connection)+1;
           	$VoucherNo2=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
           	$VoucherNo="PIV-".$VoucherNo2;
           	$ACNarration='AUTO VOUCHER for DOC: '.$VoucherNo.' from Purchase Invoice';
           	$VoucherTypeID=71;
           	}
           	if($InvoiceType==3)
           	{
           	$where="VoucherTypeID=72";           		
//           	$VoucherNo=getnamesingle("TablesMaster","LastID","TableID","72",$connection)+1;
            $VoucherNo=generateCode("VoucherMaster","VoucherNo",$where,$connection)+1;
 
           	$VoucherNo2=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
           	$VoucherNo="PR-".$VoucherNo2;
           	$ACNarration='AUTO VOUCHER for DOC: '.$VoucherNo.' from Purchase Return Invoice';
           	$VoucherTypeID=72;
           	}
           	$VoucherDateTime=date("Y-m-d m:i:s");
           	//insert into voucher 
           	$sql="INSERT INTO [dbo].[VoucherMaster]
           ([VoucherID]
           ,[VoucherNo]
           ,[TotalAmount]
           ,[Active]
           ,[VoucherDate]
           ,[Narration]
           ,[Posted]
           ,[IsPostDated]
           ,[VoucherTypeID]
           ,[PeriodID]
           ,[ReferenceInvoiceID]
           ,[LedgerID]
           ,[AmountDebit]
           ,[AmountCredit]
           ,[IsAuto]
           ,[LocationID]
           ,[ReferenceVoucherID]
           ,[GroupID]
           ,[MultiVoucher]
           ,[VoucherToBePosted]
           ,[Cash]
           ,[ContractID]
           ,[UserID]
           ,[VoucherDateTime]
           ,[PaymentType],CreateLog)
     VALUES($VoucherID
           ,'$VoucherNo'
           ,$NetAmount
           ,$Active
           ,'$VoucherDate'
           ,'$ACNarration'
           ,$Posted
           ,$IsPostDated
           ,$VoucherTypeID
           ,$PeriodID
           ,$ReferenceInvoiceID
           ,$SupplierID
           ,$AmountDebit
           ,$AmountCredit
           ,$IsAuto
           ,$LocationID
           ,$ReferenceVoucherID
           ,$GroupID
           ,$MultiVoucher
           ,$VoucherToBePosted
           ,$Cash
           ,$ContractID
           ,$UserID
           ,'$VoucherDateTime'
           ,'$PaymentType','".$_SESSION['UserName']."'

     )

           	";
            odbc_exec($connection,$sql) or die(odbc_error().$sql);	
           	}
           // enter for voucher detail 
           	//delete previous record 
           	$sqldelete="delete from voucherdetails where ReferenceInvoiceID=".$ReferenceInvoiceID;
           	odbc_exec($connection,$sqldelete);
            //Purchase 
            $TransactionType="PURCHASE A/C";
            $Debit=$TotalAmount;
            $Credit=$TotalAmount;
            if($InvoiceType==3)
            $CreditLedgerID=$PurchaseReturnLedgerID;//$SupplierID; credit
            else
            $CreditLedgerID=$SupplierID;//$SupplierID;
            $CostCenterID=$GodownID;
            $IsDelete=0;
            $DebitCostCenterID=$GodownID;
            $Narrationdetail="Narration details here";
            if($InvoiceType==3)
            $LedgerID=$SupplierID;//debit
            else 
            $LedgerID=$PurchaseLedgerID;

             $sqldetail="INSERT INTO [dbo].[VoucherDetails]
           ([VoucherID]
           ,[LedgerID]
           ,[Debit]
           ,[Credit]
           ,[Narration]
           ,[ReferenceInvoiceID]
           ,[CreditLedgerID]
           ,[CostCenterID]
           ,[IsDelete]
           ,[DebitCostCenterID]
           ,[TransactionType])
     VALUES($VoucherID
           ,$LedgerID
           ,$Debit
           ,$Credit
           ,'$Narrationdetail'
           ,$ReferenceInvoiceID
           ,$CreditLedgerID
           ,$CostCenterID
           ,$IsDelete
           ,$DebitCostCenterID
           ,'$TransactionType')";
 odbc_exec($connection,$sqldetail) or die(odbc_error().$sqldetail);	

            $TransactionType="VAT A/C";
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
            if($InvoiceType==3)
            $CreditLedgerID=$VATLedgerID;//purchase return VAT CREDIT	
            else	
            $CreditLedgerID=$SupplierID;//$SupplierID purchases Supplier credit
            $CostCenterID=$GodownID;
            $IsDelete=0;
            $DebitCostCenterID=$GodownID;
            $Narrationdetail="Narration details here";
            if($InvoiceType==3)
            $LedgerID=$SupplierID;//$VATLedgerID;// supplier debit
        	else
        	$LedgerID=$VATLedgerID;	//purchase VAT Debit
             $sqldetail="INSERT INTO [dbo].[VoucherDetails]
           ([VoucherID]
           ,[LedgerID]
           ,[Debit]
           ,[Credit]
           ,[Narration]
           ,[ReferenceInvoiceID]
           ,[CreditLedgerID]
           ,[CostCenterID]
           ,[IsDelete]
           ,[DebitCostCenterID]
           ,[TransactionType])
     VALUES($VoucherID
           ,$LedgerID
           ,$Debit
           ,$Credit
           ,'$Narrationdetail'
           ,$ReferenceInvoiceID
           ,$CreditLedgerID
           ,$CostCenterID
           ,$IsDelete
           ,$DebitCostCenterID
           ,'$TransactionType')";
            odbc_exec($connection,$sqldetail) or die(odbc_error().$sqldetail);	
           }//end if invoicetype=4 and 3
            // detail fields
            //delete preivous record 
              $sql="delete from invoiceDetail where InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sql);
       //     print_r($_REQUEST);
            for($a=0;$a<count($mrdetail);$a++)
            {
            $Flag =isset($mrdetail[$a]->Flag)?$mrdetail[$a]->Flag:'';
            if($Flag!="D")
            {
//
            	if($InvoiceType==41)
            	{
			/*	$ItemID=isset($mrdetail[$a]->ItemID)?$mrdetail[$a]->ItemID:0;
				$ItemName =isset($mrdetail[$a]->ItemName)?$mrdetail[$a]->ItemName:'';
            $Color =isset($mrdetail[$a]->Color)?$mrdetail[$a]->Color:'';
            $Size =isset($mrdetail[$a]->Size)?$mrdetail[$a]->Size:'';
            $Barcode =isset($mrdetail[$a]->Barcode)?$mrdetail[$a]->Barcode:'';
            $Category =isset($mrdetail[$a]->Category)?$mrdetail[$a]->Category:'';
            $Brand =isset($mrdetail[$a]->Brand)?$mrdetail[$a]->Brand:'';
            $Item_KeyField =isset($mrdetail[$a]->KeyField)?$mrdetail[$a]->KeyField:'';*/
            	}
            
            	//Item_ItemID
            $ItemID =isset($mrdetail[$a]->Item_ItemID)?$mrdetail[$a]->Item_ItemID:'0';
            $JobCardItem=isset($mrdetail[$a]->JobCardItem)?$mrdetail[$a]->JobCardItem:'';
            /*if($JobCardItem!="")$ItemID=getnamesingle("Inventory","ID","Name","'".$JobCardItem."'",$connection);*/ 
            if($ItemID=="")$ItemID=0;
            $ItemName =isset($mrdetail[$a]->Item_ItemName)?$mrdetail[$a]->Item_ItemName:'';

            $Color =isset($mrdetail[$a]->Item_Color)?$mrdetail[$a]->Item_Color:'';
            $Size =isset($mrdetail[$a]->Item_Size)?$mrdetail[$a]->Item_Size:'';
            $Barcode =isset($mrdetail[$a]->Item_Barcode)?$mrdetail[$a]->Item_Barcode:'';
            $Category =isset($mrdetail[$a]->Item_Category)?$mrdetail[$a]->Item_Category:'';
            $Brand =isset($mrdetail[$a]->Item_Brand)?$mrdetail[$a]->Item_Brand:'';
            $Item_KeyField =isset($mrdetail[$a]->Item_KeyField)?$mrdetail[$a]->Item_KeyField:'';
            
            $UnitPrice =(isset($mrdetail[$a]->Rate) && $mrdetail[$a]->Rate!="")?$mrdetail[$a]->Rate:0;
            $StockQty =isset($mrdetail[$a]->StockQty)?$mrdetail[$a]->StockQty:0;
            $ItemTable =isset($mrdetail[$a]->ItemTable)?$mrdetail[$a]->ItemTable:'';
            $Qty =isset($mrdetail[$a]->Qty)?$mrdetail[$a]->Qty:0;
   $ReceivedQty=(isset($mrdetail[$a]->ReceivedQty) && $mrdetail[$a]->ReceivedQty!="")?(double)$mrdetail[$a]->ReceivedQty:0;
    $Amount =(isset($mrdetail[$a]->Amount) && $mrdetail[$a]->Amount>0)?$mrdetail[$a]->Amount:($ReceivedQty*$UnitPrice);
            $Discount =(isset($mrdetail[$a]->Discount) && $mrdetail[$a]->Discount>=0)?(double)$mrdetail[$a]->Discount:0;
            $TaxPercent =(isset($mrdetail[$a]->VAT) && $mrdetail[$a]->VAT>0)?(double)$mrdetail[$a]->VAT:0;
            $NetAmount =(isset($mrdetail[$a]->NetAmount) && $mrdetail[$a]->NetAmount>0)?$mrdetail[$a]->NetAmount:0;
            $TaxAmount =(isset($mrdetail[$a]->VATAmount) && $mrdetail[$a]->VATAmount>0)?$mrdetail[$a]->VATAmount:0;
            $DiscountAmount =(isset($mrdetail[$a]->DiscountAmount) && $mrdetail[$a]->DiscountAmount>0)?$mrdetail[$a]->DiscountAmount:0;
            $Attr2 =isset($mrdetail[$a]->PartNumber)?$mrdetail[$a]->PartNumber:'';
            $Attr1 =isset($mrdetail[$a]->Specification)?$mrdetail[$a]->Specification:'';
            $Narration =isset($mrdetail[$a]->Narration)?$mrdetail[$a]->Narration:'';
            $ReferenceTransactionID =isset($mrdetail[$a]->ReferenceTransactionID)?$mrdetail[$a]->ReferenceTransactionID:'';
            $JobCardItem =isset($mrdetail[$a]->JobCardItem)?$mrdetail[$a]->JobCardItem:'';
            $TransactionID =isset($mrdetail[$a]->TransactionID)?$mrdetail[$a]->TransactionID:'';
            $VATPercent=$TaxPercent;
            $VATAmount=$TaxAmount;
            $UnitID=1;
            $TotalNetAmount=0;
            if($ReferenceTransactionID>0)
            {
            	if($InvoiceType==100 || $InvoiceType==4)
            	{
            		$istatus=4;
            	}	
            	else
            	{
            		$istatus=2;
            	}
            	 $sqlupdateinvoice="update invoicedetail set ReceivedQty=(isnull(ReceivedQty,0)+$Qty) where TransactionID=".$ReferenceTransactionID;
            	
            	odbc_exec($connection, $sqlupdateinvoice);
             	$sqlupdatestatus="update invoicemaster set InvoiceStatus=$istatus where invoiceid in(select invoiceid from invoiceDetail where TransactionID=".$ReferenceTransactionID.")";
            	odbc_exec($connection, $sqlupdatestatus);
            	$ReferenceInvoiceID=getnamesingle("InvoiceDetail","InvoiceID","TransactionID",$ReferenceTransactionID,$connection);
            if($ReferenceInvoiceID>0)
            {
            	$sqlcheck="select * from invoiceDetail where invoiceid=$ReferenceInvoiceID and (qty-receivedQty)>0";//check remainig quantity 
            	$resultcheck=odbc_exec($connection,$sqlcheck);
            	if(odbc_num_rows($resultcheck)<1)
            	{
            		//update Invoice
            		$updatelpo="update InvoiceMaster set InvoiceStatus=4 where InvoiceID=$ReferenceInvoiceID";
            		odbc_exec($connection,$updatelpo);
            	}
            }

            }
            else
            {
            	$ReferenceTransactionID=0;
            }
              $TransactionID=getmaxId("invoiceDetail","TransactionID",$connection)+1;
               $sql="insert into invoicedetail (
InvoiceID
           ,ItemID
           ,UnitPrice
           ,QTY
           ,Amount
           ,UnitID
           ,NetAmount
           ,TaxPercent
           ,TaxAmount
           ,Narration
           ,TotalNetAmount
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4           
           ,VATPercent
           ,VATAmount
           ,ReceivedQty
           ,ReferenceTransactionID
        ) values("
		   .$InvoiceID."
           ,".$ItemID."
           ,".$UnitPrice."
           ,".$Qty."
           ,".$Amount."
           ,".$UnitID."
           ,".$NetAmount."
           ,".$TaxPercent."
           ,".$TaxAmount."
           ,'".str_replace('_',' ',$Narration)."'
           ,".$TotalNetAmount."
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$JobCardItem."'
           ,'".$ItemName."'
           ,".$VATPercent."
           ,".$VATAmount."
           ,".$ReceivedQty."
           ,".$ReferenceTransactionID.           
    			")";
        	odbc_exec($connection, $sql) or die(odbc_error().$sql);
        	}//end if flag
        	}//end for loop
        	if (!odbc_error())
      odbc_commit($connection);
else
      odbc_rollback($connection);
//            		$res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
        $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
		echo json_encode($res);
            }// insert mrq
                        		$res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');

		//echo json_encode($res);//implode(",",$res);		
   	}//end action
//}

?>