<?php include_once('database_connection.php');
$userid="";
$branches=array();
$branches[0]='[Makaw_BR-1].dbo.';
$branches[1]='[Makaw_BR-2].dbo.';
//$branches[0]='makaw_Branch1';
if(isset($_GET['action']) && $_GET['action']=="GenerateVoucher1")
{
$id=0;
      $sql="select * from SalesInvoiceMaster where InvoiceID not in (select ReferenceInvoiceID from VoucherMaster where VoucherTypeID=8 and active=1) and active=1";//.$id;
      $result=odbc_exec($connection,$sql);
      while($row=odbc_fetch_array($result))
       {
       $id=$row['InvoiceID'];
       $AmountDebit=0;
      $AmountCredit=0;
      $GodownID=$row['GodownID'];
      $TotalTaxAmount=$row['TotalTaxAmount'];//im
      $TotalAmount=$row['TotalAmount'];//im
      $InvoiceType=$row['InvoiceType'];
      $InvoiceTypeID=$row['InvoiceType'];
      $ReferenceInvoiceID=$row['ReferenceInvoiceID'];
      $SupplierID=$row['CustomerID'];
      //$ReferenceInvoiceID=$row['ReferenceInvoiceID'];
      $KeyField=$row['KeyField'];
      $COAID=$row['CustomerID'];
      if($COAID>10000)
      $COAID=$COAID-100000000;
    $SupplierID=$COAID;
      $ProjectID=$GodownID;
      $BranchID=$GodownID;
      $InvoiceDate=$row['InvoiceDate'];
      $Active=$row['Active'];
 
                  //code for stockledger 
             $sqlStock="select * from SalesInvoiceDetail where InvoiceID=".$id;
            $resultStock=odbc_exec($connection,$sqlStock) or die(odbc_error().$sqlStock);
            $subtotal=0;
            while($rowStock=odbc_fetch_array($resultStock))
            {
                  $ITEMID=$rowStock['ItemID'];
                  $Rate=$rowStock['StandardPrice3'];
                  $Qty=$rowStock['QTY'];
      $Attr1=$rowStock['Attr1'];
      $Attr2=$rowStock['Attr2'];
      $Attr3=$rowStock['Attr3'];
      $Attr4=$rowStock['Attr4'];
      $Attr5=$rowStock['Attr5'];
      $Attr6=$rowStock['Attr6'];
      $Attr7=$rowStock['Attr7'];
      $Attr8=$rowStock['Attr8'];
      $Attr9=$rowStock['Attr9'];
      $Attr10=$rowStock['Attr10'];
      $InvoiceID=$rowStock['InvoiceID'];
      $ReferenceInvoiceID=$rowStock['ReferenceInvoiceID'];
      $InvoiceType=5;
      $Remarks=$rowStock['Narration'];
      $SupplierID=$COAID;
$Active=1;
$ContainerNo=$rowStock['Narration'];
$ExpiryDate=$InvoiceDate;
$DepartmentID=7;
$ItemJson="";
$VoucherID=0;
$UserID=1;
//code for BOM 

//end code for BOM
      $deletesql="delete from stockledger where ItemID=".$ITEMID." and InvoiceTypeID=5 and InvoiceID=".$id;
odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);
            //code for material 
            

      
            $subtotal=$subtotal+($Rate*1);//$Qty
    //code for BOM (Bill of Material)
    //generateRawMaterial();
  $sqlmaterial="select * from inventory_ingredients where ItemID=$ITEMID";
           $resultmaterial=odbc_exec($connection,$sqlmaterial);
           if(odbc_num_rows($resultmaterial)>0)
           {
           while($rowmaterial=odbc_fetch_array($resultmaterial))
           {
                          $ID=getmaxId("stockledger","ID",$connection)+1;

            $MaterialID=$rowmaterial['MaterialID'];
            $Qty2=$rowmaterial['Qty'];
            $Qt=$Qty*$Qty2;
                      //code for stock ledger 
  $sql="INSERT INTO [StockLedger]
           (ID,[ItemID],[ReferenceItemID],[Qty],[InvoiceTypeID],[InvoiceID],[ReferenceInvoiceID],[Reference],[Remarks],[GodownID],[ProjectID],[BranchID],[COAID],[Active],[ContainerNo],[UserID],[Rate],[CounterID],[VoucherID],[TransDate],[ExpiryDate],[SupplierID],[DepartmentID],ItemJson,Attr1,Attr2,Attr3,Attr4,Attr5,Attr6,Attr7,Attr8,Attr9,Attr10)
     VALUES ($ID,$MaterialID,$ITEMID,".(-1*$Qt).",$InvoiceType,$InvoiceID,$ReferenceInvoiceID,'$KeyField','$Remarks',$GodownID,$ProjectID,$BranchID,$COAID,$Active,'$ContainerNo',$UserID,$Rate,$GodownID,$VoucherID,'$InvoiceDate','$ExpiryDate',$SupplierID,$DepartmentID,'".$ItemJson."','".$Attr1."','".$Attr2."','".$Attr3."','".$Attr4."','".$Attr5."','".$Attr6."','".$Attr7."','".$Attr8."','".$Attr9."','".$Attr10."')"; 
      odbc_exec($connection, $sql) or die(odbc_error().$sql);

         }
       }//end if result material 
       else
       {
  $STKID=getmaxId("stockledger","ID",$connection)+1;
     $sqlStock="insert into StockLedger (ID,InvoiceTypeID,ITEMID,InvoiceID,Rate,QTY,Remarks,Attr8,TransDate,GodownID,SupplierID,COAID,Active,ReferenceInvoiceID,
  Attr1,Attr2,Attr3,Attr4,Attr5,Attr6,Attr7,Attr9,Attr10,Reference)
    select $STKID,5,ITEMID,sim.InvoiceID,".$Rate.",(QTY*-1),sid.Narration,UnitID,InvoiceDate,GodownID,CustomerID,CustomerID,Active,sim.ReferenceInvoiceID,
  Attr1,Attr2,Attr3,Attr4,Attr5,Attr6,Attr7,Attr9,Attr10,KeyField
   from SalesInvoiceDetail as sid inner join SalesInvoiceMaster as sim on sim.InvoiceID=sid.InvoiceID where sim.InvoiceID=".$id." and sid.ITEMID=".$ITEMID;
odbc_exec($connection,$sqlStock) or die(odbc_error().$sqlStock);

       }
    //end code 
            }//end Stock Ledger Entry
            //entry for cost of good sold
//          COGS DEbit 


//generate voucher 
$VoucherTypeID=8;
      $AmountDebit=0;
      $AmountCredit=0;
      $ReferenceVoucherID=0;
      $GroupID=0;
      $InvoiceType=0;
      $ChequeNo='';
      $ClientBankAccountName ='';
      $StatusID ='';
      $ChequeDate ='';


      $PaymentType='';
      $fields=array();
            $VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=".$GodownID,$connection)+1;//getmaxId("VoucherMaster","VoucherID",$connection)+1;
      $KeyField="";
            if($VoucherTypeID==5)
            {
                  $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=5",$connection)+1;
                  $VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
                  $VoucherNo="RV-".$VoucherNo;
            }
            if($VoucherTypeID==6)
            {
                  $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=6",$connection)+1;
                  $VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
                  $VoucherNo="PV-".$VoucherNo;
            }
            if($VoucherTypeID==7)
            {
                  $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=7",$connection)+1;
                  $VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
                  $VoucherNo="JV-".$VoucherNo;
            }
               
            if($VoucherTypeID==8)
            {
                  $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=8",$connection)+1;
                  $VoucherNo=str_pad($VoucherNo,7,"0",STR_PAD_LEFT);
                  $VoucherNo="SV-".$VoucherNo;
            }
if($VoucherTypeID==71)
            {
                  $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=71",$connection)+1;
                  $VoucherNo=str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
                  $VoucherNo="PI-".$VoucherNo;
            }
$sqldelete="update VoucherMaster set active=0 where ReferenceInvoiceID=".$id." and VoucherTypeID=8";
//$sqldelete="delete from VoucherDetails"
$InvoiceTypeID=5;
         $fields['VoucherID']=$VoucherID;
           $fields['VoucherNo']=$VoucherNo;//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['ChequeNo']=($ChequeNo!="")?$ChequeNo:0;
            $fields['ClientBankAccountName']=($ClientBankAccountName!="")?$ClientBankAccountName:0;
               $fields['ChequeStatus']=($StatusID!="")?$StatusID:0;
               $fields['ChequeDate']=($ChequeDate!="")?$ChequeDate:'';
               $fields['isVoucherReturnCheque']=0;//isset($IsPostDated)?$IsPostDated:0;
           $fields['VoucherTypeID']=$VoucherTypeID;//isset($VoucherTypeID)?$VoucherTypeID:0;

           $fields['PeriodID']=1;//isset($PeriodID)?$PeriodID:0;
           $fields['ReferenceInvoiceID']=isset($id)?$id: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($ChequeDetailID)?$ChequeDetailID: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($_SESSION['UserID'])?$_SESSION['UserID']:0;
           $fields['VoucherDateTime']=isset($VoucherDateTime)?$VoucherDateTime:date("Y-m-d m:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'';
          // print_r($fields);
        $r=InsertVoucherMasterNew($fields,$InvoiceType,$VoucherID,$connection); 
        //print_r($r);
                  // insert voucher details 
            $fdetails=array();      
       $subtotal=0;
          for($a=0;$a<2;$a++)
        {
          //echo "called";
           $fdetails['VoucherID']=$VoucherID;
           if($InvoiceTypeID==5)
            $fdetails['LedgerID']=$SupplierID;//
           else 
           $fdetails['LedgerID']=$_SESSION['SETTING']['SALES'];//$d->CustomerLedgerID; DEbit side entry
           if($a==0)
           {
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
            if($InvoiceTypeID==5)
            {
$CreditLedgerID=$_SESSION['SETTING']['VATSALES'];//$d->VATLedgerID;
$fdetails['LedgerID']=$SupplierID;
            } 
            else{ 
            $fdetails['LedgerID']=$_SESSION['SETTING']['VATPURCHASE'];
            $CreditLedgerID=$SupplierID;//$d->VATLedgerID;
              }
           }
          else
          {
            $Debit=$TotalAmount;
            $Credit=$TotalAmount;
            if($InvoiceTypeID==5)
            {
              $CreditLedgerID=$_SESSION['SETTING']['SALES'];
            }
            else
            {
              $CreditLedgerID=$SupplierID;
            }
              //$d->SalesLedgerID;
            
          }
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="JOB CARD";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="JOB CARD INVOICE"; 
           $fdetails['BranchID']=$BranchID;//company
           //print_r($fdetails);
      $r=  InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);
//      print_r($r);              
        }//end for                                   
//code for cost of good sold 
  $SidebarID=44;
  $degree=1;
  $Userid="";
  $Code='COGS_POST';
  if(CheckPolicy($Userid,$SidebarID,$Code,$degree,$connection)==1)
  {
    $sql="select sum from ";
$subtotal=getSum("SalesInvoiceDetail","sum(StandardPrice3) as sum","InvoiceID",$InvoiceID,$connection);
$InventoryLedgerID=$_SESSION['SETTING']['INVENTORY'];
$COGSLedgerID=$_SESSION['SETTING']['COGS'];
$fdetails=array();  
           $fdetails['VoucherID']=$VoucherID;
           $fdetails['LedgerID']=$COGSLedgerID;//$SupplierID;//$d->CustomerLedgerID; 
        
            $Debit=$TotalAmount;
            $Credit=$TotalAmount;
            $CreditLedgerID=$InventoryLedgerID;//$d->SalesLedgerID;

           $fdetails['Debit']=$subtotal;
           $fdetails['Credit']=$subtotal;
           $fdetails['Narration']="Cost of Good Sold Entry :".$VoucherID;
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;//$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="Cost of Good Sold Entry"; 
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);
     }//end check policy
//end cost of good sold 
//end generate voucher 
$sqlupdate=" update SalesInvoiceMaster set datamode=1 Where InvoiceID=$id";
odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);

      }//end while Voucher Master
   if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully InvoiceID='.$id);
  }
else
{
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Record  Not Updated');

}
echo json_encode($res);
}//end generate voucher 

if(isset($_GET['action']) && $_GET['action']=="checkSalesStatus1")
{
      $sql="select * from SalesInvoiceMaster where datamode=0";//.$id;
      $result=odbc_exec($connection,$sql);
      while($row=odbc_fetch_array($result))
       {
       $id=$row['InvoiceID'];
      $GodownID=$row['GodownID'];
      $ReferenceInvoiceID=$row['ReferenceInvoiceID'];
      $KeyField=$row['KeyField'];
      $COAID=$row['CustomerID'];
      $ProjectID=$GodownID;
      $BranchID=$GodownID;
      $InvoiceDate=$row['InvoiceDate'];
      $Active=$row['Active'];
 
                  //code for stockledger 
             $sqlStock="select * from SalesInvoiceDetail where InvoiceID=".$id;
            $resultStock=odbc_exec($connection,$sqlStock) or die(odbc_error().$sqlStock);
            $subtotal=0;
            while($rowStock=odbc_fetch_array($resultStock))
            {
                  $ITEMID=$rowStock['ItemID'];
                  $Rate=$rowStock['StandardPrice3'];
                  $Qty=$rowStock['QTY'];
      $Attr1=$rowStock['Attr1'];
      $Attr2=$rowStock['Attr2'];
      $Attr3=$rowStock['Attr3'];
      $Attr4=$rowStock['Attr4'];
      $Attr5=$rowStock['Attr5'];
      $Attr6=$rowStock['Attr6'];
      $Attr7=$rowStock['Attr7'];
      $Attr8=$rowStock['Attr8'];
      $Attr9=$rowStock['Attr9'];
      $Attr10=$rowStock['Attr10'];
      $InvoiceID=$rowStock['InvoiceID'];
      $ReferenceInvoiceID=$rowStock['ReferenceInvoiceID'];
      $InvoiceType=5;
      $Remarks=$rowStock['Narration'];
      $SupplierID=$COAID;
$Active=1;
$ContainerNo=$rowStock['Narration'];
$ExpiryDate=$InvoiceDate;
$DepartmentID=7;
$ItemJson="";
$VoucherID=0;
$UserID=1;
//code for BOM 

//end code for BOM
      $deletesql="delete from stockledger where ItemID=".$ITEMID." and InvoiceTypeID=5 and InvoiceID=".$id;
odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);
            //code for material 
            

      
            $subtotal=$subtotal+($Rate*1);//$Qty
    //code for BOM (Bill of Material)
    //generateRawMaterial();
  $sqlmaterial="select * from inventory_ingredients where ItemID=$ITEMID";
           $resultmaterial=odbc_exec($connection,$sqlmaterial);
           if(odbc_num_rows($resultmaterial)>0)
           {
           while($rowmaterial=odbc_fetch_array($resultmaterial))
           {
                          $ID=getmaxId("stockledger","ID",$connection)+1;

            $MaterialID=$rowmaterial['MaterialID'];
            $Qty2=$rowmaterial['Qty'];
            $Qt=$Qty*$Qty2;
                      //code for stock ledger 
  $sql="INSERT INTO [StockLedger]
           (ID,[ItemID],[ReferenceItemID],[Qty],[InvoiceTypeID],[InvoiceID],[ReferenceInvoiceID],[Reference],[Remarks],[GodownID],[ProjectID],[BranchID],[COAID],[Active],[ContainerNo],[UserID],[Rate],[CounterID],[VoucherID],[TransDate],[ExpiryDate],[SupplierID],[DepartmentID],ItemJson,Attr1,Attr2,Attr3,Attr4,Attr5,Attr6,Attr7,Attr8,Attr9,Attr10)
     VALUES ($ID,$MaterialID,$ITEMID,".(-1*$Qt).",$InvoiceType,$InvoiceID,$ReferenceInvoiceID,'$KeyField','$Remarks',$GodownID,$ProjectID,$BranchID,$COAID,$Active,'$ContainerNo',$UserID,$Rate,$GodownID,$VoucherID,'$InvoiceDate','$ExpiryDate',$SupplierID,$DepartmentID,'".$ItemJson."','".$Attr1."','".$Attr2."','".$Attr3."','".$Attr4."','".$Attr5."','".$Attr6."','".$Attr7."','".$Attr8."','".$Attr9."','".$Attr10."')"; 
      odbc_exec($connection, $sql) or die(odbc_error().$sql);

         }
       }//end if result material 
       else
       {
  $STKID=getmaxId("stockledger","ID",$connection)+1;
     $sqlStock="insert into StockLedger (ID,InvoiceTypeID,ITEMID,InvoiceID,Rate,QTY,Remarks,Attr8,TransDate,GodownID,SupplierID,COAID,Active,ReferenceInvoiceID,
  Attr1,Attr2,Attr3,Attr4,Attr5,Attr6,Attr7,Attr9,Attr10,Reference)
    select $STKID,5,ITEMID,sim.InvoiceID,".$Rate.",(QTY*-1),sid.Narration,UnitID,InvoiceDate,GodownID,CustomerID,CustomerID,Active,sim.ReferenceInvoiceID,
  Attr1,Attr2,Attr3,Attr4,Attr5,Attr6,Attr7,Attr9,Attr10,KeyField
   from SalesInvoiceDetail as sid inner join SalesInvoiceMaster as sim on sim.InvoiceID=sid.InvoiceID where sim.InvoiceID=".$id." and sid.ITEMID=".$ITEMID;
odbc_exec($connection,$sqlStock) or die(odbc_error().$sqlStock);

       }
    //end code 
            }//end Stock Ledger Entry
            //entry for cost of good sold
//          COGS DEbit 

//          Inventory credit
            //GenerateCostOfGoodSold($connection,$id,$subtotal,$value);
            //end code for cost of good sold 

/*$sqlupdate=" update ".$value."VoucherMaster set LocationID=$GodownID where datamode=0";
odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);*/
            //update the branch record 
//echo $sql="select * from SalesInvoiceMaster where active=1 and InvoiceID=".$id;
 $r=GenerateSalesVoucherPayment($connection,$id,$_SESSION['UserName'],$value,$subtotal,$GodownID);
$sqlupdate=" update SalesInvoiceMaster set datamode=1 Where InvoiceID=$id";
odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);

      }//end while 
}
if(isset($_GET['action']) && $_GET['action']=="SalesManInfo")
{
$branches=getBranches($connection);
$branches1=json_decode($branches);
$branches=$branches1;
  /*$sql="select * from SalesManInformation where datamode=0 and id>0";*/
   
    /*while($row=odbc_fetch_array($result))
    {
      $id=$row['SalesManID'];*/
  foreach ($branches as $key => $value) {
    # code...
  $value1=$value;
  $value=$value->DbName;
 $deletesql="delete from ".$value."SalesManInformation";
      odbc_exec($connection,$deletesql);
      $sql="insert into ".$value."SalesManInformation select * from SalesManInformation";
 $result=odbc_exec($connection,$sql);
  }
//}

}
if(isset($_GET['action']) && $_GET['action']=="checkusersession")
{
	if(isset($_SESSION['userid']))
	$d=true;
	else
	$d=false;


$branches=getBranches($connection);
$branches1=json_decode($branches);
$branches=$branches1;
/*print_r($branches);
foreach ($branches1 as $key => $value) {
  echo $value->DbName;
  }
return;*/
//code for inventory 
  
	$sql="select * from inventory where datamode=0 and id>0";
		$result=odbc_exec($connection,$sql);
		while($row=odbc_fetch_array($result))
		{
			$id=$row['ID'];
	foreach ($branches as $key => $value) {
		# code...
	$value1=$value;
  $value=$value->DbName;

			 $deletesql="delete from ".$value."inventory where id=".$id;
			odbc_exec($connection,$deletesql);
			$sql="insert into ".$value."inventory ([ID]
      ,[Name]
      ,[Rating]
      ,[Model]
      ,[Make]
      ,[Details]
      ,[Degree]
      ,[Hierarchy]
      ,[Under]
      ,[Group]
      ,[Active]
      ,[StandardPrice1]
      ,[StandardPrice2]
      ,[StandardPrice3]
      ,[MinQtyLevel]
      ,[MaxQtyLevel]
      ,[MinPriceLevel]
      ,[MaxPriceLevel]
      ,[UnitID]
      ,[ItemType]
      ,[DepartmentID]
      ,[CreateLog]
      ,[EditLog]
      ,[DeleteLog]
      ,[AdditionalInfo1]
      ,[AdditionalInfo2]
      ,[AdditionalInfo3]
      ,[AdditionalInfo4]
      ,[AdditionalInfo5]
      ,[KeyField]
      ,[Barcode]
      ,[PictureLocation]
      ,[IsBarcodeManual]
      ,[DefaultQty]
      ,[CommisionType]
      ,[CommisionPercent]
      ,[CommisionAmount]
      ,[DiscountType]
      ,[ItemDiscountPercentage]
      ,[ItemDiscountAmount]
      ,[StandardPrice1Inclusive]
      ,[StandardPrice2Inclusive]
      ,[StandardPrice3Inclusive]
      ,[HasIngredients]
      ,[IsNonStockable]
      ,[IsAssembly]
      ,[HasBatches]
      ,[HasExpiry]
      ,[Expiry]
      ,[ExpiryDuration]
      ,[HasSupplierWarranty]
      ,[SupplierWarranty]
      ,[SupplierWarrantyDuration]
      ,[HasConsumerWarranty]
      ,[ConsumerWarranty]
      ,[ConsumerWarrantyDuration]
      ,[InitiateDate]
      ,[BatchCount]
      ,[BarcodeSequence]
      ,[BarcodePrefix]
      ,[BarcodeSuffix]
      ,[BatchBarcodeSequence]
      ,[BatchBarcodePrefix]
      ,[BatchBarcodeSuffix]
      ,[BatchBarcodeSeparator]
      ,[SequenceTypeID]
      ,[LastBarcodeNo]
      ,[Attr1]
      ,[Attr2]
      ,[Attr3]
      ,[Attr4]
      ,[Attr5]
      ,[Attr6]
      ,[Attr7]
      ,[Attr8]
      ,[Attr9]
      ,[Attr10]
      ,[Attr11]
      ,[Attr12]
      ,[Attr13]
      ,[Attr14]
      ,[Attr15]
      ,[Attr16]
      ,[Attr17]
      ,[Attr18]
      ,[Attr19]
      ,[Attr20]
      ,[ShowInPurchases]
      ,[ShowInSales]
      ,[ShowInGoodsTransfer]
      ,[ShowInDeliveryNoteReceiptNote]
      ,[ShowInIssueNoteReturnNoteRejectionNote]
      ,[ShowInFinishedGoodsReceiving]
      ,[IsWastageItem]
      ,[HasSeparateSideBarCategory]
      ,[SideBarCategoryID]
      ,[SideBarID]
      ,[SideBarMenuName]
      ,[ShowRemovedIngredients]
      ,[ShowRemovedIngredientsQty]
      ,[ShowRemovedIngredientsRate]
      ,[ShowRemovedIngredientsAmount]
      ,[ShowNewInstalledIngredients]
      ,[ShowNewInstalledIngredientsQty]
      ,[ShowNewInstalledIngredientsRate]
      ,[ShowNewInstalledIngredientsAmount]
      ,[HasProductionBatches]
      ,[IsKDSItem]
      ,[ServingTimeInMinutes]
      ,[RetailMarkupWithRespectToWholeSale]
      ,[AddPrice1]
      ,[AddPrice2]
      ,[AddPrice3]
      ,[AddPrice4]
      ,[AddPrice5]
      ,[DefaultPrinterNameSalesInvoice]
      ,[DefaultPrinterNameID]
      ,[Active_Service]
      ,[NameArabic]
      ,[CustomerId]
      ,[AddInfo6]
      ,[AddInfo7]
      ,[AddInfo8]
      ,[AddInfo9]
      ,[AddInfo10]
      ,[AddInfo11]
      ,[AddInfo12]
      ,[AddInfo13]
      ,[AddInfo14]
      ,[AddInfo15]
      ,[AddInfo16]
      ,[AddInfo17]
      ,[AddInfo18]
      ,[AddInfo19]
      ,[AddInfo20]
      ,[AddInfo21]
      ,[HasMeasurement]
      ,[ItemIDUnder]
      ,[LastItemID]
      ,[UnderItemID]
      ,[HasStockForMarble]
      ,[rtnInvoiceID]
      ,[IsAccessories]
      ,[IsBox]
      ,[DisBuyAndGetCount]
      ,[DiscountTypeID]
      ,[DisOption]
      ,[DisByPercentage]
      ,[DisByAmount]
      ,[DisStartDate]
      ,[DisEndingDate]
      ,[DisBuyAny]
      ,[DisGetAny]
      ,[DisBuyPieces]
      ,[DisBuyPercentage]
      ,[DisBuyAmount]
      ,[LastModificationSnapshotID]
      ,[ProductBaseType]
      ,[CompanyID]
      ,[ShowInStock]
      ,[IsFixedAsset]
      ,[VATPercent]
      ,[LastModificationTimeStamp]
      ,[datamode]
      ,[SortOrder]) select * from inventory where id=".$id;
			odbc_exec($connection,$sql) or die(odbc_error().$sql);
			$sqlupdate="update ".$value."inventory set datamode=1 where id=".$id;
			odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);
		}
			$sqlupdate="update inventory set datamode=1 where id=".$id;
			odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);

	}//end while

  //code for Godowns 
$sql="select * from Godowns where datamode=0 and GodownID>0 ";
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $id=$row['GodownID'];
  foreach ($branches as $key => $value) {
    # code...
  $value1=$value;
  $value=$value->DbName;

       $deletesql="delete from ".$value."Godowns where GodownID=".$id;
      odbc_exec($connection,$deletesql);
      $sql="insert into ".$value."Godowns ([GodownID]
      ,[KeyField]
      ,[Name]
      ,[Degree]
      ,[Address]
      ,[ContactNO]
      ,[AdditionalInfo1]
      ,[AdditionalInfo2]
      ,[AdditionalInfo3]
      ,[AdditionalInfo4]
      ,[AdditionalInfo5]
      ,[Group]
      ,[Under]
      ,[Hierarchy]
      ,[CreateLog]
      ,[EditLog]
      ,[DeleteLog]
      ,[Active]
      ,[GodownType]
      ,[CustomerID]
      ,[WarehouseTypeID]
      ,[RetailPriceGodownWise_RateTypeID]
      ,[InvisibleGodown]
      ,[TableID]
      ,[TableName]
      ,[LastID]
      ,[SequenceCode]
      ,[Prefix]
      ,[Suffix]
      ,[LastModificationSnapshotID]
      ,[RelatedCOAID]
      ,[datamode]) select [GodownID]
      ,[KeyField]
      ,[Name]
      ,[Degree]
      ,[Address]
      ,[ContactNO]
      ,[AdditionalInfo1]
      ,[AdditionalInfo2]
      ,[AdditionalInfo3]
      ,[AdditionalInfo4]
      ,[AdditionalInfo5]
      ,[Group]
      ,[Under]
      ,[Hierarchy]
      ,[CreateLog]
      ,[EditLog]
      ,[DeleteLog]
      ,[Active]
      ,[GodownType]
      ,[CustomerID]
      ,[WarehouseTypeID]
      ,[RetailPriceGodownWise_RateTypeID]
      ,[InvisibleGodown]
      ,[TableID]
      ,[TableName]
      ,[LastID]
      ,[SequenceCode]
      ,[Prefix]
      ,[Suffix]
      ,[LastModificationSnapshotID]
      ,[RelatedCOAID]
      ,[datamode] from Godowns where Godownid=".$id;
      odbc_exec($connection,$sql);
      $sqlupdate="update ".$value."Godowns set datamode=1 where Godownid=".$id;
      odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);
    }
      $sqlupdate="update Godowns set datamode=1 where Godownid=".$id;
      odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);

  }//end while  
  //end code for Godowns 
	//code for GoodTransfer 
	$sql="select top 5 * from GoodsTransferMaster where datamode=0 and InvoiceID>0";
		$result=odbc_exec($connection,$sql);
		while($row=odbc_fetch_array($result))
		{
				$id=$row['InvoiceID'];
				foreach ($branches as $key => $value) {
				
        $value1=$value;
  $value=$value->DbName;

			 $deletesql="delete from ".$value."GoodsTransferMaster where InvoiceID=".$id;
			odbc_exec($connection,$deletesql);
			$sql="insert into ".$value."GoodsTransferMaster select * from GoodsTransferMaster where InvoiceID=".$id;
			odbc_exec($connection,$sql);
			
       $GodownTransferID=getnamesingle("GoodsTransferMaster","InvoiceID","ReferenceInvoiceID",$id,$connection);
      //code for good Transfer
      //echo $sql="select InvoiceID from GoodsTransferMaster where ReferenceInvoiceID=".$id;

			 $deletesql="delete from ".$value."GoodsTransferDetail where InvoiceID=".$id;
			odbc_exec($connection,$deletesql);
			$sql="insert into ".$value."GoodsTransferDetail select 

      [InvoiceID]
      ,[ItemID]
      ,[UnitPrice]
      ,[QTY]
      ,[Amount]
      ,[DistributedDiscountAmount]
      ,[UnitID]
      ,[Packing]
      ,[DiscountPercent]
      ,[DiscountAmount]
      ,[BOM_HasIngredients]
      ,[BOM_LevelNo]
      ,[BOM_InventoryIngredientID]
      ,[BOM_ParentTransactionID]
      ,[Show]
      ,[ShowQty]
      ,[ShowRate]
      ,[ShowAmount]
      ,[Narration]
      ,[Attr1]
      ,[Attr2]
      ,[Attr3]
      ,[Attr4]
      ,[Attr5]
      ,[Attr6]
      ,[Attr7]
      ,[Attr8]
      ,[Attr9]
      ,[Attr10]
      ,[Attr11]
      ,[Attr12]
      ,[Attr13]
      ,[Attr14]
      ,[Attr15]
      ,[Attr16]
      ,[Attr17]
      ,[Attr18]
      ,[Attr19]
      ,[Attr20]
      ,[AttrPictureLocation1]
      ,[AttrPictureLocation2]
      ,[WorkOrderProductID]
      ,[LabourCostTypeID]
      ,[LabourCostPerUnit]
      ,[TotalLabourCost]
      ,[IngredientStatusID]
      ,[AllocatedBatchQty]
      ,[BalanceBatchQty]
      ,[WorkOrderID]
      ,[ConsumptionSourceID]
      ,[ItemActualPackingQty]
      ,[InvoicePackingQty]
      ,[UnitPrice1]
      ,[Amount1]
      ,[UnitPrice2]
      ,[Amount2]
      ,[UnitPrice3]
      ,[Amount3]
      ,[BatchLotNo]
      ,[ExpiryDate]
      ,[ItemIDUnder]
      ,[LMQty_L]
      ,[LM1Qty_W]
      ,[DMQty]
      ,[ActualReceivedQty]
      ,[Commission_Price]
      ,[BarCode_Price]
      ,[Diff_in_Price]
      ,[Result]
      ,[Cost_Price]
      ,[Profit]
      ,[BarCode_Amount]
      ,[Net_Price]
      ,[DoPcs]
      ,[DoQty]
      ,[ShipedPcs]
      ,[ShipedQty]
      ,[BalPcs]
      ,[BalQty]
			 from GoodsTransferDetail where InvoiceID=".$id;
			odbc_exec($connection,$sql) or die(odbc_error().$sql);

				}
		 $sqlupdate="update GoodsTransferMaster set datamode=1 where InvoiceID=".$id;
			odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);
     // return;
		}
	//code for salesMaster 
	foreach ($branches as $key => $value) {
    $value1=$value;
  $value=$value->DbName;
  $GodownID=floatval($value1->GodownID);
		odbc_autocommit($connection, FALSE);
		// code for retrieve records from branch 
 $sql="select  * from ".$value."SalesInvoiceMaster where   invoiceid>0 and datamode=0
";//
 //return;
		$result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
		while($row=odbc_fetch_array($result))
		{
			$id=$row['InvoiceID'];
			$GodownID=$row['GodownID'];
      $ReferenceInvoiceID=$row['ReferenceInvoiceID'];
      $KeyField=$row['KeyField'];
      $COAID=$row['CustomerID'];
      $ProjectID=$GodownID;
      $BranchID=$GodownID;
      $InvoiceDate=$row['InvoiceDate'];
      $Active=$row['Active'];
      if($Active==0)
      {


                  $deletesql="update  SalesInvoiceMaster set Active=0 where InvoiceID=".$id;
                  odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);


                  $deletesql="delete from SalesInvoiceDetail where InvoiceID=".$id;
                  odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);


                  $deletesql="delete from StockLedger where InvoiceID=".$id." and InvoiceTypeID=5 and GodownID=".$GodownID;
                  odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);

                 $deletesql="update  VoucherMaster set Active=0 where ReferenceInvoiceID=".$id;
                  odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);

$sqlupdate="update  ".$value."SalesInvoiceMaster set datamode=1 where InvoiceID=".$id;
odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);

      }
      else
      {
			$deletesql="delete from SalesInvoiceMaster where InvoiceID=".$id;
			odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);

	 	$sql="insert into SalesInvoiceMaster([InvoiceID]
      ,[InvoiceDate]
      ,[CheckedBy]
      ,[Narration]
      ,[InvoiceType]
      ,[Active]
      ,[CustomerID]
      ,[GodownID]
      ,[ChallanNo]
      ,[KeyField]
      ,[BillNO]
      ,[GRNno]
      ,[CreateLog]
      ,[EditLog]
      ,[DeleteLog]
      ,[TotalQty]
      ,[TotalAmount]
      ,[DiscountPercent]
      ,[DiscountAmount]
      ,[Rounding]
      ,[NetAmount]
      ,[ReferenceInvoiceID]
      ,[Received]
      ,[Balance]
      ,[PeriodID]
      ,[SalesManID]
      ,[ShipperID]
      ,[BiltyNo]
      ,[StatusID]
      ,[DueDate]
      ,[TotalCashReceived]
      ,[CreditCardAccountID]
      ,[TotalCreditCard]
      ,[PrevBalance]
      ,[CashRefund]
      ,[FOCTotalDiscount]
      ,[KOT_Count]
      ,[DiningTableID]
      ,[PaymentModeID]
      ,[OrderStatusID]
      ,[WorkOrderID]
      ,[AmountInWords]
      ,[InvoiceStatusID]
      ,[TotalQuotationQty]
      ,[TotalQuotationAmount]
      ,[TotalOrderQty]
      ,[TotalOrderAmount]
      ,[TotalInvoiceQty]
      ,[TotalInvoiceAmount]
      ,[TotalReturnQty]
      ,[TotalReturnAmount]
      ,[Advance]
      ,[OrderDateTime]
      ,[TimeElapsed]
      ,[BumpStatusID]
      ,[MemberID]
      ,[MemberDiscountPercent]
      ,[MemberDiscountAmount]
      ,[TokenNumber]
      ,[TotalItemsCount]
      ,[SalesCounterID]
      ,[SUM_GrossAmount]
      ,[SUM_IndividualDiscountAmount]
      ,[TotalDiscountIndividualAndTotalBoth]
      ,[TotalLMQty]
      ,[Order_Status]
      ,[ShiftNo]
      ,[ClaimNo]
      ,[LPONo]
      ,[RefID]
      ,[VehicleID]
      ,[PayCusPercentage]
      ,[PayInsPercentage]
      ,[Active_Service]
      ,[TotalDeliveryQty]
      ,[KeyField_CompanyWise]
      ,[CustomerInsuranceID]
      ,[CurrentBfLuDin]
      ,[JobCustomerStatus]
      ,[JobInsuranceStatus]
      ,[OrderPur_Status]
      ,[Posted]
      ,[PakingReferenceInvoiceID]
      ,[TotalTaxPercent]
      ,[TotalTaxAmount]
      ,[TotalDicTaxAmount]
      ,[AmountBD]
      ,[CurrencyID]
      ,[TotalCurrencyRate]
      ,[TotalCurrencyAmount]
      ,[CostCenterID]
      ,[ActualSalesCash]
      ,[UserID]
      ,[CounterID]
      ,[CashID]
      ,[TotalActualReceivedQty]
      ,[Total_Net_Price]
      ,[Total_Commission_Price]
      ,[VehicleName]
      ,[VehicleMobNo]
      ,[VehicleNumber]
      ,[ReceiverName]
      ,[ReceiverMobNo]
      ,[DnNo]
      ,[AdvanceAmount]
      ,[CommissionLedgerID]
      ,[DoReferenceInvoiceID]
      ,[PickInvoiceFactoryDo]
      ,[GrossAmount]
      ,[AmountExclVat]
      ,[AccountHeadID]
      ,[ScanStatusTrking]
      ,[IsLoyaltyPointsCompleted]
      ,[ToBePosted]
      ,[ShiftID]
      ,[DayCloseID]
      ,[datamode]
      ,[CustomerName]
      ,[MobileNumber]
      ,[Email]
      ,[Address]
      ,[InvoiceStatus]
      ,[AutoVoucherID]) select [InvoiceID]
      ,[InvoiceDate]
      ,[CheckedBy]
      ,[Narration]
      ,[InvoiceType]
      ,[Active]
      ,[CustomerID]
      ,$GodownID
      ,[ChallanNo]
      ,[KeyField]
      ,[BillNO]
      ,[GRNno]
      ,[CreateLog]
      ,[EditLog]
      ,[DeleteLog]
      ,[TotalQty]
      ,[TotalAmount]
      ,[DiscountPercent]
      ,[DiscountAmount]
      ,[Rounding]
      ,[NetAmount]
      ,[ReferenceInvoiceID]
      ,[Received]
      ,[Balance]
      ,[PeriodID]
      ,[SalesManID]
      ,[ShipperID]
      ,[BiltyNo]
      ,[StatusID]
      ,[DueDate]
      ,[TotalCashReceived]
      ,[CreditCardAccountID]
      ,[TotalCreditCard]
      ,[PrevBalance]
      ,[CashRefund]
      ,[FOCTotalDiscount]
      ,[KOT_Count]
      ,[DiningTableID]
      ,[PaymentModeID]
      ,[OrderStatusID]
      ,[WorkOrderID]
      ,[AmountInWords]
      ,[InvoiceStatusID]
      ,[TotalQuotationQty]
      ,[TotalQuotationAmount]
      ,[TotalOrderQty]
      ,[TotalOrderAmount]
      ,[TotalInvoiceQty]
      ,[TotalInvoiceAmount]
      ,[TotalReturnQty]
      ,[TotalReturnAmount]
      ,[Advance]
      ,[OrderDateTime]
      ,[TimeElapsed]
      ,[BumpStatusID]
      ,[MemberID]
      ,[MemberDiscountPercent]
      ,[MemberDiscountAmount]
      ,[TokenNumber]
      ,[TotalItemsCount]
      ,[SalesCounterID]
      ,[SUM_GrossAmount]
      ,[SUM_IndividualDiscountAmount]
      ,[TotalDiscountIndividualAndTotalBoth]
      ,[TotalLMQty]
      ,[Order_Status]
      ,[ShiftNo]
      ,[ClaimNo]
      ,[LPONo]
      ,[RefID]
      ,[VehicleID]
      ,[PayCusPercentage]
      ,[PayInsPercentage]
      ,[Active_Service]
      ,[TotalDeliveryQty]
      ,[KeyField_CompanyWise]
      ,[CustomerInsuranceID]
      ,[CurrentBfLuDin]
      ,[JobCustomerStatus]
      ,[JobInsuranceStatus]
      ,[OrderPur_Status]
      ,[Posted]
      ,[PakingReferenceInvoiceID]
      ,[TotalTaxPercent]
      ,[TotalTaxAmount]
      ,[TotalDicTaxAmount]
      ,[AmountBD]
      ,[CurrencyID]
      ,[TotalCurrencyRate]
      ,[TotalCurrencyAmount]
      ,[CostCenterID]
      ,[ActualSalesCash]
      ,[UserID]
      ,[CounterID]
      ,[CashID]
      ,[TotalActualReceivedQty]
      ,[Total_Net_Price]
      ,[Total_Commission_Price]
      ,[VehicleName]
      ,[VehicleMobNo]
      ,[VehicleNumber]
      ,[ReceiverName]
      ,[ReceiverMobNo]
      ,[DnNo]
      ,[AdvanceAmount]
      ,[CommissionLedgerID]
      ,[DoReferenceInvoiceID]
      ,[PickInvoiceFactoryDo]
      ,[GrossAmount]
      ,[AmountExclVat]
      ,[AccountHeadID]
      ,[ScanStatusTrking]
      ,[IsLoyaltyPointsCompleted]
      ,[ToBePosted]
      ,[ShiftID]
      ,[DayCloseID]
      ,[datamode]
      ,[CustomerName]
      ,[MobileNumber]
      ,[Email]
      ,[Address]
      ,[InvoiceStatus]
      ,[AutoVoucherID] from ".$value."SalesInvoiceMaster where active=1 and  InvoiceID=".$id;
		odbc_exec($connection,$sql) or die(odbc_error().$sql);

		$deletesql="delete from SalesInvoiceDetail where InvoiceID=".$id;
			odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);

$deletesql="delete from stockledger where  InvoiceTypeID=5 and InvoiceID=".$id;
odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);

		 $sql="insert into SalesInvoiceDetail([TransactionID]
      ,[InvoiceID]
      ,[ItemID]
      ,[UnitPrice]
      ,[QTY]
      ,[Amount]
      ,[DistributedDiscountAmount]
      ,[UnitID]
      ,[DiscountPercent]
      ,[DiscountAmount]
      ,[NetAmount]
      ,[FOCRate]
      ,[FOCQty]
      ,[Packing]
      ,[UnitPriceInclusive]
      ,[AmountInclusive]
      ,[FOCDiscount]
      ,[TaxPercent]
      ,[TaxAmount]
      ,[BOM_HasIngredients]
      ,[BOM_LevelNo]
      ,[BOM_InventoryIngredientID]
      ,[BOM_ParentTransactionID]
      ,[Show]
      ,[ShowQty]
      ,[ShowRate]
      ,[ShowAmount]
      ,[Narration]
      ,[DiningTableID]
      ,[KOT_ID]
      ,[KOT_Number]
      ,[KOT_DateTime]
      ,[OrderStatusID]
      ,[IsLocked]
      ,[Attr1]
      ,[Attr2]
      ,[Attr3]
      ,[Attr4]
      ,[Attr5]
      ,[Attr6]
      ,[Attr7]
      ,[Attr8]
      ,[Attr9]
      ,[Attr10]
      ,[Attr11]
      ,[Attr12]
      ,[Attr13]
      ,[Attr14]
      ,[Attr15]
      ,[Attr16]
      ,[Attr17]
      ,[Attr18]
      ,[Attr19]
      ,[Attr20]
      ,[AttrPictureLocation1]
      ,[AttrPictureLocation2]
      ,[WorkOrderProductID]
      ,[IngredientStatusID]
      ,[Batch_ID]
      ,[WorkOrderID]
      ,[ConsumptionSourceID]
      ,[ReferenceInvoiceID]
      ,[ReferenceInvoiceDetailID]
      ,[QuotationQty]
      ,[QuotationAmount]
      ,[OrderQty]
      ,[OrderAmount]
      ,[InvoiceQty]
      ,[InvoiceAmount]
      ,[ReturnQty]
      ,[ReturnAmount]
      ,[NetAmountLessDistributedDiscountAmount]
      ,[DistributedReceivedAmount]
      ,[DistributedReceivedAmountUtilized]
      ,[DistributedBalanceAmount]
      ,[SalesOrderAdvanceRate]
      ,[SalesOrderAdvanceAmount]
      ,[SalesOrderMaxQty]
      ,[EmployeeID]
      ,[EmployeeAssignDateTime]
      ,[DispatchDateTime]
      ,[LMQty_L]
      ,[LM1Qty_W]
      ,[DMQty]
      ,[DocumentName]
      ,[DeliveryQty]
      ,[ItemSize]
      ,[ItemCode]
      ,[ItemColor]
      ,[ItemBrand]
      ,[ItemAInfo2]
      ,[BatchLotNo]
      ,[ExpiryDate]
      ,[CurrencyValue]
      ,[CurrencyRate]
      ,[CurrencyAmount]
      ,[AdditionalInfo1]
      ,[AdditionalInfo2]
      ,[AdditionalInfo3]
      ,[AdditionalInfo4]
      ,[DistributedTaxAmount]
      ,[dGodownID]
      ,[dUserID]
      ,[dCounterID]
      ,[dShiftNo]
      ,[dInvoiceDate]
      ,[dActive]
      ,[dPeriodID]
      ,[dInvoiceTypeID]
      ,[ActualReceivedQty]
      ,[ItemIDUnder]
      ,[Net_Price]
      ,[Commission_Price]
      ,[BarCode_Price]
      ,[BarCode_Amount]
      ,[Diff_in_Price]
      ,[Result]
      ,[Cost_Price]
      ,[Profit]
      ,[Commission_Amount]
      ,[DoPcs]
      ,[DoQty]
      ,[BalPcs]
      ,[BalQty]
      ,[ShipedPcs]
      ,[ShipedQty]
      ,[DeliverToName]
      ,[OrderKeyField]
      ,[DeliverToID]
      ,[StandardPrice3]
      ,[StandardPrice1]
      ,[Cost_Amount]) select [TransactionID]
      ,[InvoiceID]
      ,[ItemID]
      ,[UnitPrice]
      ,[QTY]
      ,[Amount]
      ,[DistributedDiscountAmount]
      ,[UnitID]
      ,[DiscountPercent]
      ,[DiscountAmount]
      ,[NetAmount]
      ,[FOCRate]
      ,[FOCQty]
      ,[Packing]
      ,[UnitPriceInclusive]
      ,[AmountInclusive]
      ,[FOCDiscount]
      ,[TaxPercent]
      ,[TaxAmount]
      ,[BOM_HasIngredients]
      ,[BOM_LevelNo]
      ,[BOM_InventoryIngredientID]
      ,[BOM_ParentTransactionID]
      ,[Show]
      ,[ShowQty]
      ,[ShowRate]
      ,[ShowAmount]
      ,[Narration]
      ,[DiningTableID]
      ,[KOT_ID]
      ,[KOT_Number]
      ,[KOT_DateTime]
      ,[OrderStatusID]
      ,[IsLocked]
      ,[Attr1]
      ,[Attr2]
      ,[Attr3]
      ,[Attr4]
      ,[Attr5]
      ,[Attr6]
      ,[Attr7]
      ,[Attr8]
      ,[Attr9]
      ,[Attr10]
      ,[Attr11]
      ,[Attr12]
      ,[Attr13]
      ,[Attr14]
      ,[Attr15]
      ,[Attr16]
      ,[Attr17]
      ,[Attr18]
      ,[Attr19]
      ,[Attr20]
      ,[AttrPictureLocation1]
      ,[AttrPictureLocation2]
      ,[WorkOrderProductID]
      ,[IngredientStatusID]
      ,[Batch_ID]
      ,[WorkOrderID]
      ,[ConsumptionSourceID]
      ,[ReferenceInvoiceID]
      ,[ReferenceInvoiceDetailID]
      ,[QuotationQty]
      ,[QuotationAmount]
      ,[OrderQty]
      ,[OrderAmount]
      ,[InvoiceQty]
      ,[InvoiceAmount]
      ,[ReturnQty]
      ,[ReturnAmount]
      ,[NetAmountLessDistributedDiscountAmount]
      ,[DistributedReceivedAmount]
      ,[DistributedReceivedAmountUtilized]
      ,[DistributedBalanceAmount]
      ,[SalesOrderAdvanceRate]
      ,[SalesOrderAdvanceAmount]
      ,[SalesOrderMaxQty]
      ,[EmployeeID]
      ,[EmployeeAssignDateTime]
      ,[DispatchDateTime]
      ,[LMQty_L]
      ,[LM1Qty_W]
      ,[DMQty]
      ,[DocumentName]
      ,[DeliveryQty]
      ,[ItemSize]
      ,[ItemCode]
      ,[ItemColor]
      ,[ItemBrand]
      ,[ItemAInfo2]
      ,[BatchLotNo]
      ,[ExpiryDate]
      ,[CurrencyValue]
      ,[CurrencyRate]
      ,[CurrencyAmount]
      ,[AdditionalInfo1]
      ,[AdditionalInfo2]
      ,[AdditionalInfo3]
      ,[AdditionalInfo4]
      ,[DistributedTaxAmount]
      ,[dGodownID]
      ,[dUserID]
      ,[dCounterID]
      ,[dShiftNo]
      ,[dInvoiceDate]
      ,[dActive]
      ,[dPeriodID]
      ,[dInvoiceTypeID]
      ,[ActualReceivedQty]
      ,[ItemIDUnder]
      ,[Net_Price]
      ,[Commission_Price]
      ,[BarCode_Price]
      ,[BarCode_Amount]
      ,[Diff_in_Price]
      ,[Result]
      ,[Cost_Price]
      ,[Profit]
      ,[Commission_Amount]
      ,[DoPcs]
      ,[DoQty]
      ,[BalPcs]
      ,[BalQty]
      ,[ShipedPcs]
      ,[ShipedQty]
      ,[DeliverToName]
      ,[OrderKeyField]
      ,[DeliverToID]
      ,[StandardPrice3]
      ,[StandardPrice1]
      ,[Cost_Amount] from ".$value."SalesInvoiceDetail where InvoiceID=".$id;

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

		//code for stockledger 
		 $sqlStock="select * from SalesInvoiceDetail where InvoiceID=".$id;
		$resultStock=odbc_exec($connection,$sqlStock) or die(odbc_error().$sqlStock);
		$subtotal=0;
		while($rowStock=odbc_fetch_array($resultStock))
		{
			$ITEMID=$rowStock['ItemID'];
			$Rate=$rowStock['StandardPrice3'];
			$Qty=$rowStock['QTY'];
      $Attr1=$rowStock['Attr1'];
      $Attr2=$rowStock['Attr2'];
      $Attr3=$rowStock['Attr3'];
      $Attr4=$rowStock['Attr4'];
      $Attr5=$rowStock['Attr5'];
      $Attr6=$rowStock['Attr6'];
      $Attr7=$rowStock['Attr7'];
      $Attr8=$rowStock['Attr8'];
      $Attr9=$rowStock['Attr9'];
      $Attr10=$rowStock['Attr10'];
      $InvoiceID=$rowStock['InvoiceID'];
      $ReferenceInvoiceID=$rowStock['ReferenceInvoiceID'];
      $InvoiceType=5;
      $Remarks=$rowStock['Narration'];
      $SupplierID=$COAID;
$Active=1;
$ContainerNo=$rowStock['Narration'];
$ExpiryDate=$InvoiceDate;
$DepartmentID=7;
$ItemJson="";
$VoucherID=0;
$UserID=1;
//code for BOM 

//end code for BOM
	$deletesql="delete from stockledger where ItemID=".$ITEMID." and InvoiceTypeID=5 and InvoiceID=".$id;
odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);
		//code for material 
		

	
		$subtotal=$subtotal+($Rate*1);//$Qty
    //code for BOM (Bill of Material)
    //generateRawMaterial();
  $sqlmaterial="select * from inventory_ingredients where ItemID=$ITEMID";
           $resultmaterial=odbc_exec($connection,$sqlmaterial);
           if(odbc_num_rows($resultmaterial)>0)
           {
           while($rowmaterial=odbc_fetch_array($resultmaterial))
           {
                          $ID=getmaxId("stockledger","ID",$connection)+1;

            $MaterialID=$rowmaterial['MaterialID'];
            $Qty2=$rowmaterial['Qty'];
            $Qt=$Qty*$Qty2;
                      //code for stock ledger 
  $sql="INSERT INTO [StockLedger]
           (ID,[ItemID],[ReferenceItemID],[Qty],[InvoiceTypeID],[InvoiceID],[ReferenceInvoiceID],[Reference],[Remarks],[GodownID],[ProjectID],[BranchID],[COAID],[Active],[ContainerNo],[UserID],[Rate],[CounterID],[VoucherID],[TransDate],[ExpiryDate],[SupplierID],[DepartmentID],ItemJson,Attr1,Attr2,Attr3,Attr4,Attr5,Attr6,Attr7,Attr8,Attr9,Attr10)
     VALUES ($ID,$MaterialID,$ITEMID,".(-1*$Qt).",$InvoiceType,$InvoiceID,$ReferenceInvoiceID,'$KeyField','$Remarks',$GodownID,$ProjectID,$BranchID,$COAID,$Active,'$ContainerNo',$UserID,$Rate,$GodownID,$VoucherID,'$InvoiceDate','$ExpiryDate',$SupplierID,$DepartmentID,'".$ItemJson."','".$Attr1."','".$Attr2."','".$Attr3."','".$Attr4."','".$Attr5."','".$Attr6."','".$Attr7."','".$Attr8."','".$Attr9."','".$Attr10."')"; 
      odbc_exec($connection, $sql) or die(odbc_error().$sql);

         }
       }//end if result material 
       else
       {
  $STKID=getmaxId("stockledger","ID",$connection)+1;
     $sqlStock="insert into StockLedger (ID,InvoiceTypeID,ITEMID,InvoiceID,Rate,QTY,Remarks,Attr8,TransDate,GodownID,SupplierID,COAID,Active,ReferenceInvoiceID,
  Attr1,Attr2,Attr3,Attr4,Attr5,Attr6,Attr7,Attr9,Attr10,Reference)
    select $STKID,5,ITEMID,sim.InvoiceID,".$Rate.",(QTY*-1),sid.Narration,UnitID,InvoiceDate,GodownID,CustomerID,CustomerID,Active,sim.ReferenceInvoiceID,
  Attr1,Attr2,Attr3,Attr4,Attr5,Attr6,Attr7,Attr9,Attr10,KeyField
   from SalesInvoiceDetail as sid inner join SalesInvoiceMaster as sim on sim.InvoiceID=sid.InvoiceID where sim.InvoiceID=".$id." and sid.ITEMID=".$ITEMID;
odbc_exec($connection,$sqlStock) or die(odbc_error().$sqlStock);

       }
    //end code 
		}//end Stock Ledger Entry
		//entry for cost of good sold
//		COGS DEbit 

//		Inventory credit
		//GenerateCostOfGoodSold($connection,$id,$subtotal,$value);
		//end code for cost of good sold 

/*$sqlupdate=" update ".$value."VoucherMaster set LocationID=$GodownID where datamode=0";
odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);*/
		//update the branch record 
//echo $sql="select * from SalesInvoiceMaster where active=1 and InvoiceID=".$id;
 $r=GenerateSalesVoucherPayment($connection,$id,$_SESSION['UserName'],$value,$subtotal,$GodownID);
 //return;
/*if($r!=1)
{

  echo $r;*/
//echo "Not Generated";  
//return;  
//}
/*$sqlupdate=" update VoucherMaster set LocationID=$GodownID where ReferenceInvoiceID=".$id;
odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);*/

$sqlupdate="update  ".$value."SalesInvoiceMaster set datamode=1 where InvoiceID=".$id;
odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);
//code for sales voucher 
/*$sql="select * from ".$value."vouchermaster where ReferenceInvoiceID=".$InvoiceID;
$result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {

	}*/

//end code for sales voucher 			
$deletesql="delete from ".$value."SyncTableStatus where PrimaryKeyID=".$id." and TableName='SalesInvoiceMaster'";
odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);

$syntableid=getmaxId("".$value."SyncTableStatus","ID",$connection)+1;
 $sqlupdate="insert into ".$value."SyncTableStatus(ID,TableName,PrimaryKeyID,PrimaryFieldName,datamode,GodownID) values($syntableid,'SalesInvoiceMaster',$id,'InvoiceID',0,$GodownID) ";
			odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);
            }//end if ELese for Active Record
		}//end while 
		/*while($row=odbc_fetch_array($result))
		{
			$id=$row['ID'];

		}//end while */
			//code for Vouchers 
$sql="select * from ".$value."vouchermaster where VoucherTypeID not in (2,3,4,7,11,10,6) and datamode=0";
			$result=odbc_exec($connection,$sql);
			while($row=odbc_fetch_array($result))	
			{

	$VoucherID=getMaxLocationID("VoucherMaster","VoucherID","LocationID=1",$connection)+1;//getmaxId("VoucherMaster","VoucherID",$connection)+1;
				$VoucherIDOLD=$row['VoucherID'];
				$VoucherTypeID=$row['VoucherTypeID'];
				$VoucherNo=$row['VoucherNo'];
				$ReferenceInvoiceID=$row['ReferenceInvoiceID'];
				$LocationID=$row['LocationID'];
				$Active=$row['Active'];
if($VoucherTypeID=="8")
$deletesql="delete from VoucherMaster  where  VoucherID=".$VoucherIDOLD;            
else
//$deletesql="update VoucherMaster set Active=0 where VoucherID=".$VoucherIDOLD;	
$deletesql="delete from VoucherMaster  where  VoucherID=".$VoucherIDOLD;            		
odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);

$deletesql="delete voucherdetails where VoucherID=".$VoucherIDOLD;;				
if($VoucherTypeID=="8")
odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);

if($Active==1)
{
			if($VoucherTypeID==1)$VoucherTypeID=5;
			if($VoucherTypeID==2)$VoucherTypeID=5;
			
			if($VoucherTypeID==3)$VoucherTypeID=6;
			if($VoucherTypeID==4)$VoucherTypeID=6;

				if($VoucherTypeID==5)$VoucherTypeID=7;
				elseif($VoucherTypeID==6)$VoucherTypeID=71;
				elseif($VoucherTypeID==7)$VoucherTypeID=8;
if($LocationID==1)
{
if($VoucherTypeID==5)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=5 and LocationID=1",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,7,"0",STR_PAD_LEFT);
          $VoucherNo="RV-".$VoucherNo;
        }
        if($VoucherTypeID==6)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=6 and LocationID=1",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,7,"0",STR_PAD_LEFT);
          $VoucherNo="PV-".$VoucherNo;
        }
        if($VoucherTypeID==8)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=8 and LocationID=1",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,7,"0",STR_PAD_LEFT);
          $VoucherNo="SV-".$VoucherNo;
        }
        if($VoucherTypeID==7)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=7  and LocationID=1",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,7,"0",STR_PAD_LEFT);
          $VoucherNo="JV-".$VoucherNo;
        }
        if($VoucherTypeID==10)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=10  and LocationID=1",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,7,"0",STR_PAD_LEFT);
          $VoucherNo="PTC-".$VoucherNo;
        }
}

$sqlinsert="insert into vouchermaster (VoucherID,[VoucherNo]
      ,[TotalAmount]
      ,[Active]
      ,[VoucherDate]
      ,[Narration]
      ,[Posted]
      ,[IsPostDated]
      ,[PostDate]
      ,[VoucherTypeID]
      ,[ChequeNo]
      ,[PONO]
      ,[DD]
      ,[TC]
      ,[PeriodID]
      ,[ReferenceInvoiceID]
      ,[ClientBankAccountName]
      ,[LedgerID]
      ,[AmountDebit]
      ,[AmountCredit]
      ,[IsAuto]
      ,[WorkOrderID]
      ,[LocationID]
      ,[VoucherPostDateTime]
      ,[CreateLog]
      ,[EditLog]
      ,[DeleteLog]
      ,[EmployeeID]
      ,[CostCenterID]
      ,[Received]
      ,[Balance]
      ,[ReferenceVoucherID]
      ,[GroupID]
      ,[ClientPayeeName]
      ,[AmountInWords]
      ,[PostDatedCh]
      ,[MultiVoucher]
      ,[VoucherToBePosted]
      ,[Cash]
      ,[PDCDayshold]
      ,[ChequeStatus]
      ,[SelectionID]
      ,[PDCPostDate]
      ,[PDCPostHoldDate]
      ,[IsVoucherReturnCheque]
      ,[ContractID]
      ,[UserID]
      ,[ApprovalDate]
      ,[ApprovalDescription]
      ,[ApprovalDescriptionReturn]
      ,[ApprovalToBePosted]
      ,[ApprovalToBeReturn]
      ,[CounterID]
      ,[ShiftNo]
      ,[NatureID]
      ,[InvoiceTypeID]
      ,[BankBranchName]
      ,[BankLedgerID]
      ,[PDCVoucherReferenceID]
      ,[ChequeStatusID]
      ,[BankDate]
      ,[NewLedgerID]
      ,[NewChequeStatusID]
      ,[PaymentID]
      ,[VoucherReferenceInvoiceID]
      ,[IsAutoPettyCashVoucher])
SELECT VoucherID
      ,'".$VoucherNo."'
      ,[TotalAmount]
      ,[Active]
      ,[VoucherDate]
      ,[Narration]
      ,[Posted]
      ,[IsPostDated]
      ,[PostDate]
      ,".$VoucherTypeID."
      ,[ChequeNo]
      ,[PONO]
      ,[DD]
      ,[TC]
      ,[PeriodID]
      ,[ReferenceInvoiceID]
      ,[ClientBankAccountName]
      ,[LedgerID]
      ,[AmountDebit]
      ,[AmountCredit]
      ,[IsAuto]
      ,[WorkOrderID]
      ,[LocationID]
      ,[VoucherPostDateTime]
      ,[CreateLog]
      ,[EditLog]
      ,[DeleteLog]
      ,[EmployeeID]
      ,[CostCenterID]
      ,[Received]
      ,[Balance]
      ,[ReferenceVoucherID]
      ,[GroupID]
      ,[ClientPayeeName]
      ,[AmountInWords]
      ,[PostDatedCh]
      ,[MultiVoucher]
      ,[VoucherToBePosted]
      ,[Cash]
      ,[PDCDayshold]
      ,[ChequeStatus]
      ,[SelectionID]
      ,[PDCPostDate]
      ,[PDCPostHoldDate]
      ,[IsVoucherReturnCheque]
      ,[ContractID]
      ,[UserID]
      ,[ApprovalDate]
      ,[ApprovalDescription]
      ,[ApprovalDescriptionReturn]
      ,[ApprovalToBePosted]
      ,[ApprovalToBeReturn]
      ,[CounterID]
      ,[ShiftNo]
      ,[NatureID]
      ,[InvoiceTypeID]
      ,[BankBranchName]
      ,[BankLedgerID]
      ,[PDCVoucherReferenceID]
      ,[ChequeStatusID]
      ,[BankDate]
      ,[NewLedgerID]
      ,[NewChequeStatusID]
      ,[PaymentID]
      ,[VoucherReferenceInvoiceID]
      ,[IsAutoPettyCashVoucher]
  FROM ".$value."[VoucherMaster] where VoucherID=".$VoucherIDOLD;

odbc_exec($connection,$sqlinsert);

$sqlupdate="update ".$value."[VoucherMaster] set datamode=1 where VoucherID=".$VoucherIDOLD;
odbc_exec($connection,$sqlupdate);
//code for Voucher Details 
$sqldelete ="delete from VoucherDetails where VoucherID=".$VoucherIDOLD;
odbc_exec($connection,$sqldelete);

if($LocationID>1)
$GStart=getnamesingle("Godowns","AdditionalInfo3","GodownID",$LocationID,$connection);


$sqldetail="insert into voucherdetails (VoucherID,[LedgerID],[Debit],[Credit],[Narration],[ReferenceInvoiceID],DetailLocationID,[EmployeeID],[ChequeNo],[InstrumentDate],[ChequeAmount],[CostCenterID],[CreditLedgerID],[dInvoiceTypeID])
SELECT VoucherID
      ,case when isnull([LedgerID],0)>100000 then (isnull([LedgerID],0)-(select isnull(convert(numeric(14),(case when AdditionalInfo3='' then 0 else AdditionalInfo3 end)),0) from Godowns  where GodownID= ".$LocationID.")) else isnull(LedgerID,0) end as LedgerID
      ,[Debit]
      ,[Credit]
      ,[Narration]
      ,[ReferenceInvoiceID]
      ,LocationID
      ,[EmployeeID]
      ,[ChequeNoD]
      ,[InstrumentDate]
      ,case when [ChequeAmount] is null then 0 else [ChequeAmount] end as [ChequeAmount]
      ,[CostCenterID]
      ,case when isnull([CreditLedgerID],0)>100000 then (isnull([CreditLedgerID],0)-(select isnull(convert(numeric(14),(case when AdditionalInfo3='' then 0 else AdditionalInfo3 end)),0) from Godowns where GodownID= ".$LocationID.")) else isnull(CreditLedgerID,0) end as [CreditLedgerID]
      ,[dInvoiceTypeID]
  FROM ".$value."[vw_VoucherDetails_Online] where VoucherID=".$VoucherIDOLD;
odbc_exec($connection,$sqldetail) or die(odbc_error().$sqldetail);
//end code for voucher details 
//update syntable 
$deletesql="delete from ".$value."SyncTableStatus where PrimaryKeyID=".$id." and TableName='VoucherMaster'";
odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);

$syntableid=getmaxId("".$value."SyncTableStatus","ID",$connection)+1;

$sqlupdate="insert into ".$value."SyncTableStatus(ID,TableName,PrimaryKeyID,PrimaryFieldName,datamode,GodownID) values($syntableid,'VoucherMaster',$VoucherIDOLD,'VoucherID',0,$GodownID) ";
			odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);

}//end Active if 
			}
	 if (!odbc_error())
	 {
      odbc_commit($connection);
	    $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
	}
else
{
      odbc_rollback($connection);
	    $res=array('status'=>"Error",'description'=>'Record  Not Updated');

}
	}


	echo $d;
}
if(isset($_POST['username']))
{
//print_r($_POST);
	$username=$_POST['username'];
	$password=$_POST['password'];
$upassword="";
	  $sql="select UserName,convert(nvarchar(max),[Password]) as password,UserID,CompanyID from UserAccounts where UserName='$username'";
	$result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
	if(odbc_num_rows($result)>0)
	{
		$upassword=odbc_result($result,2);
		$userid=odbc_result($result,3);
    $CompanyID=odbc_result($result,4);
		/*$PassCode=odbc_result($result,4);
		$Picture=odbc_result($result,5);
		$fullname=odbc_result($result,6);
		$phone=odbc_result($result,7);	
		$gender=odbc_result($result,8);	*/						
	}
	if($password==$upassword)
	{
		$_SESSION['userid']=$userid;
		$_SESSION['UserName']=$username;
		$_SESSION['PassCode']='';//$PassCode;
    $_SESSION['CompanyID']=$CompanyID;//$PassCode;
		//$_SESSION['Picture']=$Picture;
		/*$_SESSION['fullname']=$fullname;
		$_SESSION['phone']=$phone;
		$_SESSION['gender']=$gender;*/									
		// get Running Period
		//
		$sqlsetting="select COAID,'CASHINHAND' as COAName from accounts where COAName like '%cash in hand%' and Degree=5
union
select COAID,'CASHCUSTOMERS' as COAName from accounts where COAName like '%cash customers%' and Degree=5
union
select COAID,'PURCHASES' as COAName from accounts where COAName like '%Purchases%' and Degree=5
union
select COAID,'PURCHASERETURN' as COAName from accounts where COAName like '%Purchase Ret%' and Degree=5
union
select COAID,'VATSALES' as COAName from accounts where COAName like '%VAT-OUTPUT%' and Degree=5
union
select COAID,'VATPURCHASE' as COAName from accounts where COAName like '%VAT-INPUT%' and Degree=5
union
select COAID,'VATPURCHASE' as COAName from accounts where COAName like '%VAT-INPUT%' and Degree=5
union
select COAID,'SALES' as COAName from accounts where COAName like 'sales%' and Degree=5
union
select COAID,'CREDITCARD' as COAName from accounts where COAName like 'credit card%' and Degree=5
union
select COAID,'RTAHEAD' as COAName from accounts where COAName like '%(RTA)%' and Degree=5
";
$sqlsetting="select * from master_values where textboxname='accountsetup'";

		$resultsetting=odbc_exec($connection,$sqlsetting);
		while($row=odbc_fetch_array($resultsetting))
		{
			$COAName=$row['MasterValue'];
			$_SESSION['SETTING'][$COAName]=$row['Code'];
		}/*
		$_SESSION['SETTING']['OPENINGBALANCE']=false;
		$sqlperiod="select top 1 MonthID
      ,StartDate
      ,EndDate
      ,DaysInMonth
      ,MonthDesc,active from monthmaster where active=1 ";
		$resultperiod=odbc_exec($connection,$sqlperiod);
		if(odbc_num_rows($result)>0)
		{
		$_SESSION['StartDate']=odbc_result($resultperiod,2);
		$_SESSION['EndDate']=odbc_result($resultperiod,3);
		$_SESSION['DaysInMonth']=odbc_result($resultperiod,4);
		$_SESSION['MonthDesc']=odbc_result($resultperiod,5);
						
		}*/
		echo 1;
	}
	else
	{
		echo 0;
	}
//	echo $upassword;
}

if(isset($_GET['id']))
{
	$id=$_GET['id'];
$data=array();
	$result=odbc_exec($connection, "select *  FROM VisitMaster where id='$id'");
  while ($row = odbc_fetch_array($result)) {
//$id=$row[0];
  	
    $data []=$row;
    
  }
   echo json_encode($data);

}


?>