<?php
include_once('database_connection.php');
//error_reporting(0);
if(isset($_GET['action']))
{
  
  if($_GET['action']=="getInvoiceService")
  {

  $data=array();

    if(isset($_GET['Customer_Email']) && $_GET['Customer_Email']!="")
    {
    $Email=$_GET['Customer_Email'];
    $Email="i.Email like '%".$Email."%' and ";
    }
    else
    {
  $Email="";
    }
    if(isset($_GET['Customer_MobileNumber']) && $_GET['Customer_MobileNumber']!="")
    {
    $MobileNumber=$_GET['Customer_MobileNumber'];
    $MobileNumber="i.MobileNumber like '%".$MobileNumber."%' and ";
    }
    else
    {
  $MobileNumber="";
    }
    if(isset($_GET['Customer_PlateNumber']) && $_GET['Customer_PlateNumber']!="")
    {
    $PlateNumber=$_GET['Customer_PlateNumber'];
    $PlateNumber="i.PlateNumber like '%".$PlateNumber."%' and ";
    }
    else
    {
  $PlateNumber="";
    }

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

    if(isset($_GET['EmployeeName']) && $_GET['EmployeeName']!="")
    {
    $EmployeeName=$_GET['EmployeeName'];
    $EmployeeName="i.Name like '%".$EmployeeName."%' and ";
    }
    else
    {
  $EmployeeName="";
    }
    if(isset($_GET['EmployeeCode']) && $_GET['EmployeeCode']!="")
    {
    $EmployeeCode=$_GET['EmployeeCode'];
    $EmployeeCode="i.Code like '%".$EmployeeCode."%' and ";
    }
    else
    {
  $EmployeeCode="";
    }

    if(isset($_GET['ReferenceNo']) && $_GET['ReferenceNo']!="")
    {
    $KeyField=$_GET['ReferenceNo'];
    $KeyField="i.KeyField like '%".$KeyField."%' and ";
    }
    else
    {
  $KeyField="";
    }

$searchbox=$MobileNumber.$CustomerName.$Email.$PlateNumber.$KeyField.$EmployeeCode.$EmployeeName;


    $GodownID=$_GET['GodownID'];
      $sql="select
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.Name as CompanyShortForm,CustomerName as JC_CustomerName,MobileNumber as JC_MobileNumber,PlateNumber as JC_PlateNumber,ChassisNumber as JC_ChassisNumber,InvoiceDate,i.KeyField as KeyField,'' as CreateByUserName,InvoiceID,DeliveryDate,i.Narration as Narration,g.Name as Department,g.godownid as supplier,c.Name as Location,InvoiceStatus,'' as col_Action ,i.godownid as GodownID,NetAmount,TotalQty
   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  i.GodownID=".$GodownID." and i.InvoiceType=5 and i.CreateLog='".$_SESSION['UserName']."' and i.ItemID<1";

  $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {

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

  }
//get service item 
  if($_GET['action']=="getInvoiceServiceItem")
  {


  $InvoiceID=$_GET['InvoiceID'];
     $sql="select
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.Name as CompanyName,CustomerName as customerName,MobileNumber as mobilenumber,PlateNumber as platenumber,ChassisNumber as JC_ChassisNumber,InvoiceDate,i.KeyField as keyfield,biltyno,'' as CreateByUserName,InvoiceID,DeliveryDate,i.Narration as Narration,g.Name as Department,g.godownid as supplier,c.Name as Location,InvoiceStatus,'' as col_Action ,i.godownid as GodownID,NetAmount,TotalQty,TotalCurrencyAmount as cashpaid,CreditCard as creditcard,cashrefund as cashrefund
   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   i.InvoiceID=".$InvoiceID." and i.InvoiceType=5 ";
  $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data[]=$row;
    }

    $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as CompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,i.Under Category,i.Name as itemname,i.Model as brand,i.KeyField as KeyField,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,i.ID as itemid
   ,StandardPrice2 as unitprice,amount,discountpercent,discountamount,d.taxpercent as vatpercent,d.taxAmount as vatamount,netamount,transactionid,d.Narration as detailnarration from  invoiceDetail as d 
   left outer join inventory as i on i.ID=d.ItemID
   left outer join Godowns as g on i.CompanyID=g.GodownID where InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['detailitems'][]=$row;
    }   

    echo json_encode($data);


  }//get invoice service item

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

  $data=array();
$InvoiceType=0;
if(isset($_GET['InvoiceType']) && $_GET['InvoiceType']!="")
    {
    $InvoiceType=$_GET['InvoiceType'];
    //$Email="i.Email like '%".$Email."%' and ";
    }
    else
    {
      $InvoiceType=8;
    }

    if(isset($_GET['Customer_Email']) && $_GET['Customer_Email']!="")
    {
    $Email=$_GET['Customer_Email'];
    $Email="i.Email like '%".$Email."%' and ";
    }
    else
    {
  $Email="";
    }
    if(isset($_GET['Customer_MobileNumber']) && $_GET['Customer_MobileNumber']!="")
    {
    $MobileNumber=$_GET['Customer_MobileNumber'];
    $MobileNumber="i.MobileNumber like '%".$MobileNumber."%' and ";
    }
    else
    {
  $MobileNumber="";
    }
    if(isset($_GET['Customer_PlateNumber']) && $_GET['Customer_PlateNumber']!="")
    {
    $PlateNumber=$_GET['Customer_PlateNumber'];
    $PlateNumber="i.PlateNumber like '%".$PlateNumber."%' and ";
    }
    else
    {
  $PlateNumber="";
    }

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

    if(isset($_GET['EmployeeName']) && $_GET['EmployeeName']!="")
    {
    $EmployeeName=$_GET['EmployeeName'];
    $EmployeeName="i.Name like '%".$EmployeeName."%' and ";
    }
    else
    {
  $EmployeeName="";
    }
    if(isset($_GET['EmployeeCode']) && $_GET['EmployeeCode']!="")
    {
    $EmployeeCode=$_GET['EmployeeCode'];
    $EmployeeCode="i.Code like '%".$EmployeeCode."%' and ";
    }
    else
    {
  $EmployeeCode="";
    }

    if(isset($_GET['ReferenceNo']) && $_GET['ReferenceNo']!="")
    {
    $KeyField=$_GET['ReferenceNo'];
    $KeyField="i.KeyField like '%".$KeyField."%' and ";
    }
    else
    {
  $KeyField="";
    }

$searchbox=$MobileNumber.$CustomerName.$Email.$PlateNumber.$KeyField.$EmployeeCode.$EmployeeName;


    $GodownID=$_GET['GodownID'];
      $sql="select
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.Name as CompanyShortForm,CustomerName as JC_CustomerName,MobileNumber as JC_MobileNumber,PlateNumber as JC_PlateNumber,ChassisNumber as JC_ChassisNumber,InvoiceDate,i.KeyField as KeyField,'' as CreateByUserName,InvoiceID,DeliveryDate,i.Narration as Narration,g.Name as Department,g.godownid as supplier,c.Name as Location,InvoiceStatus,'' as col_Action ,i.godownid as GodownID,NetAmount,TotalQty,symreceived
   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  i.GodownID=".$GodownID." and i.InvoiceType=$InvoiceType";//and CreateLog='$_'
  $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data[]=$row;
    }
    echo json_encode($data);  

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

	$InvoiceID=$_GET['InvoiceID'];
		 $sql="select
		ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.Name as CompanyName,c.AdditionalInfo2 as CompanyShortForm,CustomerName as customerName,MobileNumber as mobilenumber,PlateNumber as platenumber,ChassisNumber as JC_ChassisNumber,InvoiceDate,i.KeyField as keyfield,biltyno,i.CreateLog as CreateByUserName,i.InvoiceID as InvoiceID,DeliveryDate,i.Narration as Narration,g.Name as Department,g.godownid as supplier,c.Name as Location,InvoiceStatus,'' as col_Action ,i.godownid as GodownID,NetAmount,TotalQty,TotalCurrencyAmount as cashpaid,CreditCard as creditcard,cashrefund as cashrefund,symreceived,i.TRNNo as TRNNo ,keyno,parkingno,(select count(*) from InvoiceMaster where CreateLog='".$_SESSION['UserName']."' and InvoiceDate='".date('Y-m-d')."') as counter
   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   i.InvoiceID=".$InvoiceID." and i.InvoiceType in(18,8,5) ";
   
	$result=odbc_exec($connection,$sql);
		while($row=odbc_fetch_array($result))
		{
			$data[]=$row;
		}

		$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as CompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,i.Under Category,i.Name as itemname,i.Model as brand,i.KeyField as KeyField,InvoiceID,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,i.ID as itemid
   ,StandardPrice2 as unitprice,amount,discountpercent,discountamount,d.taxpercent as vatpercent,d.taxamount as vatamount,netamount,transactionid,d.Narration as detailnarration from  invoiceDetail as d 
   left outer join inventory as i on i.ID=d.ItemID
   left outer join Godowns as g on i.CompanyID=g.GodownID where InvoiceID=".$InvoiceID."";
		$result=odbc_exec($connection,$sql);
		while($row=odbc_fetch_array($result))
		{
			$data['detailitems'][]=$row;
		}		

		echo json_encode($data);

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



      odbc_autocommit($connection, FALSE);
    $main=json_decode($_POST['data']);
   /* print_r($main);
   return;*/
    $details=$_POST['details'];
  /*
    $checklistdetail=$_POST['checklistdetail'];
    $warningdetail=$_POST['warningdetail'];
    $inspectiondetail=$_POST['inspectiondetail'];
*/
    $mrdetails=json_decode($details);
    //$sql="update InvoiceMaster set ";
    /*foreach($main as $key=>$value )
    {

      //echo $key."---".$value;
      if(getDataType2($connection,"invoicemaster",$key)==1)
          {

            $sql.=$key."='".$value."',";
          }
          else
          {
            if($value=="")$value="0";
          $sql .="$key=".$value.",";  
          }
    }*/
      $CardNumber =isset($main->CardNumber)?$main->CardNumber:0;
      $ShipperID =isset($main->ShipperID)?$main->ShipperID:0;
            $GodownID =isset($main->GodownID)?$main->GodownID:0;
            $SupplierID =isset($main->SupplierID)?$main->SupplierID:0;
            $SupplierName =isset($main->SupplierName)?$main->SupplierName:'';
            $Location =isset($main->Location)?$main->Location:0;
          //  $CashRefund =isset($main->CashRefund)?$main->CashRefund:0;
            $CreditCard =(isset($main->CreditCard) && $main->CreditCard>0)?str_replace(",",".",$main->CreditCard):0;
            $TotalCurrencyAmount =(isset($main->CashReceived) && $main->CashReceived>0)?str_replace(",",".",$main->CashReceived):0;
          $CashRefund=(isset($main->CashRefund) && $main->CashRefund>0)?str_replace(",",".",$main->CashRefund):0;

            $Narration =isset($main->Narration)?$main->Narration:'';
            $InvoiceType =isset($main->InvoiceType)?$main->InvoiceType:0;
            $QuoteReference =isset($main->QuoteReference)?$main->QuoteReference:null;
            $Notes =isset($main->Notes)?$main->Notes:'';
            $DueDate =isset($main->DeliveryDate)?$main->DeliveryDate:'';
            $InvoiceDate =isset($main->BillDate)?$main->BillDate:'';
            $InvoiceID =isset($main->InvoiceID)?$main->InvoiceID:0;
            $PurchaseLedgerID =isset($main->DebitToHeadID)?$main->DebitToHeadID:0;
            $VATLedgerID =isset($main->VATLedgerID)?$main->VATLedgerID:0;
            $TotalAmount =str_replace('_','.',isset($main->TotalAmt)?$main->TotalAmt:0);
            $DiscountAmount =str_replace('_','.',isset($main->TotalDisountAmount)?$main->TotalDisountAmount:0);
            $TotalTaxAmount =str_replace('_','.',isset($main->TotalTaxAmount)?$main->TotalTaxAmount:0);
            $InculsiveAmount =str_replace('_','.',isset($main->InculsiveAmount)?$main->InculsiveAmount:0);
            $NetAmount =str_replace('_','.',isset($main->NetAmount)?$main->NetAmount:0);
            $MobileNumber =isset($main->Mobile)?$main->Mobile:'';
            $Email =isset($main->Email)?$main->Email:'';
            $CustomerName =isset($main->CustomerName)?$main->CustomerName:'';
            $ChassisNumber =isset($main->ChassisNumber)?$main->ChassisNumber:'';
            $PlateNumber =isset($main->PlateNumber)?$main->PlateNumber:'';
            $TRNNo =isset($main->TRNNo)?$main->TRNNo:'-';
            $PreparedBy =isset($main->PreparedBy)?$main->PreparedBy:'';
            $CustomerType =isset($main->CustomerType)?$main->CustomerType:0;
            $VehicleBrand =isset($main->VehicleBrand)?$main->VehicleBrand:0;
            $ChallanNo =isset($main->ChallanNo)?$main->ChallanNo:0;
            $VehicleModel =isset($main->VehicleModel)?$main->VehicleModel:0; 
            $VehicleType =isset($main->VehicleType)?$main->VehicleType:0; 
            $VehicleColor =isset($main->VehicleColor)?$main->VehicleColor:0;  
            $VehicleYear =isset($main->VehicleYear)?$main->VehicleYear:0;  
            $FuelLevel =isset($main->FuelLevel)?$main->FuelLevel:0;  
            $MulkiyaNo =isset($main->MulkiyaNo)?$main->MulkiyaNo:0;  
            $ParkingNo =isset($main->ParkingNo)?$main->ParkingNo:'-';  
            $KeyNo =isset($main->KeyNo)?$main->KeyNo:'-';  
            $SalesManID =isset($main->SalesManID)?$main->SalesManID:0;  
      $SalesManID2 =isset($main->SalesManID2)?$main->SalesManID2:0; 
      $BiltyNo =isset($main->BiltyNo)?$main->BiltyNo:0; 
      //biltyno 
           /* $SalesManID=0;
            $SalesManID2=0;*/

            $PassCode='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)$GodownID=getnamesingle("invoicemaster","GodownID","InvoiceID",$ReferenceInvoiceID,$connection);
            $BiltyNo='0';
            $ItemID='';
            $InvoiceStatusID=1;
            if($InvoiceID=="")$InvoiceID=0;
            $DeliveryDate=$DueDate;
        $sql="select * from invoicemaster where invoiceid=".$InvoiceID;
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {
              $row=odbc_fetch_array($result);
              $KeyField=$row['KeyField'];
     $sql="update InvoiceMaster set SupplierID=".$SupplierID.",MobileNumber='".$MobileNumber."',CustomerName='".$CustomerName."',Email='".$Email."',InvoiceDate='".$InvoiceDate."',DeliveryDate='".$DeliveryDate."',PlateNumber='".$PlateNumber."',ChassisNumber='".$ChassisNumber."',ChallanNo='".$ChallanNo."',SalesManID=".$SalesManID.",SalesManID2=".$SalesManID2.",TRNNo='".$TRNNo."',CustomerType=".$CustomerType.",VehicleBrand=".$VehicleBrand.",VehicleModel=".$VehicleModel.",VehicleType=".$VehicleType.",VehicleColor=".$VehicleColor.",VehicleYear=".$VehicleYear.",Notes='".$Notes."',FuelLevel=".$FuelLevel.",GodownID=".$GodownID.",InvoiceType=".$InvoiceType.",TotalAmount=".$TotalAmount.",DiscountAmount=".$DiscountAmount.",TotalTaxAmount=".$TotalTaxAmount.",NetAmount=".$NetAmount.",MulkiyaNo='".$MulkiyaNo."',ParkingNo='".$ParkingNo."',KeyNo='".$KeyNo."',PictureLocation='',CashRefund=".$CashRefund.",CreditCard=".$CreditCard.",TotalCurrencyAmount=".$TotalCurrencyAmount." where InvoiceID=".$InvoiceID;
         /*$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."  where InvoiceID=".$InvoiceID;*/       
            //delete preivous record 
            $sqldelete="delete from invoicedetail where InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sqldelete);
            }
            else
            {
            $InvoiceID=getmaxId("InvoiceMaster","InvoiceID",$connection)+1;
            $PictureLocation='';
            if($InvoiceType==8)
            {
            $where="InvoiceType=8 and GodownID=".$GodownID; 
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            if($GodownID==1)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="POS-MVR-".$KeyField2;
            }
            if($GodownID==2)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="POS-CCL-".$KeyField2;
            }
            if($GodownID==3)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="POS-RDL-".$KeyField2;
            }
            if($GodownID==4)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="POS-PWS-".$KeyField2;
            }
            $ACNarration='AUTO VOUCHER for DOC: '.$KeyField.' from Jobcard';
            }
            // 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
           ,VATLedgerID
           ,CashRefund
       ,CreditCard
       ,TotalCurrencyAmount
           ,PurchaseLedgerID
           ,MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,symCardNo
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",'".$ChallanNo
           ."','".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount
           .",".$DiscountAmount
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$ShipperID
           .",'".$BiltyNo
           ."','".$DueDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$CashRefund."
       ,".$CreditCard."
       ,".$TotalCurrencyAmount."
           ,".$PurchaseLedgerID."
           ,'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$SalesManID.",".$SalesManID2.",'".$TRNNo."',".$CustomerType.",".$VehicleBrand.",".$VehicleModel.",".$VehicleType.",".$VehicleColor.",".$VehicleYear.",'".$Notes."',".$FuelLevel.",'".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."','".$PictureLocation."','".$_SESSION['UserName']."','".$CardNumber."')";
          }//end else for insert */

          odbc_exec($connection,$sql) or die(odbc_error().$sql);
    //print_r(array_keys($_POST));
    //print_r(array_values($_POST));
    //$data=json_decode($_POST);
    //print_r($_POST);
          //code for details 
          insertInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);
//sym PAyment here 
 //enter in the invoicemaster 
   //delete previous card transaction 
   $sql="delete from cardtransaction where invoiceid=$InvoiceID";

  $date=Date("Y-m-d");
          $Debit=0;
$Credit=$NetAmount;
$LocationID=$GodownID;
    $Narration="SemNox Payment :Reference : $KeyField";
    $VoucherID=getNameSingle("VoucherMaster","VoucherID","ReferenceInvoiceID",$InvoiceID,$connection);
    if($VoucherID==null)$VoucherID=0;
    $CardID=getMaxId("CardTransaction","ID",$connection);
    if($CardID==null)$CardID=0+1;
    else
    $CardID=$CardID+1;  


  $sql="INSERT INTO [dbo].[CardTransaction]
           ([ID]
           ,[CardNumber]
           ,[COAID]
           ,[Debit]
           ,[Credit]
           ,[Narration]
           ,[TDate]
           ,[Reference]
           ,[VoucherID]
           ,[isActive]
           ,[CreateLog]
           ,[InvoiceID]
           ,[LocationID])
     VALUES($CardID,'$CardNumber',$SupplierID,$Debit,$Credit,'$Narration','$date','$KeyField',$VoucherID,1,'".$_SESSION['UserName']."',$InvoiceID,$LocationID)";
     odbc_exec($connection,$sql) or die(odbc_error().$sql);
     //update invoicemaster
     $sql="update invoicemaster set symreceived=$Credit,Paid=(isnull(Paid,0)+$Credit),InvoiceStatus=4 where InvoiceID=$InvoiceID";         
odbc_exec($connection,$sql) or die(odbc_error().$sql);
 // insert into cardtransaction 

$sql="insert into cardtransaction () values($InvoiceID,$CardNumber,$Debit,$Credit)";
//odbc_exec($connection,$sql) or die(odbc_error().$sql);
if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Invoice Generated Sucessfully');
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Generated');

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


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


      odbc_autocommit($connection, FALSE);
    $main=json_decode($_POST['data']);
   /* print_r($main);
   return;*/
    $details=$_POST['details'];
  /*
    $checklistdetail=$_POST['checklistdetail'];
    $warningdetail=$_POST['warningdetail'];
    $inspectiondetail=$_POST['inspectiondetail'];
*/
    $mrdetails=json_decode($details);
    //$sql="update InvoiceMaster set ";
    /*foreach($main as $key=>$value )
    {

      //echo $key."---".$value;
      if(getDataType2($connection,"invoicemaster",$key)==1)
          {

            $sql.=$key."='".$value."',";
          }
          else
          {
            if($value=="")$value="0";
          $sql .="$key=".$value.",";  
          }
    }*/
      $CardNumber =isset($main->CardNumber)?$main->CardNumber:0;
      $ShipperID =isset($main->ShipperID)?$main->ShipperID:0;
            $GodownID =isset($main->GodownID)?$main->GodownID:0;
            $SupplierID =isset($main->SupplierID)?$main->SupplierID:0;
            $SupplierName =isset($main->SupplierName)?$main->SupplierName:'';
            $Location =isset($main->Location)?$main->Location:0;
          //  $CashRefund =isset($main->CashRefund)?$main->CashRefund:0;
            $CreditCard =(isset($main->CreditCard) && $main->CreditCard>0)?str_replace(",",".",$main->CreditCard):0;
            $TotalCurrencyAmount =(isset($main->CashReceived) && $main->CashReceived>0)?str_replace(",",".",$main->CashReceived):0;
          $CashRefund=(isset($main->CashRefund) && $main->CashRefund>0)?str_replace(",",".",$main->CashRefund):0;

            $Narration =isset($main->Narration)?$main->Narration:'';
            $InvoiceType =isset($main->InvoiceType)?$main->InvoiceType:0;
            $QuoteReference =isset($main->QuoteReference)?$main->QuoteReference:null;
            $Notes =isset($main->Notes)?$main->Notes:'';
            $DueDate =isset($main->DeliveryDate)?$main->DeliveryDate:'';
            $InvoiceDate =isset($main->BillDate)?$main->BillDate:'';
            $InvoiceID =isset($main->InvoiceID)?$main->InvoiceID:0;
            $PurchaseLedgerID =isset($main->DebitToHeadID)?$main->DebitToHeadID:0;
            $VATLedgerID =isset($main->VATLedgerID)?$main->VATLedgerID:0;
            $TotalAmount =str_replace('_','.',isset($main->TotalAmt)?$main->TotalAmt:0);
            $DiscountAmount =str_replace('_','.',isset($main->TotalDisountAmount)?$main->TotalDisountAmount:0);
            $TotalTaxAmount =str_replace('_','.',isset($main->TotalTaxAmount)?$main->TotalTaxAmount:0);
            $InculsiveAmount =str_replace('_','.',isset($main->InculsiveAmount)?$main->InculsiveAmount:0);
            $NetAmount =str_replace('_','.',isset($main->NetAmount)?$main->NetAmount:0);
            $MobileNumber =isset($main->Mobile)?$main->Mobile:'';
            $Email =isset($main->Email)?$main->Email:'';
            $CustomerName =isset($main->CustomerName)?$main->CustomerName:'';
            $ChassisNumber =isset($main->ChassisNumber)?$main->ChassisNumber:'';
            $PlateNumber =isset($main->PlateNumber)?$main->PlateNumber:'';
            $TRNNo =isset($main->TRNNo)?$main->TRNNo:'-';
            $PreparedBy =isset($main->PreparedBy)?$main->PreparedBy:'';
            $CustomerType =isset($main->CustomerType)?$main->CustomerType:0;
            $VehicleBrand =isset($main->VehicleBrand)?$main->VehicleBrand:0;
            $ChallanNo =isset($main->ChallanNo)?$main->ChallanNo:0;
            $VehicleModel =isset($main->VehicleModel)?$main->VehicleModel:0; 
            $VehicleType =isset($main->VehicleType)?$main->VehicleType:0; 
            $VehicleColor =isset($main->VehicleColor)?$main->VehicleColor:0;  
            $VehicleYear =isset($main->VehicleYear)?$main->VehicleYear:0;  
            $FuelLevel =isset($main->FuelLevel)?$main->FuelLevel:0;  
            $MulkiyaNo =isset($main->MulkiyaNo)?$main->MulkiyaNo:0;  
            $ParkingNo =isset($main->ParkingNo)?$main->ParkingNo:'-';  
            $KeyNo =isset($main->KeyNo)?$main->KeyNo:'-';  
            $SalesManID =isset($main->SalesManID)?$main->SalesManID:0;  
      $SalesManID2 =isset($main->SalesManID2)?$main->SalesManID2:0; 
      $BiltyNo =isset($main->BiltyNo)?$main->BiltyNo:0; 
      //biltyno 
           /* $SalesManID=0;
            $SalesManID2=0;*/

            $PassCode='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)$GodownID=getnamesingle("invoicemaster","GodownID","InvoiceID",$ReferenceInvoiceID,$connection);
            $BiltyNo='0';
            $ItemID='';
            $InvoiceStatusID=1;
            if($InvoiceID=="")$InvoiceID=0;
            $DeliveryDate=$DueDate;
        $sql="select * from invoicemaster where invoiceid=".$InvoiceID;
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {
              $row=odbc_fetch_array($result);
              $KeyField=$row['KeyField'];
     $sql="update InvoiceMaster set SupplierID=".$SupplierID.",MobileNumber='".$MobileNumber."',CustomerName='".$CustomerName."',Email='".$Email."',InvoiceDate='".$InvoiceDate."',DeliveryDate='".$DeliveryDate."',PlateNumber='".$PlateNumber."',ChassisNumber='".$ChassisNumber."',ChallanNo='".$ChallanNo."',SalesManID=".$SalesManID.",SalesManID2=".$SalesManID2.",TRNNo='".$TRNNo."',CustomerType=".$CustomerType.",VehicleBrand=".$VehicleBrand.",VehicleModel=".$VehicleModel.",VehicleType=".$VehicleType.",VehicleColor=".$VehicleColor.",VehicleYear=".$VehicleYear.",Notes='".$Notes."',FuelLevel=".$FuelLevel.",GodownID=".$GodownID.",InvoiceType=".$InvoiceType.",TotalAmount=".$TotalAmount.",DiscountAmount=".$DiscountAmount.",TotalTaxAmount=".$TotalTaxAmount.",NetAmount=".$NetAmount.",MulkiyaNo='".$MulkiyaNo."',ParkingNo='".$ParkingNo."',KeyNo='".$KeyNo."',PictureLocation='',CashRefund=".$CashRefund.",CreditCard=".$CreditCard.",TotalCurrencyAmount=".$TotalCurrencyAmount." where InvoiceID=".$InvoiceID;
         /*$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."  where InvoiceID=".$InvoiceID;*/       
            //delete preivous record 
            $sqldelete="delete from invoicedetail where InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sqldelete);
            }
            else
            {
            $InvoiceID=getmaxId("InvoiceMaster","InvoiceID",$connection)+1;
            $PictureLocation='';
            if($InvoiceType==5)
            {
            $where="InvoiceType=5 and GodownID=".$GodownID; 
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            if($GodownID==1)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="MVR-".$KeyField2;
            }
            if($GodownID==2)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="CCL-".$KeyField2;
            }
            if($GodownID==3)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="RDL-".$KeyField2;
            }
            if($GodownID==4)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="PWS-".$KeyField2;
            }
            if($GodownID==19)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="FOTC-".$KeyField2;
            }
            $ACNarration='AUTO VOUCHER for DOC: '.$KeyField.' from Jobcard';
            }
            // 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
           ,VATLedgerID
           ,CashRefund
       ,CreditCard
       ,TotalCurrencyAmount
           ,PurchaseLedgerID
           ,MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,symCardNo
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",'".$ChallanNo
           ."','".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount
           .",".$DiscountAmount
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$ShipperID
           .",'".$BiltyNo
           ."','".$DueDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$CashRefund."
       ,".$CreditCard."
       ,".$TotalCurrencyAmount."
           ,".$PurchaseLedgerID."
           ,'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$SalesManID.",".$SalesManID2.",'".$TRNNo."',".$CustomerType.",".$VehicleBrand.",".$VehicleModel.",".$VehicleType.",".$VehicleColor.",".$VehicleYear.",'".$Notes."',".$FuelLevel.",'".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."','".$PictureLocation."','".$_SESSION['UserName']."','".$CardNumber."')";
          }//end else for insert */

          odbc_exec($connection,$sql) or die(odbc_error().$sql);
    //print_r(array_keys($_POST));
    //print_r(array_values($_POST));
    //$data=json_decode($_POST);
    //print_r($_POST);
          //code for details 
          insertInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);
//sym PAyment here 
 //enter in the invoicemaster 
   //delete previous card transaction 
   $sql="delete from cardtransaction where invoiceid=$InvoiceID";

  $date=Date("Y-m-d");
          $Debit=0;
$Credit=$NetAmount;
$LocationID=$GodownID;
    $Narration="SemNox Payment :Reference : $KeyField";
//code from here
             $fields=array();
              $VoucherID=getmaxId("VoucherMaster","VoucherID",$connection)+1;
         $fields['VoucherID']=$VoucherID;
           $fields['VoucherNo']=$KeyField;//isset($VoucherNo)?$VoucherNo:0;
           $fields['TotalAmount']=isset($NetAmount)?$NetAmount:0;
           $fields['Active']=1;//isset($Active)?$Active:0;
           $fields['VoucherDate']=isset($InvoiceDate)?$InvoiceDate:null;
           $fields['Narration']=isset($Narration)?$Narration:0;
           $fields['Posted']=1;//isset($Posted)?$Posted:0;
           $fields['IsPostDated']=0;//isset($IsPostDated)?$IsPostDated:0;
           $fields['VoucherTypeID']=8;//jobcard isset($VoucherTypeID)?$VoucherTypeID:0;
           $fields['PeriodID']=1;//isset($PeriodID)?$PeriodID:0;
           $fields['ReferenceInvoiceID']=isset($InvoiceID)?$InvoiceID:0;
           $fields['SupplierID']=isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($LedgerID)?$LedgerID:0;
           $fields['AmountDebit']=0;
           $fields['AmountCredit']=0;
           $fields['IsAuto']=1;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['ReferenceVoucherID']=isset($ReferenceVoucherID)?$ReferenceVoucherID:0;
           $fields['GroupID']=0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=0;//$TotalCurrencyAmount;//isset($Cash)?$Cash:0;
           $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['UserID']=isset($UserID)?$UserID:0;
           $fields['VoucherDateTime']=isset($InvoiceDate)?$InvoiceDate:date("Y-m-d m:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'Job Card';
         //  print_r($fields);
          InsertVoucherMaster($fields,$InvoiceType,$InvoiceID,$connection); 
            $TotalAmt=((isset($main->TotalAmt) && $main->TotalAmt!="") ?$main->TotalAmt:0);
    $TotalDisountAmount=((isset($main->TotalDisountAmount) && $main->TotalDisountAmount!="") ?$main->TotalDisountAmount:0);
    $TotalTaxAmount=((isset($main->TotalTaxAmount) && $main->TotalTaxAmount!="") ?$main->TotalTaxAmount:0);
    $NetAmount=((isset($main->NetAmount) && $main->NetAmount!="") ?$main->NetAmount:0);
    $InculsiveAmount=((isset($main->InculsiveAmount) && $main->InculsiveAmount!="") ?$main->InculsiveAmount:0);
    $CashRefund=((isset($main->CashRefund) && $main->CashRefund!="") ?$main->CashRefund:0);
    $CashPaid=((isset($main->CashPaid) && $main->CashPaid!="") ?$main->CashPaid:0);
    $CashAccountID=((isset($main->CashAccountID) && $main->CashAccountID!="") ?$main->CashAccountID:0);
    $CCAcountID=((isset($main->CCAcountID) && $main->CCAcountID!="") ?$main->CCAcountID:0);
    $CustomerID=((isset($main->CustomerID) && $main->CustomerID!="") ?$main->CustomerID:0);
    $SalesAccountID=((isset($main->SalesAccountID) && $main->SalesAccountID!="") ?$main->SalesAccountID:0);
    $VATAccountID=((isset($main->VATAccountID) && $main->VATAccountID!="") ?$main->VATAccountID:0);
    $VoucherTypeID=((isset($main->VoucherTypeID) && $main->VoucherTypeID!="") ?$main->VoucherTypeID:0);
/*
CASH DR 
CREDIT CARD DR  
VAT CR 
SALES CR 
*/
$CashAccountID=$_SESSION['SETTING']['CASHINHAND'];
$CashCustomer=$_SESSION['SETTING']['CASHCUSTOMERS'];
if($CustomerID=="")$CustomerID=$CashCustomer;
        $fdetails=array();  
        for($a=0;$a<2;$a++)
        {
           $fdetails['VoucherID']=$VoucherID;
           if($a==2 && $CustomerID<>$CashCustomer)
           {
            break;
           }
           if($a==0)
           {
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
            $CreditLedgerID=$VATAccountID;
            $LedgerID=$CustomerID;
           }
           if($a==1)
           {
            $Debit=($NetAmount-$TotalTaxAmount);
            $Credit=($NetAmount-$TotalTaxAmount);
            $CreditLedgerID=$SalesAccountID;
            $LedgerID=$CustomerID;
           }
            if($a==2)
           {
            $Debit=($TotalCurrencyAmount-$CashRefund);
            $Credit=($TotalCurrencyAmount-$CashRefund);
            $CreditLedgerID=$CustomerID;
            $LedgerID=$CashAccountID;
           }
           if($a==3)
           {
            $Debit=$CreditCard;
            $Credit=$CreditCard;
            $CreditLedgerID=$CustomerID;
            $LedgerID=$CCAcountID;
           }
           $fdetails['LedgerID']=$LedgerID;
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="POS ";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;
           $fdetails['TransactionType']="POS INVOICE"; 
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);              
        }//end for */


    $CardID=getMaxId("CardTransaction","ID",$connection);
    if($CardID==null)$CardID=0+1;
    else
    $CardID=$CardID+1;  


  $sql="INSERT INTO [dbo].[CardTransaction]
           ([ID]
           ,[CardNumber]
           ,[COAID]
           ,[Debit]
           ,[Credit]
           ,[Narration]
           ,[TDate]
           ,[Reference]
           ,[VoucherID]
           ,[isActive]
           ,[CreateLog]
           ,[InvoiceID]
           ,[LocationID])
     VALUES($CardID,'$CardNumber',$SupplierID,$Debit,$Credit,'$Narration','$date','$KeyField',$VoucherID,1,'".$_SESSION['UserName']."',$InvoiceID,$LocationID)";
     odbc_exec($connection,$sql) or die(odbc_error().$sql);
     //update invoicemaster
     $sql="update invoicemaster set symreceived=$Credit,Paid=(isnull(Paid,0)+$Credit),InvoiceStatus=4,EditLog='".$_SESSION['UserName']."' where InvoiceID=$InvoiceID";         
odbc_exec($connection,$sql) or die(odbc_error().$sql);
 // insert into cardtransaction 

$sql="insert into cardtransaction () values($InvoiceID,$CardNumber,$Debit,$Credit)";
//odbc_exec($connection,$sql) or die(odbc_error().$sql);
if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Invoice Generated Sucessfully','total_records'=>$InvoiceID);
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Generated');

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

}
if($_GET['action']=="insertJobCardInvoice")
{
    if(isset($_GET['DirectSave']))
    {
      $DirectSave=1;
    }
    else
    {
      $DirectSave=0;
    }
      odbc_autocommit($connection, FALSE);
    
    
    $main=json_decode($_POST['data']);
    /*print_r($main);
   return;*/
    $details=$_POST['details'];
  /*
    $checklistdetail=$_POST['checklistdetail'];
    $warningdetail=$_POST['warningdetail'];
    $inspectiondetail=$_POST['inspectiondetail'];
*/
    $mrdetails=json_decode($details);
/*    print_r($mrdetails);
    return;*/
    //$sql="update InvoiceMaster set ";
    /*foreach($main as $key=>$value )
    {

      //echo $key."---".$value;
      if(getDataType2($connection,"invoicemaster",$key)==1)
          {

            $sql.=$key."='".$value."',";
          }
          else
          {
            if($value=="")$value="0";
          $sql .="$key=".$value.",";  
          }
    }*/

//$main->CashPaid=0;
    if(isset($main->CashPaid))
  $main->CashPaid =($main->CashPaid!="")?$main->CashPaid:0;
    else
    $main->CashPaid=0;  

      $ShipperID =isset($main->ShipperID)?$main->ShipperID:0;
            $GodownID =isset($main->GodownID)?$main->GodownID:0;
            $SupplierID =isset($main->SupplierID)?$main->SupplierID:0;
            $SupplierName =isset($main->SupplierName)?$main->SupplierName:'';
            $Location =isset($main->Location)?$main->Location:0;
          //  $CashRefund =isset($main->CashRefund)?$main->CashRefund:0;
            $CreditCard =(isset($main->CreditCard) && $main->CreditCard>0)?str_replace(",",".",$main->CreditCard):0;
            $TotalCurrencyAmount =(isset($main->CashReceived) && $main->CashReceived>0)?str_replace(",",".",$main->CashReceived):$main->CashPaid;
          $CashRefund=(isset($main->CashRefund) && $main->CashRefund>0)?str_replace(",",".",$main->CashRefund):0;
            $Narration =isset($main->Narration)?$main->Narration:'';
            $InvoiceType =isset($main->InvoiceType)?$main->InvoiceType:0;
            $QuoteReference =isset($main->QuoteReference)?$main->QuoteReference:null;
            $Notes =isset($main->Notes)?$main->Notes:'';
            $DueDate =isset($main->DeliveryDate)?$main->DeliveryDate:'';
            $InvoiceDate =isset($main->BillDate)?$main->BillDate:'';
            $InvoiceID =isset($main->InvoiceID)?$main->InvoiceID:0;
            $PurchaseLedgerID =isset($main->DebitToHeadID)?$main->DebitToHeadID:0;
            $VATLedgerID =isset($main->VATLedgerID)?$main->VATLedgerID:0;
            $TotalAmount =str_replace('_','.',isset($main->TotalAmt)?$main->TotalAmt:0);
            $DiscountAmount =str_replace('_','.',isset($main->TotalDisountAmount)?$main->TotalDisountAmount:0);
            $TotalTaxAmount =str_replace('_','.',isset($main->TotalTaxAmount)?$main->TotalTaxAmount:0);
            $InculsiveAmount =str_replace('_','.',isset($main->InculsiveAmount)?$main->InculsiveAmount:0);
            $NetAmount =str_replace('_','.',isset($main->NetAmount)?$main->NetAmount:0);
            $MobileNumber =isset($main->Mobile)?$main->Mobile:'';
            $Email =isset($main->Email)?$main->Email:'';
            $CustomerName =isset($main->CustomerName)?$main->CustomerName:'';
            $ChassisNumber =isset($main->ChassisNumber)?$main->ChassisNumber:'';
            $PlateNumber =isset($main->PlateNumber)?$main->PlateNumber:'';
            $TRNNo =isset($main->TRNNo)?$main->TRNNo:'-';
            $PreparedBy =isset($main->PreparedBy)?$main->PreparedBy:'';
            $CustomerType =isset($main->CustomerType)?$main->CustomerType:0;
            $VehicleBrand =isset($main->VehicleBrand)?$main->VehicleBrand:0;
            $ChallanNo =isset($main->ChallanNo)?$main->ChallanNo:0;
            $VehicleModel =isset($main->VehicleModel)?$main->VehicleModel:0; 
            $VehicleType =isset($main->VehicleType)?$main->VehicleType:0; 
            $VehicleColor =isset($main->VehicleColor)?$main->VehicleColor:0;  
            $VehicleYear =isset($main->VehicleYear)?$main->VehicleYear:0;  
            $FuelLevel =isset($main->FuelLevel)?$main->FuelLevel:0;  
            $MulkiyaNo =isset($main->MulkiyaNo)?$main->MulkiyaNo:0;  
            $ParkingNo =isset($main->ParkingNo)?$main->ParkingNo:'-';  
            $KeyNo =isset($main->KeyNo)?$main->KeyNo:'-';  
            $SalesManID =isset($main->SalesManID)?$main->SalesManID:0;  
      $SalesManID2 =isset($main->SalesManID2)?$main->SalesManID2:0; 
      $BiltyNo =isset($main->BiltyNo)?$main->BiltyNo:0; 
      //biltyno 
           /* $SalesManID=0;
            $SalesManID2=0;*/

            $PassCode='0';
            $Active=1;
            if($DirectSave==1)
            $InvoiceStatus=4;
            else
            $InvoiceStatus=1;
              
            $KeyField="";
          //  $ChallanNo="0";
            $ItemID='0';
            $BillNO=$QuoteReference;
            $GRNno="0";
            $ReferenceInvoiceID="0";
            $ReferenceInvoiceID =isset($mrmaster->ReferenceInvoiceID)?$mrmaster->ReferenceInvoiceID:0;
            if($InvoiceType==6)$GodownID=getnamesingle("invoicemaster","GodownID","InvoiceID",$ReferenceInvoiceID,$connection);
            $BiltyNo='0';
            $ItemID='';
            if($DirectSave==1)
            $InvoiceStatusID=4;  
            else  
            $InvoiceStatusID=1;
            if($InvoiceID=="")$InvoiceID=0;
            $DeliveryDate=$DueDate;
        $sql="select * from invoicemaster where invoiceid=".$InvoiceID;
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {
              $row=odbc_fetch_array($result);
              $KeyField=$row['KeyField'];
     $sql="update InvoiceMaster set SupplierID=".$SupplierID.",MobileNumber='".$MobileNumber."',CustomerName='".$CustomerName."',Email='".$Email."',InvoiceDate='".$InvoiceDate."',DeliveryDate='".$DeliveryDate."',PlateNumber='".$PlateNumber."',ChassisNumber='".$ChassisNumber."',ChallanNo='".$ChallanNo."',SalesManID=".$SalesManID.",SalesManID2=".$SalesManID2.",TRNNo='".$TRNNo."',CustomerType=".$CustomerType.",VehicleBrand=".$VehicleBrand.",VehicleModel=".$VehicleModel.",VehicleType=".$VehicleType.",VehicleColor=".$VehicleColor.",VehicleYear=".$VehicleYear.",Notes='".$Notes."',FuelLevel=".$FuelLevel.",GodownID=".$GodownID.",InvoiceType=".$InvoiceType.",TotalAmount=".$TotalAmount.",DiscountAmount=".$DiscountAmount.",TotalTaxAmount=".$TotalTaxAmount.",NetAmount=".$NetAmount.",MulkiyaNo='".$MulkiyaNo."',ParkingNo='".$ParkingNo."',KeyNo='".$KeyNo."',PictureLocation='',CashRefund=".$CashRefund.",CreditCard=".$CreditCard.",TotalCurrencyAmount=".$TotalCurrencyAmount." where InvoiceID=".$InvoiceID;
         /*$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."  where InvoiceID=".$InvoiceID;*/       
            //delete preivous record 
            $sqldelete="delete from invoicedetail where InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sqldelete);
            }
            else
            {
            $InvoiceID=getmaxId("InvoiceMaster","InvoiceID",$connection)+1;
            $PictureLocation='';
            if($InvoiceType==5)
            {
            $where="InvoiceType=5 and GodownID=".$GodownID; 
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            if($GodownID==1)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="MVR-".$KeyField2;
            }
            if($GodownID==2)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="CCL-".$KeyField2;
            }
            if($GodownID==3)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="RDL-".$KeyField2;
            }
            if($GodownID==4)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="PWS-".$KeyField2;
            }
            if($GodownID==19)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="FOTC-".$KeyField2;
            }
            if($GodownID==20)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="AYQ-".$KeyField2;
            }
            $ACNarration='AUTO VOUCHER for DOC: '.$KeyField.' from Jobcard';
            }
            // 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
           ,VATLedgerID
           ,CashRefund
       ,CreditCard
       ,TotalCurrencyAmount
           ,PurchaseLedgerID
           ,MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",'".$ChallanNo
           ."','".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount
           .",".$DiscountAmount
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$ShipperID
           .",'".$BiltyNo
           ."','".$DueDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$CashRefund."
       ,".$CreditCard."
       ,".$TotalCurrencyAmount."
           ,".$PurchaseLedgerID."
           ,'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$SalesManID.",".$SalesManID2.",'".$TRNNo."',".$CustomerType.",".$VehicleBrand.",".$VehicleModel.",".$VehicleType.",".$VehicleColor.",".$VehicleYear.",'".$Notes."',".$FuelLevel.",'".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."','".$PictureLocation."','".$_SESSION['UserName']."')";
          }//end else for insert */

          odbc_exec($connection,$sql) or die(odbc_error().$sql);
    //print_r(array_keys($_POST));
    //print_r(array_values($_POST));
    //$data=json_decode($_POST);
    //print_r($_POST);
          //code for details 
          insertInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);
          /*    InsertJList($InvoiceID,$checklistdetail,'CheckList',$connection);
              InsertJList($InvoiceID,$warningdetail,'WarningList',$connection);
              InsertJList($InvoiceID,$inspectiondetail,'InspectionList',$connection);     */
              
              //remove if previous voucher exists 

              $sqlupdate="update VoucherMaster set active=0 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
              $sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
              //delete voucher 
              $sqldelete="delete from VoucherDetails where ReferenceInvoiceID=$InvoiceID";
               odbc_exec($connection,$sqlupdate); 
          // Insert Voucher 
/*          $where=" VoucherTypeID=8 and LocationID=".$GodownID;//jobcard ID 
              $KeyField=generateCode("VoucherMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            
/*            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="SALE-".$KeyField2;*/
 /*           if($GodownID==1)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="MVR-".$KeyField2;
            }
            if($GodownID==2)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="CCL-".$KeyField2;
            }
            if($GodownID==3)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="RDL-".$KeyField2;
            }
            if($GodownID==4)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="PWS-".$KeyField2;
            }*/
             $fields=array();
              $VoucherID=getmaxId("VoucherMaster","VoucherID",$connection)+1;
         $fields['VoucherID']=$VoucherID;
           $fields['VoucherNo']=$KeyField;//isset($VoucherNo)?$VoucherNo:0;
           $fields['TotalAmount']=isset($NetAmount)?$NetAmount:0;
           $fields['Active']=1;//isset($Active)?$Active:0;
           $fields['VoucherDate']=isset($InvoiceDate)?$InvoiceDate:null;
           $fields['Narration']=isset($Narration)?$Narration:0;
           $fields['Posted']=1;//isset($Posted)?$Posted:0;
           $fields['IsPostDated']=0;//isset($IsPostDated)?$IsPostDated:0;
           $fields['VoucherTypeID']=8;//jobcard isset($VoucherTypeID)?$VoucherTypeID:0;
           $fields['PeriodID']=1;//isset($PeriodID)?$PeriodID:0;
           $fields['ReferenceInvoiceID']=isset($InvoiceID)?$InvoiceID:0;
           $fields['SupplierID']=96;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($LedgerID)?$LedgerID:0;
           $fields['AmountDebit']=0;
           $fields['AmountCredit']=0;
           $fields['IsAuto']=1;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['ReferenceVoucherID']=isset($ReferenceVoucherID)?$ReferenceVoucherID:0;
           $fields['GroupID']=0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=$TotalCurrencyAmount;//isset($Cash)?$Cash:0;
           $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['UserID']=isset($UserID)?$UserID:0;
           $fields['VoucherDateTime']=isset($InvoiceDate)?$InvoiceDate:date("Y-m-d m:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'Job Card';
         //  print_r($fields);
          InsertVoucherMaster($fields,$InvoiceType,$InvoiceID,$connection); 
            $TotalAmt=((isset($main->TotalAmt) && $main->TotalAmt!="") ?$main->TotalAmt:0);
    $TotalDisountAmount=((isset($main->TotalDisountAmount) && $main->TotalDisountAmount!="") ?$main->TotalDisountAmount:0);
    $TotalTaxAmount=((isset($main->TotalTaxAmount) && $main->TotalTaxAmount!="") ?$main->TotalTaxAmount:0);
    $NetAmount=((isset($main->NetAmount) && $main->NetAmount!="") ?$main->NetAmount:0);
    $InculsiveAmount=((isset($main->InculsiveAmount) && $main->InculsiveAmount!="") ?$main->InculsiveAmount:0);
    $CashRefund=((isset($main->CashRefund) && $main->CashRefund!="") ?$main->CashRefund:0);
    $CashPaid=((isset($main->CashPaid) && $main->CashPaid!="") ?$main->CashPaid:0);
    $CashAccountID=((isset($main->CashAccountID) && $main->CashAccountID!="") ?$main->CashAccountID:0);
    $CCAcountID=((isset($main->CCAcountID) && $main->CCAcountID!="") ?$main->CCAcountID:0);
    $CustomerID=((isset($main->CustomerID) && $main->CustomerID!="") ?$main->CustomerID:0);
    $SalesAccountID=((isset($main->SalesAccountID) && $main->SalesAccountID!="") ?$main->SalesAccountID:0);
    $VATAccountID=((isset($main->VATAccountID) && $main->VATAccountID!="") ?$main->VATAccountID:0);
    $VoucherTypeID=((isset($main->VoucherTypeID) && $main->VoucherTypeID!="") ?$main->VoucherTypeID:0);
/*
CASH DR 
CREDIT CARD DR  
VAT CR 
SALES CR 
*/
$CashAccountID=$_SESSION['SETTING']['CASHINHAND'];
$CashCustomer=$_SESSION['SETTING']['CASHCUSTOMERS'];
if($CustomerID=="")$CustomerID=$CashCustomer;
        $fdetails=array();  
        for($a=0;$a<4;$a++)
        {
           $fdetails['VoucherID']=$VoucherID;
           if($a==2 && $CustomerID<>$CashCustomer)
           {
            break;
           }
           if($a==0)
           {
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
            $CreditLedgerID=$VATAccountID;
            $LedgerID=$CustomerID;
           }
           if($a==1)
           {
            $Debit=($NetAmount-$TotalTaxAmount);
            $Credit=($NetAmount-$TotalTaxAmount);
            $CreditLedgerID=$SalesAccountID;
            $LedgerID=$CustomerID;
           }
            if($a==2)
           {
            $Debit=($TotalCurrencyAmount-$CashRefund);
            $Credit=($TotalCurrencyAmount-$CashRefund);
            $CreditLedgerID=$CustomerID;
            $LedgerID=$CashAccountID;
           }
           if($a==3)
           {
            $Debit=$CreditCard;
            $Credit=$CreditCard;
            $CreditLedgerID=$CustomerID;
            $LedgerID=$CCAcountID;
           }
           $fdetails['LedgerID']=$LedgerID;
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="POS ";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;
           $fdetails['TransactionType']="POS INVOICE"; 
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);              
        }//end for */

            //end Insert Voucher 
if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Invoice Generated Sucessfully','total_records'=>$InvoiceID);
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Generated');

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

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



     odbc_autocommit($connection, FALSE);
 
    $main=json_decode($_POST['data']);
//    print_r($main);
//    return;
    $details=$_POST['details'];
  /*  $checklistdetail=$_POST['checklistdetail'];
    $warningdetail=$_POST['warningdetail'];
    $inspectiondetail=$_POST['inspectiondetail'];
*/
    $mrdetails=json_decode($details);
    //$sql="update InvoiceMaster set ";
    /*foreach($main as $key=>$value )
    {

      //echo $key."---".$value;
      if(getDataType2($connection,"invoicemaster",$key)==1)
          {

            $sql.=$key."='".$value."',";
          }
          else
          {
            if($value=="")$value="0";
          $sql .="$key=".$value.",";  
          }
    }*/

      $ShipperID =isset($main->ShipperID)?$main->ShipperID:0;
            $GodownID =isset($main->GodownID)?$main->GodownID:0;
            $SupplierID =isset($main->SupplierID)?$main->SupplierID:0;
            $SupplierName =isset($main->SupplierName)?$main->SupplierName:'';
            $Location =isset($main->Location)?$main->Location:0;
          //  $CashRefund =isset($main->CashRefund)?$main->CashRefund:0;
            $CreditCard =(isset($main->CreditCard) && $main->CreditCard>0)?str_replace(",",".",$main->CreditCard):0;
            $TotalCurrencyAmount =(isset($main->CashReceived) && $main->CashReceived>0)?str_replace(",",".",$main->CashReceived):$main->CashPaid;
          $CashRefund=0;
            $Narration =isset($main->Narration)?$main->Narration:'';
            $InvoiceType =isset($main->InvoiceType)?$main->InvoiceType:0;
            $QuoteReference =isset($main->QuoteReference)?$main->QuoteReference:null;
            $Notes =isset($main->Notes)?$main->Notes:'';
            $DueDate =isset($main->DeliveryDate)?$main->DeliveryDate:'';
            $InvoiceDate =isset($main->BillDate)?$main->BillDate:'';
            $InvoiceID =isset($main->InvoiceID)?$main->InvoiceID:0;
            $PurchaseLedgerID =isset($main->DebitToHeadID)?$main->DebitToHeadID:0;
            $VATLedgerID =isset($main->VATLedgerID)?$main->VATLedgerID:0;
            $TotalAmount =str_replace('_','.',isset($main->TotalAmt)?$main->TotalAmt:0);
            $DiscountAmount =str_replace('_','.',isset($main->TotalDisountAmount)?$main->TotalDisountAmount:0);
            $TotalTaxAmount =str_replace('_','.',isset($main->TotalTaxAmount)?$main->TotalTaxAmount:0);
            $InculsiveAmount =str_replace('_','.',isset($main->InculsiveAmount)?$main->InculsiveAmount:0);
            $NetAmount =str_replace('_','.',isset($main->NetAmount)?$main->NetAmount:0);
            $MobileNumber =isset($main->Mobile)?$main->Mobile:'';
            $Email =isset($main->Email)?$main->Email:'';
            $CustomerName =isset($main->CustomerName)?$main->CustomerName:'';
            $ChassisNumber =isset($main->ChassisNumber)?$main->ChassisNumber:'';
            $PlateNumber =isset($main->PlateNumber)?$main->PlateNumber:'';
            $TRNNo =isset($main->TRNNo)?$main->TRNNo:'-';
            $PreparedBy =isset($main->PreparedBy)?$main->PreparedBy:'';
            $CustomerType =isset($main->CustomerType)?$main->CustomerType:'0';
            $VehicleBrand =isset($main->VehicleBrand)?$main->VehicleBrand:'0';
            $ChallanNo =isset($main->ChallanNo)?$main->ChallanNo:'0';
            $VehicleModel =isset($main->VehicleModel)?$main->VehicleModel:'0'; 
            $VehicleType =isset($main->VehicleType)?$main->VehicleType:'0'; 
            $VehicleColor =isset($main->VehicleColor)?$main->VehicleColor:'0';  
            $VehicleYear =isset($main->VehicleYear)?$main->VehicleYear:'0';  
            $FuelLevel =isset($main->FuelLevel)?$main->FuelLevel:'0';  
            $MulkiyaNo =isset($main->MulkiyaNo)?$main->MulkiyaNo:'0';  
            $ParkingNo =isset($main->ParkingNo)?$main->ParkingNo:'-';  
            $KeyNo =isset($main->KeyNo)?$main->KeyNo:'-';  
            $SalesManID =isset($main->SalesManID)?$main->SalesManID:'0';  
      $SalesManID2 =isset($main->SalesManID2)?$main->SalesManID2:'0'; 
      $BiltyNo =isset($main->BiltyNo)?$main->BiltyNo:'0'; 
      //biltyno 
           /* $SalesManID=0;
            $SalesManID2=0;*/

            $PassCode='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)$GodownID=getnamesingle("invoicemaster","GodownID","InvoiceID",$ReferenceInvoiceID,$connection);
            $BiltyNo='0';
            $ItemID='';
            $InvoiceStatusID=4;
            if($InvoiceID=="")$InvoiceID=0;
            $DeliveryDate=$DueDate;
        $sql="select * from invoicemaster where invoiceid=".$InvoiceID;
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {
              $row=odbc_fetch_array($result);
              $KeyField=$row['KeyField'];
     $sql="update InvoiceMaster set SupplierID=".$SupplierID.",MobileNumber='".$MobileNumber."',CustomerName='".$CustomerName."',Email='".$Email."',InvoiceDate='".$InvoiceDate."',DeliveryDate='".$DeliveryDate."',PlateNumber='".$PlateNumber."',ChassisNumber='".$ChassisNumber."',ChallanNo='".$ChallanNo."',SalesManID=".$SalesManID.",SalesManID2=".$SalesManID2.",TRNNo='".$TRNNo."',CustomerType=".$CustomerType.",VehicleBrand=".$VehicleBrand.",VehicleModel=".$VehicleModel.",VehicleType=".$VehicleType.",VehicleColor=".$VehicleColor.",VehicleYear=".$VehicleYear.",Notes='".$Notes."',FuelLevel=".$FuelLevel.",GodownID=".$GodownID.",InvoiceType=".$InvoiceType.",TotalAmount=".$TotalAmount.",DiscountAmount=".$DiscountAmount.",TotalTaxAmount=".$TotalTaxAmount.",NetAmount=".$NetAmount.",MulkiyaNo='".$MulkiyaNo."',ParkingNo='".$ParkingNo."',KeyNo='".$KeyNo."',PictureLocation='',CashRefund=".$CashRefund.",CreditCard=".$CreditCard.",TotalCurrencyAmount=".$TotalCurrencyAmount." where InvoiceID=".$InvoiceID;
         /*$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."  where InvoiceID=".$InvoiceID;*/       
            //delete preivous record 
            $sqldelete="delete from invoicedetail where InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sqldelete);
            }
            else
            {
            $InvoiceID=getmaxId("InvoiceMaster","InvoiceID",$connection)+1;
            $PictureLocation='';
            if($InvoiceType==18)
            {
            $where="InvoiceType=18 and GodownID=".$GodownID; 
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection);
            $KeyField=($KeyField==null)?1:$KeyField;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            if($GodownID==1)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="POS-RET-MVR-".$KeyField2;
            }
            if($GodownID==2)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="POS-RET-CCL-".$KeyField2;
            }
            if($GodownID==3)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="POS-RET-RDL-".$KeyField2;
            }
            if($GodownID==4)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="POS-RET-PWS-".$KeyField2;
            }
            $ACNarration='AUTO VOUCHER for DOC: '.$KeyField.' from Jobcard';
            }
            // 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
           ,VATLedgerID
           ,CashRefund
       ,CreditCard
       ,TotalCurrencyAmount
           ,PurchaseLedgerID
           ,MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",'".$ChallanNo
           ."','".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount
           .",".$DiscountAmount
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$ShipperID
           .",'".$BiltyNo
           ."','".$DueDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$CashRefund."
       ,".$CreditCard."
       ,".$TotalCurrencyAmount."
           ,".$PurchaseLedgerID."
           ,'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$SalesManID.",".$SalesManID2.",'".$TRNNo."',".$CustomerType.",".$VehicleBrand.",".$VehicleModel.",".$VehicleType.",".$VehicleColor.",".$VehicleYear.",'".$Notes."',".$FuelLevel.",'".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."','".$PictureLocation."','".$_SESSION['UserName']."')";
          }//end else for insert */

          odbc_exec($connection,$sql) or die(odbc_error().$sql);
    //print_r(array_keys($_POST));
    //print_r(array_values($_POST));
    //$data=json_decode($_POST);
    //print_r($_POST);
          //code for details 
          insertInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);
          /*    InsertJList($InvoiceID,$checklistdetail,'CheckList',$connection);
              InsertJList($InvoiceID,$warningdetail,'WarningList',$connection);
              InsertJList($InvoiceID,$inspectiondetail,'InspectionList',$connection);     */
              
              //remove if previous voucher exists 

              $sqlupdate="update VoucherMaster set active=0 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
              $sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
          // Insert Voucher 
              $where=" VoucherTypeID=19 ";
              $KeyField=generateCode("VoucherMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="SALE-RET-".$KeyField2;
            
             $fields=array();
              $VoucherID=getmaxId("VoucherMaster","VoucherID",$connection)+1;
         $fields['VoucherID']=$VoucherID;
           $fields['VoucherNo']=$KeyField;//isset($VoucherNo)?$VoucherNo:0;
           $fields['TotalAmount']=isset($NetAmount)?$NetAmount:0;
           $fields['Active']=1;//isset($Active)?$Active:0;
           $fields['VoucherDate']=isset($InvoiceDate)?$InvoiceDate:null;
           $fields['Narration']=isset($Narration)?$Narration:0;
           $fields['Posted']=1;//isset($Posted)?$Posted:0;
           $fields['IsPostDated']=0;//isset($IsPostDated)?$IsPostDated:0;
           $fields['VoucherTypeID']=19;//isset($VoucherTypeID)?$VoucherTypeID:0;
           $fields['PeriodID']=1;//isset($PeriodID)?$PeriodID:0;
           $fields['ReferenceInvoiceID']=isset($InvoiceID)?$InvoiceID:0;
           $fields['SupplierID']=96;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($LedgerID)?$LedgerID:0;
           $fields['AmountDebit']=0;
           $fields['AmountCredit']=0;
           $fields['IsAuto']=1;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['ReferenceVoucherID']=isset($ReferenceVoucherID)?$ReferenceVoucherID:0;
           $fields['GroupID']=0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=$TotalCurrencyAmount;//isset($Cash)?$Cash:0;
           $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['UserID']=isset($UserID)?$UserID:0;
           $fields['VoucherDateTime']=isset($InvoiceDate)?$InvoiceDate:date("Y-m-d m:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'POS-RETURN';
         //  print_r($fields);
          InsertVoucherMaster($fields,$InvoiceType,$InvoiceID,$connection); 
            $TotalAmt=$main->TotalAmt;
    $TotalDisountAmount=$main->TotalDisountAmount;
    $TotalTaxAmount=$main->TotalTaxAmount;
    $NetAmount=$main->NetAmount;
    $InculsiveAmount=$main->InculsiveAmount;
    $CashRefund=$main->CashRefund;
    $CashPaid=$main->CashPaid;
    $CashAccountID=$main->CashAccountID;
    $CCAcountID=$main->CCAcountID;
    $CustomerID=$main->CustomerID;
    $SalesAccountID=$main->SalesAccountID;
    $VATAccountID=$main->VATAccountID;
    $VoucherTypeID=$main->VoucherTypeID;
/*
CASH DR 
CREDIT CARD DR  
VAT CR 
SALES CR 
*/
        $fdetails=array();  
        for($a=0;$a<2;$a++)
        {
           $fdetails['VoucherID']=$VoucherID;

           if($a==0)
           {
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
/*            $CreditLedgerID=$VATAccountID;
            $LedgerID=$CustomerID;*/
            $CreditLedgerID=$CustomerID;
            $LedgerID=$VATAccountID;
           }
           if($a==1)
           {
            $Debit=($NetAmount-$TotalTaxAmount);
            $Credit=($NetAmount-$TotalTaxAmount);
/*            $CreditLedgerID=$SalesAccountID;
            $LedgerID=$CustomerID;*/
            $CreditLedgerID=$CustomerID;
              $LedgerID=$SalesAccountID;
           }
/*            if($a==2)
           {
            $Debit=$TotalCurrencyAmount;
            $Credit=$TotalCurrencyAmount;
            $CreditLedgerID=$CustomerID;
            $LedgerID=$CashAccountID;
           }
           if($a==3)
           {
            $Debit=$CreditCard;
            $Credit=$CreditCard;
            $CreditLedgerID=$CustomerID;
            $LedgerID=$CCAcountID;
           }*/
           $fdetails['LedgerID']=$LedgerID;
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="POS RETURN ";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;
           $fdetails['TransactionType']="POS INVOICE"; 
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);              
        }//end for */
if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Invoice Generated Sucessfully');
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Generated');

  }
            //end Insert Voucher 
  //        $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
    echo json_encode($res);

  
  

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


     odbc_autocommit($connection, FALSE);
 
    $main=json_decode($_POST['data']);
//    print_r($main);
//    return;
    $details=$_POST['details'];
  /*  $checklistdetail=$_POST['checklistdetail'];
    $warningdetail=$_POST['warningdetail'];
    $inspectiondetail=$_POST['inspectiondetail'];
*/
    $mrdetails=json_decode($details);
    //$sql="update InvoiceMaster set ";
    /*foreach($main as $key=>$value )
    {

      //echo $key."---".$value;
      if(getDataType2($connection,"invoicemaster",$key)==1)
          {

            $sql.=$key."='".$value."',";
          }
          else
          {
            if($value=="")$value="0";
          $sql .="$key=".$value.",";  
          }
    }*/

      $ShipperID =isset($main->ShipperID)?$main->ShipperID:0;
            $GodownID =isset($main->GodownID)?$main->GodownID:0;
            $SupplierID =isset($main->SupplierID)?$main->SupplierID:0;
            $SupplierName =isset($main->SupplierName)?$main->SupplierName:'';
            $Location =isset($main->Location)?$main->Location:0;
          //  $CashRefund =isset($main->CashRefund)?$main->CashRefund:0;
            $CreditCard =(isset($main->CreditCard) && $main->CreditCard>0)?str_replace(",",".",$main->CreditCard):0;
            $TotalCurrencyAmount =(isset($main->CashReceived) && $main->CashReceived>0)?str_replace(",",".",$main->CashReceived):$main->CashPaid;
          $CashRefund=0;
            $Narration =isset($main->Narration)?$main->Narration:'';
            $InvoiceType =isset($main->InvoiceType)?$main->InvoiceType:0;
            $QuoteReference =isset($main->QuoteReference)?$main->QuoteReference:null;
            $Notes =isset($main->Notes)?$main->Notes:'';
            $DueDate =isset($main->DeliveryDate)?$main->DeliveryDate:'';
            $InvoiceDate =isset($main->BillDate)?$main->BillDate:'';
            $InvoiceID =isset($main->InvoiceID)?$main->InvoiceID:0;
            $PurchaseLedgerID =isset($main->DebitToHeadID)?$main->DebitToHeadID:0;
            $VATLedgerID =isset($main->VATLedgerID)?$main->VATLedgerID:0;
            $TotalAmount =str_replace('_','.',isset($main->TotalAmt)?$main->TotalAmt:0);
            $DiscountAmount =str_replace('_','.',isset($main->TotalDisountAmount)?$main->TotalDisountAmount:0);
            $TotalTaxAmount =str_replace('_','.',isset($main->TotalTaxAmount)?$main->TotalTaxAmount:0);
            $InculsiveAmount =str_replace('_','.',isset($main->InculsiveAmount)?$main->InculsiveAmount:0);
            $NetAmount =str_replace('_','.',isset($main->NetAmount)?$main->NetAmount:0);
            $MobileNumber =isset($main->Mobile)?$main->Mobile:'';
            $Email =isset($main->Email)?$main->Email:'';
            $CustomerName =isset($main->CustomerName)?$main->CustomerName:'';
            $ChassisNumber =isset($main->ChassisNumber)?$main->ChassisNumber:'';
            $PlateNumber =isset($main->PlateNumber)?$main->PlateNumber:'';
            $TRNNo =isset($main->TRNNo)?$main->TRNNo:'-';
            $PreparedBy =isset($main->PreparedBy)?$main->PreparedBy:'';
            $CustomerType =isset($main->CustomerType)?$main->CustomerType:'0';
            $VehicleBrand =isset($main->VehicleBrand)?$main->VehicleBrand:'0';
            $ChallanNo =isset($main->ChallanNo)?$main->ChallanNo:'0';
            $VehicleModel =isset($main->VehicleModel)?$main->VehicleModel:'0'; 
            $VehicleType =isset($main->VehicleType)?$main->VehicleType:'0'; 
            $VehicleColor =isset($main->VehicleColor)?$main->VehicleColor:'0';  
            $VehicleYear =isset($main->VehicleYear)?$main->VehicleYear:'0';  
            $FuelLevel =isset($main->FuelLevel)?$main->FuelLevel:'0';  
            $MulkiyaNo =isset($main->MulkiyaNo)?$main->MulkiyaNo:'0';  
            $ParkingNo =isset($main->ParkingNo)?$main->ParkingNo:'-';  
            $KeyNo =isset($main->KeyNo)?$main->KeyNo:'-';  
            $SalesManID =isset($main->SalesManID)?$main->SalesManID:'0';  
      $SalesManID2 =isset($main->SalesManID2)?$main->SalesManID2:'0'; 
      $BiltyNo =isset($main->BiltyNo)?$main->BiltyNo:'0'; 
      //biltyno 
           /* $SalesManID=0;
            $SalesManID2=0;*/

            $PassCode='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)$GodownID=getnamesingle("invoicemaster","GodownID","InvoiceID",$ReferenceInvoiceID,$connection);
            $BiltyNo='0';
            $ItemID='';
            $InvoiceStatusID=1;
            if($InvoiceID=="")$InvoiceID=0;
            $DeliveryDate=$DueDate;
        $sql="select * from invoicemaster where invoiceid=".$InvoiceID;
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {
              $row=odbc_fetch_array($result);
              $KeyField=$row['KeyField'];
     $sql="update InvoiceMaster set SupplierID=".$SupplierID.",MobileNumber='".$MobileNumber."',CustomerName='".$CustomerName."',Email='".$Email."',InvoiceDate='".$InvoiceDate."',DeliveryDate='".$DeliveryDate."',PlateNumber='".$PlateNumber."',ChassisNumber='".$ChassisNumber."',ChallanNo='".$ChallanNo."',SalesManID=".$SalesManID.",SalesManID2=".$SalesManID2.",TRNNo='".$TRNNo."',CustomerType=".$CustomerType.",VehicleBrand=".$VehicleBrand.",VehicleModel=".$VehicleModel.",VehicleType=".$VehicleType.",VehicleColor=".$VehicleColor.",VehicleYear=".$VehicleYear.",Notes='".$Notes."',FuelLevel=".$FuelLevel.",GodownID=".$GodownID.",InvoiceType=".$InvoiceType.",TotalAmount=".$TotalAmount.",DiscountAmount=".$DiscountAmount.",TotalTaxAmount=".$TotalTaxAmount.",NetAmount=".$NetAmount.",MulkiyaNo='".$MulkiyaNo."',ParkingNo='".$ParkingNo."',KeyNo='".$KeyNo."',PictureLocation='',CashRefund=".$CashRefund.",CreditCard=".$CreditCard.",TotalCurrencyAmount=".$TotalCurrencyAmount." where InvoiceID=".$InvoiceID;
         /*$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."  where InvoiceID=".$InvoiceID;*/       
            //delete preivous record 
            $sqldelete="delete from invoicedetail where InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sqldelete);
            }
            else
            {
            $InvoiceID=getmaxId("InvoiceMaster","InvoiceID",$connection)+1;
            $PictureLocation='';
            if($InvoiceType==8)
            {
            $where="InvoiceType=8 and GodownID=".$GodownID; 
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            if($GodownID==1)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="POS-MVR-".$KeyField2;
            }
            if($GodownID==2)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="POS-CCL-".$KeyField2;
            }
            if($GodownID==3)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="POS-RDL-".$KeyField2;
            }
            if($GodownID==4)
            { 
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="POS-PWS-".$KeyField2;
            }
            $ACNarration='AUTO VOUCHER for DOC: '.$KeyField.' from Jobcard';
            }
            // 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
           ,VATLedgerID
           ,CashRefund
       ,CreditCard
       ,TotalCurrencyAmount
           ,PurchaseLedgerID
           ,MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",'".$ChallanNo
           ."','".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount
           .",".$DiscountAmount
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$ShipperID
           .",'".$BiltyNo
           ."','".$DueDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$CashRefund."
       ,".$CreditCard."
       ,".$TotalCurrencyAmount."
           ,".$PurchaseLedgerID."
           ,'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$SalesManID.",".$SalesManID2.",'".$TRNNo."',".$CustomerType.",".$VehicleBrand.",".$VehicleModel.",".$VehicleType.",".$VehicleColor.",".$VehicleYear.",'".$Notes."',".$FuelLevel.",'".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."','".$PictureLocation."','".$_SESSION['UserName']."')";
          }//end else for insert */

          odbc_exec($connection,$sql) or die(odbc_error().$sql);
    //print_r(array_keys($_POST));
    //print_r(array_values($_POST));
    //$data=json_decode($_POST);
    //print_r($_POST);
          //code for details 
          insertInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);
          /*    InsertJList($InvoiceID,$checklistdetail,'CheckList',$connection);
              InsertJList($InvoiceID,$warningdetail,'WarningList',$connection);
              InsertJList($InvoiceID,$inspectiondetail,'InspectionList',$connection);     */
              
              //remove if previous voucher exists 

              $sqlupdate="update VoucherMaster set active=0 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
              $sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
          // Insert Voucher 
              $where=" VoucherTypeID=9 ";
              $KeyField=generateCode("VoucherMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="SALE-".$KeyField2;
            
             $fields=array();
              $VoucherID=getmaxId("VoucherMaster","VoucherID",$connection)+1;
         $fields['VoucherID']=$VoucherID;
           $fields['VoucherNo']=$KeyField;//isset($VoucherNo)?$VoucherNo:0;
           $fields['TotalAmount']=isset($NetAmount)?$NetAmount:0;
           $fields['Active']=1;//isset($Active)?$Active:0;
           $fields['VoucherDate']=isset($InvoiceDate)?$InvoiceDate:null;
           $fields['Narration']=isset($Narration)?$Narration:0;
           $fields['Posted']=1;//isset($Posted)?$Posted:0;
           $fields['IsPostDated']=0;//isset($IsPostDated)?$IsPostDated:0;
           $fields['VoucherTypeID']=9;//isset($VoucherTypeID)?$VoucherTypeID:0;
           $fields['PeriodID']=1;//isset($PeriodID)?$PeriodID:0;
           $fields['ReferenceInvoiceID']=isset($InvoiceID)?$InvoiceID:0;
           $fields['SupplierID']=96;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($LedgerID)?$LedgerID:0;
           $fields['AmountDebit']=0;
           $fields['AmountCredit']=0;
           $fields['IsAuto']=1;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['ReferenceVoucherID']=isset($ReferenceVoucherID)?$ReferenceVoucherID:0;
           $fields['GroupID']=0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=$TotalCurrencyAmount;//isset($Cash)?$Cash:0;
           $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['UserID']=isset($UserID)?$UserID:0;
           $fields['VoucherDateTime']=isset($InvoiceDate)?$InvoiceDate:date("Y-m-d m:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'POS';
         //  print_r($fields);
          InsertVoucherMaster($fields,$InvoiceType,$InvoiceID,$connection); 
            $TotalAmt=$main->TotalAmt;
    $TotalDisountAmount=$main->TotalDisountAmount;
    $TotalTaxAmount=$main->TotalTaxAmount;
    $NetAmount=$main->NetAmount;
    $InculsiveAmount=$main->InculsiveAmount;
    $CashRefund=$main->CashRefund;
    $CashPaid=$main->CashPaid;
    $CashAccountID=$main->CashAccountID;
    $CCAcountID=$main->CCAcountID;
    $CustomerID=$main->CustomerID;
    $SalesAccountID=$main->SalesAccountID;
    $VATAccountID=$main->VATAccountID;
    $VoucherTypeID=$main->VoucherTypeID;
/*
CASH DR 
CREDIT CARD DR  
VAT CR 
SALES CR 
*/
        $fdetails=array();  
        for($a=0;$a<2;$a++)
        {
           $fdetails['VoucherID']=$VoucherID;

           if($a==0)
           {
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
            $CreditLedgerID=$VATAccountID;
            $LedgerID=$CustomerID;
           }
           if($a==1)
           {
            $Debit=($NetAmount-$TotalTaxAmount);
            $Credit=($NetAmount-$TotalTaxAmount);
            $CreditLedgerID=$SalesAccountID;
            $LedgerID=$CustomerID;
           }
            if($a==2)
           {
            $Debit=$TotalCurrencyAmount;
            $Credit=$TotalCurrencyAmount;
            $CreditLedgerID=$CustomerID;
            $LedgerID=$CashAccountID;
           }
           if($a==3)
           {
            $Debit=$CreditCard;
            $Credit=$CreditCard;
            $CreditLedgerID=$CustomerID;
            $LedgerID=$CCAcountID;
           }
           $fdetails['LedgerID']=$LedgerID;
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="POS ";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;
           $fdetails['TransactionType']="POS INVOICE"; 
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);              
        }//end for */
if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Invoice Generated Sucessfully');
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Generated');

  }
            //end Insert Voucher 
  //        $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
    echo json_encode($res);

  
  
}
if($_GET['action']=="InsertPOSInvoice")
	{
     odbc_autocommit($connection, FALSE);
 
		$main=json_decode($_POST['data']);
//		print_r($main);
//		return;
    $details=$_POST['details'];
	/*	$checklistdetail=$_POST['checklistdetail'];
		$warningdetail=$_POST['warningdetail'];
		$inspectiondetail=$_POST['inspectiondetail'];
*/
		$mrdetails=json_decode($details);
		//$sql="update InvoiceMaster set ";
		/*foreach($main as $key=>$value )
		{

			//echo $key."---".$value;
			if(getDataType2($connection,"invoicemaster",$key)==1)
					{

						$sql.=$key."='".$value."',";
					}
					else
					{
						if($value=="")$value="0";
					$sql .="$key=".$value.",";	
					}
		}*/

			$ShipperID =isset($main->ShipperID)?$main->ShipperID:0;
            $GodownID =isset($main->GodownID)?$main->GodownID:0;
            $SupplierID =isset($main->SupplierID)?$main->SupplierID:0;
            $SupplierName =isset($main->SupplierName)?$main->SupplierName:'';
            $Location =isset($main->Location)?$main->Location:0;
          //  $CashRefund =isset($main->CashRefund)?$main->CashRefund:0;
            $CreditCard =(isset($main->CreditCard) && $main->CreditCard>0)?str_replace(",",".",$main->CreditCard):0;
            $TotalCurrencyAmount =(isset($main->CashReceived) && $main->CashReceived>0)?str_replace(",",".",$main->CashReceived):$main->CashPaid;
      		$CashRefund=0;
            $Narration =isset($main->Narration)?$main->Narration:'';
            $InvoiceType =isset($main->InvoiceType)?$main->InvoiceType:0;
            $QuoteReference =isset($main->QuoteReference)?$main->QuoteReference:null;
            $Notes =isset($main->Notes)?$main->Notes:'';
            $DueDate =isset($main->DeliveryDate)?$main->DeliveryDate:'';
            $InvoiceDate =isset($main->BillDate)?$main->BillDate:'';
            $InvoiceID =isset($main->InvoiceID)?$main->InvoiceID:0;
            $PurchaseLedgerID =isset($main->DebitToHeadID)?$main->DebitToHeadID:0;
            $VATLedgerID =isset($main->VATLedgerID)?$main->VATLedgerID:0;
            $TotalAmount =str_replace('_','.',isset($main->TotalAmt)?$main->TotalAmt:0);
            $DiscountAmount =str_replace('_','.',isset($main->TotalDisountAmount)?$main->TotalDisountAmount:0);
            $TotalTaxAmount =str_replace('_','.',isset($main->TotalTaxAmount)?$main->TotalTaxAmount:0);
            $InculsiveAmount =str_replace('_','.',isset($main->InculsiveAmount)?$main->InculsiveAmount:0);
            $NetAmount =str_replace('_','.',isset($main->NetAmount)?$main->NetAmount:0);
            $MobileNumber =isset($main->Mobile)?$main->Mobile:'';
            $Email =isset($main->Email)?$main->Email:'';
            $CustomerName =isset($main->CustomerName)?$main->CustomerName:'';
            $ChassisNumber =isset($main->ChassisNumber)?$main->ChassisNumber:'';
            $PlateNumber =isset($main->PlateNumber)?$main->PlateNumber:'';
            $TRNNo =isset($main->TRNNo)?$main->TRNNo:'-';
            $PreparedBy =isset($main->PreparedBy)?$main->PreparedBy:'';
            $CustomerType =isset($main->CustomerType)?$main->CustomerType:'0';
            $VehicleBrand =isset($main->VehicleBrand)?$main->VehicleBrand:'0';
            $ChallanNo =isset($main->ChallanNo)?$main->ChallanNo:'0';
            $VehicleModel =isset($main->VehicleModel)?$main->VehicleModel:'0'; 
            $VehicleType =isset($main->VehicleType)?$main->VehicleType:'0'; 
            $VehicleColor =isset($main->VehicleColor)?$main->VehicleColor:'0';  
            $VehicleYear =isset($main->VehicleYear)?$main->VehicleYear:'0';  
            $FuelLevel =isset($main->FuelLevel)?$main->FuelLevel:'0';  
            $MulkiyaNo =isset($main->MulkiyaNo)?$main->MulkiyaNo:'0';  
            $ParkingNo =isset($main->ParkingNo)?$main->ParkingNo:'-';  
            $KeyNo =isset($main->KeyNo)?$main->KeyNo:'-';  
            $SalesManID =isset($main->SalesManID)?$main->SalesManID:'0';  
			$SalesManID2 =isset($main->SalesManID2)?$main->SalesManID2:'0'; 
			$BiltyNo =isset($main->BiltyNo)?$main->BiltyNo:'0'; 
			//biltyno 
           /* $SalesManID=0;
            $SalesManID2=0;*/

            $PassCode='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)$GodownID=getnamesingle("invoicemaster","GodownID","InvoiceID",$ReferenceInvoiceID,$connection);
            $BiltyNo='0';
            $ItemID='';
            $InvoiceStatusID=1;
            if($InvoiceID=="")$InvoiceID=0;
            $DeliveryDate=$DueDate;
		    $sql="select * from invoicemaster where invoiceid=".$InvoiceID;
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {
            	$row=odbc_fetch_array($result);
            	$KeyField=$row['KeyField'];
		 $sql="update InvoiceMaster set SupplierID=".$SupplierID.",MobileNumber='".$MobileNumber."',CustomerName='".$CustomerName."',Email='".$Email."',InvoiceDate='".$InvoiceDate."',DeliveryDate='".$DeliveryDate."',PlateNumber='".$PlateNumber."',ChassisNumber='".$ChassisNumber."',ChallanNo='".$ChallanNo."',SalesManID=".$SalesManID.",SalesManID2=".$SalesManID2.",TRNNo='".$TRNNo."',CustomerType=".$CustomerType.",VehicleBrand=".$VehicleBrand.",VehicleModel=".$VehicleModel.",VehicleType=".$VehicleType.",VehicleColor=".$VehicleColor.",VehicleYear=".$VehicleYear.",Notes='".$Notes."',FuelLevel=".$FuelLevel.",GodownID=".$GodownID.",InvoiceType=".$InvoiceType.",TotalAmount=".$TotalAmount.",DiscountAmount=".$DiscountAmount.",TotalTaxAmount=".$TotalTaxAmount.",NetAmount=".$NetAmount.",MulkiyaNo='".$MulkiyaNo."',ParkingNo='".$ParkingNo."',KeyNo='".$KeyNo."',PictureLocation='',CashRefund=".$CashRefund.",CreditCard=".$CreditCard.",TotalCurrencyAmount=".$TotalCurrencyAmount." where InvoiceID=".$InvoiceID;
         /*$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."  where InvoiceID=".$InvoiceID;*/      	
            //delete preivous record 
            $sqldelete="delete from invoicedetail where InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sqldelete);
            }
            else
            {
            $InvoiceID=getmaxId("InvoiceMaster","InvoiceID",$connection)+1;
            $PictureLocation='';
           	if($InvoiceType==8)
           	{
           	$where="InvoiceType=8 and GodownID=".$GodownID;	
           	$KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
           	//getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
           	if($GodownID==1)
           	{	
           	$KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
           	$KeyField="POS-MVR-".$KeyField2;
           	}
           	if($GodownID==2)
           	{	
           	$KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
           	$KeyField="POS-CCL-".$KeyField2;
           	}
           	if($GodownID==3)
           	{	
           	$KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
           	$KeyField="POS-RDL-".$KeyField2;
           	}
           	if($GodownID==4)
           	{	
           	$KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
           	$KeyField="POS-PWS-".$KeyField2;
           	}
           	$ACNarration='AUTO VOUCHER for DOC: '.$KeyField.' from Jobcard';
           	}
            // 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
           ,VATLedgerID
           ,CashRefund
		   ,CreditCard
		   ,TotalCurrencyAmount
           ,PurchaseLedgerID
           ,MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation
       ) values (".$InvoiceID.",'".
			$InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",'".$ChallanNo
           ."','".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
			.",".$TotalAmount
           .",".$DiscountAmount
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$ShipperID
           .",'".$BiltyNo
           ."','".$DueDate."'
           ,".$InvoiceStatusID
       	   .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$CashRefund."
		   ,".$CreditCard."
		   ,".$TotalCurrencyAmount."
           ,".$PurchaseLedgerID."
           ,'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$SalesManID.",".$SalesManID2.",'".$TRNNo."',".$CustomerType.",".$VehicleBrand.",".$VehicleModel.",".$VehicleType.",".$VehicleColor.",".$VehicleYear.",'".$Notes."',".$FuelLevel.",'".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."','".$PictureLocation."')";
       		}//end else for insert */

       		odbc_exec($connection,$sql) or die(odbc_error().$sql);
		//print_r(array_keys($_POST));
		//print_r(array_values($_POST));
		//$data=json_decode($_POST);
		//print_r($_POST);
       		//code for details 
       		insertInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);
       		/*		InsertJList($InvoiceID,$checklistdetail,'CheckList',$connection);
       				InsertJList($InvoiceID,$warningdetail,'WarningList',$connection);
       				InsertJList($InvoiceID,$inspectiondetail,'InspectionList',$connection);     */
              
              //remove if previous voucher exists 

              $sqlupdate="update VoucherMaster set active=0 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
              $sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
       		// Insert Voucher 
              $where=" VoucherTypeID=9 ";
              $KeyField=generateCode("VoucherMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            
            $KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
            $KeyField="SALE-".$KeyField2;
            
             $fields=array();
              $VoucherID=getmaxId("VoucherMaster","VoucherID",$connection)+1;
         $fields['VoucherID']=$VoucherID;
           $fields['VoucherNo']=$KeyField;//isset($VoucherNo)?$VoucherNo:0;
           $fields['TotalAmount']=isset($NetAmount)?$NetAmount:0;
           $fields['Active']=1;//isset($Active)?$Active:0;
           $fields['VoucherDate']=isset($InvoiceDate)?$InvoiceDate:null;
           $fields['Narration']=isset($Narration)?$Narration:0;
           $fields['Posted']=1;//isset($Posted)?$Posted:0;
           $fields['IsPostDated']=0;//isset($IsPostDated)?$IsPostDated:0;
           $fields['VoucherTypeID']=9;//isset($VoucherTypeID)?$VoucherTypeID:0;
           $fields['PeriodID']=1;//isset($PeriodID)?$PeriodID:0;
           $fields['ReferenceInvoiceID']=isset($InvoiceID)?$InvoiceID:0;
           $fields['SupplierID']=96;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($LedgerID)?$LedgerID:0;
           $fields['AmountDebit']=0;
           $fields['AmountCredit']=0;
           $fields['IsAuto']=1;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['ReferenceVoucherID']=isset($ReferenceVoucherID)?$ReferenceVoucherID:0;
           $fields['GroupID']=0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=$TotalCurrencyAmount;//isset($Cash)?$Cash:0;
           $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['UserID']=isset($UserID)?$UserID:0;
           $fields['VoucherDateTime']=isset($InvoiceDate)?$InvoiceDate:date("Y-m-d m:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'POS';
         //  print_r($fields);
          InsertVoucherMaster($fields,$InvoiceType,$InvoiceID,$connection); 
            $TotalAmt=$main->TotalAmt;
    $TotalDisountAmount=$main->TotalDisountAmount;
    $TotalTaxAmount=$main->TotalTaxAmount;
    $NetAmount=$main->NetAmount;
    $InculsiveAmount=$main->InculsiveAmount;
    $CashRefund=$main->CashRefund;
    $CashPaid=$main->CashPaid;
    $CashAccountID=$main->CashAccountID;
    $CCAcountID=$main->CCAcountID;
    $CustomerID=$main->CustomerID;
    $SalesAccountID=$main->SalesAccountID;
    $VATAccountID=$main->VATAccountID;
    $VoucherTypeID=$main->VoucherTypeID;
/*
CASH DR 
CREDIT CARD DR  
VAT CR 
SALES CR 
*/
        $fdetails=array();  
        for($a=0;$a<4;$a++)
        {
           $fdetails['VoucherID']=$VoucherID;

           if($a==0)
           {
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
            $CreditLedgerID=$VATAccountID;
            $LedgerID=$CustomerID;
           }
           if($a==1)
           {
            $Debit=($NetAmount-$TotalTaxAmount);
            $Credit=($NetAmount-$TotalTaxAmount);
            $CreditLedgerID=$SalesAccountID;
            $LedgerID=$CustomerID;
           }
            if($a==2)
           {
            $Debit=$TotalCurrencyAmount;
            $Credit=$TotalCurrencyAmount;
            $CreditLedgerID=$CustomerID;
            $LedgerID=$CashAccountID;
           }
           if($a==3)
           {
            $Debit=$CreditCard;
            $Credit=$CreditCard;
            $CreditLedgerID=$CustomerID;
            $LedgerID=$CCAcountID;
           }
           $fdetails['LedgerID']=$LedgerID;
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="POS ";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;
           $fdetails['TransactionType']="POS INVOICE"; 
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);              
        }//end for */
if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Invoice Generated Sucessfully');
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Generated');

  }
       			//end Insert Voucher 
  //     		$res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
		echo json_encode($res);

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

    $InvoiceType=$_GET['InvoiceType'];
    $data=array();
     if(isset($_GET['CustomerName']))
    {
    $CustomerName=$_GET['CustomerName'];
    $CustomerName="CustomerName like '%".$CustomerName."%' and ";
    }
    else
    {
  $CustomerName="";
    }
    if(isset($_GET['Email']))
    {
    $Email=$_GET['Email'];
    $Email="Email like '%".$Email."%' and ";
    }
    else
    {
  $Email="";
    }
    if(isset($_GET['MobileNumber']))
    {
    $MobileNumber=$_GET['MobileNumber'];
    $MobileNumber="MobileNumber like '%".$MobileNumber."%' and ";
    }
    else
    {
  $MobileNumber="";
    }
//(select top 1 VoucherID from VoucherDetails where VoucherID=im.AutoVoucherID )
    $searchbox= $CustomerName.$MobileNumber.$Email;
 $sql="select distinct CustomerName,ROW_NUMBER() OVER (
      ORDER BY [InvoiceID]    ) row_num,MobileNumber,Email,SupplierID as  CustomerID,
      PlateNumber,ChassisNumber,'Individual' as CustomerType,'' as GlCode from invoicemaster as im  where CustomerName is not null and InvoiceType=$InvoiceType and SupplierID not in (select COAID from accounts where NatureID=14 and active=1 and [group]=0 )
     Union
   
   select COAName as CustomerName,ROW_NUMBER() OVER (
      ORDER BY [COAID]    ) row_num,Attr10 as MobileNumber,Attr11 as Email,COAID as CustomerID,'','','Cooperate' as CustomerType,GlCode from Accounts where NatureID=14 and active=1 and [group]=0";
//left outer join  VoucherDetails as vd on VoucherID=im.AutoVoucherID
      $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      foreach ($row as $key => $value) {
        # code...
        $row[$key]=utf8_encode($value);
      }
      $data[]=$row;
    }
    echo json_encode($data);
  


}
    if($_GET['action']=="getCustomerdata")
  {
		$InvoiceType=$_GET['InvoiceType'];
		$data=array();
	   if(isset($_GET['CustomerName']))
    {
    $CustomerName=$_GET['CustomerName'];
    $CustomerName="CustomerName like '%".$CustomerName."%' and ";
    }
    else
    {
  $CustomerName="";
    }
    if(isset($_GET['Email']))
    {
    $Email=$_GET['Email'];
    $Email="Email like '%".$Email."%' and ";
    }
    else
    {
  $Email="";
    }
    if(isset($_GET['MobileNumber']))
    {
    $MobileNumber=$_GET['MobileNumber'];
    $MobileNumber="MobileNumber like '%".$MobileNumber."%' and ";
    }
    else
    {
  $MobileNumber="";
    }

    $searchbox= $CustomerName.$MobileNumber.$Email;
  	$sql="   select ROW_NUMBER() OVER (
      ORDER BY [InvoiceID]    ) row_num ,CustomerName,MobileNumber,Email,(select top 1 LedgerID from VoucherDetails where VoucherID=im.AutoVoucherID ) as  CustomerID,PlateNumber,ChassisNumber from invoicemaster as im  
   where $searchbox InvoiceType=".$InvoiceType;
//left outer join  VoucherDetails as vd on VoucherID=im.AutoVoucherID
   		$result=odbc_exec($connection,$sql);
		while($row=odbc_fetch_array($result))
		{
			$data[]=$row;
		}
		echo json_encode($data);
	}
if($_GET['action']=="GetProduct_VehicleType")
{
	print_r($_GET);
}

	if($_GET['action']=="GetSalesMan")
	{
				$data=array();

		$sql="select ROW_NUMBER() OVER (
      ORDER BY [DepartmentID]    ) row_num,SalesManID
      ,SalesManName,
      dept.Name as Name
      ,Code
      ,sm.ContactNo as ContactNo
      ,CellPhoneNo
      ,sm.KeyField
      ,FathersName
      ,DepartmentID
      ,DesignationID as DesignationName from SalesManInformation as sm inner join Godowns as dept on sm.DepartmentID=dept.GodownID ";
	$result=odbc_exec($connection,$sql);
		while($row=odbc_fetch_array($result))
		{
			$data[]=$row;
		}
		echo json_encode($data);

	}
	if($_GET['action']=="GetProduct_Item")
	{
		$ProductBaseType=$_GET['ProductBaseType'];
		$start=0;
		$limit=10;
		if(isset($_GET['ItemName']))
		{
		$Item=$_GET['ItemName'];
		$ItemName="i.Name like '%".$Item."%' and ";
		}
		else
		{
	$ItemName="";
		}
		if(isset($_GET['ID']) && trim($_GET['ID'])!="")
		{
		$ItemID=$_GET['ID'];
		$ID="ID=".$ItemID." and ";
		}
		else
		{
		$Barcode="";
		}
		if(isset($_GET['Under']) && trim($_GET['Under'])!="")
		{
		$ItemUnder=$_GET['Under'];
		$Under="i.Under =".$ItemUnder." and ";
		}
		else
		{
		$Under="";
		}
		if(isset($_GET['AddtionalInfo3']) && trim($_GET['AddtionalInfo3'])!="")
		{
		$ItemAddtionalInfo3=$_GET['AddtionalInfo3'];
		$AddtionalInfo5="i.Name like '%".$ItemAddtionalInfo5."%' and ";
		}
		else
		{
		$AddtionalInfo3="";
		}
		if(isset($_GET['Code']) && trim($_GET['Code'])!="")
		{
		$ItemCode=$_GET['Code'];
		$Code="i.AdditionalInfo2 like '%".$ItemCode."%' and ";
		}
		else
		{
		$Code="";
		}

		$searchbox=$ItemName."".$ID."".$Under."".$AddtionalInfo3."".$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 as AdditionalInfo3,i.AdditionalInfo5 as AdditionalInfo5,cast(StandardPrice3 as numeric) as CostPrice,cast(StandardPrice2 as numeric) as SalePrice,cast(StandardPrice1 as numeric) as RetailPrice1,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,
i.KeyField as KeyField,ShowInPurchases,ShowInSales,IsFixedAsset,ShowInStock,IsNonStockAble,Details,i.LastModificationTimeStamp,cast(i.VATPercent as numeric) as VATPercent,i.AdditionalInfo1 as AdditionalInfo1
   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";
   // offset $start rows fetch next $limit rows only";
		$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']=htmlspecialchars($row['ItemName']);
        $row['ProductCategoryName']=getnamesingle("inventory","Name","Under",$row['ProductCategoryName'],$connection);
      // $row['CompanyShortForm']=getnamesingle("Godowns","AdditionalInfo1","GodownID",$row['CompanyShortForm'],$connection);
        $row['Code']=htmlentities($row['Code']);

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

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

$ProductBaseType=$_GET['ProductBaseType'];
    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 RetailPrice,cast(StandardPrice1 as numeric) as RetailPrice1,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="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="";
    }

    if(isset($_GET['ShipperID']) && trim($_GET['ShipperID'])!="")
    {
    $ItemShipperID=$_GET['ShipperID'];
    $ShipperID="departid=".$ItemShipperID."";
    }
    else
    {
    $ShipperID="";
    }
    $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 as AdditionalInfo3,i.AdditionalInfo5 as AdditionalInfo5,cast(StandardPrice3 as numeric) as CostPrice,cast(StandardPrice2 as numeric) as RetailPrice,cast(StandardPrice1 as numeric) as RetailPrice1,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,
i.KeyField as KeyField,ShowInPurchases,ShowInSales,IsFixedAsset,ShowInStock,IsNonStockAble,Details,i.LastModificationTimeStamp,cast(i.VATPercent as numeric) as VATPercent,i.AdditionalInfo1 as AdditionalInfo1
   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";
   // offset $start rows fetch next $limit rows only";
    }

   $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']=htmlspecialchars($row['ItemName']);*/
        $row['ProductCategoryName']=getnamesingle("inventory","Name","Under",$row['ProductCategoryName'],$connection);
      // $row['CompanyShortForm']=getnamesingle("Godowns","AdditionalInfo1","GodownID",$row['CompanyShortForm'],$connection);
        $row['Code']=htmlentities($row['Code']);
foreach ($row as $key => $value) {
  # code...
  $row[$key]=utf8_encode($value);
}
    $data []=$row;
      }//end while
      //print_r($data);
      echo json_encode($data); 

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

$ProductBaseType=$_GET['ProductBaseType'];
    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 RetailPrice,cast(StandardPrice1 as numeric) as RetailPrice1,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="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="";
    }

    if(isset($_GET['ShipperID']) && trim($_GET['ShipperID'])!="")
    {
    $ItemShipperID=$_GET['ShipperID'];
    $ShipperID="departid=".$ItemShipperID."";
    }
    else
    {
    $ShipperID="";
    }
    $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 as AdditionalInfo3,i.AdditionalInfo5 as AdditionalInfo5,cast(StandardPrice3 as numeric) as CostPrice,cast(StandardPrice2 as numeric) as RetailPrice,cast(StandardPrice1 as numeric) as RetailPrice1,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,
i.KeyField as KeyField,ShowInPurchases,ShowInSales,IsFixedAsset,ShowInStock,IsNonStockAble,Details,i.LastModificationTimeStamp,cast(i.VATPercent as numeric) as VATPercent,i.AdditionalInfo1 as AdditionalInfo1
   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";
   // offset $start rows fetch next $limit rows only";
    }

   $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']=htmlspecialchars($row['ItemName']);*/
        $row['ProductCategoryName']=getnamesingle("inventory","Name","Under",$row['ProductCategoryName'],$connection);
      // $row['CompanyShortForm']=getnamesingle("Godowns","AdditionalInfo1","GodownID",$row['CompanyShortForm'],$connection);
        $row['Code']=htmlentities($row['Code']);
foreach ($row as $key => $value) {
  # code...
  $row[$key]=utf8_encode($value);
}
    $data []=$row;
      }//end while
      //print_r($data);
      echo json_encode($data); 

  
      
  
  }
	if($_GET['action']=="getItem")
	{
$ProductBaseType=$_GET['ProductBaseType'];
		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 RetailPrice,cast(StandardPrice1 as numeric) as RetailPrice1,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="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="";
		}

    if(isset($_GET['ShipperID']) && trim($_GET['ShipperID'])!="")
    {
    $ItemShipperID=$_GET['ShipperID'];
    $ShipperID="departid=".$ItemShipperID."";
    }
    else
    {
    $ShipperID="";
    }
		$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 as AdditionalInfo3,i.AdditionalInfo5 as AdditionalInfo5,cast(StandardPrice3 as numeric) as CostPrice,cast(StandardPrice2 as numeric) as RetailPrice,cast(StandardPrice1 as numeric) as RetailPrice1,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,
i.KeyField as KeyField,ShowInPurchases,ShowInSales,IsFixedAsset,ShowInStock,IsNonStockAble,Details,i.LastModificationTimeStamp,cast(i.VATPercent as numeric) as VATPercent,i.AdditionalInfo1 as AdditionalInfo1
   from inventory as i inner join godowns as c on c.GodownID=i.CompanyID where  ".$searchbox." i.[group]=0 and   ProductBaseType='".$ProductBaseType."' and ID in(select ItemID from StockSummary where $ShipperID 
group by itemid having sum(case when InvoiceType=8 then qty*-1 else qty*1 end )>0)  order by CompanyID";
   // offset $start rows fetch next $limit rows only";
		}

   $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']=htmlspecialchars($row['ItemName']);*/
        $row['ProductCategoryName']=getnamesingle("inventory","Name","Under",$row['ProductCategoryName'],$connection);
      // $row['CompanyShortForm']=getnamesingle("Godowns","AdditionalInfo1","GodownID",$row['CompanyShortForm'],$connection);
        $row['Code']=htmlentities($row['Code']);
foreach ($row as $key => $value) {
  # code...
  $row[$key]=utf8_encode($value);
}
    $data []=$row;
  		}//end while
  		//print_r($data);
  		echo json_encode($data); 

	
  		
	}
}
?>