<?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);
    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' 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(isset($_SESSION['userid']))
{

  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=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($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,5,"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);

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

  }
  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']=="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);

  }
  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']=="GenerateAdvancePayment")
  {
odbc_autocommit($connection, FALSE);    
    $data=($_POST['data']);
    $data=json_decode($data);
    //print_r($data);
                $VoucherID=getmaxId("VoucherMaster","VoucherID",$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,5,"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;
    
  $SelectionID=(isset($data->SelectionID) && $data->SelectionID!="")?$data->SelectionID:0;      
    
      $NetAmount=$CashAmount+$CreditAmount;
      $InvoiceDate=(isset($data->InvoiceDate) && $data->InvoiceDate!="")?$data->InvoiceDate:Date("Y-m-d");
      $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 
     // InvoiceDate
      //check the invoice reference 
 

                  $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']=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:'';
        //   print_r($fields);
          InsertVoucherMasterJob($fields,$InvoiceType,$ReferenceInvoiceID,$connection); 
          // update invoicemaster 
          if($ReferenceInvoiceID>0)
          {
           $sql="update invoicemaster set Paid=(isNull(Paid,0)+$NetAmount),Balance=(NetAmount-(isNull(Paid,0)+$NetAmount)),EditLog='".$_SESSION['UserName']."' where InvoiceID=".$ReferenceInvoiceID;
          odbc_exec($connection,$sql) or die(odbc_error().$sql);
          }
        $fdetails=array();  
        for($a=0;$a<2;$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($CreditAmount>0)
            {
           $fdetails['LedgerID']=$CreditAccountID;            
            $Debit=$CreditAmount;
            $Credit=$CreditAmount;
            $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;
           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 
      $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,5,"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:'';
            $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==12)
            {
            $where="InvoiceType=12"; 
            $KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
            //getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
            
            $KeyField2=str_pad($KeyField,5,"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);
    //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']=="jobcardInsert")
	{
    odbc_autocommit($connection, FALSE);
  $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);
		//$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:'';
            $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:'';
                 $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 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($InvoiceType==5)
           	{
           	$where="InvoiceType=5 and GodownID=".$GodownID;	
           	$KeyField=generateCode("InvoiceMaster","KeyField",$where,$connection)+1;
           	//getnamesingle("InvoiceMaster","count(*)","TableID","71",$connection)+1;
           	if($GodownID==1)
           	{	
           	$KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
           	$KeyField="MVR-".$KeyField2;
           	}
           	if($GodownID==2)
           	{	
           	$KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
           	$KeyField="CCL-".$KeyField2;
           	}
           	if($GodownID==3)
           	{	
           	$KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
           	$KeyField="RDL-".$KeyField2;
           	}
           	if($GodownID==4)
           	{	
           	$KeyField2=str_pad($KeyField,5,"0",STR_PAD_LEFT);
           	$KeyField="PWS-".$KeyField2;
           	}
           	$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','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=".$_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.""." 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['CompanyID']))
    $CompanyID="CompanyID=".$_GET['CompanyID']." and";
    else
    $CompanyID="";*/
      mb_internal_encoding('UTF-8'); 

    $Size=$_GET['Size'];
    $ProductBaseType=$_GET['BaseType'];
    $where=$Under.""." 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);

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

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

    //echo getSelect2List2($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="";
		$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'].",StandardPrice2 as SalePrice,VATPercent";
		$fieldid=$_GET['fieldid'];
		echo getSelect2List2($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]=utf8_encode($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(sum(paid),0))+' || Balance:'+convert(varchar,(isnull(sum(NetAmount),0)-isnull(sum(Paid),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);

      }//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);
    }//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 ''";
      }
      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(sum(paid),0))+' || Balance:'+convert(varchar,(isnull(sum(NetAmount),0)-isnull(sum(Paid),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);

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

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

      }//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=12 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);
    }//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);

      }//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);
    }//end else 
  
    }//rtajobcardlist
  if($_GET['action']=="jobcardlist")
	{
		//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);

    	}//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);
		}//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);
  
  
  }
  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);
  
  }
  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);
  
  }
	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." 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='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."";
		$result=odbc_exec($connection,$sql);
		while($row=odbc_fetch_array($result))
		{
			$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);


  }

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


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


  }
	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);
	}
	
if($_GET['action']=="GetSalesMan")
{
	$where=" IsCurrentlyActive=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);

  }
  //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']=="GenerateSalesInvoice")
{
      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=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($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);
       		InsertVoucherMaster($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";	
           //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 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']=="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']=="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 getSelect2List2($table,$id,$name,$where='1=1',$connection)
  {
    $data=array();
    if($where!="")$where=" where ".$where;else $where="";
         $sql="select $id,$name from $table $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]=utf8_encode($value);
        $row[$key]=htmlspecialchars($value); 
        //$row[$key]=urlencode($value);       
      }
      $data []=$row;

    }
    return json_encode($data);

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

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