<?php include_once('database_connection.php');

if(isset($_GET['action1']))
{
    if($_GET['action1']=="gettokendata")
  {
    $data=array();
    $token=$_GET['token'];
    $sql="select top 1 InvoiceID,CustomerName,MobileNumber,KeyNo,InvoiceDate,Email from invoicemaster where keyno='$token' and InvoiceDate='".Date("Y-m-d")."' order by invoiceid desc";
    $result=odbc_exec($connection, $sql);
    while($row=odbc_fetch_array($result))
    {
      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);
    return;
  }
    if($_GET['action1']=="editjobcard")
  {
         odbc_autocommit($connection, FALSE);
         $data=$_POST;
         $data=array_keys($data);
        // $_POST=json_decode($data);
    $d=json_decode($data[0]);
    //print_r($d);
    $InvoiceID=$d->InvoiceID;
    $CustomerName=$d->fullname;
    $Email=str_replace("_",".",$d->email);
    $MobileNumber=$d->phone;
    $KeyNo=$d->KeyNo;

$sql="update invoicemaster set CustomerName='$CustomerName',Email='$Email',MobileNumber='$MobileNumber',Narration=Narration+' Modified ' where InvoiceID=$InvoiceID";
odbc_exec($connection,$sql);

   if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
else
{
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

}
//$res=array('status'=>"ok",'description'=>'RTA Invoice Generated Sucessfully');
    echo json_encode($res);

return;
  }


}
if(!(isset($_SESSION['userid'])))
{
   $res=array('status'=>"Error",'description'=>'Session Expired , Please Login  First ');
   echo json_encode($res);
   return;
}
else
{
  $Userid=$_SESSION['userid'];
}
if(isset($_GET['action']))
{
  if($_GET['action']=="Q1")
  {
    $data=array();
    $data[0]='Q1';
    $data[1]='Q2';
    $data[2]='Q3';
    $data[3]='Q4';
    $data[4]='Q5';
    $data[5]='Q6';
    $data[6]='Q7';
    $data[7]='Q8';
    $data[8]='Q9';
    $data[9]='Q10';
    $data[10]='Q11';
    $data[11]='Q12';
    $data[12]='Q13';
    $data[13]='Q14';
    echo json_encode($data);
  }

if(isset($_SESSION['userid']))
{

  if($_GET['action']=="UpdatePrice")
  {
    $InvoiceID=$_GET['InvoiceID'];
    //update invoice details 
    $sql="update invoiceDetail set UnitPrice=95,Amount=95*Qty,
TaxAmount=((Qty*95)*(TaxPercent/100)),NetAmount=((Qty*95)+((Qty*95)*(TaxPercent/100))) where UnitPrice=70 and  InvoiceID=$InvoiceID";
odbc_exec($connection,$sql);


    $sql="update invoiceDetail set UnitPrice=220,Amount=220*Qty,
TaxAmount=((Qty*220)*(TaxPercent/100)),NetAmount=((Qty*220)+((Qty*220)*(TaxPercent/100))) where UnitPrice=170 and InvoiceID=$InvoiceID";

odbc_exec($connection,$sql);

    $sql="select sum(Amount) as Amount,sum(TaxAmount) as TotalTaxAmount,sum(NetAmount) as NetAmount from invoiceDetail where InvoiceID=$InvoiceID";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
$Amount=$row['Amount'];
$TotalTaxAmount=$row['TotalTaxAmount'];
$NetAmount=$row['NetAmount'];
    $sql="update InvoiceMaster set TotalAmount=$Amount,TotalTaxAmount=$TotalTaxAmount,NetAmount=$NetAmount where InvoiceID=$InvoiceID";
    odbc_exec($connection,$sql);

    }
    //update invoicemaster 
    $sql="update VoucherDetails set debit=$NetAmount,Credit=$NetAmount where ReferenceInvoiceID=$InvoiceID and LedgerID=96";
    odbc_exec($connection,$sql);
    //update voucher details 
    $sql="update VoucherMaster set totalamount=$NetAmount where ReferenceInvoiceID=$InvoiceID and VoucherTypeID=8";
    odbc_exec($connection,$sql);    
    //update vouchermaster 
     if (!odbc_error())
  {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
//$res=array('status'=>"ok",'description'=>'RTA Invoice Generated Sucessfully');
    echo json_encode($res);    
  }
  if($_GET['action']=="StockAdjustment")
  {




  odbc_autocommit($connection, FALSE);
  $SideBarID=$_GET['SideBarID'];    
  $permission=userrights($Userid,$SideBarID,'[Create]',$connection);
    if($permission==1)
    {
    $main=json_decode($_POST['data']);
    $details=$_POST['detail'];
    $detailsOut=$_POST['detailOut'];

/*    $checklistdetail=$_POST['checklistdetail'];
    $warningdetail=$_POST['warningdetail'];
    $inspectiondetail=$_POST['inspectiondetail'];*/

    $mrdetails=json_decode($details);
    $mrdetailsOut=json_decode($detailsOut);
    /*print_r($main);
    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.",";  
          }
    }*/
$CurrentDepartmentID =isset($main->CurrentDepartmentID)?$main->CurrentDepartmentID: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;
          
            $Narration =isset($main->Narration)?$main->Narration:'';
            $Narration=htmlspecialchars($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:Date('Y-m-d');
            $InvoiceDate =(isset($main->BillDate) && $main->BillDate!="")?$main->BillDate:Date('Y-m-d');
            $InvoiceID =isset($main->InvoiceID)?$main->InvoiceID:0;
            $ReferenceInvoiceID =isset($main->ReferenceInvoiceID)?$main->ReferenceInvoiceID: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:'';
            $CustomerName=str_replace('_',' ',$CustomerName);
            $Email=str_replace('_','.',$Email);
                 $ChassisNumber =(isset($main->ChassisNumber) && $main->ChassisNumber!="")?$main->ChassisNumber:'';
            $PlateNumber =(isset($main->PlateNumber) && $main->PlateNumber!="")?$main->PlateNumber:'';
            $TRNNo =(isset($main->TRNNo) && $main->TRNNo!="")?$main->TRNNo:'';
            $PreparedBy =(isset($main->PreparedBy) && $main->PreparedBy!="")?$main->PreparedBy:'';
            $CustomerType =(isset($main->CustomerType) && $main->CustomerType!="")?$main->CustomerType:6;
            $VehicleBrand =(isset($main->VehicleBrand) && $main->VehicleBrand!="")?$main->VehicleBrand:0;
            $ChallanNo =(isset($main->ChallanNo) && $main->ChallanNo!="")?$main->ChallanNo:0;
$VehicleModel =(isset($main->VehicleModel)&& $main->VehicleModel!="" )?$main->VehicleModel:0; 
$VehicleType =(isset($main->VehicleType)&& $main->VehicleType!="" )?$main->VehicleType:0; 
 $VehicleColor =(isset($main->VehicleColor)&& $main->VehicleColor!="" )?$main->VehicleColor:0;  
  $VehicleYear =(isset($main->VehicleYear) && $main->VehicleYear!="") ?$main->VehicleYear:0;  
            $FuelLevel =(isset($main->FuelLevel) && $main->FuelLevel>0)?$main->FuelLevel:0;  
            $MulkiyaNo =(isset($main->MulkiyaNo) && $main->MulkiyaNo!="") ?$main->MulkiyaNo:0;  
            $ParkingNo =(isset($main->ParkingNo) && $main->ParkingNo!="") ?$main->ParkingNo:0;  
            $KeyNo =(isset($main->KeyNo) && $main->KeyNo!="") ?$main->KeyNo:0;  
            $SalesManID =(isset($main->SalesManID) && $main->SalesManID>0 )?$main->SalesManID:0;  
      $SalesManID2 =(isset($main->SalesManID2) && $main->SalesManID2>0 )?$main->SalesManID2:0;
     /*   if($InvoiceID<1 && $GodownID==1 && ($ParkingNo!="" || $ParkingNo!="-" || $ParkingNo!="0"))
        {  
        $sql="select * from invoicemaster where InvoiceType=$InvoiceType and ParkingNo='".$ParkingNo."'";
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'TransactionNumber Already Exists');
echo json_encode($res);
              return;
            }
          }*/
           /* $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;
            $DeliveryDate=$DueDate;
            if($InvoiceID=="")$InvoiceID=0;
        $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='',EditLog='".$_SESSION['UserName']."',ShipperID=$ShipperID 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($GodownID==1)
            {
            $where="InvoiceType=$InvoiceType  and GodownID=".$GodownID;  
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            if($InvoiceType==55)
            { 
              $BranchID=getnamesingle("Godowns","KeyField","GodownID",1,$connection);
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="ST-ADJ-".$KeyField2;
            }
            if($InvoiceType==56)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="CCL-".$KeyField2;
            }
            if($InvoiceType==57)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="RDL-".$KeyField2;
            }
            if($InvoiceType==58)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="PWS-".$KeyField2;
            }
            if($InvoiceType==59)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="DN-".$KeyField2;
            }
            if($GodownID==20)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="AYQ-".$KeyField2;
            }
            $ACNarration='AUTO VOUCHER for DOC: '.$KeyField.' from Jobcard';
            }
            // insert query for invoice master 
             $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,BranchID
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",".$ChallanNo
           .",'".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount
           .",".$DiscountAmount
           .",".$TotalTaxAmount           
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$CurrentDepartmentID
           .",".$BiltyNo
           .",'".$DueDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$PurchaseLedgerID.",'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$SalesManID.",".$SalesManID2.",'".$TRNNo."',".$CustomerType.",".$VehicleBrand.",".$VehicleModel.",".$VehicleType.",".$VehicleColor.",".$VehicleYear.",'".$Notes."',".$FuelLevel.",'".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."','".$PictureLocation."','".$_SESSION['UserName']."',1)";
      /*     $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,BranchID
       ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $res=odbc_prepare($connection,$sql);
$UserName=$_SESSION['UserName'];
$BRANCHID=$_SESSION['BRANCHID'];
 $para=array($InvoiceID,$InvoiceDate,$Narration
           ,$InvoiceType,$Active,$SupplierID,$GodownID,$ChallanNo,$KeyField,
           $BillNO,$GRNno,$TotalAmount,$DiscountAmount,$TotalTaxAmount         
 ,$NetAmount,$ReferenceInvoiceID,$ShipperID,$BiltyNo,$DueDate,$InvoiceStatusID,$DeliveryDate,$InvoiceStatus,$VATLedgerID,$PurchaseLedgerID,$MobileNumber,$CustomerName,$Email,$PlateNumber,$ChassisNumber,$SalesManID,$SalesManID2,$TRNNo,$CustomerType,$VehicleBrand,$VehicleModel,$VehicleType,$VehicleColor,$VehicleYear,$Notes,$FuelLevel,$MulkiyaNo,$ParkingNo,$KeyNo,$PictureLocation,$UserName,$BRANCHID);
$r=odbc_execute($res,$para);*/
//return;
          }//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 stockeldger 
$sql="delete from stockledger where InvoiceTypeID=$InvoiceType and  InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sql);//remove Previous Stock
          //code for details 
       //   insertInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);
          insertInvoiceDetail($InvoiceID,$mrdetailsOut,$InvoiceType,$connection);
          $main->ParkingNo=$KeyField;
          $main->KeyField=$KeyField;
          //code for details 
         // StockINOnly($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
         // StockIN($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
          StockINOnly($InvoiceID,$main,$mrdetailsOut,$InvoiceType,$connection);
         // StockProcess($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
         // insertStock2($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
  /*            InsertJList($InvoiceID,$checklistdetail,'CheckList',$connection);
              InsertJList($InvoiceID,$warningdetail,'WarningList',$connection);
              InsertJList($InvoiceID,$inspectiondetail,'InspectionList',$connection);     
*/
          // Insert Voucher 

            
          $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
  if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
       }
       else
       {
        $res=array('status'=>"Error",'description'=>'Sorry You Dont have Permission to Enter JobCard');
       }
    echo json_encode($res);

  

  }//end Stock Adjustment

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



  odbc_autocommit($connection, FALSE);
  $SideBarID=$_GET['SideBarID'];    
  $permission=userrights($Userid,$SideBarID,'[Create]',$connection);
    if($permission==1)
    {
    $main=json_decode($_POST['data']);
    $details=$_POST['detail'];
    $detailsOut=$_POST['detailOut'];

/*    $checklistdetail=$_POST['checklistdetail'];
    $warningdetail=$_POST['warningdetail'];
    $inspectiondetail=$_POST['inspectiondetail'];*/

    $mrdetails=json_decode($details);
    $mrdetailsOut=json_decode($detailsOut);
    /*print_r($main);
    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.",";  
          }
    }*/
$CurrentDepartmentID =isset($main->CurrentDepartmentID)?$main->CurrentDepartmentID: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;
          
            $Narration =isset($main->Narration)?$main->Narration:'';
            $Narration=htmlspecialchars($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:Date('Y-m-d');
            $InvoiceDate =(isset($main->BillDate) && $main->BillDate!="")?$main->BillDate:Date('Y-m-d');
            $InvoiceID =isset($main->InvoiceID)?$main->InvoiceID:0;
            $ReferenceInvoiceID =isset($main->ReferenceInvoiceID)?$main->ReferenceInvoiceID: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:'';
            $CustomerName=str_replace('_',' ',$CustomerName);
            $Email=str_replace('_','.',$Email);
                 $ChassisNumber =(isset($main->ChassisNumber) && $main->ChassisNumber!="")?$main->ChassisNumber:'';
            $PlateNumber =(isset($main->PlateNumber) && $main->PlateNumber!="")?$main->PlateNumber:'';
            $TRNNo =(isset($main->TRNNo) && $main->TRNNo!="")?$main->TRNNo:'';
            $PreparedBy =(isset($main->PreparedBy) && $main->PreparedBy!="")?$main->PreparedBy:'';
            $CustomerType =(isset($main->CustomerType) && $main->CustomerType!="")?$main->CustomerType:6;
            $VehicleBrand =(isset($main->VehicleBrand) && $main->VehicleBrand!="")?$main->VehicleBrand:0;
            $ChallanNo =(isset($main->ChallanNo) && $main->ChallanNo!="")?$main->ChallanNo:0;
$VehicleModel =(isset($main->VehicleModel)&& $main->VehicleModel!="" )?$main->VehicleModel:0; 
$VehicleType =(isset($main->VehicleType)&& $main->VehicleType!="" )?$main->VehicleType:0; 
 $VehicleColor =(isset($main->VehicleColor)&& $main->VehicleColor!="" )?$main->VehicleColor:0;  
  $VehicleYear =(isset($main->VehicleYear) && $main->VehicleYear!="") ?$main->VehicleYear:0;  
            $FuelLevel =(isset($main->FuelLevel) && $main->FuelLevel>0)?$main->FuelLevel:0;  
            $MulkiyaNo =(isset($main->MulkiyaNo) && $main->MulkiyaNo!="") ?$main->MulkiyaNo:0;  
            $ParkingNo =(isset($main->ParkingNo) && $main->ParkingNo!="") ?$main->ParkingNo:0;  
            $KeyNo =(isset($main->KeyNo) && $main->KeyNo!="") ?$main->KeyNo:0;  
            $SalesManID =(isset($main->SalesManID) && $main->SalesManID>0 )?$main->SalesManID:0;  
      $SalesManID2 =(isset($main->SalesManID2) && $main->SalesManID2>0 )?$main->SalesManID2:0;
     /*   if($InvoiceID<1 && $GodownID==1 && ($ParkingNo!="" || $ParkingNo!="-" || $ParkingNo!="0"))
        {  
        $sql="select * from invoicemaster where InvoiceType=$InvoiceType and ParkingNo='".$ParkingNo."'";
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'TransactionNumber Already Exists');
echo json_encode($res);
              return;
            }
          }*/
           /* $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;
            $DeliveryDate=$DueDate;
            if($InvoiceID=="")$InvoiceID=0;
        $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='',EditLog='".$_SESSION['UserName']."',ShipperID=$ShipperID 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($GodownID==1)
            {
            $where="InvoiceType=$InvoiceType  and GodownID=".$GodownID;  
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            if($InvoiceType==55)
            { 
              $BranchID=getnamesingle("Godowns","KeyField","GodownID",1,$connection);
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="PRO-".$KeyField2;
            }
            if($InvoiceType==56)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="CCL-".$KeyField2;
            }
            if($InvoiceType==57)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="RDL-".$KeyField2;
            }
            if($InvoiceType==58)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="PWS-".$KeyField2;
            }
            if($InvoiceType==59)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="DN-".$KeyField2;
            }
            if($GodownID==20)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="AYQ-".$KeyField2;
            }
            $ACNarration='AUTO VOUCHER for DOC: '.$KeyField.' from Jobcard';
            }
            // insert query for invoice master 
             $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,BranchID
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",".$ChallanNo
           .",'".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount
           .",".$DiscountAmount
           .",".$TotalTaxAmount           
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$CurrentDepartmentID
           .",".$BiltyNo
           .",'".$DueDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$PurchaseLedgerID.",'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$SalesManID.",".$SalesManID2.",'".$TRNNo."',".$CustomerType.",".$VehicleBrand.",".$VehicleModel.",".$VehicleType.",".$VehicleColor.",".$VehicleYear.",'".$Notes."',".$FuelLevel.",'".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."','".$PictureLocation."','".$_SESSION['UserName']."',1)";
      /*     $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,BranchID
       ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $res=odbc_prepare($connection,$sql);
$UserName=$_SESSION['UserName'];
$BRANCHID=$_SESSION['BRANCHID'];
 $para=array($InvoiceID,$InvoiceDate,$Narration
           ,$InvoiceType,$Active,$SupplierID,$GodownID,$ChallanNo,$KeyField,
           $BillNO,$GRNno,$TotalAmount,$DiscountAmount,$TotalTaxAmount         
 ,$NetAmount,$ReferenceInvoiceID,$ShipperID,$BiltyNo,$DueDate,$InvoiceStatusID,$DeliveryDate,$InvoiceStatus,$VATLedgerID,$PurchaseLedgerID,$MobileNumber,$CustomerName,$Email,$PlateNumber,$ChassisNumber,$SalesManID,$SalesManID2,$TRNNo,$CustomerType,$VehicleBrand,$VehicleModel,$VehicleType,$VehicleColor,$VehicleYear,$Notes,$FuelLevel,$MulkiyaNo,$ParkingNo,$KeyNo,$PictureLocation,$UserName,$BRANCHID);
$r=odbc_execute($res,$para);*/
//return;
          }//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 stockeldger 
$sql="delete from stockledger where InvoiceTypeID=$InvoiceType and  InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sql);//remove Previous Stock
          //code for details 
          insertInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);

          //code for details 
          StockINOnly($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
         // StockIN($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
      //    StockOut($InvoiceID,$main,$mrdetailsOut,$InvoiceType,$connection);
         // StockProcess($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
         // insertStock2($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
  /*            InsertJList($InvoiceID,$checklistdetail,'CheckList',$connection);
              InsertJList($InvoiceID,$warningdetail,'WarningList',$connection);
              InsertJList($InvoiceID,$inspectiondetail,'InspectionList',$connection);     
*/
          // Insert Voucher 

            
          $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
  if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
       }
       else
       {
        $res=array('status'=>"Error",'description'=>'Sorry You Dont have Permission to Enter JobCard');
       }
    echo json_encode($res);

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


  $_POST['data']=json_encode($_POST);

  //print_r($_POST);

//return;
  odbc_autocommit($connection, FALSE);
  $SideBarID=$_GET['SideBarID'];    
  $permission=userrights($Userid,$SideBarID,'[Create]',$connection);
    if($permission==1)
    {
    $main=json_decode($_POST['data']);
    $details=$_POST['detail'];
    $mrdetails=json_decode($details);

    $main=json_decode($main->data);
    $detailsOut=$_POST['detailOut'];
    $mrdetailsOut=json_decode($detailsOut);
              /*          print_r($main);
                      return;*/
//print_r($mrdetails[0]->CategorySize);
/*
for($a=0;$a<count($mrdetails);$a++)
{
  $CategorySize=json_decode($mrdetails[$a]->CategorySize); 
   for($b=0;$b<count($CategorySize);$b++)
   {
    $ItemID= $CategorySize[$b]->Item_ItemID;//."<br>";
    $ReferenceItemID=$CategorySize[$b]->Item_RefID;
    $Qty=$CategorySize[$b]->Qty;
    $Rate=$CategorySize[$b]->Rate;
    $Remarks= $CategorySize[$b]->Narration;
    $ExpiryDate=Date("Y-m-d");
    $InvoiceID=21;
    $InvoiceType=5;
    $Active=1;
    $ContainerNo="";
    $COAID=0;
    $BranchID=0;
    $UserID=0;
    $TransDate=Date("Y-m-d");
    $CounterID=0;
    $VoucherID=0;
    $SupplierID=0;
    $CurrentDepartmentID=7;
    $GodownID=1;
    $Reference="";
    $ReferenceInvoiceID=0;
    $ProjectID=0;
    $ItemJson="";
    $Attr1="";
    $Attr2="";
    $Attr3="";
    $Attr4="";
    $Attr5="";
    $Attr6="";
    $Attr7="";
    $Attr8="";
    $Attr9="";
    $Attr10="";
    
               $ID=getmaxId("stockledger","ID",$connection)+1;
             echo   $sql="INSERT INTO [StockLedger]
           ([ID]
           ,[ItemID]
           ,[ReferenceItemID]
           ,[Qty]
           ,[InvoiceTypeID]
           ,[InvoiceID]
           ,[ReferenceInvoiceID]
           ,[Reference]
           ,[Remarks]
           ,[GodownID]
           ,[ProjectID]
           ,[BranchID]
           ,[COAID]
           ,[Active]
           ,[ContainerNo]
           ,[UserID]
           ,[Rate]
           ,[CounterID]
           ,[VoucherID]
           ,[TransDate]
           ,[ExpiryDate]
           ,[SupplierID]
           ,[DepartmentID]
           ,[ItemJson]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           ".(-1*$Qty).",
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $GodownID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $CurrentDepartmentID,'$ItemJson'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
          )"; 
   }
}*/
//return;
    

          //code for Image 
//    $c=0;
          /*foreach ($_FILES['image'] as $key => $value) {
            # code...
*/         

           
    //        if($c<2)
  //          $c++;
//          }
            //print_r($value) ;           }
/*print_r($main);
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.",";  
          }
    }*/
$CurrentDepartmentID =isset($main->CurrentDepartmentID)?$main->CurrentDepartmentID:0;
      $ShipperID =isset($main->ShipperID)?$main->ShipperID:0;
            $GodownID =(isset($main->GodownID) && $main->GodownID!="")?$main->GodownID:1;
            $SupplierID =isset($main->SupplierID)?$main->SupplierID:0;
            $SupplierName =isset($main->SupplierName)?$main->SupplierName:'';
            $Location =isset($main->Location)?$main->Location:0;
          
            $Narration =isset($main->Narration)?$main->Narration:'';
            $Narration=htmlspecialchars($Narration);
            $InvoiceType =isset($main->InvoiceType)?$main->InvoiceType:3;
            $QuoteReference =isset($main->QuoteReference)?$main->QuoteReference:null;
            $Notes =isset($main->Notes)?$main->Notes:'';
            $DueDate =isset($main->DeliveryDate)?$main->DeliveryDate:date("Y-m-d");
            $InvoiceDate =isset($main->BillDate)?$main->BillDate:date("Y-m-d");
            $InvoiceID =isset($main->InvoiceID)?$main->InvoiceID:0;
            $ReferenceInvoiceID =isset($main->ReferenceInvoiceID)?$main->ReferenceInvoiceID: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:'';
            $CustomerName=str_replace('_',' ',$CustomerName);
            $Email=str_replace('_','.',$Email);
                 $ChassisNumber =(isset($main->ChassisNumber) && $main->ChassisNumber!="")?$main->ChassisNumber:'';
            $PlateNumber =(isset($main->PlateNumber) && $main->PlateNumber!="")?$main->PlateNumber:'';
            $TRNNo =(isset($main->TRNNo) && $main->TRNNo!="")?$main->TRNNo:'';
            $PreparedBy =(isset($main->PreparedBy) && $main->PreparedBy!="")?$main->PreparedBy:'';
            $CustomerType =(isset($main->CustomerType) && $main->CustomerType!="")?$main->CustomerType:6;
            $VehicleBrand =(isset($main->VehicleBrand) && $main->VehicleBrand!="")?$main->VehicleBrand:0;
            $ChallanNo =(isset($main->ChallanNo) && $main->ChallanNo!="")?$main->ChallanNo:0;
$VehicleModel =(isset($main->VehicleModel)&& $main->VehicleModel!="" )?$main->VehicleModel:0; 
$VehicleType =(isset($main->VehicleType)&& $main->VehicleType!="" )?$main->VehicleType:0; 
 $VehicleColor =(isset($main->VehicleColor)&& $main->VehicleColor!="" )?$main->VehicleColor:0;  
  $VehicleYear =(isset($main->VehicleYear) && $main->VehicleYear!="") ?$main->VehicleYear:0;  
            $FuelLevel =(isset($main->FuelLevel) && $main->FuelLevel>0)?$main->FuelLevel:0;  
            $MulkiyaNo =(isset($main->MulkiyaNo) && $main->MulkiyaNo!="") ?$main->MulkiyaNo:0;  
            $ParkingNo =(isset($main->ParkingNo) && $main->ParkingNo!="") ?$main->ParkingNo:0;  
            $KeyNo =(isset($main->KeyNo) && $main->KeyNo!="") ?$main->KeyNo:0;  
            $SalesManID =(isset($main->SalesManID) && $main->SalesManID>0 )?$main->SalesManID:0;  
      $SalesManID2 =(isset($main->SalesManID2) && $main->SalesManID2>0 )?$main->SalesManID2:0;
     /*   if($InvoiceID<1 && $GodownID==1 && ($ParkingNo!="" || $ParkingNo!="-" || $ParkingNo!="0"))
        {  
        $sql="select * from invoicemaster where InvoiceType=$InvoiceType and ParkingNo='".$ParkingNo."'";
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'TransactionNumber Already Exists');
echo json_encode($res);
              return;
            }
          }*/
           /* $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=5;
            $InvoiceStatusID=1;
            $DeliveryDate=$DueDate;
            if($InvoiceID=="" || $InvoiceID==null || $InvoiceID=="undefined")$InvoiceID=0;
        $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'];
              $main->KeyField=$KeyField;
     $sql="update SalesInvoiceMaster set CustomerID=".$SupplierID.",MobileNumber='".$MobileNumber."',CustomerName='".$CustomerName."',Email='".$Email."',InvoiceDate='".$InvoiceDate."',GodownID=".$GodownID.",InvoiceType=".$InvoiceType.",TotalAmount=".$TotalAmount.",DiscountAmount=".$DiscountAmount.",TotalTaxAmount=".$TotalTaxAmount.",NetAmount=".$NetAmount.",EditLog='".$_SESSION['UserName']."',ShipperID=$ShipperID 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;
            $sqldelete="delete from Salesinvoicedetail where InvoiceID=".$InvoiceID;
         odbc_exec($connection,$sqldelete);

            }
            else
            {
             // if($GodownID==10)
//$InvoiceID=getMaxLocationID("SalesInvoiceMaster","InvoiceID","GodownID=10",$connection)+1;                

               //else 
              $InvoiceID=getMaxId("SalesInvoiceMaster","InvoiceID",$connection)+1;
            //$InvoiceID=getMaxLocationID("SalesInvoiceMaster","InvoiceID",$connection)+1;
              $GodownID=1;
            $PictureLocation='';
            if($GodownID==1 || $GodownID==10)
            {
            $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="SI-".$KeyField2;
            }
            if($InvoiceType==56)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="CUT-".$KeyField2;
            }
            if($InvoiceType==57)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="RDL-".$KeyField2;
            }
            if($InvoiceType==58)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="PWS-".$KeyField2;
            }
            if($InvoiceType==59)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="DN-".$KeyField2;
            }
            if($GodownID==20)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="AYQ-".$KeyField2;
            }
            $ACNarration='AUTO VOUCHER for DOC: '.$KeyField.' from Jobcard';
            }
            $main->KeyField=$KeyField;
//code for SalesInvoiceMaster 
$UserName=$_SESSION['UserName'];
  $sql="insert into SalesInvoiceMaster(InvoiceID,InvoiceDate,GodownID,KeyField,InvoiceType,Active,
Posted,TotalTaxAmount,NetAmount,CreateLog,InvoiceStatusID,CustomerID,OrderStatusID,BillNo,datamode) values($InvoiceID,'$InvoiceDate',$GodownID,'$KeyField',3,1,
1,$TotalTaxAmount,$NetAmount,'".$UserName."',1,".$SupplierID.",1,'$BillNO',0)";
//odbc_exec($connection,$sql) or die(odbc_error().$sql);


//end code for Sales Invoice Master            

            // insert query for invoice master 
             $sql1="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,ItemID
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",".$ChallanNo
           .",'".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount
           .",".$DiscountAmount
           .",".$TotalTaxAmount           
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$CurrentDepartmentID
           .",".$BiltyNo
           .",'".$DueDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$PurchaseLedgerID.",'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$SalesManID.",".$SalesManID2.",'".$TRNNo."',".$CustomerType.",".$VehicleBrand.",".$VehicleModel.",".$VehicleType.",".$VehicleColor.",".$VehicleYear.",'".$Notes."',".$FuelLevel.",'".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."','".$PictureLocation."','".$_SESSION['UserName']."',5)";
      /*     $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,BranchID
       ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $res=odbc_prepare($connection,$sql);
$UserName=$_SESSION['UserName'];
$BRANCHID=$_SESSION['BRANCHID'];
 $para=array($InvoiceID,$InvoiceDate,$Narration
           ,$InvoiceType,$Active,$SupplierID,$GodownID,$ChallanNo,$KeyField,
           $BillNO,$GRNno,$TotalAmount,$DiscountAmount,$TotalTaxAmount         
 ,$NetAmount,$ReferenceInvoiceID,$ShipperID,$BiltyNo,$DueDate,$InvoiceStatusID,$DeliveryDate,$InvoiceStatus,$VATLedgerID,$PurchaseLedgerID,$MobileNumber,$CustomerName,$Email,$PlateNumber,$ChassisNumber,$SalesManID,$SalesManID2,$TRNNo,$CustomerType,$VehicleBrand,$VehicleModel,$VehicleType,$VehicleColor,$VehicleYear,$Notes,$FuelLevel,$MulkiyaNo,$ParkingNo,$KeyNo,$PictureLocation,$UserName,$BRANCHID);
$r=odbc_execute($res,$para);*/
//return;
          }//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 stockeldger 

$sql="delete from stockledger where InvoiceTypeID=$InvoiceType and  InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sql);//remove Previous Stock
          //code for details 
       //   StockIN($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);                      
insertSalesInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);         
         // insertInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);
          StockOut($InvoiceID,$main,$mrdetails,5,$connection);
//code for image 
          $TextBoxName="CuttingPicture";
          $sql="delete from InvoiceMaster_JobDetail where InvoiceID=".$InvoiceID." and TextBoxName='".$TextBoxName."'";
  odbc_exec($connection, $sql);

          if(isset($_FILES['Picture1']))
          {
            $ppic=$_FILES['Picture1']['name'];
                if($ppic!="")
              {
          
      $newfile=rand()*1200;
      $ext=strrchr($ppic,".");
      $newpic=$newfile.$ext;
      save($_FILES['Picture1'],'',"images/");  
      rename("images/".$ppic,"images/".$newpic);
      $PictureLocation=$newpic;

$TextBoxName="CuttingPicture";
$Description=$_POST['remark'][0];
$Particular=$Description;
$MasterValueID=10752;
 

$sql ="insert into InvoiceMaster_JobDetail (InvoiceID,MasterValueID,Description,TextBoxName,Particulars,PictureLocation) values(".$InvoiceID.",".$MasterValueID.",'".$Description."','".$TextBoxName."','".$Particular."','".$PictureLocation."')";

      odbc_exec($connection,$sql);
    }
  }
        if(isset($_FILES['Picture2']))
          {
$ppic=$_FILES['Picture2']['name'];
                if($ppic!="")
              {
      $newfile=rand()*1200;
      $ext=strrchr($ppic,".");
      $newpic=$newfile.$ext;
      save($_FILES['Picture2'],'',"images/");  
      rename("images/".$ppic,"images/".$newpic);
      $PictureLocation=$newpic;

$TextBoxName="CuttingPicture";
$Description=$_POST['remark'][1];
$Particular=$Description;
$MasterValueID=10753;
/* $sql="delete from InvoiceMaster_JobDetail where InvoiceID=".$InvoiceID." and TextBoxName='".$TextBoxName."'";
  odbc_exec($connection, $sql);
*/

$sql ="insert into InvoiceMaster_JobDetail (InvoiceID,MasterValueID,Description,TextBoxName,Particulars,PictureLocation) values(".$InvoiceID.",".$MasterValueID.",'".$Description."','".$TextBoxName."','".$Particular."','".$PictureLocation."')";

      odbc_exec($connection,$sql);
    }
  }
        if(isset($_FILES['Picture3']))
          {
 $ppic=$_FILES['Picture3']['name'];
                if($ppic!="")
              {
      $newfile=rand()*1200;
      $ext=strrchr($ppic,".");
      $newpic=$newfile.$ext;
      save($_FILES['Picture3'],'',"images/");  
      rename("images/".$ppic,"images/".$newpic);
      $PictureLocation=$newpic;

$TextBoxName="CuttingPicture";
$Description=$_POST['remark'][0];
$Particular=$Description;
$MasterValueID=10754;
 /*$sql="delete from InvoiceMaster_JobDetail where InvoiceID=".$InvoiceID." and TextBoxName='".$TextBoxName."'";
  odbc_exec($connection, $sql);
*/

$sql ="insert into InvoiceMaster_JobDetail (InvoiceID,MasterValueID,Description,TextBoxName,Particulars,PictureLocation) values(".$InvoiceID.",".$MasterValueID.",'".$Description."','".$TextBoxName."','".$Particular."','".$PictureLocation."')";

      odbc_exec($connection,$sql);
    }
    }   
//end code for image           
      //    StockOut($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
  /*            InsertJList($InvoiceID,$checklistdetail,'CheckList',$connection);
              InsertJList($InvoiceID,$warningdetail,'WarningList',$connection);
              InsertJList($InvoiceID,$inspectiondetail,'InspectionList',$connection);     
*/
          // Insert Voucher 

            
          $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
  if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
       }
       else
       {
        $res=array('status'=>"Error",'description'=>'Sorry You Dont have Permission to Enter JobCard');
       }
    echo json_encode($res);

  
  
  
  
  
 
}
    if($_GET['action']=="InsertJobCardDM")
    {
          odbc_autocommit($connection, FALSE);
      //$data=$_POST;
      $data=array_keys($_POST);
     // print_r($data[0]);
     // json_decode(json)
      $data1=json_decode($data[0]);
   //  print_r($data1);
     $SupplierID=33;
$InvoiceStatusID=1;
if(isset($data1->ID))
$InvoiceID=$data1->ID;
else
$InvoiceID=0;

     $MobileNumber=isset($data1->Phone)?$data1->Phone:0;
     $CustomerName=isset($data1->CustomerName)?$data1->CustomerName:0;
     $CustomerName=str_replace("_"," ",$CustomerName);

     $Email=isset($data1->Email)?$data1->Email:0;
     $Email=str_replace("_",".",$Email);
     $InvoiceDate=Date("Y-m-d");
    $DeliveryDate=(isset($data1->PromiseDate)?$data1->PromiseDate:$InvoiceDate);
  //   $dd=explode("-",$DeliveryDate);
    // $DeliveryDate=$dd[2]."-".$dd[1]."-".$dd[0];

    
     $DeliveryDate=$InvoiceDate;
     $PromiseDate=$DeliveryDate;
     $ChallanNo=0;
     $GRNno=0;
     $CustomerType=9;
     $PlateNumber=(isset($data1->PlateNumber) && $data1->PlateNumber!="")?$data1->PlateNumber:0;
     $ChassisNumber=(isset($data1->ChassisNumber) && $data1->ChassisNumber!="")?$data1->ChassisNumber:0;
     $MulkiyaNo=(isset($data1->MulkiyaNumber) && $data1->MulkiyaNumber!="")?$data1->MulkiyaNumber:0;
     $GodownID=(isset($data1->GodownID) && $data1->GodownID!="")?$data1->GodownID:0;//2
     $InvoiceType=5;
     $InvoiceStatus=1;
     $ReferenceInvoiceID=0;
     $BillNO=0;
/*     $ParkingNo=$data1->$ParkingNo;*/
     $KeyNo=(isset($data1->LicenseNo) && $data1->LicenseNo!="")?$data1->LicenseNo:0;
     $ParkingNo=(isset($data1->VehicleCapacity) && $data1->VehicleCapacity!="")?$data1->VehicleCapacity:0;
     $TotalAmount=210;
     $DiscountAmount=0;
     $TotalTaxAmount=0;
     $NetAmount=210;
     $Narration=(isset($data1->Remarks) && $data1->Remarks!="")?$data1->Remarks:0;
     $Narration=str_replace("_"," ", $Narration);
     $Notes=(isset($data1->Notes) && $data1->Notes!="")?$data1->Notes:0;
     $Notes=str_replace("_"," ", $Notes);
     $Active=1;
     $ShipperID=0;
     $BiltyNo=0;
     $VATLedgerID=0;
     $PurchaseLedgerID=0;
     $BranchID=$_SESSION['BRANCHID'];
     //PromiseDateinto invoicemaster
                 if($InvoiceID=="")$InvoiceID=0;

        $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 ITEMID=2 ,SupplierID=".$SupplierID.",MobileNumber='".$MobileNumber."',CustomerName='".$CustomerName."',Email='".$Email."',InvoiceDate='".$InvoiceDate."',DeliveryDate='".$DeliveryDate."',PlateNumber='".$PlateNumber."',ChassisNumber='".$ChassisNumber."',CustomerType=".$CustomerType.",Notes='".$Notes."',GodownID=".$GodownID.",InvoiceType=".$InvoiceType.",TotalAmount=".$TotalAmount.",DiscountAmount=".$DiscountAmount.",TotalTaxAmount=".$TotalTaxAmount.",NetAmount=".$NetAmount.",MulkiyaNo='".$MulkiyaNo."',ParkingNo='".$ParkingNo."',KeyNo='".$KeyNo."',EditLog='".$_SESSION['UserName']."',Narration='".$Narration."' 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)
            {
              //  and SupplierID='".$SupplierID."' 
      $where="InvoiceType=5 and  GodownID=".$GodownID." and itemid=2"; 
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            if($GodownID==1)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="MUN-".$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;
            }*/
            $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
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,CustomerType,Notes,MulkiyaNo,ParkingNo,KeyNo,ItemID,CreateLog,BranchID
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",".$ChallanNo
           .",'".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount
           .",".$DiscountAmount
           .",".$TotalTaxAmount           
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$ShipperID
           .",".$BiltyNo
           .",'".$PromiseDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$PurchaseLedgerID.",'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$CustomerType.",'".str_replace('_',' ',$Notes)."','".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."',2,'".$_SESSION['UserName']."',".$BranchID.")";
          }//end else for insert */

      odbc_exec($connection,$sql) or die(odbc_error().$sql);
     //insert in invoicedetails 
$sql="insert into invoiceDetail (InvoiceID,ItemID,UnitPrice,Qty,Amount,UnitID,NetAmount,TaxPercent,TaxAmount,Narration,VatPercent,VatAmount) values($InvoiceID,3543,210,1,210,1,210,0,0,'',0,0)";
      odbc_exec($connection,$sql) or die(odbc_error().$sql);
     //end insert invoicedetails

    //insert in invoice_jobdetails 
      $test=array();

      $test[0]=explode(":", $data1->TestCode1);
      //print_r($test[0]);
      $test[1]=explode(":", $data1->TestCode2);
      $test[2]=explode(":", $data1->TestCode3);
      $test[3]=explode(":", $data1->TestCode4);
      $test[4]=explode(":", $data1->TestCode5);
      $test[5]=explode(":", $data1->TestCode6);
      $test[6]=explode(":", $data1->TestCode7);
      $test[7]=explode(":", $data1->TestCode8);
      $test[8]=explode(":", $data1->TestCode9);

$sql="delete from InvoiceMaster_JobDetail where InvoiceID=".$InvoiceID;
      odbc_exec($connection,$sql) or die(odbc_error().$sql);

      for($a=0;$a<count($test);$a++) {
        # code...
        
        if(isset($test[$a][1]))$v=$test[$a][1];else $v=0;

        $v=str_replace("_",".",$v);
         $sql="insert into InvoiceMaster_JobDetail (
InvoiceID,
MasterValueID,
Description,
TextBoxName,
Active
) values(".$InvoiceID.",".$test[$a][0].",'".$v."','DM',1)";
  odbc_exec($connection,$sql) or die(odbc_error().$sql);

               }

      $ServiceLevel=array();
      $ServiceLevel[0]=explode(":",$data1->ServiceLevel1);
      $ServiceLevel[1]=explode(":",$data1->ServiceLevel2);
      $ServiceLevel[2]=explode(":",$data1->ServiceLevel3);
      $ServiceLevel[3]=explode(":",$data1->ServiceLevel4);
      $ServiceLevel[4]=explode(":",$data1->ServiceLevel5);
      $ServiceLevel[5]=explode(":",$data1->ServiceLevel6);
      $ServiceLevel[6]=explode(":",$data1->ServiceLevel7);

            for($a=0;$a<count($ServiceLevel);$a++) {
        # code...
        
        if(isset($ServiceLevel[$a][1]))$v=$ServiceLevel[$a][1];else $v=0;

        $v=str_replace("_"," ",$v);
         $sql="insert into InvoiceMaster_JobDetail (
InvoiceID,
MasterValueID,
Description,
TextBoxName,
Active
) values(".$InvoiceID.",".$ServiceLevel[$a][0].",'".$v."','DM',1)";
  odbc_exec($connection,$sql) or die(odbc_error().$sql);

               }
     //end insert invoice_jobdetails
//

  if (!odbc_error())
  {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
//$res=array('status'=>"ok",'description'=>'RTA Invoice Generated Sucessfully');
    echo json_encode($res);

     //end insert invoicemaster
    //  return;
    }

  if($_GET['action']=="GenerateSalesRTA")
  {
     odbc_autocommit($connection, FALSE);
$details=array_keys($_POST);
$d=json_decode(($details[0].$details[1]));
//print_r($d);
$InvoiceID=$_GET['InvoiceID'];

//remove previous generated invoice
$sqlupdate="update VoucherMaster set active=0,DeleteLog='".$_SESSION['UserName']."' where VoucherTypeID=8 and ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
              $sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);


    $sql="select * from InvoiceMaster where InvoiceID=".$InvoiceID;
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $NetAmount=$row['NetAmount'];
      $InvoiceDate=$row['InvoiceDate'];
      $Narration="";
      $ReferenceInvoiceID=$InvoiceID;
      $AmountDebit=0;
      $AmountCredit=0;
      $GodownID=$row['GodownID'];
      $TotalTaxAmount=$row['TotalTaxAmount'];
      $TotalAmount=$row['TotalAmount'];
      $InvoiceType=$row['InvoiceType'];
      $KeyField=$row['KeyField'];
      $SupplierID=$row['SupplierID'];


    }
              $fields=array();
            $VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$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($ReferenceInvoiceID)?$ReferenceInvoiceID:0;
           $fields['SupplierID']=0;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($SupplierID)?$SupplierID:0;
           $fields['AmountDebit']=isset($AmountDebit)?$AmountDebit:0;
           $fields['AmountCredit']=isset($AmountCredit)?$AmountCredit:0;
           $fields['IsAuto']=1;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['ReferenceVoucherID']=isset($ReferenceVoucherID)?$ReferenceVoucherID:0;
           $fields['GroupID']=isset($GroupID)?$GroupID:0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=0;//isset($Cash)?$Cash:0;
           $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['UserID']=isset($UserID)?$UserID:0;
           $fields['VoucherDateTime']=isset($VoucherDateTime)?$VoucherDateTime:date("Y-m-d m:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'';
         //  print_r($fields);
         
          InsertVoucherMaster2($fields,$InvoiceType,$InvoiceID,$connection); 
//return;
        $fdetails=array();  
        for($a=0;$a<2;$a++)
        {
           $fdetails['VoucherID']=$VoucherID;
           $fdetails['LedgerID']=$SupplierID;//$d->CustomerLedgerID; DEbit side entry
           if($a==0)
           {
            //VAT ENTRY
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
            $CreditLedgerID=$d->VATLedgerID;
           }
           if($a==1){
            //RTA Entry
            $sql="select sum(netamount) as RTA from InvoiceDetail where InvoiceID=$InvoiceID and TaxAmount<=0";
            $Amount=getnamewhere("InvoiceDetail","sum(netamount) as RTA"," InvoiceID=$InvoiceID and TaxAmount<=0",$connection);
            $Amount=json_decode($Amount);
            $Debit=$Amount->RTA;//
            $RTAAmount=$Debit;
            $Credit=$Debit;//
            $CreditLedgerID=$_SESSION['SETTING']['RTAHEAD'];//151;
            //  $d->VATLedgerID;    //RTA HEAD A/C        
           }
          else
          {
/*            $Debit=$TotalAmount;
            $Credit=$TotalAmount;
              $CreditLedgerID=$d->SalesLedgerID;*/
             // $sql="select sum(netamount) as RTA from InvoiceDetail where InvoiceID=$InvoiceID and TaxAmount<=0";
            $Amount=getnamewhere("InvoiceDetail","sum(netamount) as MVR"," InvoiceID=$InvoiceID and TaxAmount>0",$connection);
            $Amount=json_decode($Amount);
            $Debit=$Amount->MVR;//
            $Credit=$Debit;//
            $CreditLedgerID=$_SESSION['SETTING']['SALES'];//170;//
          }
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="JOB CARD";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="JOB CARD INVOICE"; 
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);              
        }//end for 
        // entry for Credit CARD for RTA Payment
        $CreditCardAccountID=$_SESSION['SETTING']['CREDITCARD'];//309;//
        $CreditLedgerID=$CreditCardAccountID;
           $fdetails['VoucherID']=$VoucherID;
           $fdetails['LedgerID']=$_SESSION['SETTING']['RTAHEAD'];//DEBIT RTA PAYABLE 151
          $Debit=$RTAAmount;
          $Credit=$RTAAmount;
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="JOB CARD RTA PAYMENT";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="JOB CARD INVOICE "; 
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);

        //end RTA PAYMENT  
        //update master invoice 
         $updateinvoice="update InvoiceMaster set AutoVoucherID=$VoucherID,InvoiceStatus=4,editLog='".$_SESSION['UserName']."' where InvoiceID=".$InvoiceID;
        odbc_exec($connection,$updateinvoice);
   if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
else
{
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

}
//$res=array('status'=>"ok",'description'=>'RTA Invoice Generated Sucessfully');
    echo json_encode($res);


  }


  if($_GET['action']=="jobcardRTAInsert")
  {
      odbc_autocommit($connection, FALSE);
    $isRTA=$_GET['isRTA'];
  $SideBarID=$_GET['SideBarID'];    
  $permission=userrights($Userid,$SideBarID,'[Delete]',$connection);
    if($permission==1)
    {
    $main=json_decode($_POST['data']);
    $details=$_POST['detail'];
    $checklistdetail=$_POST['checklistdetail'];
    $warningdetail=$_POST['warningdetail'];
    $inspectiondetail=$_POST['inspectiondetail'];

    $mrdetails=json_decode($details);
   
      $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;
          
            $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!="")?$main->ChassisNumber:'';
            $PlateNumber =(isset($main->PlateNumber) && $main->PlateNumber!="")?$main->PlateNumber:'';
            $TRNNo =(isset($main->TRNNo) && $main->TRNNo!="")?$main->TRNNo:'';
            $PreparedBy =(isset($main->PreparedBy) && $main->PreparedBy!="")?$main->PreparedBy:'';
            $CustomerType =(isset($main->CustomerType) && $main->CustomerType!="")?$main->CustomerType:'';
            $VehicleBrand =(isset($main->VehicleBrand) && $main->VehicleBrand!="")?$main->VehicleBrand:0;
            $ChallanNo =(isset($main->ChallanNo) && $main->ChallanNo!="")?$main->ChallanNo:0;
$VehicleModel =(isset($main->VehicleModel)&& $main->VehicleModel!="" )?$main->VehicleModel:0; 
$VehicleType =(isset($main->VehicleType)&& $main->VehicleType!="" )?$main->VehicleType:0; 
 $VehicleColor =(isset($main->VehicleColor)&& $main->VehicleColor!="" )?$main->VehicleColor:0;  
  $VehicleYear =(isset($main->VehicleYear) && $main->VehicleYear!="") ?$main->VehicleYear:0;  
            $FuelLevel =(isset($main->FuelLevel) && $main->FuelLevel>0)?$main->FuelLevel:0;  
            $MulkiyaNo =(isset($main->MulkiyaNo) && $main->MulkiyaNo!="") ?$main->MulkiyaNo:0;  
            $ParkingNo =(isset($main->ParkingNo) && $main->ParkingNo!="") ?$main->ParkingNo:0;  
            $KeyNo =(isset($main->KeyNo) && $main->KeyNo!="") ?$main->KeyNo:0;  
            $SalesManID =(isset($main->SalesManID) && $main->SalesManID>0 )?$main->SalesManID:0;  
      $SalesManID2 =(isset($main->SalesManID2) && $main->SalesManID2>0 )?$main->SalesManID2:0;  
           /* $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;
            $DeliveryDate=$DueDate;
            if($InvoiceID=="")$InvoiceID=0;
        $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 ITEMID=1 ,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='',EditLog='".$_SESSION['UserName']."' 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 ItemID=1 and  GodownID=".$GodownID; 
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            if($GodownID==1)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="RTA-".$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;
            }*/
            $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
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,ItemID,PictureLocation,CreateLog
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",".$ChallanNo
           .",'".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount
           .",".$DiscountAmount
           .",".$TotalTaxAmount           
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$ShipperID
           .",".$BiltyNo
           .",'".$DueDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$PurchaseLedgerID.",'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$SalesManID.",".$SalesManID2.",'".$TRNNo."',".$CustomerType.",".$VehicleBrand.",".$VehicleModel.",".$VehicleType.",".$VehicleColor.",".$VehicleYear.",'".$Notes."',".$FuelLevel.",'".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."',1,'".$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);     

          // Insert Voucher 

            
          $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
       }
       else
       {
        $res=array('status'=>"Error",'description'=>'Sorry You Dont have Permission to Enter JobCard');
       }
     if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
else
{
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

}
    echo json_encode($res);

  
  }
  if($_GET['action']=="GenerateJobCardSales2")
  {
    $data=array();
    $JobCardNo=$_GET['JobCardNo'];//ParkingNo like '$JobCardNo'
    $InvoiceID=$_GET['InvoiceID'];
    $sql="select InvoiceID,KeyField,InvoiceDate,GodownID,ReferenceInvoiceID from InvoiceMaster where InvoiceID=$InvoiceID";
$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      foreach($row as $key=>$value)
      {
        $row[$key]=utf8_encode($value);
      }
   //   $row['Value']=htmlspecialchars($row['Value']);
      $data []=$row;

    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);

  
  }
  if($_GET['action']=="GenerateJobCardSales")
  {
    $data=array();
    $JobCardNo=$_GET['JobCardNo'];//ParkingNo like '$JobCardNo'
    $InvoiceID=$_GET['InvoiceID'];
    $sql="select InvoiceID,KeyField,InvoiceDate,GodownID,ReferenceInvoiceID from InvoiceMaster where ReferenceInvoiceID=$InvoiceID";
$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      foreach($row as $key=>$value)
      {
        $row[$key]=utf8_encode($value);
      }
   //   $row['Value']=htmlspecialchars($row['Value']);
      $data []=$row;

    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);

  }
  if($_GET['action']=="DeleteJobSheet")
  {
  odbc_autocommit($connection, FALSE);    
        $JobDetailID=$_GET['JobDetailID'];
        $sql="update InvoiceMaster_JobDetail set Active=0 where JobDetailID=".$JobDetailID;
        odbc_exec($connection,$sql);

        $res=array('status'=>"ok",'description'=>'Record Deleted Sucessfully');
    echo json_encode($res);
     if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
  }//
  if($_GET['action']=="DeleteQuotation")
  {
  odbc_autocommit($connection, FALSE);    

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

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

       if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

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

  odbc_autocommit($connection, FALSE);    

        $InvoiceID=$_GET['InvoiceID'];
        // check for payment 
        $sqlcheck=" select * from VoucherMaster where VoucherTypeID in(7) and ReferenceInvoiceID=".$InvoiceID." and active=1";
        $resultcheck=odbc_exec($connection,$sqlcheck);

        //check for stock issue
        $sqlstock="select * from Salesinvoicemaster where ReferenceInvoiceID=".$InvoiceID." and active=1";
        $resultstock=odbc_exec($connection,$sqlstock);

        if(odbc_num_rows($resultcheck)>0)
        {
            $res=array('status'=>"error",'description'=>'Record not Deleted,JobCard Already Made Payment'); 

        }
        else if(odbc_num_rows($resultstock)>0)
        {
            $res=array('status'=>"error",'description'=>'Record not Deleted,JobCard Already Have Stock Issue'); 

        }
        else
        {
        $sql="update SalesInvoiceMaster set Active=0,DeleteLog='".$_SESSION['UserName']."' where InvoiceID=".$InvoiceID;
        odbc_exec($connection,$sql);

        /*$sql="update salesinvoiceDetail set IsDelete=1 where InvoiceID=".$InvoiceID;
        odbc_exec($connection,$sql);
    */
           $sqlupdate="update VoucherMaster set active=0,DeleteLog='".$_SESSION['UserName']."' where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
              $sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);

        $res=array('status'=>"ok",'description'=>'Record Deleted Sucessfully');
      }
      
     if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
    echo json_encode($res);


  
}
    if($_GET['action']=="DeleteJobCard")
  {
  odbc_autocommit($connection, FALSE);    

        $InvoiceID=$_GET['InvoiceID'];
        // check for payment 
        $sqlcheck=" select * from VoucherMaster where VoucherTypeID in(7) and ReferenceInvoiceID=".$InvoiceID." and active=1";
        $resultcheck=odbc_exec($connection,$sqlcheck);

        //check for stock issue
        $sqlstock="select * from invoicemaster where ReferenceInvoiceID=".$InvoiceID." and active=1";
        $resultstock=odbc_exec($connection,$sqlstock);

        if(odbc_num_rows($resultcheck)>0)
        {
            $res=array('status'=>"error",'description'=>'Record not Deleted,JobCard Already Made Payment'); 

        }
        else if(odbc_num_rows($resultstock)>0)
        {
            $res=array('status'=>"error",'description'=>'Record not Deleted,JobCard Already Have Stock Issue'); 

        }
        else
        {
        $sql="update InvoiceMaster set Active=0,DeleteLog='".$_SESSION['UserName']."' where InvoiceID=".$InvoiceID;
        odbc_exec($connection,$sql);

        $sql="update invoiceDetail set IsDelete=1 where InvoiceID=".$InvoiceID;
        odbc_exec($connection,$sql);
    
           $sqlupdate="update VoucherMaster set active=0,DeleteLog='".$_SESSION['UserName']."' where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
              $sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);

        $res=array('status'=>"ok",'description'=>'Record Deleted Sucessfully');
      }
      
     if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
    echo json_encode($res);


  }
  if($_GET['action']=="getJobSheet")
  {
    $data=array();
    if(isset($_GET['InvoiceID']))
    {
    $InvoiceID=$_GET['InvoiceID'];
    $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,TimeIn,[TimeOut],ijb.SalesManID,smi.SalesManName ,EmployeeWorkingMinutes,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue
    ,Description,Particulars,InvoiceID,(select GodownID from InvoiceMaster where InvoiceID=ijb.InvoiceID) as GodownID,ActivityStatus,(select KeyField from InvoiceMaster where InvoiceID=ijb.InvoiceID) as KeyField,(select InvoiceDate from InvoiceMaster where InvoiceID=ijb.InvoiceID) as InvoiceDate from [InvoiceMaster_JobDetail] as ijb 
  left outer join SalesManInformation as smi on ijb.SalesManID=smi.SalesManID
  where TextBoxName='Jobsheet' and InvoiceID=$InvoiceID";
  }
  else
  {
    if(isset($_GET['ItemName']) && $_GET['ItemName']!="")
    {
      $ItemName=" Particulars like '".$_GET['ItemName']."' and ";
    }
    else
    {
     $ItemName=""; 
    }
    if(isset($_GET['Description']) && $_GET['Description']!="")
    {
      $Description=" [Description] like '".$_GET['Description']."' and ";
    }
    else
    {
     $Description=""; 
    }
        if(isset($_GET['ActivityStatus']) && $_GET['ActivityStatus']!="")
    {
      $ActivityStatus=" [ActivityStatus] like '".$_GET['ActivityStatus']."' and ";
    }
    else
    {
     $ActivityStatus=""; 
    }
        if(isset($_GET['KeyField']) && $_GET['KeyField']!="")
    {
      $KeyField=" im.[KeyField] like '%".$_GET['KeyField']."%' and ";
    }
    else
    {
     $KeyField=""; 
    }
        if(isset($_GET['Employee']) && $_GET['Employee']!="")
    {
      $Employee=" [SalesManName] like '".$_GET['Employee']."' and ";
    }
    else
    {
     $Employee=""; 
    }

    $searchbox="".$ItemName."".$KeyField."".$Employee."".$ActivityStatus."".$Description."";

     $sql=" select ROW_NUMBER() OVER (
      PARTITION BY im.[InvoiceID]
      ORDER BY im.[InvoiceID]
   ) row_num,JobDetailID,MasterValueID,TimeIn,[TimeOut],ijb.SalesManID,smi.SalesManName ,EmployeeWorkingMinutes,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue
    ,Description,Particulars,ijb.InvoiceID as InvoiceID,GodownID,ActivityStatus,im.KeyField as KeyField,InvoiceDate from [InvoiceMaster_JobDetail] as ijb 
  left outer join SalesManInformation as smi on ijb.SalesManID=smi.SalesManID
  left outer join InvoiceMaster as im on ijb.InvoiceID=im.InvoiceID
  where $searchbox TextBoxName='Jobsheet' ";   
  }
 $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      foreach($row as $key=>$value)
      {
        $row[$key]=utf8_encode($value);
      }
   //   $row['Value']=htmlspecialchars($row['Value']);
      $data []=$row;

    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);

  }
  if($_GET['action']=="getSelectionID")
  {
    $data=array();
    $SelectionID=0;
    $ReferenceInvoiceID=$_GET['ReferenceInvoiceID'];
    $sql="select max(SelectionID) as SelectionID from VoucherMaster where VoucherTypeID=7  and ReferenceInvoiceID in(select InvoiceID from invoicemaster where ReferenceInvoiceID=$ReferenceInvoiceID)";
    $resultselection=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($resultselection))
    {
        $SelectionID=$row['SelectionID']+1;
    }
    echo json_encode($SelectionID);
  }
  if($_GET['action']=="getGroupJobCardPayment")
  {
    odbc_autocommit($connection, FALSE);    
    $data=($_POST['data']);
    $data=json_decode($data);
   // print_r($data);
  //  return;    
      $CashAmount=(isset($data->CashAmount) && $data->CashAmount>0)?$data->CashAmount:0;
      $CreditAmount=(isset($data->CreditAmount) && $data->CreditAmount>0)?$data->CreditAmount:0;
$ReferenceInvoiceID=(isset($data->ReferenceInvoiceID) && $data->ReferenceInvoiceID>0)?$data->ReferenceInvoiceID:0;
//get all jobard from group jobcard
$sql="select * from invoicemaster where ReferenceInvoiceID=$ReferenceInvoiceID";
$result1=odbc_exec($connection,$sql);
 while($row=odbc_fetch_array($result1))
    {
        $VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$connection)+1;
            
            $where="VoucherTypeID=7"; 
            $KeyField=generateCode("VoucherMaster","KeyField",$where,$connection)+1;
            $rep="JV-";
          //  $KeyField=generateCode2("VoucherMaster","KeyField",$where,$rep,$connection);
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="JV-".$KeyField2;
$CustomerID=$row['SupplierID'];//$_SESSION['SETTING']['CASHCUSTOMERS'];
$GodownID=$row['GodownID'];  
    $NetAmount=$row['NetAmount'];
    if($CashAmount>0)
    $CashAmountInvoice=$NetAmount;
    else
    $CashAmountInvoice=0;
      
    if($CreditAmount>0)
    $CreditAmountInvoice=$NetAmount;
    else 
    $CreditAmountInvoice=0;

    $InvoiceDate=$row['InvoiceDate'];
    $Narration="";
    $InvoiceID=$row['InvoiceID'];
    $PaidCheck=0;
    $sql="select NetAmount,Paid from InvoiceMaster where NetAmount<>paid and InvoiceID=$InvoiceID";
         $resultselection=odbc_exec($connection,$sql);
    while($row1=odbc_fetch_array($resultselection))
    {
        $NetAmountCheck=$row1['NetAmount'];
         $PaidCheck=$row1['Paid'];

    }
    if($PaidCheck<=0)
    {
   //  echo "<br> paid $PaidCheck  and check id  =".$InvoiceID; 
    //code for voucher 
 $fields=array();
              $VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$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']=7;//isset($VoucherTypeID)?$VoucherTypeID:0;
           $fields['PeriodID']=1;//isset($PeriodID)?$PeriodID:0;
           $fields['ReferenceInvoiceID']=isset($InvoiceID)?$InvoiceID:0;
           $fields['SupplierID']=$CustomerID;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($CustomerID)?$CustomerID:0;
           $fields['AmountDebit']=0;
           $fields['AmountCredit']=0;
           $fields['IsAuto']=0;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['ReferenceVoucherID']=isset($ReferenceInvoiceID)?$ReferenceInvoiceID:0;
           $fields['GroupID']=0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=$CashAmountInvoice;//isset($Cash)?$Cash:0;
           $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['SelectionID']=0;//$SelectionID;//isset($ContractID)?$ContractID:0;           
           $fields['UserID']=0;
           $fields['VoucherDateTime']=date("Y-m-d H:i:s");
           $fields['PaymentType']='';//isset($PaymentType)?$PaymentType:'';
           $fields['BranchID']=$_SESSION['BRANCHID'];
        //   print_r($fields);
                 $InvoiceType=5;//jobcard 

         $res=InsertVoucherMasterJobGroup($fields,$InvoiceType,$InvoiceID,$connection); 
         //print_r($res);
         // return;
         
          // update invoicemaster 
        /*  if($InvoiceID>0)
          {
          echo  $sql="update invoicemaster set Paid=(isNull(Paid,0)+$NetAmount),Balance=(NetAmount-(isNull(Paid,0)+$NetAmount)),TotalCurrencyAmount=$CashAmountInvoice,CreditCard=$CreditAmountInvoice,EditLog='".$_SESSION['UserName']."' where InvoiceID=".$InvoiceID;
          odbc_exec($connection,$sql) or die(odbc_error().$sql);
          }*/
        $fdetails=array();  
        for($a=0;$a<2;$a++)
        {
           $fdetails['VoucherID']=$VoucherID;
           if($a==0)
           {
            if($CashAmountInvoice>0)
            {
           $fdetails['LedgerID']=90;//$CashAccountID;
            $Debit=$CashAmountInvoice;
            $Credit=$CashAmountInvoice;
            $CreditLedgerID=$_SESSION['SETTING']['SALES'];//170;//$d->VATLedgerID; 
            $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="JOB CARD";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CustomerID;//$_SESSION['SETTING']['CASHCUSTOMERS'];//96;//Credit Ledger  
           $fdetails['CostCenterID']=$GodownID;
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;
           $fdetails['BranchID']=$_SESSION['BRANCHID'];

           if($fdetails['LedgerID']==90)//$_SESSION['SETTING']['CASHINHAND'])
           $fdetails['TransactionType']="JOB CARD INVOICE";
           else
           $fdetails['TransactionType']="SYMK";  
           //print_r($fdetails);
      InsertVoucherDetailGroup($fdetails,$InvoiceType,$VoucherID,$connection);    
            }
            else
            {
           //   continue;
            }
           }
          else
          {
            if($CreditAmountInvoice>0)
            {
           $fdetails['LedgerID']=98;//$CreditAccountID;            
            $Debit=$CreditAmountInvoice;
            $Credit=$CreditAmountInvoice;
            $CreditLedgerID=$_SESSION['SETTING']['CASHCUSTOMERS'];//96;//$d->SalesLedgerID;$_SESSION['SETTING']['CASHCUSTOMERS']
            $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="JOB CARD";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CustomerID;//$_SESSION['SETTING']['CASHCUSTOMERS'];//96;//Credit Ledger  
           $fdetails['CostCenterID']=$GodownID;
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;
           $fdetails['BranchID']=$_SESSION['BRANCHID'];

           if($fdetails['LedgerID']==90)//$_SESSION['SETTING']['CASHINHAND'])
           $fdetails['TransactionType']="JOB CARD INVOICE";
           else
           $fdetails['TransactionType']="SYMK";  
           //print_r($fdetails);
  InsertVoucherDetailGroup($fdetails,$InvoiceType,$VoucherID,$connection);    
            }
            else
            {
           //   continue;
            }
          }
                     
     }//end for 

     if($NetAmount>0)
    {
             $sql="update invoicemaster set LastModificationTimeStamp='".Date("Y-m-d H:i:s")."', Paid=$NetAmount,Balance=(NetAmount-(isNull(Paid,0)+$NetAmount)),TotalCurrencyAmount=$CashAmountInvoice,CreditCard=$CreditAmountInvoice,EditLog='".$_SESSION['UserName']."' where InvoiceID=".$InvoiceID;
     odbc_exec($connection,$sql) or die(odbc_error().$sql);
    }
    //end code for voucher 
  //  echo "<br>".$InvoiceID;
  }//end check
  }//end result
    if (!odbc_error())
   {
/*    */
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','VoucherID'=>$VoucherID);
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

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

odbc_autocommit($connection, FALSE);    
    $data=($_POST['data']);
    $data=json_decode($data);
    //print_r($data);
                $VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$connection)+1;
            
            $where="VoucherTypeID=7"; 
            $KeyField=generateCode("VoucherMaster","KeyField",$where,$connection)+1;
            $rep="JV-";
          //  $KeyField=generateCode2("VoucherMaster","KeyField",$where,$rep,$connection);
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="JV-".$KeyField2;
$CustomerID=(isset($data->CustomerID) && $data->CustomerID>0)?$data->CustomerID:$_SESSION['SETTING']['CASHCUSTOMERS'];
      $CashAmount=(isset($data->CashAmount) && $data->CashAmount>0)?$data->CashAmount:0;
      $CreditAmount=(isset($data->CreditAmount) && $data->CreditAmount>0)?$data->CreditAmount:0;
      $ChequeAmt=(isset($data->ChequeAmt) && $data->ChequeAmt>0)?$data->ChequeAmt:0;
    
  $SelectionID=(isset($data->SelectionID) && $data->SelectionID!="")?$data->SelectionID:0;      
    
      $NetAmount=$CashAmount+$CreditAmount;
      $InvoiceDate=(isset($data->InvoiceDate) && $data->InvoiceDate!="")?$data->InvoiceDate:Date("Y-m-d H:i:s");
      $ReferenceInvoiceID=(isset($data->InvoiceID) && $data->InvoiceID>0)?$data->InvoiceID:0;
      $GodownID=(isset($data->GodownID) && $data->GodownID>0)?$data->GodownID:0;  
      $CashAccountID=(isset($data->CashAccountID) && $data->CashAccountID>0)?$data->CashAccountID:0;// 
      $CreditAccountID=(isset($data->CreditAccountID) && $data->CreditAccountID>0)?$data->CreditAccountID:0;    
      $jKeyField=(isset($data->KeyField) && $data->KeyField>0)?$data->KeyField:0;    

  $TransactionNumber=(isset($data->TransactionNumber) && $data->TransactionNumber!="")?$data->TransactionNumber:0;//
      $Narration=" Payment Received Against ".$jKeyField;
      $PaymentType="TransactionNumber :".$TransactionNumber." Payment Received for Job Card ".$jKeyField;
      $InvoiceType=5;//jobcard 

      $PaidCheck=0;
    $sql="select NetAmount,Paid from InvoiceMaster where NetAmount<=Paid and InvoiceID=$ReferenceInvoiceID";
         $resultselection=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($resultselection))
    {
        $NetAmountCheck=$row['NetAmount'];
        $PaidCheck=$row['Paid'];

    }
    if($PaidCheck>0)
    {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Already Paid');
      echo json_encode($res);
      return; 
    }
     // InvoiceDate
                $sql="update invoicemaster set LastModificationTimeStamp='".Date("Y-m-d H:i:s")."',EditLog='".$_SESSION['UserName']."' where InvoiceID=".$ReferenceInvoiceID;

          odbc_exec($connection,$sql) or die(odbc_error().$sql);

      //check the invoice reference 
          $sql="update VoucherMaster set CreateLog='".$_SESSION['UserName']."' where ReferenceInvoiceID=$ReferenceInvoiceID";
     odbc_exec($connection,$sql) or die(odbc_error().$sql);
     
                  $fields=array();
              $VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$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']=7;//isset($VoucherTypeID)?$VoucherTypeID:0;
           $fields['PeriodID']=1;//isset($PeriodID)?$PeriodID:0;
           $fields['ReferenceInvoiceID']=isset($ReferenceInvoiceID)?$ReferenceInvoiceID:0;
           $fields['SupplierID']=0;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($CustomerID)?$CustomerID:0;
           $fields['AmountDebit']=0;
           $fields['AmountCredit']=0;
           $fields['IsAuto']=0;//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']=$CashAmount;//isset($Cash)?$Cash:0;
           $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['SelectionID']=$SelectionID;//isset($ContractID)?$ContractID:0;           
           $fields['UserID']=isset($UserID)?$UserID:0;
           $fields['VoucherDateTime']=date("Y-m-d H:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'';
           $fields['BranchID']=$_SESSION['BRANCHID'];
        //   print_r($fields);
          InsertVoucherMasterJob($fields,$InvoiceType,$ReferenceInvoiceID,$connection); 
          // update invoicemaster 
          if($ReferenceInvoiceID>0)
          {
            $sql="select * from invoicemaster where InvoiceID=".$ReferenceInvoiceID;
            $resultupdate=odbc_exec($connection,$sql);
            while($rowupdate=odbc_fetch_array($resultupdate))
            {
              $updatePaid=$rowupdate['Paid'];
              $updateCreditCard=$rowupdate['CreditCard'];
              $updateTotalCurrencyAmount=$rowupdate['TotalCurrencyAmount'];
              $updateCash=$rowupdate['Cash'];
           $sql="update invoicemaster set Paid=(isNull(Paid,0)+$NetAmount),Balance=(NetAmount-(isNull(Paid,0)+$NetAmount)),TotalCurrencyAmount=($updateTotalCurrencyAmount+$CashAmount),CreditCard=($updateCreditCard+$CreditAmount),Cash=($updateTotalCurrencyAmount+$CashAmount),EditLog='".$_SESSION['UserName']."' where InvoiceID=".$ReferenceInvoiceID;
          odbc_exec($connection,$sql) or die(odbc_error().$sql);
            }

          }
        $fdetails=array();  
        for($a=0;$a<3;$a++)
        {
           $fdetails['VoucherID']=$VoucherID;
           if($a==0)
           {
            if($CashAmount>0)
            {
           $fdetails['LedgerID']=$CashAccountID;
            $Debit=$CashAmount;
            $Credit=$CashAmount;
            $CreditLedgerID=$_SESSION['SETTING']['SALES'];//170;//$d->VATLedgerID; 
            }
            else
            {
              continue;
            }
           }
         else if($a==1)
          {
            if($CreditAmount>0)
            {
           $fdetails['LedgerID']=$CreditAccountID;            
            $Debit=$CreditAmount;
            $Credit=$CreditAmount;
            $CreditLedgerID=$_SESSION['SETTING']['CASHCUSTOMERS'];//96;//$d->SalesLedgerID;$_SESSION['SETTING']['CASHCUSTOMERS']
            }
            else
            {
              continue;
            }
          }
          else
          {
            if($ChequeAmt>0)
            {
           $fdetails['LedgerID']=83;//Cheque Head            
            $Debit=$ChequeAmt;
            $Credit=$ChequeAmt;
            $CreditLedgerID=$_SESSION['SETTING']['CASHCUSTOMERS'];//96;//$d->SalesLedgerID;$_SESSION['SETTING']['CASHCUSTOMERS']
            }
            else
            {
              continue;
            }
          }
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="JOB CARD";
           $fdetails['ReferenceInvoiceID']=$ReferenceInvoiceID;
           $fdetails['CreditLedgerID']=$CustomerID;//$_SESSION['SETTING']['CASHCUSTOMERS'];//96;//Credit Ledger  
           $fdetails['CostCenterID']=$GodownID;
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;
           $fdetails['BranchID']=$_SESSION['BRANCHID'];

           if($fdetails['LedgerID']==$_SESSION['SETTING']['CASHINHAND'])
           $fdetails['TransactionType']="JOB CARD INVOICE";
           else
           $fdetails['TransactionType']="SYMK";  
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);              
     }//end for 

     if($NetAmount>0)
    {
      $sql="update invoicemaster set Paid=(select sum(debit) from VoucherDetails where ReferenceInvoiceID=$ReferenceInvoiceID and LedgerID in(90,98,83)),Balance=(NetAmount-(isNull(Paid,0)+$NetAmount)),TotalCurrencyAmount=(select sum(debit) from VoucherDetails where ReferenceInvoiceID=$ReferenceInvoiceID and LedgerID in(90)),CreditCard=(select sum(debit) from VoucherDetails where ReferenceInvoiceID=$ReferenceInvoiceID and LedgerID in(98)),Cash=(select sum(debit) from VoucherDetails where ReferenceInvoiceID=$ReferenceInvoiceID and LedgerID in(90)),chequeamt=(select sum(debit) from VoucherDetails where ReferenceInvoiceID=$ReferenceInvoiceID and LedgerID in(83)),EditLog='".$_SESSION['UserName']."' where InvoiceID=".$ReferenceInvoiceID;
            /* $sql="update invoicemaster set LastModificationTimeStamp='".Date("Y-m-d H:i:s")."', Paid=$NetAmount,Balance=(NetAmount-(isNull(Paid,0)+$NetAmount)),TotalCurrencyAmount=$CashAmount,CreditCard=$CreditAmount,EditLog='".$_SESSION['UserName']."' where InvoiceID=".$ReferenceInvoiceID;*/
          odbc_exec($connection,$sql) or die(odbc_error().$sql);
    }

      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','KeyField'=>$KeyField,'VoucherID'=>$VoucherID);
      if (!odbc_error())
   {
/*    */
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','VoucherID'=>$VoucherID);
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
    echo json_encode($res);

  
  }
  if($_GET['action']=="GenerateAdvancePayment")
  {
odbc_autocommit($connection, FALSE);    
    $data=($_POST['data']);
    $data=json_decode($data);
    //print_r($data);
                $VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$connection)+1;
            
            $where="VoucherTypeID=7"; 
            $KeyField=generateCode("VoucherMaster","KeyField",$where,$connection)+1;
            $rep="JV-";
          //  $KeyField=generateCode2("VoucherMaster","KeyField",$where,$rep,$connection);
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="JV-".$KeyField2;
$CustomerID=(isset($data->CustomerID) && $data->CustomerID>0)?$data->CustomerID:$_SESSION['SETTING']['CASHCUSTOMERS'];
      $CashAmount=(isset($data->CashAmount) && $data->CashAmount>0)?$data->CashAmount:0;
      $CreditAmount=(isset($data->CreditAmount) && $data->CreditAmount>0)?$data->CreditAmount:0;
      $ChequeAmt=(isset($data->ChequeAmt) && $data->ChequeAmt>0)?$data->ChequeAmt:0;
    
  $SelectionID=(isset($data->SelectionID) && $data->SelectionID!="")?$data->SelectionID:0;      
    
      $NetAmount=$CashAmount+$CreditAmount;
      $InvoiceDate=(isset($data->InvoiceDate) && $data->InvoiceDate!="")?$data->InvoiceDate:Date("Y-m-d H:i:s");
      $ReferenceInvoiceID=(isset($data->InvoiceID) && $data->InvoiceID>0)?$data->InvoiceID:0;
      $GodownID=(isset($data->GodownID) && $data->GodownID>0)?$data->GodownID:0;  
      $CashAccountID=(isset($data->CashAccountID) && $data->CashAccountID>0)?$data->CashAccountID:0;// 
      $CreditAccountID=(isset($data->CreditAccountID) && $data->CreditAccountID>0)?$data->CreditAccountID:0;    
      $jKeyField=(isset($data->KeyField) && $data->KeyField>0)?$data->KeyField:0;    

  $TransactionNumber=(isset($data->TransactionNumber) && $data->TransactionNumber!="")?$data->TransactionNumber:0;//
      $Narration=" Payment Received Against ".$jKeyField;
      $PaymentType="TransactionNumber :".$TransactionNumber." Payment Received for Job Card ".$jKeyField;
      $InvoiceType=5;//jobcard 

      $PaidCheck=0;
    $sql="select NetAmount,Paid from InvoiceMaster where NetAmount<=Paid and InvoiceID=$ReferenceInvoiceID";
         $resultselection=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($resultselection))
    {
        $NetAmountCheck=$row['NetAmount'];
        $PaidCheck=$row['Paid'];

    }
    if($PaidCheck>0)
    {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Already Paid');
      echo json_encode($res);
      return; 
    }
     // InvoiceDate
                $sql="update invoicemaster set LastModificationTimeStamp='".Date("Y-m-d H:i:s")."',EditLog='".$_SESSION['UserName']."' where InvoiceID=".$ReferenceInvoiceID;

          odbc_exec($connection,$sql) or die(odbc_error().$sql);

      //check the invoice reference 
          $sql="update VoucherMaster set CreateLog='".$_SESSION['UserName']."' where ReferenceInvoiceID=$ReferenceInvoiceID";
     odbc_exec($connection,$sql) or die(odbc_error().$sql);
     
                  $fields=array();
              $VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$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']=7;//isset($VoucherTypeID)?$VoucherTypeID:0;
           $fields['PeriodID']=1;//isset($PeriodID)?$PeriodID:0;
           $fields['ReferenceInvoiceID']=isset($ReferenceInvoiceID)?$ReferenceInvoiceID:0;
           $fields['SupplierID']=0;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($CustomerID)?$CustomerID:0;
           $fields['AmountDebit']=0;
           $fields['AmountCredit']=0;
           $fields['IsAuto']=0;//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']=$CashAmount;//isset($Cash)?$Cash:0;
           $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['SelectionID']=$SelectionID;//isset($ContractID)?$ContractID:0;           
           $fields['UserID']=isset($UserID)?$UserID:0;
           $fields['VoucherDateTime']=date("Y-m-d H:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'';
           $fields['BranchID']=$_SESSION['BRANCHID'];
        //   print_r($fields);
          InsertVoucherMasterJob($fields,$InvoiceType,$ReferenceInvoiceID,$connection); 
          // update invoicemaster 
          if($ReferenceInvoiceID>0)
          {
            $sql="select * from invoicemaster where InvoiceID=".$ReferenceInvoiceID;
            $resultupdate=odbc_exec($connection,$sql);
            while($rowupdate=odbc_fetch_array($resultupdate))
            {
              $updatePaid=$rowupdate['Paid'];
              $updateCreditCard=$rowupdate['CreditCard'];
              $updateTotalCurrencyAmount=$rowupdate['TotalCurrencyAmount'];
              $updateCash=$rowupdate['Cash'];
           $sql="update invoicemaster set Paid=(isNull(Paid,0)+$NetAmount),Balance=(NetAmount-(isNull(Paid,0)+$NetAmount)),TotalCurrencyAmount=($updateTotalCurrencyAmount+$CashAmount),CreditCard=($updateCreditCard+$CreditAmount),Cash=($updateTotalCurrencyAmount+$CashAmount),EditLog='".$_SESSION['UserName']."' where InvoiceID=".$ReferenceInvoiceID;
          odbc_exec($connection,$sql) or die(odbc_error().$sql);
            }

          }
        $fdetails=array();  
        for($a=0;$a<3;$a++)
        {
           $fdetails['VoucherID']=$VoucherID;
           if($a==0)
           {
            if($CashAmount>0)
            {
           $fdetails['LedgerID']=$CashAccountID;
            $Debit=$CashAmount;
            $Credit=$CashAmount;
            $CreditLedgerID=$_SESSION['SETTING']['SALES'];//170;//$d->VATLedgerID; 
            }
            else
            {
              continue;
            }
           }
         else if($a==1)
          {
            if($CreditAmount>0)
            {
           $fdetails['LedgerID']=$CreditAccountID;            
            $Debit=$CreditAmount;
            $Credit=$CreditAmount;
            $CreditLedgerID=$_SESSION['SETTING']['CASHCUSTOMERS'];//96;//$d->SalesLedgerID;$_SESSION['SETTING']['CASHCUSTOMERS']
            }
            else
            {
              continue;
            }
          }
          else
          {
            if($ChequeAmt>0)
            {
           $fdetails['LedgerID']=83;//Cheque Head            
            $Debit=$ChequeAmt;
            $Credit=$ChequeAmt;
            $CreditLedgerID=$_SESSION['SETTING']['CASHCUSTOMERS'];//96;//$d->SalesLedgerID;$_SESSION['SETTING']['CASHCUSTOMERS']
            }
            else
            {
              continue;
            }
          }
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="JOB CARD";
           $fdetails['ReferenceInvoiceID']=$ReferenceInvoiceID;
           $fdetails['CreditLedgerID']=$CustomerID;//$_SESSION['SETTING']['CASHCUSTOMERS'];//96;//Credit Ledger  
           $fdetails['CostCenterID']=$GodownID;
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;
           $fdetails['BranchID']=$_SESSION['BRANCHID'];

           if($fdetails['LedgerID']==$_SESSION['SETTING']['CASHINHAND'])
           $fdetails['TransactionType']="JOB CARD INVOICE";
           else
           $fdetails['TransactionType']="SYMK";  
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);              
     }//end for 

     if($NetAmount>0)
    {
      $sql="update invoicemaster set Paid=(select sum(debit) from VoucherDetails where ReferenceInvoiceID=$ReferenceInvoiceID and LedgerID in(90,98,83)),Balance=(NetAmount-(isNull(Paid,0)+$NetAmount)),TotalCurrencyAmount=(select sum(debit) from VoucherDetails where ReferenceInvoiceID=$ReferenceInvoiceID and LedgerID in(90)),CreditCard=(select sum(debit) from VoucherDetails where ReferenceInvoiceID=$ReferenceInvoiceID and LedgerID in(98)),Cash=(select sum(debit) from VoucherDetails where ReferenceInvoiceID=$ReferenceInvoiceID and LedgerID in(90)),EditLog='".$_SESSION['UserName']."' where InvoiceID=".$ReferenceInvoiceID;
            /* $sql="update invoicemaster set LastModificationTimeStamp='".Date("Y-m-d H:i:s")."', Paid=$NetAmount,Balance=(NetAmount-(isNull(Paid,0)+$NetAmount)),TotalCurrencyAmount=$CashAmount,CreditCard=$CreditAmount,EditLog='".$_SESSION['UserName']."' where InvoiceID=".$ReferenceInvoiceID;*/
          odbc_exec($connection,$sql) or die(odbc_error().$sql);
    }

      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','KeyField'=>$KeyField,'VoucherID'=>$VoucherID);
      if (!odbc_error())
   {
/*    */
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','VoucherID'=>$VoucherID);
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
    echo json_encode($res);

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

odbc_autocommit($connection, FALSE);    
  $SideBarID=100;//$_GET['SideBarID'];    
  $permission=userrights($Userid,$SideBarID,'[Create]',$connection);
    if($permission==1)
    {
    $main=json_decode($_POST['data']);
    $details=$_POST['detail'];
    
    $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.",";  
          }
    }*/

      $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;
          
            $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:'';
            $VehicleBrand =isset($main->VehicleBrand)?$main->VehicleBrand:0;
            $ChallanNo =(isset($main->ChallanNo) && $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)?$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 )?$main->SalesManID:0;  
      $SalesManID2 =(isset($main->SalesManID2) && $main->SalesManID2>0 )?$main->SalesManID2:0;  
           /* $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;
            $DeliveryDate=$DueDate;
            if($InvoiceID=="")$InvoiceID=0;
        $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='',EditLog='".$_SESSION['UserName']."' 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==14)
            {
            $where="InvoiceType=14"; 
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="CTR-".Date("ym").$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
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,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
           .",".$TotalTaxAmount           
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$ShipperID
           .",".$BiltyNo
           .",'".$DueDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$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);
    //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);     
*/
          // Insert Voucher 

            
          $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
      if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
       }
       else
       {
        $res=array('status'=>"Error",'description'=>'Sorry You Dont have Permission to Enter JobCard');
       }
      
    echo json_encode($res);

  
  
  }//end contracts
  if($_GET['action']=="quotationInsert")
  {
odbc_autocommit($connection, FALSE);    
  $SideBarID=100;//$_GET['SideBarID'];    
  $permission=userrights($Userid,$SideBarID,'[Create]',$connection);
    if($permission==1)
    {
    $main=json_decode($_POST['data']);
    $details=$_POST['detail'];
    
    $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.",";  
          }
    }*/

      $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;
          
            $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:Date("Y-m-d");
            $InvoiceDate =isset($main->BillDate)?$main->BillDate:Date("Y-m-d");
            $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!="")?$main->Mobile:'';
            $Email =(isset($main->Email) && $main->Email!="")?$main->Email:'';
            $CustomerName =(isset($main->CustomerName) && $main->CustomerName!="")?$main->CustomerName:'';
            $ChassisNumber =(isset($main->ChassisNumber) && $main->ChassisNumber!="")?$main->ChassisNumber:'';
            $PlateNumber =(isset($main->PlateNumber) && $main->PlateNumber!="")?$main->PlateNumber:'';
            $TRNNo =(isset($main->TRNNo) && $main->TRNNo!="")?$main->TRNNo:'';
            $PreparedBy =(isset($main->PreparedBy) && $main->PreparedBy!="")?$main->PreparedBy:'';
            $CustomerType =(isset($main->CustomerType) && $main->CustomerType!="")?$main->CustomerType:0;
            $VehicleBrand =(isset($main->VehicleBrand) && $main->VehicleBrand!="")?$main->VehicleBrand:0;
  $ChallanNo =(isset($main->ChallanNo) && $main->ChallanNo!="")?$main->ChallanNo:0;
            $VehicleModel =(isset($main->VehicleModel) && $main->VehicleModel!="")?$main->VehicleModel:0; 
            $VehicleType =(isset($main->VehicleType) && $main->VehicleType!="")?$main->VehicleType:0; 
            $VehicleColor =(isset($main->VehicleColor) && $main->VehicleColor!="")?$main->VehicleColor:0;  
            $VehicleYear =(isset($main->VehicleYear) && $main->VehicleYear!="")?$main->VehicleYear:0;  
            $FuelLevel =(isset($main->FuelLevel) && $main->FuelLevel>0)?$main->FuelLevel:0;  
            $MulkiyaNo =isset($main->MulkiyaNo)?$main->MulkiyaNo:'0';  
            $ParkingNo =isset($main->ParkingNo)?$main->ParkingNo:0;  
            $KeyNo =isset($main->KeyNo)?$main->KeyNo:'';  
            $SalesManID =(isset($main->SalesManID) && $main->SalesManID>0 )?$main->SalesManID:0;  
      $SalesManID2 =(isset($main->SalesManID2) && $main->SalesManID2>0 )?$main->SalesManID2:0;  
           /* $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;
            $DeliveryDate=$DueDate;
            if($InvoiceID=="")$InvoiceID=0;
        $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='',EditLog='".$_SESSION['UserName']."' 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==12)
            {
            $where="InvoiceType=12"; 
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="QUA-".Date("ym").$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
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,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
           .",".$TotalTaxAmount           
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$ShipperID
           .",".$BiltyNo
           .",'".$DueDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$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);     
*/
          // Insert Voucher 

            
          $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
      if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
       }
       else
       {
        $res=array('status'=>"Error",'description'=>'Sorry You Dont have Permission to Enter JobCard');
       }
      
    echo json_encode($res);

  
  }//end quotation
  
  if($_GET['action']=="DeliveryNote")
  {

  odbc_autocommit($connection, FALSE);
  $SideBarID=$_GET['SideBarID'];    
  $permission=userrights($Userid,$SideBarID,'[Create]',$connection);
    if($permission==1)
    {
    $main=json_decode($_POST['data']);
    $details=$_POST['detail'];

/*    $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.",";  
          }
    }*/
$CurrentDepartmentID =isset($main->CurrentDepartmentID)?$main->CurrentDepartmentID: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;
          
            $Narration =isset($main->Narration)?$main->Narration:'';
            $Narration=htmlspecialchars($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;
            $ReferenceInvoiceID =isset($main->ReferenceInvoiceID)?$main->ReferenceInvoiceID: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:'';
            $CustomerName=str_replace('_',' ',$CustomerName);
            $Email=str_replace('_','.',$Email);
                 $ChassisNumber =(isset($main->ChassisNumber) && $main->ChassisNumber!="")?$main->ChassisNumber:'';
            $PlateNumber =(isset($main->PlateNumber) && $main->PlateNumber!="")?$main->PlateNumber:'';
            $TRNNo =(isset($main->TRNNo) && $main->TRNNo!="")?$main->TRNNo:'';
            $PreparedBy =(isset($main->PreparedBy) && $main->PreparedBy!="")?$main->PreparedBy:'';
            $CustomerType =(isset($main->CustomerType) && $main->CustomerType!="")?$main->CustomerType:'';
            $VehicleBrand =(isset($main->VehicleBrand) && $main->VehicleBrand!="")?$main->VehicleBrand:0;
            $ChallanNo =(isset($main->ChallanNo) && $main->ChallanNo!="")?$main->ChallanNo:0;
$VehicleModel =(isset($main->VehicleModel)&& $main->VehicleModel!="" )?$main->VehicleModel:0; 
$VehicleType =(isset($main->VehicleType)&& $main->VehicleType!="" )?$main->VehicleType:0; 
 $VehicleColor =(isset($main->VehicleColor)&& $main->VehicleColor!="" )?$main->VehicleColor:0;  
  $VehicleYear =(isset($main->VehicleYear) && $main->VehicleYear!="") ?$main->VehicleYear:0;  
            $FuelLevel =(isset($main->FuelLevel) && $main->FuelLevel>0)?$main->FuelLevel:0;  
            $MulkiyaNo =(isset($main->MulkiyaNo) && $main->MulkiyaNo!="") ?$main->MulkiyaNo:0;  
            $ParkingNo =(isset($main->ParkingNo) && $main->ParkingNo!="") ?$main->ParkingNo:0;  
            $KeyNo =(isset($main->KeyNo) && $main->KeyNo!="") ?$main->KeyNo:0;  
            $SalesManID =(isset($main->SalesManID) && $main->SalesManID>0 )?$main->SalesManID:0;  
      $SalesManID2 =(isset($main->SalesManID2) && $main->SalesManID2>0 )?$main->SalesManID2:0;
     /*   if($InvoiceID<1 && $GodownID==1 && ($ParkingNo!="" || $ParkingNo!="-" || $ParkingNo!="0"))
        {  
        $sql="select * from invoicemaster where InvoiceType=$InvoiceType and ParkingNo='".$ParkingNo."'";
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'TransactionNumber Already Exists');
echo json_encode($res);
              return;
            }
          }*/
           /* $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;
            $DeliveryDate=$DueDate;
            if($InvoiceID=="")$InvoiceID=0;
        $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='',EditLog='".$_SESSION['UserName']."',ShipperID=$ShipperID 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($GodownID==1)
            {
            $where="InvoiceType=$InvoiceType and branchID=".$_SESSION['BRANCHID']." and GodownID=".$GodownID;  
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            if($InvoiceType==55)
            { 
              $BranchID=getnamesingle("Godowns","KeyField","GodownID",$_SESSION['BRANCHID'],$connection);
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField=$BranchID."-".$KeyField2;
            }
            if($InvoiceType==56)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="CCL-".$KeyField2;
            }
            if($InvoiceType==57)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="RDL-".$KeyField2;
            }
            if($InvoiceType==58)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="PWS-".$KeyField2;
            }
            if($InvoiceType==59)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="DN-".$KeyField2;
            }
            if($GodownID==20)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="AYQ-".$KeyField2;
            }
            $ACNarration='AUTO VOUCHER for DOC: '.$KeyField.' from Jobcard';
            }
            // insert query for invoice master 
             $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,BranchID
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",".$ChallanNo
           .",'".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount
           .",".$DiscountAmount
           .",".$TotalTaxAmount           
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$CurrentDepartmentID
           .",".$BiltyNo
           .",'".$DueDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$PurchaseLedgerID.",'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$SalesManID.",".$SalesManID2.",'".$TRNNo."',".$CustomerType.",".$VehicleBrand.",".$VehicleModel.",".$VehicleType.",".$VehicleColor.",".$VehicleYear.",'".$Notes."',".$FuelLevel.",'".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."','".$PictureLocation."','".$_SESSION['UserName']."',".$_SESSION['BRANCHID'].")";
      /*     $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,BranchID
       ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $res=odbc_prepare($connection,$sql);
$UserName=$_SESSION['UserName'];
$BRANCHID=$_SESSION['BRANCHID'];
 $para=array($InvoiceID,$InvoiceDate,$Narration
           ,$InvoiceType,$Active,$SupplierID,$GodownID,$ChallanNo,$KeyField,
           $BillNO,$GRNno,$TotalAmount,$DiscountAmount,$TotalTaxAmount         
 ,$NetAmount,$ReferenceInvoiceID,$ShipperID,$BiltyNo,$DueDate,$InvoiceStatusID,$DeliveryDate,$InvoiceStatus,$VATLedgerID,$PurchaseLedgerID,$MobileNumber,$CustomerName,$Email,$PlateNumber,$ChassisNumber,$SalesManID,$SalesManID2,$TRNNo,$CustomerType,$VehicleBrand,$VehicleModel,$VehicleType,$VehicleColor,$VehicleYear,$Notes,$FuelLevel,$MulkiyaNo,$ParkingNo,$KeyNo,$PictureLocation,$UserName,$BRANCHID);
$r=odbc_execute($res,$para);*/
//return;
          }//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 stockeldger 

          //code for details 
          insertInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);
          StockOut($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
  /*            InsertJList($InvoiceID,$checklistdetail,'CheckList',$connection);
              InsertJList($InvoiceID,$warningdetail,'WarningList',$connection);
              InsertJList($InvoiceID,$inspectiondetail,'InspectionList',$connection);     
*/
          // Insert Voucher 

            
          $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
  if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
       }
       else
       {
        $res=array('status'=>"Error",'description'=>'Sorry You Dont have Permission to Enter JobCard');
       }
    echo json_encode($res);

  
  
  
  
  }
  if($_GET['action']=="joborderIron")
  {
    odbc_autocommit($connection, FALSE);
  $SideBarID=$_GET['SideBarID'];    
  $permission=userrights($Userid,$SideBarID,'[Create]',$connection);
    if($permission==1)
    {
    $main=json_decode($_POST['data']);
    $details=$_POST['detail'];

/*    $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.",";  
          }
    }*/
$CurrentDepartmentID =isset($main->CurrentDepartmentID)?$main->CurrentDepartmentID: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;
          
            $Narration =isset($main->Narration)?$main->Narration:'';
            $Narration=htmlspecialchars($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;
            $ReferenceInvoiceID =isset($main->ReferenceInvoiceID)?$main->ReferenceInvoiceID: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:'';
            $CustomerName=str_replace('_',' ',$CustomerName);
            $Email=str_replace('_','.',$Email);
                 $ChassisNumber =(isset($main->ChassisNumber) && $main->ChassisNumber!="")?$main->ChassisNumber:'';
            $PlateNumber =(isset($main->PlateNumber) && $main->PlateNumber!="")?$main->PlateNumber:'';
            $TRNNo =(isset($main->TRNNo) && $main->TRNNo!="")?$main->TRNNo:'';
            $PreparedBy =(isset($main->PreparedBy) && $main->PreparedBy!="")?$main->PreparedBy:'';
            $CustomerType =(isset($main->CustomerType) && $main->CustomerType!="")?$main->CustomerType:'';
            $VehicleBrand =(isset($main->VehicleBrand) && $main->VehicleBrand!="")?$main->VehicleBrand:0;
            $ChallanNo =(isset($main->ChallanNo) && $main->ChallanNo!="")?$main->ChallanNo:0;
$VehicleModel =(isset($main->VehicleModel)&& $main->VehicleModel!="" )?$main->VehicleModel:0; 
$VehicleType =(isset($main->VehicleType)&& $main->VehicleType!="" )?$main->VehicleType:0; 
 $VehicleColor =(isset($main->VehicleColor)&& $main->VehicleColor!="" )?$main->VehicleColor:0;  
  $VehicleYear =(isset($main->VehicleYear) && $main->VehicleYear!="") ?$main->VehicleYear:0;  
            $FuelLevel =(isset($main->FuelLevel) && $main->FuelLevel>0)?$main->FuelLevel:0;  
            $MulkiyaNo =(isset($main->MulkiyaNo) && $main->MulkiyaNo!="") ?$main->MulkiyaNo:0;  
            $ParkingNo =(isset($main->ParkingNo) && $main->ParkingNo!="") ?$main->ParkingNo:0;  
            $KeyNo =(isset($main->KeyNo) && $main->KeyNo!="") ?$main->KeyNo:0;  
            $SalesManID =(isset($main->SalesManID) && $main->SalesManID>0 )?$main->SalesManID:0;  
      $SalesManID2 =(isset($main->SalesManID2) && $main->SalesManID2>0 )?$main->SalesManID2:0;
     /*   if($InvoiceID<1 && $GodownID==1 && ($ParkingNo!="" || $ParkingNo!="-" || $ParkingNo!="0"))
        {  
        $sql="select * from invoicemaster where InvoiceType=$InvoiceType and ParkingNo='".$ParkingNo."'";
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'TransactionNumber Already Exists');
echo json_encode($res);
              return;
            }
          }*/
           /* $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;
            $DeliveryDate=$DueDate;
            if($InvoiceID=="")$InvoiceID=0;
        $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='',EditLog='".$_SESSION['UserName']."',ShipperID=$ShipperID 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($GodownID==1)
            {
            $where="InvoiceType=$InvoiceType and branchID=".$_SESSION['BRANCHID']." and GodownID=".$GodownID;  
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            if($InvoiceType==55)
            { 
              $BranchID=getnamesingle("Godowns","KeyField","GodownID",$GodownID,$connection);
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField=$BranchID."-".$KeyField2;
            }
            if($InvoiceType==56)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="PRO-".$KeyField2;
            }
            if($InvoiceType==57)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="QC-".$KeyField2;
            }
            if($InvoiceType==58)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="IRN-".$KeyField2;
            }
            if($InvoiceType==59)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="DN-".$KeyField2;
            }
            if($GodownID==20)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="AYQ-".$KeyField2;
            }
            $ACNarration='AUTO VOUCHER for DOC: '.$KeyField.' from Jobcard';
            }
            // insert query for invoice master 
             $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,BranchID
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",".$ChallanNo
           .",'".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount
           .",".$DiscountAmount
           .",".$TotalTaxAmount           
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$CurrentDepartmentID
           .",".$BiltyNo
           .",'".$DueDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$PurchaseLedgerID.",'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$SalesManID.",".$SalesManID2.",'".$TRNNo."',".$CustomerType.",".$VehicleBrand.",".$VehicleModel.",".$VehicleType.",".$VehicleColor.",".$VehicleYear.",'".$Notes."',".$FuelLevel.",'".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."','".$PictureLocation."','".$_SESSION['UserName']."',".$_SESSION['BRANCHID'].")";
      /*     $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,BranchID
       ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $res=odbc_prepare($connection,$sql);
$UserName=$_SESSION['UserName'];
$BRANCHID=$_SESSION['BRANCHID'];
 $para=array($InvoiceID,$InvoiceDate,$Narration
           ,$InvoiceType,$Active,$SupplierID,$GodownID,$ChallanNo,$KeyField,
           $BillNO,$GRNno,$TotalAmount,$DiscountAmount,$TotalTaxAmount         
 ,$NetAmount,$ReferenceInvoiceID,$ShipperID,$BiltyNo,$DueDate,$InvoiceStatusID,$DeliveryDate,$InvoiceStatus,$VATLedgerID,$PurchaseLedgerID,$MobileNumber,$CustomerName,$Email,$PlateNumber,$ChassisNumber,$SalesManID,$SalesManID2,$TRNNo,$CustomerType,$VehicleBrand,$VehicleModel,$VehicleType,$VehicleColor,$VehicleYear,$Notes,$FuelLevel,$MulkiyaNo,$ParkingNo,$KeyNo,$PictureLocation,$UserName,$BRANCHID);
$r=odbc_execute($res,$para);*/
//return;
          }//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 stockeldger 
 $sql="delete from stockledger where InvoiceTypeID=$InvoiceType and  InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sql);//remove Previous Stock
          //code for details 
          insertInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);
          insertStockTransfer($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
  /*            InsertJList($InvoiceID,$checklistdetail,'CheckList',$connection);
              InsertJList($InvoiceID,$warningdetail,'WarningList',$connection);
              InsertJList($InvoiceID,$inspectiondetail,'InspectionList',$connection);     
*/
          // Insert Voucher 

            
          $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
  if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
       }
       else
       {
        $res=array('status'=>"Error",'description'=>'Sorry You Dont have Permission to Enter JobCard');
       }
    echo json_encode($res);

  
  
  
  }//end Job Order Iron
  if($_GET['action']=="joborderQCInsert")
  {

  odbc_autocommit($connection, FALSE);
  $SideBarID=$_GET['SideBarID'];    
  $permission=userrights($Userid,$SideBarID,'[Create]',$connection);
    if($permission==1)
    {
    $main=json_decode($_POST['data']);
    $details=$_POST['detail'];

/*    $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.",";  
          }
    }*/
$CurrentDepartmentID =isset($main->CurrentDepartmentID)?$main->CurrentDepartmentID: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;
          
            $Narration =isset($main->Narration)?$main->Narration:'';
            $Narration=htmlspecialchars($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;
            $ReferenceInvoiceID =isset($main->ReferenceInvoiceID)?$main->ReferenceInvoiceID: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:'';
            $CustomerName=str_replace('_',' ',$CustomerName);
            $Email=str_replace('_','.',$Email);
                 $ChassisNumber =(isset($main->ChassisNumber) && $main->ChassisNumber!="")?$main->ChassisNumber:'';
            $PlateNumber =(isset($main->PlateNumber) && $main->PlateNumber!="")?$main->PlateNumber:'';
            $TRNNo =(isset($main->TRNNo) && $main->TRNNo!="")?$main->TRNNo:'';
            $PreparedBy =(isset($main->PreparedBy) && $main->PreparedBy!="")?$main->PreparedBy:'';
            $CustomerType =(isset($main->CustomerType) && $main->CustomerType!="")?$main->CustomerType:'';
            $VehicleBrand =(isset($main->VehicleBrand) && $main->VehicleBrand!="")?$main->VehicleBrand:0;
            $ChallanNo =(isset($main->ChallanNo) && $main->ChallanNo!="")?$main->ChallanNo:0;
$VehicleModel =(isset($main->VehicleModel)&& $main->VehicleModel!="" )?$main->VehicleModel:0; 
$VehicleType =(isset($main->VehicleType)&& $main->VehicleType!="" )?$main->VehicleType:0; 
 $VehicleColor =(isset($main->VehicleColor)&& $main->VehicleColor!="" )?$main->VehicleColor:0;  
  $VehicleYear =(isset($main->VehicleYear) && $main->VehicleYear!="") ?$main->VehicleYear:0;  
            $FuelLevel =(isset($main->FuelLevel) && $main->FuelLevel>0)?$main->FuelLevel:0;  
            $MulkiyaNo =(isset($main->MulkiyaNo) && $main->MulkiyaNo!="") ?$main->MulkiyaNo:0;  
            $ParkingNo =(isset($main->ParkingNo) && $main->ParkingNo!="") ?$main->ParkingNo:0;  
            $KeyNo =(isset($main->KeyNo) && $main->KeyNo!="") ?$main->KeyNo:0;  
            $SalesManID =(isset($main->SalesManID) && $main->SalesManID>0 )?$main->SalesManID:0;  
      $SalesManID2 =(isset($main->SalesManID2) && $main->SalesManID2>0 )?$main->SalesManID2:0;
     /*   if($InvoiceID<1 && $GodownID==1 && ($ParkingNo!="" || $ParkingNo!="-" || $ParkingNo!="0"))
        {  
        $sql="select * from invoicemaster where InvoiceType=$InvoiceType and ParkingNo='".$ParkingNo."'";
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'TransactionNumber Already Exists');
echo json_encode($res);
              return;
            }
          }*/
           /* $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;
            $DeliveryDate=$DueDate;
            if($InvoiceID=="")$InvoiceID=0;
        $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='',EditLog='".$_SESSION['UserName']."',ShipperID=$ShipperID 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($GodownID==1)
            {
            $where="InvoiceType=55 and branchID=".$_SESSION['BRANCHID']." and GodownID=".$GodownID;  
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            if($InvoiceType==55)
            { 
              $BranchID=getnamesingle("Godowns","KeyField","GodownID",$_SESSION['BRANCHID'],$connection);
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField=$BranchID."-".$KeyField2;
            }
            if($InvoiceType==56)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="STC-".$KeyField2;
            }
            if($InvoiceType==57)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="QC-".$KeyField2;
            }
            if($GodownID==58)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="IRN-".$KeyField2;
            }
            if($InvoiceType==59)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="DN-".$KeyField2;
            }
            if($GodownID==20)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="AYQ-".$KeyField2;
            }
            $ACNarration='AUTO VOUCHER for DOC: '.$KeyField.' from Jobcard';
            }
            // insert query for invoice master 
             $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,BranchID
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",".$ChallanNo
           .",'".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount
           .",".$DiscountAmount
           .",".$TotalTaxAmount           
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$CurrentDepartmentID
           .",".$BiltyNo
           .",'".$DueDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$PurchaseLedgerID.",'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$SalesManID.",".$SalesManID2.",'".$TRNNo."',".$CustomerType.",".$VehicleBrand.",".$VehicleModel.",".$VehicleType.",".$VehicleColor.",".$VehicleYear.",'".$Notes."',".$FuelLevel.",'".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."','".$PictureLocation."','".$_SESSION['UserName']."',".$_SESSION['BRANCHID'].")";
      /*     $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,BranchID
       ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $res=odbc_prepare($connection,$sql);
$UserName=$_SESSION['UserName'];
$BRANCHID=$_SESSION['BRANCHID'];
 $para=array($InvoiceID,$InvoiceDate,$Narration
           ,$InvoiceType,$Active,$SupplierID,$GodownID,$ChallanNo,$KeyField,
           $BillNO,$GRNno,$TotalAmount,$DiscountAmount,$TotalTaxAmount         
 ,$NetAmount,$ReferenceInvoiceID,$ShipperID,$BiltyNo,$DueDate,$InvoiceStatusID,$DeliveryDate,$InvoiceStatus,$VATLedgerID,$PurchaseLedgerID,$MobileNumber,$CustomerName,$Email,$PlateNumber,$ChassisNumber,$SalesManID,$SalesManID2,$TRNNo,$CustomerType,$VehicleBrand,$VehicleModel,$VehicleType,$VehicleColor,$VehicleYear,$Notes,$FuelLevel,$MulkiyaNo,$ParkingNo,$KeyNo,$PictureLocation,$UserName,$BRANCHID);
$r=odbc_execute($res,$para);*/
//return;
          }//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 stockeldger 
$sql="delete from stockledger where InvoiceTypeID=$InvoiceType and  InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sql);//remove Previous Stock
          //code for details 
          insertInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);
          insertStockQC($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
  /*            InsertJList($InvoiceID,$checklistdetail,'CheckList',$connection);
              InsertJList($InvoiceID,$warningdetail,'WarningList',$connection);
              InsertJList($InvoiceID,$inspectiondetail,'InspectionList',$connection);     
*/
          // Insert Voucher 

            
          $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
  if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
       }
       else
       {
        $res=array('status'=>"Error",'description'=>'Sorry You Dont have Permission to Enter JobCard');
       }
    echo json_encode($res);

  
  }//end Job Order QC
  if($_GET['action']=="joborderInsert")
  {

    odbc_autocommit($connection, FALSE);
  $SideBarID=$_GET['SideBarID'];    
  $permission=userrights($Userid,$SideBarID,'[Create]',$connection);
    if($permission==1)
    {
    $main=json_decode($_POST['data']);
    $details=$_POST['detail'];

/*    $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.",";  
          }
    }*/
$CurrentDepartmentID =isset($main->CurrentDepartmentID)?$main->CurrentDepartmentID: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;
          
            $Narration =isset($main->Narration)?$main->Narration:'';
            $Narration=htmlspecialchars($Narration);
            $InvoiceType =isset($main->InvoiceType)?$main->InvoiceType:5;
            $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;
            $ReferenceInvoiceID =isset($main->ReferenceInvoiceID)?$main->ReferenceInvoiceID: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:'';
            $CustomerName=str_replace('_',' ',$CustomerName);
            $Email=str_replace('_','.',$Email);
                 $ChassisNumber =(isset($main->ChassisNumber) && $main->ChassisNumber!="")?$main->ChassisNumber:'';
            $PlateNumber =(isset($main->PlateNumber) && $main->PlateNumber!="")?$main->PlateNumber:'';
            $TRNNo =(isset($main->TRNNo) && $main->TRNNo!="")?$main->TRNNo:'';
            $PreparedBy =(isset($main->PreparedBy) && $main->PreparedBy!="")?$main->PreparedBy:'';
            $CustomerType =(isset($main->CustomerType) && $main->CustomerType!="")?$main->CustomerType:1;
            $VehicleBrand =(isset($main->VehicleBrand) && $main->VehicleBrand!="")?$main->VehicleBrand:0;
            $ChallanNo =(isset($main->ChallanNo) && $main->ChallanNo!="")?$main->ChallanNo:0;
$VehicleModel =(isset($main->VehicleModel)&& $main->VehicleModel!="" )?$main->VehicleModel:0; 
$VehicleType =(isset($main->VehicleType)&& $main->VehicleType!="" )?$main->VehicleType:0; 
 $VehicleColor =(isset($main->VehicleColor)&& $main->VehicleColor!="" )?$main->VehicleColor:0;  
  $VehicleYear =(isset($main->VehicleYear) && $main->VehicleYear!="") ?$main->VehicleYear:0;  
            $FuelLevel =(isset($main->FuelLevel) && $main->FuelLevel>0)?$main->FuelLevel:0;  
            $MulkiyaNo =(isset($main->MulkiyaNo) && $main->MulkiyaNo!="") ?$main->MulkiyaNo:0;  
            $ParkingNo =(isset($main->ParkingNo) && $main->ParkingNo!="") ?$main->ParkingNo:0;  
            $KeyNo =(isset($main->KeyNo) && $main->KeyNo!="") ?$main->KeyNo:0;  
            $SalesManID =(isset($main->SalesManID) && $main->SalesManID>0 )?$main->SalesManID:0;  
      $SalesManID2 =(isset($main->SalesManID2) && $main->SalesManID2>0 )?$main->SalesManID2:0;
     /*   if($InvoiceID<1 && $GodownID==1 && ($ParkingNo!="" || $ParkingNo!="-" || $ParkingNo!="0"))
        {  
        $sql="select * from invoicemaster where InvoiceType=$InvoiceType and ParkingNo='".$ParkingNo."'";
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'TransactionNumber Already Exists');
echo json_encode($res);
              return;
            }
          }*/
           /* $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;
            $DeliveryDate=$DueDate;
            if($InvoiceID=="")$InvoiceID=0;
        $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='',EditLog='".$_SESSION['UserName']."',ShipperID=$ShipperID 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($GodownID==1)
            {
            $where="InvoiceType=$InvoiceType and GodownID=".$GodownID;  
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            if($InvoiceType==55)
            { 
              $BranchID=getnamesingle("Godowns","KeyField","GodownID",$CustomerType,$connection);
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="PRO-".$KeyField2;

           // $KeyField=$BranchID."-".$KeyField2;
            }
            if($InvoiceType==56)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="STC-".$KeyField2;
            }
            if($InvoiceType==57)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="QC-".$KeyField2;
            }
            if($InvoiceType==58)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="IRN-".$KeyField2;
            }
            if($InvoiceType==58)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="DN-".$KeyField2;
            }
            if($GodownID==20)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="AYQ-".$KeyField2;
            }
            $ACNarration='AUTO VOUCHER for DOC: '.$KeyField.' from Jobcard';
            }
            // insert query for invoice master 
             $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,BranchID
       ) values (".$InvoiceID.",'".
      $InvoiceDate."'
           ,'".$Narration."'
           ,".$InvoiceType
           .",".$Active
           .",".$SupplierID
           .",".$GodownID
           .",".$ChallanNo
           .",'".$KeyField."'
           ,'".$BillNO
           ."',".$GRNno
      .",".$TotalAmount
           .",".$DiscountAmount
           .",".$TotalTaxAmount           
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$CurrentDepartmentID
           .",".$BiltyNo
           .",'".$DueDate."'
           ,".$InvoiceStatusID
           .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$PurchaseLedgerID.",'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$SalesManID.",".$SalesManID2.",'".$TRNNo."',".$CustomerType.",".$VehicleBrand.",".$VehicleModel.",".$VehicleType.",".$VehicleColor.",".$VehicleYear.",'".$Notes."',".$FuelLevel.",'".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."','".$PictureLocation."','".$_SESSION['UserName']."',1)";
      /*     $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,BranchID
       ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $res=odbc_prepare($connection,$sql);
$UserName=$_SESSION['UserName'];
$BRANCHID=$_SESSION['BRANCHID'];
 $para=array($InvoiceID,$InvoiceDate,$Narration
           ,$InvoiceType,$Active,$SupplierID,$GodownID,$ChallanNo,$KeyField,
           $BillNO,$GRNno,$TotalAmount,$DiscountAmount,$TotalTaxAmount         
 ,$NetAmount,$ReferenceInvoiceID,$ShipperID,$BiltyNo,$DueDate,$InvoiceStatusID,$DeliveryDate,$InvoiceStatus,$VATLedgerID,$PurchaseLedgerID,$MobileNumber,$CustomerName,$Email,$PlateNumber,$ChassisNumber,$SalesManID,$SalesManID2,$TRNNo,$CustomerType,$VehicleBrand,$VehicleModel,$VehicleType,$VehicleColor,$VehicleYear,$Notes,$FuelLevel,$MulkiyaNo,$ParkingNo,$KeyNo,$PictureLocation,$UserName,$BRANCHID);
$r=odbc_execute($res,$para);*/
//return;
          }//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 stockeldger 
$sql="delete from stockledger where InvoiceTypeID=$InvoiceType and  InvoiceID=".$InvoiceID;
 odbc_exec($connection,$sql) or die(odbc_error().$sql);
          //code for details 
          insertInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);
          insertStock2($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
  /*            InsertJList($InvoiceID,$checklistdetail,'CheckList',$connection);
              InsertJList($InvoiceID,$warningdetail,'WarningList',$connection);
              InsertJList($InvoiceID,$inspectiondetail,'InspectionList',$connection);     
*/
          // Insert Voucher 

            
          $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
  if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
       }
       else
       {
        $res=array('status'=>"Error",'description'=>'Sorry You Dont have Permission to Enter JobCard');
       }
    echo json_encode($res);

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



 odbc_autocommit($connection, FALSE);
$details=array_keys($_POST);
//print_r($details);//.$details[1])
$d=json_decode($details[0]);
//print_r($d);
//return;
$InvoiceID=$_GET['InvoiceID'];

//remove previous generated invoice
$sqlupdate="update VoucherMaster set active=0,DeleteLog='".$_SESSION['UserName']."' where VoucherTypeID=8 and ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
              $sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);


    $sql="select * from InvoiceMaster where InvoiceID=".$InvoiceID;
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $NetAmount=$row['NetAmount'];//im
      $InvoiceDate=$row['InvoiceDate'];
      $Narration=$row['KeyNo']."Sales Return Entry";
      $ReferenceInvoiceID=$row['ReferenceInvoiceID'];//$InvoiceID;
      $AmountDebit=0;
      $AmountCredit=0;
      $GodownID=$row['GodownID'];
      $TotalTaxAmount=$row['TotalTaxAmount'];//im
      $TotalAmount=$row['TotalAmount'];//im
      $DiscountAmount=$row['DiscountAmount'];//im
      $InvoiceType=$row['InvoiceType'];
      $KeyField=$row['KeyField'];
      $SupplierID=$row['SupplierID'];//im
      $BranchID=$row['BranchID'];//im

    }
/*$sql="select * from InvoiceDetail where InvoiceID=".$InvoiceID;
    $result2=odbc_exec($connection,$sql);
    while($row2=odbc_fetch_array($result2))
    {
   //   $Amount=$row2['Amount'];

      $ItemID=$row2['ItemID'];
 $sqlupdate="update InvoiceDetail set CurrencyValue=Qty,CurrencyRate=(select convert(numeric(9,2),(sum(Amount)/sum(Qty))) from AverageCostPrice where ItemID=$ItemID) ,
 CurrencyAmount=(Qty*(select convert(numeric(9,2),(sum(Amount)/sum(Qty))) from AverageCostPrice where ItemID=$ItemID)) where InvoiceID=".$InvoiceID." and ItemID=".$ItemID;
odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);

    } */   
              $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']=0;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($SupplierID)?$SupplierID:0;
           $fields['AmountDebit']=isset($AmountDebit)?$AmountDebit:0;
           $fields['AmountCredit']=isset($AmountCredit)?$AmountCredit:0;
           $fields['IsAuto']=1;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['BranchID']=isset($BranchID)?$BranchID:0;
           $fields['ReferenceVoucherID']=isset($ReferenceVoucherID)?$ReferenceVoucherID:0;
           $fields['GroupID']=isset($GroupID)?$GroupID:0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=0;//isset($Cash)?$Cash:0;
           $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['UserID']=isset($UserID)?$UserID:0;
           $fields['VoucherDateTime']=isset($VoucherDateTime)?$VoucherDateTime:date("Y-m-d H:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'';
         //  print_r($fields);
          InsertVoucherMaster2($fields,$InvoiceType,$InvoiceID,$connection);  
$COGS=0;
$sql="select sum(StandardPrice3) as Total from InvoiceDetail where InvoiceID=".$InvoiceID;
    $result2=odbc_exec($connection,$sql);
    while($row2=odbc_fetch_array($result2))
    {
      $COGS=$row2['Total'];
    }
$LedgerID=$_SESSION['SETTING']['SALES'];//170;//
$InventoryLedgerID=$_SESSION['SETTING']['INVENTORY'];
$COGSID=$_SESSION['SETTING']['COGS'];

        $fdetails=array();  
        for($a=0;$a<3;$a++)
        {
           $fdetails['VoucherID']=$VoucherID;
           if($a==0)
           {
           $fdetails['LedgerID']=$d->VATLedgerID;//$d->CustomerLedgerID; DEbit side entry
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
            $CreditLedgerID=$SupplierID;
           }
           else if($a==1)
           {
            $fdetails['LedgerID']=$InventoryLedgerID;
            $CreditLedgerID=$COGSID;
           $Debit=$COGS;
            $Credit=$COGS; 
           }
           /*else if($a==2)
           {
            $fdetails['LedgerID']=$LedgerID;
            $CreditLedgerID=$SupplierID;
           $Debit=$TotalAmount;
            $Credit=$TotalAmount; 
           }*/
          else
          {
            $fdetails['LedgerID']=$d->SalesLedgerID;
            $Debit=($NetAmount-$TotalTaxAmount);
            $Credit=($NetAmount-$TotalTaxAmount);
            $CreditLedgerID=$SupplierID;
          }
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="JOB CARD";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="JOB CARD INVOICE"; 
           $fdetails['BranchID']=$BranchID;//company
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);              
        }//end for 

        //code for Sales Invoice Knock OFf
         $InvoiceTotal=getnamesingle("InvoiceMaster","NetAmount","InvoiceID",$ReferenceInvoiceID,$connection);
         $InvoiceTotalPaid=getnamesingle("InvoiceMaster","Paid","InvoiceID",$ReferenceInvoiceID,$connection);
         $InvoiceTotal=floatval($InvoiceTotal)-floatval($InvoiceTotalPaid);
   $sql="delete from VoucherDetails_InvoiceDetail where SettlementID=".$InvoiceID." and ReferenceInvoiceID=".$ReferenceInvoiceID;
    odbc_exec($connection,$sql);
$Balance=($InvoiceTotal-$NetAmount);
$VoucherDetailID=0;
          $sql="insert into  VoucherDetails_InvoiceDetail([VoucherID]
      ,[VoucherDetailID]
      ,[ReferenceInvoiceID]
      ,[InvoiceTotalAmount]
      ,[InvoicePaidAmount]
      ,[InvoiceBalance],SettlementID) 
      values($VoucherID
      ,$VoucherDetailID
      ,$ReferenceInvoiceID
      ,$InvoiceTotal
      ,$NetAmount
      ,$Balance,$InvoiceID)";
      odbc_exec($connection,$sql) or die(odbc_error().$sql);
        //end code for Sales Invoice Knock off
        //update master invoice 
         $updateinvoice="update InvoiceMaster set AutoVoucherID=$VoucherID,InvoiceStatus=4,editLog='".$_SESSION['UserName']."' where InvoiceID=".$InvoiceID;
        odbc_exec($connection,$updateinvoice);
        $ReferenceInvoiceID=getnamesingle("InvoiceMaster","ReferenceInvoiceID","InvoiceID",$InvoiceID,$connection);
        if($ReferenceInvoiceID>0)
        {
        $sql="update InvoiceMaster set InvoiceStatus=4,Paid=(isnull(paid,0)+$NetAmount) where InvoiceID=".$ReferenceInvoiceID;
odbc_exec($connection,$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');

  }
    echo json_encode($res);


  

  }
	if($_GET['action']=="jobcardInsert")
	{
    odbc_autocommit($connection, FALSE);
  $SideBarID=$_GET['SideBarID'];    
  $permission=userrights($Userid,$SideBarID,'[Create]',$connection);
    if($permission==1)
    {
		$main=json_decode($_POST['data']);
		$details=$_POST['detail'];
		$checklistdetail=$_POST['checklistdetail'];
		$warningdetail=$_POST['warningdetail'];
		$inspectiondetail=$_POST['inspectiondetail'];

		$mrdetails=json_decode($details);
		//$sql="update InvoiceMaster set ";
	

   // print_r($mrdetails);
  /*  print_r($main);
    return;*/
			$ShipperID =isset($main->ShipperID)?$main->ShipperID:0;
            $GodownID =isset($main->GodownID)?$main->GodownID:$_SESSION['CompanyID'];
            $SupplierID =isset($main->SupplierID)?$main->SupplierID:0;
            $ReferenceInvoiceID =isset($main->ReferenceInvoiceID)?$main->ReferenceInvoiceID:0;
            $SupplierName =isset($main->SupplierName)?$main->SupplierName:'';
            $Location =isset($main->Location)?$main->Location:0;
      		
            $Narration =isset($main->Narration)?$main->Narration:'';
            $Narration=htmlspecialchars($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:'';
            $CustomerName=str_replace('_',' ',$CustomerName);
            $Email=str_replace('_','.',$Email);
                 $ChassisNumber =(isset($main->ChassisNumber) && $main->ChassisNumber!="")?$main->ChassisNumber:'';
            $PlateNumber =(isset($main->PlateNumber) && $main->PlateNumber!="")?$main->PlateNumber:'';
            $TRNNo =(isset($main->TRNNo) && $main->TRNNo!="")?$main->TRNNo:'';
            $PreparedBy =(isset($main->PreparedBy) && $main->PreparedBy!="")?$main->PreparedBy:'';
            $CustomerType =(isset($main->CustomerType) && $main->CustomerType!="")?$main->CustomerType:0;
            $VehicleBrand =(isset($main->VehicleBrand) && $main->VehicleBrand!="")?$main->VehicleBrand:0;
            $ChallanNo =(isset($main->ChallanNo) && $main->ChallanNo!="")?$main->ChallanNo:0;
$VehicleModel =(isset($main->VehicleModel)&& $main->VehicleModel!="" )?$main->VehicleModel:0; 
$VehicleType =(isset($main->VehicleType)&& $main->VehicleType!="" )?$main->VehicleType:0; 
 $VehicleColor =(isset($main->VehicleColor)&& $main->VehicleColor!="" )?$main->VehicleColor:0;  
  $VehicleYear =(isset($main->VehicleYear) && $main->VehicleYear!="") ?$main->VehicleYear:0;  
            $FuelLevel =(isset($main->FuelLevel) && $main->FuelLevel>0)?$main->FuelLevel:0;  
            $MulkiyaNo =(isset($main->MulkiyaNo) && $main->MulkiyaNo!="") ?$main->MulkiyaNo:0;  
            $ParkingNo =(isset($main->ParkingNo) && $main->ParkingNo!="") ?$main->ParkingNo:0;  
            $KeyNo =(isset($main->KeyNo) && $main->KeyNo!="") ?$main->KeyNo:0;  
            $SalesManID =(isset($main->SalesManID) && $main->SalesManID>0 )?$main->SalesManID:0;  
      $SalesManID2 =(isset($main->SalesManID2) && $main->SalesManID2>0 )?$main->SalesManID2:0;
        if($InvoiceID<1 && $GodownID==1 && ($ParkingNo!="" || $ParkingNo!="-" || $ParkingNo!="0"))
        {  
        /*$sql="select * from invoicemaster where ParkingNo='".$ParkingNo."'";
            $result=odbc_exec($connection, $sql);
            if(odbc_num_rows($result)>0)
            {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'SALES ORDER Already Exists');
echo json_encode($res);
              return;
            }*/
          }
           /* $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;
            $DeliveryDate=$DueDate;
            if($InvoiceID=="")$InvoiceID=0;
		    $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='',EditLog='".$_SESSION['UserName']."',ShipperID=$ShipperID,InvoiceStatus=1 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 branchID=".$_SESSION['BRANCHID']." and GodownID=".$GodownID;	
           	$KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
           	//getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
           	if($GodownID==1)
           	{	
              $BranchID=getnamesingle("Godowns","KeyField","GodownID",$_SESSION['BRANCHID'],$connection);
           	$KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
           	$KeyField=$BranchID."-".$KeyField2;
           	}
           	if($GodownID==2)
           	{	
           	$KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
           	$KeyField="CCL-".$KeyField2;
           	}
           	if($GodownID==3)
           	{	
           	$KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
           	$KeyField="RDL-".$KeyField2;
           	}
           	if($GodownID==4)
           	{	
           	$KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
           	$KeyField="PWS-".$KeyField2;
           	}
            if($GodownID==19)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="FOTC-".$KeyField2;
            }
            if($GodownID==20)
            { 
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="AYQ-".$KeyField2;
            }
           	$ACNarration='AUTO VOUCHER for DOC: '.$KeyField.' from Jobcard';
           	}
            else if ($InvoiceType==61)
            {
              $where="InvoiceType=61";  
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            $ACNarration='AUTO VOUCHER for DOC: '.$KeyField.' from Sales Return ';
            $KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
            $KeyField="SRI-".$KeyField2;
            }
            // insert query for invoice master 
             $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
			,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
       	   ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,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
           .",".$TotalTaxAmount           
           .",".$NetAmount
           .",".$ReferenceInvoiceID
           .",".$ShipperID
           .",".$BiltyNo
           .",'".$DueDate."'
           ,".$InvoiceStatusID
       	   .",'".$DeliveryDate."'
           ,".$InvoiceStatus."
           ,".$VATLedgerID."
           ,".$PurchaseLedgerID.",'".$MobileNumber."','".$CustomerName."','".$Email."','".$PlateNumber."','".$ChassisNumber."',".$SalesManID.",".$SalesManID2.",'".$TRNNo."',".$CustomerType.",".$VehicleBrand.",".$VehicleModel.",".$VehicleType.",".$VehicleColor.",".$VehicleYear.",'".$Notes."',".$FuelLevel.",'".$MulkiyaNo."','".$ParkingNo."','".$KeyNo."','".$PictureLocation."','".$_SESSION['UserName']."')";
      /*     $sql="insert into invoicemaster ([InvoiceID]
           ,InvoiceDate
           ,Narration
           ,InvoiceType
           ,Active
           ,SupplierID
           ,GodownID
           ,ChallanNo
           ,KeyField
           ,BillNO
           ,GRNno
      ,TotalAmount
           ,DiscountAmount
           ,TotalTaxAmount
           ,NetAmount
           ,ReferenceInvoiceID
           ,ShipperID
           ,BiltyNo
           ,DueDate
           ,InvoiceStatusID
           ,DeliveryDate
           ,InvoiceStatus
           ,VATLedgerID
           ,PurchaseLedgerID,
           MobileNumber,CustomerName,Email,PlateNumber,ChassisNumber,SalesManID,SalesManID2,TRNNo,CustomerType,VehicleBrand,VehicleModel,VehicleType,VehicleColor,VehicleYear,Notes,FuelLevel,MulkiyaNo,ParkingNo,KeyNo,PictureLocation,CreateLog,BranchID
       ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $res=odbc_prepare($connection,$sql);
$UserName=$_SESSION['UserName'];
$BRANCHID=$_SESSION['BRANCHID'];
 $para=array($InvoiceID,$InvoiceDate,$Narration
           ,$InvoiceType,$Active,$SupplierID,$GodownID,$ChallanNo,$KeyField,
           $BillNO,$GRNno,$TotalAmount,$DiscountAmount,$TotalTaxAmount         
 ,$NetAmount,$ReferenceInvoiceID,$ShipperID,$BiltyNo,$DueDate,$InvoiceStatusID,$DeliveryDate,$InvoiceStatus,$VATLedgerID,$PurchaseLedgerID,$MobileNumber,$CustomerName,$Email,$PlateNumber,$ChassisNumber,$SalesManID,$SalesManID2,$TRNNo,$CustomerType,$VehicleBrand,$VehicleModel,$VehicleType,$VehicleColor,$VehicleYear,$Notes,$FuelLevel,$MulkiyaNo,$ParkingNo,$KeyNo,$PictureLocation,$UserName,$BRANCHID);
$r=odbc_execute($res,$para);*/
//return;
       		}//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 
        
      // return;
    /*  if(getDataType2($connection,"invoicemaster",$key)==1)
          {

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

       		insertInvoiceDetail($InvoiceID,$mrdetails,$InvoiceType,$connection);
          $main->ParkingNo=$KeyField;
          $main->GodownID=$_SESSION['CompanyID'];
           StockINOnly($InvoiceID,$main,$mrdetails,$InvoiceType,$connection);
 /*      				InsertJList($InvoiceID,$checklistdetail,'CheckList',$connection);
       				InsertJList($InvoiceID,$warningdetail,'WarningList',$connection);
       				InsertJList($InvoiceID,$inspectiondetail,'InspectionList',$connection);     */
if($InvoiceType==61)
{
       		// Insert Voucher 
  $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="SRV-".$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']=20;//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']=$_SESSION['CompanyID'];
           $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']=$NetAmount;//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=$NetAmount;
    $CashPaid=0;//$NetAmount
    $CashAccountID=22;//$main->CashAccountID;
    $CCAcountID=21;//$main->CCAcountID;
    $CustomerID=20;//$main->CustomerID;
    $SalesAccountID=6;//$main->SalesAccountID;
    $VATAccountID=27;//$main->VATAccountID;
    $VoucherTypeID=8;//$main->VoucherTypeID;
/*
CASH CR 
CREDIT CARD CR  
VAT DR 
SALES DR 
*/
$TotalCurrencyAmount=$NetAmount;
$CreditCard=0;
        $fdetails=array();  
        for($a=0;$a<4;$a++)
        {
           $fdetails['VoucherID']=$VoucherID;

           if($a==0)
           {
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
            $LedgerID=$VATAccountID;
            $CreditLedgerID=$CustomerID;
           }
           if($a==1)
           {
            $Debit=($NetAmount-$TotalTaxAmount);
            $Credit=($NetAmount-$TotalTaxAmount);
            $LedgerID=$SalesAccountID;
            $CreditLedgerID=$CustomerID;
           }
            if($a==2)
           {
            $Debit=$TotalCurrencyAmount;
            $Credit=$TotalCurrencyAmount;
            $LedgerID=$CustomerID;
            $CreditLedgerID=$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 */
      }//sales return Voucher 
       			//end voucher 
       		$res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
	if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully','InvoiceID'=>$InvoiceID);
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
       }
       else
       {
        $res=array('status'=>"Error",'description'=>'Sorry You Dont have Permission to Enter JobCard');
       }
  	echo json_encode($res);

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

    if(isset($_GET['Under']))
    $Under="Under=".$_GET['Under']." and";
    else
    $Under="";
    /*if(isset($_GET['CompanyID']))
    $CompanyID="CompanyID=".$_GET['CompanyID']." and";
    else
    $CompanyID="";*/
    //$Size=$_GET['Size'];
    $ProductBaseType=$_GET['BaseType'];
    $condition=$_GET['condition'];
    if(isset($_GET['term']))
    {
      $term=" and name like '%".$_GET['term']."%'";
    }
    else
    {
      $term="";
    }
    $where=$Under.""." ProductBaseType='".$ProductBaseType."' and ".$condition;
    $table=$_GET['TextBoxName'];
    $fieldname=$_GET['fieldname'];
    $fieldid=$_GET['fieldid'];
    echo getSelect2List2($table,$fieldid,$fieldname,$where,$connection);
  
  }
	if($_GET['action']=="getSubcategory")
	{
		if(isset($_GET['under']))
		$Under="Under=".$_GET['under']." and ";
		else if(isset($_GET['Under']))
    $Under="Under in (".$_GET['Under'].") and ";
    else
    $Under=" Under=0 and ";  
		/*if(isset($_GET['CompanyID']))
		$CompanyID="CompanyID=".$_GET['CompanyID']." and";
		else
		$CompanyID="";*/
		$Size=$_GET['Size'];
		$ProductBaseType=$_GET['BaseType'];
    if(isset($_GET['term']))
    {
      $term=" and name like '%".$_GET['term']."%'";
    }
    else
    {
      $term="";
    }
		 $where=$Under." active=1 and ProductBaseType='".$ProductBaseType."' and [group]=1 and ID not in (3200)".$term;
		$table=$_GET['TextBoxName'];
		$fieldname=$_GET['fieldname'];
		$fieldid=$_GET['fieldid'];
		echo getSelect2List2($table,$fieldid,$fieldname,$where,$connection);
	}
  if($_GET['action']=="getSubcategory2")
  {
    if(isset($_GET['Under']))
    $Under=" Under in (select id from inventory where under=".$_GET['Under'].") and ";
    else
    $Under="";
    /*if(isset($_GET['CompanyID']))
    $CompanyID="CompanyID=".$_GET['CompanyID']." and";
    else
    $CompanyID="";*/
    $Size=$_GET['Size'];
    $ProductBaseType=$_GET['BaseType'];
    if(isset($_GET['term']))
    {
      $term=" and name like '%".$_GET['term']."%'";
    }
    else
    {
      $term="";
    }
    $where=$Under.""." ProductBaseType='".$ProductBaseType."' ".$term;
    $table=$_GET['TextBoxName'];
    $fieldname=$_GET['fieldname'];
    $fieldid=$_GET['fieldid'];
    //echo $sql="select $fieldid,$fieldname from $table where $where ";

    echo getSelect2List2($table,$fieldid,$fieldname,$where,$connection);
  }
  if($_GET['action']=="getServices")
  {

$data=array();
    if(isset($_GET['ShipperID']) && trim($_GET['ShipperID'])!="")
    {
    $ItemShipperID=$_GET['ShipperID'];
    $ShipperID="departid=".$ItemShipperID."";
    }
    else
    {
    $ShipperID="";
    }

    if(isset($_GET['Under']))
    $Under="(Under=".$_GET['Under']." or Under in(select ID from inventory where Under=".$_GET['Under'].")) and ";
    else
    $Under="";
   if(isset($_GET['ShowInSales']) && $_GET['ShowInSales']==true)
    $ShowInSales="ShowInSales=1 and ";//.$_GET['ShowInSales']." and ";
    else
    $ShowInSales="";
    /*if(isset($_GET['CompanyID']))
    $CompanyID="CompanyID=".$_GET['CompanyID']." and";
    else
    $CompanyID="";*/
      //mb_internal_encoding('UTF-8'); 

    $Size=$_GET['Size'];
    $ProductBaseType=$_GET['BaseType'];
    $where=$Under."".$ShowInSales." ProductBaseType='".$ProductBaseType."'  and [group]=0 and active=1";
  /*  mysql_query("SET NAMES 'utf8'");
mysql_query('SET CHARACTER SET utf8');
*/
    $table=$_GET['TextBoxName'];
    $fieldname=$_GET['fieldname'];
    $fieldid=$_GET['fieldid'];
      $sql="select $fieldid,$fieldname from $table where $where ";
    $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      $row['Value']=htmlspecialchars($row['Value']);
  //echo utf8_encode($row['arabic']); // واللغة العربية php مشروع
//echo $value = iconv("UTF-8", "Windows-1252",$row['arabic']);
//echo "2".iconv("ISO-8859-1", "UTF-8", $row['arabic']);
//echo  "3".mb_internal_encoding($row['arabic']);
//$row['arabic']=iconv('cp1256', 'utf-8',$row['arabic']);
      $data []=$row;

    }
   // print_r($data);
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);

    //echo getSelect2List2($table,$fieldid,$fieldname,$where,$connection);
  
  
  }
  if($_GET['action']=="getStockProducts")
  {
$data=array();
    if(isset($_GET['ShipperID']) && trim($_GET['ShipperID'])!="")
    {
    $ItemShipperID=$_GET['ShipperID'];
    $ShipperID="departid=".$ItemShipperID."";
    }
    else
    {
    $ShipperID="";
    }

    if(isset($_GET['Under']))
    $Under="(Under=".$_GET['Under']." or Under in(select ID from inventory where Under=".$_GET['Under'].")) and ";
    else
    $Under="";
    /*if(isset($_GET['CompanyID']))
    $CompanyID="CompanyID=".$_GET['CompanyID']." and";
    else
    $CompanyID="";*/
    $Size=$_GET['Size'];
    $ProductBaseType=$_GET['BaseType'];
    $where=$Under.""." ProductBaseType='".$ProductBaseType."' and [group]=0";
    $table=$_GET['TextBoxName'];
    $fieldname=$_GET['fieldname'];
    $fieldid=$_GET['fieldid'];
    $sql="select $fieldid,$fieldname from $table where $where 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)";
    $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      $row['Value']=htmlspecialchars($row['Value']);
      $data []=$row;

    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);

    //echo getSelect2List2($table,$fieldid,$fieldname,$where,$connection);
  
  }
  if($_GET['action']=="getProducts")
  {
    if(isset($_GET['Under']))
    $Under="(Under=".$_GET['Under']." or Under in(select ID from inventory where Under=".$_GET['Under'].")) and ";
    else
    $Under="";
    /*if(isset($_GET['CompanyID']))
    $CompanyID="CompanyID=".$_GET['CompanyID']." and";
    else
    $CompanyID="";*/
    $Size=$_GET['Size'];
    $ProductBaseType=$_GET['BaseType'];
    $where=$Under.""." ProductBaseType='".$ProductBaseType."' and [group]=0";
    $table=$_GET['TextBoxName'];
    $fieldname=$_GET['fieldname'];
    $fieldid=$_GET['fieldid'];
      $sql="select $fieldid,$fieldname from $table where $where";
    $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      $row['Value']=htmlspecialchars($row['Value']);
      $data []=$row;

    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);

    //echo getSelect2List2($table,$fieldid,$fieldname,$where,$connection);
  }
  if($_GET['action']=="getItemRaw")
  {

    //    //$ItemName="Under=".$_GET['ItemName']." and ";
    /*if(isset($_GET['ItemName']))
    $ItemName=" Name like '%".$_GET['ItemName']."%' and "; 
    else*/
    $ItemName="";
    /*if(isset($_GET['Under']) && $ItemName=="")
    $Under="(Under=".$_GET['Under']." or under in (select id from inventory where under=".$_GET['Under'].")) and ";
    else*/
    $Under="";
    if(isset($_GET['IName']))
    $IName="Name like '%".$_GET['IName']."%' and ";
    else
    $IName="";


  $CompanyID="";
/*    if(isset($_GET['CompanyID']) && $_GET['CompanyID']>0)
    $CompanyID="CompanyID=".$_GET['CompanyID']." and ";
    else
    $CompanyID="";*/
    $Size=$_GET['Size'];
    $ProductBaseType=$_GET['BaseType'];
    $where=$Under."".$ItemName."".$IName."".$CompanyID." active=1 and [group]=0 and ProductBaseType='".$ProductBaseType."'";
    $table=$_GET['TextBoxName'];
    $fieldname=$_GET['fieldname'].",StandardPrice1 as SalePrice,VATPercent,StandardPrice1 as CostPrice ";
    $fieldid=$_GET['fieldid'];
    echo getSelect2List2new($table,$fieldid,$fieldname,$where,$connection);
  
  }
    if($_GET['action']=="getitemProcess")
  {
    $data=array();
    //    //$ItemName="Under=".$_GET['ItemName']." and ";
    /*if(isset($_GET['ItemName']))
    $ItemName=" Name like '%".$_GET['ItemName']."%' and "; 
    else*/
    $ItemName="";
    if(isset($_GET['Under']) && $ItemName=="")
    $Under="(Under=".$_GET['Under']." or under in (select id from inventory where under=".$_GET['Under'].")) and ";
    else
    $Under="";
    if(isset($_GET['IName']))
    $IName="Name like '%".$_GET['IName']."%' and ";
    else
    $IName="";
    if(isset($_GET['CompanyID']) && $_GET['CompanyID']>0)
    $CompanyID="CompanyID=".$_GET['CompanyID']." and ";
    else
    $CompanyID="";
    $InvoiceID=$_GET['InvoiceID'];
    $ProductBaseType=$_GET['BaseType'];
    $where=$Under."".$ItemName."".$IName."".$CompanyID." active=1 and [group]=0 and ProductBaseType='".$ProductBaseType."'";
    $table=$_GET['TextBoxName'];
    $fieldname=$_GET['fieldname'].",StandardPrice2 as SalePrice,VATPercent,Under as SubCategoryID,Attr18";
    $fieldid=$_GET['fieldid'];
      $sql="select $fieldid,$fieldname from $table where $where ";
      //and Attr18 in (select itemid from invoiceDetail where InvoiceID=$InvoiceID)

     $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      foreach ($row as $key => $value) {
        # code...
        $row[$key]=htmlspecialchars($value);
      //  $row[$key]=clean($value); 
       // $row[$key]=urlencode($value);       
      }
      $data []=$row;

    }
    echo json_encode($data);
    //echo getSelect2List2new($table,$fieldid,$fieldname,$where,$connection);
  }
	if($_GET['action']=="getitem")
	{
    //    //$ItemName="Under=".$_GET['ItemName']." and ";
		/*if(isset($_GET['ItemName']))
    $ItemName=" Name like '%".$_GET['ItemName']."%' and "; 
		else*/
		$ItemName="";
		if(isset($_GET['Under']) && $ItemName=="")
		$Under="(Under=".$_GET['Under']." or under in (select id from inventory where under=".$_GET['Under'].")) and ";
		else
		$Under="";
		if(isset($_GET['IName']))
		$IName="Name like '%".$_GET['IName']."%' and ";
		else
		$IName="";
		if(isset($_GET['CompanyID']) && $_GET['CompanyID']>0)
		$CompanyID="CompanyID=".$_GET['CompanyID']." and ";
		else
		$CompanyID="";
    if(isset($_GET['ShowInSales']) && $_GET['ShowInSales']==true)
    $ShowInSales="ShowInSales=1 and ";//.$_GET['ShowInSales']." and ";
    else
    $ShowInSales="";

		$Size=$_GET['Size'];
		$ProductBaseType=$_GET['BaseType'];
		$where=$Under."".$ItemName."".$IName."".$CompanyID."".$ShowInSales." active=1 and [group]=0 and ProductBaseType='".$ProductBaseType."'";
		$table=$_GET['TextBoxName'];
		$fieldname=$_GET['fieldname'].",StandardPrice1 as CostPrice,StandardPrice2 as SalePrice,VATPercent,Under as SubCategoryID";
		$fieldid=$_GET['fieldid'];
		echo getSelect2List2new($table,$fieldid,$fieldname,$where,$connection);
	}
  if($_GET['action']=="ShowDetailOnly")
  {
$data=array();
    //echo "called";
    $where="";
    if(isset($_GET['GLStartsWith']))
    {
    $GLStartsWith=$_GET['GLStartsWith'];
    $where .=" GLCode like '".$GLStartsWith."%' and ";
    }
    if(isset($_GET['NatureID']))
    {
    $NatureID=$_GET['NatureID'];
    $where .=" NatureID =".$NatureID." and  ";   
    }
    if(isset($_GET['condition']))
    {
    $condition=$_GET['condition'];
    $where .=$condition;    
    }
    
    $table=$_GET['TextBoxName'];
    $fieldname=$_GET['fieldname']."";
    $fieldid=$_GET['fieldid'];
    $where .="  1=1 ";
    $sql="select $fieldid,$fieldname from $table where $where";
     $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      foreach ($row as $key => $value) {
        # code...
        $row[$key]=htmlspecialchars($value);
      //  $row[$key]=clean($value); 
       // $row[$key]=urlencode($value);       
      }
      $data []=$row;

    }
    echo json_encode($data);
   // echo getSelect2List2($table,$fieldid,$fieldname,$where,$connection);  

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

    //echo "called";
    $where="";
    if(isset($_GET['GLStartsWith']))
    {
    $GLStartsWith=$_GET['GLStartsWith'];
    $where .=" GLCode like '".$GLStartsWith."%' and ";
    }
    if(isset($_GET['NatureID']))
    {
    $NatureID=$_GET['NatureID'];
    $where .=" NatureID =".$NatureID." and  ";   
    }
    if(isset($_GET['condition']))
    {
    $condition=$_GET['condition'];
    $where .=" COAID in(".$condition.") and  ";    
    }

    $table=$_GET['TextBoxName'];
    $fieldname=$_GET['fieldname']."";
    $fieldid=$_GET['fieldid'];
    $where .="  active=1 ";
    echo getSelect2List2($table,$fieldid,$fieldname,$where,$connection);  

  
  }
	if($_GET['action']=="GetAccountsMasterForm")
	{
		//echo "called";
		$where="";
		if(isset($_GET['GLStartsWith']))
		{
		$GLStartsWith=$_GET['GLStartsWith'];
		$where .=" GLCode like '".$GLStartsWith."%' or ";
		}
		if(isset($_GET['NatureID']))
		{
		$NatureID=$_GET['NatureID'];
		$where .=" NatureID =".$NatureID." or  ";		
		}
		if(isset($_GET['condition']))
		{
		$condition=$_GET['condition'];
		$where .=" COAID in(".$condition.") or  ";		
		}

		$table=$_GET['TextBoxName'];
		$fieldname=$_GET['fieldname']."";
		$fieldid=$_GET['fieldid'];
    $where .="  active=1 ";
		echo getSelect2List2($table,$fieldid,$fieldname,$where,$connection);	

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

//group jobcard
    //print_r($_GET);

    $data=array();
    if(isset($_GET['search']))
    {
      $Company=   isset($_GET['Company'])?$_GET['Company']:'';
      if($Company!='')
      {
        $Company="c.Name like ''";
      }
      else
      {
        $Company="";
      }
            
            $Supplier=    isset($_GET['Supplier'])?$_GET['Supplier']:'';
            if($Supplier!="")
            {
            $Supplier=""; 
            }
            else
            {
            $Supplier=""; 
            }
            $BillDate=    isset($_GET['BillDate'])?$_GET['BillDate']:'';
            if($BillDate!="")
            {
            $BillDate=""; 
            }
            else
            {
            $BillDate=""; 
            }
            $ReferenceNo= isset($_GET['ReferenceNo'])?$_GET['ReferenceNo']:'';
            if($ReferenceNo!="")
            {
            $ReferenceNo="i.KeyField like '%".$ReferenceNo."%' and "; 
            }
            else
            {
            $ReferenceNo="";  
            }
            $Customer=    isset($_GET['Customer'])?$_GET['Customer']:'';
            if($Customer!="")
            {
            $Customer="CustomerName like '%".$Customer."%' and "; 
            }
            else
            {
            $Customer=""; 
            }
            $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          $InvoiceStatus="i.InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="";  
          }
       $Customer_MobileNumber=   isset($_GET['Customer_MobileNumber'])?$_GET['Customer_MobileNumber']:'';    
          if($Customer_MobileNumber!="")
          {
          $Customer_MobileNumber="i.MobileNumber like '%".$Customer_MobileNumber."%' and ";  
          }
          else
          {
          $Customer_MobileNumber="";  
          }
    $Customer_PlateNumber=   isset($_GET['Customer_PlateNumber'])?$_GET['Customer_PlateNumber']:'';    
          if($Customer_PlateNumber!="")
          {
          $Customer_PlateNumber="i.PlateNumber like '%".$Customer_PlateNumber."%' and ";  
          }
          else
          {
          $Customer_PlateNumber="";  
          }
 $Customer_ChassisNumber=   isset($_GET['Customer_ChassisNumber'])?$_GET['Customer_ChassisNumber']:'';    
          if($Customer_ChassisNumber!="")
          {
          $Customer_ChassisNumber="i.ChassisNumber like '%".$Customer_ChassisNumber."%' and ";  
          }
          else
          {
          $Customer_ChassisNumber="";  
          }


          $searchbox=$Company.$Supplier.$ReferenceNo.$Customer.$InvoiceStatus.$Customer_MobileNumber.$Customer_ChassisNumber;
      //$GodownID=$_GET['GodownID'];
    $sql="select
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 as CompanyShortForm,CustomerName as JC_CustomerName,MobileNumber as JC_MobileNumber,PlateNumber as JC_PlateNumber,ChassisNumber as JC_ChassisNumber,convert(date,InvoiceDate) as InvoiceDate,i.KeyField as KeyField,i.CreateLog as CreateByUserName,InvoiceID,convert(date,DeliveryDate) 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,i.supplierid as supplierid,ParkingNo,i.ReferenceInvoiceID as ReferenceInvoiceID,(select 
' Bill:'+convert(varchar,isnull(sum(NetAmount),0))+' || Paid:'+convert(varchar,isnull((select SUM(paid) from InvoiceMaster as  ii where ReferenceInvoiceID=i.InvoiceID),0))+' || Balance:'+convert(varchar,(isnull(sum(NetAmount),0)-isnull((select SUM(paid) from InvoiceMaster as  ii where ReferenceInvoiceID=i.InvoiceID),0))) as Balance from InvoiceMaster where InvoiceType=5 
and InvoiceID in (select invoiceid from invoicemaster where ReferenceInvoiceID=i.InvoiceID) 
group by ReferenceInvoiceID ) as Balance
   from InvoiceMaster as i left outer join godowns  as g on i.Shipperid=g.GodownID
   left outer join godowns as c on c.GodownID=i.GodownID where ".$searchbox."  i.InvoiceType=5 and i.Active=1 and i.SupplierID=1066 and i.InvoiceStatus=4";//and i.CreateLog='".$_SESSION['UserName']."'
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      foreach ($row as $key => $value) {
        # code...
        $row[$key]=utf8_encode($value);
      }
      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);

      }//end if 
        else
    {
   // $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
   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.GodownID=".$GodownID." and i.InvoiceType=5 and i.InvoiceStatus<3";*/
    $sql="select * from view_jobcard_list where  InvoiceType=5 and CustomerID=1066 and InvoiceStatus<>3";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      switch ($row['InvoiceStatus']) {
        case '1':
          # code...
        $row['InvoiceStatus']="PENDING";
          break;
        case '2':
          # code...
        $row['InvoiceStatus']="ACCEPTED";
          break;
          case '3':
          # code...
        $row['InvoiceStatus']="REJECTED";
          break;
          case '4':
          # code...
        $row['InvoiceStatus']="CLOSED";
          break;
        default:
          # code...
        $row['InvoiceStatus']="";
          break;
      }
      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);
    }//end else 
  
  
  }
	if($_GET['action']=="jobcardlist2")
  {
//group jobcard
    //print_r($_GET);

    $data=array();
    if(isset($_GET['search']))
    {
      $Company=   isset($_GET['Company'])?$_GET['Company']:'';
      if($Company!='')
      {
        $Company="c.Name like '".$Company."%'";
      }
      else
      {
        $Company="";
      }
            
            $Supplier=    isset($_GET['Supplier'])?$_GET['Supplier']:'';
            if($Supplier!="")
            {
            $Supplier=""; 
            }
            else
            {
            $Supplier=""; 
            }
            $BillDate=    isset($_GET['BillDate'])?$_GET['BillDate']:'';
            if($BillDate!="")
            {
            $BillDate=" i.InvoiceDate='".$BillDate."' and "; 
            }
            else
            {
            $BillDate=""; 
            }
            $ReferenceNo= isset($_GET['ReferenceNo'])?$_GET['ReferenceNo']:'';
            if($ReferenceNo!="")
            {
            $ReferenceNo="i.KeyField like '%".$ReferenceNo."%' and "; 
            }
            else
            {
            $ReferenceNo="";  
            }
            $Customer=    isset($_GET['Customer'])?$_GET['Customer']:'';
            if($Customer!="")
            {
            $Customer="CustomerName like '%".$Customer."%' and "; 
            }
            else
            {
            $Customer=""; 
            }
            $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          $InvoiceStatus="i.InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="";  
          }
       $Customer_MobileNumber=   isset($_GET['Customer_MobileNumber'])?$_GET['Customer_MobileNumber']:'';    
          if($Customer_MobileNumber!="")
          {
          $Customer_MobileNumber="i.MobileNumber like '%".$Customer_MobileNumber."%' and ";  
          }
          else
          {
          $Customer_MobileNumber="";  
          }
    $Customer_PlateNumber=   isset($_GET['Customer_PlateNumber'])?$_GET['Customer_PlateNumber']:'';    
          if($Customer_PlateNumber!="")
          {
          $Customer_PlateNumber="i.PlateNumber like '%".$Customer_PlateNumber."%' and ";  
          }
          else
          {
          $Customer_PlateNumber="";  
          }
 $Customer_ChassisNumber=   isset($_GET['Customer_ChassisNumber'])?$_GET['Customer_ChassisNumber']:'';    
          if($Customer_ChassisNumber!="")
          {
          $Customer_ChassisNumber="i.ChassisNumber like '%".$Customer_ChassisNumber."%' and ";  
          }
          else
          {
          $Customer_ChassisNumber="";  
          }


          $searchbox=$Company.$Supplier.$ReferenceNo.$Customer.$InvoiceStatus.$Customer_MobileNumber.$Customer_ChassisNumber.$BillDate;
      $GodownID=$_GET['GodownID'];
    $sql="select
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 as CompanyShortForm,CustomerName as JC_CustomerName,MobileNumber as JC_MobileNumber,PlateNumber as JC_PlateNumber,ChassisNumber as JC_ChassisNumber,convert(date,InvoiceDate) as InvoiceDate,i.KeyField as KeyField,i.CreateLog as CreateByUserName,InvoiceID,convert(date,DeliveryDate) 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,i.supplierid as supplierid,ParkingNo,i.ReferenceInvoiceID as ReferenceInvoiceID,(select 
' Bill:'+convert(varchar,isnull(sum(NetAmount),0))+' || Paid:'+convert(varchar,isnull((select SUM(paid) from InvoiceMaster as  ii where ReferenceInvoiceID=i.InvoiceID),0))+' || Balance:'+convert(varchar,(isnull(sum(NetAmount),0)-isnull((select SUM(paid) from InvoiceMaster as  ii where ReferenceInvoiceID=i.InvoiceID),0))) as Balance from InvoiceMaster where InvoiceType=5 
and InvoiceID in (i.InvoiceID) 
group by ReferenceInvoiceID ) as Balance
   from InvoiceMaster as i left outer join godowns  as g on i.Shipperid=g.GodownID
   left outer join godowns as c on c.GodownID=i.GodownID where ".$searchbox."  i.InvoiceType=5 and i.Active=1 and i.GodownID=0";//and i.CreateLog='".$_SESSION['UserName']."'
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      foreach ($row as $key => $value) {
        # code...
        $row[$key]=utf8_encode($value);
      }
      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);

      }//end if 
        else
    {
    $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
   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.GodownID=".$GodownID." and i.InvoiceType=5 and i.InvoiceStatus<3";*/
    $sql="select * from view_jobcard_list where GodownID=".$GodownID." and InvoiceType=5 and InvoiceStatus<3";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      switch ($row['InvoiceStatus']) {
        case '1':
          # code...
        $row['InvoiceStatus']="PENDING";
          break;
        case '2':
          # code...
        $row['InvoiceStatus']="ACCEPTED";
          break;
          case '3':
          # code...
        $row['InvoiceStatus']="REJECTED";
          break;
          case '4':
          # code...
        $row['InvoiceStatus']="CLOSED";
          break;
        default:
          # code...
        $row['InvoiceStatus']="";
          break;
      }
      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);
    }//end else 
  
  }
  if($_GET['action']=="contractlist")
  {


    //print_r($_GET);

    $data=array();
    if(isset($_GET['search']))
    {
      $Company=   isset($_GET['Company'])?$_GET['Company']:'';
      if($Company!='')
      {
        $Company="c.Name like ''";
      }
      else
      {
        $Company="";
      }
            
            $Supplier=    isset($_GET['Supplier'])?$_GET['Supplier']:'';
            if($Supplier!="")
            {
            $Supplier=""; 
            }
            else
            {
            $Supplier=""; 
            }
            $BillDate=    isset($_GET['BillDate'])?$_GET['BillDate']:'';
            if($BillDate!="")
            {
            $BillDate=""; 
            }
            else
            {
            $BillDate=""; 
            }
            $ReferenceNo= isset($_GET['ReferenceNo'])?$_GET['ReferenceNo']:'';
            if($ReferenceNo!="")
            {
            $ReferenceNo="i.KeyField like '%".$ReferenceNo."%' and "; 
            }
            else
            {
            $ReferenceNo="";  
            }
            $Customer=    isset($_GET['Customer'])?$_GET['Customer']:'';
            if($Customer!="")
            {
            $Customer="CustomerName like '%".$Customer."%' and "; 
            }
            else
            {
            $Customer=""; 
            }
            $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          $InvoiceStatus="i.InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="i.InvoiceStatus<3 and ";  
          }
       $Customer_MobileNumber=   isset($_GET['Customer_MobileNumber'])?$_GET['Customer_MobileNumber']:'';    
          if($Customer_MobileNumber!="")
          {
          $Customer_MobileNumber="i.MobileNumber like '%".$Customer_MobileNumber."%' and ";  
          }
          else
          {
          $Customer_MobileNumber="";  
          }
    $Customer_PlateNumber=   isset($_GET['Customer_PlateNumber'])?$_GET['Customer_PlateNumber']:'';    
          if($Customer_PlateNumber!="")
          {
          $Customer_PlateNumber="i.PlateNumber like '%".$Customer_PlateNumber."%' and ";  
          }
          else
          {
          $Customer_PlateNumber="";  
          }
 $Customer_ChassisNumber=   isset($_GET['Customer_ChassisNumber'])?$_GET['Customer_ChassisNumber']:'';    
          if($Customer_ChassisNumber!="")
          {
          $Customer_ChassisNumber="i.ChassisNumber like '%".$Customer_ChassisNumber."%' and ";  
          }
          else
          {
          $Customer_ChassisNumber="";  
          }


          $searchbox=$Company.$Supplier.$ReferenceNo.$Customer.$InvoiceStatus.$Customer_MobileNumber.$Customer_ChassisNumber;
      $GodownID=$_GET['GodownID'];
    $sql="select
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 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,i.supplierid as supplierid
   from InvoiceMaster as i left outer join godowns  as g on i.Shipperid=g.GodownID
   inner join godowns as c on c.GodownID=i.GodownID where ".$searchbox."  i.GodownID=".$GodownID." and i.InvoiceType=14 and i.Active=1  and i.CreateLog='".$_SESSION['UserName']."' ";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);

      }//end if 
    else
    {
    $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
   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.GodownID=".$GodownID." and i.InvoiceType=5 and i.InvoiceStatus<3";*/
   $sql="select * from view_jobcard_list where GodownID=".$GodownID." and InvoiceType=14 and InvoiceStatus<3 and CreateLog='".$_SESSION['UserName']."'";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {

    //$row['InvoiceDate']=str_replace("00:00:00","", $row['InvoiceDate']);
      switch ($row['InvoiceStatus']) {
        case '1':
          # code...
        $row['InvoiceStatus']="PENDING";
          break;
        case '2':
          # code...
        $row['InvoiceStatus']="ACCEPTED";
          break;
          case '3':
          # code...
        $row['InvoiceStatus']="REJECTED";
          break;
          case '4':
          # code...
        $row['InvoiceStatus']="CLOSED";
          break;
        default:
          # code...
        $row['InvoiceStatus']="";
          break;
      }

      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);
    }//end else 
   
  
  }
  if($_GET['action']=="quotationlist")
  {

    //print_r($_GET);

    $data=array();
    if(isset($_GET['search']))
    {
      $Company=   isset($_GET['Company'])?$_GET['Company']:'';
      if($Company!='')
      {
        $Company="c.Name like ''";
      }
      else
      {
        $Company="";
      }
            
            $Supplier=    isset($_GET['Supplier'])?$_GET['Supplier']:'';
            if($Supplier!="")
            {
            $Supplier=""; 
            }
            else
            {
            $Supplier=""; 
            }
            $BillDate=    isset($_GET['BillDate'])?$_GET['BillDate']:'';
            if($BillDate!="")
            {
            $BillDate=""; 
            }
            else
            {
            $BillDate=""; 
            }
            $ReferenceNo= isset($_GET['ReferenceNo'])?$_GET['ReferenceNo']:'';
            if($ReferenceNo!="")
            {
            $ReferenceNo="i.KeyField like '%".$ReferenceNo."%' and "; 
            }
            else
            {
            $ReferenceNo="";  
            }
            $Customer=    isset($_GET['Customer'])?$_GET['Customer']:'';
            if($Customer!="")
            {
            $Customer="CustomerName like '%".$Customer."%' and "; 
            }
            else
            {
            $Customer=""; 
            }
            $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          $InvoiceStatus="i.InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="i.InvoiceStatus<3 and ";  
          }
       $Customer_MobileNumber=   isset($_GET['Customer_MobileNumber'])?$_GET['Customer_MobileNumber']:'';    
          if($Customer_MobileNumber!="")
          {
          $Customer_MobileNumber="i.MobileNumber like '%".$Customer_MobileNumber."%' and ";  
          }
          else
          {
          $Customer_MobileNumber="";  
          }
    $Customer_PlateNumber=   isset($_GET['Customer_PlateNumber'])?$_GET['Customer_PlateNumber']:'';    
          if($Customer_PlateNumber!="")
          {
          $Customer_PlateNumber="i.PlateNumber like '%".$Customer_PlateNumber."%' and ";  
          }
          else
          {
          $Customer_PlateNumber="";  
          }
 $Customer_ChassisNumber=   isset($_GET['Customer_ChassisNumber'])?$_GET['Customer_ChassisNumber']:'';    
          if($Customer_ChassisNumber!="")
          {
          $Customer_ChassisNumber="i.ChassisNumber like '%".$Customer_ChassisNumber."%' and ";  
          }
          else
          {
          $Customer_ChassisNumber="";  
          }


          $searchbox=$Company.$Supplier.$ReferenceNo.$Customer.$InvoiceStatus.$Customer_MobileNumber.$Customer_ChassisNumber;
      $GodownID=$_GET['GodownID'];
    $sql="select
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 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,i.supplierid as supplierid
   from InvoiceMaster as i left outer join godowns  as g on i.Shipperid=g.GodownID
   left outer join godowns as c on c.GodownID=i.GodownID where ".$searchbox."  i.GodownID=".$GodownID." and i.InvoiceType=12 and i.Active=1  and i.CreateLog='".$_SESSION['UserName']."' ";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);

      }//end if 
    else
    {
    $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
   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.GodownID=".$GodownID." and i.InvoiceType=5 and i.InvoiceStatus<3";*/

    $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          $InvoiceStatus="InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="InvoiceStatus<3 and ";  
          }
    $sql="select * from view_jobcard_list where GodownID=".$GodownID." and InvoiceType=12 and $InvoiceStatus CreateLog='".$_SESSION['UserName']."'";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {

    //$row['InvoiceDate']=str_replace("00:00:00","", $row['InvoiceDate']);
      switch ($row['InvoiceStatus']) {
        case '1':
          # code...
        $row['InvoiceStatus']="PENDING";
          break;
        case '2':
          # code...
        $row['InvoiceStatus']="ACCEPTED";
          break;
          case '3':
          # code...
        $row['InvoiceStatus']="REJECTED";
          break;
          case '4':
          # code...
        $row['InvoiceStatus']="CLOSED";
          break;
        default:
          # code...
        $row['InvoiceStatus']="";
          break;
      }

      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);
    }//end else 
   
  }
  if($_GET['action']=="DMjobcardlist")
  {


    //print_r($_GET);

    $data=array();
    if(isset($_GET['search']))
    {
      $Company=   isset($_GET['Company'])?$_GET['Company']:'';
      if($Company!='')
      {
        $Company="c.Name like ''";
      }
      else
      {
        $Company="";
      }
            
            $Supplier=    isset($_GET['Supplier'])?$_GET['Supplier']:'';
            if($Supplier!="")
            {
            $Supplier=""; 
            }
            else
            {
            $Supplier=""; 
            }
            $BillDate=    isset($_GET['BillDate'])?$_GET['BillDate']:'';
            if($BillDate!="")
            {
            $BillDate=""; 
            }
            else
            {
            $BillDate=""; 
            }
            $ReferenceNo= isset($_GET['ReferenceNo'])?$_GET['ReferenceNo']:'';
            if($ReferenceNo!="")
            {
            $ReferenceNo="i.KeyField like '%".$ReferenceNo."%' and "; 
            }
            else
            {
            $ReferenceNo="";  
            }
            $Customer=    isset($_GET['Customer'])?$_GET['Customer']:'';
            if($Customer!="")
            {
            $Customer="CustomerName like '%".$Customer."%' and "; 
            }
            else
            {
            $Customer=""; 
            }
            $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          $InvoiceStatus="i.InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="i.InvoiceStatus<3 and ";  
          }
       $Customer_MobileNumber=   isset($_GET['Customer_MobileNumber'])?$_GET['Customer_MobileNumber']:'';    
          if($Customer_MobileNumber!="")
          {
          $Customer_MobileNumber="i.MobileNumber like '%".$Customer_MobileNumber."%' and ";  
          }
          else
          {
          $Customer_MobileNumber="";  
          }
    $Customer_PlateNumber=   isset($_GET['Customer_PlateNumber'])?$_GET['Customer_PlateNumber']:'';    
          if($Customer_PlateNumber!="")
          {
          $Customer_PlateNumber="i.PlateNumber like '%".$Customer_PlateNumber."%' and ";  
          }
          else
          {
          $Customer_PlateNumber="";  
          }
 $Customer_ChassisNumber=   isset($_GET['Customer_ChassisNumber'])?$_GET['Customer_ChassisNumber']:'';    
          if($Customer_ChassisNumber!="")
          {
          $Customer_ChassisNumber="i.ChassisNumber like '%".$Customer_ChassisNumber."%' and ";  
          }
          else
          {
          $Customer_ChassisNumber="";  
          }


          $searchbox=$Company.$Supplier.$ReferenceNo.$Customer.$InvoiceStatus.$Customer_MobileNumber.$Customer_ChassisNumber;
      $GodownID=$_GET['GodownID'];
    $sql="select
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 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,i.supplierid as supplierid
   from InvoiceMaster as i left outer join godowns  as g on i.Shipperid=g.GodownID
   inner join godowns as c on c.GodownID=i.GodownID  where ".$searchbox."  i.GodownID=".$GodownID." and i.InvoiceType=5 and i.Active=1  and i.itemid=2 ";//and i.CreateLog='".$_SESSION['UserName']."'
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      foreach ($row as $key => $value) {
        # code...
        $row[$key]=utf8_encode($value);
      }
      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);

      }//end if 
        else
    {
    $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
   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.GodownID=".$GodownID." and i.InvoiceType=5 and i.InvoiceStatus<3";*/
   $sql="select convert(date,InvoiceDate) as InvoiceDate1,convert(date,DeliveryDate) as DeliveryDate1,* from view_jobcard_list where GodownID=".$GodownID." and InvoiceType=5 and InvoiceStatus<>3 and ItemID=2";
   //and CreateLog='".$_SESSION['UserName']."'
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      switch ($row['InvoiceStatus']) {
        case '1':
          # code...
        $row['InvoiceStatus']="PENDING";
          break;
        case '2':
          # code...
        $row['InvoiceStatus']="ACCEPTED";
          break;
          case '3':
          # code...
        $row['InvoiceStatus']="REJECTED";
          break;
          case '4':
          # code...
        $row['InvoiceStatus']="CLOSED";
          break;
        default:
          # code...
        $row['InvoiceStatus']="";
          break;
      }
      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);
    }//end else 
  
    
  }
  if($_GET['action']=="rtajobcardlist")
  {

    //print_r($_GET);

    $data=array();
    if(isset($_GET['search']))
    {
      $Company=   isset($_GET['Company'])?$_GET['Company']:'';
      if($Company!='')
      {
        $Company="c.Name like ''";
      }
      else
      {
        $Company="";
      }
            
            $Supplier=    isset($_GET['Supplier'])?$_GET['Supplier']:'';
            if($Supplier!="")
            {
            $Supplier=""; 
            }
            else
            {
            $Supplier=""; 
            }
            $BillDate=    isset($_GET['BillDate'])?$_GET['BillDate']:'';
            if($BillDate!="")
            {
            $BillDate=""; 
            }
            else
            {
            $BillDate=""; 
            }
            $ReferenceNo= isset($_GET['ReferenceNo'])?$_GET['ReferenceNo']:'';
            if($ReferenceNo!="")
            {
            $ReferenceNo="i.KeyField like '%".$ReferenceNo."%' and "; 
            }
            else
            {
            $ReferenceNo="";  
            }
            $Customer=    isset($_GET['Customer'])?$_GET['Customer']:'';
            if($Customer!="")
            {
            $Customer="CustomerName like '%".$Customer."%' and "; 
            }
            else
            {
            $Customer=""; 
            }
            $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          $InvoiceStatus="i.InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="i.InvoiceStatus<3 and ";  
          }
       $Customer_MobileNumber=   isset($_GET['Customer_MobileNumber'])?$_GET['Customer_MobileNumber']:'';    
          if($Customer_MobileNumber!="")
          {
          $Customer_MobileNumber="i.MobileNumber like '%".$Customer_MobileNumber."%' and ";  
          }
          else
          {
          $Customer_MobileNumber="";  
          }
    $Customer_PlateNumber=   isset($_GET['Customer_PlateNumber'])?$_GET['Customer_PlateNumber']:'';    
          if($Customer_PlateNumber!="")
          {
          $Customer_PlateNumber="i.PlateNumber like '%".$Customer_PlateNumber."%' and ";  
          }
          else
          {
          $Customer_PlateNumber="";  
          }
 $Customer_ChassisNumber=   isset($_GET['Customer_ChassisNumber'])?$_GET['Customer_ChassisNumber']:'';    
          if($Customer_ChassisNumber!="")
          {
          $Customer_ChassisNumber="i.ChassisNumber like '%".$Customer_ChassisNumber."%' and ";  
          }
          else
          {
          $Customer_ChassisNumber="";  
          }


          $searchbox=$Company.$Supplier.$ReferenceNo.$Customer.$InvoiceStatus.$Customer_MobileNumber.$Customer_ChassisNumber;
      $GodownID=$_GET['GodownID'];
    $sql="select
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 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,i.supplierid as supplierid
   from InvoiceMaster as i left outer join godowns  as g on i.Shipperid=g.GodownID
   inner join godowns as c on c.GodownID=i.GodownID  where ".$searchbox."  i.GodownID=".$GodownID." and i.InvoiceType=5 and i.Active=1  and i.itemid>0 ";//and i.CreateLog='".$_SESSION['UserName']."'
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      foreach ($row as $key => $value) {
        # code...
        $row[$key]=utf8_encode($value);
      }
      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);

      }//end if 
        else
    {
    $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
   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.GodownID=".$GodownID." and i.InvoiceType=5 and i.InvoiceStatus<3";*/
   $sql="select convert(date,InvoiceDate) as InvoiceDate1,convert(date,DeliveryDate) as DeliveryDate1,* from view_jobcard_list where GodownID=".$GodownID." and InvoiceType=5 and InvoiceStatus<>3 and ItemID>0";
   //and CreateLog='".$_SESSION['UserName']."'
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      switch ($row['InvoiceStatus']) {
        case '1':
          # code...
        $row['InvoiceStatus']="PENDING";
          break;
        case '2':
          # code...
        $row['InvoiceStatus']="ACCEPTED";
          break;
          case '3':
          # code...
        $row['InvoiceStatus']="REJECTED";
          break;
          case '4':
          # code...
        $row['InvoiceStatus']="CLOSED";
          break;
        default:
          # code...
        $row['InvoiceStatus']="";
          break;
      }
      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);
    }//end else 
  
    }//rtajobcardlist
    if($_GET['action']=="jobcardlist_civil")
    {
      
    //print_r($_GET);

    $data=array();
    if(isset($_GET['search']))
    {
            $ParkingNo=    isset($_GET['ParkingNo'])?$_GET['ParkingNo']:'';
            if($ParkingNo!="")
            {
            $ParkingNo=" ParkingNo like '%".$ParkingNo."%' and "; 
            }
            else
            {
            $ParkingNo=""; 
            }
      $isBooth=(isset($_GET['isBooth'])?$_GET['isBooth']:'');
      if($isBooth!="")
      {
        if($ParkingNo=="")
        $tokendate=" InvoiceDate='".Date("Y-m-d")."' and ";
        else
        $tokendate="";

      }
      else
      {
        $tokendate="";
      }

      $Company=   isset($_GET['Company'])?$_GET['Company']:'';
      if($Company!='')
      {
        $Company="c.Name like ''";
      }
      else
      {
        $Company="";
      }
            
            $Supplier=    isset($_GET['Supplier'])?$_GET['Supplier']:'';
            if($Supplier!="")
            {
            $Supplier=""; 
            }
            else
            {
            $Supplier=""; 
            }
            $BillDate=    isset($_GET['BillDate'])?$_GET['BillDate']:'';
            if($BillDate!="")
            {
            $BillDate=""; 
            }
            else
            {
            $BillDate=""; 
            }
            $ReferenceNo= isset($_GET['ReferenceNo'])?$_GET['ReferenceNo']:'';
            if($ReferenceNo!="")
            {
            $ReferenceNo="i.KeyField like '%".$ReferenceNo."%' and "; 
            }
            else
            {
            $ReferenceNo="";  
            }
            $Customer=    isset($_GET['Customer'])?$_GET['Customer']:'';
            if($Customer!="")
            {
            $Customer="CustomerName like '%".$Customer."%' and "; 
            }
            else
            {
            $Customer=""; 
            }
          $KeyNo=    isset($_GET['KeyNo'])?$_GET['KeyNo']:'';
            if($KeyNo!="")
            {
            $KeyNo="KeyNo like '%".$KeyNo."%' and "; 
            }
            else
            {
            $KeyNo=""; 
            }

            $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          $InvoiceStatus="i.InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="i.InvoiceStatus<>3 and "; 
          }
       $Customer_MobileNumber=   isset($_GET['Customer_MobileNumber'])?$_GET['Customer_MobileNumber']:'';    
          if($Customer_MobileNumber!="")
          {
          $Customer_MobileNumber="i.MobileNumber like '%".$Customer_MobileNumber."%' and ";  
          }
          else
          {
          $Customer_MobileNumber="";  
          }
    $Customer_PlateNumber=   isset($_GET['Customer_PlateNumber'])?$_GET['Customer_PlateNumber']:'';    
          if($Customer_PlateNumber!="")
          {
          $Customer_PlateNumber="i.PlateNumber like '%".$Customer_PlateNumber."%' and ";  
          }
          else
          {
          $Customer_PlateNumber="";  
          }
 $Customer_ChassisNumber=   isset($_GET['Customer_ChassisNumber'])?$_GET['Customer_ChassisNumber']:'';    
          if($Customer_ChassisNumber!="")
          {
          $Customer_ChassisNumber="i.ChassisNumber like '%".$Customer_ChassisNumber."%' and ";  
          }
          else
          {
          $Customer_ChassisNumber="";  
          }


          $searchbox=$Company.$Supplier.$ReferenceNo.$Customer.$InvoiceStatus.$Customer_MobileNumber.$Customer_ChassisNumber.$KeyNo.$tokendate.$ParkingNo;
      $GodownID=$_GET['GodownID'];
      $sql="select
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 as CompanyShortForm,CustomerName as JC_CustomerName,MobileNumber as JC_MobileNumber,PlateNumber as JC_PlateNumber,ChassisNumber as JC_ChassisNumber,InvoiceDate,i.KeyField as KeyField,i.CreateLog 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,i.supplierid as supplierid,i.ItemID as ITEMID,i.KeyNo as KeyNo,i.Email as Email
   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.Active=1  and ITEMID<1";//and i.CreateLog='".$_SESSION['UserName']."'
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);

      }//end if 
        else
    {
    $GodownID=$_GET['GodownID'];
    if(isset($_GET['isBooth']) && $_GET['isBooth']!="")
    {
        $isBooth=" and InvoiceDate='".Date("Y-m-d")."'";
    }
    else
    {
      $isBooth="";
    }
   /*$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
   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.GodownID=".$GodownID." and i.InvoiceType=5 and i.InvoiceStatus<3";*/
    $sql="select convert(date,InvoiceDate) as InvoiceDate1,convert(date,DeliveryDate) as DeliveryDate1,(select 
' Bill:'+convert(varchar,isnull(sum(NetAmount),0))+' || Paid:'+convert(varchar,isnull(sum(paid),0))+' || Balance:'+convert(varchar,(isnull(sum(NetAmount),0)-isnull(sum(Paid),0))) as Balance from InvoiceMaster where InvoiceType=5 and ReferenceInvoiceID=0 
and InvoiceID in (select invoiceid from invoicemaster where InvoiceID=view_jobcard_list.InvoiceID) 
group by ReferenceInvoiceID ) as Balance1,* from view_jobcard_list where GodownID=".$GodownID." and InvoiceType=5 and InvoiceStatus<>3 and itemid<1  and CreateLog='".$_SESSION['UserName']."' $isBooth";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      switch ($row['InvoiceStatus']) {
        case '1':
          # code...
        $row['InvoiceStatus']="PENDING";
          break;
        case '2':
          # code...
        $row['InvoiceStatus']="ACCEPTED";
          break;
          case '3':
          # code...
        $row['InvoiceStatus']="REJECTED";
          break;
          case '4':
          # code...
        $row['InvoiceStatus']="CLOSED";
          break;
        default:
          # code...
        $row['InvoiceStatus']="";
          break;
      }
      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);
    }//end else 
  
    }
    if($_GET['action']=="jobcardlist_approval")
    {



    //print_r($_GET);

    $data=array();
    if(isset($_GET['search']))
    {
            $ParkingNo=    isset($_GET['ParkingNo'])?$_GET['ParkingNo']:'';
            if($ParkingNo!="")
            {
            $ParkingNo=" ParkingNo like '%".$ParkingNo."%' and "; 
            }
            else
            {
            $ParkingNo=""; 
            }
      $isBooth=(isset($_GET['isBooth'])?$_GET['isBooth']:'');
      if($isBooth!="")
      {
        if($ParkingNo=="")
        $tokendate=" InvoiceDate='".Date("Y-m-d")."' and ";
        else
        $tokendate="";

      }
      else
      {
        $tokendate="";
      }

      $Company=   isset($_GET['Company'])?$_GET['Company']:'';
      if($Company!='')
      {
        $Company="";//"c.Name like '' and ";
      }
      else
      {
        $Company="";
      }
            
            $Supplier=    isset($_GET['Supplier'])?$_GET['Supplier']:'';
            if($Supplier!="")
            {
            $Supplier=""; 
            }
            else
            {
            $Supplier=""; 
            }
            $BillDate=    isset($_GET['BillDate'])?$_GET['BillDate']:'';
            if($BillDate!="")
            {
            $BillDate=""; 
            }
            else
            {
            $BillDate=""; 
            }
            $ReferenceNo= isset($_GET['ReferenceNo'])?$_GET['ReferenceNo']:'';
            if($ReferenceNo!="")
            {
            $ReferenceNo="i.KeyField like '%".$ReferenceNo."%' and "; 
            }
            else
            {
            $ReferenceNo="";  
            }
            $Customer=    isset($_GET['Customer'])?$_GET['Customer']:'';
            if($Customer!="")
            {
            $Customer="CustomerName like '%".$Customer."%' and "; 
            }
            else
            {
            $Customer=""; 
            }
          $KeyNo=    isset($_GET['KeyNo'])?$_GET['KeyNo']:'';
            if($KeyNo!="")
            {
            $KeyNo="KeyNo like '%".$KeyNo."%' and "; 
            }
            else
            {
            $KeyNo=""; 
            }

            $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          $InvoiceStatus="i.InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="i.InvoiceStatus<>3 and "; 
          }
       $Customer_MobileNumber=   isset($_GET['Customer_MobileNumber'])?$_GET['Customer_MobileNumber']:'';    
          if($Customer_MobileNumber!="")
          {
          $Customer_MobileNumber="i.MobileNumber like '%".$Customer_MobileNumber."%' and ";  
          }
          else
          {
          $Customer_MobileNumber="";  
          }
    $Customer_PlateNumber=   isset($_GET['Customer_PlateNumber'])?$_GET['Customer_PlateNumber']:'';    
          if($Customer_PlateNumber!="")
          {
          $Customer_PlateNumber="i.PlateNumber like '%".$Customer_PlateNumber."%' and ";  
          }
          else
          {
          $Customer_PlateNumber="";  
          }
 $Customer_ChassisNumber=   isset($_GET['Customer_ChassisNumber'])?$_GET['Customer_ChassisNumber']:'';    
          if($Customer_ChassisNumber!="")
          {
          $Customer_ChassisNumber="i.ChassisNumber like '%".$Customer_ChassisNumber."%' and ";  
          }
          else
          {
          $Customer_ChassisNumber="";  
          }


          $searchbox=$Company.$Supplier.$ReferenceNo.$Customer.$InvoiceStatus.$Customer_MobileNumber.$Customer_ChassisNumber.$KeyNo.$tokendate.$ParkingNo;
      $GodownID=$_GET['GodownID'];
       $sql="select
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 as CompanyShortForm,CustomerName as JC_CustomerName,MobileNumber as JC_MobileNumber,PlateNumber as JC_PlateNumber,ChassisNumber as JC_ChassisNumber,InvoiceDate,i.KeyField as KeyField,i.CreateLog 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,i.supplierid as supplierid,i.ItemID as ITEMID,i.KeyNo as KeyNo,i.Email as Email
   from InvoiceMaster as i inner join godowns  as g on i.Shipperid=g.GodownID
   inner join godowns as c on c.GodownID=i.GodownID where ".$searchbox."  i.GodownID=".$GodownID." and i.InvoiceType=5 and i.Active=1 and CheckedBy is null  
   and InvoiceID in (select InvoiceID from InvoiceDetail where ItemID in(3515,3522))";//and i.CreateLog='".$_SESSION['UserName']."'
    $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,JSON_PRESERVE_ZERO_FRACTION);

      }//end if 
        else
    {
    $GodownID=$_GET['GodownID'];
    if(isset($_GET['isBooth']) && $_GET['isBooth']!="")
    {
        $isBooth=" and InvoiceDate='".Date("Y-m-d")."'";
    }
    else
    {
      $isBooth="";
    }
   /*$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
   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.GodownID=".$GodownID." and i.InvoiceType=5 and i.InvoiceStatus<3";*/
    $sql="select convert(date,InvoiceDate) as InvoiceDate1,convert(date,DeliveryDate) as DeliveryDate1,(select 
' Bill:'+convert(varchar,isnull(sum(NetAmount),0))+' || Paid:'+convert(varchar,isnull(sum(paid),0))+' || Balance:'+convert(varchar,(isnull(sum(NetAmount),0)-isnull(sum(Paid),0))) as Balance from InvoiceMaster where InvoiceType=5 and ReferenceInvoiceID=0 
and InvoiceID in (select invoiceid from invoicemaster where InvoiceID=view_jobcard_list.InvoiceID) 
group by ReferenceInvoiceID ) as Balance1,* from view_jobcard_list where GodownID=".$GodownID." and InvoiceType=5 and InvoiceStatus<>3 and InvoiceID in (select InvoiceID from InvoiceDetail where ItemID in(3515,3522))   $isBooth";
    $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      switch ($row['InvoiceStatus']) {
        case '1':
          # code...
        $row['InvoiceStatus']="PENDING";
          break;
        case '2':
          # code...
        $row['InvoiceStatus']="ACCEPTED";
          break;
          case '3':
          # code...
        $row['InvoiceStatus']="REJECTED";
          break;
          case '4':
          # code...
        $row['InvoiceStatus']="CLOSED";
          break;
        default:
          # code...
        $row['InvoiceStatus']="";
          break;
      }
      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);
    }//end else 
  

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


    //print_r($_GET);

    $data=array();
    if(isset($_GET['search']))
    {
            $ParkingNo=    isset($_GET['ParkingNo'])?$_GET['ParkingNo']:'';
            if($ParkingNo!="")
            {
            $ParkingNo=" ParkingNo like '%".$ParkingNo."%' and "; 
            }
            else
            {
            $ParkingNo=""; 
            }
      $isBooth=(isset($_GET['isBooth'])?$_GET['isBooth']:'');
      if($isBooth!="")
      {
        if($ParkingNo=="")
        $tokendate=" InvoiceDate='".Date("Y-m-d")."' and ";
        else
        $tokendate="";

      }
      else
      {
        $tokendate="";
      }

      $Company=   isset($_GET['Company'])?$_GET['Company']:'';
      if($Company!='')
      {
        $Company="";//"c.Name like '' and ";
      }
      else
      {
        $Company="";
      }
            
            $Supplier=    isset($_GET['Supplier'])?$_GET['Supplier']:'';
            if($Supplier!="")
            {
            $Supplier=""; 
            }
            else
            {
            $Supplier=""; 
            }
            $BillDate=    isset($_GET['BillDate'])?$_GET['BillDate']:'';
            if($BillDate!="")
            {
            $BillDate=""; 
            }
            else
            {
            $BillDate=""; 
            }
            $ReferenceNo= isset($_GET['ReferenceNo'])?$_GET['ReferenceNo']:'';
            if($ReferenceNo!="")
            {
            $ReferenceNo="i.KeyField like '%".$ReferenceNo."%' and "; 
            }
            else
            {
            $ReferenceNo="";  
            }
            $Customer=    isset($_GET['Customer'])?$_GET['Customer']:'';
            if($Customer!="")
            {
            $Customer="CustomerName like '%".$Customer."%' and "; 
            }
            else
            {
            $Customer=""; 
            }
          $KeyNo=    isset($_GET['KeyNo'])?$_GET['KeyNo']:'';
            if($KeyNo!="")
            {
            $KeyNo="KeyNo like '%".$KeyNo."%' and "; 
            }
            else
            {
            $KeyNo=""; 
            }

            $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          $InvoiceStatus="i.InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="i.InvoiceStatus<>3 and "; 
          }
       $Customer_MobileNumber=   isset($_GET['Customer_MobileNumber'])?$_GET['Customer_MobileNumber']:'';    
          if($Customer_MobileNumber!="")
          {
          $Customer_MobileNumber="i.MobileNumber like '%".$Customer_MobileNumber."%' and ";  
          }
          else
          {
          $Customer_MobileNumber="";  
          }
    $Customer_PlateNumber=   isset($_GET['Customer_PlateNumber'])?$_GET['Customer_PlateNumber']:'';    
          if($Customer_PlateNumber!="")
          {
          $Customer_PlateNumber="i.PlateNumber like '%".$Customer_PlateNumber."%' and ";  
          }
          else
          {
          $Customer_PlateNumber="";  
          }
 $Customer_ChassisNumber=   isset($_GET['Customer_ChassisNumber'])?$_GET['Customer_ChassisNumber']:'';    
          if($Customer_ChassisNumber!="")
          {
          $Customer_ChassisNumber="i.ChassisNumber like '%".$Customer_ChassisNumber."%' and ";  
          }
          else
          {
          $Customer_ChassisNumber="";  
          }


          $searchbox=$Company.$Supplier.$ReferenceNo.$Customer.$InvoiceStatus.$Customer_MobileNumber.$Customer_ChassisNumber.$KeyNo.$tokendate.$ParkingNo;
      $GodownID=$_GET['GodownID'];
       $sql="select
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 as CompanyShortForm,CustomerName as JC_CustomerName,MobileNumber as JC_MobileNumber,PlateNumber as JC_PlateNumber,ChassisNumber as JC_ChassisNumber,InvoiceDate,i.KeyField as KeyField,i.CreateLog 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,i.supplierid as supplierid,i.ItemID as ITEMID,i.KeyNo as KeyNo,i.Email as Email
   from InvoiceMaster as i inner join godowns  as g on i.Shipperid=g.GodownID
   inner join godowns as c on c.GodownID=i.GodownID where ".$searchbox."  i.GodownID<>".$GodownID." and i.InvoiceType=5 and i.Active=1  and ITEMID<1";//and i.CreateLog='".$_SESSION['UserName']."'
    $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,JSON_PRESERVE_ZERO_FRACTION);

      }//end if 
        else
    {
    $GodownID=$_GET['GodownID'];
    if(isset($_GET['isBooth']) && $_GET['isBooth']!="")
    {
        $isBooth=" and InvoiceDate='".Date("Y-m-d")."'";
    }
    else
    {
      $isBooth="";
    }
   /*$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
   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.GodownID=".$GodownID." and i.InvoiceType=5 and i.InvoiceStatus<3";*/
    $sql="select convert(date,InvoiceDate) as InvoiceDate1,convert(date,DeliveryDate) as DeliveryDate1,(select 
' Bill:'+convert(varchar,isnull(sum(NetAmount),0))+' || Paid:'+convert(varchar,isnull(sum(paid),0))+' || Balance:'+convert(varchar,(isnull(sum(NetAmount),0)-isnull(sum(Paid),0))) as Balance from InvoiceMaster where InvoiceType=5 and ReferenceInvoiceID=0 
and InvoiceID in (select invoiceid from invoicemaster where InvoiceID=view_jobcard_list.InvoiceID) 
group by ReferenceInvoiceID ) as Balance1,* from view_jobcard_list where GodownID<>".$GodownID." and InvoiceType=5 and InvoiceStatus<>3 and itemid<1   $isBooth";
    $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      switch ($row['InvoiceStatus']) {
        case '1':
          # code...
        $row['InvoiceStatus']="PENDING";
          break;
        case '2':
          # code...
        $row['InvoiceStatus']="ACCEPTED";
          break;
          case '3':
          # code...
        $row['InvoiceStatus']="REJECTED";
          break;
          case '4':
          # code...
        $row['InvoiceStatus']="CLOSED";
          break;
        default:
          # code...
        $row['InvoiceStatus']="";
          break;
      }
      $data[]=$row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);
    }//end else 
  

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

    //print_r($_GET);

    $data=array();
    if(isset($_GET['search']))
    {
            $ParkingNo=    isset($_GET['ParkingNo'])?$_GET['ParkingNo']:'';
            if($ParkingNo!="")
            {
            $ParkingNo=" ParkingNo like '%".$ParkingNo."%' and "; 
            }
            else
            {
            $ParkingNo=""; 
            }
      $isBooth=(isset($_GET['isBooth'])?$_GET['isBooth']:'');
      if($isBooth!="")
      {
        if($ParkingNo=="")
        $tokendate=" InvoiceDate='".Date("Y-m-d")."' and ";
        else
        $tokendate="";

      }
      else
      {
        $tokendate="";
      }

      $Company=   isset($_GET['Company'])?$_GET['Company']:'';
      if($Company!='')
      {
        $Company="";//"c.Name like '' and ";
      }
      else
      {
        $Company="";
      }
            
            $Supplier=    isset($_GET['Supplier'])?$_GET['Supplier']:'';
            if($Supplier!="")
            {
            $Supplier=""; 
            }
            else
            {
            $Supplier=""; 
            }
            $BillDate=    isset($_GET['BillDate'])?$_GET['BillDate']:'';
            if($BillDate!="")
            {
            $BillDate=""; 
            }
            else
            {
            $BillDate=""; 
            }
            $ReferenceNo= isset($_GET['ReferenceNo'])?$_GET['ReferenceNo']:'';
            if($ReferenceNo!="")
            {
            $ReferenceNo="i.KeyField like '%".$ReferenceNo."%' and "; 
            }
            else
            {
            $ReferenceNo="";  
            }
            $Customer=    isset($_GET['Customer'])?$_GET['Customer']:'';
            if($Customer!="")
            {
            $Customer="CustomerName like '%".$Customer."%' and "; 
            }
            else
            {
            $Customer=""; 
            }
          $KeyNo=    isset($_GET['KeyNo'])?$_GET['KeyNo']:'';
            if($KeyNo!="")
            {
            $KeyNo="KeyNo like '%".$KeyNo."%' and "; 
            }
            else
            {
            $KeyNo=""; 
            }

            $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          $InvoiceStatus="i.InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="i.InvoiceStatus<>3 and "; 
          }
       $Customer_MobileNumber=   isset($_GET['Customer_MobileNumber'])?$_GET['Customer_MobileNumber']:'';    
          if($Customer_MobileNumber!="")
          {
          $Customer_MobileNumber="i.MobileNumber like '%".$Customer_MobileNumber."%' and ";  
          }
          else
          {
          $Customer_MobileNumber="";  
          }
    $Customer_PlateNumber=   isset($_GET['Customer_PlateNumber'])?$_GET['Customer_PlateNumber']:'';    
          if($Customer_PlateNumber!="")
          {
          $Customer_PlateNumber="i.PlateNumber like '%".$Customer_PlateNumber."%' and ";  
          }
          else
          {
          $Customer_PlateNumber="";  
          }
 $Customer_ChassisNumber=   isset($_GET['Customer_ChassisNumber'])?$_GET['Customer_ChassisNumber']:'';    
          if($Customer_ChassisNumber!="")
          {
          $Customer_ChassisNumber="i.ChassisNumber like '%".$Customer_ChassisNumber."%' and ";  
          }
          else
          {
          $Customer_ChassisNumber="";  
          }


          $searchbox=$Company.$Supplier.$ReferenceNo.$Customer.$InvoiceStatus.$Customer_MobileNumber.$Customer_ChassisNumber.$KeyNo.$tokendate.$ParkingNo;
      $GodownID=$_GET['GodownID'];
       $sql="select
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 as CompanyShortForm,CustomerName as JC_CustomerName,MobileNumber as JC_MobileNumber,PlateNumber as JC_PlateNumber,ChassisNumber as JC_ChassisNumber,InvoiceDate,i.KeyField as KeyField,i.CreateLog 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,i.supplierid as supplierid,i.ItemID as ITEMID,i.KeyNo as KeyNo,i.Email as Email
   from InvoiceMaster as i inner join godowns  as g on i.Shipperid=g.GodownID
   inner join godowns as c on c.GodownID=i.GodownID where ".$searchbox."  i.GodownID=".$GodownID." and i.InvoiceType=5 and i.Active=1  and ITEMID<1";//and i.CreateLog='".$_SESSION['UserName']."'
    $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);

      }//end if 
        else
    {
    $GodownID=$_GET['GodownID'];
    if(isset($_GET['isBooth']) && $_GET['isBooth']!="")
    {
        $isBooth=" and InvoiceDate='".Date("Y-m-d")."'";
    }
    else
    {
      $isBooth="";
    }
   /*$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
   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.GodownID=".$GodownID." and i.InvoiceType=5 and i.InvoiceStatus<3";*/
    $sql="select convert(date,InvoiceDate) as InvoiceDate1,convert(date,DeliveryDate) as DeliveryDate1,(select 
' Bill:'+convert(varchar,isnull(sum(NetAmount),0))+' || Paid:'+convert(varchar,isnull(sum(paid),0))+' || Balance:'+convert(varchar,(isnull(sum(NetAmount),0)-isnull(sum(Paid),0))) as Balance from InvoiceMaster where InvoiceType=5 and ReferenceInvoiceID=0 
and InvoiceID in (select invoiceid from invoicemaster where InvoiceID=view_jobcard_list.InvoiceID) 
group by ReferenceInvoiceID ) as Balance1,* from view_jobcard_list where GodownID=".$GodownID." and InvoiceType=5 and InvoiceStatus<>3 and itemid<1   $isBooth";
    $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      switch ($row['InvoiceStatus']) {
        case '1':
          # code...
        $row['InvoiceStatus']="PENDING";
          break;
        case '2':
          # code...
        $row['InvoiceStatus']="ACCEPTED";
          break;
          case '3':
          # code...
        $row['InvoiceStatus']="REJECTED";
          break;
          case '4':
          # code...
        $row['InvoiceStatus']="CLOSED";
          break;
        default:
          # code...
        $row['InvoiceStatus']="";
          break;
      }
      $data[]=$row;
    }
    echo json_encode($data);
    }//end else 
  

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

    //print_r($_GET);
      $InvoiceType=isset($_GET['InvoiceType'])?$_GET['InvoiceType']:5;
    $data=array();
    if(isset($_GET['search']))
    {
            $ParkingNo=    isset($_GET['ParkingNo'])?$_GET['ParkingNo']:'';
            if($ParkingNo!="")
            {
            $ParkingNo=" ParkingNo like '%".$ParkingNo."%' and "; 
            }
            else
            {
            $ParkingNo=""; 
            }
      $isBooth=(isset($_GET['isBooth'])?$_GET['isBooth']:'');
      if($isBooth!="")
      {
        if($ParkingNo=="")
        $tokendate=" InvoiceDate='".Date("Y-m-d")."' and ";
        else
        $tokendate="";

      }
      else
      {
        $tokendate="";
      }

      $Company=   isset($_GET['Company'])?$_GET['Company']:'';
      if($Company!='')
      {
        $Company="";//"c.Name like '' and ";
      }
      else
      {
        $Company="";
      }
            
            $Supplier=    isset($_GET['Supplier'])?$_GET['Supplier']:'';
            if($Supplier!="")
            {
            $Supplier=""; 
            }
            else
            {
            $Supplier=""; 
            }
            $BillDate=    isset($_GET['BillDate'])?$_GET['BillDate']:'';
            if($BillDate!="")
            {
            $BillDate=""; 
            }
            else
            {
            $BillDate=""; 
            }
            $ReferenceNo= isset($_GET['ReferenceNo'])?$_GET['ReferenceNo']:'';
            if($ReferenceNo!="")
            {
            $ReferenceNo="i.KeyField like '%".$ReferenceNo."%' and "; 
            }
            else
            {
            $ReferenceNo="";  
            }
            $Customer=    isset($_GET['Customer'])?$_GET['Customer']:'';
            if($Customer!="")
            {
            $Customer="CustomerName like '%".$Customer."%' and "; 
            }
            else
            {
            $Customer=""; 
            }
          $KeyNo=    isset($_GET['KeyNo'])?$_GET['KeyNo']:'';
            if($KeyNo!="")
            {
            $KeyNo="KeyNo like '%".$KeyNo."%' and "; 
            }
            else
            {
            $KeyNo=""; 
            }

            $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          $InvoiceStatus="i.InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="i.InvoiceStatus<>3 and "; 
          }
       $Customer_MobileNumber=   isset($_GET['Customer_MobileNumber'])?$_GET['Customer_MobileNumber']:'';    
          if($Customer_MobileNumber!="")
          {
          $Customer_MobileNumber="i.MobileNumber like '%".$Customer_MobileNumber."%' and ";  
          }
          else
          {
          $Customer_MobileNumber="";  
          }
    $Customer_PlateNumber=   isset($_GET['Customer_PlateNumber'])?$_GET['Customer_PlateNumber']:'';    
          if($Customer_PlateNumber!="")
          {
          $Customer_PlateNumber="i.PlateNumber like '%".$Customer_PlateNumber."%' and ";  
          }
          else
          {
          $Customer_PlateNumber="";  
          }
 $Customer_ChassisNumber=   isset($_GET['Customer_ChassisNumber'])?$_GET['Customer_ChassisNumber']:'';    
          if($Customer_ChassisNumber!="")
          {
          $Customer_ChassisNumber="i.ChassisNumber like '%".$Customer_ChassisNumber."%' and ";  
          }
          else
          {
          $Customer_ChassisNumber="";  
          }


          $searchbox=$Company.$Supplier.$ReferenceNo.$Customer.$InvoiceStatus.$Customer_MobileNumber.$Customer_ChassisNumber.$KeyNo.$tokendate.$ParkingNo;
      $GodownID=$_GET['GodownID'];
      $sql="select
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 as CompanyShortForm,CustomerName as JC_CustomerName,MobileNumber as JC_MobileNumber,PlateNumber as JC_PlateNumber,ChassisNumber as JC_ChassisNumber,InvoiceDate,i.KeyField as KeyField,i.CreateLog as CreateByUserName,i.EditLog as Cashier,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,i.supplierid as supplierid,i.ItemID as ITEMID,i.KeyNo as KeyNo,i.Email as Email,i.paid as paid,i.VoucherDateTime as VoucherDateTime
   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 ITEMID<1 and BranchID=".$_SESSION['BRANCHID'];//and i.CreateLog='".$_SESSION['UserName']."'
    $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      
      $InvoiceID=$row['InvoiceID'];
  //code for some changes HERE 
if($InvoiceID!="")
    {
       echo $sql1="   select i.ID as itemid,i.name as itemname,i.barcode as barcode,cast(d.unitprice as numeric(7,2)) as unitprice,qty,amount,cast(d.vatpercent as numeric(7,2)) as vatpercent,cast(VATAmount as numeric(7,2)) as vatamount,cast(discountpercent as numeric(7,2)) as discountpercent,cast(discountamount as numeric(7,2)) as discountamount,'' as partnumber ,d.Attr1 as specification,(select ide.Name from inventory as ide where  ide.ID=i.under) as category,d.Attr2 as partnumber,netamount,d.Attr3 as JobCardItem,d.Attr4 as Attr4,
   ReferenceInvoiceID,ReferenceTransactionID,d.[guid] as guid,ParentGUid as referenceguid,
   d.Narration as detailnarration,transactionid,d.StockQty as StockQty,d.itemjson as itemjson,
    i.keyfield as itemkeyfield,i.AdditionalInfo2 as code,Make as brand,Rating as color,Model as size  from invoiceDetail as d left outer join inventory as i on i.ID=d.ItemID
   
   where InvoiceID=".$InvoiceID;
       $result1=odbc_exec($connection, $sql1) or die(odbc_error().$sql1);
  //'.$row["CategoryID"].'
  //$limit=425;//
  //echo  odbc_num_rows($result);
        while ($row1 = odbc_fetch_array($result1)) {
            foreach ($row1 as $key => $value) {
          # code...
          $row1[$key]=utf8_encode($value);
        }
      $row['detailitems'][]=$row1;
      }//end while
    
    foreach ($row as $key => $value) {
        # code...
        $row[$key]=utf8_encode($value);
      }
        $data[]=$row;
      }//end if InvoiceID
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);

      }//end if 
        else
    {
    $GodownID=$_GET['GodownID'];
    if(isset($_GET['isBooth']) && $_GET['isBooth']!="")
    {
        $isBooth="";// and InvoiceDate='".Date("Y-m-d")."'";
    }
    else
    {
      $isBooth="";
    }
   /*$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
   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.GodownID=".$GodownID." and i.InvoiceType=5 and i.InvoiceStatus<3";*/
    $sql="select convert(date,InvoiceDate) as InvoiceDate1,convert(date,DeliveryDate) as DeliveryDate1,(select 
' Bill:'+convert(varchar,isnull(sum(NetAmount),0))+' || Paid:'+convert(varchar,isnull(sum(paid),0))+' || Balance:'+convert(varchar,(isnull(sum(NetAmount),0)-isnull(sum(Paid),0))) as Balance from InvoiceMaster where InvoiceType=5 and ReferenceInvoiceID=0 
and InvoiceID in (select invoiceid from invoicemaster where InvoiceID=view_jobcard_list.InvoiceID) 
group by ReferenceInvoiceID ) as Balance1,* from view_jobcard_list where GodownID=".$GodownID." and InvoiceType=$InvoiceType and InvoiceStatus<>3 and itemid<1  and CreateLog='".$_SESSION['UserName']."' $isBooth";
    $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      switch ($row['InvoiceStatus']) {
        case '1':
          # code...
        $row['InvoiceStatus']="PENDING";
          break;
        case '2':
          # code...
        $row['InvoiceStatus']="ACCEPTED";
          break;
          case '3':
          # code...
        $row['InvoiceStatus']="REJECTED";
          break;
          case '4':
          # code...
        $row['InvoiceStatus']="CLOSED";
          break;
        default:
          # code...
        $row['InvoiceStatus']="";
          break;
      
  $InvoiceID=$row['InvoiceID'];
  //code for some changes HERE 
if($InvoiceID!="")
    {
       $sql1="   select i.ID as itemid,i.name as itemname,i.barcode as barcode,cast(d.unitprice as numeric(7,2)) as unitprice,qty,amount,cast(d.vatpercent as numeric(7,2)) as vatpercent,cast(VATAmount as numeric(7,2)) as vatamount,cast(discountpercent as numeric(7,2)) as discountpercent,cast(discountamount as numeric(7,2)) as discountamount,'' as partnumber ,d.Attr1 as specification,(select ide.Name from inventory as ide where  ide.ID=i.under) as category,d.Attr2 as partnumber,netamount,d.Attr3 as JobCardItem,d.Attr4 as Attr4,
   ReferenceInvoiceID,ReferenceTransactionID,d.[guid] as guid,ParentGUid as referenceguid,
   d.Narration as detailnarration,transactionid,d.StockQty as StockQty,d.itemjson as itemjson,
    i.keyfield as itemkeyfield,i.AdditionalInfo2 as code,Make as brand,Rating as color,Model as size  from invoiceDetail as d left outer join inventory as i on i.ID=d.ItemID
   
   where InvoiceID=".$InvoiceID;
       $result1=odbc_exec($connection, $sql1) or die(odbc_error().$sql1);
  //'.$row["CategoryID"].'
  //$limit=425;//
  //echo  odbc_num_rows($result);
        while ($row1 = odbc_fetch_array($result1)) {
            foreach ($row1 as $key => $value) {
          # code...
          $row1[$key]=utf8_encode($value);
        }
      $row['detailitems'][]=$row1;
      }//end while
      $data[]=$row;
      }//end if InvoiceID
      
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);
    }//end else 
  
    }
  }
    if($_GET['action']=="jobcardlistSpecial")
    {

    //print_r($_GET);
      $GodownID=$_GET['CompanyID'];
$InvoiceType=isset($_GET['InvoiceType'])?$_GET['InvoiceType']:3;
    $data=array();
    if(isset($_GET['search']))
    {
            $ParkingNo=    isset($_GET['ParkingNo'])?$_GET['ParkingNo']:'';
            if($ParkingNo!="")
            {
            $ParkingNo=" ParkingNo like '%".$ParkingNo."%' and "; 
            }
            else
            {
            $ParkingNo=""; 
            }
      $isBooth=(isset($_GET['isBooth'])?$_GET['isBooth']:'');
      if($isBooth!="")
      {
        if($ParkingNo=="")
        $tokendate=" InvoiceDate='".Date("Y-m-d")."' and ";
        else
        $tokendate="";

      }
      else
      {
        $tokendate="";
      }

      $Company=   isset($_GET['Company'])?$_GET['Company']:'';
      if($Company!='' && $CompanyID>0)
      {
        $Company=" i.GodownID=".$Company." and ";//"c.Name like '' and ";
      }
      else
      {
        $Company="";
      }
            
            $Supplier=    isset($_GET['Supplier'])?$_GET['Supplier']:'';
            if($Supplier!="")
            {
            $Supplier=""; 
            }
            else
            {
            $Supplier=""; 
            }
            $BillDate=    isset($_GET['BillDate'])?$_GET['BillDate']:'';
            if($BillDate!="")
            {
             $tokendate=" InvoiceDate='".$BillDate."' and ";
            $BillDate=""; 
            }
            else
            {
            $BillDate=" InvoiceDate='".Date("Y-m-d")."' and "; 
            }
            $ReferenceNo= isset($_GET['ReferenceNo'])?$_GET['ReferenceNo']:'';
            if($ReferenceNo!="")
            {
            $ReferenceNo="i.KeyField like '%".$ReferenceNo."%' and "; 
            }
            else
            {
            $ReferenceNo="";  
            }
            $Customer=    isset($_GET['Customer'])?$_GET['Customer']:'';
            if($Customer!="")
            {
            $Customer="CustomerName like '%".$Customer."%' and "; 
            }
            else
            {
            $Customer=""; 
            }
          $KeyNo=    isset($_GET['KeyNo'])?$_GET['KeyNo']:'';
            if($KeyNo!="")
            {
            $KeyNo="KeyNo like '%".$KeyNo."%' and "; 
            }
            else
            {
            $KeyNo=""; 
            }

            $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          $InvoiceStatus="i.InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="i.InvoiceStatus<>3 and "; 
          }
       $Customer_MobileNumber=   isset($_GET['Customer_MobileNumber'])?$_GET['Customer_MobileNumber']:'';    
          if($Customer_MobileNumber!="")
          {
          $Customer_MobileNumber="i.MobileNumber like '%".$Customer_MobileNumber."%' and ";  
          }
          else
          {
          $Customer_MobileNumber="";  
          }
    $Customer_PlateNumber=   isset($_GET['Customer_PlateNumber'])?$_GET['Customer_PlateNumber']:'';    
          if($Customer_PlateNumber!="")
          {
          $Customer_PlateNumber="i.PlateNumber like '%".$Customer_PlateNumber."%' and ";  
          }
          else
          {
          $Customer_PlateNumber="";  
          }
 $Customer_ChassisNumber=   isset($_GET['Customer_ChassisNumber'])?$_GET['Customer_ChassisNumber']:'';    
          if($Customer_ChassisNumber!="")
          {
          $Customer_ChassisNumber="i.ChassisNumber like '%".$Customer_ChassisNumber."%' and ";  
          }
          else
          {
          $Customer_ChassisNumber="";  
          }


          $searchbox=$Company.$Supplier.$ReferenceNo.$Customer.$InvoiceStatus.$Customer_MobileNumber.$Customer_ChassisNumber.$KeyNo.$BillDate.$ParkingNo;
      $GodownID=$_GET['GodownID'];
       $sql="select
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 as CompanyShortForm,(case when isnull(i.CustomerID,0)<1 then 'WALK IN CUSTOMER' else (select COAName from accounts where COAID=i.CustomerID)) as JC_CustomerName1,MobileNumber as JC_MobileNumber,PlateNumber as JC_PlateNumber,ChassisNumber as JC_ChassisNumber,InvoiceDate,i.KeyField as KeyField,i.CreateLog as CreateByUserName,i.EditLog as Cashier,InvoiceID,InvoiceDate 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,i.supplierid as supplierid,i.ItemID as ITEMID,i.KeyNo as KeyNo,i.Email as Email,i.Received as paid,i.VoucherDateTime as VoucherDateTime,(isNull(NetAmount,0)-isNull(Received,0)) as Balance2
   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 i.CustomerID<>20";//and i.CreateLog='".$_SESSION['UserName']."'
    $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);

      }//end if 
        else
    {
    $GodownID=isset($_GET['GodownID'])?$_GET['GodownID']:$_GET['CompanyID'];
    if(isset($_GET['isBooth']) && $_GET['isBooth']!="")
    {
        $isBooth="";// and InvoiceDate='".Date("Y-m-d")."'";
    }
    else
    {
      $isBooth="";
    }
      $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          //$InvoiceStatus="InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="1,2,4"; 
          }
           $BillDate=    isset($_GET['BillDate'])?$_GET['BillDate']:'';
            if($BillDate!="")
            {
             $tokendate=" InvoiceDate='".$BillDate."' and ";
            $BillDate=" InvoiceDate='".$BillDate."' and "; 
            }
            else
            {
            $BillDate=" InvoiceDate='".Date("Y-m-d")."' and "; 
            }

            $ReferenceNo= isset($_GET['ReferenceNo'])?$_GET['ReferenceNo']:'';
            if($ReferenceNo!="")
            {
            $ReferenceNo=" KeyField like '%".$ReferenceNo."%' and "; 
            }
            else
            {
            $ReferenceNo="";  
            }
             $Company=   isset($_GET['Company'])?$_GET['Company']:'';
      if($Company!='' && $Company>0)
      {
        $Company=" GodownID=".$Company." and ";//"c.Name like '' and ";
      }
      else
      {
        $Company="";
      }
     
             $searchbox=$ReferenceNo.$BillDate.$Company;
   /*$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
   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.GodownID=".$GodownID." and i.InvoiceType=5 and i.InvoiceStatus<3";*/
   //and CreateLog='".$_SESSION['UserName']."'
  // GodownID=".$GodownID."
     $sql="select convert(date,InvoiceDate) as InvoiceDate1,convert(date,DeliveryDate) as DeliveryDate1,Balance as Balance1,(select (isNull(NetAmount,0)-isNull(Paid,0)) from Salesinvoicemaster where InvoiceID=view_jobcard_list_special.InvoiceID) as Balance2,(case when isnull(view_jobcard_list_special.CustomerID,0)<1 then 'WALK IN CUSTOMER' else (select COAName from accounts where COAID=view_jobcard_list_special.CustomerID) end) as JC_CustomerName1,convert(Numeric(9,2),NetAmount) as NetAmount1, * from [view_jobcard_list_special] where $searchbox InvoiceType=$InvoiceType and  CustomerID<>20  $isBooth";
    $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      switch ($row['InvoiceStatus']) {
        case '1':
          # code...
        $row['InvoiceStatus']="PENDING";
          break;
        case '2':
          # code...
        $row['InvoiceStatus']="ACCEPTED";
          break;
          case '3':
          # code...
        $row['InvoiceStatus']="REJECTED";
          break;
          case '4':
          # code...
        $row['InvoiceStatus']="CLOSED";
          break;
        default:
          # code...
        $row['InvoiceStatus']="";
          break;
      }
      //code for details 
      $InvoiceID=$row['InvoiceID'];
      if($InvoiceID!="")
    {
$sql1="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as ItemCompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,(select Under from inventory where id=i.Under) as Category,(select Name from inventory where id=i.Under) as SubCategory ,i.Under as SubCategoryID,i.Name as itemname,i.Model as brand,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,d.DiscountAmount as discountamount,(select Keyfield from Salesinvoicemaster where Invoiceid=d.Invoiceid) as KeyField
   ,unitprice,amount,discountpercent,0 as vatpercent,0 as vatamount,netamount,transactionid,d.Narration as detailnarration,d.Attr1 as Attr1,d.Attr2 as Attr2,'' as ItemJson,AttrPictureLocation1 as Picture1,AttrPictureLocation2 as Picture2 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."  order by i.CompanyID";
       $result1=odbc_exec($connection, $sql1) or die(odbc_error().$sql1);
  //'.$row["CategoryID"].'
  //$limit=425;//
  //echo  odbc_num_rows($result);
        while ($row1 = odbc_fetch_array($result1)) {
            foreach ($row1 as $key => $value) {
          # code...
          $row1[$key]=utf8_encode($value);
        }
      $row['detailitems'][]=$row1;
      }//end while
  $data[]=$row;
      
      
      }//end else 
      //$data[]=$row;
    }
    echo json_encode($data);
    }//end else 
  
    }
    if($_GET['action']=="Salesjobcardlist")
    {

    //print_r($_GET);
$InvoiceType=isset($_GET['InvoiceType'])?$_GET['InvoiceType']:3;
    $data=array();
    if(isset($_GET['search']))
    {
            $ParkingNo=    isset($_GET['ParkingNo'])?$_GET['ParkingNo']:'';
            if($ParkingNo!="")
            {
            $ParkingNo=" ParkingNo like '%".$ParkingNo."%' and "; 
            }
            else
            {
            $ParkingNo=""; 
            }
      $isBooth=(isset($_GET['isBooth'])?$_GET['isBooth']:'');
      if($isBooth!="")
      {
        if($ParkingNo=="")
        $tokendate="";// InvoiceDate='".Date("Y-m-d")."' and ";
        else
        $tokendate="";

      }
      else
      {
        $tokendate="";
      }

      $Company=   isset($_GET['Company'])?$_GET['Company']:'';
      if($Company!='')
      {
        $Company="";//"c.Name like '' and ";
      }
      else
      {
        $Company="";
      }
            
            $Supplier=    isset($_GET['Supplier'])?$_GET['Supplier']:'';
            if($Supplier!="")
            {
            $Supplier=""; 
            }
            else
            {
            $Supplier=""; 
            }
            $BillDate=    isset($_GET['BillDate'])?$_GET['BillDate']:'';
            if($BillDate!="")
            {
             $tokendate=" InvoiceDate='".$BillDate."' and ";
            $BillDate=" InvoiceDate='".$BillDate."' and ";  
            }
            else
            {
            $BillDate="convert(date,InvoiceDate)='".Date("Y-m-d")."'"; 
            }
            $ReferenceNo= isset($_GET['ReferenceNo'])?$_GET['ReferenceNo']:'';
            if($ReferenceNo!="")
            {
            $ReferenceNo="i.KeyField like '%".$ReferenceNo."%' and "; 
            }
            else
            {
            $ReferenceNo="";  
            }
            $Customer=    isset($_GET['Customer'])?$_GET['Customer']:'';
            if($Customer!="")
            {
            $Customer="CustomerName like '%".$Customer."%' and "; 
            }
            else
            {
            $Customer=""; 
            }
          $KeyNo=    isset($_GET['KeyNo'])?$_GET['KeyNo']:'';
            if($KeyNo!="")
            {
            $KeyNo="KeyNo like '%".$KeyNo."%' and "; 
            }
            else
            {
            $KeyNo=""; 
            }

            $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          $InvoiceStatus="i.InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="i.InvoiceStatus<>3 and "; 
          }
       $Customer_MobileNumber=   isset($_GET['Customer_MobileNumber'])?$_GET['Customer_MobileNumber']:'';    
          if($Customer_MobileNumber!="")
          {
          $Customer_MobileNumber="i.MobileNumber like '%".$Customer_MobileNumber."%' and ";  
          }
          else
          {
          $Customer_MobileNumber="";  
          }
    $Customer_PlateNumber=   isset($_GET['Customer_PlateNumber'])?$_GET['Customer_PlateNumber']:'';    
          if($Customer_PlateNumber!="")
          {
          $Customer_PlateNumber="i.PlateNumber like '%".$Customer_PlateNumber."%' and ";  
          }
          else
          {
          $Customer_PlateNumber="";  
          }
 $Customer_ChassisNumber=   isset($_GET['Customer_ChassisNumber'])?$_GET['Customer_ChassisNumber']:'';    
          if($Customer_ChassisNumber!="")
          {
          $Customer_ChassisNumber="i.ChassisNumber like '%".$Customer_ChassisNumber."%' and ";  
          }
          else
          {
          $Customer_ChassisNumber="";  
          }


          $searchbox=$Company.$Supplier.$ReferenceNo.$Customer.$InvoiceStatus.$Customer_MobileNumber.$Customer_ChassisNumber.$KeyNo.$tokendate.$ParkingNo;
      $GodownID=$_GET['GodownID'];
      if($_SESSION['UserName']=="admin")
      {
        $sql="select
      
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 as CompanyShortForm,CustomerName as JC_CustomerName,MobileNumber as JC_MobileNumber,PlateNumber as JC_PlateNumber,ChassisNumber as JC_ChassisNumber,InvoiceDate,i.KeyField as KeyField,i.CreateLog as CreateByUserName,i.EditLog as Cashier,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,i.supplierid as supplierid,i.ItemID as ITEMID,i.KeyNo as KeyNo,i.Email as Email,i.Received as paid,i.VoucherDateTime as VoucherDateTime,(isNull(NetAmount,0)-isNull(Received,0)) as Balance2
   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.InvoiceType=$InvoiceType and i.Active=1 ";
    }
    else
    {
    
        $sql="select
      
    ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 as CompanyShortForm,CustomerName as JC_CustomerName,MobileNumber as JC_MobileNumber,PlateNumber as JC_PlateNumber,ChassisNumber as JC_ChassisNumber,InvoiceDate,i.KeyField as KeyField,i.CreateLog as CreateByUserName,i.EditLog as Cashier,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,i.supplierid as supplierid,i.ItemID as ITEMID,i.KeyNo as KeyNo,i.Email as Email,i.Received as paid,i.VoucherDateTime as VoucherDateTime,(isNull(NetAmount,0)-isNull(Received,0)) as Balance2
   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.InvoiceType=$InvoiceType and i.Active=1 and i.CreateLog='".$_SESSION['UserName']."'";
      
    }
   //
    $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);
      }
    $InvoiceID=$row['InvoiceID'];
      if($InvoiceID!="")
    {
       $sql1="   select i.ID as itemid,i.name as itemname,i.barcode as barcode,cast(d.unitprice as numeric(7,2)) as unitprice,qty,amount,cast(d.vatpercent as numeric(7,2)) as vatpercent,cast(VATAmount as numeric(7,2)) as vatamount,cast(discountpercent as numeric(7,2)) as discountpercent,cast(discountamount as numeric(7,2)) as discountamount,'' as partnumber ,d.Attr1 as specification,(select ide.Name from inventory as ide where  ide.ID=i.under) as category,d.Attr2 as partnumber,netamount,d.Attr3 as JobCardItem,d.Attr4 as Attr4,
   ReferenceInvoiceID,ReferenceTransactionID,d.[guid] as guid,ParentGUid as referenceguid,
   d.Narration as detailnarration,transactionid,d.StockQty as StockQty,d.itemjson as itemjson,
    i.keyfield as itemkeyfield,i.AdditionalInfo2 as code,Make as brand,Rating as color,Model as size  from salesinvoiceDetail as d left outer join inventory as i on i.ID=d.ItemID
   
   where InvoiceID=".$InvoiceID;
       $result1=odbc_exec($connection, $sql1) or die(odbc_error().$sql1);
  //'.$row["CategoryID"].'
  //$limit=425;//
  //echo  odbc_num_rows($result);
        while ($row1 = odbc_fetch_array($result1)) {
            foreach ($row1 as $key => $value) {
          # code...
          $row1[$key]=utf8_encode($value);
        }
      $row['detailitems'][]=$row1;
      }//end while
    
/*    foreach ($row as $key => $value) {
        # code...
        $row[$key]=utf8_encode($value);
      }*/
      //  $data[]=$row;
      }//end if InvoiceID
      $data[]=$row;
    }
    echo json_encode($data);

      }//end if 
        else
    {
    $GodownID=isset($_GET['GodownID'])?$_GET['GodownID']:$_SESSION['CompanyID'];
    if(isset($_GET['isBooth']) && $_GET['isBooth']!="")
    {
        $isBooth="";// and InvoiceDate='".Date("Y-m-d")."'";
    }
    else
    {
      $isBooth="";
    }
      $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          //$InvoiceStatus="InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="1,2,4"; 
          }
   /*$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
   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.GodownID=".$GodownID." and i.InvoiceType=5 and i.InvoiceStatus<3";*/
   if($_SESSION['UserName']=="admin" || $_SESSION['UserName']=="ADMIN")
   {

     $sql="select convert(date,InvoiceDate) as InvoiceDate1,convert(date,DueDate) as DeliveryDate1,(select 
' Bill:'+convert(varchar,isnull(sum(NetAmount),0))+' || Paid:'+convert(varchar,isnull(sum(Received),0))+' || Balance:'+convert(varchar,(isnull(sum(NetAmount),0)-isnull(sum(Received),0))) as Balance from SalesInvoiceMaster where InvoiceType=$InvoiceType and ReferenceInvoiceID=0 
and InvoiceID in (select invoiceid from Salesinvoicemaster where InvoiceID=view_jobcard_list.InvoiceID) 
group by ReferenceInvoiceID ) as Balance1,(select (isNull(NetAmount,0)-isNull(Received,0)) from Salesinvoicemaster where InvoiceID=view_jobcard_list.InvoiceID) as Balance2,* from salesInvoiceMaster as  view_jobcard_list where InvoiceType=$InvoiceType and InvoiceStatus in ($InvoiceStatus) and active=1   $isBooth";
   }
 else
{     $sql="select convert(date,InvoiceDate) as InvoiceDate1,convert(date,DueDate) as DeliveryDate1,(select 
 ' Bill:'+convert(varchar,isnull(sum(NetAmount),0))+' || Paid:'+convert(varchar,isnull(sum(Received),0))+' || Balance:'+convert(varchar,(isnull(sum(NetAmount),0)-isnull(sum(Received),0))) as Balance from salesInvoiceMaster where InvoiceType=3 and ReferenceInvoiceID=0 
and InvoiceID in (select invoiceid from salesinvoicemaster where InvoiceID=view_jobcard_list.InvoiceID) 
group by ReferenceInvoiceID ) as Balance1,(select (isNull(NetAmount,0)-isNull(Paid,0)) from invoicemaster where InvoiceID=view_jobcard_list.InvoiceID) as Balance2,* from SalesInvoiceMaster as view_jobcard_list where GodownID=".$GodownID." and InvoiceType=$InvoiceType and InvoiceStatus in ($InvoiceStatus)   and active=1 and CreateLog='".$_SESSION['UserName']."' $isBooth";
}
    $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      switch ($row['InvoiceStatus']) {
        case '1':
          # code...
        $row['InvoiceStatus']="PENDING";
          break;
        case '2':
          # code...
        $row['InvoiceStatus']="ACCEPTED";
          break;
          case '3':
          # code...
        $row['InvoiceStatus']="REJECTED";
          break;
          case '4':
          # code...
        $row['InvoiceStatus']="CLOSED";
          break;
        default:
          # code...
        $row['InvoiceStatus']="";
          break;
          }
      $InvoiceID=$row['InvoiceID'];
          foreach ($row as $key => $value) {
        # code...
        $row[$key]=utf8_encode($value);
      }

  //code for some changes HERE 
if($InvoiceID!="")
    {
      $sql1="   select i.ID as itemid,i.name as itemname,i.barcode as barcode,cast(d.unitprice as numeric(7,2)) as unitprice,qty,amount,cast(d.TaxPercent as numeric(7,2)) as vatpercent,cast(TaxAmount as numeric(7,2)) as vatamount,cast(discountpercent as numeric(7,2)) as discountpercent,cast(discountamount as numeric(7,2)) as discountamount,'' as partnumber ,d.Attr1 as specification,(select ide.Name from inventory as ide where  ide.ID=i.under) as category,d.Attr2 as partnumber,netamount,d.Attr3 as JobCardItem,d.Attr4 as Attr4,
   ReferenceInvoiceID,0 as ReferenceTransactionID,'' as guid,'' as referenceguid,
   d.Narration as detailnarration,transactionid,0 as StockQty,'' as itemjson,
    i.keyfield as itemkeyfield,i.AdditionalInfo2 as code,Make as brand,Rating as color,Model as size  from salesinvoiceDetail as d left outer join inventory as i on i.ID=d.ItemID
   
   where InvoiceID=".$InvoiceID;
       $result1=odbc_exec($connection, $sql1) or die(odbc_error().$sql1);
  //'.$row["CategoryID"].'
  //$limit=425;//
  //echo  odbc_num_rows($result);
        while ($row1 = odbc_fetch_array($result1)) {
            foreach ($row1 as $key => $value) {
          # code...
          $row1[$key]=utf8_encode($value);
        }
      $row['detailitems'][]=$row1;
      }//end while
    
        $data[]=$row;
      }//end if InvoiceID
      
      //$data[]=$row;
    }
    echo json_encode($data);
    }//end else 
  
    }
  if($_GET['action']=="jobcardlist")
	{
		//print_r($_GET);
$InvoiceType=isset($_GET['InvoiceType'])?$_GET['InvoiceType']:5;
		$data=array();
		if(isset($_GET['search']))
		{
            $ParkingNo=    isset($_GET['ParkingNo'])?$_GET['ParkingNo']:'';
            if($ParkingNo!="")
            {
            $ParkingNo=" ParkingNo like '%".$ParkingNo."%' and "; 
            }
            else
            {
            $ParkingNo=""; 
            }
      $isBooth=(isset($_GET['isBooth'])?$_GET['isBooth']:'');
      if($isBooth!="")
      {
        if($ParkingNo=="")
        $tokendate="";// InvoiceDate='".Date("Y-m-d")."' and ";
        else
        $tokendate="";

      }
      else
      {
        $tokendate="";
      }

			$Company=		isset($_GET['Company'])?$_GET['Company']:'';
			if($Company!='')
			{
				$Company="";//"c.Name like '' and ";
			}
			else
			{
				$Company="";
			}
            
            $Supplier=		isset($_GET['Supplier'])?$_GET['Supplier']:'';
            if($Supplier!="")
            {
            $Supplier="";	
            }
            else
            {
            $Supplier="";	
            }
            $BillDate=		isset($_GET['BillDate'])?$_GET['BillDate']:'';
            if($BillDate!="")
            {
             $tokendate=" InvoiceDate='".$BillDate."' and ";
            $BillDate=" InvoiceDate='".$BillDate."' and ";	
            }
            else
            {
            $BillDate="";	
            }
            $ReferenceNo=	isset($_GET['ReferenceNo'])?$_GET['ReferenceNo']:'';
            if($ReferenceNo!="")
            {
            $ReferenceNo="i.KeyField like '%".$ReferenceNo."%' and ";	
            }
            else
            {
            $ReferenceNo="";	
            }
            $Customer=		isset($_GET['Customer'])?$_GET['Customer']:'';
            if($Customer!="")
            {
            $Customer="CustomerName like '%".$Customer."%' and ";	
            }
            else
            {
            $Customer="";	
            }
          $KeyNo=    isset($_GET['KeyNo'])?$_GET['KeyNo']:'';
            if($KeyNo!="")
            {
            $KeyNo="KeyNo like '%".$KeyNo."%' and "; 
            }
            else
            {
            $KeyNo=""; 
            }

            $InvoiceStatus=		isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';		
          if($InvoiceStatus!="")
	        {
	        $InvoiceStatus="i.InvoiceStatus =".$InvoiceStatus." and ";	
	        }
	        else
	        {
	        $InvoiceStatus="i.InvoiceStatus<>3 and ";	
	        }
       $Customer_MobileNumber=   isset($_GET['Customer_MobileNumber'])?$_GET['Customer_MobileNumber']:'';    
          if($Customer_MobileNumber!="")
          {
          $Customer_MobileNumber="i.MobileNumber like '%".$Customer_MobileNumber."%' and ";  
          }
          else
          {
          $Customer_MobileNumber="";  
          }
    $Customer_PlateNumber=   isset($_GET['Customer_PlateNumber'])?$_GET['Customer_PlateNumber']:'';    
          if($Customer_PlateNumber!="")
          {
          $Customer_PlateNumber="i.PlateNumber like '%".$Customer_PlateNumber."%' and ";  
          }
          else
          {
          $Customer_PlateNumber="";  
          }
 $Customer_ChassisNumber=   isset($_GET['Customer_ChassisNumber'])?$_GET['Customer_ChassisNumber']:'';    
          if($Customer_ChassisNumber!="")
          {
          $Customer_ChassisNumber="i.ChassisNumber like '%".$Customer_ChassisNumber."%' and ";  
          }
          else
          {
          $Customer_ChassisNumber="";  
          }


	        $searchbox=$Company.$Supplier.$ReferenceNo.$Customer.$InvoiceStatus.$Customer_MobileNumber.$Customer_ChassisNumber.$KeyNo.$tokendate.$ParkingNo;
    	$GodownID=$_GET['GodownID'];
	      $sql="select
		ROW_NUMBER() OVER (
      PARTITION BY [InvoiceType]
      ORDER BY [InvoiceType]
   ) row_num,c.AdditionalInfo1 as CompanyShortForm,CustomerName as JC_CustomerName,MobileNumber as JC_MobileNumber,PlateNumber as JC_PlateNumber,ChassisNumber as JC_ChassisNumber,InvoiceDate,i.KeyField as KeyField,i.CreateLog as CreateByUserName,i.EditLog as Cashier,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,i.supplierid as supplierid,i.ItemID as ITEMID,i.KeyNo as KeyNo,i.Email as Email,i.paid as paid,i.VoucherDateTime as VoucherDateTime,(isNull(NetAmount,0)-isNull(Paid,0)) as Balance2
   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.InvoiceType=$InvoiceType and i.Active=1  and ITEMID<1";//and i.CreateLog='".$_SESSION['UserName']."'
		$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);
      }
		$InvoiceID=$row['InvoiceID'];
      if($InvoiceID!="")
    {
       $sql1="   select i.ID as itemid,i.name as itemname,i.barcode as barcode,cast(d.unitprice as numeric(7,2)) as unitprice,qty,amount,cast(d.vatpercent as numeric(7,2)) as vatpercent,cast(VATAmount as numeric(7,2)) as vatamount,cast(discountpercent as numeric(7,2)) as discountpercent,cast(discountamount as numeric(7,2)) as discountamount,'' as partnumber ,d.Attr1 as specification,(select ide.Name from inventory as ide where  ide.ID=i.under) as category,d.Attr2 as partnumber,netamount,d.Attr3 as JobCardItem,d.Attr4 as Attr4,d.StandardPrice3 as Cost,
   ReferenceInvoiceID,ReferenceTransactionID,d.[guid] as guid,ParentGUid as referenceguid,
   d.Narration as detailnarration,transactionid,d.StockQty as StockQty,d.itemjson as itemjson,
    i.keyfield as itemkeyfield,i.AdditionalInfo2 as code,Make as brand,Rating as color,Model as size  from invoiceDetail as d left outer join inventory as i on i.ID=d.ItemID
   
   where InvoiceID=".$InvoiceID;
       $result1=odbc_exec($connection, $sql1) or die(odbc_error().$sql1);
  //'.$row["CategoryID"].'
  //$limit=425;//
  //echo  odbc_num_rows($result);
        while ($row1 = odbc_fetch_array($result1)) {
            foreach ($row1 as $key => $value) {
          # code...
          $row1[$key]=utf8_encode($value);
        }
      $row['detailitems'][]=$row1;
      }//end while
    
/*    foreach ($row as $key => $value) {
        # code...
        $row[$key]=utf8_encode($value);
      }*/
      //  $data[]=$row;
      }//end if InvoiceID
		  $data[]=$row;
    }
		echo json_encode($data);

    	}//end if 
        else
		{
		$GodownID=isset($_GET['GodownID'])?$_GET['GodownID']:$_SESSION['CompanyID'];
    if(isset($_GET['isBooth']) && $_GET['isBooth']!="")
    {
        $isBooth="";// and InvoiceDate='".Date("Y-m-d")."'";
    }
    else
    {
      $isBooth="";
    }
      $InvoiceStatus=   isset($_GET['InvoiceStatus'])?$_GET['InvoiceStatus']:'';    
          if($InvoiceStatus!="")
          {
          //$InvoiceStatus="InvoiceStatus =".$InvoiceStatus." and ";  
          }
          else
          {
          $InvoiceStatus="1,2,4"; 
          }
	 /*$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
   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.GodownID=".$GodownID." and i.InvoiceType=5 and i.InvoiceStatus<3";*/
   if($_SESSION['UserName']=="admin" || $_SESSION['UserName']=="ADMIN")
   {

     $sql="select convert(date,InvoiceDate) as InvoiceDate1,convert(date,DeliveryDate) as DeliveryDate1,(select 
' Bill:'+convert(varchar,isnull(sum(NetAmount),0))+' || Paid:'+convert(varchar,isnull(sum(paid),0))+' || Balance:'+convert(varchar,(isnull(sum(NetAmount),0)-isnull(sum(Paid),0))) as Balance from InvoiceMaster where InvoiceType=$InvoiceType and ReferenceInvoiceID=0 
and InvoiceID in (select invoiceid from invoicemaster where InvoiceID=view_jobcard_list.InvoiceID) 
group by ReferenceInvoiceID ) as Balance1,(select (isNull(NetAmount,0)-isNull(Paid,0)) from invoicemaster where InvoiceID=view_jobcard_list.InvoiceID) as Balance2,* from view_jobcard_list where InvoiceType=$InvoiceType and InvoiceStatus in ($InvoiceStatus)   $isBooth";
   }
 else
{     $sql="select convert(date,InvoiceDate) as InvoiceDate1,convert(date,DeliveryDate) as DeliveryDate1,(select 
   
' Bill:'+convert(varchar,isnull(sum(NetAmount),0))+' || Paid:'+convert(varchar,isnull(sum(paid),0))+' || Balance:'+convert(varchar,(isnull(sum(NetAmount),0)-isnull(sum(Paid),0))) as Balance from InvoiceMaster where InvoiceType=5 and ReferenceInvoiceID=0 
and InvoiceID in (select invoiceid from invoicemaster where InvoiceID=view_jobcard_list.InvoiceID) 
group by ReferenceInvoiceID ) as Balance1,(select (isNull(NetAmount,0)-isNull(Paid,0)) from invoicemaster where InvoiceID=view_jobcard_list.InvoiceID) as Balance2,* from view_jobcard_list where GodownID=".$GodownID." and InvoiceType=$InvoiceType and InvoiceStatus in ($InvoiceStatus) and itemid<1  and CreateLog='".$_SESSION['UserName']."' $isBooth";
}
		$result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
		while($row=odbc_fetch_array($result))
		{
      switch ($row['InvoiceStatus']) {
        case '1':
          # code...
        $row['InvoiceStatus']="PENDING";
          break;
        case '2':
          # code...
        $row['InvoiceStatus']="ACCEPTED";
          break;
          case '3':
          # code...
        $row['InvoiceStatus']="REJECTED";
          break;
          case '4':
          # code...
        $row['InvoiceStatus']="CLOSED";
          break;
        default:
          # code...
        $row['InvoiceStatus']="";
          break;
          }
      $InvoiceID=$row['InvoiceID'];
          foreach ($row as $key => $value) {
        # code...
        $row[$key]=utf8_encode($value);
      }

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

    $data=array();
    /*$offset=0;
    $limit=1;*/
    if(isset($_GET['offset']) && $_GET['offset']>0)
    {
      $offset=$_GET['offset'];
    }
    else
    {
      $offset=0;
    }
    if(isset($_GET['limit']) && $_GET['limit']>0)
    {
      $limit=$_GET['limit'];
    }
    else
    {
      $limit=1;
    }

    if(isset($_GET['InvoiceID']) && $_GET['InvoiceID']>0)
    {
    $InvoiceID="InvoiceID =".$_GET['InvoiceID']." and ";
    }
    else
    {
     $InvoiceID="";
     
    }
           if((isset($_GET['startdate']) &&  $_GET['startdate']!="undefined" && $_GET['startdate']!="")  && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
            {
                $start=$_GET['startdate'];
                $end=$_GET['enddate'];
                $date="convert(date,InvoiceDate) Between '$start' and '$end' and ";
            }
            else
            {
                $date="";
            }

            if(isset($_GET['supplier']) && $_GET['supplier']!="" && $_GET['supplier']!="undefined")
            {
                $supplier=$_GET['supplier'];
                $supplier="supplierid=$supplier and ";
            }
            else
            {
                $supplier="";
            }

            if(isset($_GET['companyid']) && $_GET['companyid']!="" && $_GET['companyid']!="undefined")
            {
                $companyid=$_GET['companyid'];
                $companyid="InvoiceMaster.GodownID=$companyid and ";
            }
            else
            {
                $companyid="";
            }
        if(isset($_GET['company']) && $_GET['company']!="" && $_GET['company']!="undefined")
            {
                $companyid=$_GET['company'];
                $companyid="InvoiceMaster.GodownID=$companyid and ";
            }
            else
            {
                $companyid="";
            }
            
            $searchbox="".$date."".$supplier."".$companyid.$InvoiceID;


    $sqlcount="select count(*) as total from  InvoiceMaster left outer join godowns on godowns.GodownID=InvoiceMaster.Shipperid
   left outer join accounts on invoicemaster.supplierid=accounts.coaid where $searchbox  invoicetype=2";
   $resultcount=odbc_exec($connection,$sqlcount);
   if(odbc_num_rows($resultcount)>0)
   {
    $rowcount=odbc_fetch_array($resultcount);
    $totalrecord=$rowcount['total'];
   }
    $fetch="OFFSET $offset ROWS 
FETCH NEXT $limit ROWS ONLY";
     $sql="   select ROW_NUMBER() OVER (
      ORDER BY [InvoiceID]
   ) row_num,InvoiceID,CheckInDateTime as CheckInTime,CheckOutDateTime as CheckOutTime,fuellevel,invoicedate,deliverydate,CheckedBy as UserName,vehiclebrand,vehiclemodel,vehicletype,vehiclesize,
   vehiclecolor,vehicleyear,customertype,salesmanid,salesmanid2,challanno,supplierid,accounts.COAName as Supplier,Accounts.Attr15 as SupplierTRN,accounts.Attr11 as SupplierEmail,accounts.Attr9 as SupplierContact,notes,mobilenumber,'".$_SESSION['UserName']."' as Username
   ,customerName,platenumber,chassisnumber,invoicemaster.trnno as trnno,totalamount,discountamount,TotalTaxAmount as taxamount,netamount,mulkiyano,parkingno,keyno,invoicemaster.keyfield as keyfield,Email as email,godowns.Name as Department
   from InvoiceMaster left outer join godowns on godowns.GodownID=InvoiceMaster.Shipperid
   left outer join accounts on invoicemaster.supplierid=accounts.coaid where  $InvoiceID invoicetype=2 order by invoiceid ";
  $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);

  //$totalrecord=odbc_num_rows($resultcount);
    if($totalrecord>$offset)
  $currentpage=$offset+1;
else
  $currentpage="";

  if($totalrecord>$currentpage)
  $nextpage=$currentpage+1;
  else
  $nextpage="";
  if($currentpage>1)
  $preivouspage=$currentpage-1;
  else
  $preivouspage="";

  $lastpage=$totalrecord;

  $firstpage=1;
    $data['nav']=array('CurrentPage'=>$currentpage,'NextPage'=>$nextpage,'FirstPage'=>$firstpage,'LastPage'=>$lastpage);

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

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

    //job card details 
    
    $sql="select ROW_NUMBER() OVER (
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as ItemCompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,i.Under Category,i.Name as itemname,i.Model as brand,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,d.DiscountAmount as discountamount
   ,unitprice,amount,discountpercent,d.vatpercent as vatpercent,vatamount,netamount,transactionid,d.Narration as detailnarration,d.Attr1 as Attr1,d.Attr2 as Attr2 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) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      foreach($row as $key=>$value)
      $row[$key]=utf8_encode($value);  
     
      $data['detailitems'][]=$row;
    }   

    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);
  
  
  }
  if($_GET['action']=="getInvoiceall")
  {
    $data=array();
    if(isset($_GET['InvoiceID']) && $_GET['InvoiceID']>0)
    {
    $InvoiceID="InvoiceID =".$_GET['InvoiceID']." and ";
    }
    else
    {
     $InvoiceID="";
    }
     $sql="   select CheckInDateTime as CheckInTime,CheckOutDateTime as CheckOutTime,fuellevel,invoicedate,deliverydate,CheckedBy as UserName,vehiclebrand,vehiclemodel,vehicletype,vehiclesize,
   vehiclecolor,vehicleyear,customertype,salesmanid,salesmanid2,challanno,supplierid,accounts.COAName as Supplier,Accounts.Attr15 as SupplierTRN,accounts.Attr11 as SupplierEmail,accounts.Attr9 as SupplierContact,narration as notes,InvoiceMaster.createlog as PreparedBy,mobilenumber,notes
   ,customerName,platenumber,chassisnumber,invoicemaster.trnno as trnno,totalamount,discountamount,TotalTaxAmount as taxamount,netamount,mulkiyano,parkingno,keyno,invoicemaster.keyfield as keyfield,Email as email,godowns.Name as Department,invoicemaster.godownid as godownid
   from InvoiceMaster left outer join godowns on godowns.GodownID=InvoiceMaster.Shipperid
   left outer join accounts on invoicemaster.supplierid=accounts.coaid where $InvoiceID 1=1";
  $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
            foreach($row as $key=>$value)
      $row[$key]=utf8_encode($value); 
      $data[][]=$row;
    }

    //job card details 
    
     $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as ItemCompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,i.Under Category,i.Name as itemname,i.Model as brand,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,d.DiscountAmount as discountamount
   ,unitprice,amount,discountpercent,d.vatpercent as vatpercent,vatamount,netamount,transactionid,d.Narration as detailnarration,d.Attr1 as Attr1,d.Attr2 as Attr2,i.AdditionalInfo2 as part, 
(select KeyField from invoicemaster inm where invoiceid=d.ReferenceInvoiceID) as Reference,
(select KeyField from invoicemaster inm where invoiceid=(select InvoiceID from invoicedetail ind where TransactionID=d.ReferenceTransactionID)) as Reference1,(select Attr1+'---'+Attr2+'---'+Narration from invoicedetail ind where TransactionID=d.ReferenceTransactionID) as Narration
   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 1=1";
    $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      foreach($row as $key=>$value)
      $row[$key]=utf8_encode($value);  
     
      $data['detailitems'][]=$row;
    }   

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

    $InvoiceID=$_GET['InvoiceID'];
       $sql="   select InvoiceMaster.CreateLog as CreateLog,CheckInDateTime as CheckInTime,CheckOutDateTime as CheckOutTime,fuellevel,invoicedate,deliverydate,CheckedBy as UserName,mv.MasterValue as vehiclebrand,invoicemaster.vehiclebrand as VehicleBrandID,mv1.MasterValue as vehiclemodel,invoicemaster.vehiclemodel as VehicleModelID2,mv2.MasterValue as vehicletype,invoicemaster.vehicletype as VehicleTypeID,mv3.MasterValue as vehiclecolor,invoicemaster.VehicleColor as VehicleColorID,vehiclesize,mv4.MasterValue as vehicleyear
   ,invoicemaster.vehicleyear as VehicleYearID,customertype,invoicemaster.salesmanid as salesmanid ,invoicemaster.salesmanid2 as salesmanid2,SalesManName as salesman,challanno,supplierid,notes,mobilenumber,Narration,godownid
   ,customerName,platenumber,chassisnumber,trnno,totalamount,discountamount,TotalTaxAmount as taxamount,netamount,mulkiyano,parkingno,keyno,invoicemaster.keyfield as keyfield,Email as email
   from InvoiceMaster left outer join SalesManInformation as sim  on sim.SalesManID=invoicemaster.SalesManID2  
 left outer join Master_Values as mv  on mv.MasterValueID=invoicemaster.VehicleBrand
left outer join Master_Values as mv1  on mv1.MasterValueID=invoicemaster.vehiclemodel
 left outer join Master_Values as mv2  on mv2.MasterValueID=invoicemaster.VehicleType 
 left outer join Master_Values as mv3  on mv3.MasterValueID=invoicemaster.VehicleColor
 left outer join Master_Values as mv4 on mv4.MasterValueID=invoicemaster.VehicleYear    
   where InvoiceID=".$InvoiceID." and InvoiceType=12";
  $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $row['UserName']=$_SESSION['UserName'];
      $row['PreparedBy']=$row['CreateLog'];      
      foreach ($row as $key => $value) {
        # code...
      $row[$key]=utf8_encode($value);
      }
      $data[][]=$row;
    }


    //job card details 
    
    $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as ItemCompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,i.Under Category,i.Name as itemname,i.Model as brand,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,d.DiscountAmount as discountamount
   ,unitprice,amount,discountpercent,d.vatpercent as vatpercent,vatamount,netamount,transactionid,d.Narration as detailnarration,d.Attr1 as Attr1,d.Attr2 as Attr2,d.Attr3 as Attr3,d.Attr4 as Attr4,itemBrand,itemSize,ItemCode 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,JSON_PRESERVE_ZERO_FRACTION);
  
  }
  if($_GET['action']=="getInvoiceDM")
  {

    $InvoiceID=$_GET['InvoiceID'];
       $sql="   select InvoiceMaster.InvoiceID as InvoiceID,InvoiceMaster.CreateLog as CreateLog,CheckInDateTime as CheckInTime,CheckOutDateTime as CheckOutTime,fuellevel,invoicedate,deliverydate,CheckedBy as UserName,mv.MasterValue as vehiclebrand,invoicemaster.vehiclebrand as VehicleBrandID,mv1.MasterValue as vehiclemodel,invoicemaster.vehiclemodel as VehicleModelID2,mv2.MasterValue as vehicletype,invoicemaster.vehicletype as VehicleTypeID,mv3.MasterValue as vehiclecolor,invoicemaster.VehicleColor as VehicleColorID,vehiclesize,mv4.MasterValue as vehicleyear
   ,invoicemaster.vehicleyear as VehicleYearID,customertype,invoicemaster.salesmanid as salesmanid ,invoicemaster.salesmanid2 as salesmanid2,SalesManName as salesman,challanno,supplierid,notes,mobilenumber,Narration,godownid
   ,customerName,platenumber,chassisnumber,trnno,totalamount,discountamount,TotalTaxAmount as taxamount,netamount,mulkiyano,parkingno,keyno,invoicemaster.keyfield as keyfield,Email as email
   from InvoiceMaster left outer join SalesManInformation as sim  on sim.SalesManID=invoicemaster.SalesManID2  
 left outer join Master_Values as mv  on mv.MasterValueID=invoicemaster.VehicleBrand
left outer join Master_Values as mv1  on mv1.MasterValueID=invoicemaster.vehiclemodel
 left outer join Master_Values as mv2  on mv2.MasterValueID=invoicemaster.VehicleType 
 left outer join Master_Values as mv3  on mv3.MasterValueID=invoicemaster.VehicleColor
 left outer join Master_Values as mv4 on mv4.MasterValueID=invoicemaster.VehicleYear    
   where InvoiceID=".$InvoiceID." and InvoiceType=5";
  $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $row['UserName']=$_SESSION['UserName'];
      $row['PreparedBy']=$row['CreateLog'];      
      foreach ($row as $key => $value) {
        # code...
      $row[$key]=utf8_encode($value);
      }
      $data[][]=$row;
    }
// warning list 
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars from [InvoiceMaster_JobDetail] as ijb where TextBoxName='DM' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['dm'][]=$row;
    }
/*$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars from [InvoiceMaster_JobDetail] as ijb where TextBoxName='CheckList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['CheckList'][]=$row;
    }
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars,PictureLocation from [InvoiceMaster_JobDetail] as ijb where TextBoxName='InspectionList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['InspectionList'][]=$row;
    }   
*/
    //job card details 
    
    $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as ItemCompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,i.Under Category,i.Name as itemname,i.Model as brand,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,d.DiscountAmount as discountamount,isNUll((select KeyField from invoicemaster where invoiceid in 
   (select InvoiceID from Invoicedetail where invoiceid in (select Invoiceid from InvoiceMaster where ReferenceInvoiceID=d.InvoiceID) and itemID=d.ItemID)),(select Keyfield from invoicemaster where Invoiceid=d.Invoiceid)) as KeyField
   ,unitprice,amount,discountpercent,d.vatpercent as vatpercent,vatamount,netamount,transactionid,d.Narration as detailnarration,d.Attr1 as Attr1,d.Attr2 as Attr2 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,JSON_PRESERVE_ZERO_FRACTION);
  
  }
  
  if($_GET['action']=="getInvoicePacking")
  {


$data=array();
    $InvoiceID=$_GET['InvoiceID'];
        $sql="   select InvoiceMaster.CreateLog as CreateLog,CheckInDateTime as CheckInTime,CheckOutDateTime as CheckOutTime,fuellevel,invoicedate,deliverydate,CheckedBy as UserName,mv.MasterValue as vehiclebrand,invoicemaster.vehiclebrand as VehicleBrandID,mv1.MasterValue as vehiclemodel,invoicemaster.vehiclemodel as VehicleModelID2,mv2.MasterValue as vehicletype,invoicemaster.vehicletype as VehicleTypeID,mv3.MasterValue as vehiclecolor,invoicemaster.VehicleColor as VehicleColorID,vehiclesize,mv4.MasterValue as vehicleyear
   ,invoicemaster.vehicleyear as VehicleYearID,customertype,invoicemaster.salesmanid as salesmanid ,invoicemaster.salesmanid2 as salesmanid2,SalesManName as salesman,challanno,supplierid,notes,mobilenumber,Narration,godownid
   ,customerName,platenumber,chassisnumber,trnno,totalamount,discountamount,TotalTaxAmount as taxamount,netamount,mulkiyano,parkingno,keyno,invoicemaster.keyfield as keyfield,Email as email
   from InvoiceMaster left outer join SalesManInformation as sim  on sim.SalesManID=invoicemaster.SalesManID2  
 left outer join Master_Values as mv  on mv.MasterValueID=invoicemaster.VehicleBrand
left outer join Master_Values as mv1  on mv1.MasterValueID=invoicemaster.vehiclemodel
 left outer join Master_Values as mv2  on mv2.MasterValueID=invoicemaster.VehicleType 
 left outer join Master_Values as mv3  on mv3.MasterValueID=invoicemaster.VehicleColor
 left outer join Master_Values as mv4 on mv4.MasterValueID=invoicemaster.VehicleYear    
   where InvoiceID=".$InvoiceID." and InvoiceType=55";
  $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $row['UserName']=$_SESSION['UserName'];
      $row['PreparedBy']=$row['CreateLog'];      
      foreach ($row as $key => $value) {
        # code...
      $row[$key]=utf8_encode($value);
      }
      $data[][]=$row;
    }
    //CategorySize
    
// warning list 
//$sql="select * from stockledger where  InvoiceID=".$InvoiceID." and Qty<0";
 $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as ItemCompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,(select Under from inventory where id=i.Under) as Category,(select Name from inventory where id=i.Under) as SubCategory ,i.Under as SubCategoryID,i.Name as itemname,i.Model as brand,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,d.DiscountAmount as discountamount,(select Keyfield from invoicemaster where Invoiceid=d.Invoiceid) as KeyField
   ,unitprice,amount,discountpercent,d.vatpercent as vatpercent,vatamount,netamount,transactionid,d.Narration as detailnarration,d.Attr1 as Attr1,d.Attr2 as Attr2,ItemJson,AttrPictureLocation1 as Picture1,AttrPictureLocation2 as Picture2 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."   order by i.CompanyID";
    $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['OutDetail'][]=$row;
    }
/*$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars from [InvoiceMaster_JobDetail] as ijb where TextBoxName='CheckList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['CheckList'][]=$row;
    }
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars,PictureLocation from [InvoiceMaster_JobDetail] as ijb where TextBoxName='InspectionList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['InspectionList'][]=$row;
    }   
*/
    //job card details 
    
    $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as ItemCompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,(select Under from inventory where id=i.Under) as Category,(select Name from inventory where id=i.Under) as SubCategory ,i.Under as SubCategoryID,i.Name as itemname,i.Model as brand,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,d.DiscountAmount as discountamount,(select Keyfield from invoicemaster where Invoiceid=d.Invoiceid) as KeyField
   ,unitprice,amount,discountpercent,d.vatpercent as vatpercent,vatamount,netamount,transactionid,d.Narration as detailnarration,d.Attr1 as Attr1,d.Attr2 as Attr2,ItemJson,AttrPictureLocation1 as Picture1,AttrPictureLocation2 as Picture2 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."  order by i.CompanyID";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['detailitems'][]=$row;
    }   

    echo json_encode($data);
   
   
  
   
  }//End getInvoicePacking
  if($_GET['action']=="getInvoiceSpecial")
  {


$data=array();
    $InvoiceID=$_GET['InvoiceID'];
        $sql="   select InvoiceMaster.CreateLog as CreateLog,'' as CheckInTime,'' as CheckOutTime,0 as fuellevel,invoicedate,InvoiceDate as deliverydate,CheckedBy as UserName,0 as customertype,invoicemaster.salesmanid as salesmanid ,0 as salesmanid2,SalesManName as salesman,challanno,CustomerID as  supplierid,'' as notes,mobilenumber,Narration,godownid
   ,customerName,0 as platenumber,0 as chassisnumber,0 as trnno,totalamount,discountamount,TotalTaxAmount as taxamount,netamount,0 as mulkiyano,0 as parkingno,0 as keyno,invoicemaster.keyfield as keyfield,Email as email,COAName as CustomerName,acc.Attr6 as Address,acc.Attr15 as SupplierTRN
   from SalesInvoiceMaster as  InvoiceMaster left outer join SalesManInformation as sim  on sim.SalesManID=invoicemaster.SalesManID  
   left outer join accounts as acc  on acc.COAID=invoicemaster.CustomerID      
   where InvoiceID=".$InvoiceID."";
  $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $row['UserName']=$_SESSION['UserName'];
      $row['PreparedBy']=$row['CreateLog'];      
      foreach ($row as $key => $value) {
        # code...
      $row[$key]=utf8_encode($value);
      }
      $data[][]=$row;
    }
    //CategorySize
    
// warning list 
/*$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars from [InvoiceMaster_JobDetail] as ijb where TextBoxName='WarningList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['WarningDetail'][]=$row;
    }
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars from [InvoiceMaster_JobDetail] as ijb where TextBoxName='CheckList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['CheckList'][]=$row;
    }
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars,PictureLocation from [InvoiceMaster_JobDetail] as ijb where TextBoxName='InspectionList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['InspectionList'][]=$row;
    }   
*/
    //job card details 
    
     $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as ItemCompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,(select Under from inventory where id=i.Under) as Category,(select Name from inventory where id=i.Under) as SubCategory ,i.Under as SubCategoryID,i.Name as itemname,i.Model as brand,(SELEcT Abbreviation FROM UnitOfMeasure WHERE ID=i.UnitID) AS UnitName,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,d.DiscountAmount as discountamount,(select Keyfield from Salesinvoicemaster where Invoiceid=d.Invoiceid) as KeyField
   ,unitprice,amount,discountpercent,TaxPercent as vatpercent,TaxAmount as vatamount,netamount,transactionid,d.Narration as detailnarration,d.Attr1 as Attr1,d.Attr2 as Attr2,'' as ItemJson,AttrPictureLocation1 as Picture1,AttrPictureLocation2 as Picture2 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."  order by i.CompanyID";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['detailitems'][]=$row;
    }   

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


$data=array();
    $InvoiceID=$_GET['InvoiceID'];
        $sql="   select InvoiceMaster.CreateLog as CreateLog,CheckInDateTime as CheckInTime,CheckOutDateTime as CheckOutTime,fuellevel,invoicedate,deliverydate,CheckedBy as UserName,mv.MasterValue as vehiclebrand,invoicemaster.vehiclebrand as VehicleBrandID,mv1.MasterValue as vehiclemodel,invoicemaster.vehiclemodel as VehicleModelID2,mv2.MasterValue as vehicletype,invoicemaster.vehicletype as VehicleTypeID,mv3.MasterValue as vehiclecolor,invoicemaster.VehicleColor as VehicleColorID,vehiclesize,mv4.MasterValue as vehicleyear
   ,invoicemaster.vehicleyear as VehicleYearID,customertype,invoicemaster.salesmanid as salesmanid ,invoicemaster.salesmanid2 as salesmanid2,SalesManName as salesman,challanno,supplierid,notes,mobilenumber,Narration,godownid
   ,customerName,platenumber,chassisnumber,trnno,totalamount,discountamount,TotalTaxAmount as taxamount,netamount,mulkiyano,parkingno,keyno,invoicemaster.keyfield as keyfield,Email as email
   from InvoiceMaster left outer join SalesManInformation as sim  on sim.SalesManID=invoicemaster.SalesManID2  
 left outer join Master_Values as mv  on mv.MasterValueID=invoicemaster.VehicleBrand
left outer join Master_Values as mv1  on mv1.MasterValueID=invoicemaster.vehiclemodel
 left outer join Master_Values as mv2  on mv2.MasterValueID=invoicemaster.VehicleType 
 left outer join Master_Values as mv3  on mv3.MasterValueID=invoicemaster.VehicleColor
 left outer join Master_Values as mv4 on mv4.MasterValueID=invoicemaster.VehicleYear    
   where InvoiceID=".$InvoiceID."";
  $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $row['UserName']=$_SESSION['UserName'];
      $row['PreparedBy']=$row['CreateLog'];      
      foreach ($row as $key => $value) {
        # code...
      $row[$key]=utf8_encode($value);
      }
      $data[][]=$row;
    }
    //CategorySize
    
// warning list 
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars from [InvoiceMaster_JobDetail] as ijb where TextBoxName='WarningList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['WarningDetail'][]=$row;
    }
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars from [InvoiceMaster_JobDetail] as ijb where TextBoxName='CheckList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['CheckList'][]=$row;
    }
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars,PictureLocation from [InvoiceMaster_JobDetail] as ijb where TextBoxName='InspectionList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['InspectionList'][]=$row;
    }   

    //job card details 
    
    $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as ItemCompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,(select Under from inventory where id=i.Under) as Category,(select Name from inventory where id=i.Under) as SubCategory ,i.Under as SubCategoryID,i.Name as itemname,i.Model as brand,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,d.DiscountAmount as discountamount,(select Keyfield from invoicemaster where Invoiceid=d.Invoiceid) as KeyField
   ,unitprice,amount,discountpercent,d.TaxPercent as vatpercent,TaxAmount as  vatamount,netamount,transactionid,d.Narration as detailnarration,d.Attr1 as Attr1,d.Attr2 as Attr2,'' as ItemJson,AttrPictureLocation1 as Picture1,AttrPictureLocation2 as Picture2 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."  order by i.CompanyID";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['detailitems'][]=$row;
    }   

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

$data=array();
    $InvoiceID=$_GET['InvoiceID'];
        $sql="   select InvoiceMaster.CreateLog as CreateLog,CheckInDateTime as CheckInTime,CheckOutDateTime as CheckOutTime,fuellevel,invoicedate,deliverydate,CheckedBy as UserName,mv.MasterValue as vehiclebrand,invoicemaster.vehiclebrand as VehicleBrandID,mv1.MasterValue as vehiclemodel,invoicemaster.vehiclemodel as VehicleModelID2,mv2.MasterValue as vehicletype,invoicemaster.vehicletype as VehicleTypeID,mv3.MasterValue as vehiclecolor,invoicemaster.VehicleColor as VehicleColorID,vehiclesize,mv4.MasterValue as vehicleyear
   ,invoicemaster.vehicleyear as VehicleYearID,customertype,invoicemaster.salesmanid as salesmanid ,invoicemaster.salesmanid2 as salesmanid2,SalesManName as salesman,challanno,supplierid,notes,mobilenumber,Narration,godownid
   ,customerName,platenumber,chassisnumber,trnno,totalamount,discountamount,TotalTaxAmount as taxamount,netamount,mulkiyano,parkingno,keyno,invoicemaster.keyfield as keyfield,Email as email
   from InvoiceMaster left outer join SalesManInformation as sim  on sim.SalesManID=invoicemaster.SalesManID2  
 left outer join Master_Values as mv  on mv.MasterValueID=invoicemaster.VehicleBrand
left outer join Master_Values as mv1  on mv1.MasterValueID=invoicemaster.vehiclemodel
 left outer join Master_Values as mv2  on mv2.MasterValueID=invoicemaster.VehicleType 
 left outer join Master_Values as mv3  on mv3.MasterValueID=invoicemaster.VehicleColor
 left outer join Master_Values as mv4 on mv4.MasterValueID=invoicemaster.VehicleYear    
   where InvoiceID=".$InvoiceID."";
  $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $row['UserName']=$_SESSION['UserName'];
      $row['PreparedBy']=$row['CreateLog'];      
      foreach ($row as $key => $value) {
        # code...
      $row[$key]=utf8_encode($value);
      }
      $data[][]=$row;
    }
    //CategorySize
    
// warning list 
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars from [InvoiceMaster_JobDetail] as ijb where TextBoxName='WarningList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['WarningDetail'][]=$row;
    }
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars from [InvoiceMaster_JobDetail] as ijb where TextBoxName='CheckList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['CheckList'][]=$row;
    }
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars,PictureLocation from [InvoiceMaster_JobDetail] as ijb where TextBoxName='InspectionList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['InspectionList'][]=$row;
    }   

    //job card details 
    
    $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as ItemCompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,(select Under from inventory where id=i.Under) as Category,(select Name from inventory where id=i.Under) as SubCategory ,i.Under as SubCategoryID,i.Name as itemname,i.Model as brand,d.StandardPrice3 as Cost,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,d.DiscountAmount as discountamount,(select Keyfield from invoicemaster where Invoiceid=d.Invoiceid) as KeyField
   ,unitprice,amount,discountpercent,d.vatpercent as vatpercent,vatamount,netamount,transactionid,d.Narration as detailnarration,d.Attr1 as Attr1,d.Attr2 as Attr2,ItemJson,AttrPictureLocation1 as Picture1,AttrPictureLocation2 as Picture2 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."  order by i.CompanyID";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['detailitems'][]=$row;
    }   

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


    $InvoiceID=$_GET['InvoiceID'];
       $sql="   select InvoiceMaster.CreateLog as CreateLog,CheckInDateTime as CheckInTime,CheckOutDateTime as CheckOutTime,fuellevel,convert(date,invoicedate) as invoicedate,convert(date,deliverydate) as deliverydate,CheckedBy as UserName,mv.MasterValue as vehiclebrand,invoicemaster.vehiclebrand as VehicleBrandID,mv1.MasterValue as vehiclemodel,invoicemaster.vehiclemodel as VehicleModelID2,mv2.MasterValue as vehicletype,invoicemaster.vehicletype as VehicleTypeID,mv3.MasterValue as vehiclecolor,invoicemaster.VehicleColor as VehicleColorID,vehiclesize,mv4.MasterValue as vehicleyear
   ,invoicemaster.vehicleyear as VehicleYearID,customertype,invoicemaster.salesmanid as salesmanid ,invoicemaster.salesmanid2 as salesmanid2,SalesManName as salesman,challanno,supplierid,notes,mobilenumber,Narration,godownid
   ,customerName,platenumber,chassisnumber,trnno,totalamount,discountamount,TotalTaxAmount as taxamount,netamount,mulkiyano,parkingno,keyno,invoicemaster.keyfield as keyfield,Email as email
   from InvoiceMaster left outer join SalesManInformation as sim  on sim.SalesManID=invoicemaster.SalesManID2  
 left outer join Master_Values as mv  on mv.MasterValueID=invoicemaster.VehicleBrand
left outer join Master_Values as mv1  on mv1.MasterValueID=invoicemaster.vehiclemodel
 left outer join Master_Values as mv2  on mv2.MasterValueID=invoicemaster.VehicleType 
 left outer join Master_Values as mv3  on mv3.MasterValueID=invoicemaster.VehicleColor
 left outer join Master_Values as mv4 on mv4.MasterValueID=invoicemaster.VehicleYear    
   where InvoiceID=".$InvoiceID."  and InvoiceMaster.InvoiceStatus=1";
  $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $row['UserName']=$_SESSION['UserName'];
      $row['PreparedBy']=$row['CreateLog'];      
      foreach ($row as $key => $value) {
        # code...
      //$row[$key]=htmlspecialchars($value);
      $row[$key]=utf8_encode($value);


      }
      $data[][]=$row;
    }
    //CategorySize

// warning list 
/*$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars from [InvoiceMaster_JobDetail] as ijb where TextBoxName='WarningList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['WarningDetail'][]=$row;
    }
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars from [InvoiceMaster_JobDetail] as ijb where TextBoxName='CheckList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['CheckList'][]=$row;
    }
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars,PictureLocation from [InvoiceMaster_JobDetail] as ijb where TextBoxName='InspectionList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['InspectionList'][]=$row;
    }   
*/
    //job card details 
    
    $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as ItemCompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,i.Under Category,i.Name as itemname,i.Model as brand,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,d.DiscountAmount as discountamount,isNUll((select KeyField from invoicemaster where invoiceid in 
   (select InvoiceID from Invoicedetail where invoiceid in (select Invoiceid from InvoiceMaster where ReferenceInvoiceID=d.InvoiceID) and itemID=d.ItemID)),(select Keyfield from invoicemaster where Invoiceid=d.Invoiceid)) as KeyField
   ,unitprice,amount,discountpercent,d.vatpercent as vatpercent,vatamount,netamount,transactionid,d.Narration as detailnarration,d.Attr1 as Attr1,d.Attr2 as Attr2 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."  order by i.CompanyID";
    $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['detailitems'][]=$row;
    }   

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

    $InvoiceID=$_GET['InvoiceID'];
       $sql="   select InvoiceMaster.CreateLog as CreateLog,CheckInDateTime as CheckInTime,CheckOutDateTime as CheckOutTime,fuellevel,invoicedate,deliverydate,CheckedBy as UserName,mv.MasterValue as vehiclebrand,invoicemaster.vehiclebrand as VehicleBrandID,mv1.MasterValue as vehiclemodel,invoicemaster.vehiclemodel as VehicleModelID2,mv2.MasterValue as vehicletype,invoicemaster.vehicletype as VehicleTypeID,mv3.MasterValue as vehiclecolor,invoicemaster.VehicleColor as VehicleColorID,vehiclesize,mv4.MasterValue as vehicleyear
   ,invoicemaster.vehicleyear as VehicleYearID,customertype,invoicemaster.salesmanid as salesmanid ,invoicemaster.salesmanid2 as salesmanid2,SalesManName as salesman,challanno,supplierid,notes,mobilenumber,Narration,godownid
   ,customerName,platenumber,chassisnumber,trnno,totalamount,discountamount,TotalTaxAmount as taxamount,netamount,mulkiyano,parkingno,keyno,invoicemaster.keyfield as keyfield,Email as email
   from InvoiceMaster left outer join SalesManInformation as sim  on sim.SalesManID=invoicemaster.SalesManID2  
 left outer join Master_Values as mv  on mv.MasterValueID=invoicemaster.VehicleBrand
left outer join Master_Values as mv1  on mv1.MasterValueID=invoicemaster.vehiclemodel
 left outer join Master_Values as mv2  on mv2.MasterValueID=invoicemaster.VehicleType 
 left outer join Master_Values as mv3  on mv3.MasterValueID=invoicemaster.VehicleColor
 left outer join Master_Values as mv4 on mv4.MasterValueID=invoicemaster.VehicleYear    
   where InvoiceID=".$InvoiceID." and InvoiceType=5 and InvoiceMaster.InvoiceStatus=1";
  $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $row['UserName']=$_SESSION['UserName'];
      $row['PreparedBy']=$row['CreateLog'];      
      foreach ($row as $key => $value) {
        # code...
      $row[$key]=utf8_encode($value);
      }
      $data[][]=$row;
    }
// warning list 
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars from [InvoiceMaster_JobDetail] as ijb where TextBoxName='WarningList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['WarningDetail'][]=$row;
    }
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars from [InvoiceMaster_JobDetail] as ijb where TextBoxName='CheckList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['CheckList'][]=$row;
    }
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars,PictureLocation from [InvoiceMaster_JobDetail] as ijb where TextBoxName='InspectionList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['InspectionList'][]=$row;
    }   

    //job card details 
    
    $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as ItemCompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,i.Under Category,i.Name as itemname,i.Model as brand,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,d.DiscountAmount as discountamount,isNUll((select KeyField from invoicemaster where invoiceid in 
   (select InvoiceID from Invoicedetail where invoiceid in (select Invoiceid from InvoiceMaster where ReferenceInvoiceID=d.InvoiceID) and itemID=d.ItemID)),(select Keyfield from invoicemaster where Invoiceid=d.Invoiceid)) as KeyField
   ,unitprice,amount,discountpercent,d.vatpercent as vatpercent,vatamount,netamount,transactionid,d.Narration as detailnarration,d.Attr1 as Attr1,d.Attr2 as Attr2 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."  order by i.CompanyID";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['detailitems'][]=$row;
    }   

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

    $InvoiceID=$_GET['InvoiceID'];
    $ItemID=$_GET['ItemID'];
       $sql="   select InvoiceMaster.CreateLog as CreateLog,CheckInDateTime as CheckInTime,CheckOutDateTime as CheckOutTime,fuellevel,invoicedate,deliverydate,CheckedBy as UserName,mv.MasterValue as vehiclebrand,invoicemaster.vehiclebrand as VehicleBrandID,mv1.MasterValue as vehiclemodel,invoicemaster.vehiclemodel as VehicleModelID2,mv2.MasterValue as vehicletype,invoicemaster.vehicletype as VehicleTypeID,mv3.MasterValue as vehiclecolor,invoicemaster.VehicleColor as VehicleColorID,vehiclesize,mv4.MasterValue as vehicleyear
   ,invoicemaster.vehicleyear as VehicleYearID,customertype,invoicemaster.salesmanid as salesmanid ,invoicemaster.salesmanid2 as salesmanid2,SalesManName as salesman,challanno,supplierid,notes,mobilenumber,Narration,godownid
   ,customerName,platenumber,chassisnumber,trnno,totalamount,discountamount,TotalTaxAmount as taxamount,netamount,mulkiyano,parkingno,keyno,invoicemaster.keyfield as keyfield,Email as email
   from InvoiceMaster left outer join SalesManInformation as sim  on sim.SalesManID=invoicemaster.SalesManID2  
 left outer join Master_Values as mv  on mv.MasterValueID=invoicemaster.VehicleBrand
left outer join Master_Values as mv1  on mv1.MasterValueID=invoicemaster.vehiclemodel
 left outer join Master_Values as mv2  on mv2.MasterValueID=invoicemaster.VehicleType 
 left outer join Master_Values as mv3  on mv3.MasterValueID=invoicemaster.VehicleColor
 left outer join Master_Values as mv4 on mv4.MasterValueID=invoicemaster.VehicleYear    
   where InvoiceID=".$InvoiceID." and InvoiceType=5";
  $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $row['UserName']=$_SESSION['UserName'];
      $row['PreparedBy']=$row['CreateLog'];      
      foreach ($row as $key => $value) {
        # code...
      $row[$key]=utf8_encode($value);
      }
      $data[][]=$row;
    }


    //job card details 
    
    $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as ItemCompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,i.Under Category,i.Name as itemname,i.Model as brand,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,d.DiscountAmount as discountamount,(select Keyfield from invoicemaster where Invoiceid=d.Invoiceid) as KeyField
   ,unitprice,amount,discountpercent,d.vatpercent as vatpercent,vatamount,netamount,transactionid,d.Narration as detailnarration,d.Attr1 as Attr1,d.Attr2 as Attr2,d.ItemJson,d.AttrPictureLocation1 as Picture1,d.AttrPictureLocation2 as Picture2 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." and ItemID=".$ItemID." order by i.CompanyID";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data['detailitems'][]=$row;
    }   

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

    $InvoiceID=$_GET['InvoiceID'];
       $sql="   select InvoiceMaster.CreateLog as CreateLog,CheckInDateTime as CheckInTime,CheckOutDateTime as CheckOutTime,fuellevel,invoicedate,deliverydate,CheckedBy as UserName,mv.MasterValue as vehiclebrand,invoicemaster.vehiclebrand as VehicleBrandID,mv1.MasterValue as vehiclemodel,invoicemaster.vehiclemodel as VehicleModelID2,mv2.MasterValue as vehicletype,invoicemaster.vehicletype as VehicleTypeID,mv3.MasterValue as vehiclecolor,invoicemaster.VehicleColor as VehicleColorID,vehiclesize,mv4.MasterValue as vehicleyear
   ,invoicemaster.vehicleyear as VehicleYearID,customertype,invoicemaster.salesmanid as salesmanid ,invoicemaster.salesmanid2 as salesmanid2,SalesManName as salesman,challanno,supplierid,notes,mobilenumber,Narration,godownid
   ,customerName,platenumber,chassisnumber,trnno,totalamount,discountamount,TotalTaxAmount as taxamount,netamount,mulkiyano,parkingno,keyno,invoicemaster.keyfield as keyfield,Email as email
   from InvoiceMaster left outer join SalesManInformation as sim  on sim.SalesManID=invoicemaster.SalesManID2  
 left outer join Master_Values as mv  on mv.MasterValueID=invoicemaster.VehicleBrand
left outer join Master_Values as mv1  on mv1.MasterValueID=invoicemaster.vehiclemodel
 left outer join Master_Values as mv2  on mv2.MasterValueID=invoicemaster.VehicleType 
 left outer join Master_Values as mv3  on mv3.MasterValueID=invoicemaster.VehicleColor
 left outer join Master_Values as mv4 on mv4.MasterValueID=invoicemaster.VehicleYear    
   where InvoiceID=".$InvoiceID."";
  $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $row['UserName']=$_SESSION['UserName'];
      $row['PreparedBy']=$row['CreateLog'];      
      foreach ($row as $key => $value) {
        # code...
      $row[$key]=utf8_encode($value);
      }
      $data[][]=$row;
    }

    //job card details 
    
     $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,d.ItemID as ItemID,i.CompanyID as ItemCompanyID,'' as ItemCompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,i.Under Category,i.Name as itemname,i.Model as brand,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,d.DiscountAmount as discountamount,(select Keyfield from invoicemaster where Invoiceid=d.Invoiceid) as KeyField
   ,unitprice,amount,discountpercent,d.vatpercent as vatpercent,vatamount,netamount,transactionid,d.Narration as detailnarration,d.Attr1 as Attr1,d.Attr2 as Attr2,d.ItemJson,d.AttrPictureLocation1 as Picture1,d.AttrPictureLocation2 as Picture2,'' as CategorySize 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." order by i.CompanyID";
    $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);
      }

      $row['CategorySize']=getRawMaterial($row['ItemID'],$InvoiceID,$connection);
      $data['detailitems'][]=$row;
    }   

    echo json_encode($data);
   
  }
	if($_GET['action']=="getInvoice")
	{
		$InvoiceID=$_GET['InvoiceID'];
		   $sql="   select InvoiceMaster.CreateLog as CreateLog,CheckInDateTime as CheckInTime,CheckOutDateTime as CheckOutTime,fuellevel,invoicedate,deliverydate,CheckedBy as UserName,mv.MasterValue as vehiclebrand,invoicemaster.vehiclebrand as VehicleBrandID,mv1.MasterValue as vehiclemodel,invoicemaster.vehiclemodel as VehicleModelID2,mv2.MasterValue as vehicletype,invoicemaster.vehicletype as VehicleTypeID,mv3.MasterValue as vehiclecolor,invoicemaster.VehicleColor as VehicleColorID,vehiclesize,mv4.MasterValue as vehicleyear
   ,invoicemaster.vehicleyear as VehicleYearID,customertype,invoicemaster.salesmanid as salesmanid ,invoicemaster.salesmanid2 as salesmanid2,SalesManName as salesman,challanno,supplierid,notes,mobilenumber,Narration,godownid
   ,customerName,platenumber,chassisnumber,trnno,totalamount,discountamount,TotalTaxAmount as taxamount,netamount,mulkiyano,parkingno,keyno,invoicemaster.keyfield as keyfield,Email as email
   from InvoiceMaster left outer join SalesManInformation as sim  on sim.SalesManID=invoicemaster.SalesManID2  
 left outer join Master_Values as mv  on mv.MasterValueID=invoicemaster.VehicleBrand
left outer join Master_Values as mv1  on mv1.MasterValueID=invoicemaster.vehiclemodel
 left outer join Master_Values as mv2  on mv2.MasterValueID=invoicemaster.VehicleType 
 left outer join Master_Values as mv3  on mv3.MasterValueID=invoicemaster.VehicleColor
 left outer join Master_Values as mv4 on mv4.MasterValueID=invoicemaster.VehicleYear    
   where InvoiceID=".$InvoiceID."";
	$result=odbc_exec($connection,$sql);
		while($row=odbc_fetch_array($result))
		{
      $row['UserName']=$_SESSION['UserName'];
      $row['PreparedBy']=$row['CreateLog'];      
      foreach ($row as $key => $value) {
        # code...
      $row[$key]=utf8_encode($value);
      }
			$data[][]=$row;
		}
// warning list 
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars from [InvoiceMaster_JobDetail] as ijb where TextBoxName='WarningList' and InvoiceID=".$InvoiceID."";
		$result=odbc_exec($connection,$sql);
		while($row=odbc_fetch_array($result))
		{
			$data['WarningDetail'][]=$row;
		}
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars from [InvoiceMaster_JobDetail] as ijb where TextBoxName='CheckList' and InvoiceID=".$InvoiceID."";
		$result=odbc_exec($connection,$sql);
		while($row=odbc_fetch_array($result))
		{
			$data['CheckList'][]=$row;
		}
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars,PictureLocation from [InvoiceMaster_JobDetail] as ijb where TextBoxName='InspectionList' and InvoiceID=".$InvoiceID."";
		$result=odbc_exec($connection,$sql);
		while($row=odbc_fetch_array($result))
		{
			$data['InspectionList'][]=$row;
		}		

		//job card details 
		
		 $sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,i.CompanyID as ItemCompanyID,'' as ItemCompanyName,i.ProductBaseType as ItemProductBaseType,i.Under as Under,i.Under Category,i.Name as itemname,i.Model as brand,
   i.MaxQtyLevel as ItemMaxQtyLevel,d.itemid,barcode,qty,d.DiscountAmount as discountamount,(select Keyfield from invoicemaster where Invoiceid=d.Invoiceid) as KeyField
   ,unitprice,amount,discountpercent,d.vatpercent as vatpercent,vatamount,netamount,transactionid,d.Narration as detailnarration,d.Attr1 as Attr1,d.Attr2 as Attr2,d.ItemJson,d.AttrPictureLocation1 as Picture1,d.AttrPictureLocation2 as Picture2 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." order by i.CompanyID";
		$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['detailitems'][]=$row;
		}		

		echo json_encode($data);
	}

  if($_GET['action']=="getGallery")
  {
    $data=array();
$InvoiceID=$_GET['InvoiceID'];
if($InvoiceID!="" && $InvoiceID!="undefined" && $InvoiceID>0)
{
$sql="select ROW_NUMBER() OVER (
      PARTITION BY [InvoiceID]
      ORDER BY [InvoiceID]
   ) row_num,JobDetailID,MasterValueID,(select MasterValue from master_values as mv where mv.MasterValueID=ijb.MasterValueID)as MasterValue ,Description,Particulars,PictureLocation from [InvoiceMaster_JobDetail] as ijb where TextBoxName='InspectionList' and InvoiceID=".$InvoiceID."";
    $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      $data[]=$row;
    }     
}
        echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);


  }

	if($_GET['action']=="getChasisdata")
	{
		$data=array();
    if(isset($_GET['cop']))
    {
      $CustomerID=$_GET['CustomerID'];
$sql="select chasisno as ChassisNumber,0 as SalesManID,0 as challanno,keyno  as KeyNo,parkingno as ParkingNo,MulkiyaNo,plateno as PlateNumber,'' as MobileNumber,
'' as CustomerName,mv2.MasterValue VehicleModel,mv2.MasterValueID as VehicleModelID,mv.MasterValue as  VehicleBrand,
mv.MasterValueID as VehicleBrandID,mv1.MasterValue as VehicleType,mv1.MasterValueID as VehicleTypeID,mv3.MasterValue as VehicleColor,
mv3.MasterValueID as VehicleColorID,mv4.MasterValue as VehicleYear,mv4.MasterValueID as VehicleYearID  from RAC_VehicleMaster as im 

   inner join MASTER_VALUES as mv on im.VIN=convert(varchar,mv.MasterValueID)
   inner join MASTER_VALUES as mv1 on im.Model=convert(varchar,mv1.MasterValueID)
inner join MASTER_VALUES as mv2 on im.Make=convert(varchar,mv2.MasterValueID)
inner join MASTER_VALUES as mv3 on im.Color=convert(varchar,mv3.MasterValueID)
inner join MASTER_VALUES as mv4 on im.Yr=convert(varchar,mv4.MasterValueID)


where GLCODE='$CustomerID'
";
    }
    else
    {



        if(isset($_GET['ChassisNumber']))
    $ChassisNumber="ChassisNumber like '%".$_GET['ChassisNumber']."%' and ";
    else
    $ChassisNumber="";
    
    if(isset($_GET['PlateNumber']))
    $PlateNumber="PlateNumber like '%".$_GET['PlateNumber']."%' and ";
    else
    $PlateNumber="";

    if(isset($_GET['VehicleType']))
    $VehicleType="mv2.MasterValue like '%".$_GET['VehicleType']."%' and ";
    else
    $VehicleType="";  
  

    $searchbox=$ChassisNumber."".$PlateNumber."".$VehicleType;

		 $sql="  select  distinct ChassisNumber,SalesManID,challanno,KeyNo,ParkingNo,MobileNumber,
CustomerName,Email,MulkiyaNo,PlateNumber,mv2.MasterValue as VehicleBrand,mv2.MasterValueID as VehicleBrandID,mv.MasterValue as VehicleType,
mv.MasterValueID as VehicleTypeID,mv1.MasterValue as VehicleModel,mv1.MasterValueID as VehicleModelID,mv3.MasterValue as VehicleColor,
mv3.MasterValueID as VehicleColorID,mv4.MasterValue as VehicleYear,mv4.MasterValueID as VehicleYearID from InvoiceMaster as im
   inner join MASTER_VALUES as mv on im.VehicleType=mv.MasterValueID
   inner join MASTER_VALUES as mv1 on im.VehicleModel=mv1.MasterValueID
inner join MASTER_VALUES as mv2 on im.VehicleBrand=mv2.MasterValueID
inner join MASTER_VALUES as mv3 on im.VehicleColor=mv3.MasterValueID
inner join MASTER_VALUES as mv4 on im.VehicleYear=mv4.MasterValueID

   where $searchbox  InvoiceType=5 
";
/*and im.active=1 and  not EXISTS(select 1 from InvoiceMaster as b where im.MobileNumber=b.MobileNumber and im.ChassisNumber=b.ChassisNumber
   and im.MulkiyaNo=b.MulkiyaNo and im.PlateNumber=b.PlateNumber   and im.Email=b.Email and im.CustomerName=b.CustomerName )*/
    }
$counter=0;
   		$result=odbc_exec($connection,$sql);
		while($row=odbc_fetch_array($result))
		{
      $counter++;
      $row['row_num']=$counter;
      foreach ($row as $key => $value) {
        # code...
        $row[$key]=utf8_encode($value);
      }
			$data[]=$row;
		}
		echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);
	}
  if($_GET['action']=="getCustomerSearch2")
  {

    $data=array();
        $InvoiceType=$_GET['InvoiceType'];
        if(isset($_GET['CustomerName']))
    $CustomerName="COAName like '%".$_GET['CustomerName']."%' and ";
    else
    $CustomerName="";

     if(isset($_GET['MobileNumber']) && $_GET['MobileNumber']>0)  
    $MobileNumber="Attr10 like '%".$_GET['MobileNumber']."%' and ";
    else
    $MobileNumber="";  

    if(isset($_GET['Email']))  
    $Email="Attr11 like '%".$_GET['Email']."%' and ";
    else
    $Email="";

    $searchbox=$CustomerName."".$MobileNumber."".$Email;
       
 
    $sql="select COAName as CustomerName,Attr10 as MobileNumber,Attr11 as Email,GLCode,COAID as  CustomerID,Attr15 as Trnno,Attr9 as landline,
   COAName  from Accounts    where $searchbox NatureID=14 and active=1 and degree=5";
      $filename='cache/'.md5($sql).".txt";
       if (filemtime($filename) < time()-1*1) 
       {
   $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
   $counter=0;
    while($row=odbc_fetch_array($result))
    {
      $counter++;
      foreach($row as $key=>$value)
      $row[$key]=utf8_encode($value);  

      $row['row_num']=$counter;
      $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']=="getCustomerSearch")
  {
    $data=array();
        $InvoiceType=$_GET['InvoiceType'];
        if(isset($_GET['CustomerName']))
    $CustomerName="CustomerName like '%".$_GET['CustomerName']."%' and ";
    else
    $CustomerName="";

     if(isset($_GET['MobileNumber']))  
    $MobileNumber="MobileNumber like '%".$_GET['MobileNumber']."%' and ";
    else
    $MobileNumber="";  

    if(isset($_GET['Email']))  
    $Email="Email like '%".$_GET['Email']."%' and ";
    else
    $Email="";

    $searchbox=$CustomerName."".$MobileNumber."".$Email;

    $sql="select  distinct(InvoiceID),CustomerName,MobileNumber,Email,(select GLCODE from accounts where COAID=vd.LedgerID) as GLCODE,vd.LedgerID as  CustomerID,
   (select COAName from accounts where COAID=vd.LedgerID) as COAName  from invoicemaster as im 
   inner  join  VoucherDetails as vd on VoucherID=im.AutoVoucherID
   where $searchbox InvoiceType=".$InvoiceType." and vd.LedgerID<>172";
   $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
   $counter=0;
    while($row=odbc_fetch_array($result))
    {
      $counter++;
      foreach($row as $key=>$value)
      $row[$key]=utf8_encode($value);  

      $row['row_num']=$counter;
      $data[]= $row;
    }
    echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);


  }
	if($_GET['action']=="getCustomerdata")
	{
		$InvoiceType=$_GET['InvoiceType'];
		$data=array();
		$sql="   select ROW_NUMBER() OVER (
      ORDER BY [InvoiceID]    ) row_num ,CustomerName,MobileNumber,Email,(select GLCODE from accounts where COAID=vd.LedgerID) as GLCODE,vd.LedgerID as  CustomerID,
   (select COAName from accounts where COAID=vd.LedgerID) as COAName from invoicemaster as im 
   left outer join  VoucherDetails as vd on VoucherID=im.AutoVoucherID
   where InvoiceType=".$InvoiceType;

   		$result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
		while($row=odbc_fetch_array($result))
		{
      foreach($row as $key=>$value)
      $row[$key]=utf8_encode($value);  

			$data[]= $row;
		}
		echo json_encode($data,JSON_PRESERVE_ZERO_FRACTION);
	}
	
if($_GET['action']=="GetSalesMan")
{
	$where=" active=1";
$table=$_GET['TextBoxName'];
		$fieldname=$_GET['fieldname'];
		$fieldid=$_GET['fieldid'];
		echo getSelect2List2($table,$fieldid,$fieldname,$where,$connection);
}
if($_GET['action']=="InvoiceCheck")
{


$InvoiceID=$_GET['InvoiceID'];
   $sql="select * from VoucherMaster where ReferenceInvoiceID=".$InvoiceID." and active=1 and VoucherTypeID=8";
//$sql="select * from VoucherMaster where ReferenceInvoiceID=".$InvoiceID." and active=1";
  $result=odbc_exec($connection,$sql);
  if(odbc_num_rows($result)>0)
  {
    $row=odbc_fetch_array($result);
    $res=array('status'=>"View",'description'=>$InvoiceID,'supplierid'=>0);
    echo json_encode($res);
      $updatesql="update InvoiceMaster set InvoiceStatus=4 where InvoiceID=$InvoiceID";
      odbc_exec($connection,$updatesql);
  }
  else
  {
$res=array('status'=>"ok",'description'=>'Generate');
    echo json_encode($res,JSON_UNESCAPED_UNICODE);

  }
  //if record not exists send to ok 

  //else send it to view 

}

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

$InvoiceID=$_GET['InvoiceID'];
/*	$sql="select * from VoucherMaster where ReferenceInvoiceID=".$InvoiceID." and active=1 and VoucherTypeID=8";*/
$sql="select * from VoucherMaster where ReferenceInvoiceID in(select InvoiceID from InvoiceMaster where ReferenceInvoiceID=".$InvoiceID.")";
	$result=odbc_exec($connection,$sql);
	if(odbc_num_rows($result)>0)
	{
    $row=odbc_fetch_array($result);
		$res=array('status'=>"View",'description'=>$InvoiceID,'supplierid'=>0);
		echo json_encode($res);

	}
	else
	{
$res=array('status'=>"ok",'description'=>'Generate');
		echo json_encode($res);

	}
	//if record not exists send to ok 

	//else send it to view 
}
if($_GET['action']=="reversePayment")
{
      odbc_autocommit($connection, FALSE);
$InvoiceID=$_GET['InvoiceID'];
//$Narration=$_POST['Narration'];
  //remove previous generated invoice/Voucher
$sqlupdate="update VoucherMaster set active=0,DeleteLog='".$_SESSION['UserName']."' where VoucherTypeID=7 and ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);

              $sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);

              $sqlupdate="delete from VoucherDetails  where ReferenceInvoiceID=".$InvoiceID." and LedgerID in(90,98)";
              odbc_exec($connection,$sqlupdate);

$sql="update invoicemaster set editLog='', TotalCurrencyAmount=0,paid=0,symreceived=0,CreditCard=0 where invoiceid=$InvoiceID";
              odbc_exec($connection,$sql);

   $sql="delete from cardtransaction where invoiceid=$InvoiceID";
           odbc_exec($connection,$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');

  }
    echo json_encode($res);

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


 //odbc_autocommit($connection, FALSE);
//$details=array_keys($_POST);
//$d=json_decode(($details[0].$details[1]));
//print_r($d);
//$InvoiceID=$_GET['InvoiceID'];
//$_SESSION['SETTING']['SALES'];
//remove previous generated invoice
/*$sqlupdate="update VoucherMaster set active=0,DeleteLog='".$_SESSION['UserName']."' where VoucherTypeID=71 and ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
$sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
*/

//    $sql="select * from InvoiceMaster where InvoiceID=".$InvoiceID;
              //and voucherdate between '2020-11-01' and '2020-11-30' 
              //InvoiceDate between '2020-11-01' and '2020-11-30' and  
              $sql="select * from InvoiceMaster where  
  InvoiceType in(3,4)   and active=1 and 
   invoiceid not in (
  select ReferenceInvoiceID from VoucherMaster where VoucherTypeID in (66,71,10,6) 
     and active=1 )";
$res="";
    $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
//odbc_autocommit($connection, FALSE);
      $InvoiceID=$row['InvoiceID'];
$sqlupdate="update VoucherMaster set active=0,DeleteLog='".$_SESSION['UserName']."' where VoucherTypeID=71 and ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);
$sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);


      $NetAmount=$row['NetAmount'];//im
      $InvoiceDate=$row['InvoiceDate'];
      $Narration="";
      $ReferenceInvoiceID=$InvoiceID;
      $AmountDebit=0;
      $AmountCredit=0;
      $GodownID=$row['GodownID'];
      $TotalTaxAmount=$row['TotalTaxAmount'];//im
      $TotalAmount=$row['TotalAmount'];//im
      $InvoiceType=$row['InvoiceType'];
      $InvoiceTypeID=$row['InvoiceType'];
      $KeyField=$row['KeyField'];
      $SupplierID=$row['SupplierID'];//im
      if($SupplierID>100000)
      $SupplierID=$SupplierID-100000000;

     $BranchID=$row['BranchID'];//im

               $fields=array();
            $VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$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']=($InvoiceType==3)?66:71;//isset($VoucherTypeID)?$VoucherTypeID:0;
           $fields['PeriodID']=1;//isset($PeriodID)?$PeriodID:0;
           $fields['ReferenceInvoiceID']=isset($ReferenceInvoiceID)?$ReferenceInvoiceID:0;
           $fields['SupplierID']=0;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($SupplierID)?$SupplierID:0;
           $fields['AmountDebit']=isset($AmountDebit)?$AmountDebit:0;
           $fields['AmountCredit']=isset($AmountCredit)?$AmountCredit:0;
           $fields['IsAuto']=1;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['BranchID']=isset($BranchID)?$BranchID:0;
           $fields['ReferenceVoucherID']=isset($ReferenceVoucherID)?$ReferenceVoucherID:0;
           $fields['GroupID']=isset($GroupID)?$GroupID:0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=0;//isset($Cash)?$Cash:0;
           $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['UserID']=isset($UserID)?$UserID:0;
           $fields['VoucherDateTime']=isset($VoucherDateTime)?$VoucherDateTime:date("Y-m-d H:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'';
         //  print_r($fields);
           $r=InsertVoucherMasterNew($fields,$InvoiceType,$InvoiceID,$connection);  
//print_r($r);
        $fdetails=array();  
        for($a=0;$a<2;$a++)
        {
          echo "called";
           $fdetails['VoucherID']=$VoucherID;
           if($InvoiceTypeID==3)
            $fdetails['LedgerID']=$SupplierID;//
           else 
           $fdetails['LedgerID']=$_SESSION['SETTING']['PURCHASES'];//$d->CustomerLedgerID; DEbit side entry
           if($a==0)
           {
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
            if($InvoiceTypeID==3)
            {
$CreditLedgerID=$_SESSION['SETTING']['VATPURCHASE'];//$d->VATLedgerID;
$fdetails['LedgerID']=$SupplierID;
            } 
            else{ 
            $fdetails['LedgerID']=$_SESSION['SETTING']['VATPURCHASE'];
            $CreditLedgerID=$SupplierID;//$d->VATLedgerID;
              }
           }
          else
          {
            $Debit=$TotalAmount;
            $Credit=$TotalAmount;
            if($InvoiceTypeID==3)
            {
              $CreditLedgerID=$_SESSION['SETTING']['PURCHASES'];
            }
            else
            {
              $CreditLedgerID=$SupplierID;
            }
              //$d->SalesLedgerID;
            
          }
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="JOB CARD";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="JOB CARD INVOICE"; 
           $fdetails['BranchID']=$BranchID;//company
           //print_r($fdetails);
      $r=  InsertVoucherDetail2($fdetails,$InvoiceType,$VoucherID,$connection);
  //    print_r($r);              
        }//end for 
        //update master invoice 
         $updateinvoice="update InvoiceMaster set AutoVoucherID=$VoucherID,InvoiceStatus=4,editLog='".$_SESSION['UserName']."' where InvoiceID=".$InvoiceID;
        odbc_exec($connection,$updateinvoice) or die(odbc_error().$updateinvoice);
        $ReferenceInvoiceID=getnamesingle("InvoiceMaster","ReferenceInvoiceID","InvoiceID",$InvoiceID,$connection);
        if($ReferenceInvoiceID>0)
        {
        $sql="update InvoiceMaster set InvoiceStatus=4 where InvoiceID=".$ReferenceInvoiceID;
odbc_exec($connection,$sql) or die(odbc_error().$sql);
        }
        if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Invoice Generated Sucessfully Invoice # '.$InvoiceID);
  }
  else
  {
    odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Generated');

  }

       } //end while 
    echo json_encode($res);


   

}
if($_GET['action']=="GeneratePurchaseInvoice")
{
$sql="select * from InvoiceMaster where  
  InvoiceType in(3,4)   and active=1 and 
   invoiceid not in (
  select ReferenceInvoiceID from VoucherMaster where VoucherTypeID in (66,71,10,6) 
   and active=1 )";

 odbc_autocommit($connection, FALSE);
//$details=array_keys($_POST);
//$d=json_decode(($details[0].$details[1]));
//print_r($d);
$InvoiceID=$_GET['InvoiceID'];
//$_SESSION['SETTING']['SALES'];
//remove previous generated invoice
$sqlupdate="update VoucherMaster set active=0,DeleteLog='".$_SESSION['UserName']."' where VoucherTypeID=71 and ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
$sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);


    $sql="select * from InvoiceMaster where InvoiceID=".$InvoiceID;
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $NetAmount=$row['NetAmount'];//im
      $InvoiceDate=$row['InvoiceDate'];
      $Narration="";
      $ReferenceInvoiceID=$InvoiceID;
      $AmountDebit=0;
      $AmountCredit=0;
      $GodownID=$row['GodownID'];
      $TotalTaxAmount=$row['TotalTaxAmount'];//im
      $TotalAmount=$row['TotalAmount'];//im
      $InvoiceType=$row['InvoiceType'];
      $InvoiceTypeID=$row['InvoiceType'];
      $KeyField=$row['KeyField'];
      $SupplierID=$row['SupplierID'];//im
      if($SupplierID>100000)
      $SupplierID=$SupplierID-100000000;

     $BranchID=$row['BranchID'];//im

    }
              $fields=array();
            $VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$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']=($InvoiceType==3)?66:71;//isset($VoucherTypeID)?$VoucherTypeID:0;
           $fields['PeriodID']=1;//isset($PeriodID)?$PeriodID:0;
           $fields['ReferenceInvoiceID']=isset($ReferenceInvoiceID)?$ReferenceInvoiceID:0;
           $fields['SupplierID']=0;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($SupplierID)?$SupplierID:0;
           $fields['AmountDebit']=isset($AmountDebit)?$AmountDebit:0;
           $fields['AmountCredit']=isset($AmountCredit)?$AmountCredit:0;
           $fields['IsAuto']=1;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['BranchID']=isset($BranchID)?$BranchID:0;
           $fields['ReferenceVoucherID']=isset($ReferenceVoucherID)?$ReferenceVoucherID:0;
           $fields['GroupID']=isset($GroupID)?$GroupID:0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=0;//isset($Cash)?$Cash:0;
           $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['UserID']=isset($UserID)?$UserID:0;
           $fields['VoucherDateTime']=isset($VoucherDateTime)?$VoucherDateTime:date("Y-m-d H:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'';
         //  print_r($fields);
          InsertVoucherMaster($fields,$InvoiceType,$InvoiceID,$connection);  

        $fdetails=array();  
        for($a=0;$a<2;$a++)
        {
           $fdetails['VoucherID']=$VoucherID;
           if($InvoiceTypeID==3)
            $fdetails['LedgerID']=$SupplierID;//
           else 
           $fdetails['LedgerID']=$_SESSION['SETTING']['PURCHASES'];//$d->CustomerLedgerID; DEbit side entry
           if($a==0)
           {
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
            if($InvoiceTypeID==3)
            {
$CreditLedgerID=$_SESSION['SETTING']['VATPURCHASE'];//$d->VATLedgerID;
$fdetails['LedgerID']=$SupplierID;
            } 
            else{ 
            $fdetails['LedgerID']=$_SESSION['SETTING']['VATPURCHASE'];
            $CreditLedgerID=$SupplierID;//$d->VATLedgerID;
              }
           }
          else
          {
            $Debit=$TotalAmount;
            $Credit=$TotalAmount;
            if($InvoiceTypeID==3)
            {
              $CreditLedgerID=$_SESSION['SETTING']['PURCHASES'];
            }
            else
            {
              $CreditLedgerID=$SupplierID;
            }
              //$d->SalesLedgerID;
            
          }
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="JOB CARD";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="JOB CARD INVOICE"; 
           $fdetails['BranchID']=$BranchID;//company
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);              
        }//end for 
        //update master invoice 
         $updateinvoice="update InvoiceMaster set AutoVoucherID=$VoucherID,InvoiceStatus=4,editLog='".$_SESSION['UserName']."' where InvoiceID=".$InvoiceID;
        odbc_exec($connection,$updateinvoice);
        $ReferenceInvoiceID=getnamesingle("InvoiceMaster","ReferenceInvoiceID","InvoiceID",$InvoiceID,$connection);
        if($ReferenceInvoiceID>0)
        {
        $sql="update InvoiceMaster set InvoiceStatus=4 where InvoiceID=".$ReferenceInvoiceID;
odbc_exec($connection,$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');

  }
    echo json_encode($res);


   
}

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

 odbc_autocommit($connection, FALSE);
//$details=array_keys($_POST);
//$d=json_decode(($details[0].$details[1]));
//print_r($d);
$InvoiceID=$_GET['InvoiceID'];
//$_SESSION['SETTING']['SALES'];
//remove previous generated invoice
$sqlupdate="update VoucherMaster set active=0,DeleteLog='".$_SESSION['UserName']."' where VoucherTypeID=8 and ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
              $sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);


    $sql="select * from InvoiceMaster where InvoiceID=".$InvoiceID;
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $NetAmount=$row['NetAmount'];//im
      $InvoiceDate=$row['InvoiceDate'];
      $Narration="";
      $ReferenceInvoiceID=$InvoiceID;
      $AmountDebit=0;
      $AmountCredit=0;
      $GodownID=$row['GodownID'];
      $TotalTaxAmount=$row['TotalTaxAmount'];//im
      $TotalAmount=$row['TotalAmount'];//im
      $InvoiceType=$row['InvoiceType'];
      $KeyField=$row['KeyField'];
      $SupplierID=$row['SupplierID'];//im
     $BranchID=$row['BranchID'];//im

    }
              $fields=array();
            $VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$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($ReferenceInvoiceID)?$ReferenceInvoiceID:0;
           $fields['SupplierID']=0;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($SupplierID)?$SupplierID:0;
           $fields['AmountDebit']=isset($AmountDebit)?$AmountDebit:0;
           $fields['AmountCredit']=isset($AmountCredit)?$AmountCredit:0;
           $fields['IsAuto']=1;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['BranchID']=isset($BranchID)?$BranchID:0;
           $fields['ReferenceVoucherID']=isset($ReferenceVoucherID)?$ReferenceVoucherID:0;
           $fields['GroupID']=isset($GroupID)?$GroupID:0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=0;//isset($Cash)?$Cash:0;
           $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['UserID']=isset($UserID)?$UserID:0;
           $fields['VoucherDateTime']=isset($VoucherDateTime)?$VoucherDateTime:date("Y-m-d H:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'';
         //  print_r($fields);
          InsertVoucherMasterNew($fields,$InvoiceType,$InvoiceID,$connection);  

        $fdetails=array();  
        for($a=0;$a<2;$a++)
        {
           $fdetails['VoucherID']=$VoucherID;
           $fdetails['LedgerID']=$SupplierID;//$d->CustomerLedgerID; DEbit side entry
           if($a==0)
           {
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
            $CreditLedgerID=$_SESSION['SETTING']['VATSALES'];//$d->VATLedgerID;
           }
          else
          {
            $Debit=$TotalAmount;
            $Credit=$TotalAmount;
              $CreditLedgerID=$_SESSION['SETTING']['SALES'];//$d->SalesLedgerID;
          }
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="JOB CARD";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="JOB CARD INVOICE"; 
           $fdetails['BranchID']=$BranchID;//company
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);              
        }//end for 
        //update master invoice 
         $updateinvoice="update InvoiceMaster set AutoVoucherID=$VoucherID,InvoiceStatus=4,editLog='".$_SESSION['UserName']."' where InvoiceID=".$InvoiceID;
        odbc_exec($connection,$updateinvoice);
        $ReferenceInvoiceID=getnamesingle("InvoiceMaster","ReferenceInvoiceID","InvoiceID",$InvoiceID,$connection);
        if($ReferenceInvoiceID>0)
        {
        $sql="update InvoiceMaster set InvoiceStatus=4 where InvoiceID=".$ReferenceInvoiceID;
odbc_exec($connection,$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');

  }
    echo json_encode($res);


  }//end reGenerateInvoice

if($_GET['action']=="GenerateSalesInvoice")
{
 odbc_autocommit($connection, FALSE);
 $data=$_POST['data'];
 $d=json_decode($data);
 /*print_r($d);
 return;*/
/*$details=array_keys($_POST);
$d=json_decode(($details[0].$details[1]));*/
//print_r($d);
$InvoiceID=$_GET['InvoiceID'];

//remove previous generated invoice
$sqlupdate="update VoucherMaster set active=0,DeleteLog='".$_SESSION['UserName']."' where VoucherTypeID=8 and ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
              $sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);


		$sql="select * from SalesInvoiceMaster where InvoiceID=".$InvoiceID;
		$result=odbc_exec($connection,$sql);
		while($row=odbc_fetch_array($result))
		{
			$NetAmount=$row['NetAmount'];//im
			$InvoiceDate=$row['InvoiceDate'];
			$Narration="";
			$ReferenceInvoiceID=$InvoiceID;
			$AmountDebit=0;
			$AmountCredit=0;
			$GodownID=$row['GodownID'];
			$TotalTaxAmount=$row['TotalTaxAmount'];//im
			$TotalAmount=($NetAmount-$TotalTaxAmount);//$row['TotalAmount'];//im
			$InvoiceType=$row['InvoiceType'];
			$KeyField=$row['KeyField'];
      $SupplierID=$row['CustomerID'];//im
      $BranchID=21;//$row['BranchID'];//im

		}
       				$fields=array();
       			$VoucherID=getMaxId("VoucherMaster","VoucherID",$connection)+1;//getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$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($ReferenceInvoiceID)?$ReferenceInvoiceID:0;
           $fields['SupplierID']=0;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($SupplierID)?$SupplierID:0;
           $fields['AmountDebit']=isset($AmountDebit)?$AmountDebit:0;
           $fields['AmountCredit']=isset($AmountCredit)?$AmountCredit:0;
           $fields['IsAuto']=1;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['BranchID']=isset($BranchID)?$BranchID:0;
           $fields['ReferenceVoucherID']=isset($ReferenceVoucherID)?$ReferenceVoucherID:0;
           $fields['GroupID']=isset($GroupID)?$GroupID:0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=0;//isset($Cash)?$Cash:0;
           $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['UserID']=isset($UserID)?$UserID:0;
           $fields['VoucherDateTime']=isset($VoucherDateTime)?$VoucherDateTime:date("Y-m-d H:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'';
         //  print_r($fields);
       		InsertVoucherMaster2($fields,$InvoiceType,$InvoiceID,$connection);	

       	$fdetails=array();	
       	for($a=0;$a<2;$a++)
       	{
       	   $fdetails['VoucherID']=$VoucherID;
           $fdetails['LedgerID']=$SupplierID;//$d->CustomerLedgerID; DEbit side entry
           if($a==0)
           {
           	$Debit=$TotalTaxAmount;
           	$Credit=$TotalTaxAmount;
           	$CreditLedgerID=$d->VATLedgerID;
           }
       		else
       		{
       			$Debit=$TotalAmount;
       			$Credit=$TotalAmount;
       		    $CreditLedgerID=$d->SalesLedgerID;
       		}
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="JOB CARD";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="JOB CARD INVOICE";	
           $fdetails['BranchID']=$BranchID;//company
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);		  				
       	}//end for 
        //update master invoice 
         $updateinvoice="update SalesInvoiceMaster set AutoVoucherID=$VoucherID,InvoiceStatus=4,editLog='".$_SESSION['UserName']."' where InvoiceID=".$InvoiceID;
        odbc_exec($connection,$updateinvoice);
        $ReferenceInvoiceID=getnamesingle("SalesInvoiceMaster","ReferenceInvoiceID","InvoiceID",$InvoiceID,$connection);
        if($ReferenceInvoiceID>0)
        {
        $sql="update SalesInvoiceMaster set InvoiceStatus=4 where InvoiceID=".$ReferenceInvoiceID;
odbc_exec($connection,$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');

  }
		echo json_encode($res);

}//end generate sales invoice 

if($_GET['action']=="InsertJobSheet")
{
      odbc_autocommit($connection, FALSE);
$data=array();
	$data=array_keys($_POST);
	$data=json_decode($data[0]);
//print_r($data);
	$sqldelete="delete from InvoiceMaster_JobDetail where TextBoxName='JobSheet' and InvoiceID=".$data->InvoiceID."  and MasterValueID=".$data->ItemID;
	odbc_exec($connection,$sqldelete);
//$JobDetailID=getmaxId("InvoiceMaster_JobDetail","JobDetailID",$connection)+1;
   $sql="Insert into InvoiceMaster_JobDetail(InvoiceID 
                       ,MasterValueID 
                       ,Particulars  
                       ,TransactionID 
                       ,TimeIn 
                       ,[TimeOut]  
                       ,[Description] 
                       ,TextBoxName                       
                       ,SalesManID
                       ,ActivityStatus
                       ,EmployeeSalary  
                       ,EmployeeSalaryPerDay  
                       ,EmployeeSalaryPerHour  
                       ,EmployeeSalaryPerMinute  
                       ,EmployeeWorkingMinutes 
                       ,LaborCost,EntryDate) Values(".(isset($data->InvoiceID)?$data->InvoiceID:0).",". 
                       (isset($data->ItemID)?$data->ItemID:0) .",'".
                       (isset($data->ItemName)?str_replace("_", " ",$data->ItemName):0) ."',".
                       (isset($data->TransactionID)?$data->TransactionID:0) .",'".
                       (isset($data->TimeIn)?str_replace("_", " ",$data->TimeIn):0)."','".
                       (isset($data->TimeOut)?str_replace("_", " ",$data->TimeOut):0)."','".
                       (isset($data->Description)?str_replace("_", " ",$data->Description):0) ."','".
                       (isset($data->TextBoxName)?$data->TextBoxName:0) ."',".                      
                        (isset($data->SalesManID)?$data->SalesManID:0) .",'".
                       (isset($data->ActivityStatus)?$data->ActivityStatus:0) ."',". 
                       (($data->EmployeeSalary!="")?$data->EmployeeSalary:0) .",". 
                       (($data->EmployeeSalaryPerDay!="")?$data->EmployeeSalaryPerDay:0) .",". 
                       (($data->EmployeeSalaryPerHour!="")?$data->EmployeeSalaryPerHour:0) .",". 
                       (($data->EmployeeSalaryPerMinute!="")?$data->EmployeeSalaryPerMinute:0) .",". 
                       (($data->EmployeeWorkingMinutes!="")?$data->EmployeeWorkingMinutes:0) .",".
                       (($data->LaborCost!="")?$data->LaborCost:0) .",'".$data->EntryDate."')"; 
                       odbc_exec($connection,$sql);

/*$res=array('status'=>"ok",'description'=>'Record Saved Sucessfully');
*/
if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Deleted');

  }
		echo json_encode($res);

}//jobsheet insert 
if($_GET['action']=="ApproveInvoiceStatus2")
{
  $Notes=$_GET['Notes'];
  $Notes=urldecode($Notes);

  $InvoiceID=$_GET['InvoiceID'];
   $updatesql="update invoicemaster set CheckedBy='".$_SESSION['UserName']."',Notes='$Notes' where InvoiceID=".$InvoiceID;
  odbc_exec($connection,$updatesql);
     $updatesql="update invoicemaster set CheckedBy='".$_SESSION['UserName']."',Notes='$Notes' where ReferenceInvoiceID=".$InvoiceID;
  odbc_exec($connection,$updatesql);
  $res=array('status'=>"ok",'description'=>'Invoice Approved Sucessfully');
    echo json_encode($res);

 
}
if($_GET['action']=="ApproveInvoiceStatus")
{
	$InvoiceID=$_GET['InvoiceID'];
	 $updatesql="update invoicemaster set InvoiceStatus=2 where InvoiceID=".$InvoiceID;
	odbc_exec($connection,$updatesql);
     $updatesql="update invoicemaster set InvoiceStatus=2 where ReferenceInvoiceID=".$InvoiceID;
  odbc_exec($connection,$updatesql);
	$res=array('status'=>"ok",'description'=>'Invoice Approved Sucessfully');
		echo json_encode($res);

}
if($_GET['action']=="DisapproveInvoiceStatus2")
{
  $InvoiceID=$_GET['InvoiceID'];
  $Notes=$_GET['Notes'];
  $Notes=urldecode($Notes);

   $updatesql="update invoicemaster set CheckedBy='".$_SESSION['UserName']."',Notes='$Notes' where InvoiceID=".$InvoiceID;
  odbc_exec($connection,$updatesql);
     $updatesql="update invoicemaster set CheckedBy='".$_SESSION['UserName']."',Notes='$Notes' where ReferenceInvoiceID=".$InvoiceID;
  odbc_exec($connection,$updatesql);
  $res=array('status'=>"ok",'description'=>'Invoice DisApproved Sucessfully');

    echo json_encode($res);

}
if($_GET['action']=="DisapproveInvoiceStatus")
{
	$InvoiceID=$_GET['InvoiceID'];
	$updatesql="update invoicemaster set InvoiceStatus=3 where InvoiceID=".$InvoiceID;
	odbc_exec($connection,$updatesql);
  $updatesql="update invoicemaster set InvoiceStatus=3 where ReferenceInvoiceID=".$InvoiceID;
  odbc_exec($connection,$updatesql);  
	$res=array('status'=>"ok",'description'=>'Invoice DisApproved Sucessfully');
		echo json_encode($res);

}
}
else
{

  $res=array('status'=>"redirect",'description'=>'Session Expire Please Login Again');
    echo json_encode($res);
}
}//end action if 

function getSelect2List2new($table,$id,$name,$where='1=1',$connection)
  {
    $data=array();
    if($where!="")$where=" where ".$where;else $where="";
           $sql="select $id,$name from $table $where";
            $filename='cache/'.md5($sql).".txt";
     if (filemtime($filename) < time()-1*1) 
     {
    $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);
        $row[$key]=htmlspecialchars($value); 
        //$row[$key]=urlencode($value);       
      }
      $data []=$row;
}//end while
    
      @unlink($filename);
    $data=json_encode($data);
      file_put_contents($filename, serialize($data));
    }
    else
    {
         $data=unserialize(file_get_contents($filename));  

    }
    return $data;

  }










function getSelect2List2($table,$id,$name,$where='1=1',$connection)
  {
    $data=array();
    if($where!="")$where=" where ".$where;else $where="";
         $sql="select $id,$name from $table $where";
            $filename='cache/'.md5($sql).".txt";
       if (filemtime($filename) < time()-1*1) 
       {
    $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);
        $row[$key]=htmlspecialchars($value); 
        //$row[$key]=urlencode($value);       
      }
      $data []=$row;

    }
     @unlink($filename);
     $data=json_encode($data);
          file_put_contents($filename, serialize($data));
      }
      else
      {
      $data=unserialize(file_get_contents($filename));  

      }
    return ($data);

  }
function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}
?>