<?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'];	
			        //$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 (!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']=="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 inner join godowns  as g on i.Shipperid=g.GodownID
   inner join godowns as c on c.GodownID=i.GodownID
   inner join invoicedetail as d on d.InvoiceID=i.InvoiceID
   inner 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 inner 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']))
			  $sql="  select ROW_NUMBER() OVER (
            ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 as Location,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;
   else
    $sql="  select ROW_NUMBER() OVER (
            ORDER BY [InvoiceType]
   ) row_num,c.Name as Company,c.AdditionalInfo1 as Location,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']."'";	
		
   $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(!isset($_GET['all']))
$sql="select * from view_MRQ_LIST where InvoiceType=".$InvoiceType." and InvoiceID=".$InvoiceID;
else
$sql="select * from view_MRQ_LIST where InvoiceType=".$InvoiceType." and InvoiceID=".$InvoiceID." 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)) {
  	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']);
        foreach ($row as $key => $value) {
        	# code...
        	$row[$key]=utf8_encode($value);
        }
    $data ['allinvoice'][]=$row;
  		}
  		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="";
    	}
  		}//end while

   if($InvoiceID!="")
  	{
  	  $sql="   select i.ID as itemid,i.name as itemname,i.barcode as barcode,cast(d.unitprice as numeric) as unitprice,qty,amount,cast(d.vatpercent as numeric) as vatpercent,cast(VATAmount as numeric) as vatamount,cast(discountpercent as numeric) as discountpercent,cast(discountamount as numeric) 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
		{

	 /* $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']))
		$sql="select * from view_MRQ_LIST2 where InvoiceType=".$InvoiceType;
	else
$sql="select * from view_MRQ_LIST2 where 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']);
	$data[]=$row;
  		}//end while
  		
  		echo json_encode($data); 
  		}//end else 
  	}//end permission
  		// code ofr details
  		//print_r($data);
//	code for item search 
  		}//end MRQ LIST

  		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) as CostPrice,cast(StandardPrice2 as numeric) as WholeSalePrice,cast(StandardPrice1 as numeric) as RetailPrice,cast(MinPriceLevel as numeric) as MinPriceLevel,cast(CommisionPercent as numeric) as CommisionPercent,cast(CommisionAmount as numeric) as CommisionAmount,cast(MinQtyLevel as numeric) as MinQtyLevel,cast(MaxQtyLevel as numeric) as MaxQtyLevel,KeyField,ShowInPurchases,ShowInSales,IsFixedAsset,ShowInStock,IsNonStockAble,Details,LastModificationTimeStamp,cast(VATPercent as numeric) 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";
   }
   else
   	$stocksql="";
    $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(stock),0) from stockposition where itemid=i.ID) 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." i.[group]=0 and   i.ProductBaseType='".$ProductBaseType."' $stocksql  order by i.CompanyID";
   // 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")
   	{

   		odbc_autocommit($connection, FALSE);


   		$master=array();
   		//print_r($_POST);
			$master=$_POST['data'];
			$details=$_POST['details'];
			$masterdata=$master;//$master[0];
			//$masterdata=urlencode($masterdata);
			//$detaildata=$details[0];
			//print_r($details);
			//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);
			//$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($_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:'';
            $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 
          //return;
            $sqldelete="delete from invoicedetail where InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sqldelete);
            }
            else
            {
            //	return;
            // 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);
            
   	} 	
   	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
//}

?>