<?php
include_once('database_connection.php');
//error_reporting(0);
  
  // Declare encoding META tag, it causes browser to load the UTF-8 charset before displaying the page.
  //echo '<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />';
if(isset($_SESSION['UserName']))
{
if(isset($_GET['action']))
{
    if($_GET['action']=="getStaffInfo")
  {
    $data=array();
    if(isset($_GET['COAID']))
    {
      $COAID=$_GET['COAID'];
      //$sql="select COAID,COAName from accounts where KeyField like '%$KeyField%'";
       $sql="select top 1 COAID,COANAME,Attr11 as email, 
Attr10 as Mobile,
Attr9 as  Contact,
Attr15 as TRNno,
Attr4 as licenseno,
Contactperson1,Attr13,convert(numeric,isnull(Attr7,0))+
(select SUM(credit)-sum(debit) from GeneralLedger where COAID=accounts.COAID)as Balance  
from accounts where natureid=14 and COAID=$COAID ";

      $result=odbc_exec($connection, $sql);

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

      $data[]=$row;
    }
    
    
    }
    else
    {}
  echo json_encode($data);  
  }
  if($_GET['action']=="getCompanyInfo")
  {
    $data=array();
    if(isset($_GET['KeyField']))
    {
      $KeyField=$_GET['KeyField'];
      //$sql="select COAID,COAName from accounts where KeyField like '%$KeyField%'";
       $sql="select top 1 COAID,COANAME,Attr11 as email, 
Attr10 as Mobile,
Attr9 as  Contact,
Attr15 as TRNno,
Attr4 as licenseno,
Contactperson1,Attr13,convert(numeric,isnull(Attr7,0))+isnull(
(select SUM(credit)-sum(debit) from GeneralLedger where COAID=accounts.COAID),0)as Balance  
from accounts where natureid=14 and (COAID=$KeyField or KeyField like '%$KeyField%' or COAName like '%$KeyField%') ";

      $result=odbc_exec($connection, $sql);

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

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




      odbc_autocommit($connection, FALSE);
    $main=json_decode($_POST['data']);
   /* print_r($main);
   return;*/
   // $ReferenceInvoiceID=$_GET['ReferenceInvoiceID'];
  
   // $mrdetails=json_decode($details);
                $SupplierID =isset($main->SupplierID)?$main->SupplierID: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:'-';
     $ReferenceInvoiceID =isset($main->ReferenceInvoiceID)?$main->ReferenceInvoiceID:0;
$Credit=isset($main->Credit)?$main->Credit:0;
      $sql="select * from invoicemaster where Referenceinvoiceid=".$ReferenceInvoiceID;
            $result=odbc_exec($connection, $sql);
            while($masterRow=odbc_fetch_array($result))
            {
              //$masterRow=odbc_fetch_array($result);
              $KeyField=$masterRow['KeyField'];
              $NetAmount=$masterRow['NetAmount'];
              $InvoiceID=$masterRow['InvoiceID'];
              $VoucherID=$masterRow['AutoVoucherID'];
              $InvoiceDate=$masterRow['InvoiceDate'];
              $GodownID=$masterRow['GodownID'];
              $Paid=$masterRow['Paid'];
              $Credit1=$masterRow['Credit'];
              $Payamt=$NetAmount-$Paid;

     //update invoicemaster
      $sql="update invoicemaster set SupplierID=$SupplierID,LastModificationTimeStamp=GETDATE(),Paid=($Paid+$Payamt),Credit=$Payamt,InvoiceStatus=4,EditLog='".$_SESSION['UserName']."' where InvoiceID=$InvoiceID";         
odbc_exec($connection,$sql) or die(odbc_error().$sql);
            }
 // group job card credit company


//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']=="CompanyCreditInvoice")
  {
   




      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);
      $InvoiceStatusUser=isset($main->InvoiceStatus)?$main->InvoiceStatus:1;
      $eVoucherNumber =isset($main->eVoucherNumber)?$main->eVoucherNumber: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;
            $Credit =isset($main->Credit)?$main->Credit: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.",Credit=".$Credit." 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,Credit,BranchID
       ) 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']."',".$Credit.",".$_SESSION['BRANCHID'].")";
          }//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);
if($InvoiceStatus==4 || $InvoiceStatusUser==4)
          {
          StockOut($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
//sym PAyment here 
 //enter in the invoicemaster 
   //delete previous card transaction 
           //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,$sqldelete); 
   
  $date=Date("Y-m-d");
          $Debit=0;
$Credit=$NetAmount;
$LocationID=$GodownID;
    $Narration="e-Voucher 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 H: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:$SupplierID);
    $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=($NetAmount);
            $Credit=($NetAmount);
/*            $Debit=($TotalCurrencyAmount-$CashRefund);
            $Credit=($TotalCurrencyAmount-$CashRefund);*/
            $CreditLedgerID=$CustomerID;
            $LedgerID=9000;//$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 */

/*//code for e-Voucher
$sql="select top 1 * from eVoucherMaster where eVoucherNumber='$eVoucherNumber'";
$result=odbc_exec($connection,$sql);
while($row=odbc_fetch_array($result))
{
  $RequestNo=$row['RequestNo'];
  $COAID=$row['COAID'];
  //$Under=$row['under'];
  $ItemID=0;
  $Qty=1;
  $Narration="e-Voucher Services";
  $Price=$row['Price'];
  //$transType=$row['transType'];
  $VoucherTypeID=$row['VoucherTypeID'];
  if($VoucherTypeID==1)
  $transType="Price";
  else
  $transType="Service";

  $CustomerUserID=$row['CustomerUserID'];
}

$Credit=$Debit;
$Debit=0;
$TransCode="e-Voucher Services";
      $evtID=getMaxId("evoucherTransaction","ID",$connection)+1;
$sql="insert into evoucherTransaction (ID,COAID,Debit,Credit,Under,ItemID,Qty,Narration,Price,RequestNo,eVoucherNumber,transType,VoucherTypeID,AgentID,TransCode,VoucherID) values($evtID,$COAID,0,$NetAmount,0,0,1,'$Narration',$Price,'$RequestNo','$eVoucherNumber','$transType',$VoucherTypeID,$CustomerUserID,'$TransCode',$VoucherID)";
odbc_exec($connection, $sql) or die(odbc_error().$sql); 
*/
/*
    $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 LastModificationTimeStamp=GETDATE(),InvoiceStatus=$InvoiceStatusUser,EditLog='".$_SESSION['UserName']."' where InvoiceID=$InvoiceID";         
odbc_exec($connection,$sql) or die(odbc_error().$sql);
 // insert into cardtransaction 
}//end if Invoicestatus==4

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

 

   
  }//end company credit invoice

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




      odbc_autocommit($connection, FALSE);
    $main=json_decode($_POST['data']);
  //  print_r($main);
    //return;
                $ReferenceInvoiceID =isset($main->ReferenceInvoiceID)?$main->ReferenceInvoiceID:0;
      $SupplierID=isset($main->CustomerID)?$main->CustomerID:96;
                  $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;
     $date=Date("Y-m-d");
          $Debit=0;
//$LocationID=$GodownID;
 $sql="select * from invoicemaster where Referenceinvoiceid=".$ReferenceInvoiceID;
            $result=odbc_exec($connection, $sql);
            while($masterRow=odbc_fetch_array($result))
            {
              //$masterRow=odbc_fetch_array($result);
              $KeyField=$masterRow['KeyField'];
              $NetAmount=$masterRow['NetAmount'];
              $InvoiceID=$masterRow['InvoiceID'];
              $VoucherID=$masterRow['AutoVoucherID'];
              $InvoiceDate=$masterRow['InvoiceDate'];
              $GodownID=$masterRow['GodownID'];
              $Credit=$NetAmount;

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

$Debit=0;

  $sql="INSERT INTO [dbo].[CardTransaction]
           ([ID]
           ,[CardNumber]
           ,[COAID]
           ,[Debit]
           ,[Credit]
           ,[Narration]
           ,[TDate]
           ,[Reference]
           ,[VoucherID]
           ,[isActive]
           ,[CreateLog]
           ,[InvoiceID]
           ,[LocationID],BranchID)
     VALUES($CardID,'$CardNumber',$SupplierID,$Debit,$Credit,'$Narration','$date','$KeyField',$VoucherID,1,'".$_SESSION['UserName']."',$InvoiceID,$GodownID,".$_SESSION['BRANCHID'].")";
     odbc_exec($connection,$sql) or die(odbc_error().$sql);
     //update invoicemaster
     $sql="update invoicemaster set LastModificationTimeStamp=GETDATE(),symreceived=$Credit,Paid=(isnull(Paid,0)+$Credit),InvoiceStatus=4,EditLog='".$_SESSION['UserName']."' where InvoiceID=$InvoiceID";         
odbc_exec($connection,$sql) or die(odbc_error().$sql);
}//end while 
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']=="InserteVoucherPayment")
{




      odbc_autocommit($connection, FALSE);
    $main=json_decode($_POST['data']);
  //  print_r($main);
  // return;
   // $details=$_POST['details'];
 
   // $mrdetails=json_decode($details);
    
      $eVoucherNumber =isset($main->eVoucherNumber)?$main->eVoucherNumber:0;
  

            $Narration =isset($main->Narration)?$main->Narration:'';
         
         //   $InvoiceDate =isset($main->BillDate)?$main->BillDate:'';
            $ReferenceInvoiceID =isset($main->ReferenceInvoiceID)?$main->ReferenceInvoiceID:0;
     
      //biltyno 
           /* $SalesManID=0;
            $SalesManID2=0;*/

            $PassCode='0';
            $Active=1;
            $InvoiceStatus=1;
            $KeyField="";
          //  $ChallanNo="0";
            $ItemID='0';
           // $BillNO=$QuoteReference;
            $GRNno="0";

            $BiltyNo='0';
            $ItemID='';
            $InvoiceStatusID=4;
           // if($InvoiceID=="")$InvoiceID=0;
           // $DeliveryDate=$DueDate;
        $sql="select * from invoicemaster where Referenceinvoiceid=".$ReferenceInvoiceID;
            $result=odbc_exec($connection, $sql);
            while($masterRow=odbc_fetch_array($result))
            {
              //$masterRow=odbc_fetch_array($result);
              $KeyField=$masterRow['KeyField'];
              $NetAmount=$masterRow['NetAmount'];
              $InvoiceID=$masterRow['InvoiceID'];
              $VoucherID=$masterRow['AutoVoucherID'];
              $InvoiceDate=$masterRow['InvoiceDate'];
              $GodownID=$masterRow['GodownID'];

//code for e-Voucher
$sql="select top 1 * from eVoucherMaster where eVoucherNumber='$eVoucherNumber'";
$result1=odbc_exec($connection,$sql);
while($row=odbc_fetch_array($result1))
{
  $RequestNo=$row['RequestNo'];
  $COAID=$row['COAID'];
  //$Under=$row['under'];
  $ItemID=0;
  $Qty=1;
  $Narration="e-Voucher Services";
  $Price=$row['Price'];
  //$transType=$row['transType'];
  $VoucherTypeID=$row['VoucherTypeID'];
  if($VoucherTypeID==1)
  $transType="Price";
  else
  $transType="Service";

  $CustomerUserID=$row['CustomerUserID'];
}
if($VoucherID=="")$VoucherID=0;
$Credit=$NetAmount;
$Debit=0;
$TransCode="e-Voucher Services";
      $evtID=getMaxId("evoucherTransaction","ID",$connection)+1;
 $sql="insert into evoucherTransaction (ID,COAID,Debit,Credit,Under,ItemID,Qty,Narration,Price,RequestNo,eVoucherNumber,transType,VoucherTypeID,AgentID,TransCode,VoucherID,GodownID,BranchID) values($evtID,$COAID,0,$NetAmount,0,0,1,'$Narration',$Price,'$RequestNo','$eVoucherNumber','$transType',$VoucherTypeID,$CustomerUserID,'$TransCode',$VoucherID,$GodownID,".$_SESSION['BRANCHID'].")";
odbc_exec($connection, $sql) or die(odbc_error().$sql); 

/*
    $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 LastModificationTimeStamp=GETDATE(),evoucherreceived=$NetAmount,evoucherNumber='$eVoucherNumber',Paid=(isnull(Paid,0)+$NetAmount),InvoiceStatus=4,EditLog='".$_SESSION['UserName']."' where InvoiceID=$InvoiceID";         
odbc_exec($connection,$sql) or die(odbc_error().$sql);
 // insert into cardtransaction 

}//end while 
//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']=="insertJobCardInvoiceEVoucher")
{



      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);
    
      $eVoucherNumber =isset($main->eVoucherNumber)?$main->eVoucherNumber: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,evoucherNumber
       ) 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']."','".$eVoucherNumber."')";
          }//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 
   
  $date=Date("Y-m-d");
          $Debit=0;
$Credit=$NetAmount;
$LocationID=$GodownID;
    $Narration="e-Voucher 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 
*/
$SalesAccountID=$_SESSION['SETTING']['SALES'];
$VATAccountID=$_SESSION['SETTING']['VATSALES'];


$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=($NetAmount);
            $Credit=($NetAmount);
/*            $Debit=($TotalCurrencyAmount-$CashRefund);
            $Credit=($TotalCurrencyAmount-$CashRefund);*/
            $CreditLedgerID=$CustomerID;
            $LedgerID=9000;//$CashAccountID;
           }
           if($a==3)
           {
            $Debit=$CreditCard;
            $Credit=$CreditCard;
            $CreditLedgerID=$CustomerID;
            $LedgerID=$CCAcountID;
           }
           $fdetails['LedgerID']=$LedgerID;
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="e-Voucher $eVoucherNumber , Customer Name : $CustomerName ";
           $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 */

//code for e-Voucher
$sql="select top 1 * from eVoucherMaster where eVoucherNumber='$eVoucherNumber'";
$result=odbc_exec($connection,$sql);
while($row=odbc_fetch_array($result))
{
  $RequestNo=$row['RequestNo'];
  $COAID=$row['COAID'];
  //$Under=$row['under'];
  $ItemID=0;
  $Qty=1;
  $Narration="e-Voucher Services";
  $Price=$row['Price'];
  //$transType=$row['transType'];
  $VoucherTypeID=$row['VoucherTypeID'];
  if($VoucherTypeID==1)
  $transType="Price";
  else
  $transType="Service";

  $CustomerUserID=$row['CustomerUserID'];
}

$Credit=$Debit;
$Debit=0;
$TransCode="e-Voucher Services";
      $evtID=getMaxId("evoucherTransaction","ID",$connection)+1;
$sql="insert into evoucherTransaction (ID,COAID,Debit,Credit,Under,ItemID,Qty,Narration,Price,RequestNo,eVoucherNumber,transType,VoucherTypeID,AgentID,TransCode,VoucherID,GodownID) values($evtID,$COAID,0,$NetAmount,0,0,1,'$Narration',$Price,'$RequestNo','$eVoucherNumber','$transType',$VoucherTypeID,$CustomerUserID,'$TransCode',$VoucherID,$GodownID,".$_SESSION['BRANCHID'].")";
odbc_exec($connection, $sql) or die(odbc_error().$sql); 

/*
    $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 LastModificationTimeStamp=GETDATE(),evoucherreceived=$NetAmount,evoucherNumber='$eVoucherNumber',Paid=(isnull(Paid,0)+$NetAmount),InvoiceStatus=4,EditLog='".$_SESSION['UserName']."' where InvoiceID=$InvoiceID";         
odbc_exec($connection,$sql) or die(odbc_error().$sql);
 // insert into cardtransaction 


//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']=="GetStaffBalance")
  {
   
    $data=array();
    if(isset($_GET['COAID']))
    {
      $COAID=$_GET['COAID'];
      //$sql="select COAID,COAName from accounts where KeyField like '%$KeyField%'";
      $sql="select COAID,COANAME,Attr11 as email, 
Attr10 as Mobile,
Attr9 as  Contact,
Attr15 as TRNno,
Attr4 as licenseno,
Contactperson1,Attr13,isnull(convert(numeric,Attr7)+
(select SUM(credit)-sum(debit) from GeneralLedger where COAID=accounts.COAID),0)as Balance  
from accounts where natureid=14 and COAID=".$COAID;

      $result=odbc_exec($connection, $sql);

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

      $data[]=$row;
    }
    
    
    }
    else
    {}
  echo json_encode($data);  
  
  }
  if($_GET['action']=="getStaffInfo")
  {
    $data=array();
    if(isset($_GET['COAID']))
    {
      $COAID=$_GET['COAID'];
      //$sql="select COAID,COAName from accounts where KeyField like '%$KeyField%'";
       $sql="select top 1 COAID,COANAME,Attr11 as email, 
Attr10 as Mobile,
Attr9 as  Contact,
Attr15 as TRNno,
Attr4 as licenseno,
Contactperson1,Attr13,convert(numeric,isnull(Attr7,0))+
(select SUM(credit)-sum(debit) from GeneralLedger where COAID=accounts.COAID)as Balance  
from accounts where natureid=14 and COAID=$COAID ";

      $result=odbc_exec($connection, $sql);

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

      $data[]=$row;
    }
    
    
    }
    else
    {}
  echo json_encode($data);  
  }
  if($_GET['action']=="getCompanyInfo23")
  {
    $data=array();
    if(isset($_GET['KeyField']))
    {
      $KeyField=$_GET['KeyField'];
      //$sql="select COAID,COAName from accounts where KeyField like '%$KeyField%'";
       $sql="select top 1 COAID,COANAME,Attr11 as email, 
Attr10 as Mobile,
Attr9 as  Contact,
Attr15 as TRNno,
Attr4 as licenseno,
Contactperson1,Attr13,convert(numeric,isnull(Attr7,0))+
(select SUM(credit)-sum(debit) from GeneralLedger where COAID=accounts.COAID)as Balance  
from accounts where natureid=14 and (KeyField like '%$KeyField%' or COAName like '%$KeyField%') ";

      $result=odbc_exec($connection, $sql);

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

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




      odbc_autocommit($connection, FALSE);
    $main=json_decode($_POST['data']);
   /* print_r($main);
   return;*/
   // $ReferenceInvoiceID=$_GET['ReferenceInvoiceID'];
  
   // $mrdetails=json_decode($details);
                $SupplierID =isset($main->SupplierID)?$main->SupplierID: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:'-';
     $ReferenceInvoiceID =isset($main->ReferenceInvoiceID)?$main->ReferenceInvoiceID:0;

      $sql="select * from invoicemaster where Referenceinvoiceid=".$ReferenceInvoiceID;
            $result=odbc_exec($connection, $sql);
            while($masterRow=odbc_fetch_array($result))
            {
              //$masterRow=odbc_fetch_array($result);
              $KeyField=$masterRow['KeyField'];
              $NetAmount=$masterRow['NetAmount'];
              $InvoiceID=$masterRow['InvoiceID'];
              $VoucherID=$masterRow['AutoVoucherID'];
              $InvoiceDate=$masterRow['InvoiceDate'];
              $GodownID=$masterRow['GodownID'];

     //update invoicemaster
      $sql="update invoicemaster set SupplierID=$SupplierID,LastModificationTimeStamp=GETDATE(),Paid=$NetAmount,Credit=$NetAmount,InvoiceStatus=4,EditLog='".$_SESSION['UserName']."' where InvoiceID=$InvoiceID";         
odbc_exec($connection,$sql) or die(odbc_error().$sql);
            }
 // group job card credit company


//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']=="CompanyCreditInvoice2")
  {
   




      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);
    
      $eVoucherNumber =isset($main->eVoucherNumber)?$main->eVoucherNumber: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;
            $Credit =isset($main->Credit)?$main->Credit: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.",Credit=".$Credit." 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,Credit,BranchID
       ) 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']."',".$Credit.",".$_SESSION['BRANCHID'].")";
          }//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 
   
  $date=Date("Y-m-d");
          $Debit=0;
$Credit=$NetAmount;
$LocationID=$GodownID;
    $Narration="e-Voucher 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 H: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:$SupplierID);
    $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=($NetAmount);
            $Credit=($NetAmount);
/*            $Debit=($TotalCurrencyAmount-$CashRefund);
            $Credit=($TotalCurrencyAmount-$CashRefund);*/
            $CreditLedgerID=$CustomerID;
            $LedgerID=9000;//$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 */

/*//code for e-Voucher
$sql="select top 1 * from eVoucherMaster where eVoucherNumber='$eVoucherNumber'";
$result=odbc_exec($connection,$sql);
while($row=odbc_fetch_array($result))
{
  $RequestNo=$row['RequestNo'];
  $COAID=$row['COAID'];
  //$Under=$row['under'];
  $ItemID=0;
  $Qty=1;
  $Narration="e-Voucher Services";
  $Price=$row['Price'];
  //$transType=$row['transType'];
  $VoucherTypeID=$row['VoucherTypeID'];
  if($VoucherTypeID==1)
  $transType="Price";
  else
  $transType="Service";

  $CustomerUserID=$row['CustomerUserID'];
}

$Credit=$Debit;
$Debit=0;
$TransCode="e-Voucher Services";
      $evtID=getMaxId("evoucherTransaction","ID",$connection)+1;
$sql="insert into evoucherTransaction (ID,COAID,Debit,Credit,Under,ItemID,Qty,Narration,Price,RequestNo,eVoucherNumber,transType,VoucherTypeID,AgentID,TransCode,VoucherID) values($evtID,$COAID,0,$NetAmount,0,0,1,'$Narration',$Price,'$RequestNo','$eVoucherNumber','$transType',$VoucherTypeID,$CustomerUserID,'$TransCode',$VoucherID)";
odbc_exec($connection, $sql) or die(odbc_error().$sql); 
*/
/*
    $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 LastModificationTimeStamp=GETDATE(),InvoiceStatus=4,EditLog='".$_SESSION['UserName']."' where InvoiceID=$InvoiceID";         
odbc_exec($connection,$sql) or die(odbc_error().$sql);
 // insert into cardtransaction 


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

 

   
  }//end company credit invoice
  if($_GET['action']=="getDiscounteVoucher")
  {
    $data=array();

    $CardNumber=$_GET['CardNumber'];
    $sql="select * from eVoucherMaster where eVoucherNumber='$CardNumber'";
    $result=odbc_exec($connection,$sql);
    if(odbc_num_rows($result)>0)
    {
      $row=odbc_fetch_array($result);
      $data=$row;
    }
    echo json_encode($data);
  }
  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")
  {

$data=array();
  $InvoiceID=$_GET['InvoiceID'];
  $InvoiceType=isset($_GET['InvoiceType'])?$_GET['InvoiceType']:5;
  if($InvoiceType==3){

 $sql="select  
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.Name as CompanyName,CustomerName as customerName,MobileNumber as mobilenumber,0 as platenumber,0 as JC_ChassisNumber,convert(Date,InvoiceDate) as InvoiceDate,i.KeyField as keyfield,biltyno,'' as CreateByUserName,InvoiceID,DueDate as 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,0 as creditcard,cashrefund as cashrefund
   from SalesInvoiceMaster 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=$InvoiceType ";

  }
    else{

     $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=$InvoiceType ";
    }
  $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data[]=$row;
    }

    if($InvoiceType==3)
    {
      $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
   ,unitprice as unitprice,amount,discountpercent,discountamount,d.taxpercent as vatpercent,d.taxAmount as vatamount,netamount,transactionid,d.Narration as detailnarration,'' as CategorySize,d.StandardPrice3 as CostPrice from  SalesinvoiceDetail 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."";
    }
    else
    {

    $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
   ,unitprice as unitprice,amount,discountpercent,discountamount,d.taxpercent as vatpercent,d.taxAmount as vatamount,netamount,transactionid,d.Narration as detailnarration,ItemJson as CategorySize,d.StandardPrice3 as CostPrice 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']=="getSalesInvoice")
{


  $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['InvoiceStatus']) && $_GET['InvoiceStatus']!="")
    {
    $InvoiceStatus=$_GET['InvoiceStatus'];
    $InvoiceStatus="";//i.InvoiceStatus in(".$InvoiceStatus.") and ";
    }
    else
    {
     // $InvoiceStatus=1;
      $InvoiceStatus="";
    }
    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.InvoiceStatus like '%".$PlateNumber."%' and ";
     $InvoiceStatus="";
    }
    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['StartDate']) && $_GET['StartDate']!="")
    {
    $InvoiceDate=$_GET['StartDate'];
    $InvoiceDate="convert(date,i.InvoiceDate)='".$InvoiceDate."' and ";
    }
    else
    {
  $InvoiceDate="(convert(date,i.InvoiceDate) between DateADD(DAY,-30,GETDATE()) and '".Date("Y-m-d")."')  and ";
    }

    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.$InvoiceStatus.$InvoiceDate;


$GodownID=(isset($_GET['GodownID']) && $_GET['GodownID']>0)?$_GET['GodownID']:$_SESSION['CompanyID'];
        $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,'' as JC_PlateNumber,'' as JC_ChassisNumber,convert(date,InvoiceDate) as InvoiceDate,i.KeyField as KeyField,'' as CreateByUserName,InvoiceID,DueDate as DeliveryDate,i.Narration as Narration,g.Name as Department,g.godownid as supplier,c.Name as Location,InvoiceStatus,(Case when InvoiceStatus=1 then 'Pending' when InvoiceStatus=2 then 'Accepted' when InvoiceStatus=3 then 'Rejected' when InvoiceStatus=4 then 'Closed'  else '' end) as OrderStatus,'' as col_Action ,i.godownid as GodownID,NetAmount,TotalQty,0 as symreceived
   from SalesInvoiceMaster 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 i.active=1";//and CreateLog='$_'
  $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      $data[]=$row;
    }
    echo json_encode($data);  

  
}

if($_GET['action']=="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['InvoiceStatus']) && $_GET['InvoiceStatus']!="")
    {
    $InvoiceStatus=$_GET['InvoiceStatus'];
    $InvoiceStatus="i.InvoiceStatus in(".$InvoiceStatus.") and ";
    }
    else
    {
     // $InvoiceStatus=1;
      $InvoiceStatus="";
    }
    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.InvoiceStatus like '%".$PlateNumber."%' and ";
     $InvoiceStatus="";
    }
    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.$InvoiceStatus;


    $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,(Case when InvoiceStatus=1 then 'Pending' when InvoiceStatus=2 then 'Accepted' when InvoiceStatus=3 then 'Rejected' when InvoiceStatus=4 then 'Closed'  else '' end) as OrderStatus,'' 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 i.active=1";//and CreateLog='$_'
  $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data[]=$row;
    }
    echo json_encode($data);  

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

$data=array();
	$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,'' as platenumber,'' as JC_ChassisNumber,InvoiceDate,i.KeyField as keyfield,biltyno,i.CreateLog as CreateByUserName,i.InvoiceID as InvoiceID,'' as DeliveryDate,i.Narration as Narration,g.Name as Department,g.godownid as supplier,c.Name as Location,InvoiceStatus,(Case when InvoiceStatus=1 then 'Pending' when InvoiceStatus=2 then 'Accepted' when InvoiceStatus=3 then 'Rejected' when InvoiceStatus=4 then 'Closed'  else '' end) as OrderStatus,'' as col_Action ,i.godownid as GodownID,NetAmount,TotalQty,TotalCurrencyAmount as cashpaid,TotalCreditCard as creditcard,cashrefund as cashrefund,0 as symreceived,0 as TRNNo,i.InvoiceDate as VoucherDateTime,case when i.editLog is null then i.CreateLog else i.editLog end   as Cashier ,0 as keyno,0 as parkingno,(select count(*) from SalesInvoiceMaster where CreateLog='".$_SESSION['UserName']."') as counter,i.InvoiceDate as VoucherDateTime,0 as evoucherreceived,TotalTaxAmount,TotalAmount,DiscountAmount,TotalAmount
   from SalesInvoiceMaster 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  salesinvoiceDetail 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 LastModificationTimeStamp=GETDATE(),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');
  }
  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']=="insertMutakamelaPayment2")
{




      odbc_autocommit($connection, FALSE);
    $main=json_decode($_POST['data']);
  //  print_r($main);
    //return;
                $ReferenceInvoiceID =isset($main->ReferenceInvoiceID)?$main->ReferenceInvoiceID:0;
      $SupplierID=isset($main->CustomerID)?$main->CustomerID:96;
                  $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;
     $date=Date("Y-m-d");
          $Debit=0;
//$LocationID=$GodownID;
 $sql="select * from invoicemaster where Referenceinvoiceid=".$ReferenceInvoiceID;
            $result=odbc_exec($connection, $sql);
            while($masterRow=odbc_fetch_array($result))
            {
              //$masterRow=odbc_fetch_array($result);
              $KeyField=$masterRow['KeyField'];
              $NetAmount=$masterRow['NetAmount'];
              $InvoiceID=$masterRow['InvoiceID'];
              $VoucherID=$masterRow['AutoVoucherID'];
              $InvoiceDate=$masterRow['InvoiceDate'];
              $GodownID=$masterRow['GodownID'];
              $Credit=$NetAmount;

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

$Debit=0;

  $sql="INSERT INTO [dbo].[CardTransaction]
           ([ID]
           ,[CardNumber]
           ,[COAID]
           ,[Debit]
           ,[Credit]
           ,[Narration]
           ,[TDate]
           ,[Reference]
           ,[VoucherID]
           ,[isActive]
           ,[CreateLog]
           ,[InvoiceID]
           ,[LocationID],BranchID)
     VALUES($CardID,'$CardNumber',$SupplierID,$Debit,$Credit,'$Narration','$date','$KeyField',$VoucherID,1,'".$_SESSION['UserName']."',$InvoiceID,$GodownID,".$_SESSION['BRANCHID'].")";
     odbc_exec($connection,$sql) or die(odbc_error().$sql);
     //update invoicemaster
     $sql="update invoicemaster set LastModificationTimeStamp=GETDATE(),symreceived=$Credit,Paid=(isnull(Paid,0)+$Credit),InvoiceStatus=4,EditLog='".$_SESSION['UserName']."' where InvoiceID=$InvoiceID";         
odbc_exec($connection,$sql) or die(odbc_error().$sql);
}//end while 
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']=="InserteVoucherPayment2")
{




      odbc_autocommit($connection, FALSE);
    $main=json_decode($_POST['data']);
  //  print_r($main);
  // return;
   // $details=$_POST['details'];
 
   // $mrdetails=json_decode($details);
    
      $eVoucherNumber =isset($main->eVoucherNumber)?$main->eVoucherNumber:0;
  

            $Narration =isset($main->Narration)?$main->Narration:'';
         
         //   $InvoiceDate =isset($main->BillDate)?$main->BillDate:'';
            $ReferenceInvoiceID =isset($main->ReferenceInvoiceID)?$main->ReferenceInvoiceID:0;
     
      //biltyno 
           /* $SalesManID=0;
            $SalesManID2=0;*/

            $PassCode='0';
            $Active=1;
            $InvoiceStatus=1;
            $KeyField="";
          //  $ChallanNo="0";
            $ItemID='0';
           // $BillNO=$QuoteReference;
            $GRNno="0";

            $BiltyNo='0';
            $ItemID='';
            $InvoiceStatusID=4;
           // if($InvoiceID=="")$InvoiceID=0;
           // $DeliveryDate=$DueDate;
        $sql="select * from invoicemaster where Referenceinvoiceid=".$ReferenceInvoiceID;
            $result=odbc_exec($connection, $sql);
            while($masterRow=odbc_fetch_array($result))
            {
              //$masterRow=odbc_fetch_array($result);
              $KeyField=$masterRow['KeyField'];
              $NetAmount=$masterRow['NetAmount'];
              $InvoiceID=$masterRow['InvoiceID'];
              $VoucherID=$masterRow['AutoVoucherID'];
              $InvoiceDate=$masterRow['InvoiceDate'];
              $GodownID=$masterRow['GodownID'];

//code for e-Voucher
$sql="select top 1 * from eVoucherMaster where eVoucherNumber='$eVoucherNumber'";
$result1=odbc_exec($connection,$sql);
while($row=odbc_fetch_array($result1))
{
  $RequestNo=$row['RequestNo'];
  $COAID=$row['COAID'];
  //$Under=$row['under'];
  $ItemID=0;
  $Qty=1;
  $Narration="e-Voucher Services";
  $Price=$row['Price'];
  //$transType=$row['transType'];
  $VoucherTypeID=$row['VoucherTypeID'];
  if($VoucherTypeID==1)
  $transType="Price";
  else
  $transType="Service";

  $CustomerUserID=$row['CustomerUserID'];
}

$Credit=$NetAmount;
$Debit=0;
$TransCode="e-Voucher Services";
      $evtID=getMaxId("evoucherTransaction","ID",$connection)+1;
 $sql="insert into evoucherTransaction (ID,COAID,Debit,Credit,Under,ItemID,Qty,Narration,Price,RequestNo,eVoucherNumber,transType,VoucherTypeID,AgentID,TransCode,VoucherID,GodownID,BranchID) values($evtID,$COAID,0,$NetAmount,0,0,1,'$Narration',$Price,'$RequestNo','$eVoucherNumber','$transType',$VoucherTypeID,$CustomerUserID,'$TransCode',$VoucherID,$GodownID,".$_SESSION['BRANCHID'].")";
odbc_exec($connection, $sql) or die(odbc_error().$sql); 

/*
    $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 LastModificationTimeStamp=GETDATE(),evoucherreceived=$NetAmount,evoucherNumber='$eVoucherNumber',Paid=(isnull(Paid,0)+$NetAmount),InvoiceStatus=4,EditLog='".$_SESSION['UserName']."' where InvoiceID=$InvoiceID";         
odbc_exec($connection,$sql) or die(odbc_error().$sql);
 // insert into cardtransaction 

}//end while 
//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']=="insertJobCardInvoiceEVoucher2")
{



      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);
    
      $eVoucherNumber =isset($main->eVoucherNumber)?$main->eVoucherNumber: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,evoucherNumber
       ) 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']."','".$eVoucherNumber."')";
          }//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 
   
  $date=Date("Y-m-d");
          $Debit=0;
$Credit=$NetAmount;
$LocationID=$GodownID;
    $Narration="e-Voucher 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 
*/
$SalesAccountID=$_SESSION['SETTING']['SALES'];
$VATAccountID=$_SESSION['SETTING']['VATSALES'];


$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=($NetAmount);
            $Credit=($NetAmount);
/*            $Debit=($TotalCurrencyAmount-$CashRefund);
            $Credit=($TotalCurrencyAmount-$CashRefund);*/
            $CreditLedgerID=$CustomerID;
            $LedgerID=9000;//$CashAccountID;
           }
           if($a==3)
           {
            $Debit=$CreditCard;
            $Credit=$CreditCard;
            $CreditLedgerID=$CustomerID;
            $LedgerID=$CCAcountID;
           }
           $fdetails['LedgerID']=$LedgerID;
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="e-Voucher $eVoucherNumber , Customer Name : $CustomerName ";
           $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 */

//code for e-Voucher
$sql="select top 1 * from eVoucherMaster where eVoucherNumber='$eVoucherNumber'";
$result=odbc_exec($connection,$sql);
while($row=odbc_fetch_array($result))
{
  $RequestNo=$row['RequestNo'];
  $COAID=$row['COAID'];
  //$Under=$row['under'];
  $ItemID=0;
  $Qty=1;
  $Narration="e-Voucher Services";
  $Price=$row['Price'];
  //$transType=$row['transType'];
  $VoucherTypeID=$row['VoucherTypeID'];
  if($VoucherTypeID==1)
  $transType="Price";
  else
  $transType="Service";

  $CustomerUserID=$row['CustomerUserID'];
}

$Credit=$Debit;
$Debit=0;
$TransCode="e-Voucher Services";
      $evtID=getMaxId("evoucherTransaction","ID",$connection)+1;
$sql="insert into evoucherTransaction (ID,COAID,Debit,Credit,Under,ItemID,Qty,Narration,Price,RequestNo,eVoucherNumber,transType,VoucherTypeID,AgentID,TransCode,VoucherID,GodownID) values($evtID,$COAID,0,$NetAmount,0,0,1,'$Narration',$Price,'$RequestNo','$eVoucherNumber','$transType',$VoucherTypeID,$CustomerUserID,'$TransCode',$VoucherID,$GodownID,".$_SESSION['BRANCHID'].")";
odbc_exec($connection, $sql) or die(odbc_error().$sql); 

/*
    $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 LastModificationTimeStamp=GETDATE(),evoucherreceived=$NetAmount,evoucherNumber='$eVoucherNumber',Paid=(isnull(Paid,0)+$NetAmount),InvoiceStatus=4,EditLog='".$_SESSION['UserName']."' where InvoiceID=$InvoiceID";         
odbc_exec($connection,$sql) or die(odbc_error().$sql);
 // insert into cardtransaction 


//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']=="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,0,$NetAmount,'$Narration','$date','$KeyField',$VoucherID,1,'".$_SESSION['UserName']."',$InvoiceID,$LocationID)";
     odbc_exec($connection,$sql) or die(odbc_error().$sql);
     //update invoicemaster
     $sql="update invoicemaster set LastModificationTimeStamp=GETDATE(),symreceived=$NetAmount,Paid=(isnull(Paid,0)+$NetAmount),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")
{
  
//  print_r($_POST['paydetail']);
  $paydetail=$_POST['paydetail'];
  $paydetail=json_decode($paydetail);
  print_r($paydetail);
  return;
  /*foreach($paydetail as $p)
  $p[0]=str_replace("SP-", "", $p[0]) ;*/
    
    $SplitPay=0;
  foreach($paydetail as $p)
  {
    $amt=$p[1];
    if($amt>0)$SplitPay=1;
  }  
  //print_r($paydetail);
  //return;*/
  if($SplitPay==0)
      {
    if(isset($_GET['DirectSave']) && $_GET['DirectSave']==1)
    {
      $DirectSave=1;
    }
    else
    {
      $DirectSave=0;
    }
      odbc_autocommit($connection, FALSE);
    
    
    //print_r();
    $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))
    {
    if($main->CashPaid==null)
  $main->CashPaid =0;//($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=2;
            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;
            $dt=Date("Y-m-d H:i");
           /*$sql="select * from invoicemaster where LastModificationTimeStamp between '$dt:00'   and '$dt:59' and  CreateLog='".$_SESSION['UserName']."'";
            //return;
             $result=odbc_exec($connection, $sql);
             if(odbc_num_rows($result)>0)
             {
             odbc_rollback($connection);
            $res=array('status'=>"Error",'description'=>'Invoice Can Not BE DUPLICATE');
            echo json_encode($res);
              return;
             }*/

        $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'];
              if($InvoiceType==59)
               $InvoiceStatus=2;
              else if($InvoiceType==5)
              $InvoiceStatus=1;
              else 
              $InvoiceStatus=4;

      $sql="update InvoiceMaster set InvoiceStatus=$InvoiceStatus,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.",TotalAmount=".$TotalAmount.",DiscountAmount=".$DiscountAmount.",TotalTaxAmount=".$TotalTaxAmount.",NetAmount=".$NetAmount.",MulkiyaNo='".$MulkiyaNo."',ParkingNo='".$ParkingNo."',KeyNo='".$KeyNo."',PictureLocation='',CashRefund=".$CashRefund.",CreditCard=".$CreditCard.",TotalCurrencyAmount=".$TotalCurrencyAmount.",Cash=".$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;*/       
       //  return;
            //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="SO-".$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,
      TotalTaxAmount
           ,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,Cash,BranchID
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",'".$ChallanNo
           ."','".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount.",".$TotalTaxAmount
           .",".$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']."',".($TotalCurrencyAmount-$CashRefund).",1)";
          }//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);

        //  insertInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);
          if($InvoiceStatus==4 || $InvoiceStatus==2)
          {
          /*    InsertJList($InvoiceID,$checklistdetail,'CheckList',$connection);
              InsertJList($InvoiceID,$warningdetail,'WarningList',$connection);
              InsertJList($InvoiceID,$inspectiondetail,'InspectionList',$connection);     */
           $ID=getmaxId("SalesInvoiceMaster","InvoiceID",$connection)+1;

            
            $where="InvoiceType=3"; 
    $KeyField=generateCode("SalesInvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="SI-".$KeyField2;
            
              //insert into salesinvoicemaster 
              $sql="   insert into Salesinvoicemaster (InvoiceID,InvoiceDate,[CheckedBy],[Narration],InvoiceType,[Active],[Customerid],[GodownID],[ChallanNo],KeyField,[BillNO] ,[GRNno]
      ,[CreateLog],[EditLog],[DeleteLog] ,[TotalQty],[TotalAmount],[DiscountPercent],[DiscountAmount],[Rounding],[NetAmount],[ReferenceInvoiceID]
      ,[Received],[Balance],[PeriodID],[ShipperID],[DueDate],[InvoiceStatusID],[Posted],[TotalTaxPercent],[TotalTaxAmount],[CurrencyID],[TotalCurrencyRate] ,[TotalCurrencyAmount]
      ,[InvoiceStatus]
      ,[MobileNumber]
      ,[CustomerName]
      ,[Email]
      ,[SalesManID]
      ,[datamode])
SELECT $ID,'".Date('Y-m-d')."',[CheckedBy],[Narration],3,[Active],[SupplierID],[GodownID],[ChallanNo],'$KeyField' ,[BillNO]
      ,[GRNno],[CreateLog],[EditLog],[DeleteLog]
      ,[TotalQty],[TotalAmount],[DiscountPercent],[DiscountAmount],[Rounding]
      ,[NetAmount],[InvoiceID],[Paid]
      ,[Balance],[PeriodID],[ShipperID],[DueDate],[InvoiceStatusID],[Posted],[TotalTaxPercent]
      ,[TotalTaxAmount],[CurrencyID],[TotalCurrencyRate]
      ,[TotalCurrencyAmount],[InvoiceStatus],[MobileNumber],[CustomerName],[Email],[SalesManID]
      ,[datamode]
  FROM [dbo].[InvoiceMaster] where invoiceid=$InvoiceID";
     odbc_exec($connection,$sql);
              //insert sales detail
  insertSalesInvoiceDetail($ID,$mrdetails,$InvoiceType,$connection);  
  //stock
              StockOut($InvoiceID,$main,$mrdetails,59,$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']=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:'Delivery';
         //  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:98);
    $CustomerID=((isset($main->CustomerID) && $main->CustomerID!="") ?$main->CustomerID:0);
    $SalesAccountID=((isset($main->SalesAccountID) && $main->SalesAccountID!="") ?$main->SalesAccountID:6);
    $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 
*/
if($InvoiceType==59)
{
        $Code='COGS_POST';
  /*if(CheckPolicy($Userid,$SidebarID,$Code,$degree,$connection)==1)*/
  if(1==1)
  {
    $sql="select sum from ";
$subtotal=getSum("InvoiceDetail","sum(StandardPrice3) as sum","InvoiceID",$InvoiceID,$connection);
$InventoryLedgerID=$_SESSION['SETTING']['INVENTORY'];
$COGSLedgerID=$_SESSION['SETTING']['COGS'];
$fdetails=array();  
           $fdetails['VoucherID']=$VoucherID;
           $fdetails['LedgerID']=$COGSLedgerID;//$SupplierID;//$d->CustomerLedgerID; 
        
            $Debit=$TotalAmount;
            $Credit=$TotalAmount;
            $CreditLedgerID=$InventoryLedgerID;//$d->SalesLedgerID;

           $fdetails['Debit']=$subtotal;
           $fdetails['Credit']=$subtotal;
           $fdetails['Narration']="Cost of Good Sold Entry :".$VoucherID;
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;//$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="Cost of Good Sold Entry"; 
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);
     }//end check policy
}
$CashAccountID=$_SESSION['SETTING']['CASHINHAND'];
$SalesAccountID=$_SESSION['SETTING']['SALES'];
$CashCustomer=$_SESSION['SETTING']['CASHCUSTOMERS'];
$VATAccountID=$_SESSION['SETTING']['VATSALES'];
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 */
        //TotalTaxAmount=(select convert(numeric(5,2),sum(taxamount)) from invoiceDetail where invoiceid=$InvoiceID)-$DiscountAmount

        //Paid=(isnull(Paid,0)+$NetAmount),
  $sql="update invoicemaster set LastModificationTimeStamp='".Date("Y-m-d H:i:s")."',InvoiceStatus=4,EditLog='".$_SESSION['UserName']."' where InvoiceID=$InvoiceID";         
odbc_exec($connection,$sql) or die(odbc_error().$sql);
}//end invoicestatus==4
/*else if ($InvoiceStatus==2)
{
   StockOut($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
}*/
            //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);
}
 else
 {
//print_r($paydetail);

    if(isset($_GET['DirectSave']) && $_GET['DirectSave']==1 || $SplitPay==1)
    {
      $DirectSave=1;
    }
    else
    {
      $DirectSave=0;
    }
      odbc_autocommit($connection, FALSE);
    
    
    //print_r();
    $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))
    {
    if($main->CashPaid==null)
  $main->CashPaid =0;//($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=2;
            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;
            $dt=Date("Y-m-d H:i");
           $sql="select * from invoicemaster where LastModificationTimeStamp between '$dt:00'   and '$dt:59' and  CreateLog='".$_SESSION['UserName']."'";
            //return;
             $result=odbc_exec($connection, $sql);
             if(odbc_num_rows($result)>0)
             {
             odbc_rollback($connection);
            $res=array('status'=>"Error",'description'=>'Invoice Can Not BE DUPLICATE');
            echo json_encode($res);
              return;
             }

        $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'];
              if($InvoiceType==59)
               $InvoiceStatus=2;
              else if($InvoiceType==5)
              $InvoiceStatus=1;
              else 
              $InvoiceStatus=4;

      $sql="update InvoiceMaster set InvoiceStatus=$InvoiceStatus,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.",TotalAmount=".$TotalAmount.",DiscountAmount=".$DiscountAmount.",TotalTaxAmount=".$TotalTaxAmount.",NetAmount=".$NetAmount.",MulkiyaNo='".$MulkiyaNo."',ParkingNo='".$ParkingNo."',KeyNo='".$KeyNo."',PictureLocation='',CashRefund=".$CashRefund.",CreditCard=".$CreditCard.",TotalCurrencyAmount=".$TotalCurrencyAmount.",Cash=".$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;*/       
       //  return;
            //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="SO-".$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,
      TotalTaxAmount
           ,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,Cash,BranchID
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",'".$ChallanNo
           ."','".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount.",".$TotalTaxAmount
           .",".$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']."',".($TotalCurrencyAmount-$CashRefund).",1)";
          }//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);
          if($InvoiceStatus==4 || $InvoiceStatus==2)
          {
          /*    InsertJList($InvoiceID,$checklistdetail,'CheckList',$connection);
              InsertJList($InvoiceID,$warningdetail,'WarningList',$connection);
              InsertJList($InvoiceID,$inspectiondetail,'InspectionList',$connection);     */
              StockOut($InvoiceID,$main,$mrdetails,5,$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']=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:21);
    $CustomerID=((isset($main->CustomerID) && $main->CustomerID!="") ?$main->CustomerID:0);
    $SalesAccountID=((isset($main->SalesAccountID) && $main->SalesAccountID!="") ?$main->SalesAccountID:6);
    $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'];
$SalesAccountID=$_SESSION['SETTING']['SALES'];
$CashCustomer=$_SESSION['SETTING']['CASHCUSTOMERS'];
$VATAccountID=$_SESSION['SETTING']['VATSALES'];


if($InvoiceType==59)
{
          $Code='COGS_POST';
  /*if(CheckPolicy($Userid,$SidebarID,$Code,$degree,$connection)==1)*/
  if(1==1)
  {
    $sql="select sum from ";
$subtotal=getSum("InvoiceDetail","sum(StandardPrice3) as sum","InvoiceID",$InvoiceID,$connection);
$InventoryLedgerID=$_SESSION['SETTING']['INVENTORY'];
$COGSLedgerID=$_SESSION['SETTING']['COGS'];
$fdetails=array();  
           $fdetails['VoucherID']=$VoucherID;
           $fdetails['LedgerID']=$COGSLedgerID;//$SupplierID;//$d->CustomerLedgerID; 
        
            $Debit=$TotalAmount;
            $Credit=$TotalAmount;
            $CreditLedgerID=$InventoryLedgerID;//$d->SalesLedgerID;

           $fdetails['Debit']=$subtotal;
           $fdetails['Credit']=$subtotal;
           $fdetails['Narration']="Cost of Good Sold Entry :".$VoucherID;
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;//$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="Cost of Good Sold Entry"; 
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);
     }//end check policy

}
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 */
        //echo count($paydetail);
        for($a=0;$a<count($paydetail);$a++)
        {
          if($paydetail[$a][1]>0)
          {
          $PayID=str_replace("SP-","", $paydetail[$a][0]);
           $fdetails['VoucherID']=$VoucherID;
       //    $table,$field,$exp=1,$value=1,$connection
           $LedgerID=getnamesingle("Chargesandpayments","LedgerID","ID",$PayID,$connection);
            //$paydetail[$a][1]
           if($LedgerID==22)
           {
            $Debit=($TotalCurrencyAmount-$CashRefund);
            $Credit=($TotalCurrencyAmount-$CashRefund);
            $Debit=$paydetail[$a][1];
            $Credit=$paydetail[$a][1];
            $CreditLedgerID=$CustomerID;
           // $LedgerID=$CashAccountID;
           }
           else
           {
            $Debit=$paydetail[$a][1];
            $Credit=$paydetail[$a][1];
            $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);
            }
         }

        //TotalTaxAmount=(select convert(numeric(5,2),sum(taxamount)) from invoiceDetail where invoiceid=$InvoiceID)-$DiscountAmount

        //Paid=(isnull(Paid,0)+$NetAmount),
  $sql="update invoicemaster set LastModificationTimeStamp='".Date("Y-m-d H:i:s")."',InvoiceStatus=4,EditLog='".$_SESSION['UserName']."' where InvoiceID=$InvoiceID";         
odbc_exec($connection,$sql) or die(odbc_error().$sql);
}//end invoicestatus==4
/*else if ($InvoiceStatus==2)
{
   StockOut($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
}*/
            //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']=="insertJobCardInvoiceold")
{
    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;
            $dt=Date("Y-m-d H:i");
           $sql="select * from invoicemaster where LastModificationTimeStamp between '$dt:00'   and '$dt:59' and  CreateLog='".$_SESSION['UserName']."'";
            //return;
             $result=odbc_exec($connection, $sql);
             if(odbc_num_rows($result)>0)
             {
             odbc_rollback($connection);
            $res=array('status'=>"Error",'description'=>'Invoice Can Not BE DUPLICATE');
            echo json_encode($res);
              return;
             }

        $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.",Cash=".$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,
      TotalTaxAmount
           ,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,Cash,BranchID
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",'".$ChallanNo
           ."','".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount.",".$TotalTaxAmount
           .",".$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']."',".($TotalCurrencyAmount-$CashRefund).",".$_SESSION['BRANCHID'].")";
          }//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);
          if($InvoiceStatus==4)
          {
          /*    InsertJList($InvoiceID,$checklistdetail,'CheckList',$connection);
              InsertJList($InvoiceID,$warningdetail,'WarningList',$connection);
              InsertJList($InvoiceID,$inspectiondetail,'InspectionList',$connection);     */
              StockOut($InvoiceID,$main,$mrdetails,$InvoiceType,$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:98);
    $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 */
        //TotalTaxAmount=(select convert(numeric(5,2),sum(taxamount)) from invoiceDetail where invoiceid=$InvoiceID)-$DiscountAmount
  $sql="update invoicemaster set LastModificationTimeStamp='".Date("Y-m-d H:i:s")."',Paid=(isnull(Paid,0)+$NetAmount),InvoiceStatus=4,EditLog='".$_SESSION['UserName']."' where InvoiceID=$InvoiceID";         
odbc_exec($connection,$sql) or die(odbc_error().$sql);
}//end invoicestatus==4
            //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'];
   /* print_r($details);
    return;*/
	/*	$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 =$_SESSION['CompanyID'];//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->Cash;
      		$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 Salesinvoicemaster where invoiceid=".$InvoiceID;
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {

            	$row=odbc_fetch_array($result);
            	$KeyField=$row['KeyField'];
		  $sql="update SalesInvoiceMaster set CustomerID=".$SupplierID.",MobileNumber='".$MobileNumber."',CustomerName='".$CustomerName."',Email='".$Email."',InvoiceDate='".$InvoiceDate."',DueDate='".$DeliveryDate."',ChallanNo='".$ChallanNo."',SalesManID=".$SalesManID.",Narration='".$Notes."',GodownID=".$GodownID.",InvoiceType=3,TotalAmount=".$TotalAmount.",DiscountAmount=".$DiscountAmount.",TotalTaxAmount=".$TotalTaxAmount.",NetAmount=".$NetAmount.",CashRefund=".$CashRefund.",TotalCurrencyAmount=".$TotalCurrencyAmount.",TotalCreditCard=".$CreditCard." where InvoiceID=".$InvoiceID;
     //return;
         /*$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 salesinvoicedetail where InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sqldelete);
            }
            else
            {
             /* echo "here";
              return;*/
              $InvoiceType=3;
              $GType="InvoiceDate>'2022-11-01' and GodownID=".$GodownID;
               $InvoiceID=getMaxLocationID("SalesInvoiceMaster","InvoiceID",$GType,$connection)+1;
            //$InvoiceID=getMaxLocationID("SalesInvoiceMaster","InvoiceID",$connection)+1;
            $PictureLocation='';
            //if($GodownID==1)$InvoiceID=$InvoiceID-100000000;
            $where="InvoiceType=$InvoiceType";//  and GodownID=".$GodownID;  
            $KeyField=generateCode("SalesInvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            if($InvoiceType==3)
            { 
              /*$BranchID=getnamesingle("Godowns","KeyField","GodownID",$_SESSION['BRANCHID'],$connection);*/
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="SALE-".$KeyField2;
            }
            
            //$InvoiceID=getmaxId("SalesInvoiceMaster","InvoiceID",$connection)+1;
            $PictureLocation='';
           	if($InvoiceType==8)
           	{/*
           	$where="InvoiceType=8 and GodownID=".$GodownID;	
           	$KeyField=generateCode("SalesInvoiceMaster","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."')";
           $sql="insert into Salesinvoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,CustomerID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,InvoiceStatus
           ,CashRefund
       ,TotalCurrencyAmount
       ,TotalCreditCard
           ,MobileNumber,CustomerName,Email,SalesManID,CreateLog
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",'".$ChallanNo
           ."','".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount
           .",".$DiscountAmount
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$ShipperID
           .",'".$TRNNo
           ."','".$DueDate."'
           ,".$InvoiceStatusID
           .",".$InvoiceStatus."
           ,".$CashRefund."
           ,".$TotalCurrencyAmount."
           ,".$CreditCard."
           ,'".$MobileNumber."','".$CustomerName."','".$Email."',".$SalesManID.",'".$_SESSION['UserName']."')";
       		}//end else for insert */
//return;
       		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);
          insertSalesInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);
          $main->ParkingNo=$KeyField;
          $main->KeyField=$KeyField;
          $main->GodownID=$_SESSION['CompanyID'];
          StockOut($InvoiceID,$main,$mrdetails,5,$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 VoucherTypeID=8 and  ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
              $sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
            //  odbc_exec($connection,$sqlupdate);
       		// Insert Voucher 
              $where=" VoucherTypeID=8 ";
              $KeyField=generateCode("VoucherMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            
            $KeyField2=str_pad($KeyField,7,"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']=8;//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 H: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','InvoiceID'=>$InvoiceID);
  }
  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";*/
      $sql="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 where sm.Active=1 ";
         $filename='cache/'.md5($sql).".txt";
       if (filemtime($filename) < time()-1*600) 
       {
	$result=odbc_exec($connection,$sql);
		while($row=odbc_fetch_array($result))
		{
			$data[]=$row;
		}
     @unlink($filename);
     $data=json_encode($data);
          file_put_contents($filename, serialize($data));
      }
      else
      {
      $data=unserialize(file_get_contents($filename));  

      }
		echo ($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,cast(i.Additionalinfo5 as nvarchar) 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,i.PictureLocation as Picture
   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)) {
//     $result=$conn->query($sql);
//$rows = $result->fetchAll(PDO::FETCH_NAMED);//FETCH_NUM
//print_r($rows);
//foreach($rows as $row) {
  //printf($row['AdditionalInfo5']);

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

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

	}
   if($_GET['action']=="getPaymentMethod")
{
  $data=array();
  if(isset($_GET['Enabled']) && $_GET['Enabled']==1)
  {
$sql="select * from Chargesandpayments where isEnabled=1 and Active=1";    
  }
else
{
$sql="select * from Chargesandpayments where Active=1";
}
      $result=odbc_exec($connection, $sql);

    while($row=odbc_fetch_array($result))
    {
     /* if($row['Description']=="Cash")
      $row['LedgerID']=$_SESSION['AccountID'];*/ // for driver cash account
        
$data[]=$row;
    }

    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['ShowInSales']) && $_GET['ShowInSales']==true)
    $ShowInSales="ShowInSales=1 and ";//.$_GET['ShowInSales']." and ";
    else
    $ShowInSales="";

    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.$ShowInSales;

     $sql="  select   ROW_NUMBER() OVER (
      PARTITION BY [CompanyID]
      ORDER BY [CompanyID]
   ) row_num,i.Name as ItemName,(select Name from inventory inv2 where inv2.id=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['ShowInSales']) && trim($_GET['ShowInSales'])!="" && $_GET['ShowInSales']==true)
    {
    $ItemShowInSales=$_GET['ShowInSales'];
    $ShowInSales="i.ShowInSales =".$ItemShowInSales." and ";
    }
    else
    {
    $ShowInSales="";
    }
		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.$ShowInSales;

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

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

	
  		
	}
}
}//end session
else
{
        $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Generated , Please Login Again');
        echo json_encode($res);
}

function getMaterial($PackageID,$connection)
{
  $data=array();
  $sql="select *,(select Name from inventory where id=(select Under from inventory where id=(select under from inventory as i where i.id=Inventory_Ingredients.MaterialID))) as Category,(select Under from inventory where id=(select under from inventory as i where i.id=Inventory_Ingredients.MaterialID)) as CategoryID,(select Name from inventory where id=(select under from inventory as i where i.id=Inventory_Ingredients.MaterialID)) as SubCategory,(select Under from inventory as i where i.id=Inventory_Ingredients.MaterialID) as SubCategoryID,(select Name from Inventory where ID=Inventory_Ingredients.MaterialID) as Name from Inventory_Ingredients where ItemID=$PackageID";

          $result1=odbc_exec($connection,$sql);
    while($row1=odbc_fetch_array($result1))
    {
      $data['detailitems'][]=$row1;
    }   
    return json_encode($data);
}
?>