package main_package;

import group_head_package.JournalInfo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.primefaces.context.RequestContext;
import org.primefaces.json.JSONArray;
import org.primefaces.json.JSONObject;
import org.primefaces.model.UploadedFile;

import other_package.ProblemInfo;
import other_package.ReportInfo;
import report_package.BorrowerLenderInfo;
import report_package.CommanInfo;
import report_package.DataBaseReportMethods;
import report_package.MembersOdInfo;

public class DataBaseMethods implements Serializable
{	
	String onlineFileViewPath="";
	String onlineFileUploadPath="";
	DecimalFormat df=new DecimalFormat("##.##");
	SimpleDateFormat sf=new SimpleDateFormat("dd/MM/yyyy");
	SimpleDateFormat sdfForDb=new SimpleDateFormat("yyyy-MM-dd");  
	
	
	
	public ArrayList<LoanInfo> fetchallLoanNobyshareholderNo(
	        Connection conn, String shareHolderNo) {

	    ArrayList<LoanInfo> infoList = new ArrayList<>();

	    String[] tableNames = {
	        "grouploan",
	        "personalloan",
	        "secure_loan"
	    };

	    String qq = "";

	    try (Statement st = conn.createStatement()) {

	        for (String table : tableNames) {

	            if (table.equalsIgnoreCase("grouploan")) {
	                qq = "SELECT sub_loan_no, status, paidStatus, approvalDate "
	                   + "FROM grouploan "
	                   + "WHERE status = 'Approve' "
	                   + "AND paidStatus = 'unpaid' "
	                   + "AND teamLeader = '" + shareHolderNo + "'";
	            } else {
	                qq = "SELECT loanNo, status, paidStatus, approvalDate "
	                   + "FROM " + table + " "
	                   + "WHERE status = 'Approve' "
	                   + "AND paidStatus = 'unpaid' "
	                   + "AND shareholderno = '" + shareHolderNo + "'";
	            }

	            try (ResultSet rr = st.executeQuery(qq)) {

	                while (rr.next()) {

	                    LoanInfo info = new LoanInfo();

	                    if (table.equalsIgnoreCase("grouploan")) {
	                        info.setLoanNo(rr.getString("sub_loan_no"));
	                    } else {
	                        info.setLoanNo(rr.getString("loanNo"));
	                    }

	                    info.setStatus(rr.getString("status"));
	                    info.setPaidStatus(rr.getString("paidStatus"));

	                    infoList.add(info);
	                }
	            }
	        }

	    } catch (Exception e) {
	        e.printStackTrace();
	    }

	    return infoList;
	}
	
	
	
	public ArrayList<ReportInfo> incomeListByLoanNo(String loanNo, String itemName) 
	{
		ArrayList<ReportInfo> incomeList=new ArrayList<>();
		
		Statement st=null;
		ResultSet rs=null;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			st=conn.createStatement();
//			String query="select income_date,voucher_no,description,sum(amount) from income_table where loan_no='"+loanNo+"' and item='"+itemName+"' and status='active' and chequeStatus='cleared'"
//					+ " group by income_date";
			String query = "SELECT income_date, voucher_no, description, "
			        + "SUM(amount) AS total_amount "
			        + "FROM income_table "
			        + "WHERE loan_no='"+loanNo+"' "
			        + "AND item='"+itemName+"' "
			        + "AND status='active' "
			        + "AND chequeStatus='cleared' "
			        + "GROUP BY income_date, voucher_no, description";
			
			////System.out.println(query);
			
			rs=st.executeQuery(query);
			while(rs.next())
			{
				ReportInfo obj= new ReportInfo();
				
				obj.setAmount(rs.getDouble("total_amount"));
				obj.setCreditAmount(obj.getAmount());
				obj.setStatus(itemName);
				obj.setDate(rs.getDate("income_date"));
				obj.setDateStr(sf.format(rs.getDate("income_date")));
				obj.setReceiptNo(rs.getString("voucher_no"));
				obj.setRemark(rs.getString("description"));
				
				incomeList.add(obj);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} 
			catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return incomeList;
	}	
	
	public int editMemberInLoanTable(String loanNo, String tableName, String newMember) 
	{   
		String qq="";
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			Statement st1=conn.createStatement();
			if(tableName.equalsIgnoreCase("grouploan"))
			{
				qq="update grouploan set teamLeader='"+newMember+"' where sub_loan_no='"+loanNo+"' ";
			}
			else
			{
				qq="update "+tableName+" set shareholderno='"+newMember+"' where loanNo='"+loanNo+"' ";
			}
			//System.out.println(qq);
			int j=	st.executeUpdate(qq);
			if(j>0)
			{
				String qq1="update debit_loan set shareholderno='"+newMember+"' where loanNo='"+loanNo+"' and loanType='"+tableName+"' ";
				//System.out.println(qq1);
				st1.executeUpdate(qq1);
				return j;
			}
			
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
   public String selectQueWithBranch(String query,int branchId)
	{
		
		if(branchId==-1)
		{
			return query;
//			if(query.contains("where"))
//			{
//				query=query+" and "+branchBuilder();
//			}
//			else
//			{
//				query=query+" where"+branchBuilder();
//			}
		}
		else
		{
			if(query.contains("where"))
			{
				query=query+" and branch_id='"+branchId+"'";
			}
			else
			{
				query=query+" where branch_id='"+branchId+"'";
			}
		}
		
		//System.out.println(query);
		return query;
	}
   
   
   public LoanInfo loanDocumentsForView(String loanType, String loanNo, LoanInfo uu) 
	{
		String qq="";
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(loanType.equalsIgnoreCase("grouploan") || loanType.equalsIgnoreCase("Group Loan"))
			{
				qq="select * from "+loanType+" where sub_loan_no='"+loanNo+"' ";
			}
			else
			{
				qq="select * from "+loanType+" where loanNo='"+loanNo+"' ";
			}
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				filePathDetail(conn);  //for set online view path if exist
				if(onlineFileViewPath==null || onlineFileViewPath.trim().equals(""))
				{
					uu.setDoc1Path(rs.getString("doc1"));
					uu.setDoc2Path(rs.getString("doc2"));
					uu.setDoc3Path(rs.getString("doc3")); 
					uu.setDoc4Path(rs.getString("doc4"));
					uu.setDoc5Path(rs.getString("doc5"));
					uu.setDoc6Path(rs.getString("doc6"));
					uu.setDoc7Path(rs.getString("doc7"));
					uu.setDoc8Path(rs.getString("doc8")); 
					uu.setDoc9Path(rs.getString("doc9"));
					uu.setDoc10Path(rs.getString("doc10"));
				}
				else
				{
					uu.setDoc1Path(onlineFileViewPath+rs.getString("doc1"));
					uu.setDoc2Path(onlineFileViewPath+rs.getString("doc2"));
					uu.setDoc3Path(onlineFileViewPath+rs.getString("doc3"));
					uu.setDoc4Path(onlineFileViewPath+rs.getString("doc4"));
					uu.setDoc5Path(onlineFileViewPath+rs.getString("doc5"));
					uu.setDoc6Path(onlineFileViewPath+rs.getString("doc6"));
					uu.setDoc7Path(onlineFileViewPath+rs.getString("doc7"));
					uu.setDoc8Path(onlineFileViewPath+rs.getString("doc8")); 
					uu.setDoc9Path(onlineFileViewPath+rs.getString("doc9"));
					uu.setDoc10Path(onlineFileViewPath+rs.getString("doc10"));
				}
				
				uu.setDoc1PathForEdit(rs.getString("doc1"));
				uu.setDoc2PathForEdit(rs.getString("doc2"));
				uu.setDoc3PathForEdit(rs.getString("doc3")); 
				uu.setDoc4PathForEdit(rs.getString("doc4"));
				uu.setDoc5PathForEdit(rs.getString("doc5"));
				uu.setDoc6PathForEdit(rs.getString("doc6"));
				uu.setDoc7PathForEdit(rs.getString("doc7"));
				uu.setDoc8PathForEdit(rs.getString("doc8")); 
				uu.setDoc9PathForEdit(rs.getString("doc9"));
				uu.setDoc10PathForEdit(rs.getString("doc10"));
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return uu;
	}
   
   
   
   public int updateLoanDocumentDetail(String id, String loanType,String doc1Path, String doc2Path,
			String doc3Path, String doc4Path, String doc5Path,String doc6Path, String doc7Path,
			String doc8Path, String doc9Path, String doc10Path) 
	{  
	   System.out.println("photo managepersonl photo hit");
	   int i=0;
		try (Connection conn = DataBaseConnection.JAVAConnection();)
		{
			String query="update "+loanType+" set doc1=?, doc2=?, doc3=?, doc4=?, doc5=?,doc6=?, doc7=?, doc8=?, doc9=?, doc10=? where id=?";
			////System.out.println(query);
			PreparedStatement st1 = conn.prepareStatement(query);
			st1.setString(1, doc1Path);
			st1.setString(2, doc2Path);
			st1.setString(3, doc3Path);
			st1.setString(4, doc4Path);
			st1.setString(5, doc5Path);
			st1.setString(6, doc6Path);
			st1.setString(7, doc7Path);
			st1.setString(8, doc8Path);
			st1.setString(9, doc9Path);
			st1.setString(10, doc10Path);
			st1.setString(11, id);
			 i = st1.executeUpdate();
			if (i >= 1)
			{
				dataInsertInQueryTable(String.valueOf(st1), conn);
				return i;
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}
		
   public String selectQueWithBranch(String query,int branchId,String tableName)
	{
		if(branchId==-1)
		{
			
			if(query.contains("where"))
			{
				query=query+" and "+branchBuilder(tableName);
			}
			else
			{
				query=query+" where"+branchBuilder(tableName);
			}
		}
		else
		{
			if(query.contains("where"))
			{
				query=query+" and "+tableName+".branch_id='"+branchId+"'";
			}
			else
			{
				query=query+" where "+tableName+".branch_id='"+branchId+"'";
			}
		}
		
		////System.out.println(query);
		return query;
	}
   
   
   
  public String selectBranchName(int branchid) {
	  String branchName="";
	  
	  try (Connection con =DataBaseConnection.JAVAConnection()){
		  
		  Statement st =con.createStatement();
		  String qq="select branch_name from firm_detail where id='"+branchid+"' ";
		  ResultSet rr=st.executeQuery(qq);
		   while(rr.next())
		   {
			   branchName = rr.getString("branch_name");
			   
		   }
		
	} catch (Exception e) {
		// TODO: handle exception
	}
	return branchName;
	
}
   public String branchBuilder()
   {
	    HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		String branchUserId = (String) ss.getAttribute("branchUserId");
		String que="(";
		int i=0;
		try(Connection con = DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select branch_id from branch_allocate_table where user_id ='"+branchUserId+"'";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				if(i==0)
				{
					que=que+"branch_id='"+rr.getString("branch_id")+"'";
					i++;
				}
				else
				{
					que=que+"or branch_id='"+rr.getString("branch_id")+"'";
				}
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();
		}
		return que+") ";
   }
   
   public String branchBuilder(String tableName)
   {
	    HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		String branchUserId = (String) ss.getAttribute("branchUserId");
		String que="(";
		int i=0;
		try(Connection con = DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select branch_id from branch_allocate_table where user_id ='"+branchUserId+"'";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				if(i==0)
				{
					que=que+tableName+".branch_id='"+rr.getString("branch_id")+"'";
					i++;
				}
				else
				{
					que=que+"or "+tableName+".branch_id='"+rr.getString("branch_id")+"'";
				}
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();
		}
		return que+") ";
   }
	
	public static String selectedSessionDetail()
    {
        HeaderBean nn=new HeaderBean();
        return nn.getSelectedSession() ;
    }
	
	
	public boolean personalLoanNoDuplicacy(String loanNo, Connection conn) 
	{  
		 System.out.println("loan no is in duplcaete"+loanNo);
		System.out.println("value of the loanno DBS :"+loanNo);
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select loanNo from personalloan where loanNo='"+loanNo+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return false;
	}
	
	
	public void dataInsertInQueryTable(String query, Connection conn) 
	{
		String userId=userId();
		Timestamp tt=new Timestamp(new Date().getTime());
		tt.setNanos(0);
		
		String qq="insert into query_table(query_time, query, user_id) values(?,?,?)";
		try 
		{
			PreparedStatement st=conn.prepareStatement(qq);
			st.setTimestamp(1, tt);
			st.setString(2, query);
			st.setString(3, userId);
			st.executeUpdate();
			
		} 
		catch (SQLException e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}
	
	// File/Document online path from db 
	public void filePathDetail(Connection conn)  
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select * from firm_detail limit 1";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				onlineFileUploadPath=rs.getString("file_upload_path");       
				onlineFileViewPath=rs.getString("file_view_path");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		} 
	}
	
	// Login User-Id
	public String userId()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		String userId="";
		if(ss!=null)
		{
			 userId=(String) ss.getAttribute("username");
		}
		return userId;
	}
	
	// User Type
	public String userType()
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		String type="";
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		if(ss==null)
		{
			type=userTypeByUserId(userId(),conn);
		}
		else
		{
			type=(String) ss.getAttribute("type");
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return type;
	}
	
	// User Type By User ID
	public String userTypeByUserId(String userId, Connection conn)
	{
		String qq="";	
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			qq="select type from login where userid='"+userId+"'  ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("type");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return "";
	}
	
	
	
	// Error Log File Creation
	public void fileCreation(String msg) {

	    BufferedWriter writer = null;

	    try {
	        // ---------- Message handling ----------
	        if (msg == null || msg.trim().isEmpty()) {
	            msg = "[EMPTY LOG MESSAGE]";
	        }
	        
	        String time = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a").format(new Date());
	        msg = msg + "  " + time;

//			ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
//			String realPath = ctx.getRealPath("/");
//				String dirPath=realPath;
			  //Offline
			
	  
	       String dirPath = fileUploadPathDetail(); // e.g. /home/delights/public_html/soft_files

	       

	        if (!dirPath.endsWith("/")) {
	            dirPath = dirPath + "/";
	        }

	        // ---------- Ensure directory exists ----------
	        File logDir = new File(dirPath);
	        if (!logDir.exists()) {
	            logDir.mkdirs();
	        }

	        // ---------- Ensure file exists ----------
	        File logFile = new File(dirPath + "ErrorLogDetail.txt");
	        if (!logFile.exists()) {
	            logFile.createNewFile();
	        }

	        // ---------- Write log ----------
	        writer = new BufferedWriter(new FileWriter(logFile, true));
	        writer.newLine();
	        writer.write(msg);

	     

	    } catch (Exception e) {
	        e.printStackTrace();
	        System.err.println("Logging failed: " + e.getMessage());

	    } finally {
	        try {
	            if (writer != null) {
	                writer.close();
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	}

	
	// Pending Cheque From shareholder_info table
	public ArrayList<UserInfo> pendingCheque(int branchId)
	{
		ArrayList<UserInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from shareholder_info where cheque_status='uncleared' and pay_mode !='cash' ";
			//// System.out.println(query);
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				UserInfo ll=new UserInfo();
				//BankInfo bb=obtainBankInfoById(rr.getString("transfer_to_bank"));
				ll.setId(rr.getString("id"));
				ll.setStatus("Share Holder");
				ll.setAccountNo(rr.getString("shareholderno"));
				ll.setFirst_applicantName(rr.getString("first_applicantName"));
				ll.setAmount(rr.getDouble("totalAmount"));
				ll.setPayMode(rr.getString("pay_mode"));
				ll.setEntryDateStr(sf.format(rr.getDate("office_date")));
				ll.setChq_ddDateStr(sf.format(rr.getDate("office_date")));
				ll.setBank_name(rr.getString("bank_name_cheque"));
				ll.setChq_ddNo(rr.getString("cheque_no"));
				ll.setTransferredToBankName(bankNameById(rr.getString("transfer_to_bank")));
				ll.setSubmittedToBank(rr.getString("transfer_to_bank"));
				list.add(ll);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}
	
	public ArrayList<UserInfo> pendingChequeFromShareInfoTable(int branchId)
	{
		ArrayList<UserInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from share_info where cheque_status='uncleared' and pay_mode !='cash' ";
			//// System.out.println(query);
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				UserInfo ll=new UserInfo();
				//BankInfo bb=obtainBankInfoById(rr.getString("transfer_to_bank"));
				ll.setId(rr.getString("id"));
				ll.setStatus("Extra Share Holder");
				ll.setAccountNo(rr.getString("shareholderno"));
				ll.setFirst_applicantName(rr.getString("first_applicantName"));
				ll.setAmount(rr.getDouble("totalAmount"));
				ll.setPayMode(rr.getString("pay_mode"));
				ll.setEntryDateStr(sf.format(rr.getDate("office_date")));
				ll.setChq_ddDateStr(sf.format(rr.getDate("office_date")));
				ll.setBank_name(rr.getString("bank_name_cheque"));
				ll.setChq_ddNo(rr.getString("cheque_no"));
				ll.setTransferredToBankName(bankNameById(rr.getString("transfer_to_bank")));
				ll.setSubmittedToBank(rr.getString("transfer_to_bank"));
				list.add(ll);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}
	
	
	public static boolean dateTrialPeriod(Connection conn)
	{
		String id=null;
		Date startingDate=null,endingDate=null;
		int count=0;
		Calendar cal = Calendar.getInstance();
	     cal.setTimeZone(TimeZone.getTimeZone("GMT"));
	     SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		try {
			Statement stmt=conn.createStatement();
			String query1="select * from datetrialperiod";
			ResultSet rs1=stmt.executeQuery(query1);
			while(rs1.next()){
				startingDate=rs1.getDate("startingDate");
				endingDate=rs1.getDate("endingDate");
				id=rs1.getString("idDateTrialPeriod");
				count++;
			}
			if(count==0){
				try {
					Date d1 = sdf.parse(getDate(cal));
					Timestamp currentDate1=new Timestamp(d1.getTime());
					cal.add(Calendar.DAY_OF_MONTH, 7);
					Date d2=sdf.parse(getDate(cal));
					Timestamp endingDate2=new Timestamp(d2.getTime());
					String que="insert into datetrialperiod (startingDate, endingDate) values ('"+currentDate1+"','"+endingDate2+"')";
					stmt.executeUpdate(que);
				} catch (ParseException e) {
					 e.printStackTrace();
				}
				
			}
		    try {
		    	Date date1=sdf.parse(getDate(cal));
				Timestamp currentDate=new Timestamp(date1.getTime());
				
				if((startingDate.equals(currentDate)) || (endingDate.equals(currentDate))){
					String query3="update datetrialperiod set startingDate='"+currentDate+"' where idDateTrialPeriod='"+id+"' ";
					int i=stmt.executeUpdate(query3);
					
					if(i==1)
					{
						return true;
					}
					return true;
				}
				else if((startingDate.before(currentDate)) && (endingDate.after(currentDate))){
					String query3="update datetrialperiod set startingDate='"+currentDate+"' where idDateTrialPeriod='"+id+"' ";
					int i=stmt.executeUpdate(query3);
					if(i==1){
						return true;
					}
				}
				
			} 
		     catch (ParseException e) {
				 e.printStackTrace();
			}
			
		} catch (SQLException e) {
			 e.printStackTrace();
		}
		
		return false;
	}
	
	// to check how many Loan type allow to client
	public boolean checkPermissionInDb(int branchId,String loanType, Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select loan_permission from loan_table where loan_type='"+loanType+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				if(rr.getString("loan_permission").equals("true"))
				{
					return true;	
				}
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
			fileCreation(e.getMessage());
		}
		return false;
	}
	
	// to get the Reg. Firm/Nidhi Detail from db
	public UserInfo firmDetails(int branchId) 
	{
		UserInfo uu=new UserInfo();
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String	qq="select * from firm_detail where id ='"+branchId+"' ";
			//System.out.println(qq);
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{  
				uu.setFirm_name(rs.getString("name"));
				uu.setName(rs.getString("name"));
				uu.setAddress1(rs.getString("address1"));
				uu.setAddress2(rs.getString("address2"));
				uu.setAddress3(rs.getString("address3"));
				uu.setAddress4(rs.getString("address4"));
				uu.setLogo(rs.getString("logo"));
				uu.setCompanytype(rs.getString("company_type"));
				
				/*
				filePathDetail(con);  //for set online view path if exist
				if(onlineFileViewPath==null || onlineFileViewPath.trim().equals(""))
				{
					ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
					String realPath = ctx.getRealPath("/");
					
					uu.setLogoForApp(realPath+rs.getString("logo"));
				}
				else
				{
					uu.setLogoForApp(onlineFileViewPath+rs.getString("logo"));
				}*/
				uu.setOnlineFileUploadPath(rs.getString("file_upload_path"));
				uu.setOnlineFileViewPath(rs.getString("file_view_path"));
				uu.setMobile(rs.getString("mobile_no"));
				uu.setSentBy(rs.getString("sent_by"));
				uu.setBranch(rs.getString("branch_name"));
				uu.setBranchCode(rs.getString("branch_code"));
				uu.setMemberAgeLimit(rs.getInt("member_age_limit"));
				uu.setQrPhotoPath(rs.getString("qr_code_image"));
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		} 
		return uu;
	}
	
	
	
	public UserInfo firmDetailsLogo() 
	{ 
		UserInfo uu=new UserInfo();
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select logo,name from firm_detail";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{  
				uu.setLogo(rs.getString("logo"));
				uu.setName(rs.getString("name"));
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		} 
		return uu;
	}
	
	/*// Send Message Method........
		public int runMessageUrl(String contactNo, String typeMessage, String userId) 
		{
			//System.out.println(contactNo+"==="+typeMessage);
			
			Connection conn=DataBaseConnection.JAVAConnection();
			try
			{
				if(!userId.equalsIgnoreCase("System"))
				{
					HeaderBean hh=new HeaderBean();
					typeMessage+=" Sent By: "+hh.getName();
				}
				typeMessage=URLEncoder.encode(typeMessage,"UTF-8");
			} 
			catch (UnsupportedEncodingException e1) 
			{
				e1.printStackTrace();
			}
			//System.out.println(contactNo+"===fdddddd"+typeMessage);

			if(contactNo==null || contactNo.equals(""))
			{
				
			}
			else if(contactNo.length()==10)
			{
					String regex = "[0-9]";
				//if(contactNo.matches(regex))
				{
					String 	url=checkSMessageApiDetailFromTable("api_url", conn);
					if(!url.equals(""))
					{
						url+="username="+checkSMessageApiDetailFromTable("user_name", conn);
						String 	senderId=checkSMessageApiDetailFromTable("sender_id", conn);
						url+="&message="+typeMessage+"&sendername="+senderId+"&smstype=TRANS&numbers="+contactNo+"&apikey="+checkSMessageApiDetailFromTable("api_key", conn);
						// HSP SMS API
						
						String 	senderId=checkSMessageApiDetailFromTable("sender_id", conn);
						String apiKey=checkSMessageApiDetailFromTable("api_key", conn);
						url=url+apiKey+contactNo+"&senderid="+senderId+"&msg="+typeMessage;
						
						//System.out.println(senderId+url+apiKey);
						// Bulk SMS Root
						System.out.println(url);
						try 
						{
							 URL myURL = new URL(url);
							   myURL.openStream();
							   insertDetailIntoSendMessageTable(userId, contactNo, typeMessage);
							   
							   return 1; 
						}
						catch (Exception e) 
						{ 
							e.printStackTrace();fileCreation(e.getMessage());
						} 
					}
					else
					{
						// // // System.out.println(contactNo+"==="+typeMessage);
					}
				}
			}
			return 0;
		}*/
		
	
	
	// Send Message Method........
	public int runMessageUrl(int branchId,String contactNo, String typeMessage, String userId, String templateId, Connection conn) 
	{
		System.out.println(userId+"==="+typeMessage);
		try
		{
			if(!userId.equalsIgnoreCase("System"))
			{
				typeMessage+=" Sent By: "+sentByFromFirmTable(conn);
			}
			typeMessage=addTemplateContent(typeMessage, userId, conn);
			typeMessage=URLEncoder.encode(typeMessage,"UTF-8");
		} 
		catch (UnsupportedEncodingException e1) 
		{
			e1.printStackTrace();
		}

		if(contactNo==null || contactNo.equals(""))
		{
			
		}
		else if(contactNo.length()==10)
		{
			String 	url=checkSMessageApiDetailFromTable("api_url", "",conn);
			if(!url.equals(""))
			{
				String senderId=checkSMessageApiDetailFromTable("sender_id","", conn);
				String apiKey=checkSMessageApiDetailFromTable("api_key","", conn);
				String userName=checkSMessageApiDetailFromTable("user_name","", conn);
				
				// THESE BELOW LINE COMMENT ON 15-DEC-2024
//				if(url.contains("http://sms.bulksmsind.in/v2/sendSMS?"))
//				{
//					url+="username="+userName+"&message="+typeMessage+"&sendername="+senderId+"&smstype=TRANS&numbers="+contactNo+"&"
//							+ "apikey="+apiKey; //+"&peid=1201159689958334816&templateid="+templateId
//				}
//				else
//				{
//					url=url+apiKey+contactNo+"&senderid="+senderId+"&msg="+typeMessage;
//				}
				
				if(url.contains("http://sms.bulksmsind.in/v2/sendSMS?"))
				{
					url+="username="+userName+"&message="+typeMessage+"&sendername="+senderId+"&smstype=TRANS&numbers="+contactNo+"&"
							+ "apikey="+apiKey+"&peid=1201159689958334816&templateid="+templateId;
				}
				else
				{
					url=url+apiKey+contactNo+"&senderid="+senderId+"&msg="+typeMessage+"&tlv=%7B%22DLT_ENTITY_ID%22%3A%221201159689958334816%22%2C%22DLT_TEMPLATE_ID%22%3A%22"+templateId+"%22%7D";
				}
				
				
				
				try 
				{
					////System.out.println("Template ID: "+templateId);
					System.out.println(url);
					
					if(templateId.equalsIgnoreCase("pending"))
					{
						FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Template not approve on DLT protal, Message will be delivered after approval of template. Thanks..."));
					}
					
					else if(url.contains("http://sms.bulksmsind.in/v2/sendSMS?") || url.contains("http://admin.bulksms.tech/app/smsapi/index.php?")
							 || url.contains("https://bulksms.tekhook.in/smsapi/index?"))
					{
						////System.out.println("2");
						 URL myURL = new URL(url);
						   myURL.openStream();
					}
					else
					{
						////System.out.println("3");
						RequestContext.getCurrentInstance().execute("window.open('"+url+"')");
					}
					
					String wpKey=checkSMessageApiDetailFromTable("balance_api","", conn);
					if(!wpKey.trim().equalsIgnoreCase("") && !typeMessage.contains("OTP"))
					{
						String urlW=wpKey+contactNo+"&msg="+typeMessage;
						/*URL myURL = new URL(urlW);
						   myURL.openStream();*/ // Comment due to https
						RequestContext.getCurrentInstance().execute("window.open('"+urlW+"')");
					}
					
					insertDetailIntoSendMessageTable(branchId,userId, contactNo, typeMessage);
					   
					return 1; 
				}
				catch (Exception e) 
				{ 
					e.printStackTrace();fileCreation(e.getMessage());
				} 
			}
		}
		return 0;
	}
			
	private String addTemplateContent(String typeMessage, String userId, Connection conn) 
	{
		String senderId=checkSMessageApiDetailFromTable("sender_id","", conn);
		if(typeMessage.contains("Total Deposit Amount Balance") && userId.equalsIgnoreCase("System"))
		{
			if(senderId.equalsIgnoreCase("Kavyam"))
			{
				typeMessage+=" Sent By: Kavyam Nidhi";
			}  
			
			else if(senderId.equalsIgnoreCase("BMKALP"))
			{
				typeMessage+=" Sent By: KALPTARU FINANCE";
			}
			
			else if(senderId.equalsIgnoreCase("JANJNI"))
			{
				// already Proper delivered
			}
			
			else
			{
				typeMessage+=" Sent By: NIDHI";
			}
		}
		
		if(senderId.equalsIgnoreCase("ADNBAK"))
		{
			typeMessage+=" ADNBAK";
		}
		else if(senderId.equalsIgnoreCase("JANJNI"))
		{
			typeMessage+=" JANJNI";
		}
		else if(senderId.equalsIgnoreCase("BMKALP"))
		{
			typeMessage+=" BMKALP";
		}
		else if(senderId.equalsIgnoreCase("MSSAGE") || senderId.equalsIgnoreCase("FINDHI")
				|| senderId.equalsIgnoreCase("MSFINF") || senderId.equalsIgnoreCase("FINMSF"))
		{
			typeMessage+=" MSSAGE";
		}
		else if(senderId.equalsIgnoreCase("MSAAGE") || senderId.equalsIgnoreCase("MESGEE"))
		{
			typeMessage+=" MESGEE";
		}
		
		
		return typeMessage;
	}		
	
	private String sentByFromFirmTable(Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select sent_by from firm_detail";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("sent_by");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return "Finance";
	}
	
	public void runWhatsAppUrl(String contactNo, String typeMessage, Connection conn)
	{
		try
		{
			typeMessage+=" Sent By: "+sentByFromFirmTable(conn);
			typeMessage=URLEncoder.encode(typeMessage,"UTF-8");
		} 
		catch (UnsupportedEncodingException e1) 
		{
			e1.printStackTrace();
		}

		if(contactNo!=null && !contactNo.trim().equals("") && contactNo.length()==10)
		{
			String wpKey=checkWhatsAppAPI(conn);
			if(!wpKey.trim().equalsIgnoreCase("") && !typeMessage.contains("OTP"))
			{
				String urlW=wpKey+contactNo+"&msg="+typeMessage;
				RequestContext.getCurrentInstance().execute("window.open('"+urlW+"')");
			}
		}
	}
	
	public void runWhatsAppDirect(String contactNo, String typeMessage, Connection conn) {
	    try {
	        typeMessage += " Sent By: " + sentByFromFirmTable(conn);
	        typeMessage = URLEncoder.encode(typeMessage, "UTF-8");
	    } catch (UnsupportedEncodingException e1) {
	        e1.printStackTrace();
	    }

	    if (contactNo == null || contactNo.trim().isEmpty() || contactNo.length() != 10) {
	        System.out.println("Invalid contactNo: '" + contactNo + "'");
	        return;
	    }

	    String apiKey =	checkWhatsAppAPI(conn);       // token/key


	    // Build final CloudWhatsApp API URL
	    String urlW = "https://web.cloudwhatsapp.com/wapp/api/send"
	                + "?apikey=" + apiKey
	                + "&mobile=" + contactNo
	                + "&msg=" + typeMessage;

	    System.out.println("Final WhatsApp API URL: " + urlW);

	    // Perform actual HTTP GET request
	    String response = performGetRequest(urlW);

	    System.out.println("WhatsApp API Response: " + response);
	}

	
	
	private String performGetRequest(String urlStr) {
	    HttpURLConnection conn = null;
	    BufferedReader reader = null;
	    try {
	        URL urlObj = new URL(urlStr);
	        conn = (HttpURLConnection) urlObj.openConnection();
	        conn.setRequestMethod("GET");
	        conn.setConnectTimeout(15000);
	        conn.setReadTimeout(15000);
	        conn.setDoInput(true);
	        conn.setUseCaches(false);

	        int code = conn.getResponseCode();

	        InputStream is;
	        if (code >= 200 && code < 300) {
	            is = conn.getInputStream();
	        } else {
	            is = conn.getErrorStream();
	            if (is == null) {
	                return "HTTP error code: " + code;
	            }
	        }

	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        StringBuilder sb = new StringBuilder();
	        String line;
	        while ((line = reader.readLine()) != null) {
	            sb.append(line);
	        }

	        return sb.toString();

	    } catch (Exception e) {
	        e.printStackTrace();
	        return "EXCEPTION: " + e.getMessage();
	    } finally {
	        try { if (reader != null) reader.close(); } catch (Exception ignore) {}
	        if (conn != null) conn.disconnect();
	    }
	}

			
	// For Client Problem Module Send Message Method........
	public int runMessageUrlForClientProblemModule(int branchId,String contactNo, String typeMessage, String userId, Connection conn) 
	{
		//System.out.println(contactNo+"==="+typeMessage);
		try
		{
			if(!userId.equalsIgnoreCase("System"))
			{
				HeaderBean hh=new HeaderBean();
				typeMessage+=" Sent By: "+hh.getSentBy();
			}
			typeMessage=URLEncoder.encode(typeMessage,"UTF-8");
		} 
		catch (UnsupportedEncodingException e1) 
		{
			e1.printStackTrace();
		}
		//System.out.println(contactNo+"===fdddddd"+typeMessage);

		if(contactNo==null || contactNo.equals(""))
		{
			
		}
		else if(contactNo.length()==10)
		{
				String regex = "[0-9]";
			//if(contactNo.matches(regex))
			{
				String 	url=checkSMessageApiDetailFromTable("api_url","active" ,conn);
				if(!url.equals(""))
				{
					/*url+="username="+checkSMessageApiDetailFromTable("user_name", conn);
					String 	senderId=checkSMessageApiDetailFromTable("sender_id", conn);
					url+="&message="+typeMessage+"&sendername="+senderId+"&smstype=TRANS&numbers="+contactNo+"&apikey="+checkSMessageApiDetailFromTable("api_key", conn);*/
					// HSP SMS API
					
					String 	senderId=checkSMessageApiDetailFromTable("sender_id","active", conn);
					String apiKey=checkSMessageApiDetailFromTable("api_key","active", conn);
					url=url+apiKey+contactNo+"&senderid="+senderId+"&msg="+typeMessage;
					
					//System.out.println(senderId+url+apiKey);
					// Bulk SMS Root
					//System.out.println(url);
					try 
					{
						 /*URL myURL = new URL(url);
						   myURL.openStream();*/
						
						RequestContext.getCurrentInstance().execute("window.open('"+url+"')");
						   insertDetailIntoSendMessageTable(branchId,userId, contactNo, typeMessage);
						   
						   return 1; 
					}
					catch (Exception e) 
					{ 
						e.printStackTrace();fileCreation(e.getMessage());
					} 
				}
				else
				{
					// // // System.out.println(contactNo+"==="+typeMessage);
				}
			}
		}
		return 0;
	}
						
	public void insertDetailIntoSendMessageTable(int branchId,String userId, String contactNo, String typeMessage) 
	{
		Timestamp sendDate=new Timestamp(new Date().getTime());
		sendDate.setNanos(0);
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="insert into send_message(user_id, contact_no, message, send_date,branch_id) "
					+ "values('"+userId+"','"+contactNo+"','"+typeMessage+"','"+sendDate+"','"+branchId+"')";
			//System.out.println(query);
			st.executeUpdate(query);
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}
	
	
	// can check Send Messages Report Date Wise 
	public ArrayList<LoanInfo> sendMessageReport(int branchId,String sDate, Timestamp eDate) 
	{
		int count=1;
		ArrayList<LoanInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from send_message where send_date between '"+sDate+"' and '"+eDate+"'";
			query=query+"and branch_id='"+branchId+"' order by id desc";
			ResultSet rr=st.executeQuery(query);
			while(rr.next())
			{
				LoanInfo vv=new LoanInfo();
				
				vv.setSno(count++);
				vv.setUserId(rr.getString("user_id"));
				vv.setContactNo(rr.getString("contact_no"));
				vv.setSendDt(rr.getString("send_date"));
				vv.setMessage(java.net.URLDecoder.decode(rr.getString("message"), "UTF-8"));
				
				list.add(vv);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	
	public static String getDate(Calendar cal){
		return "" + cal.get(Calendar.DATE) +"/" +
	    (cal.get(Calendar.MONTH)+1) + "/" + cal.get(Calendar.YEAR);
	}
	
	public static long dayCalculateForLeave(Calendar startCalendar,Calendar endCalendar)
	{
		startCalendar.set(Calendar.MILLISECOND, 0);
		endCalendar.set(Calendar.MILLISECOND, 0);
		long difference = Math.abs((startCalendar.getTimeInMillis()-endCalendar.getTimeInMillis())/86400000);
		return difference+1;
	}
	
	// Month name from it's Integer month value
	public String  monthList(int i)
	{
		String monthName=null;
		if(i==1)
		{
			monthName="January";
		}
		else if(i==2)
		{
			monthName="February";
		}
		else if(i==3)
		{
			monthName="March";
		}
		else if(i==4)
		{
			monthName="April";
		}
		else if(i==5)
		{
			monthName="May";
		}
		else if(i==6)
		{
			monthName="June";
		}
		else if(i==7)
		{
			monthName="July";
		}
		else if(i==8)
		{
			monthName="August";
		}
		else if(i==9)
		{
			monthName="September";
		}
		else if(i==10)
		{
			monthName="October";
		}
		else if(i==11)
		{
			monthName="November";
		}
		else if(i==12)
		{
			monthName="December";
		}
		return monthName;
	}
	
	// Add new collection and it is not compulsory for all Nidhi 
	public int addCenter(int branchId,String centerName, String centerCode,String descriptoin, String dsaCode, String centerLeaderName, String centerTime, Connection conn) 
	{
		Statement st=null;
		try
		{
             st=conn.createStatement();
		     String query="insert into center(centerName, centerCode, description, dsacode, branch_id, center_leader_name, center_time) "
		     		+ "values('"+centerName+"','"+centerCode+"','"+descriptoin+"','"+dsaCode+"','"+branchId+"','"+centerLeaderName+"','"+centerTime+"')";	
		     int i=st.executeUpdate(query);
		     if(i>=1)
		     {
		    	 dataInsertInQueryTable(query, conn);
		    	 return 1;
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		
		}
		return 0;
	}
	
	// to get personal Loan Detail which are not approved
	public ArrayList<LoanInfo> pendingPersonalLoanList(int branchId)
    {
		int i=0;
        ArrayList<LoanInfo> list=new ArrayList<>();
        try(Connection conn=DataBaseConnection.JAVAConnection();)
        {
            Statement stt=conn.createStatement();
            String query="select * from personalloan"
                    + " INNER JOIN shareholder_info on personalloan.shareholderno=shareholder_info.shareholderno"
                    + " where personalloan.status='pending' and shareholder_info.branch_id = '" + branchId + "' ";
            
            ResultSet ss=stt.executeQuery(query);
            while(ss.next())
            {
                LoanInfo info=new LoanInfo();
                info.setSno(++i);
                info.setShareHolderNo(ss.getString("personalloan.shareholderno"));
                info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
                info.setFatherHusbandName(ss.getString("shareholder_info.father_husband_name"));
                info.setContactNo(ss.getString("shareholder_info.mobile"));
                info.setId(ss.getString("personalloan.id"));
//                if(ss.getString("loanNo").contains("R"))
//                {
//                    info.setLoanAmount(ss.getString("increase_amount"));
//                }
//                else
                {
                    info.setLoanAmount(ss.getString("loanAmount"));
                }
                if(!ss.getString("firstguarantor").equals(""))
                {
                    info.setGuarantarName(shareHolderDetailByColumnName(ss.getString("firstguarantor"),"first_applicantName", conn));
                    info.setGuarantarFatherName(shareHolderDetailByColumnName(ss.getString("firstguarantor"),"father_husband_name", conn));
                    info.setGuarantarAddress(shareHolderDetailByColumnName(ss.getString("firstguarantor"),"address", conn));
                }
                info.setLoanInterest(ss.getString("personalloan.interest"));
                info.setLoanTerm(ss.getString("personalloan.terms"));
                info.setTerms(ss.getInt("personalloan.terms"));
                info.setInstallAmount(ss.getDouble("personalloan.emi"));
                info.setLoanType("Personal Loan");
                info.setRequestDate(ss.getDate("requestDate"));
                info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
                info.setLoanNo(ss.getString("loanNo"));
                info.setFirstGuarantor(ss.getString("firstguarantor"));
                if(ss.getDate("emi_due_date")!=null)
                {
                    info.setEmiPaidDate(ss.getDate("emi_due_date"));
                }
                else
                {
                    info.setEmiPaidDate(ss.getDate("approvalDate"));
                }
               
                info.setSecondGuarantor(ss.getString("secondguarantor"));
                info.setIdProof(ss.getString("idproof"));
                info.setFileCharge(ss.getString("fileCharge"));
                info.setInsuranceFee(ss.getString("insurance_fee"));
                info.setProcessingCharge(ss.getDouble("processing_charge"));
                info.setReason(ss.getString("reason"));
                info.setFrequency(String.valueOf(ss.getInt("frequency")));
                info.setFrequencyVal(ss.getInt("frequency"));
                info.setAppChqNo(ss.getString("personalloan.app_chq_no"));
                info.setAppAccNo(ss.getString("personalloan.app_acc_no"));
                info.setAppBankName(ss.getString("personalloan.app_bank_name"));
                info.setAppBankBranch(ss.getString("personalloan.app_bank_branch"));
               
                info.setG1ChqNo(ss.getString("personalloan.g1_chq_no"));
                info.setG1AccNo(ss.getString("personalloan.g1_acc_no"));
                info.setG1BankName(ss.getString("personalloan.g1_bank_name"));
                info.setG1BankBranch(ss.getString("personalloan.g1_bank_branch"));
               
                info.setG2ChqNo(ss.getString("personalloan.g2_chq_no"));
                info.setG2AccNo(ss.getString("personalloan.g2_acc_no"));
                info.setG2BankName(ss.getString("personalloan.g2_bank_name"));
                info.setG2BankBranch(ss.getString("personalloan.g2_bank_branch"));
                info.setPlanNo(ss.getString("plan_no"));
                info.setDsacode(ss.getString("dsacode"));
                info.setCommission(ss.getDouble("commission"));
              //  info.setPlanNo(ss.getString("plan_no"));
               
                list.add(info);
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return list;
    }
	
	// to get personal Loan Detail which are not approved
	public ArrayList<LoanInfo> pendingSecureLoanList(int branchId)
    {
		int i=0;
        ArrayList<LoanInfo> list=new ArrayList<>();
        try(Connection conn=DataBaseConnection.JAVAConnection();)
        {
            Statement stt=conn.createStatement();
            String query="select * from secure_loan"
                    + " INNER JOIN shareholder_info on secure_loan.shareholderno=shareholder_info.shareholderno"
                    + " where secure_loan.status='pending' and shareholder_info.branch_id='"+branchId+"'";
            
            ResultSet ss=stt.executeQuery(query);
            while(ss.next())
            {
                LoanInfo info=new LoanInfo();
                info.setSno(++i);
                info.setShareHolderNo(ss.getString("secure_loan.shareholderno"));
                info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
                info.setFatherHusbandName(ss.getString("shareholder_info.father_husband_name"));
                info.setContactNo(ss.getString("shareholder_info.mobile"));
                info.setId(ss.getString("secure_loan.id"));
                if(ss.getString("loanNo").contains("R"))
                {
                    info.setLoanAmount(ss.getString("increase_amount"));
                }
                else
                {
                    info.setLoanAmount(ss.getString("loanAmount"));
                }
                if(!ss.getString("firstguarantor").equals(""))
                {
                    info.setGuarantarName(shareHolderDetailByColumnName(ss.getString("firstguarantor"),"first_applicantName", conn));
                    info.setGuarantarFatherName(shareHolderDetailByColumnName(ss.getString("firstguarantor"),"father_husband_name", conn));
                    info.setGuarantarAddress(shareHolderDetailByColumnName(ss.getString("firstguarantor"),"address", conn));
                }
                info.setLoanInterest(ss.getString("secure_loan.interest"));
                info.setLoanTerm(ss.getString("secure_loan.terms"));
                info.setTerms(ss.getInt("secure_loan.terms"));
                info.setInstallAmount(ss.getDouble("secure_loan.emi"));
                info.setLoanType("Secure Loan");
                info.setRequestDate(ss.getDate("requestDate"));
                info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
                info.setLoanNo(ss.getString("loanNo"));
                info.setFirstGuarantor(ss.getString("firstguarantor"));
                if(ss.getDate("emi_due_date")!=null)
                {
                    info.setEmiPaidDate(ss.getDate("emi_due_date"));
                }
                else
                {
                    info.setEmiPaidDate(ss.getDate("approvalDate"));
                }
               
                info.setSecondGuarantor(ss.getString("secondguarantor"));
                info.setIdProof(ss.getString("idproof"));
                info.setFileCharge(ss.getString("fileCharge"));
                info.setInsuranceFee(ss.getString("insurance_fee"));
                info.setReason(ss.getString("reason"));
                info.setFrequency(String.valueOf(ss.getInt("frequency")));
                info.setFrequencyVal(ss.getInt("frequency"));
                info.setAppChqNo(ss.getString("secure_loan.app_chq_no"));
                info.setAppAccNo(ss.getString("secure_loan.app_acc_no"));
                info.setAppBankName(ss.getString("secure_loan.app_bank_name"));
                info.setAppBankBranch(ss.getString("secure_loan.app_bank_branch"));
               
                info.setG1ChqNo(ss.getString("secure_loan.g1_chq_no"));
                info.setG1AccNo(ss.getString("secure_loan.g1_acc_no"));     
                info.setG1BankName(ss.getString("secure_loan.g1_bank_name"));
                info.setG1BankBranch(ss.getString("secure_loan.g1_bank_branch"));
               
                info.setG2ChqNo(ss.getString("secure_loan.g2_chq_no"));
                info.setG2AccNo(ss.getString("secure_loan.g2_acc_no"));
                info.setG2BankName(ss.getString("secure_loan.g2_bank_name"));
                info.setG2BankBranch(ss.getString("secure_loan.g2_bank_branch"));
                info.setPlanNo(ss.getString("plan_no"));
                info.setDsacode(ss.getString("dsacode"));
                info.setCommission(ss.getDouble("commission"));
                
                if (ss.getString("security_type") != null) 
                {
                	info.setSecurityype(ss.getString("security_type"));
				}
            
                //  info.setPlanNo(ss.getString("plan_no"));
               
                list.add(info);
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return list;
    }
		
	// to get personal Loan Detail which are not approved
	public ArrayList<LoanInfo> pendingBusinessLoanList(int branchId)
    {
		int i=0;
        ArrayList<LoanInfo> list=new ArrayList<>();
        try(Connection conn=DataBaseConnection.JAVAConnection();)
        {
            Statement stt=conn.createStatement();
            String query="select * from business_loan"
                    + " INNER JOIN shareholder_info on business_loan.shareholderno=shareholder_info.shareholderno"
                    + " where business_loan.status='pending' and shareholder_info.branch_id='"+branchId+"'";
            
            ResultSet ss=stt.executeQuery(query);
            while(ss.next())
            {
                LoanInfo info=new LoanInfo();
                info.setSno(++i);
                info.setShareHolderNo(ss.getString("business_loan.shareholderno"));
                info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
                info.setFatherHusbandName(ss.getString("shareholder_info.father_husband_name"));
                info.setContactNo(ss.getString("shareholder_info.mobile"));
                info.setId(ss.getString("business_loan.id"));
                if(ss.getString("loanNo").contains("R"))
                {
                    info.setLoanAmount(ss.getString("increase_amount"));
                }
                else
                {
                    info.setLoanAmount(ss.getString("loanAmount"));
                }
                if(!ss.getString("firstguarantor").equals(""))
                {
                    info.setGuarantarName(shareHolderDetailByColumnName(ss.getString("firstguarantor"),"first_applicantName", conn));
                    info.setGuarantarFatherName(shareHolderDetailByColumnName(ss.getString("firstguarantor"),"father_husband_name", conn));
                    info.setGuarantarAddress(shareHolderDetailByColumnName(ss.getString("firstguarantor"),"address", conn));
                }
                info.setLoanInterest(ss.getString("business_loan.interest"));
                info.setLoanTerm(ss.getString("business_loan.terms"));
                info.setInstallAmount(ss.getDouble("business_loan.emi"));
                info.setLoanType("Business Loan");
                info.setRequestDate(ss.getDate("requestDate"));
                info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
                info.setLoanNo(ss.getString("loanNo"));
                info.setFirstGuarantor(ss.getString("firstguarantor"));
                if(ss.getDate("emi_due_date")!=null)
                {
                    info.setEmiPaidDate(ss.getDate("emi_due_date"));
                }
                else
                {
                    info.setEmiPaidDate(ss.getDate("approvalDate"));
                }
               
                info.setSecondGuarantor(ss.getString("secondguarantor"));
                info.setIdProof(ss.getString("idproof"));
                info.setFileCharge(ss.getString("fileCharge"));
                info.setInsuranceFee(ss.getString("insurance_fee"));
                info.setReason(ss.getString("reason"));
                info.setFrequency(String.valueOf(ss.getInt("frequency")));
               
                info.setAppChqNo(ss.getString("business_loan.app_chq_no"));
                info.setAppAccNo(ss.getString("business_loan.app_acc_no"));
                info.setAppBankName(ss.getString("business_loan.app_bank_name"));
                info.setAppBankBranch(ss.getString("business_loan.app_bank_branch"));
               
                info.setG1ChqNo(ss.getString("business_loan.g1_chq_no"));
                info.setG1AccNo(ss.getString("business_loan.g1_acc_no"));
                info.setG1BankName(ss.getString("business_loan.g1_bank_name"));
                info.setG1BankBranch(ss.getString("business_loan.g1_bank_branch"));
               
                info.setG2ChqNo(ss.getString("business_loan.g2_chq_no"));
                info.setG2AccNo(ss.getString("business_loan.g2_acc_no"));
                info.setG2BankName(ss.getString("business_loan.g2_bank_name"));
                info.setG2BankBranch(ss.getString("business_loan.g2_bank_branch"));
                info.setPlanNo(ss.getString("plan_no"));
                info.setDsacode(ss.getString("dsacode"));
                info.setCommission(ss.getDouble("commission"));
              //  info.setPlanNo(ss.getString("plan_no"));
               
                list.add(info);
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return list;
    }
	
	// shareholder detail by shareholder no. and column name from shareholder_info table
	public String shareHolderDetailByColumnName(String shareHolderNo, String columnName, Connection conn)
    {
        String fatherName="";
        Statement st=null;
		ResultSet rs=null;
        try (Connection con = DataBaseConnection.JAVAConnection();)
        {
            st = con.createStatement();
            String qq = "select "+columnName+" from shareholder_info where shareholderno='"+shareHolderNo+"' ";
            rs = st.executeQuery(qq);
            if (rs.next())
            {
                fatherName=rs.getString(columnName);
            }
        }
        catch (Exception e)
        {
        	 e.printStackTrace();fileCreation(e.getMessage());
        }
        finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
        return fatherName;
    }
    
	// to get property Loan Detail which are not approved
	public ArrayList<LoanInfo> pendingPropertyLoanList(int branchId)
    {
        ArrayList<LoanInfo> list=new ArrayList<>();
        try(Connection conn=DataBaseConnection.JAVAConnection();)
        {
            Statement stt=conn.createStatement();
            String query="select * from propertyloan"
                    + " INNER JOIN shareholder_info on propertyloan.shareholderno=shareholder_info.shareholderno"
                    + " where propertyloan.status='pending' and shareholder_info.branch_id='"+branchId+"'";
            ResultSet ss=stt.executeQuery(query);
            while(ss.next())
            {
                LoanInfo info=new LoanInfo();
                info.setShareHolderNo(ss.getString("propertyloan.shareholderno"));
                info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
                info.setFatherHusbandName(ss.getString("shareholder_info.father_husband_name"));
                info.setId(ss.getString("propertyloan.id"));
                if(!ss.getString("firstguarantor").equals(""))
                {
                    info.setGuarantarFatherName(shareHolderDetailByColumnName(ss.getString("firstguarantor"), "father_husband_name", conn));
                    info.setGuarantarName(shareHolderDetailByColumnName(ss.getString("firstguarantor"), "first_applicantName", conn));
                    info.setGuarantarAddress(shareHolderDetailByColumnName(ss.getString("firstguarantor"),"address", conn));
                }
               
                if(ss.getString("loanNo").contains("R"))
                {
                    info.setLoanAmount(ss.getString("increase_amount"));
                }
                else
                {
                    info.setLoanAmount(ss.getString("loanAmount"));
                }
               
                info.setLoanInterest(ss.getString("propertyloan.interest"));
                info.setLoanTerm(ss.getString("propertyloan.terms"));
                info.setRequestDate(ss.getDate("requestDate"));
                info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
                info.setInstallAmount(ss.getDouble("propertyloan.emi"));
                info.setLoanType("Property Loan");
                info.setLoanNo(ss.getString("loanNo"));
                info.setFirstGuarantor(ss.getString("firstguarantor"));
                info.setSecondGuarantor(ss.getString("secondguarantor"));
                info.setIdProof(ss.getString("idproof"));
                info.setFileCharge(ss.getString("fileCharge"));
                info.setInsuranceFee(ss.getString("insurance_fee"));
                info.setCategory(ss.getString("category"));
                info.setRegistryNo(ss.getString("registryNo"));
                info.setVerified(ss.getString("verified"));
               
                info.setPatta(ss.getString("patta"));
                info.setAuthorityPatta(ss.getString("authorityPatta"));
                info.setJamabandi(ss.getString("jamabandi"));
                info.setFrequency(String.valueOf(ss.getInt("frequency")));
               
                info.setAppChqNo(ss.getString("personalloan.app_chq_no"));
                info.setAppAccNo(ss.getString("personalloan.app_acc_no"));
                info.setAppBankName(ss.getString("personalloan.app_bank_name"));
                info.setAppBankBranch(ss.getString("personalloan.app_bank_branch"));
               
                info.setG1ChqNo(ss.getString("personalloan.g1_chq_no"));
                info.setG1AccNo(ss.getString("personalloan.g1_acc_no"));
                info.setG1BankName(ss.getString("personalloan.g1_bank_name"));
                info.setG1BankBranch(ss.getString("personalloan.g1_bank_branch"));
               
                info.setG2ChqNo(ss.getString("personalloan.g2_chq_no"));
                info.setG2AccNo(ss.getString("personalloan.g2_acc_no"));
                info.setG2BankName(ss.getString("personalloan.g2_bank_name"));
                info.setG2BankBranch(ss.getString("personalloan.g2_bank_branch"));
               
                info.setDsacode(ss.getString("dsacode"));
                info.setCommission(ss.getDouble("commission"));
                info.setPlanNo(ss.getString("plan_no"));
               
                list.add(info);
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return list;
    }
	
	// to get Vehicle Loan Detail which are not approved
	public ArrayList<LoanInfo> pendingVehicleLoanList(int branchId)
    {
        ArrayList<LoanInfo> list=new ArrayList<>();
        try(Connection conn=DataBaseConnection.JAVAConnection();)
        {
            Statement stt=conn.createStatement();
            String query="select * from vechicleloan"
                    + " INNER JOIN shareholder_info on vechicleloan.shareholderno=shareholder_info.shareholderno"
                    + " where vechicleloan.status='pending' and shareholder_info.branch_id='"+branchId+"'";
            ResultSet ss=stt.executeQuery(query);
            while(ss.next())
            {
                LoanInfo info=new LoanInfo();
                info.setShareHolderNo(ss.getString("vechicleloan.shareholderno"));
                info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
                info.setFatherHusbandName(ss.getString("shareholder_info.father_husband_name"));
                info.setId(ss.getString("vechicleloan.id"));
                if(!ss.getString("firstguarantor").equals(""))
                {
                    info.setGuarantarFatherName(shareHolderDetailByColumnName(ss.getString("firstguarantor"), "father_husband_name",conn));
                    info.setGuarantarName(shareHolderDetailByColumnName(ss.getString("firstguarantor"), "first_applicantName", conn));
                    info.setGuarantarAddress(shareHolderDetailByColumnName(ss.getString("firstguarantor"),"address", conn));
                }
                if(ss.getString("loanNo").contains("R"))
                {
                    info.setLoanAmount(ss.getString("increase_amount"));
                }
                else
                {
                    info.setLoanAmount(ss.getString("loanAmount"));
                }
               
                info.setLoanInterest(ss.getString("vechicleloan.interest"));
                info.setLoanTerm(ss.getString("vechicleloan.terms"));
                info.setInstallAmount(ss.getDouble("vechicleloan.emi"));
                info.setRequestDate(ss.getDate("requestDate"));
                info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
                info.setLoanType("Vehicle Loan");
                info.setLoanNo(ss.getString("loanNo"));
                info.setFirstGuarantor(ss.getString("firstguarantor"));
                info.setSecondGuarantor(ss.getString("secondguarantor"));
                info.setIdProof(ss.getString("idproof"));
                info.setCategory(ss.getString("category"));
                info.setVechiclename(ss.getString("vechileName"));
                info.setVechileModel(ss.getString("model"));
                info.setEngineNo(ss.getString("engineno"));
                info.setMacNo(ss.getString("macNo"));
                info.setFileCharge(ss.getString("fileCharge"));
                info.setInsuranceFee(ss.getString("insurance_fee"));
                info.setFrequency(String.valueOf(ss.getInt("frequency")));
               
                info.setAppChqNo(ss.getString("personalloan.app_chq_no"));
                info.setAppAccNo(ss.getString("personalloan.app_acc_no"));
                info.setAppBankName(ss.getString("personalloan.app_bank_name"));
                info.setAppBankBranch(ss.getString("personalloan.app_bank_branch"));
               
                info.setG1ChqNo(ss.getString("personalloan.g1_chq_no"));
                info.setG1AccNo(ss.getString("personalloan.g1_acc_no"));
                info.setG1BankName(ss.getString("personalloan.g1_bank_name"));
                info.setG1BankBranch(ss.getString("personalloan.g1_bank_branch"));
               
                info.setG2ChqNo(ss.getString("personalloan.g2_chq_no"));
                info.setG2AccNo(ss.getString("personalloan.g2_acc_no"));
                info.setG2BankName(ss.getString("personalloan.g2_bank_name"));
                info.setG2BankBranch(ss.getString("personalloan.g2_bank_branch"));
               
                info.setDsacode(ss.getString("dsacode"));
                info.setCommission(ss.getDouble("commission"));
                info.setPlanNo(ss.getString("plan_no"));
               
                list.add(info);
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return list;
    }
   
	// to get Group Loan Detail which are not approved
	public ArrayList<LoanInfo> pendingGroupLoanList(int branchId)
    {
        ArrayList<LoanInfo> list=new ArrayList<>();
        try(Connection conn=DataBaseConnection.JAVAConnection();)
        {
            Statement stt=conn.createStatement();
            String query="select * from grouploan"
                    + " INNER JOIN shareholder_info on grouploan.teamLeader=shareholder_info.shareholderno"
                    + " where grouploan.status='pending' and shareholder_info.branch_id='"+branchId+"'";
            ResultSet ss=stt.executeQuery(query);
            while(ss.next())
            {
                LoanInfo info=new LoanInfo();
                info.setShareHolderNo(ss.getString("grouploan.teamLeader"));
                info.setContactNo(ss.getString("shareholder_info.mobile"));
                info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
                info.setFatherHusbandName(ss.getString("shareholder_info.father_husband_name"));
                info.setId(ss.getString("grouploan.id"));
                /*if(!ss.getString("firstguarantor").equals(""))
                {
                    info.setGuarantarName(guarantarName(ss.getString("firstguarantor")));
                    info.setGuarantarFatherName(guarantarFatherName(ss.getString("firstguarantor")));
                    info.setGuarantarAddress(guarantarAddress(ss.getString("firstguarantor")));
                }*/
               
                if(ss.getString("loanNo").contains("R"))
                {
                    info.setLoanAmount(ss.getString("increase_amount"));
                }
                else
                {
                    info.setLoanAmount(ss.getString("loanAmount"));
                }
               
                info.setLoanInterest(ss.getString("grouploan.interest"));
                info.setLoanTerm(ss.getString("grouploan.terms"));
                info.setTerms(ss.getInt("grouploan.terms"));
                info.setRequestDate(ss.getDate("requestDate"));
                info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
                info.setInstallAmount(ss.getDouble("grouploan.emi"));
                info.setLoanType("Group Loan");
                info.setLoanNo(ss.getString("loanNo"));
                info.setSubLoanNo(ss.getString("sub_loan_no"));
                info.setIdProof(ss.getString("idproof"));
                info.setFileCharge(ss.getString("fileCharge"));
                info.setInsuranceFee(ss.getString("insurance_fee"));
                info.setCenter(ss.getString("center"));
                
                if (info.getCenter() != null) 
                {
                	info.setCenterName(centerNameByCenterId(info.getCenter(), conn));
				}
                info.setMembers(ss.getString("members"));
               
                info.setAppChqNo(ss.getString("grouploan.app_chq_no"));
                info.setAppAccNo(ss.getString("grouploan.app_acc_no"));
                info.setAppBankName(ss.getString("grouploan.app_bank_name"));
                info.setAppBankBranch(ss.getString("grouploan.app_bank_branch"));
               
                info.setG1ChqNo(ss.getString("grouploan.g1_chq_no"));
                info.setG1AccNo(ss.getString("grouploan.g1_acc_no"));
                info.setG1BankName(ss.getString("grouploan.g1_bank_name"));
                info.setG1BankBranch(ss.getString("grouploan.g1_bank_branch"));
               
                info.setG2ChqNo(ss.getString("grouploan.g2_chq_no"));
                info.setG2AccNo(ss.getString("grouploan.g2_acc_no"));
                info.setG2BankName(ss.getString("grouploan.g2_bank_name"));
                info.setG2BankBranch(ss.getString("grouploan.g2_bank_branch"));
               
                info.setFrequency(String.valueOf(ss.getInt("frequency")));
                info.setFrequencyVal(ss.getInt("frequency"));
                info.setDsacode(ss.getString("dsacode"));
                info.setCommission(ss.getDouble("commission"));
                info.setPlanNo(ss.getString("plan_no"));
               
                list.add(info);
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return list;
    }

	// increase Company Cash Balance by any credit Cash Entry and amount increase in this method
	public void increaseSharedCompanyAmount(int branchId,double amount, Connection conn)
	{
		Statement st=null;
		double sharedAmount=totalSharedAmountOfCompany(branchId);
		double updatedAmount=sharedAmount+amount;
		try
		{
			 st=conn.createStatement();
			String qq="update company_shares set amount_shared='"+updatedAmount+"'";
			st.executeUpdate(selectQueWithBranch(qq, branchId));
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
	}
	
	// increase Saving Account Balance by using deposit or transfer from other account into saving Account and amount should be increase before parameter passing
	public void increaseSavingAccountAmount(double amount, String savingAccountNo)
	{
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="update savingaccount set amount='"+amount+"' where accountNo='"+savingAccountNo+"' ";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
				dataInsertInQueryTable(qq, con);
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}
	
	// increase Company Cash Balance by any credit Cash Entry and amount increase in this method
	public void increaseCompanyCapitalAmount(int branchId,double amount,Connection conn)
	{
		double capitalAmount=totalCompanyCapitalAmount(branchId);
		double updatedCapitalAmount=capitalAmount+amount;
		Statement st=null;
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
				st=con.createStatement();
			String qq="update company_shares set company_capital_amount='"+updatedCapitalAmount+"'";
			st.executeUpdate(selectQueWithBranch(qq,branchId));
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
			
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
	// add new DSA in DSA Table
	public int adddsa(int branchId,String code1, String name, String address, String mobile, String commissionType, double commissionValue, String categoryname, Connection conn) 
	{
		Statement stt=null;
		try 
		{
		 stt = conn.createStatement();
			String query ="insert into dsa (code, name, mobile, address, status,commission_type,commission_value,category_type, branch_id) "
					+ "values('"+code1+"','"+name+"','"+mobile+"','"+address+"','active','"+commissionType+"','"+commissionValue+"','"+categoryname+"','"+branchId+"')";
			 int er = stt.executeUpdate(query);
			 if(er>0)
			 {
				 dataInsertInQueryTable(query, conn);
				 return er;
			 }
			
		} catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}

		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	
	// update Personal Loan Status and Emi Due Date id date is not null
	public int updateStatusForPersonalLoan(String id, String status, Date approveDate, String amount, Date emiDueDate, Connection conn) 
	{
		 int i=0;
		 
		Timestamp tt=null;
		if(emiDueDate!=null)
		{
			tt=new Timestamp(emiDueDate.getTime());
		}
			
		Timestamp approvalDate=new Timestamp(approveDate.getTime());
		try
		{
			Statement stt=conn.createStatement();
			String query="";
			if(emiDueDate!=null)
			{
				query="update personalloan set status='"+status+"',approvalDate='"+approvalDate+"', emi_due_date='"+tt+"' where id='"+id+"'";
			}
			else
			{
			      query="update personalloan set status='"+status+"',approvalDate='"+approvalDate+"' where id='"+id+"'";
			}
			if(status.equals("Approve"))
			{
				 i=stt.executeUpdate(query);
				 if(i>=1)
				 {
					 dataInsertInQueryTable(query, conn);
					 return 1;
				 }
			}
			else
			{
				i=stt.executeUpdate(query);
				 if(i>=1)
				 {
					 dataInsertInQueryTable(query, conn);
					 return 1;
				 }
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public int updateStatusForPersonalLoanByLoanNo(String loanNo, String status, Date approveDate, Date emiDueDate, Connection conn) 
	{
		 int i=0;
		 
		Timestamp tt=null;
		if(emiDueDate!=null)
		{
			tt=new Timestamp(emiDueDate.getTime());
		}
			
		Timestamp approvalDate=new Timestamp(approveDate.getTime());
		try
		{
			Statement stt=conn.createStatement();
			String query="";
			if(emiDueDate!=null)
			{
				query="update personalloan set status='"+status+"',approvalDate='"+approvalDate+"', emi_due_date='"+tt+"' where loanNo='"+loanNo+"'";
			}
			else
			{
			      query="update personalloan set status='"+status+"',approvalDate='"+approvalDate+"' where loanNo='"+loanNo+"'";
			}
			if(status.equals("Approve"))
			{
				 i=stt.executeUpdate(query);
				 if(i>=1)
				 {
					 dataInsertInQueryTable(query, conn);
					 return 1;
				 }
			}
			else
			{
				i=stt.executeUpdate(query);
				 if(i>=1)
				 {
					 dataInsertInQueryTable(query, conn);
					 return 1;
				 }
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public int updateStatusForSecureLoanByLoanNo(String loanNo, String status, Date approveDate, Date emiDueDate, Connection conn) 
	{
		 int i=0;
		 
		Timestamp tt=null;
		if(emiDueDate!=null)
		{
			tt=new Timestamp(emiDueDate.getTime());
		}
			
		Timestamp approvalDate=new Timestamp(approveDate.getTime());
		try
		{
			Statement stt=conn.createStatement();
			String query="";
			if(emiDueDate!=null)
			{
				query="update secure_loan set status='"+status+"',approvalDate='"+approvalDate+"', emi_due_date='"+tt+"' where loanNo='"+loanNo+"'";
			}
			else
			{
			      query="update secure_loan set status='"+status+"',approvalDate='"+approvalDate+"' where loanNo='"+loanNo+"'";
			}
			if(status.equals("Approve"))
			{
				 i=stt.executeUpdate(query);
				 if(i>=1)
				 {
					 dataInsertInQueryTable(query, conn);
					 return 1;
				 }
			}
			else
			{
				i=stt.executeUpdate(query);
				 if(i>=1)
				 {
					 dataInsertInQueryTable(query, conn);
					 return 1;
				 }
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	
	// update Personal Loan Status and Emi Due Date id date is not null
	public int updateStatusForSecureLoan(String id, String status, Date approveDate, String amount, Date emiDueDate, Connection conn) 
	{
		/*double loanAmount=Double.valueOf(amount);
		 double remainingCompanyCapitalAmount=remainingCompanyCapitalAmount();*/
		 int i=0;
		 
		Timestamp tt=null;
		if(emiDueDate!=null)
		{
			tt=new Timestamp(emiDueDate.getTime());
		}
			
		Timestamp approvalDate=new Timestamp(approveDate.getTime());
		try
		{
			Statement stt=conn.createStatement();
			String query="";
			if(emiDueDate!=null)
			{
				query="update secure_loan set status='"+status+"',approvalDate='"+approvalDate+"', emi_due_date='"+tt+"' where id='"+id+"'";
			}
			else
			{
			      query="update secure_loan set status='"+status+"',approvalDate='"+approvalDate+"' where id='"+id+"'";
			}
			if(status.equals("Approve"))
			{
				 i=stt.executeUpdate(query);
				 if(i>=1)
				 {
					 dataInsertInQueryTable(query, conn);
					 return 1;
				 }
			}
			else
			{
				i=stt.executeUpdate(query);
				 if(i>=1)
				 {
					 dataInsertInQueryTable(query, conn);
					 return 1;
				 }
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
		
	// update Personal Loan Status and Emi Due Date id date is not null
	public int updateStatusForBusinessLoan(String id, String status, Date approveDate, String amount, Date emiDueDate, Connection conn) 
	{
		/*double loanAmount=Double.valueOf(amount);
		 double remainingCompanyCapitalAmount=remainingCompanyCapitalAmount();*/
		 int i=0;
		 
		Timestamp tt=null;
		if(emiDueDate!=null)
		{
			tt=new Timestamp(emiDueDate.getTime());
		}
			
		Timestamp approvalDate=new Timestamp(approveDate.getTime());
		try
		{
			Statement stt=conn.createStatement();
			String query="";
			if(emiDueDate!=null)
			{
				query="update business_loan set status='"+status+"',approvalDate='"+approvalDate+"', emi_due_date='"+tt+"' where id='"+id+"'";
			}
			else
			{
			      query="update business_loan set status='"+status+"',approvalDate='"+approvalDate+"' where id='"+id+"'";
			}
			if(status.equals("Approve"))
			{
				 i=stt.executeUpdate(query);
				 if(i>=1)
				 {
					 dataInsertInQueryTable(query, conn);
					 return 1;
				 }
			}
			else
			{
				i=stt.executeUpdate(query);
				 if(i>=1)
				 {
					 dataInsertInQueryTable(query, conn);
					 return 1;
				 }
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	// update Vehicle Loan Status and Emi Due Date id date is not null
	public int updateStatusForVechileLoan(String id, String status, Date approveDate, String amount, Date emiDueDate, Connection conn)
	{
		/*double loanAmount=Double.valueOf(amount);
		 double remainingCompanyCapitalAmount=remainingCompanyCapitalAmount();*/
		 int i=0;
		 Timestamp tt=null;
			if(emiDueDate!=null)
			{
				tt=new Timestamp(emiDueDate.getTime());
			}
		Timestamp approvalDate=new Timestamp(approveDate.getTime());
		try
		{
			Statement stt=conn.createStatement();
			String query="";
			if(emiDueDate!=null)
			{
				query="update vechicleloan set status='"+status+"',approvalDate='"+approvalDate+"', emi_due_date='"+tt+"' where id='"+id+"'";
			}
			else
			{
				query="update vechicleloan set status='"+status+"',approvalDate='"+approvalDate+"' where id='"+id+"'";
			}
			
			if(status.equals("Approve"))
			{
				i=stt.executeUpdate(query);
				 if(i>=1)
				 {
					 dataInsertInQueryTable(query, conn);
					 return 1;
				 }
			}
			else
			{
				i=stt.executeUpdate(query);
				 if(i>=1)
				 {
					 dataInsertInQueryTable(query, conn);
					 return 1;
				 }
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	// update Property Loan Status and Emi Due Date id date is not null
	public int updateStatusForPropertyLoan(String id, String status, Date approveDate, String amount, Date emiDueDate, Connection conn ) 
	   {
		 /*double loanAmount=Double.valueOf(amount);
		 double remainingCompanyCapitalAmount=remainingCompanyCapitalAmount();*/
		 int i=0;
		 Timestamp tt=null;
			if(emiDueDate!=null)
			{
				tt=new Timestamp(emiDueDate.getTime());
			}
		 Timestamp approvalDate=new Timestamp(approveDate.getTime());
			try
			{
				Statement stt=conn.createStatement();
				String query="";
				
				if(emiDueDate!=null)
				{
					query="update propertyloan set status='"+status+"',approvalDate='"+approvalDate+"', emi_due_date='"+tt+"' where id='"+id+"'";
				}
				else
				{
					query="update propertyloan set status='"+status+"',approvalDate='"+approvalDate+"' where id='"+id+"'";
				}
				
				if(status.equals("Approve"))
				{
					i=stt.executeUpdate(query);
					 if(i>=1)
					 {
						 dataInsertInQueryTable(query, conn);
						 return 1;
					 }
				}
				else
				{
					i=stt.executeUpdate(query);
					 if(i>=1)
					 {
						 dataInsertInQueryTable(query, conn);
						 return 1;
					 }
				}
			} 
			catch (Exception e) 
			{
				 e.printStackTrace();fileCreation(e.getMessage());
			}
			return 0;
		}  

	// update Group Loan Status and Emi Due Date id date is not null
		public int updateStatusForGroupLoan(String id, String status, Date approveDate, String amount, Date emiDueDate, String loanNo, String subLoanNo, Connection conn) 
	   {
		   /*double loanAmount=Double.valueOf(amount);
		   double remainingCompanyCapitalAmount=remainingCompanyCapitalAmount();*/
		   int i=0;
		   Timestamp tt=null;
			if(emiDueDate!=null)
			{
				tt=new Timestamp(emiDueDate.getTime());
			}
		   Timestamp approvalDate=new Timestamp(approveDate.getTime());
			try
			{
				Statement stt=conn.createStatement();
				String query="";
				if(emiDueDate!=null)
				{
					query="update grouploan set status='"+status+"',approvalDate='"+approvalDate+"', emi_due_date='"+tt+"' where sub_loan_no='"+subLoanNo+"'";
				}
				else
				{
					query="update grouploan set status='"+status+"',approvalDate='"+approvalDate+"' where sub_loan_no='"+subLoanNo+"'";
				}
				
				if(status.equals("Approve"))
				{
					i=stt.executeUpdate(query);
					 if(i>=1)
					 {
						 dataInsertInQueryTable(query, conn);
						 return 1;
					 }
				}
				else
				{
					i=stt.executeUpdate(query);
					 if(i>=1)
					 {
						dataInsertInQueryTable(query, conn);
						 return 1;
					 }
				}
			} 
			catch (Exception e) 
			{
				 e.printStackTrace();fileCreation(e.getMessage());
			}
			return 0;
	   }   
	   
		// to get the Deposit (DD/RD/FD) detail from customer_info table by using deposit user no
	   public double checkForPaymentReceipt(String user_no,String scheme)
		{
			double payableAmount = 0;
			try (Connection conn = DataBaseConnection.JAVAConnection();) 
			{
				Statement st = conn.createStatement();
				String qq = "select * from customer_info where user_no='" + user_no+"' and account_status='active' and paid_status='unpaid'";
				ResultSet rs = st.executeQuery(qq);
				if (rs.next()) 
				{
					int x=0;
					int terms = rs.getInt("terms");
					/*int frequency=rs.getInt("frequency");
					if(frequency==4)
				    {
				    	x=terms/3;
				    }
				    else if(frequency==2)
				    {
				    	x=terms/6;
				    }
				    else if(frequency==1)
				    {
				    	x=terms/12;
				    }
				    else if(frequency==12)
				    {
				    	x=terms;
				    }*/
					double instlmnt = rs.getDouble("installment_amount");
					if(scheme.equals("RD") || scheme.equals("DD"))
					{
						payableAmount = instlmnt * terms;
					}
					else
					{
						payableAmount = instlmnt;
					}
				}
			} 
			catch (Exception e) 
			{
				 e.printStackTrace();fileCreation(e.getMessage());
			}
			return payableAmount;
		}
	   
	   // to find the total Paid amount by user against a deposit no RDDD
	   public double paidAmountByUser(String user_no, Connection conn) 
	   {
		   Statement stt=null;
		   ResultSet rr =null;
			double amount = 0;
			try 
			{
				stt = conn.createStatement();
				String qs = "select sum(amount) from payment_receipt where user_no='"+ user_no + "' and receipt_status='approved' and chequeStatus='cleared' ";
				rr= stt.executeQuery(qs);
				if (rr.next()) 
				{
					amount = rr.getDouble("sum(amount)");
				}
			} 
			catch (Exception e)
			{
				 e.printStackTrace();fileCreation(e.getMessage());
			}
			finally
			{
				try {
					if(stt!=null)
					{
						stt.close();
					}
					if(rr!=null)
					{
						rr.close();
					}
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
			return amount;
		}
	   
	   // to find the paid amount against Deposit by a Particular date. 
	   public double paidAmountByUserByDate(String user_no,Connection conn, String eDate) 
	   {
		   Statement stt=null;
		   ResultSet rr =null;
			double amount = 0;
			try 
			{
				stt = conn.createStatement();
				String qs = "select sum(amount) from payment_receipt where user_no='"+ user_no + "' and receipt_status='approved' and chequeStatus='cleared' and date<='"+eDate+"' ";
				rr= stt.executeQuery(qs);
				if (rr.next()) 
				{
					amount = rr.getDouble("sum(amount)");
				}
			} 
			catch (Exception e)
			{
				 e.printStackTrace();fileCreation(e.getMessage());
			}
			finally
			{
				try {
					if(stt!=null)
					{
						stt.close();
					}
					if(rr!=null)
					{
						rr.close();
					}
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
			return amount;
		}
	   
	   // this method not use right now 
	   public int updateReceipt(String id, double amount, Date date,String cheque_no, Date cheque_date, String bank_name, double penalty) 
		{
			int j = 0;
			Timestamp dt = new Timestamp(date.getTime());
			Timestamp cdt = null;
			if (cheque_date != null)
			{
				cdt = new Timestamp(cheque_date.getTime());
			}
			try (Connection con = DataBaseConnection.JAVAConnection();) 
			{
				String query = "update payment_receipt set date=?,amount='"+ amount+"', cheque_no='"+cheque_no+"',cheque_date=?,"
						+ "bank_name='" + bank_name+ "', penalty='" + penalty + "' where id='" + id + "'";
				PreparedStatement st1 = con.prepareStatement(query);
				st1.setTimestamp(1, dt);
				st1.setTimestamp(2, cdt);
				int i = st1.executeUpdate();
				if (i >= 1)
				{
					String query1="update payment_receipt set date='" + dt + "',amount='"+ amount+"', cheque_no='"+cheque_no+"',cheque_date='" + cdt + "',"
							+ "bank_name='" + bank_name+ "', penalty='" + penalty + "' where id='" + id + "'";
					dataInsertInQueryTable(query1, con);
					j++;
				}
					
			} 
			catch (Exception e) 
			{
				 e.printStackTrace();fileCreation(e.getMessage());
			}
			return j;
		}

	// use for document upload online and offline
	   public void makeProfile(UploadedFile file, String filePath) {
			Connection conn = DataBaseConnection.JAVAConnection();
			filePathDetail(conn); // Method for set file upload path
			String realPath = "";

			if (onlineFileUploadPath == null || onlineFileUploadPath.trim().equals("")) {
				ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
				realPath = ctx.getRealPath("/");
			} else {
				realPath = onlineFileUploadPath;
			}

			String savePath = realPath;
			String fullFilePath = savePath + filePath;

			try {
				// Create parent directory if it doesn't exist
				File outputFile = new File(fullFilePath);
				File parentDir = outputFile.getParentFile();
				if (parentDir != null && !parentDir.exists()) {
					parentDir.mkdirs(); // Create missing directories
				}

				// Write file
				InputStream in = file.getInputstream();
				OutputStream out = new FileOutputStream(outputFile);

				byte[] bytes = new byte[1024];
				int read;
				while ((read = in.read(bytes)) != -1) {
					out.write(bytes, 0, read);
				}
				in.close();
				out.flush();
				out.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			} finally {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
					fileCreation(e.getMessage());
				}
			}
		}
	   
	   
	   public void makeProfile(InputStream in, String filePath) {

		    Connection conn = DataBaseConnection.JAVAConnection();

		    try {

		        // DB se server upload path milega
		        filePathDetail(conn);

		        String realPath = "";

		        if (onlineFileUploadPath == null
		                || onlineFileUploadPath.trim().equals("")) {

		            System.out.println("ERROR: file_upload_path is empty in firm_detail");

		            return;
		        }

		        realPath = onlineFileUploadPath;

		        
		        if (!realPath.endsWith("/")
		                && !realPath.endsWith("\\")) {

		            realPath = realPath + File.separator;
		        }

		        String fullFilePath = realPath + filePath;

		        System.out.println("UPLOAD PATH = " + fullFilePath);

		        File outputFile = new File(fullFilePath);

		        File parentDir = outputFile.getParentFile();

		        if (parentDir != null && !parentDir.exists()) {
		            parentDir.mkdirs();
		        }

		        OutputStream out =
		                new FileOutputStream(outputFile);

		        byte[] bytes = new byte[1024];

		        int read;

		        while ((read = in.read(bytes)) != -1) {
		            out.write(bytes, 0, read);
		        }

		        out.flush();
		        out.close();
		        in.close();

		        System.out.println("PHOTO UPLOADED SUCCESSFULLY");
		        System.out.println("FILE = " + fullFilePath);

		    } catch (Exception e) {

		        e.printStackTrace();

		    } finally {

		        try {
		            conn.close();
		        } catch (SQLException e) {
		            e.printStackTrace();
		        }
		    }
		}

	
	// update share holder detail by id
	public int updateShareHolder(String id, String office_application_no, Date office_date, String shareNo,String first_applicantName,
	Date dob,String father_husband_name, String guardian_name,String guardian_relation,String status,String pAN,String bank_accountNo,
	String bank_name, String branch, String address,String mobile,String nominee_name, String nominee_relation, Date nominee_dob,
	String nominee_address, double noOfShare,double shareAmount, double totalAmount,String category,String
	perAddress, String votrId, String uniqueId, String rationNo, String dlNo, String electBill, 
	String resCert, String appCheque, String gCheque, String tBill,String gender, String maritalStatus, String keyPersonName, String keyPersonRelation, 
	String telephoneIndicator, int noOfDependent, String religion, String stateCode, String pinCode, String email, String qualification, String occupation, 
	String bankIfsc, String referenceBy, String remark, String title, String monthlyIncome, String nomAadhar, String nomPan, String brideFhname, String brideMname, 
	String brideAddress, String brideBusiness, String brideBusinessPlace, String brideMobileNo, String brideRemark,String nomTitle,String nomGender,String center,
	String altMobileNo,String nomMobileNo, String nomFatherName)
	{
		    
			int j = 0;
			Timestamp ofcdt = new Timestamp(office_date.getTime());
			Timestamp dbdt = new Timestamp(dob.getTime());
			Timestamp ndbdt=null;
						
			
			if(nominee_dob!=null)
			{
				ndbdt= new Timestamp(nominee_dob.getTime());
			}
			
			try (Connection conn = DataBaseConnection.JAVAConnection();)
			{   
		        	
				String query="update shareholder_info set office_application_no=?,office_date=?,shareholderno=?,first_applicantName=?,"
				+ "dob=?, father_husband_name=?, guardian_name=?, guardian_relation=?, status=?,PAN=?, bank_accountNo=?, bank_name=?,"
				+ "branch=?, address=?, mobile=?,nominee_name=?, nominee_relation=?, nominee_dob=?,nominee_address=?,"
				+ "account_status=?,noofShare=?,shareAmount=?,totalAmount=?,perAddress=?,category=?, "
				+ "voter_id=?, unique_id=?, ration_no=?, dl_no=?, elect_bill=?, res_cert=?, app_cheque=?, g_cheque=?, t_bill=?, "
				+ " gender=?, marital_status=?, key_person_name=?, key_person_relation=?, "
				+ "telephone_indicator=?, no_of_dependent=?, religion=?, state_code=?, pin_code=?, email=?, qualification=?, occupation=?, bank_ifsc=?, reference_by=?,"
				+ " remark=?, title=?, monthly_income=?, nom_aadhar=?, nom_pan=?, bride_fhname=?, bride_mname=?, bride_address=?, bride_business=?, "
				+ " bride_business_place=?, bride_mobile_no=?, bride_remark=?,nom_title=?,nom_gender=?,center=?,alt_mobile_no=?,nom_mobile_no=?,nominee_father=? where id='"+id+"'";
				
				
				PreparedStatement st1 = conn.prepareStatement(query);
				st1.setString(1, office_application_no);
				st1.setTimestamp(2, ofcdt);
				st1.setString(3, shareNo);
				st1.setString(4, first_applicantName);
				st1.setTimestamp(5, dbdt);
				st1.setString(6, father_husband_name);
				st1.setString(7, guardian_name);
				st1.setString(8, guardian_relation);
				st1.setString(9, status);
				st1.setString(10, pAN);
				st1.setString(11, bank_accountNo);
				st1.setString(12, bank_name);
				st1.setString(13, branch);
				st1.setString(14, address);
				st1.setString(15, mobile);
				st1.setString(16, nominee_name);
				st1.setString(17, nominee_relation);
				st1.setTimestamp(18, ndbdt);
				st1.setString(19, nominee_address);
				st1.setString(20, "active");
				st1.setDouble(21, noOfShare);
				st1.setDouble(22, shareAmount);
				st1.setDouble(23, totalAmount);
				st1.setString(24, perAddress);
				st1.setString(25, category);
				st1.setString(26, votrId);
				st1.setString(27, uniqueId);
				st1.setString(28, rationNo);
				st1.setString(29, dlNo);
				st1.setString(30, electBill);
				st1.setString(31, resCert);
				st1.setString(32, appCheque);
				st1.setString(33, gCheque);
				st1.setString(34, tBill);
				st1.setString(35, gender);
				st1.setString(36, maritalStatus);
				st1.setString(37, keyPersonName);
				st1.setString(38, keyPersonRelation);
				st1.setString(39, telephoneIndicator);
				st1.setInt(40, noOfDependent);
				st1.setString(41, religion);
				st1.setString(42, stateCode);
				st1.setString(43, pinCode);
				st1.setString(44, email);
				st1.setString(45, qualification);
				st1.setString(46, occupation);
				st1.setString(47, bankIfsc);
				st1.setString(48, referenceBy);
				st1.setString(49, remark);
				st1.setString(50, title);
				st1.setString(51, monthlyIncome);
				st1.setString(52, nomAadhar);
				st1.setString(53, nomPan);
				st1.setString(54, brideFhname);
				st1.setString(55, brideMname);
				st1.setString(56, brideAddress);
				st1.setString(57, brideBusiness);
				st1.setString(58, brideBusinessPlace);
				st1.setString(59, brideMobileNo);
				st1.setString(60, brideRemark);
				st1.setString(61, nomTitle);
				st1.setString(62, nomGender);
				st1.setString(63, center);
				
				st1.setString(64, altMobileNo);
				st1.setString(65, nomMobileNo);
				st1.setString(66, nomFatherName);
				
				int i = st1.executeUpdate();
				if (i >= 1)
				{
					dataInsertInQueryTable(String.valueOf(st1), conn);
					j++;
				}
					
			} 
			catch (Exception e)
			{
				 e.printStackTrace();fileCreation(e.getMessage());
			}
			return j;
		}
	    
	// to calculate the Loan EMI using Reducing Interest method
	public double calculateLoanEmi(double principalBal, double loanterm,double interstRate, int frequency) 
	{
		double interestMonthly,monthlyPayment;
		interestMonthly = interstRate / (100.00 * frequency);
		try
		{
			monthlyPayment = principalBal* ((interestMonthly * (Math.pow((1 + interestMonthly), loanterm))) / (Math.pow((1 + interestMonthly), loanterm) - 1));
			monthlyPayment=Double.parseDouble(df.format(monthlyPayment));
		}
		catch(Exception e)
		{
			monthlyPayment=0;
		}
		return Math.round(monthlyPayment);
	}

	// to find the deposit no with dynamic Prefix and Length
	public String calculateUserNo(int branchId,String type)
	{
		String acc="";
		String qq="";
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			if(checkContinitySchemeNo(branchId,con).equals("true"))
			{
				if(checkContinityLoanNo(branchId,con).equals("true"))
				{
					qq = "select user_no from customer_info where scheme_type='"+type+"' and branch_id='"+branchId+"' order by id desc limit 1";
				}
				else
				{
					qq = "select user_no from customer_info where scheme_type='"+type+"' order by id desc limit 1";
				}
				   
			}
			else
			{
				if(checkContinityLoanNo(branchId,con).equals("true"))
				{
					qq = "select user_no from customer_info where branch_id='"+branchId+"' order by id desc limit 1";
				}
				else
				{
					qq = "select user_no from customer_info order by id desc limit 1";
				}
				
			}
		
			ResultSet rs = st.executeQuery(qq);
			//System.out.println(qq);
			int accLen=accountNoLengthFromMasterTable(type,branchId);
			if (rs.next()) 
			{
				String no=rs.getString("user_no");
				
				String account=String.valueOf(Integer.parseInt(no.substring(no.length()-accLen,no.length()))+ 1);
				int len=account.length();
				if(len>0)
				{
					while(acc.length()!=accLen-len)
					{
						acc+="0";
					}
					acc=acc+account;
				}
			}
			else
			{
				// if table is blank than come in this block
				if(accLen==4)
				{
					acc="0001";
				}
				else if(accLen==5)
				{
					acc="00001";
				}
				else if(accLen==6)
				{
					acc="000001";
				}
				else if(accLen==7)
				{
					acc="0000001";
				}
				else if(accLen==8)
				{
					acc="00000001";
				}
				else if(accLen==9)
				{
					acc="000000001";
				}
				else if(accLen==10)
				{
					acc="0000000001";
				}
			}
			String accInitial=accountNoInitialFromMasterTable(branchId,type);   // deposit no initial word from master_setting table
			acc=accInitial+acc;
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return acc;
	}

	// to find the shareholder no with dynamic Prefix and Length
	public String shareHolderNo(int branchId) 
	{ 
		String account="",qq="";
		HeaderBean hh=new HeaderBean();
//		if(!hh.getName().equalsIgnoreCase("Vibhu Micro Benefit Foundation"))  // Condition for manual share holder no 16 january 2023
//		{
			try(Connection con = DataBaseConnection.JAVAConnection();) 
			{
				
	            String checkStart = checkContinityLoanNo(branchId,con);
				Statement st = con.createStatement();
				
				if(checkStart.equals("true"))
				{
					qq = "select shareholderno from shareholder_info where branch_id='"+branchId+"' order by id desc";
				}
				else
				{
					qq = "select shareholderno from shareholder_info  order by id desc";
				}
				ResultSet rs = st.executeQuery(qq);
				int accLen=accountNoLengthFromMasterTable("Share Holder",branchId);
				if(rs.next()) 
				{
					String no=rs.getString("shareholderno");
					account=String.valueOf(Integer.parseInt(no.substring(no.length()-accLen,no.length()))+ 1);
				}
				String initial=accountNoInitialFromMasterTable(branchId,"Share Holder");
				account=initial+commonNo(account,accLen);
			}
			catch (Exception e) 
			{
				 e.printStackTrace();fileCreation(e.getMessage());
			}
//		}
		
		return account;
	}
	
	public String insertFirmDetails(String address1,String address2,String address3,String address4,String branchCode, String branchName, Connection con) 
	{
		Statement st =null,st1=null;ResultSet rs=null;
		int branchId = 0;
		try 
		{
			
		   st=con.createStatement();
		   st1=con.createStatement();
		   String query="insert into firm_detail(mobile_no,address1,address2,address3,address4,branch_code,branch_name) values('"+address1+"','"+address2+"','"+address3+"','"+address4+"','"+branchCode+"','"+branchName+"')";	
		  //System.out.println(query);
		   int i = st.executeUpdate(query);
		   if(i>0)
		   {
			   
			   String pQue="select id from firm_detail order by id desc limit 1";	
			   rs=st1.executeQuery(pQue);
			   if(rs.next())
			   {
				   branchId=rs.getInt("id");
			   }
			   insertBasicBalanceSheetValue(branchId,con);
			   insertFyDetails(branchId,con);
			   insertBasicCompanyShare(branchId,con);
			//   insertMasterSetting(branchId,con);
			   return "1";
		   }
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		finally {
			try {
				if(st!=null)
				{
					st.close();
				}
				if(st1!=null)
				{
					st1.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "0";
		
	}
	
//	private void insertMasterSetting(int branchId, Connection con)
//	{
//		
//		
//	}
//	private ArrayList<UserInfo> masterSettingHeads(Connection con)
//	{
//		Statement st =null; ResultSet rs = null;
//		ArrayList<UserInfo> list = new ArrayList<UserInfo>();
//        
//		try {
//			st=con.createStatement();
//			String query ="select * from master_setting where branch_id=1";
//			rs = st.executeQuery(query);
//			while
//			
//		} catch (Exception e) {
//			// TODO: handle exception
//		}
//		
//		return list;
//	}

	private void insertFyDetails(int branchId, Connection con) 
	{
        String fYear,sDate,eDate;
		int d = new Date().getYear()+1900;
		int m = new Date().getMonth()+1;
		if(m>3)
		{
			fYear = String.valueOf(d)+"-"+String.valueOf(d+1);
			sDate = String.valueOf(d)+"-"+"04-01";
			eDate = String.valueOf(d+1)+"-"+"03-31";
		}
		else
		{
			fYear = String.valueOf(d-1)+"-"+String.valueOf(d);
			sDate = String.valueOf(d-1)+"-"+"04-01";
			eDate = String.valueOf(d)+"-"+"03-31";
		}
		Statement st =null;
		try 
		{
		   st=con.createStatement();
		   String query="insert into fy_setting(financial_year,fy_start_date,fy_end_date,data_freeze_status,status,branch_id)"
				   		+ " values('"+fYear+"','"+sDate+"','"+eDate+"','no','active','"+branchId+"')";	
				    st.executeUpdate(query);
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		finally {
			try {
				if(st!=null)
				{
					st.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	
		
	}

	private void insertBasicCompanyShare(int branchId, Connection con) 
	{
		Statement st =null;
		try 
		{
		   st=con.createStatement();
		   String query="insert into company_shares(no_of_shares,share_amount,company_capital_amount,amount_shared,share_amt_member,share_check,branch_id)"
				   		+ " values('0','0','0.0','0.0','no','yes','"+branchId+"')";	
				    st.executeUpdate(query);
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		finally {
			try {
				if(st!=null)
				{
					st.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}

	private void insertBasicBalanceSheetValue(int branchId,Connection con)
	{
		Statement st =null;
		Timestamp tp = new Timestamp(new Date().getTime());
		tp.setNanos(0);
		int d = new Date().getYear()+1900;
		String year = String.valueOf(d-1)+"-"+String.valueOf(d);
		ArrayList<BankInfo> list  = balanceSheetHeads(con);
		try 
		{
		   st=con.createStatement();
		   
		   for(int i=0;i<list.size();i++)
		   {
			   String query="insert into balance_sheet(liabilities_head,dr_amount,assets_head,cr_amount,financial_year,entry_date,branch_id)"
				   		+ " values('"+list.get(i).getLibilityName()+"','0.0','"+list.get(i).getAssetName()+"','0','"+year+"','"+tp+"','"+branchId+"')";	
				    st.executeUpdate(query);
		   }
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		finally {
			try {
				if(st!=null)
				{
					st.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}

	public boolean checkBranchCodeName(String branchCode, String branchName, Connection con) 
	{
		Statement st=null;ResultSet rr=null;
		try
		{
			st=con.createStatement();
			String query="select id from firm_detail where (branch_code='"+branchCode+"' or branch_name='"+branchName+"')";
			rr = st.executeQuery(query);
			if(rr.next())
			{
				return true;
			}	
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	
		return false;
	}

	// to get the share/Loan/DD/RD/FD/DSA Initial word or prefix for account no.
	private String accountNoInitialFromMasterTable(int branchId,String accountType) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select account_initial from master_setting where account_type='"+accountType+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getString("account_initial");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}
	
	// cf Natch related
	
	public String fetchDataBySubscriptionId(String sub_id) {
	    
	    String query = "SELECT loan_no FROM subscriptions_overview WHERE subscription_id = ?";
	    String loanNo = null;

	    try (Connection conn = DataBaseConnection.JAVAConnection();
	         PreparedStatement ps = conn.prepareStatement(query)) {

	        ps.setString(1, sub_id); 
	        try (ResultSet rs = ps.executeQuery()) {
	            if (rs.next()) {
	                loanNo = rs.getString("loan_no"); 
	              
	            }
	        }

    } catch (Exception e) {
        e.printStackTrace(); 
    }
   
    return loanNo;
}
	// to get the Length for share/Loan/DD/RD/FD/DSA no.
	private int accountNoLengthFromMasterTable(String accountType,int branchId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select account_length from master_setting where account_type='"+accountType+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq, branchId));
			if(rr.next())
			{
				return rr.getInt("account_length");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 6;
	}

	//to find the share certification no.
	public String shareHolderCertificationNo(double noOfShare, int id, String tableName)
	{
		String accStart="";
		String accLast="";
		String accFinal="";
		String qq="";
		int nos=(int)noOfShare;
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			if(tableName.equalsIgnoreCase("shareholder_info"))
			{
				qq="select sum(noofShare) from shareholder_info where id<'"+id+"' ";
			}
			else
			{
				qq="select sum(noofShare) from shareholder_info ";
			}
			
			ResultSet rr = st.executeQuery(qq);
			if(rr.next())
			{
				int addShr=0;
				if(tableName.equalsIgnoreCase("share_info"))
				{
					addShr=additionalShareFromShareInfoTable(id, con);
				}
				else
				{
					addShr=additionalShareFromShareInfoTable(0, con);
				}
				
				
				int no_of_share=rr.getInt("sum(noofShare)");
				no_of_share+=addShr;          // Work for Additional Share 
				int lenOfSum=String.valueOf(no_of_share+1).length();
				String reqrd_share=String.valueOf(nos+no_of_share);
				int len=reqrd_share.length();
				if(lenOfSum>0)
				{
					while(accStart.length()!=10-lenOfSum)
					{
						accStart+="0";
					}
					accStart=accStart+(no_of_share+1);
				}
				
				if(len>0)
				{
					while(accLast.length()!=10-len)
					{
						accLast+="0";
					}
					accLast=accLast+(nos+no_of_share);
				}
				
				accFinal=accStart+"-"+accLast;
			}
			
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return accFinal;
	}
	
	private int additionalShareFromShareInfoTable(int id,Connection con) 
	{
		String qq="";
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=con.createStatement();
			if(id>0)
			{
				qq="select sum(noofShare) from share_info where id<'"+id+"'  ";
			}
			else
			{
				qq="select sum(noofShare) from share_info ";
			}
			rr = st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getInt("sum(noofShare)");
			}	
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	private int additionalShareFromShareInfoTable(Connection con) 
	{
		String qq="";
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=con.createStatement();
			qq="select sum(noofShare) from share_info ";
			rr = st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getInt("sum(noofShare)");
			}	
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	public String personalLoanNo(int branchId)
	{
		boolean cloneCheck = true ;
		HeaderBean hh=new HeaderBean();
		String account="";
	//	if(!hh.getName().equalsIgnoreCase("SUNLOG CREDITS PRIVATE LIMITED"))  // Condition for manual share holder no 07 Feb 2023
//		{
			String qq="";
			try (Connection con = DataBaseConnection.JAVAConnection();) 
			{ 			
				String checkStart = checkContinityLoanNo(branchId,con);
				
				Statement st = con.createStatement();
				
				if(checkStart.equals("true"))
				{
					qq = "select loanNo from personalloan where branch_id='"+branchId+"' and loanNo not like '%R%' order by id desc limit 1";
				}
				else
				{
					qq = "select loanNo from personalloan order by id desc limit 1"; 
					//where loanNo not like '%R%'  comment on 01 Nov 2023 due to RK rise
				}
				System.out.println(qq);
				
				
				 
				ResultSet rs = st.executeQuery(qq);
				
				int accLen=accountNoLengthFromMasterTable("Personal Loan",branchId);
				if (rs.next())
				{
					String no=rs.getString("loanNo");
					
					System.out.println(rs.getString("loanNo")+"mm");
					account=String.valueOf(Integer.parseInt(no.substring(no.length()-accLen,no.length()))+ 1);
				}
				String initial=accountNoInitialFromMasterTable(branchId,"Personal Loan");
				
				account=initial+commonNo(account,accLen);
			}
			catch (Exception e)
			{
				 e.printStackTrace();fileCreation(e.getMessage());
			}
		

			//here this method is passing this loan no for check is it clone or not !
			account = generateLoanNo(account);

		
		return account;
		
	} 
			 
		 
			

	

	public String generateLoanNo(String account) {
		
		while (loanNoCloneCheck(account)) {

        String[] parts = account.split("-");
        String prefix = parts[0];
        String numberPart = parts[1];

        long number = Long.parseLong(numberPart);
        number++;

        // preserve leading zeros
        String newNumberPart = String.format("%0" + numberPart.length() + "d", number);

        account = prefix + "-" + newNumberPart;

        System.out.println("New Loan No Generated: " + account);
    }

    return account;}


	
	public boolean loanNoCloneCheck(String loanNo) {

	    String query = "";
	    
	    if (loanNo.startsWith("PL")) {
	        query = "SELECT loanNo FROM personalloan WHERE loanNo = ?";
	    } else if (loanNo.startsWith("GL")) {
	        query = "SELECT loanNo FROM grouploan WHERE loanNo = ?";
	    } else if (loanNo.startsWith("SL")) {
	        query = "SELECT loanNo FROM secure_loan WHERE loanNo = ?";
	    } else {
	        return false; // invalid loan number format
	    }

	    try (Connection conn = DataBaseConnection.JAVAConnection();
	        
	    		PreparedStatement ps = conn.prepareStatement(query)) {

	        ps.setString(1, loanNo);

	        try (ResultSet rs = ps.executeQuery()) {

	            if (rs.next()) {
	                // Loan already exists (CLONE)
	                return true;
	            } else {
	                // Loan does not exist
	                return false;
	            }
	        }

	    } catch (Exception e) {
	        e.printStackTrace();
	        return false;
	    }
	}

	
	// to find the CENTER CODE Loan no with dynamic Prefix and Length and R indicate Restructure Loan 
	public String centerCodeNo(int branchId)
	{
		
		String account="",qq="";
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			String checkStart = checkContinityLoanNo(branchId,con);
			
			Statement st = con.createStatement();
			
			if(checkStart.equals("true"))
			{
				qq = "select centerCode from center where branch_id='"+branchId+"' order by id desc limit 1";
			}
			else
			{
				qq = "select centerCode from center order by id desc limit 1";
			}
			
			
			 
			ResultSet rs = st.executeQuery(qq);
			if (rs.next())
			{
				String no=rs.getString("centerCode");
				account=String.valueOf(Integer.parseInt(no)+ 1);
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return account;
	}
		
	// to find the secure Loan no with dynamic Prefix and Length and R indicate Restructure Loan 
	public String secureLoanNo(int branchId)
	{   boolean cloneCheck = true;
		HeaderBean hh=new HeaderBean();
		String account="",qq="";
		if(!hh.getName().equalsIgnoreCase("AADHUNIK GROUP"))  // Condition for manual share holder no 07 Feb 2023
		{
			try (Connection con = DataBaseConnection.JAVAConnection();) 
			{
				String checkStart = checkContinityLoanNo(branchId,con);
				Statement st = con.createStatement();
				
				if(checkStart.equals("true"))
				{
					qq = "select loanNo from secure_loan where branch_id='"+branchId+"' and loanNo not like '%R%' order by id desc limit 1";
				}
				else
				{
					qq = "select loanNo from secure_loan where loanNo not like '%R%' order by id desc limit 1";
				}
				
				ResultSet rs = st.executeQuery(qq);
				int accLen=accountNoLengthFromMasterTable("Secure Loan",branchId);
				if (rs.next())
				{
					String no=rs.getString("loanNo");
					account=String.valueOf(Integer.parseInt(no.substring(no.length()-accLen,no.length()))+ 1);
				}
				String initial=accountNoInitialFromMasterTable(branchId,"Secure Loan");
				account=initial+commonNo(account,accLen);
			}
			catch (Exception e)
			{
				 e.printStackTrace();fileCreation(e.getMessage());
			}
		}	
		//here this method is passing this loan no for check is it clone or not !
		account = generateLoanNo(account);


//		while(cloneCheck) {
//			 
//			 
//			 System.out.println("loanNo"+account+" going for check with status"+cloneCheck); 
//       
//			 cloneCheck =  loanNoCloneCheck(account);
//			
//
//			// Step 1: Split
//			String numberStr = account.split("-")[1];
//
//			// Step 2: Convert to integer or long
//			long number = Long.parseLong(numberStr);
//
//			// Step 3: Increase by 1
//			number = number + 1;
//
//			// Step 4: Convert back to string
//			String newNumberStr = String.valueOf(number);
//
//			// Step 5: Add prefix again
//			String prefix = account.split("-")[0];
//			account = prefix + "-" + newNumberStr;
//		  
//
//			System.out.println(account); 
//
//				System.out.println(number); 
//			 
//		 }

		return account;
	
	}
		
	
		
	
		
	// to find the secure Loan no with dynamic Prefix and Length and R indicate Restructure Loan 
	public String businessLoanNo(int branchId)
	{
		String account="",qq="";
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			String checkStart = checkContinityLoanNo(branchId,con);
			Statement st = con.createStatement();
			if(checkStart.equals("true"))
			{
				qq = "select loanNo from business_loan where branch_id='"+branchId+"' and loanNo not like '%R%' order by id desc limit 1";
			}
			else
			{
				qq = "select loanNo from business_loan where loanNo not like '%R%' order by id desc limit 1";
			}
			ResultSet rs = st.executeQuery(qq);
			int accLen=accountNoLengthFromMasterTable("Business Loan",branchId);
			if (rs.next())
			{
				String no=rs.getString("loanNo");
				account=String.valueOf(Integer.parseInt(no.substring(no.length()-accLen,no.length()))+ 1);
			}
			String initial=accountNoInitialFromMasterTable(branchId,"Business Loan");
			account=initial+commonNo(account,accLen);
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return account;
	}
	
	// to find the group Loan no with dynamic Prefix and Length and R indicate Restructure Loan and S indicate Sub Loan no.
	public String groupLoanNo(int branchId)
	{   boolean cloneCheck=true;
		String account="",qq="";
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			String checkStart = checkContinityLoanNo(branchId,con);
			Statement st=con.createStatement();
			if(checkStart.equals("true"))
			{
				qq = "select max(convert(temp_no,decimal)) as num  from grouploan where branch_id='"+branchId+"' and loanNo not like '%R%' and loanNo not like '%S%'";
			}
			else
			{
				qq = "select max(convert(temp_no,decimal)) as num  from grouploan where loanNo not like '%R%' and loanNo not like '%S%'";
			}
			 
			ResultSet rs = st.executeQuery(qq);
			int accLen=accountNoLengthFromMasterTable("Group Loan",branchId);
			if (rs.next())
			{
				int no=rs.getInt("num");
				account=String.valueOf(no+ 1);
			}
			String initial=accountNoInitialFromMasterTable(branchId,"Group Loan");
			account=initial+commonNo(account,accLen);
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		//here this method is passing this loan no for check is it clone or not !
		account = generateLoanNo(account);
		
		
		return account;
	}
	
	// to find the vehicle Loan no with dynamic Prefix and Length and R indicate Restructure Loan
	public String vechicleLoanNo(int branchId)
	{
		String account="",qq="";
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			String checkStart = checkContinityLoanNo(branchId,con);
			Statement st = con.createStatement();
			if(checkStart.equals("true"))
			{
				qq = "select loanno from vechicleloan where branch_id='"+branchId+"' and loanNo not like '%R%'  order by id desc limit 1";
			}
			else
			{
				qq = "select loanno from vechicleloan where loanNo not like '%R%'  order by id desc limit 1";
			}
			ResultSet rs = st.executeQuery(qq);
			int accLen=accountNoLengthFromMasterTable("Vehicle Loan",branchId);
			if (rs.next())
			{
				String no=rs.getString("loanno");
				account=String.valueOf(Integer.parseInt(no.substring(no.length()-accLen,no.length()))+ 1);
			}
			String initial=accountNoInitialFromMasterTable(branchId,"Vehicle Loan");
			account=initial+commonNo(account,accLen);
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return account;
	}

	// to find the property Loan no with dynamic Prefix and Length and R indicate Restructure Loan
	public String propertyLoanNo(int branchId) 
	{
		String account="",qq="";
		try (Connection con = DataBaseConnection.JAVAConnection();)
		{
			String checkStart = checkContinityLoanNo(branchId,con);
			Statement st = con.createStatement();
			if(checkStart.equals("true"))
			{
				qq = "select loanno from propertyloan where branch_id='"+branchId+"' and loanNo not like '%R%'  order by id desc limit 1";
			}
			else
			{
				qq = "select loanno from propertyloan where loanNo not like '%R%'  order by id desc limit 1";
			}
			ResultSet rs = st.executeQuery(qq);
			int accLen=accountNoLengthFromMasterTable("Property Loan",branchId);
			if (rs.next())
			{
				String no=rs.getString("loanno");
				account=String.valueOf(Integer.parseInt(no.substring(no.length()-accLen,no.length()))+ 1);
			}
			String initial=accountNoInitialFromMasterTable(branchId,"Property Loan");
			account=initial+commonNo(account,accLen);
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return account;
	}
	
	// to find the saving account no with dynamic Prefix and Length 
	public String savingAccountNo(int branchId) 
	{
		String account="",qq="";
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			String checkStart = checkContinityLoanNo(branchId,con);
			Statement st = con.createStatement();
			if(checkStart.equals("true"))
			{
				qq = "select accountNo from savingaccount where branch_id='"+branchId+"' order by id desc limit 1";
			}
			else
			{
				qq = "select accountNo from savingaccount order by id desc limit 1";
			}
			ResultSet rs = st.executeQuery(qq);
			int accLen=accountNoLengthFromMasterTable("Saving",branchId);
			//System.out.println(accLen);
			if (rs.next()) 
			{
				String no=rs.getString("accountNo");
				account=String.valueOf(Integer.parseInt(no.substring(no.length()-accLen,no.length()))+ 1);
			}
			String initial=accountNoInitialFromMasterTable(branchId,"Saving");
			//System.out.println(initial);
			account=initial+commonNo(account,accLen);
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return account;
	}
	
	// this method for add dynamic no. of Zeros in DD/RD/FD No as per length.  
	public String commonNo(String account, int accLen)
	{
		String acc="";
		int len=account.length();
		
		if(len>0)
		{
			while(acc.length()!=accLen-len)
			{
				acc+="0";
			}
			acc=acc+account;
		}
		else
		{
			if(accLen==4)
			{
				acc="0001";
			}
			else if(accLen==5)
			{
				acc="00001";
			}
			else if(accLen==6)
			{
				acc="000001";
			}
			else if(accLen==7)
			{
				acc="0000001";
			}
			else if(accLen==8)
			{
				acc="00000001";
			}
			else if(accLen==9)
			{
				acc="000000001";
			}
			else if(accLen==10)
			{
				acc="0000000001";
			}
		}
		return acc;
	}

	//// to find the next new Receipt no as per series
	public int receiptNo()
	{
		int i=1;
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq = "select receipt_no from payment_receipt  order by id desc limit 1";
			ResultSet rs = st.executeQuery(qq);
			if (rs.next()) 
			{
				i= rs.getInt("receipt_no")+1;
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}

	// Insert Deposit detail in customer_info
	public int registerUser(int branchId,String office_application_no,Date office_date,double application_rupees,String user_no,String scheme_type,
	String plan_no, int terms,double applicant_fees,double installment_amount,double interest,double maturity_value,Date maturity_date,
	String shareHolderNo,int frequency,String dsaCode,double dsaCommission) 
	{
		
		int j = 0;
		HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		String userId=(String) ss1.getAttribute("username");
		
		Timestamp ofcdt = new Timestamp(office_date.getTime());
		Timestamp mDate = new Timestamp(maturity_date.getTime());
		mDate.setHours(0);mDate.setMinutes(0);mDate.setSeconds(0);mDate.setNanos(0);
		try (Connection conn = DataBaseConnection.JAVAConnection();) 
		{

			String query ="insert into customer_info(office_application_no,office_date,application_rupees,user_no,scheme_type,plan_no,"
			+"terms, applicant_fees,installment_amount,interest,maturity_value,maturity_date,shareHolderNo,frequency,user_id,dsa_code,dsa_commission,branch_id)"
			+ "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			PreparedStatement st1 = conn.prepareStatement(query);
			st1.setString(1, office_application_no);
			st1.setTimestamp(2, ofcdt);
			st1.setDouble(3, application_rupees);
			st1.setString(4, user_no);
			st1.setString(5, scheme_type);
			st1.setString(6, plan_no);
			st1.setInt(7, terms);
			st1.setDouble(8, applicant_fees);
			st1.setDouble(9, installment_amount);
			st1.setDouble(10, interest);
			st1.setDouble(11, maturity_value);
			st1.setTimestamp(12, mDate);
			st1.setString(13, shareHolderNo);
			st1.setInt(14,frequency);
			st1.setString(15,userId);
			st1.setString(16,dsaCode);
			st1.setDouble(17, dsaCommission);
			st1.setInt(18, branchId);
			
			int i = st1.executeUpdate();
			if (i >= 1)
			{
				dataInsertInQueryTable(String.valueOf(st1), conn);
				j++;
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
			fileCreation(e.getMessage());
		}
		return j;
	}
    
	// View DD/RD/FD Detail of active     
	public ArrayList<UserInfo> showUser(int branchId,String type) 
	{
		String qq="";
		ArrayList<UserInfo> list = new ArrayList<UserInfo>();
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			int i=0;
			Statement st = con.createStatement();
			if(type.equals("all"))
			{
				qq = "select * from customer_info where account_status='active' ";
			}
			else
			{
				qq = "select * from customer_info where account_status='active' and scheme_type='"+type+"'";
			}
			ResultSet rs = st.executeQuery(selectQueWithBranch(qq,branchId));
			while (rs.next())
			{
				i=i+1;
				String hno=rs.getString("shareHolderNo");
				UserInfo uu = new UserInfo();
				uu=userInfoByShareHolderNo(hno,con);
				uu.setSno(i);
         		uu.setId(rs.getString("id"));
         		uu.setShareHolderNo(rs.getString("shareHolderNo"));
         		uu.setOffice_application_no(rs.getString("office_application_no"));
    			uu.setOffice_date(rs.getDate("office_date"));
    			uu.setStrOffcDate(sf.format(rs.getDate("office_date")));
				uu.setUser_no(rs.getString("user_no"));
				uu.setScheme_type(rs.getString("scheme_type"));
				uu.setPlan_no(rs.getString("plan_no"));
				uu.setTerms(rs.getInt("terms"));
				uu.setDsaCode(rs.getString("dsa_code"));
				uu.setDsaCommission(rs.getDouble("dsa_commission"));
				uu.setFrequency(rs.getInt("frequency"));
				uu.setApplicant_fees(rs.getDouble("applicant_fees"));
				uu.setInstallment_amount(rs.getDouble("installment_amount"));
				uu.setInterest(rs.getDouble("interest"));
				uu.setMaturity_value(rs.getDouble("maturity_value"));
				uu.setMaturity_date(rs.getDate("maturity_date"));
				uu.setStrMatDate(sf.format(rs.getDate("maturity_date")));
				list.add(uu);
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	// to find share holder name by shareholder no
	public String applicantNameByShareHolderNo(String shno, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select first_applicantName from shareholder_info where shareholderno='"+shno+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("first_applicantName");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}
	
	// to find share holder name by shareholder no
	public String applicantPhotoByShareHolderNo(String shno, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select applicant_photo from shareholder_info where shareholderno='"+shno+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				filePathDetail(conn);  //for set online view path if exist
				if(onlineFileViewPath==null || onlineFileViewPath.trim().equals(""))
				{
					return rr.getString("applicant_photo");
				}
				else
				{
					return onlineFileViewPath+rr.getString("applicant_photo");
				}
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}

	
	// to find share holder name by Aadhar Card no
		public String shareHolderDetailByAadharCardNo(int branchId,String columnName, String aadharNo, Connection conn) 
		{
			Statement st=null;
			ResultSet rr=null;
			try
			{
				st=conn.createStatement();
				String qq="select "+columnName+" from shareholder_info where unique_id='"+aadharNo+"' ";
				rr=st.executeQuery(selectQueWithBranch(qq,branchId));
				if(rr.next())
				{
					return rr.getString(columnName);
				}
			}
			catch (Exception e)
			{
				 e.printStackTrace();fileCreation(e.getMessage());
			}
			finally
			{
				try {
					if(st!=null)
					{
						st.close();
					}
					if(rr!=null)
					{
						rr.close();
					}
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
			return "";
		}
		
	// show RD User Detail
	public ArrayList<UserInfo> showRDUser(int branchId) 
	{
		ArrayList<UserInfo> list = new ArrayList<UserInfo>();
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			int i=0;
			Statement st = con.createStatement();
			String qq = "select * from customer_info where scheme_type='RD' and account_status='active'";
			ResultSet rs = st.executeQuery(selectQueWithBranch(qq,branchId));
			while (rs.next())
			{
				i=i+1;
				String hno=rs.getString("shareHolderNo");
				UserInfo uu = new UserInfo();
				uu=userInfoByShareHolderNo(hno, con);
				uu.setSno(i);
         		uu.setId(rs.getString("id"));	
         		uu.setOffice_application_no(rs.getString("office_application_no"));
    			uu.setOffice_date(rs.getDate("office_date"));
    			uu.setStrOffcDate(sf.format(rs.getDate("office_date")));
				uu.setUser_no(rs.getString("user_no"));
				uu.setScheme_type(rs.getString("scheme_type"));
				uu.setPlan_no(rs.getString("plan_no"));
				uu.setTerms(rs.getInt("terms"));
				uu.setFrequency(rs.getInt("frequency"));
				uu.setApplicant_fees(rs.getDouble("applicant_fees"));
				uu.setInstallment_amount(rs.getDouble("installment_amount"));
				uu.setInterest(rs.getDouble("interest"));
				uu.setMaturity_value(rs.getDouble("maturity_value"));
				uu.setMaturity_date(rs.getDate("maturity_date"));
				uu.setStrMatDate(sf.format(rs.getDate("maturity_date")));
				list.add(uu);
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public ArrayList<SelectItem> fetchAllRdForNach() {

	    ArrayList<SelectItem> list = new ArrayList<>();

	    String sql = "SELECT user_no " +
	                 "FROM customer_info " +
	                 "WHERE scheme_type = ? " +
	                 "AND account_status = ? "; 

	    try (Connection con = DataBaseConnection.JAVAConnection();
	         PreparedStatement ps = con.prepareStatement(sql)) {

	        ps.setString(1, "RD");
	        ps.setString(2, "active");
	       

	        try (ResultSet rs = ps.executeQuery()) {
	            while (rs.next()) {
	                String userNo = rs.getString("user_no");
	                list.add(new SelectItem(userNo, userNo));
	            }
	        }

	    } catch (Exception e) {
	        e.printStackTrace();
	        fileCreation(e.getMessage());
	    }

	    return list;
	}

	
	public ArrayList<SelectItem> fetchRdForNachByMemberId(String shareHolderNo) {

	    ArrayList<SelectItem> list = new ArrayList<>();

	    String sql = "SELECT user_no " +
	                 "FROM customer_info " +
	                 "WHERE scheme_type = ? " +
	                 "AND account_status = ? " +
	                 "AND shareHolderNo = ?";

	    try (Connection con = DataBaseConnection.JAVAConnection();
	         PreparedStatement ps = con.prepareStatement(sql)) {

	        ps.setString(1, "RD");
	        ps.setString(2, "active");
	        ps.setString(3, shareHolderNo);

	        try (ResultSet rs = ps.executeQuery()) {
	            while (rs.next()) {
	                String userNo = rs.getString("user_no");
	                list.add(new SelectItem(userNo, userNo));
	            }
	        }

	    } catch (Exception e) {
	        e.printStackTrace();
	        fileCreation(e.getMessage());
	    }

	    return list;
	}


	
	// show FD User Detail
	public ArrayList<UserInfo> showFDUser(int branchId) 
	{
		ArrayList<UserInfo> list = new ArrayList<UserInfo>();
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			int i=0;
			Statement st = con.createStatement();
			String qq = "select * from customer_info where scheme_type='FD' and account_status='active'";
			ResultSet rs = st.executeQuery(selectQueWithBranch(qq,branchId));
			while (rs.next())
			{
				i=i+1;
				String hno=rs.getString("shareHolderNo");
				UserInfo uu = new UserInfo();
				uu=userInfoByShareHolderNo(hno,con);
				uu.setSno(i);
         		uu.setId(rs.getString("id"));	
         		uu.setOffice_application_no(rs.getString("office_application_no"));
    			uu.setOffice_date(rs.getDate("office_date"));
    			uu.setStrOffcDate(sf.format(rs.getDate("office_date")));
				uu.setUser_no(rs.getString("user_no"));
				uu.setScheme_type(rs.getString("scheme_type"));
				uu.setPlan_no(rs.getString("plan_no"));
				uu.setTerms(rs.getInt("terms"));
				uu.setFrequency(rs.getInt("frequency"));
				uu.setApplicant_fees(rs.getDouble("applicant_fees"));
				uu.setInstallment_amount(rs.getDouble("installment_amount"));
				uu.setInterest(rs.getDouble("interest"));
				uu.setMaturity_value(rs.getDouble("maturity_value"));
				uu.setMaturity_date(rs.getDate("maturity_date"));
				uu.setStrMatDate(sf.format(rs.getDate("maturity_date")));
				list.add(uu);
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	// show All FD/RD User List between two dates
	public ArrayList<UserInfo> showAllFDUser(int branchId,Date startDate, Date endDate) 
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		ArrayList<UserInfo> list = new ArrayList<UserInfo>();
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			int i=0;
			Statement st = con.createStatement();
			String qq = "select * from customer_info where scheme_type='FD' and ((office_date>='"+sDate+"' and office_date<'"+eDate+"') or (maturity_date>='"+sDate+"' and maturity_date<'"+eDate+"')) ";
			//// System.out.println(qq);
			ResultSet rs = st.executeQuery(selectQueWithBranch(qq,branchId));
			while (rs.next())
			{
				i=i+1;
				String hno=rs.getString("shareHolderNo");
				UserInfo uu = new UserInfo();
				uu=userInfoByShareHolderNo(hno, con);
				uu.setSno(i);
         		uu.setId(rs.getString("id"));	
         		uu.setOffice_application_no(rs.getString("office_application_no"));
    			uu.setOffice_date(rs.getDate("office_date"));
    			uu.setStrOffcDate(sf.format(rs.getDate("office_date")));
				uu.setUser_no(rs.getString("user_no"));
				uu.setScheme_type(rs.getString("scheme_type"));
				uu.setPlan_no(rs.getString("plan_no"));
				uu.setTerms(rs.getInt("terms"));
				uu.setFrequency(rs.getInt("frequency"));
				uu.setApplicant_fees(rs.getDouble("applicant_fees"));
				uu.setInstallment_amount(rs.getDouble("installment_amount"));
				uu.setInterest(rs.getDouble("interest"));
				uu.setMaturity_value(rs.getDouble("maturity_value"));
				uu.setMaturity_date(rs.getDate("maturity_date"));
				uu.setStrMatDate(sf.format(rs.getDate("maturity_date")));
				list.add(uu);
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	// inactive deposit no using id 
	public int removeUser(int branchId,String id)
	{
		int i = 0;
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq = "update customer_info set account_status='inactive' where id='"+ id + "'";
			i= st.executeUpdate(qq);
			if(i>0)
			{
				dataInsertInQueryTable(qq, con);
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}

	// update maturity detail on deposit closer
	public int updateMaturity(String userNo, double maturity, double interst,Date newMaturityDate) 
	{
		int i = 0;
		Timestamp ts = new Timestamp(newMaturityDate.getTime());
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq = "update customer_info set account_status='close',maturity_value='"+ maturity+"',interest='"+ interst+"',"
					+ "maturity_date='"+ ts + "' where user_no='" + userNo + "'";
			int x = st.executeUpdate(qq);
			if (x >= 1) 
			{
				dataInsertInQueryTable(qq, con);
				i++;
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}

	// update Policy Status 
	public int updatePolicyStatus(String userNo) 
	{
		int i = 0;
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq = "update customer_info set account_status='active' where user_no='" + userNo + "'";
			int x = st.executeUpdate(qq);
			if (x >= 1) 
			{
				dataInsertInQueryTable(qq, con);
				i++;
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}
	
	// update deposit detail via table id  
	public int updateUserInfo(String id,String scheme_type, String plan_no, int terms,double applicant_fees,double installment_amount,
			double interest, double maturity_value, Date maturity_date, int frequency,String dsaCode,Double dsaCommission, String office_application_no, Date office_date)
	{
		int i = 0;
		Timestamp t=new Timestamp(maturity_date.getTime());
		Timestamp offdt=new Timestamp(office_date.getTime());
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq = "update customer_info set scheme_type='"+scheme_type+"',plan_no='"+plan_no+"',terms='"+terms+"',"
			+ "applicant_fees='"+applicant_fees+"',installment_amount='"+installment_amount+"',interest='"+interest+"',maturity_value"
			+ "='"+maturity_value+"', maturity_date='"+t+"', frequency='"+frequency+"',dsa_code='"+dsaCode+"',dsa_commission='"+dsaCommission+"',"
					+ "office_application_no='"+office_application_no+"', office_date='"+offdt+"' where id='"+id+"'";
			//System.out.println(qq);
			int x = st.executeUpdate(qq);
			if (x >= 1) 
			{
				dataInsertInQueryTable(qq, con);
				i++;
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}

	// Very Important method because it calculate DD/RD/FD interest Calculation as per basis of client  
	public double findInterest(int terms, double installment_amount,double interest, String scheme_type,int frequency) 
	{
		double maturity_value = 0, mnthly_intrst = 0;
		double i = 0;
		double ins = installment_amount;
		mnthly_intrst = interest/frequency;
		int x=0;
		
		if (scheme_type.equals("RD") || scheme_type.equals("DD")) 
		{
			for (i = 1; i <= terms; i++) 
			{
				installment_amount = installment_amount+ (installment_amount* (mnthly_intrst / 100));
				if (i != terms) 
				{
					installment_amount = installment_amount + ins;
				}
			}
		} 
		else 
		{
			int j=0;
			for (i = 1; i <= terms; i++) 
			{
				String intrType=depositInterestTypeFromDepositSettingTable("FD");   // method for check Compound FD Interest type from  depositSettingTable
				if(intrType.equalsIgnoreCase("simple"))
				{
					//Simple Interest Calculation
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
				}
				else if(intrType.equalsIgnoreCase("Compound Yearly"))
				{
					//Compound Yearly
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
					j++;
					
					if(j==12)
					{
						ins=installment_amount;
						j=0;
					}	
				}
				
				else if(intrType.equalsIgnoreCase("Compound Half Yearly"))
				{
					//Compound Half Yearly
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
					j++;
					
					if(j==6)
					{
						ins=installment_amount;
						j=0;
					}	
				}
				
				else if(intrType.equalsIgnoreCase("Compound Quarterly"))  // Compund Interst Half  Yearly
				{
					//Compound Quarterly
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
					j++;
					
					if(j==3)
					{
						ins=installment_amount;
						j=0;
					}	
				}
				
				else if(intrType.equalsIgnoreCase("Compound Monthly"))
				{
					//Compound Monthly
					installment_amount = installment_amount+ (installment_amount* (mnthly_intrst / 100));
				}
				
			}
		}
		maturity_value = (installment_amount);
		return maturity_value;
	}

	// this method calculate the maturity value if deposit in break between duration
	public double findInterestForBreak(int terms, double installment_amount,double interest, String scheme_type, int month, int frequency) 
	{
		double maturity_value = 0, mnthly_intrst = 0,i = 0,ins = installment_amount;
		mnthly_intrst = interest / frequency;
		if (scheme_type.equals("RD") || scheme_type.equals("DD"))
		{
			for (i = 1;i <= month; i++) 
			{
				installment_amount = installment_amount+ (installment_amount* (mnthly_intrst / 100));
				//// System.out.println(i+"="+installment_amount);
				if (i != month)
				{
					installment_amount = installment_amount + ins;
				}
			}
		} 
		else 
		{
			int j=0;
			for (i = 1; i <= month; i++)
			{
				String intrType=depositInterestTypeFromDepositSettingTable("FD"); // method for check  FD Compound Interest type from  depositSettingTable
				if(intrType.equalsIgnoreCase("simple"))
				{
					//Simple Interest Calculation: Means interest calculate for complete duration than after add in Principal 
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
				}
				else if(intrType.equalsIgnoreCase("Compound Yearly"))
				{
					//Compound Yearly : Means interest add in Principal after every year
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
					j++;
					
					if(j==12)
					{
						ins=installment_amount;
						j=0;
					}	
				}
				
				else if(intrType.equalsIgnoreCase("Compound Half Yearly"))
				{
					//Compound Half Yearly: Means interest add in Principal after every 6 month
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
					j++;
					
					if(j==6)
					{
						ins=installment_amount;
						j=0;
					}	
				}
				
				else if(intrType.equalsIgnoreCase("Compound Quarterly"))  // Compund Interst Half  Yearly
				{
					//Compound Quarterly
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
					j++;
					
					if(j==3)
					{
						ins=installment_amount;
						j=0;
					}	
				}
				
				
				else if(intrType.equalsIgnoreCase("Compound Monthly"))
				{
					//Compound Monthly : Means interest add in Principal after every month
					installment_amount = installment_amount+ (installment_amount* (mnthly_intrst / 100));
				}
			}
		}
		maturity_value = Double.parseDouble(df.format(installment_amount));
		return maturity_value;
	}
		

		
	/*// Very Important method because it calculate DD/RD/FD interest Calculation as per basis of client  
	public double findInterest(int terms, double installment_amount,double interest, String scheme_type,int frequency) 
	{
		double maturity_value = 0, mnthly_intrst = 0;
		double i = 0;
		double ins = installment_amount;
		double emiAmt=installment_amount;
		mnthly_intrst = interest/frequency;
		
		if(scheme_type.equals("DD"))
		{
			int j=0;
			for (i = 1; i <= terms; i++) 
			{
				String intrType=depositInterestTypeFromDepositSettingTable("DD");   // method for check Compound FD Interest type from  depositSettingTable
				System.out.println(scheme_type+"=="+intrType);
				if (i != terms) 
				{
					if(intrType.equalsIgnoreCase("simple"))
					{
						installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
						installment_amount+=emiAmt;
					}
					else if(intrType.equalsIgnoreCase("Compound Quarterly"))
					{
						installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
						installment_amount+=emiAmt;
						j++;
						
						if(j==90)
						{
							ins=installment_amount;
							j=0;
						}	
					}
				}
			}	
		}
		else if (scheme_type.equals("RD")) 
		{
			int j=0;
			for (i = 1; i <= terms; i++) 
			{
				String intrType=depositInterestTypeFromDepositSettingTable("RD");   // method for check Compound FD Interest type from  depositSettingTable
				if (i != terms) 
				{
					if(intrType.equalsIgnoreCase("simple") || intrType.equalsIgnoreCase("Compound Monthly"))
					{
						installment_amount = installment_amount+ (installment_amount* (mnthly_intrst / 100));
						installment_amount+=emiAmt;
					}
					
					else if(intrType.equalsIgnoreCase("Compound Yearly"))
					{
						installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
						installment_amount+=emiAmt;
						j++;
						if(j==12)
						{
							ins=installment_amount;
							j=0;
						}	
					}
					//Compound Half Yearly: Means interest add in Principal after every 6 month
					else if(intrType.equalsIgnoreCase("Compound Half Yearly"))
					{
						installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
						installment_amount+=emiAmt;
						j++;
						if(j==6)
						{
							ins=installment_amount;
							j=0;
						}	
					}
					
					else if(intrType.equalsIgnoreCase("Compound Quarterly"))
					{
						installment_amount = installment_amount+ (installment_amount* (mnthly_intrst / 100));
						installment_amount+=emiAmt;
						j++;
						if(j==3)
						{
							ins=installment_amount;
							j=0;
						}	
					}
					
					
				}
			}
		} 
		else 
		{
			int j=0;
			for (i = 1; i <= terms; i++) 
			{
				String intrType=depositInterestTypeFromDepositSettingTable("FD");   // method for check Compound FD Interest type from  depositSettingTable
				System.out.println(scheme_type+"=="+intrType);
				if(intrType.equalsIgnoreCase("simple"))
				{
					//Simple Interest Calculation
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
				}
				else if(intrType.equalsIgnoreCase("Compound Yearly"))
				{
					//Compound Yearly
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
					j++;
					
					if(j==12)
					{
						ins=installment_amount;
						j=0;
					}	
				}
				
				else if(intrType.equalsIgnoreCase("Compound Half Yearly"))
				{
					//Compound Half Yearly
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
					j++;
					
					if(j==6)
					{
						ins=installment_amount;
						j=0;
					}	
				}
				
				else if(intrType.equalsIgnoreCase("Compound Quarterly"))  // Compund Interst Half  Yearly
				{
					//Compound Quarterly
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
					j++;
					
					if(j==3)
					{
						ins=installment_amount;
						j=0;
					}	
				}
				
				else if(intrType.equalsIgnoreCase("Compound Monthly"))
				{
					//Compound Monthly
				//	// System.out.println(mnthly_intrst);
					installment_amount = installment_amount+ (installment_amount* (mnthly_intrst / 100));
				//	// System.out.println(installment_amount);
				}
				
			}
		}
		maturity_value = (installment_amount);
		return maturity_value;
	}

	// this method calculate the maturity value if deposit in break between duration
	public double findInterestForBreak(int terms, double installment_amount,double interest, String scheme_type, int month, int frequency) 
	{
		double maturity_value = 0, mnthly_intrst = 0,i = 0,ins = installment_amount;
		mnthly_intrst = interest / frequency;
		if (scheme_type.equals("RD") || scheme_type.equals("DD"))
		{
			for (i = 1;i <= month; i++) 
			{
				installment_amount = installment_amount+ (installment_amount* (mnthly_intrst / 100));
				//// System.out.println(i+"="+installment_amount);
				if (i != month)
				{
					installment_amount = installment_amount + ins;
				}
			}
		}
		if(scheme_type.equals("DD"))
		{
			int j=0;
			for (i = 1; i <=month ; i++) 
			{
				String intrType=depositInterestTypeFromDepositSettingTable("DD");   // method for check Compound FD Interest type from  depositSettingTable
				
				installment_amount = installment_amount+ (installment_amount* (mnthly_intrst / 100));
				if (i !=month ) 
				{
					if(intrType.equalsIgnoreCase("simple"))
					{
						installment_amount = installment_amount + ins;
					}
					else if(intrType.equalsIgnoreCase("Compound Quarterly"))
					{
						installment_amount = installment_amount + ins;
						j++;
						
						if(j==90)
						{
							ins=installment_amount;
							j=0;
						}	
					}
				}
			}	
		}
		else if (scheme_type.equals("RD")) 
		{
			int j=0;
			for (i = 1; i <= month; i++) 
			{
				String intrType=depositInterestTypeFromDepositSettingTable("RD");   // method for check Compound FD Interest type from  depositSettingTable
				
				installment_amount = installment_amount+ (installment_amount* (mnthly_intrst / 100));
				if (i !=month ) 
				{
					if(intrType.equalsIgnoreCase("simple") || intrType.equalsIgnoreCase("Compound Monthly"))
					{
						installment_amount = installment_amount + ins;
					}
					
					else if(intrType.equalsIgnoreCase("Compound Yearly"))
					{
						installment_amount = installment_amount + ins;
						if(j==12)
						{
							ins=installment_amount;
							j=0;
						}	
					}
					//Compound Half Yearly: Means interest add in Principal after every 6 month
					else if(intrType.equalsIgnoreCase("Compound Half Yearly"))
					{
						installment_amount = installment_amount + ins;
						if(j==6)
						{
							ins=installment_amount;
							j=0;
						}	
					}
					
					else if(intrType.equalsIgnoreCase("Compound Quarterly"))
					{
						installment_amount = installment_amount + ins;
						if(j==3)
						{
							ins=installment_amount;
							j=0;
						}	
					}
				}
			}
		} 
		else 
		{
			int j=0;
			for (i = 1; i <= month; i++)
			{
				String intrType=depositInterestTypeFromDepositSettingTable("FD"); // method for check  FD Compound Interest type from  depositSettingTable
				if(intrType.equalsIgnoreCase("simple"))
				{
					//Simple Interest Calculation: Means interest calculate for complete duration than after add in Principal 
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
				}
				else if(intrType.equalsIgnoreCase("Compound Yearly"))
				{
					//Compound Yearly : Means interest add in Principal after every year
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
					j++;
					
					if(j==12)
					{
						ins=installment_amount;
						j=0;
					}	
				}
				
				else if(intrType.equalsIgnoreCase("Compound Half Yearly"))
				{
					//Compound Half Yearly: Means interest add in Principal after every 6 month
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
					j++;
					
					if(j==6)
					{
						ins=installment_amount;
						j=0;
					}	
				}
				
				else if(intrType.equalsIgnoreCase("Compound Quarterly"))  // Compund Interst Half  Yearly
				{
					//Compound Quarterly
					installment_amount = installment_amount+ (ins* (mnthly_intrst / 100));
					j++;
					
					if(j==3)
					{
						ins=installment_amount;
						j=0;
					}	
				}
				
				
				else if(intrType.equalsIgnoreCase("Compound Monthly"))
				{
					//Compound Monthly : Means interest add in Principal after every month
					installment_amount = installment_amount+ (installment_amount* (mnthly_intrst / 100));
				}
			}
		}
		maturity_value = Double.parseDouble(df.format(installment_amount));
		return maturity_value;
	}*/
	

	// to set the deposit interest calculation as pr client, default is simple calculation and other is recurring means calculate interest on every EMI as per his time duration
	public String depositInterestTypeFromDepositSettingTable(String schemeType) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from deposit_setting where deposit_type='"+schemeType+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("interest_type");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "simple";
	}

	// find the maturity date of the Deposit dynamic calculate with using deposit reg date, no. of terms and frequency like monthly, daily, weekly etc...
	public Date findMaturityDate(Date office_date, int terms, int frequency) 
	{
        Date date = new Date();
        int d=office_date.getDate();
        int m=office_date.getMonth();
        int y=office_date.getYear();
        int x=0,z=0;
        if(frequency==12)
        {
        	x=terms;
        }
        else if(frequency==4) // quarterly 
        {
        	x=terms*3;
        }
        else if(frequency==2) // Half Yearly
        {
        	x=terms*6;
        }
        else if(frequency==1) // yearly
        {
        	x=terms*12;
        }
        else if(frequency==365) //daily 
        {
        	z=terms;
        }
        else if(frequency==36) // 10 days
        { 
        	z=terms*10;
        }
        else if(frequency==24) // 15 days
        {
        	z=terms*15;
        }
        else if(frequency==52)  // weekly
        {
        	z=terms*7;
        }
        else if(frequency==26)  // 14 days means 2 week
        {
        	z=terms*14;
        }
        else if(frequency==13) // 28 Days means 4 week
        {
        	z=terms*28;
        }
        
        if(frequency==12 || frequency==4 || frequency==2 || frequency==1)   // frequency 12 indicate monthly, frequency 4 indicate quarterly, frequency 2 indicate half yearly, frequency 1 indicate yearly,
        {
        	date.setDate(d);
            date.setMonth(m);
            date.setYear(y);
            date.setMonth(date.getMonth() + (x));
        }
        else
        {
        	date.setDate(d);
            date.setMonth(m);
            date.setYear(y);
            date.setDate(date.getDate() + (z));
        }
        
        return date;
	}

	// to get the deposit detail via deposit no which are active and contain all information about selected deposit.
    
	public UserInfo userInfoDuringTransaction(String user_no) 
	{
		
		UserInfo uu = null;
		try (Connection con = DataBaseConnection.JAVAConnection();)
		{
			Statement st = con.createStatement();
			String qq = "select * from customer_info where user_no='" + user_no+ "' and account_status='active'";
			//System.out.println(qq);
			ResultSet rs = st.executeQuery(qq);
			if (rs.next()) 
			{   
			
				String hno=rs.getString("shareHolderNo");
				uu = new UserInfo();
				uu=userInfoByShareHolderNo(hno,con);
				uu.setShareHolderNo(hno);
         		uu.setId(rs.getString("id"));			
         		uu.setOffice_application_no(rs.getString("office_application_no"));
    			uu.setOffice_date(rs.getDate("office_date"));
    			uu.setStrOffcDate(sf.format(rs.getDate("office_date")));
				uu.setUser_no(rs.getString("user_no"));
				uu.setScheme_type(rs.getString("scheme_type"));
				uu.setPlan_no(rs.getString("plan_no"));
				uu.setTerms(rs.getInt("terms"));
				uu.setApplicant_fees(rs.getDouble("applicant_fees"));
				uu.setInstallment_amount(rs.getDouble("installment_amount"));
				uu.setFrequency(rs.getInt("frequency"));
				uu.setFrequencyLabel(frequencyLabel(String.valueOf(uu.getFrequency())));
				uu.setInterest(rs.getDouble("interest"));
				uu.setMaturity_value(rs.getDouble("maturity_value"));
				uu.setMaturity_date(rs.getDate("maturity_date"));
				uu.setStrMatDate(sf.format(rs.getDate("maturity_date")));
				uu.setDsaCode(rs.getString("dsa_code"));
				uu.getContactNo();
				}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return uu;
	}

	// Insert the deposit emi Payment Receipt Detail in payment_receipt table
	public int paymentReceipt(int branchId,String user_no, double amount, Date currentDate,String paymentMode, String chequeNo, Date chequeDate,
	String bankName, double penalty, String receipt_no, String submittedBankName, String schemeType, String savingAccountNo, String dsaCode, double creditAmount) 
	{
		int j = 0;
		
		String userId=userId();
		
		Timestamp crdt = new Timestamp(currentDate.getTime());
		Timestamp chdate = null;
		if (chequeDate != null) 
		{
			chdate = new Timestamp(chequeDate.getTime());
		}
		
		String status="pending",chequeStatus="";
		if(paymentMode.equalsIgnoreCase("Cash"))
		{   status="approved";
			chequeStatus="cleared";
		}else if(paymentMode.equalsIgnoreCase("online"))
		{
			status="approved";
			chequeStatus="cleared";
		}
		else if(paymentMode.equalsIgnoreCase("transfer_saving") || paymentMode.equalsIgnoreCase("transfer"))  // if payment of deposit emi transfer in saving account
		{
			status="approved";
			chequeStatus="cleared";
		}
		else
		{
			chequeStatus="uncleared";
		}
		
			
		try (Connection conn = DataBaseConnection.JAVAConnection();)
		{
			String query = "insert into payment_receipt(user_no, date, payment_mode, amount, cheque_no, cheque_date, bank_name, penalty,receipt_no,receipt_status,"
					+ "transfer_to_bank,chequeStatus,user_id, scheme_type, saving_account_no, dsa_code, credit_amount,branch_id) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
	
			PreparedStatement st1 = conn.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
			st1.setString(1, user_no);
			st1.setTimestamp(2, crdt);
			st1.setString(3, paymentMode);
			st1.setDouble(4, amount);
			st1.setString(5, chequeNo);
			st1.setTimestamp(6, chdate);
			st1.setString(7, bankName);
			st1.setDouble(8, penalty);
			st1.setString(9, receipt_no);
			st1.setString(10,status);
			st1.setString(11, submittedBankName);
			st1.setString(12, chequeStatus);
			st1.setString(13, userId);
			st1.setString(14, schemeType);
			st1.setString(15, savingAccountNo);
			st1.setString(16, dsaCode);
			st1.setDouble(17, creditAmount);
			st1.setInt(18, branchId);
			
			int rr1=st1.executeUpdate();
			if(rr1>0)
			{
				dataInsertInQueryTable(String.valueOf(st1), conn);
			}
			ResultSet generatedKeys = st1.getGeneratedKeys();
			if (generatedKeys.next()) 
			{
				return generatedKeys.getInt(1);
	        }
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return j;
	}

	
	public Date createDate2(Date date, int inc, int terms, int d2, Date emiDate)
    {
		
		
		// Comment by GWIT team 
	   /* if(d2 > 28 || emiDate.getDate() > 28)
	    {
		    Date dt=new Date();
		    int d=date.getDate();
		    int m=date.getMonth();
		    int y=date.getYear();
		    dt.setMonth(m);
		    dt.setDate(d);
		    if(terms==1)
		    {
		        m=m-1;
		        dt.setMonth(m+1);
		        dt.setYear(y);
		    }
		    else
		    {
		        dt.setMonth(m+1);
		       if(dt.getMonth() ==0 )
		       {
		           y=y+1;
		       }
		       dt.setYear(y);
		    }
		   
		    if(emiDate.getDate()==29)
		    {
		        if(dt.getMonth()==0 || dt.getMonth()==2 || dt.getMonth()==4 || dt.getMonth()==6 || dt.getMonth()==7 || dt.getMonth()==9 || dt.getMonth()==11 )
		        {
		            dt.setDate(29);
		        }
		        else if(dt.getMonth()==1)
		        {
		            if(dt.getYear()%4==0)
		            {
		                dt.setDate(29);
		            }
		            else
		            {
		                dt.setDate(28);
		            }
		           
		        }
		        else {
		            dt.setDate(29);
		        }
		       
		    }
		    else if(emiDate.getDate()==30)
		    {
		        if(dt.getMonth()==0 || dt.getMonth()==2 || dt.getMonth()==4 || dt.getMonth()==6 || dt.getMonth()==7 || dt.getMonth()==9 || dt.getMonth()==11 )
		        {
		            dt.setDate(30);
		        }
		        else if(dt.getMonth()==1)
		        {
		            if(dt.getYear()%4==0)
		            {
		                dt.setDate(29);
		            }
		            else
		            {
		                dt.setDate(28);
		            }
		           
		        }
		        else {
		            dt.setDate(30);
		        }
		    }
		    else
		    {
		
		        if(dt.getMonth()==0 || dt.getMonth()==2 || dt.getMonth()==4 || dt.getMonth()==6 || dt.getMonth()==7 || dt.getMonth()==9 || dt.getMonth()==11 )
		        {
		            dt.setDate(31);
		        }
		        else if(dt.getMonth()==1)
		        {
		            if(dt.getYear()%4==0)
		            {
		                dt.setDate(29);
		            }
		            else
		            {
		                dt.setDate(28);
		            }
		           
		        }
		        else {
		            dt.setDate(30);
		        }
		       
		    }
		    dt.setHours(00);
		    dt.setMinutes(00);
		    dt.setSeconds(00);
		    Calendar calendar = getCalendarForNow();
		    calendar.set(Calendar.DAY_OF_MONTH,
		            calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		    setTimeToEndofDay(calendar);
		    end = calendar.getTime();
		    return dt;
	    }
	    else*/
	    {
	        Date dt=new Date();
	     Date dt1=new Date();
	        int d=date.getDate();
	        int m=date.getMonth();
	        int y=date.getYear();
	        Date mm1=new Date(y,m,01);
	        int d1=mm1.getDate();
	        int m1=mm1.getMonth();
	        int y1=mm1.getYear();
	        String mm=String.valueOf(m);
	        // // System.out.println("tdsbdsjdsjdhsjd :"+d1+"/"+m1+"/"+y1);
	       
	       
	        dt1.setDate(d1);
	        dt1.setMonth(m1);
	        dt1.setYear(y1);
	        dt.setDate(d);
	        dt.setMonth(m);
	        dt.setYear(y);
	        if(terms==1)
	        {
	            dt.setMonth((dt.getMonth()-1)+inc);
	        }
	        else
	        {
	            dt.setMonth(dt.getMonth()+inc);
	           
	        }
	       
	        dt.setHours(00);
	        dt.setMinutes(00);
	        dt.setSeconds(00);
	      /*  Calendar calendar = getCalendarForNow();
	        calendar.set(Calendar.DAY_OF_MONTH,
	                calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
	        setTimeToEndofDay(calendar);
	        end = calendar.getTime();*/
	        return dt;
	    }
   
    }
	
	public Date createDate3(Date date, int inc)
	{
		Date dt=new Date();
		int d=date.getDate();
		int m=date.getMonth();
		int y=date.getYear();
		dt.setDate(d);
		dt.setMonth(m);
		dt.setYear(y);
		dt.setDate(dt.getDate()+inc);
		dt.setHours(00);
		dt.setMinutes(00);
		dt.setSeconds(00);
		return dt;
	}

	// Very Important Method : This Method calculate DD/RD/FD Installment List Dynamically.
	public ArrayList<InstallmentInfo> showInstallment(String user_no, Connection conn) 
	{
		
		Statement st=null;
		ResultSet rs=null;
		ArrayList<InstallmentInfo> list = new ArrayList<InstallmentInfo>();
		try 
		{
			 st = conn.createStatement();
			String qq = "select * from customer_info INNER JOIN shareholder_info on "
					+ " customer_info.shareHolderNo=shareholder_info.shareHolderNo "
					+ " where customer_info.user_no='" + user_no+ "' and customer_info.account_status='active'";
			 rs = st.executeQuery(qq);
			if (rs.next()) 
			{
				int i = 0;
				Date offcdt = rs.getDate("customer_info.office_date");
				int terms = rs.getInt("customer_info.terms");
				int frequency=rs.getInt("customer_info.frequency");
				double instlmnt_amnt = rs.getDouble("customer_info.installment_amount");
				double intrst =rs.getDouble("customer_info.interest");
				double paidAmount = paidAmountByUser(user_no,conn);
				double mnthly_intrst =intrst / frequency;
				double instlmnt = instlmnt_amnt;
				
				int x=0,y=1,z=0;
				if(frequency==4)
			    {
					y=4;
			    	//x=terms/3;
			    }
			    else if(frequency==2)
			    {
			    	y=6;
			    	//x=terms/6;
			    }
			    else if(frequency==1)
			    {
			    	y=12;
			    	//x=terms/12;
			    }
			    else if(frequency==12)
			    {
			    	y=1;
			    	//x=terms;
			    }
			    else if(frequency==365)
		        {
			    	z=1;
		        	//z=terms;
		        }
		        else if(frequency==36)
		        {
		        	z=10;
		        	//z=terms*10;
		        }
		        else if(frequency==24)
		        {
		        	z=15;
		        	//z=terms*15;
		        }else if(frequency==52)
		        {
		        	z=7;
		        }
		        else if(frequency==26)
		        {
		        	z=14;
		        }
		        else if(frequency==13)
		        {
		        	z=28;
		        }
		        
				boolean checkEMIForward=checkGroupLoanEmiFromTable(user_no, conn);
				if (rs.getString("customer_info.scheme_type").equals("RD") || rs.getString("customer_info.scheme_type").equals("DD")) 
				{
					int d=offcdt.getDate();
					for (i = 1; i <= terms; i++) 
					{
						InstallmentInfo ii = new InstallmentInfo();
						ii.setUser_no(user_no);
						
						if(checkEMIForward==false)
						{
							ii.setIns_date(sf.format(offcdt));
							ii.setInstlmntDate(offcdt);
							if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
					        {
								offcdt=createDate2(offcdt,y,terms,d,rs.getDate("customer_info.office_date"));
					        }
							else
							{
								offcdt=createDate3(offcdt,z);
							}
						}
						else
						{
							offcdt=groupLoanEmiDateFromTable(i, user_no, conn);
							ii.setIns_date(sf.format(offcdt));
							ii.setInstlmntDate(offcdt);
						}
						
						if (paidAmount >= instlmnt)
						{
							ii.setPaidAmount(instlmnt);
							ii.setStatus("Paid");
							
						}
						else if (paidAmount < instlmnt && paidAmount > 0) 
						{
							ii.setDueAmount(instlmnt-paidAmount);
							ii.setPaidAmount(paidAmount);
							ii.setStatus("Due");
						}
						else 
						{
							ii.setDueAmount(instlmnt);
							ii.setStatus("Due");
						}
						paidAmount = paidAmount - instlmnt;
						ii.setSno(i);
						ii.setInstallment_amount(instlmnt);
						ii.setInterest(intrst);  ///hello
						ii.setCalc_interest(Double.parseDouble(df.format(instlmnt_amnt* (mnthly_intrst / 100))));
						instlmnt_amnt = instlmnt_amnt+ (Double.parseDouble(df.format(instlmnt_amnt* (mnthly_intrst / 100))));
						ii.setTot_sum(Double.parseDouble(df.format(instlmnt_amnt)));
						ii.setName(rs.getString("shareholder_info.first_applicantName"));
						list.add(ii);
						if (i != terms) 
						{
							instlmnt_amnt = instlmnt_amnt + instlmnt;
						}
					}
				}
				else 
				{
					/*InstallmentInfo ii = new InstallmentInfo();
					ii.setInstallment_amount(instlmnt);
					ii.setPaidAmount(paidAmount);
					ii.setUser_no(user_no);
					ii.setSno(1);
					ii.setInterest(intrst);
					ii.setIns_date(new SimpleDateFormat("dd/MM/yyyy").format(offcdt));
					ii.setInstlmntDate(offcdt);
				
					if(paidAmount==instlmnt)
					{
						ii.setStatus("Paid");
					}
					else
					{
						ii.setStatus("Due");
					}
					ii.setTerms(terms);
					double maturityValue = findInterest(terms, instlmnt,intrst, rs.getString("scheme_type"),frequency);
					ii.setCalc_interest(maturityValue - instlmnt);
					ii.setTot_sum(Double.parseDouble(df.format(maturityValue)));
					list.add(ii);*/
					
					int d=offcdt.getDate();
					for (i = 1; i <= terms; i++) 
					{
						InstallmentInfo ii = new InstallmentInfo();
						
						int j=0;
						ii.setUser_no(user_no);
						ii.setIns_date(sf.format(offcdt));
						ii.setInstlmntDate(offcdt);
						offcdt=createDate2(offcdt,y,terms,d,rs.getDate("customer_info.office_date"));
						if (paidAmount >= instlmnt)
						{
							ii.setPaidAmount(instlmnt);
							ii.setStatus("Paid");
							
						}
						else if (paidAmount < instlmnt && paidAmount > 0) 
						{
							ii.setPaidAmount(paidAmount);
							ii.setStatus("Due");
						}
						else 
						{
							ii.setStatus("Due");
						}
						ii.setSno(i);
						ii.setInstallment_amount(instlmnt);
						ii.setInterest(intrst);  ///hello
						ii.setCalc_interest(Double.parseDouble(df.format(instlmnt* (mnthly_intrst / 100))));
						
						//Check FD Interest Type From Database
						String intrType=depositInterestTypeFromDepositSettingTable("FD");
						if(intrType.equalsIgnoreCase("simple"))
						{
							ii.setTot_sum(Double.parseDouble(df.format(ii.getCalc_interest()+instlmnt)));
						}
						else if(intrType.equalsIgnoreCase("Compound Yearly"))  // Compund Interst Yearly
						{
							ii.setCalc_interest(Double.parseDouble(df.format(instlmnt* (mnthly_intrst / 100))));
							instlmnt_amnt = instlmnt_amnt+ (Double.parseDouble(df.format(instlmnt* (mnthly_intrst / 100))));
							ii.setTot_sum(Double.parseDouble(df.format(ii.getCalc_interest()+instlmnt)));
							j++;
							if(j==12)
							{
								instlmnt=instlmnt_amnt;
								j=0;
							}
						}
						else if(intrType.equalsIgnoreCase("Compound Half Yearly"))  // Compund Interst Half  Yearly
						{
							ii.setCalc_interest(Double.parseDouble(df.format(instlmnt* (mnthly_intrst / 100))));
							instlmnt_amnt = instlmnt_amnt+ (Double.parseDouble(df.format(instlmnt* (mnthly_intrst / 100))));
							ii.setTot_sum(Double.parseDouble(df.format(ii.getCalc_interest()+instlmnt)));
							j++;
							if(j==6)
							{
								instlmnt=instlmnt_amnt;
								j=0;
							}
						}
						else if(intrType.equalsIgnoreCase("Compound Quarterly"))  // Compund Interst Half  Yearly
						{
							ii.setCalc_interest(Double.parseDouble(df.format(instlmnt* (mnthly_intrst / 100))));
							instlmnt_amnt = instlmnt_amnt+ (Double.parseDouble(df.format(instlmnt* (mnthly_intrst / 100))));
							ii.setTot_sum(Double.parseDouble(df.format(ii.getCalc_interest()+instlmnt)));
							j++;
							if(j==3)
							{
								instlmnt=instlmnt_amnt;
								j=0;
							}
						}
						else if(intrType.equalsIgnoreCase("Compound Monthly"))  // Compund Interst Monthly
						{
							ii.setCalc_interest(Double.parseDouble(df.format(instlmnt_amnt* (mnthly_intrst / 100))));
							instlmnt_amnt = instlmnt_amnt+ (Double.parseDouble(df.format(instlmnt_amnt* (mnthly_intrst / 100))));
							ii.setTot_sum(Double.parseDouble(df.format(ii.getCalc_interest()+instlmnt_amnt)));
						}
						
						ii.setName(rs.getString("shareholder_info.first_applicantName"));
						
						list.add(ii);
						
					}					
				}
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	
	
	public ArrayList<InstallmentInfo> showInstallmentForDepositDetail(String user_no,Connection conn) 
	{
		
		Statement st=null;
		ResultSet rs=null;
		ArrayList<InstallmentInfo> list = new ArrayList<InstallmentInfo>();
		try 
		{
			 st = conn.createStatement();
			String qq = "select * from customer_info INNER JOIN shareholder_info on "
					+ " customer_info.shareHolderNo=shareholder_info.shareHolderNo "
					+ " where customer_info.user_no='" + user_no+ "' and customer_info.account_status='inactive'";
			 rs = st.executeQuery(qq);
			if (rs.next()) 
			{
				int i = 0;
				Date offcdt = rs.getDate("customer_info.office_date");
				int terms = rs.getInt("customer_info.terms");
				int frequency=rs.getInt("customer_info.frequency");
				double instlmnt_amnt = rs.getDouble("customer_info.installment_amount");
				double intrst =rs.getDouble("customer_info.interest");
				double paidAmount = paidAmountByUser(user_no,conn);
				double mnthly_intrst =intrst / frequency;
				double instlmnt = instlmnt_amnt;
				
				int x=0,y=1,z=0;
				if(frequency==4)
			    {
					y=4;
			    	//x=terms/3;
			    }
			    else if(frequency==2)
			    {
			    	y=6;
			    	//x=terms/6;
			    }
			    else if(frequency==1)
			    {
			    	y=12;
			    	//x=terms/12;
			    }
			    else if(frequency==12)
			    {
			    	y=1;
			    	//x=terms;
			    }
			    else if(frequency==365)
		        {
			    	z=1;
		        	//z=terms;
		        }
		        else if(frequency==36)
		        {
		        	z=10;
		        	//z=terms*10;
		        }
		        else if(frequency==24)
		        {
		        	z=15;
		        	//z=terms*15;
		        }else if(frequency==52)
		        {
		        	z=7;
		        }
		        else if(frequency==26)
		        {
		        	z=14;
		        }
		        else if(frequency==13)
		        {
		        	z=28;
		        }
		        

				if (rs.getString("customer_info.scheme_type").equals("RD") || rs.getString("customer_info.scheme_type").equals("DD")) 
				{
					int d=offcdt.getDate();
					for (i = 1; i <= terms; i++) 
					{
						InstallmentInfo ii = new InstallmentInfo();
						ii.setUser_no(user_no);
						ii.setIns_date(sf.format(offcdt));
						ii.setInstlmntDate(offcdt);
						if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
				        {
							offcdt=createDate2(offcdt,y,terms,d,rs.getDate("customer_info.office_date"));
				        }
						else
						{
							offcdt=createDate3(offcdt,z);
						}
						
						if (paidAmount >= instlmnt)
						{
							ii.setPaidAmount(instlmnt);
							ii.setStatus("Paid");
							
						}
						else if (paidAmount < instlmnt && paidAmount > 0) 
						{
							ii.setPaidAmount(paidAmount);
							ii.setStatus("Due");
						}
						else 
						{
							ii.setStatus("Due");
						}
						paidAmount = paidAmount - instlmnt;
						ii.setSno(i);
						ii.setInstallment_amount(instlmnt);
						ii.setInterest(intrst);  ///hello
						ii.setCalc_interest(Double.parseDouble(df.format(instlmnt_amnt* (mnthly_intrst / 100))));
						instlmnt_amnt = instlmnt_amnt+ (Double.parseDouble(df.format(instlmnt_amnt* (mnthly_intrst / 100))));
						ii.setTot_sum(Double.parseDouble(df.format(instlmnt_amnt)));
						ii.setName(rs.getString("shareholder_info.first_applicantName"));
						list.add(ii);
						if (i != terms) 
						{
							instlmnt_amnt = instlmnt_amnt + instlmnt;
						}
					}
				}
				else 
				{
					/*InstallmentInfo ii = new InstallmentInfo();
					ii.setInstallment_amount(instlmnt);
					ii.setPaidAmount(paidAmount);
					ii.setUser_no(user_no);
					ii.setSno(1);
					ii.setInterest(intrst);
					ii.setIns_date(new SimpleDateFormat("dd/MM/yyyy").format(offcdt));
					ii.setInstlmntDate(offcdt);
				
					if(paidAmount==instlmnt)
					{
						ii.setStatus("Paid");
					}
					else
					{
						ii.setStatus("Due");
					}
					ii.setTerms(terms);
					double maturityValue = findInterest(terms, instlmnt,intrst, rs.getString("scheme_type"),frequency);
					ii.setCalc_interest(maturityValue - instlmnt);
					ii.setTot_sum(Double.parseDouble(df.format(maturityValue)));
					list.add(ii);*/
					
					int d=offcdt.getDate();
					for (i = 1; i <= terms; i++) 
					{
						InstallmentInfo ii = new InstallmentInfo();
						
						int j=0;
						ii.setUser_no(user_no);
						ii.setIns_date(sf.format(offcdt));
						ii.setInstlmntDate(offcdt);
						offcdt=createDate2(offcdt,y,terms,d,rs.getDate("customer_info.office_date"));
						if (paidAmount >= instlmnt)
						{
							ii.setPaidAmount(instlmnt);
							ii.setStatus("Paid");
							
						}
						else if (paidAmount < instlmnt && paidAmount > 0) 
						{
							ii.setPaidAmount(paidAmount);
							ii.setStatus("Due");
						}
						else 
						{
							ii.setStatus("Due");
						}
						ii.setSno(i);
						ii.setInstallment_amount(instlmnt);
						ii.setInterest(intrst);  ///hello
						ii.setCalc_interest(Double.parseDouble(df.format(instlmnt* (mnthly_intrst / 100))));
						
						//Check FD Interest Type From Database
						String intrType=depositInterestTypeFromDepositSettingTable("FD");
						if(intrType.equalsIgnoreCase("simple"))
						{
							ii.setTot_sum(Double.parseDouble(df.format(ii.getCalc_interest()+instlmnt)));
						}
						else if(intrType.equalsIgnoreCase("Compound Yearly"))
						{
							ii.setCalc_interest(Double.parseDouble(df.format(instlmnt* (mnthly_intrst / 100))));
							instlmnt_amnt = instlmnt_amnt+ (Double.parseDouble(df.format(instlmnt* (mnthly_intrst / 100))));
							ii.setTot_sum(Double.parseDouble(df.format(ii.getCalc_interest()+instlmnt)));
							j++;
							if(j==12)
							{
								instlmnt=instlmnt_amnt;
								j=0;
							}
						}
						else if(intrType.equalsIgnoreCase("Compound Half Yearly"))
						{
							ii.setCalc_interest(Double.parseDouble(df.format(instlmnt* (mnthly_intrst / 100))));
							instlmnt_amnt = instlmnt_amnt+ (Double.parseDouble(df.format(instlmnt* (mnthly_intrst / 100))));
							ii.setTot_sum(Double.parseDouble(df.format(ii.getCalc_interest()+instlmnt)));
							j++;
							if(j==6)
							{
								instlmnt=instlmnt_amnt;
								j=0;
							}
						}
						else if(intrType.equalsIgnoreCase("Compound Monthly"))
						{
							ii.setCalc_interest(Double.parseDouble(df.format(instlmnt_amnt* (mnthly_intrst / 100))));
							instlmnt_amnt = instlmnt_amnt+ (Double.parseDouble(df.format(instlmnt_amnt* (mnthly_intrst / 100))));
							ii.setTot_sum(Double.parseDouble(df.format(ii.getCalc_interest()+instlmnt_amnt)));
						}
						
						ii.setName(rs.getString("shareholder_info.first_applicantName"));
						list.add(ii);
						
					}					
				}
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public ArrayList<InstallmentInfo> trailBalanceShowInstallment(int branchId,String user_no, Date endDate) 
	{
		ArrayList<InstallmentInfo> list = new ArrayList<InstallmentInfo>();
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq = "select * from customer_info INNER JOIN shareholder_info on "
					+ " customer_info.shareHolderNo=shareholder_info.shareHolderNo "
					+ " where customer_info.user_no='" + user_no+ "' and customer_info.account_status='active'";
			ResultSet rs = st.executeQuery(selectQueWithBranch(qq,branchId));
			if (rs.next()) 
			{
				int i = 0;
				Date offcdt = rs.getDate("customer_info.office_date");
				int terms = rs.getInt("customer_info.terms");
				int frequency=rs.getInt("customer_info.frequency");
				double instlmnt_amnt = rs.getDouble("customer_info.installment_amount");
				double intrst = Double.parseDouble(new DecimalFormat("#.######").format(rs.getDouble("customer_info.interest")));
				double paidAmount = paidAmountByUser(user_no,con);
				double mnthly_intrst =Double.parseDouble(new DecimalFormat("#.######").format(intrst / frequency));
				double instlmnt = instlmnt_amnt;
				
				int x=0,y=1,z=0;
				if(frequency==4)
			    {
					y=4;
			    	//x=terms/3;
			    }
			    else if(frequency==2)
			    {
			    	y=6;
			    	//x=terms/6;
			    }
			    else if(frequency==1)
			    {
			    	y=12;
			    	//x=terms/12;
			    }
			    else if(frequency==12)
			    {
			    	y=1;
			    	//x=terms;
			    }
			    else if(frequency==365)
		        {
			    	z=1;
		        	//z=terms;
		        }
		        else if(frequency==36)
		        {
		        	z=10;
		        	//z=terms*10;
		        }
		        else if(frequency==24)
		        {
		        	z=15;
		        	//z=terms*15;
		        }

				if (rs.getString("customer_info.scheme_type").equals("RD")) 
				{
					int d=offcdt.getDate();
					for (i = 1; i <= terms; i++) 
					{
						InstallmentInfo ii = new InstallmentInfo();
						ii.setUser_no(user_no);
						ii.setIns_date(sf.format(offcdt));
						ii.setInstlmntDate(offcdt);
						if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
				        {
							offcdt=createDate2(offcdt,y,terms,d,rs.getDate("customer_info.office_date"));
				        }
						else
						{
							offcdt=createDate3(offcdt,z);
						}
						
						if (paidAmount >= instlmnt)
						{
							ii.setPaidAmount(instlmnt);
							ii.setStatus("Paid");
							
						}
						else if (paidAmount < instlmnt && paidAmount > 0) 
						{
							ii.setPaidAmount(paidAmount);
							ii.setStatus("Due");
						}
						else 
						{
							ii.setStatus("Due");
						}
						paidAmount = paidAmount - instlmnt;
						ii.setSno(i);
						ii.setInstallment_amount(instlmnt);
						ii.setInterest(intrst);  ///hello
						ii.setCalc_interest(Double.parseDouble(new DecimalFormat("#.######").format(instlmnt_amnt* (mnthly_intrst / 100))));
						instlmnt_amnt = instlmnt_amnt+ (Double.parseDouble(new DecimalFormat("#.######").format(instlmnt_amnt* (mnthly_intrst / 100))));
						instlmnt_amnt=Double.parseDouble(new DecimalFormat("#.######").format(instlmnt_amnt));
						ii.setTot_sum(Double.parseDouble(new DecimalFormat("#.######").format(instlmnt_amnt)));
						ii.setName(rs.getString("shareholder_info.first_applicantName"));
						list.add(ii);
						if (i != terms) 
						{
							instlmnt_amnt = instlmnt_amnt + instlmnt;
						}
					}
				}
				else 
				{
					if(user_no.equals("GF-0000000002"))
					{
						double mnthly_intrst1 =Double.parseDouble(new DecimalFormat("#.######").format(intrst / 365));
						
						int days = (int) ((endDate.getTime()-offcdt.getTime()) / (1000 * 60 * 60 * 24));
					//	// // // System.out.println(user_no+" days : "+days+" "+instlmnt_amnt);
						for(int k=0; k<=days; k++)
						{
							instlmnt_amnt = instlmnt_amnt+ (Double.parseDouble(new DecimalFormat("#.######").format(instlmnt_amnt* (mnthly_intrst1 / 100))));
							//// // // System.out.println(k+1+" Day= "+instlmnt_amnt);
						}
					}
/*					InstallmentInfo ii = new InstallmentInfo();
					ii.setInstallment_amount(instlmnt);
					ii.setPaidAmount(paidAmount);
					ii.setSno(1);
					ii.setInterest(intrst);
					if(paidAmount==instlmnt)
					{
						ii.setStatus("Paid");
					}
					else
					{
						ii.setStatus("Due");
					}
					ii.setTerms(terms);
					double maturityValue = findInterest(terms, instlmnt,intrst, rs.getString("scheme_type"),frequency);
					ii.setCalc_interest(maturityValue - instlmnt);
					ii.setTot_sum(Double.parseDouble(new DecimalFormat("#.######").format(maturityValue)));
					list.add(ii);
*/
					/*for (i = 1; i <= terms; i++) 
					{
						InstallmentInfo ii = new InstallmentInfo();
						ii.setUser_no(user_no);
						ii.setIns_date(sf.format(offcdt));
						ii.setInstlmntDate(offcdt);
						offcdt=createDate2(offcdt,y);
						if (paidAmount >= instlmnt)
						{
							ii.setPaidAmount(instlmnt);
							ii.setStatus("Paid");
							
						}
						else if (paidAmount < instlmnt && paidAmount > 0) 
						{
							ii.setPaidAmount(paidAmount);
							ii.setStatus("Due");
						}
						else 
						{
							ii.setStatus("Due");
						}
						//paidAmount = paidAmount - instlmnt;
						ii.setSno(i);
						ii.setInstallment_amount(instlmnt);
						ii.setInterest(intrst);  ///hello
						ii.setCalc_interest(Double.parseDouble(new DecimalFormat("#.######").format(instlmnt_amnt* (mnthly_intrst / 100))));
						instlmnt_amnt = instlmnt_amnt+ (Double.parseDouble(new DecimalFormat("#.######").format(instlmnt_amnt* (mnthly_intrst / 100))));
						instlmnt_amnt=Double.parseDouble(new DecimalFormat("#.######").format(instlmnt_amnt));
						ii.setTot_sum(Double.parseDouble(new DecimalFormat("#.######").format(instlmnt_amnt)));
						ii.setName(rs.getString("shareholder_info.first_applicantName"));
						// // // System.out.println(user_no+" => "+i+" = "+ii.getCalc_interest()+" ==== " +instlmnt_amnt);
						
						list.add(ii);
						if (i != terms) 
						{
							instlmnt_amnt = instlmnt_amnt + instlmnt;
						}
					}*/					
				}
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	public ArrayList<InstallmentInfo> findInstallmentNoForRdFd(String user_no, int id, double installment_amount) 
	{
		int prevPaidAmount=0;
		ArrayList<InstallmentInfo> list = new ArrayList<InstallmentInfo>();
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qs="select sum(amount) from payment_receipt where user_no='"+user_no+"' and receipt_status='approved' and id<'"+id+"'";
			ResultSet rr=st.executeQuery(qs);
			if(rr.next())
			{
				prevPaidAmount=rr.getInt("sum(amount)");
			}
			
			String qq = "select * from customer_info where user_no='" + user_no+ "' and account_status='active'";
			
			ResultSet rs = st.executeQuery(qq);
			if (rs.next()) 
			{
				int i = 0;
				int terms = rs.getInt("terms");
				int frequency=rs.getInt("frequency");
				double instlmnt_amnt = rs.getDouble("installment_amount");
				double paidAmount = prevPaidAmount;
				double paidAmountAfterTransaction=paidAmount+installment_amount;
				double instlmnt = instlmnt_amnt;
				
				int x=0,y=1,z=0;
				if(frequency==4)
			    {
					y=4;
			    	//x=terms/3;
			    }
			    else if(frequency==2)
			    {
			    	y=6;
			    	//x=terms/6;
			    }
			    else if(frequency==1)
			    {
			    	y=12;
			    	//x=terms/12;
			    }
			    else if(frequency==12)
			    {
			    	y=1;
			    	//x=terms;
			    }
			    else if(frequency==365)
		        {
			    	z=1;
		        	//z=terms;
		        }
		        else if(frequency==36)
		        {
		        	z=10;
		        	//z=terms*10;
		        }
		        else if(frequency==24)
		        {
		        	z=15;
		        	//z=terms*15;
		        }
				//int x=0;
				/*if(frequency==4)
			    {
			    	x=terms/3;
			    }
			    else if(frequency==2)
			    {
			    	x=terms/6;
			    }
			    else if(frequency==1)
			    {
			    	x=terms/12;
			    }
			    else if(frequency==12)
			    {
			    	x=terms;
			    }*/

				if (rs.getString("scheme_type").equals("RD")) 
				{
					for (i = 1; i <= terms; i++) 
					{
						InstallmentInfo ii = new InstallmentInfo();
						if (paidAmount >= instlmnt)
						{
							ii.setPaidAmount(instlmnt);
							ii.setStatus("Paid");
							if(ii.getStatus()=="Paid")
							{
								ii.setTemp1(i);
							}
							
						}
						else if (paidAmount < instlmnt && paidAmount > 0) 
						{
							ii.setPaidAmount(paidAmount);
							ii.setStatus("Due");
						}
						else 
						{
							ii.setStatus("Due");
							
						}
						paidAmount = paidAmount - instlmnt;
						list.add(ii);
					}
					
					for(i = 1; i <= terms; i++)
					{
						InstallmentInfo ii = new InstallmentInfo();
						if (paidAmountAfterTransaction >0)
						{
							ii.setPaidAmount(instlmnt);
							ii.setStatus("Paid");
							if(ii.getStatus()=="Paid")
							{
								ii.setTemp2(i);
							}
						}	
						else 
						{
							ii.setStatus("Due");
						}
						paidAmountAfterTransaction = paidAmountAfterTransaction - instlmnt;
						
						list.add(ii);
					}
				} 
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}


	public ArrayList<UserInfo> showUserByMaturityDate(int branchId,Date date, String searchType)
    {
        int i=1;
        String qq ="";
        ArrayList<UserInfo> list = new ArrayList<UserInfo>();
       
        String dt = sdfForDb.format(date.getTime());
        try (Connection con = DataBaseConnection.JAVAConnection();)
        {
            Statement st = con.createStatement();
            if(searchType.equalsIgnoreCase("all"))
            {
            	qq = "select * from customer_info where maturity_date<='"+ dt+"' and paid_status='unpaid' and (account_status='active' or account_status='close') and branch_id='"+branchId+"' order by maturity_date asc ";
            }
            else
            {
            	qq = "select * from customer_info where maturity_date<='"+dt+"' and paid_status='unpaid' and scheme_type='"+searchType+"' and (account_status='active' or account_status='close') and branch_id='"+branchId+"' order by maturity_date asc ";
            }
            ResultSet rs = st.executeQuery(qq);
            while (rs.next())
            {
                UserInfo uu = new UserInfo();
                uu = userInfoByShareHolderNo(rs.getString("shareHolderNo"), con);
                uu.setSno(i++);
                uu.setShareHolderNo(rs.getString("shareHolderNo"));
                uu.setInstallment_amount(rs.getDouble("installment_amount"));
                uu.setTerms(rs.getInt("terms"));
                uu.setMaturity_value(Double.parseDouble(df.format(rs.getDouble("maturity_value"))));
                uu.setMaturity_date(rs.getDate("maturity_date"));
                uu.setScheme_type(rs.getString("scheme_type"));
                uu.setUser_no(rs.getString("user_no"));
                 
                double insAmt=0; 
                if(uu.getScheme_type().equals("RD") || uu.getScheme_type().equals("DD"))
                {
                    insAmt=uu.getTerms()*uu.getInstallment_amount();
                }
                else
                {
                    insAmt=uu.getInstallment_amount();
                }
                uu.setPaidAmount(paidAmountByUser(uu.getUser_no(),con));
               
                if(uu.getPaidAmount()==0)
                {
                    uu.setColorStatus("nil");
                }
                else if(insAmt==uu.getPaidAmount())
                {
                    uu.setColorStatus("paid");
                }
                else
                {
                    uu.setColorStatus("pending");
                }
               
                String a=statusOfOdLoanByUserNo(rs.getString("user_no"));
                       
                if(a.equalsIgnoreCase("active"))
                {
                   
                    uu.setDisBtn2(true);
                    uu.setDisBtn1(true);
                }
                else
                {
               
               
                    if(uu.getColorStatus().equals("paid") || rs.getString("account_status").equals("close"))
                    {
                        //// // // // System.out.println(uu.getUser_no()+"hiiiiiiiii");
                        uu.setDisBtn2(true);
                    }
                    else
                    {
                        uu.setDisBtn2(false);
                    }
                   
                    if(uu.isDisBtn2()==false)
                    {
                        uu.setDisBtn1(true);
                    }
                    else
                    {
                        uu.setDisBtn1(false);
                    }
                }
                uu.setStrMatDate(sf.format(rs.getDate("maturity_date")));
                list.add(uu);
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return list;
    }
	
	public ArrayList<UserInfo> showUserByMaturityBetweenDate(int branchId,Date startDate, Date endDate, String searchType)
    {
        int i=1;
        String qq ="";
        ArrayList<UserInfo> list = new ArrayList<UserInfo>();
       
        String sDate = sdfForDb.format(startDate.getTime());
        String eDate = sdfForDb.format(endDate.getTime());
        try (Connection con = DataBaseConnection.JAVAConnection();)
        {
            Statement st = con.createStatement();
            if(searchType.equalsIgnoreCase("all"))
            {
            	qq = "select * from customer_info where maturity_date>='"+ sDate+"' and maturity_date<='"+ eDate+"' and paid_status='unpaid' and (account_status='active' or account_status='close') and branch_id='"+branchId+"' order by maturity_date asc ";
            }
            else
            {
            	qq = "select * from customer_info where maturity_date>='"+ sDate+"' and maturity_date<='"+eDate+"' and paid_status='unpaid' and scheme_type='"+searchType+"' and (account_status='active' or account_status='close') and branch_id='"+branchId+"' order by maturity_date asc ";
            }
            ResultSet rs = st.executeQuery(qq);
            while (rs.next())
            {
                UserInfo uu = new UserInfo();
                uu = userInfoByShareHolderNo(rs.getString("shareHolderNo"), con);
                uu.setSno(i++);
                uu.setShareHolderNo(rs.getString("shareHolderNo"));
                uu.setInstallment_amount(rs.getDouble("installment_amount"));
                uu.setTerms(rs.getInt("terms"));
                uu.setMaturity_value(Double.parseDouble(df.format(rs.getDouble("maturity_value"))));
                uu.setMaturity_date(rs.getDate("maturity_date"));
                uu.setScheme_type(rs.getString("scheme_type"));
                uu.setUser_no(rs.getString("user_no"));
                 
                double insAmt=0; 
                if(uu.getScheme_type().equals("RD") || uu.getScheme_type().equals("DD"))
                {
                    insAmt=uu.getTerms()*uu.getInstallment_amount();
                }
                else
                {
                    insAmt=uu.getInstallment_amount();
                }
                uu.setPaidAmount(paidAmountByUser(uu.getUser_no(),con));
               
                if(uu.getPaidAmount()==0)
                {
                    uu.setColorStatus("nil");
                }
                else if(insAmt==uu.getPaidAmount())
                {
                    uu.setColorStatus("paid");
                }
                else
                {
                    uu.setColorStatus("pending");
                }
               
                String a=statusOfOdLoanByUserNo(rs.getString("user_no"));
                       
                if(a.equalsIgnoreCase("active"))
                {
                   
                    uu.setDisBtn2(true);
                    uu.setDisBtn1(true);
                }
                else
                {
               
               
                    if(uu.getColorStatus().equals("paid") || rs.getString("account_status").equals("close"))
                    {
                        //// // // // System.out.println(uu.getUser_no()+"hiiiiiiiii");
                        uu.setDisBtn2(true);
                    }
                    else
                    {
                        uu.setDisBtn2(false);
                    }
                   
                    if(uu.isDisBtn2()==false)
                    {
                        uu.setDisBtn1(true);
                    }
                    else
                    {
                        uu.setDisBtn1(false);
                    }
                }
                uu.setStrMatDate(sf.format(rs.getDate("maturity_date")));
                list.add(uu);
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return list;
    }
	
	public ArrayList<UserInfo> upcomingLoanClosureReportByDate(int branchId,Date startDate, Date endDate, String searchType)
    {
		 String qq="";
        int i=1;
        ArrayList<UserInfo> list = new ArrayList<UserInfo>();
        try (Connection con = DataBaseConnection.JAVAConnection();)
        {
            Statement st = con.createStatement();
            if(searchType.equalsIgnoreCase("grouploan"))
            {
            	qq = "select * from grouploan inner join shareholder_info where grouploan.teamLeader=shareholder_info.shareholderno ";
            }
            else
            {
            	qq = "select * from "+searchType+" inner join shareholder_info where  "+searchType+".shareholderno=shareholder_info.shareholderno  ";
            }
            qq+=" and shareholder_info.branch_id='"+branchId+"' and paidStatus='unpaid' and "+searchType+".status='Approve' ";
            ResultSet rs = st.executeQuery(qq);
            while (rs.next())
            {
                UserInfo uu = new UserInfo();
                if(searchType.equalsIgnoreCase("grouploan"))
                {
                	 uu.setLoanNo(rs.getString("sub_loan_no"));
                }
                else
                {
                	 uu.setLoanNo(rs.getString("loanNo"));
                }
                
                //ArrayList<LoanInfo> loanEMIList=loanInstallment(searchType, uu.getLoanNo(), con);
                //Date closeDate=loanEMIList.get(loanEMIList.size()-1).getInstallDate();
                ArrayList<Date> dateList=loanEmiDateList(rs.getInt("frequency"), rs.getInt("terms"), rs.getDate("emi_due_date"), rs.getDate("approvalDate"));
                Date closeDate=dateList.get(dateList.size()-1);
                if((startDate.before(closeDate) || startDate.equals(closeDate)) &&  (endDate.after(closeDate) || endDate.equals(closeDate)))
                {
                	  uu.setPaidAmount(loanPaidAmountByUser(searchType,uu.getLoanNo(),con));
                	  
                      uu.setSno(i++);
                      uu.setShareHolderNo(rs.getString("shareholder_info.shareholderno"));
                      uu.setFirst_applicantName(rs.getString("shareholder_info.first_applicantName"));
                      uu.setAddress(rs.getString("shareholder_info.address"));
                      uu.setContactNo(rs.getString("shareholder_info.mobile"));
                      uu.setStrOffcDate(sf.format(rs.getDate("approvalDate")));
                      uu.setStrMatDate(sf.format(closeDate));
                      uu.setLoanAmount(rs.getDouble("loanAmount"));
                	  
                      list.add(uu);
                }
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return list;
    }
	
	
	public int showInstallmentStatus(String user_no) 
	{
		int i = 0;
		double instlmnt, payableAmount, terms;
		try (Connection con = DataBaseConnection.JAVAConnection();)
		{
			Statement st = con.createStatement();
			String qq = "select * from customer_info where user_no='"+ user_no+ "' and paid_status='unpaid' and (account_status='active' or account_status='close') ";
			ResultSet rs = st.executeQuery(qq);
			if (rs.next())
			{
				if (rs.getString("account_status").equals("active"))
				{
					if (rs.getString("scheme_type").equals("RD") || rs.getString("scheme_type").equals("DD")) 
					{
						instlmnt = rs.getDouble("installment_amount");
						terms = rs.getInt("terms");
						payableAmount = instlmnt * terms;
					} 
					else 
					{
						instlmnt = rs.getDouble("installment_amount");
						payableAmount = instlmnt;
					}
					double paidAmount = paidAmountByUser(user_no,con);
					if (payableAmount == paidAmount)
					{
						i++;
					}
				} 
				else if (rs.getString("account_status").equals("close")) 
				{
					i++;
				}
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}
	

	public int firstInstallment(int branchId,String user_no, Date office_date,double installment_amount, String receipt_no) 
	{
		int j = 0;
		Timestamp crdt = new Timestamp(office_date.getTime());
		try (Connection conn = DataBaseConnection.JAVAConnection();) 
		{
			String query = "insert into payment_receipt(user_no, date, payment_mode, amount, cheque_no, cheque_date, bank_name, penalty,receipt_no,receipt_status.branch_id) values(?,?,?,?,?,?,?,?,?,?,?)";
			PreparedStatement st1 = conn.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
			st1.setString(1, user_no);
			st1.setTimestamp(2, crdt);
			st1.setString(3, "cash");
			st1.setDouble(4, installment_amount);
			st1.setString(5, "");
			st1.setTimestamp(6, null);
			st1.setString(7, null);
			st1.setDouble(8, 0);
			st1.setString(9, receipt_no);
			st1.setString(10, "approved");
			st1.setInt(11, branchId);
			
			int	rr=	st1.executeUpdate();
			if(rr>0)
			{
				String query1 = "insert into payment_receipt(user_no, date, payment_mode, amount, cheque_no, cheque_date, bank_name, penalty,receipt_no,receipt_status,branch_id) "
						+ "values('"+user_no+"','"+crdt+"','cash','"+installment_amount+"',null,null,null,0,'"+receipt_no+"','approved','"+branchId+"')";
				dataInsertInQueryTable(query1, conn);
			}
			ResultSet generatedKeys = st1.getGeneratedKeys();
			if (generatedKeys.next()) 
			{
				return generatedKeys.getInt(1);
	        }
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return j;
	}

	public int returnMaturedAmount(int branchId,String user_no, double maturity_value,Date current_date,
			String paymentMode, String bankName, String bankBranch, String chequeNo, Date chequeDate, String savingAccountNo, double preMaturityCharge, double stationaryCharge, double otherCharge) 
	{
		int i = 0;
		Timestamp dt = new Timestamp(current_date.getTime());
		String status="";
		Timestamp chdate = null;
		if (chequeDate != null) 
		{
			chdate = new Timestamp(chequeDate.getTime());
		}
		
		if(paymentMode.equals("Cash") || paymentMode.equals("Transfer"))
		{
			status="cleared";
			bankName="N/A";
		}
		else
		{
			status="uncleared";
		}
		
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			String qq="insert into returned_amount_info(user_no,maturity_value,date,paymentMode,bankName,bankBranch,"
					+ "chequeNo,chequeDate,chequeStatus, saving_account_no,pre_maturity_charge, stationary_charge, other_charge, branch_id) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			
			
			PreparedStatement st=con.prepareStatement(qq);
			st.setString(1, user_no);
			st.setDouble(2, maturity_value);
			st.setTimestamp(3, dt);
			st.setString(4, paymentMode);
			st.setString(5, bankName);
			st.setString(6,bankBranch);
			st.setString(7, chequeNo);
			st.setTimestamp(8,chdate);
			st.setString(9, status);
			st.setString(10, savingAccountNo);
			st.setDouble(11, preMaturityCharge);
			st.setDouble(12, stationaryCharge);
			st.setDouble(13, otherCharge);
			st.setInt(14, branchId);
			
			int x=st.executeUpdate();
			if (x >= 1) 
			{
				dataInsertInQueryTable(String.valueOf(st), con);
				
				if(paymentMode.equalsIgnoreCase("Cash") || paymentMode.equalsIgnoreCase("Transfer"))
				{
					String qr="update customer_info set paid_status='paid',account_status='inactive' where user_no='"+ user_no + "'";
					int z = st.executeUpdate(qr);
					if (z >= 1) 
					{
						dataInsertInQueryTable(qr, con);
						i++;
					}
				}
				else
				{
					i++;
				}
				
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}

	// This Method Return the all Detail Of The Share Holder from shareholder_info table 
	public UserInfo userInfoByShareHolderNo(String holderNo,Connection conn) 
	{
		Statement stt=null;
		ResultSet ss=null;
		UserInfo uu = new UserInfo();
		try
		{
			stt = conn.createStatement();
			String query = "select * from shareholder_info where shareholderno='"+ holderNo + "'";
			ss = stt.executeQuery(query);
			
			if (ss.next()) 
			{
				uu = userInfoById(ss, conn);
			}
			else
			{
				return null;
			}
		}
		catch (Exception e) 
		{
			
            e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(ss!=null)
				{
					ss.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return uu;
	}
    
	
	// This Method Return the all Detail Of The Share Holder from shareholder_info table and This Method is use as a Inner Method in Various Methods


	public UserInfo userInfoById(ResultSet rs, Connection conn) 
	{
		
          UserInfo uu = new UserInfo();
		
		try 
		{
			uu.setId(rs.getString("id"));
			uu.setAddress(rs.getString("address"));
			uu.setOffice_application_no(rs.getString("office_application_no"));
			uu.setOffice_date(rs.getDate("office_date"));
			uu.setStrOffcDate(sf.format(rs.getDate("office_date")));
			uu.setShareHolderNo(rs.getString("shareholderno"));
			uu.setFirst_applicantName(rs.getString("first_applicantName"));
			uu.setDob(rs.getDate("dob"));
			uu.setStrdob(sf.format(rs.getDate("dob")));
			uu.setFather_husband_name(rs.getString("father_husband_name"));
			uu.setGuardian_name(rs.getString("guardian_name"));
			uu.setGuardian_relation(rs.getString("guardian_relation"));
			uu.setStatus(rs.getString("status"));
			uu.setPAN(rs.getString("PAN"));
			uu.setBank_accountNo(rs.getString("bank_accountNo"));
			uu.setBank_name(rs.getString("bank_name"));
			uu.setBranch(rs.getString("branch"));
			uu.setAddress(rs.getString("address"));
			uu.setContactNo(rs.getString("mobile"));
			uu.setNominee_name(rs.getString("nominee_name"));
			uu.setCenterCode(rs.getString("center"));
			uu.setNominee_fatherName(rs.getString("nominee_father"));
			uu.setNominee_motherName(rs.getString("nominee_mother"));
            uu.setOccupation(rs.getString("occupation"));
		    uu.setBank_name(rs.getString("bank_name"));
		    uu.setBank_accountNo(rs.getString("bank_accountNo"));
		    uu.setBankIfsc(rs.getString("bank_ifsc"));
		    uu.setNomineeBankName(rs.getString("nom_bank_name"));
		    uu.setAppCheque(rs.getString("app_cheque"));
		    uu.setUniqueId(rs.getString("unique_id"));
		    uu.setAltMobileNo(rs.getString("alt_mobile_no"));
			
			
			uu.setNominee_relation(highMarkLabelByValue("Relationship",rs.getString("nominee_relation") , conn));
					highMarkLabelByValue("Relationship",rs.getString("nominee_relation") , conn);
			uu.setNomRelation(rs.getString("nominee_relation"));
					
			if(rs.getDate("nominee_dob")!=null)
			{
				uu.setNominee_dob(rs.getDate("nominee_dob"));
				uu.setStrNomDate(sf.format(rs.getDate("nominee_dob")));
			}
			
			uu.setNominee_address(rs.getString("nominee_address"));
			
			uu.setNomineeBankName(rs.getString("nom_bank_name"));
			uu.setNomBankBranch(rs.getString("nom_bank_branch"));
			uu.setNomBankAccNo(rs.getString("nom_acc_no"));
			uu.setNomBankIfscCode(rs.getString("nom_ifsc_code"));
			uu.setNomMobileNo(rs.getString("nom_mobile_no"));

			uu.setNoOfShare(rs.getDouble("noofShare"));
			uu.setShareAmount(rs.getDouble("shareAmount"));
			uu.setTotalAmount(rs.getDouble("totalAmount"));
			
			uu.setCategory(rs.getString("category"));
			uu.setPerAddress(rs.getString("perAddress"));
			uu.setCrNo(rs.getString("crNo"));
			uu.setPayMode(rs.getString("pay_mode"));
			uu.setRelation(rs.getString("relation"));
			uu.setG1C(rs.getString("cheque_no"));
		
			filePathDetail(conn);  //for set online view path if exist
			if(onlineFileViewPath==null || onlineFileViewPath.trim().equals(""))
			{
				uu.setApplicant_photo(rs.getString("applicant_photo"));
				uu.setSignPhoto(rs.getString("signPhoto"));
				uu.setFormPhoto(rs.getString("formPhoto"));
				uu.setDoc1Path(rs.getString("doc1"));
				uu.setDoc2Path(rs.getString("doc2"));
				uu.setDoc3Path(rs.getString("doc3")); 
				uu.setDoc4Path(rs.getString("doc4"));
				uu.setDoc5Path(rs.getString("doc5"));
				uu.setDoc6Path(rs.getString("doc6")); 
				uu.setDoc7Path(rs.getString("doc7"));
				uu.setDoc8Path(rs.getString("doc8"));

				uu.setDoc9Path(rs.getString("doc9")); 
				uu.setDoc10Path(rs.getString("doc10"));
				uu.setDoc11Path(rs.getString("doc11"));

			}
			else
			{
				uu.setApplicant_photo(onlineFileViewPath+rs.getString("applicant_photo"));
				uu.setSignPhoto(onlineFileViewPath+rs.getString("signPhoto"));
				uu.setFormPhoto(onlineFileViewPath+rs.getString("formPhoto"));
				uu.setDoc1Path(onlineFileViewPath+rs.getString("doc1"));
				uu.setDoc2Path(onlineFileViewPath+rs.getString("doc2"));
				uu.setDoc3Path(onlineFileViewPath+rs.getString("doc3"));
				uu.setDoc4Path(onlineFileViewPath+rs.getString("doc4"));
				uu.setDoc5Path(onlineFileViewPath+rs.getString("doc5"));
				uu.setDoc6Path(onlineFileViewPath+rs.getString("doc6"));
				uu.setDoc7Path(onlineFileViewPath+rs.getString("doc7"));
				uu.setDoc8Path(onlineFileViewPath+rs.getString("doc8"));

				uu.setDoc9Path(onlineFileViewPath+rs.getString("doc9"));
				uu.setDoc10Path(onlineFileViewPath+rs.getString("doc10"));
				uu.setDoc11Path(onlineFileViewPath+rs.getString("doc11"));
				

			}
			
			uu.setApplicant_photoForEdit(rs.getString("applicant_photo"));
			uu.setSignPhotoForEdit(rs.getString("signPhoto"));
			uu.setFormPhotoForEdit(rs.getString("formPhoto"));
			uu.setDoc1PathForEdit(rs.getString("doc1"));
			uu.setDoc2PathForEdit(rs.getString("doc2"));
			uu.setDoc3PathForEdit(rs.getString("doc3")); 
			uu.setDoc4PathForEdit(rs.getString("doc4"));
			uu.setDoc5PathForEdit(rs.getString("doc5"));
			uu.setDoc6PathForEdit(rs.getString("doc6")); 
			uu.setDoc7PathForEdit(rs.getString("doc7"));
			uu.setDoc8PathForEdit(rs.getString("doc8"));

			uu.setDoc9PathForEdit(rs.getString("doc9")); 
			uu.setDoc10PathForEdit(rs.getString("doc10"));
			uu.setDoc11PathForEdit(rs.getString("doc11"));

			
			
			if(uu.getPayMode()==null || uu.getPayMode().equals(""))
			{
				
			}
			else
			{
				if(uu.getPayMode().equalsIgnoreCase("Cash"))
				{
					uu.setBankNameCheque("");
					uu.setChequeNo("");
				}
				else
				{
					uu.setBankNameCheque(rs.getString("bank_name_cheque"));
					uu.setChequeNo(rs.getString("cheque_no"));
				}
			}			
			
			
			if("".equals(rs.getString("transfer_from")))

			{
				uu.setTransferFrom("");
				uu.setDisable(true);
			}
			else
			{
				uu.setTransferFrom(rs.getString("transfer_from"));
				uu.setDisable(false);
			}
			/*if(rs.getString("transfer_from").equals(""))
			{
				uu.setTransferFrom("");
				uu.setPayMode("");
				uu.setBankNameCheque("");
				uu.setChequeNo("");
				uu.setDisable(true);
			}
			else
			{
				uu.setTransferFrom(rs.getString("transfer_from"));
				uu.setPayMode(rs.getString("pay_mode"));
				uu.setBankNameCheque(rs.getString("bank_name_cheque"));
				uu.setChequeNo(rs.getString("cheque_no"));
				uu.setDisable(false);
			}*/
			uu.setCrNo(rs.getString("crNo"));
			
			uu.setVoterId(rs.getString("voter_id"));
			uu.setUniqueId(rs.getString("unique_id"));
			uu.setRationNo(rs.getString("ration_no"));
			uu.setDlNo(rs.getString("dl_no"));
			uu.setElectBill(rs.getString("elect_bill"));
			uu.setResCert(rs.getString("res_cert"));
			uu.setAppCheque(rs.getString("app_cheque"));
			uu.setgCheque(rs.getString("g_cheque"));
			uu.settBill(rs.getString("t_bill"));
			uu.setTransferBank(rs.getString("transfer_to_bank"));
			uu.setTransferToBankName(bankNameById(rs.getString("transfer_to_bank")));	
			uu.setRelation(rs.getString("relation"));
			
			// High Mark Fileds
			uu.setGender(rs.getString("gender"));
			uu.setMaritalStatus(rs.getString("marital_status"));
			uu.setKeyPersonName(rs.getString("key_person_name"));
			uu.setKeyPersonRelation(rs.getString("key_person_relation"));
			uu.setTelephoneIndicator(rs.getString("telephone_indicator"));
			uu.setNoOfDependent(rs.getInt("no_of_dependent"));
			uu.setReligion(rs.getString("religion"));
			uu.setStateCode(rs.getString("state_code"));
			uu.setPinCode(rs.getString("pin_code"));
			
			uu.setMaritalStatusLabel(highMarkLabelByValue("Marital Status", rs.getString("marital_status"), conn));
			uu.setKeyPersonRelationLabel(highMarkLabelByValue("Relationship", rs.getString("key_person_relation"),conn));
			uu.setTelephoneIndicatorLabel(highMarkLabelByValue("Telephone Indicator", rs.getString("telephone_indicator"),conn));
			uu.setReligionLabel(highMarkLabelByValue("Religion", rs.getString("religion"),conn));
			uu.setStateCodeLabel(highMarkLabelByValue("State Code", rs.getString("state_code"),conn));
			
			uu.setCity(rs.getString("city"));
			uu.setCityName(cityNameById(rs.getString("city"), conn));
			
			uu.setEmail(rs.getString("email"));
			uu.setQualification(rs.getString("qualification"));
			uu.setOccupation(rs.getString("occupation"));
			uu.setBankIfsc(rs.getString("bank_ifsc"));
			uu.setReferenceBy(rs.getString("reference_by"));
			uu.setRemark(rs.getString("remark"));
			uu.setTitle(rs.getString("title"));
			uu.setMonthlyIncome(rs.getString("monthly_income"));
			
			uu.setNomAadhar(rs.getString("nom_aadhar"));
			uu.setNomPan(rs.getString("nom_pan"));
			uu.setBrideFhname(rs.getString("bride_fhname"));
			uu.setBrideMname(rs.getString("bride_mname"));
			uu.setBrideAddress(rs.getString("bride_address"));
			uu.setBrideBusiness(rs.getString("bride_business"));
			uu.setBrideBusinessPlace(rs.getString("bride_business_place"));
			uu.setBrideMobileNo(rs.getString("bride_mobile_no"));
			uu.setBrideRemark(rs.getString("bride_remark"));
			uu.setCenterId(rs.getString("center"));
			uu.setNomTitle(rs.getString("nom_title"));
			uu.setNomGender(rs.getString("nom_gender"));
			uu.setLatitude(rs.getString("latitude"));
			uu.setLongitude(rs.getString("longitude"));
		}
	
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return uu;
		
	}

	public UserInfo shareHolderDocByShareHolderNo(String shno)
	{
		UserInfo uu=new UserInfo();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from shareholder_info where shareholderno='"+shno+"' ";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				filePathDetail(conn);  //for set online view path if exist
				if(onlineFileViewPath==null || onlineFileViewPath.trim().equals(""))
				{
					uu.setApplicant_photo(rs.getString("applicant_photo"));
					uu.setSignPhoto(rs.getString("signPhoto"));
					uu.setFormPhoto(rs.getString("formPhoto"));
					uu.setDoc1Path(rs.getString("doc1"));
					uu.setDoc2Path(rs.getString("doc2"));
					uu.setDoc3Path(rs.getString("doc3")); 
					uu.setDoc4Path(rs.getString("doc4"));
					uu.setDoc5Path(rs.getString("doc5"));
					uu.setDoc6Path(rs.getString("doc6")); 
					uu.setDoc7Path(rs.getString("doc7"));
					uu.setDoc8Path(rs.getString("doc8"));
					uu.setDoc9Path(rs.getString("doc9")); 
					uu.setDoc10Path(rs.getString("doc10"));
					uu.setDoc11Path(rs.getString("doc11"));
				}
				else
				{
					if(rs.getString("applicant_photo")!=null && !rs.getString("applicant_photo").equalsIgnoreCase(""))
					{
						uu.setApplicant_photo(onlineFileViewPath+rs.getString("applicant_photo"));
					}
					else
					{
						uu.setApplicant_photo("");
					}
					
					if(rs.getString("signPhoto")!=null && !rs.getString("signPhoto").equalsIgnoreCase(""))
					{
						uu.setSignPhoto(onlineFileViewPath+rs.getString("signPhoto"));
					}
					else
					{
						uu.setSignPhoto("");
					}
					
					if(rs.getString("formPhoto")!=null && !rs.getString("formPhoto").equalsIgnoreCase(""))
					{
						uu.setFormPhoto(onlineFileViewPath+rs.getString("formPhoto"));
					}
					else
					{
						uu.setFormPhoto("");
					}
					
					if(rs.getString("doc1")!=null && !rs.getString("doc1").equalsIgnoreCase(""))
					{
						uu.setDoc1Path(onlineFileViewPath+rs.getString("doc1"));
					}
					else
					{
						uu.setDoc1Path("");
					}
				
					if(rs.getString("doc2")!=null && !rs.getString("doc2").equalsIgnoreCase(""))
					{
						uu.setDoc2Path(onlineFileViewPath+rs.getString("doc2"));
					}
					else
					{
						uu.setDoc2Path("");
					}
				
					if(rs.getString("doc3")!=null && !rs.getString("doc3").equalsIgnoreCase(""))
					{
						uu.setDoc3Path(onlineFileViewPath+rs.getString("doc3"));
					}
					else
					{
						uu.setDoc3Path("");
					}
					
					if(rs.getString("doc4")!=null && !rs.getString("doc4").equalsIgnoreCase(""))
					{
						uu.setDoc4Path(onlineFileViewPath+rs.getString("doc4"));
					}
					else
					{
						uu.setDoc4Path("");
					}
				
					if(rs.getString("doc5")!=null && !rs.getString("doc5").equalsIgnoreCase(""))
					{
						uu.setDoc5Path(onlineFileViewPath+rs.getString("doc5"));
					}
					else
					{
						uu.setDoc5Path("");
					}
				
					if(rs.getString("doc6")!=null && !rs.getString("doc6").equalsIgnoreCase(""))
					{
						uu.setDoc6Path(onlineFileViewPath+rs.getString("doc6"));
					}
					else
					{
						uu.setDoc6Path("");
					}
				
					if(rs.getString("doc7")!=null && !rs.getString("doc7").equalsIgnoreCase(""))
					{
						uu.setDoc7Path(onlineFileViewPath+rs.getString("doc7"));
					}
					else
					{
						uu.setDoc7Path("");
					}
				
					if(rs.getString("doc8")!=null && !rs.getString("doc8").equalsIgnoreCase(""))
					{
						uu.setDoc8Path(onlineFileViewPath+rs.getString("doc8"));
					}
					else
					{
						uu.setDoc8Path("");
					}
					
					if(rs.getString("doc9")!=null && !rs.getString("doc9").equalsIgnoreCase(""))
					{
						uu.setDoc6Path(onlineFileViewPath+rs.getString("doc9"));
					}
					else
					{
						uu.setDoc9Path("");
					}
				
					if(rs.getString("doc10")!=null && !rs.getString("doc10").equalsIgnoreCase(""))
					{
						uu.setDoc10Path(onlineFileViewPath+rs.getString("doc10"));
					}
					else
					
						uu.setDoc10Path("");
					}
				
					if(rs.getString("doc11")!=null && !rs.getString("doc11").equalsIgnoreCase(""))
					{
						uu.setDoc11Path(onlineFileViewPath+rs.getString("doc11"));
					}
					else
					{
					
						uu.setDoc11Path("");
			       
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return uu;
	}


	public String highMarkLabelByValue(String columnType, String columnValue, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select column_label from high_mark_table where column_type='"+columnType+"' and column_value='"+columnValue+"' ";
			//System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("column_label");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
			}
		}
		return "";
	}

	public ArrayList<PaymentReceiptInfo> receiptInfo(int branchId,String user_no) 
	{
		ArrayList<PaymentReceiptInfo> list = new ArrayList<PaymentReceiptInfo>();
		int i = 1;
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq = "SELECT * FROM payment_receipt a inner JOIN customer_info b ON a.user_no = b.user_no where a.user_no='"+ user_no
					+ "' and b.account_status='active' and a.receipt_status in ('approved') and a.chequeStatus in ('cleared') and b.branch_id='"+branchId+"'"; 
			ResultSet rs = st.executeQuery(qq);
			while (rs.next()) 
			{
				PaymentReceiptInfo pp = new PaymentReceiptInfo();
				pp.setSno(i);
				pp.setId(rs.getString("id"));
				pp.setUser_no(rs.getString("user_no"));
				pp.setAmount(rs.getDouble("amount"));
				pp.setDate(rs.getDate("date"));
				pp.setStrdate(sf.format(rs.getDate("date")));
				pp.setPayment_mode(rs.getString("payment_mode"));
				if (rs.getString("payment_mode").equals("cheque"))
				{
					pp.setCheque_no(rs.getString("cheque_no"));
					pp.setCheque_date(rs.getDate("cheque_date"));
					pp.setBank_name(rs.getString("bank_name"));
					pp.setStrchqdt(sf.format(rs.getDate("cheque_date")));
				}
				pp.setStatus(rs.getString("receipt_status"));
				if(pp.getPayment_mode().equalsIgnoreCase("Transfer"))
				{
					pp.setDisableForFreezingData(true);
				}
				else
				{
					pp.setDisableForFreezingData(checkDataFreezing(branchId,DataBaseMethods.selectedSessionDetail(), con));
				}
				if(pp.getStatus().equalsIgnoreCase("pending"))
				{
					pp.setDisableEdit(false);
				}
				else
				{
					pp.setDisableEdit(true);
				}
				pp.setPenalty(rs.getDouble("penalty"));
				pp.setReceiptNo(rs.getString("receipt_no"));
				pp.setTransferBank(rs.getString("transfer_to_bank"));
				pp.setTransferToBankName(bankNameById(rs.getString("transfer_to_bank")));
				
				list.add(pp);
				i++;
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	public int removeReceipt(String id)
	{
		int i = 0;
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq = "update payment_receipt set receipt_status='inactive' where id='"+ id + "'";
			int x = st.executeUpdate(qq);
			if (x >= 1) 
			{
				dataInsertInQueryTable(qq, con);
				i++;
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}
    
	// This Method use to Insert the All Detail of new Member and share alloted direct by the Comapny/Nidhi.
	public int addNewMember(int branchId,String office_application_no,Date office_date, String shareNo,String first_applicantName,
			Date dob, String father_husband_name,String guardian_name,String guardian_relation, String status,String pAN,String bank_accountNo,
			String bank_name, String branch,String address, String mobile,String nominee_name,String nominee_relation, Date nominee_dob,
			String nominee_address,String applicant_photoPath, double noOfShare,double shareAmount,double totalAmount,String perAddress,
			String signPath, String formPath, String category, String crNo, String votrId, String uniqueId, String rationNo, String dlNo, 
			String electBill, String resCert, String appCheque, String gCheque, String submittedBankName, String tBill, 
			String paymentMode, String bankNameCheque, String chequeNo, String aadharFrontPathDoc1, String doc2Path, String voterFrontPathDoc3, String doc4Path, String doc5Path, 
			int issueShare, Connection conn,String doc6Path, String doc7Path,String doc8Path, String city, String relation, String gender, String maritalStatus, 
			String keyPersonName, String keyPersonRelation, String telephoneIndicator, int noOfDependent, String religion, String stateCode, String pinCode, String dsaCode,
			String email, String qualification, String occupation, String bankIfsc, String referenceBy, String remark, String title, String monthlyIncome, String nomAadhar, 
			String nomPan, String brideFhname, String brideMname, String brideAddress, String brideBusiness, String brideBusinessPlace, String brideMobileNo, String brideRemark,
			String center, String nomTitle,String nomGender, String latitude, String longitude,String nomineeFather,String nomineeMother,String nomBankName,String nomBankBranch,String nomAccNo,String nomIfscCode,String nomVoterId,String nomContactNo,String altContactNo, 
			String cibilScore, String cibilReportPath,String aadharBackPath, String voterBackPath)
			{
		   System.out.println(" aadhar front doc 1 path is "+aadharFrontPathDoc1);
		   System.out.println("voter front doc 3 path"+voterFrontPathDoc3);
		   System.out.println("aadhar back path is"+aadharBackPath);
		   System.out.println("vote rback path is :"+voterBackPath);
				String chqStatus="";
				
				if(paymentMode.equalsIgnoreCase("cash"))
				{
					chqStatus="cleared";
				}
				else
				{
					chqStatus="uncleared";
				}
		
				int j = 0;
				HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
				String userId=(String) ss1.getAttribute("username");
				Timestamp ofcdt = new Timestamp(office_date.getTime());
				Timestamp dbdt = new Timestamp(dob.getTime());
				Statement st=null;
				ResultSet generatedKeys=null;
				Timestamp ndbdt=null;
				if(nominee_dob!=null)
				{
					ndbdt= new Timestamp(nominee_dob.getTime());
				}
				try  
				{   
					String query = "insert into shareholder_info(office_application_no, office_date,shareholderno,first_applicantName,dob,"
					+ "father_husband_name, guardian_name, guardian_relation, status, PAN, bank_accountNo, bank_name, branch, address, mobile,"
					+ "nominee_name, nominee_relation, nominee_dob, nominee_address, applicant_photo, account_status, noofShare, shareAmount,"
					+ "totalAmount,perAddress,category,signPhoto,formPhoto,transfer_from,crNo,  voter_id, unique_id, ration_no, dl_no, elect_bill, res_cert, "
					+ "app_cheque, g_cheque, transfer_to_bank,t_bill,pay_mode,bank_name_cheque,cheque_no, doc1, doc2,doc3,doc4,doc5, issue_share,user_id, cheque_status,"
					+ "doc6,doc7,doc8, city, relation, gender, marital_status, key_person_name, key_person_relation, telephone_indicator, no_of_dependent, religion, "
					+ "state_code, pin_code, dsacode, branch_id,email, qualification, occupation, bank_ifsc, reference_by, remark, title, monthly_income,"
					+ "nom_aadhar, nom_pan, bride_fhname, bride_mname, bride_address, bride_business, bride_business_place, bride_mobile_no, bride_remark,center,nom_title,"
					+ "nom_gender,latitude,longitude,nominee_father,nominee_mother,nom_bank_name,nom_bank_branch,nom_acc_no,nom_ifsc_code,nom_voter_id,nom_mobile_no,alt_mobile_no, "
					+ "cibil_score, cibil_report_path, report_fetch_time,aadhar_back_doc01,voterId_back_doc03) "
					+ "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,"
					+ "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?, ?, ?,?,?)";

					
					
					System.out.println(query);

					PreparedStatement st1 = conn.prepareStatement(
						    query,
						    Statement.RETURN_GENERATED_KEYS
						);

					
					st1.setString(1, office_application_no);
					st1.setTimestamp(2, ofcdt);
					st1.setString(3, shareNo);
					st1.setString(4, first_applicantName.toUpperCase());
					st1.setTimestamp(5, dbdt);
					st1.setString(6, father_husband_name.toUpperCase());
					st1.setString(7, guardian_name);
					st1.setString(8, guardian_relation);
					st1.setString(9, status);
					st1.setString(10, pAN);
					st1.setString(11, bank_accountNo);
					st1.setString(12, bank_name);
					st1.setString(13, branch);
					st1.setString(14, address.toUpperCase());
					st1.setString(15, mobile);
					st1.setString(16, nomVoterId);
					st1.setString(17,nomContactNo);
					
					
					if (nominee_name == null || nominee_name.trim().isEmpty()) {
					    st1.setString(16, "");
					} else {
					    st1.setString(16, nominee_name.toUpperCase());
					}

					
					st1.setString(17, nominee_relation);
					st1.setTimestamp(18, ndbdt);
					
					if (nominee_address == null || nominee_address.trim().isEmpty()) {
						st1.setString(19,"");
					} else {
						st1.setString(19, nominee_address.toUpperCase());
					}
										
					st1.setString(20, applicant_photoPath);
					st1.setString(21, "active");
					st1.setDouble(22, noOfShare);
					st1.setDouble(23, shareAmount);
					st1.setDouble(24, totalAmount);
					st1.setString(25, perAddress);
					st1.setString(26, category);
					st1.setString(27, signPath);
					st1.setString(28, formPath);
					st1.setString(29, "");
					st1.setString(30, crNo);
					st1.setString(31, votrId);
					st1.setString(32, uniqueId);
					st1.setString(33, rationNo);
					st1.setString(34, dlNo);
					st1.setString(35, electBill);
					st1.setString(36, resCert);
					st1.setString(37, appCheque);
					st1.setString(38, gCheque);
					st1.setString(39, submittedBankName);
					st1.setString(40, tBill);
					st1.setString(41, paymentMode);
					st1.setString(42, bankNameCheque);
					st1.setString(43, chequeNo);
					st1.setString(44, aadharFrontPathDoc1);
					st1.setString(45, doc2Path);
					st1.setString(46, voterFrontPathDoc3);
					st1.setString(47, doc4Path);
					st1.setString(48, doc5Path);
					st1.setInt(49, issueShare);
					st1.setString(50, userId);	
					st1.setString(51, chqStatus);
					st1.setString(52, doc6Path);
					st1.setString(53, doc7Path);
					st1.setString(54, doc8Path);
					st1.setString(55, city);
					st1.setString(56, relation);
					st1.setString(57, gender);
					st1.setString(58, maritalStatus);
					st1.setString(59, keyPersonName);
					st1.setString(60, keyPersonRelation);
					st1.setString(61, telephoneIndicator);
					st1.setInt(62, noOfDependent);
					st1.setString(63, religion);
					st1.setString(64, stateCode);
					st1.setString(65, pinCode);
					st1.setString(66, dsaCode);
					st1.setInt(67, branchId);
					st1.setString(68, email);
					st1.setString(69, qualification);
					st1.setString(70, occupation);
					st1.setString(71, bankIfsc);
					st1.setString(72, referenceBy);
					st1.setString(73, remark);
					st1.setString(74, title);
					st1.setString(75, monthlyIncome);
					st1.setString(76, nomAadhar);
					st1.setString(77, nomPan);
					st1.setString(78, brideFhname);
					st1.setString(79, brideMname);
					st1.setString(80, brideAddress);
					st1.setString(81, brideBusiness);
					st1.setString(82, brideBusinessPlace);
					st1.setString(83, brideMobileNo);
					st1.setString(84, brideRemark);
					st1.setString(85, center);
					st1.setString(86, nomTitle);
					st1.setString(87, nomGender);
					st1.setString(88, latitude);
					st1.setString(89, longitude);
					st1.setString(90,nomineeFather);
					st1.setString(91,nomineeMother);
					st1.setString(92,nomBankName);
					st1.setString(93,nomBankBranch);
					st1.setString(94,nomAccNo);
					st1.setString(95,nomIfscCode);
					st1.setString(96, nomVoterId);
					st1.setString(97, nomContactNo);
					st1.setString(98,altContactNo);
					st1.setString(99, cibilScore);
					st1.setString(100, cibilReportPath);
					
					
					
					if (cibilScore != null && !cibilScore.trim().equals(""))
					{
					    double score = Double.valueOf(cibilScore);

					    if (score > 0)
					    {
					        st1.setTimestamp(101, new java.sql.Timestamp(System.currentTimeMillis()));
					    }
					    else
					    {
					        st1.setTimestamp(101, null);
					    }
					}
					else
					{
					    st1.setTimestamp(101, null);
					}
					st1.setString(102, aadharBackPath);
					st1.setString(103, voterBackPath);

					int i = st1.executeUpdate();
					if(i>0)
					{
						dataInsertInQueryTable(String.valueOf(st1), conn);
						
					}
					
					generatedKeys = st1.getGeneratedKeys();
					if (generatedKeys.next()) 
					{
						updateCompanyShares(conn);
						 st=conn.createStatement();
							int s=(int) (Math.random()*999999); 
							String qq="insert into login (userid,password,type, mobile_no,branch_id) value('"+shareNo+"', '"+s+"','user','"+mobile+"','"+branchId+"')";   //	// Insert the Member Detail for Login on APP
						   int rr1= st.executeUpdate(qq);
						    if(rr1>0)
						    {
						    	dataInsertInQueryTable(qq, conn);
						    }
			           return generatedKeys.getInt(1);
			        }
				} 
				catch (Exception e) 
				{
					 e.printStackTrace();fileCreation(e.getMessage());
				}
				finally
				{
					try {
						if(st!=null)
						{
							st.close();
						}
						if(generatedKeys!=null)
						{
							generatedKeys.close();
						}
					} catch (Exception e2) {
						// TODO: handle exception
					}
				}
				return j;

			}
			
			
	
	// This Method use to Insert the All Detail of new Member and share alloted direct by the Comapny/Nidhi.
		public int addMoreShareOfExistingMember(int branchId,String office_application_no,Date office_date, String shareNo,String first_applicantName,
				Date dob, String father_husband_name,String guardian_name,String guardian_relation, String status,String pAN,String bank_accountNo,
				String bank_name, String branch,String address, String mobile,String nominee_name,String nominee_relation, Date nominee_dob,
				String nominee_address,String applicant_photoPath, double noOfShare,double shareAmount,double totalAmount,String perAddress,
				String signPath, String formPath, String category, String crNo, String votrId, String uniqueId, String rationNo, String dlNo, 
				String electBill, String resCert, String appCheque, String gCheque, String submittedBankName, String tBill, 
				String paymentMode, String bankNameCheque, String chequeNo, String doc1Path, String doc2Path, String doc3Path, String doc4Path, String doc5Path, 
				int issueShare, Connection conn)
				{
					String chqStatus="";
					
					if(paymentMode.equalsIgnoreCase("cash"))
					{
						chqStatus="cleared";
					}
					else
					{
						chqStatus="uncleared";
					}
			
					int j = 0;
					HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
					String userId=(String) ss1.getAttribute("username");
					Timestamp ofcdt = new Timestamp(office_date.getTime());
					Timestamp dbdt = new Timestamp(dob.getTime());
					Statement st=null;
					ResultSet generatedKeys=null;
					Timestamp ndbdt=null;
					if(nominee_dob!=null)
					{
						ndbdt= new Timestamp(nominee_dob.getTime());
					}
					try  
					{
						String query = "insert into share_info(office_application_no, office_date,shareholderno,first_applicantName,dob,"
						+ "father_husband_name, guardian_name, guardian_relation, status, PAN, bank_accountNo, bank_name, branch, address, mobile,"
						+ "nominee_name, nominee_relation, nominee_dob, nominee_address, applicant_photo, account_status, noofShare, shareAmount,"
						+ "totalAmount,perAddress,category,signPhoto,formPhoto,transfer_from,crNo,  voter_id, unique_id, ration_no, dl_no, elect_bill, res_cert, "
						+ "app_cheque, g_cheque, transfer_to_bank,t_bill,pay_mode,bank_name_cheque,cheque_no, doc1, doc2,doc3,doc4,doc5, issue_share,user_id, cheque_status,branch_id) "
						+ "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				
						PreparedStatement st1 = conn.prepareStatement(query);
						
						st1.setString(1, office_application_no);
						st1.setTimestamp(2, ofcdt);
						st1.setString(3, shareNo);
						st1.setString(4, first_applicantName.toUpperCase());
						st1.setTimestamp(5, dbdt);
						st1.setString(6, father_husband_name.toUpperCase());
						st1.setString(7, guardian_name);
						st1.setString(8, guardian_relation);
						st1.setString(9, status);
						st1.setString(10, pAN);
						st1.setString(11, bank_accountNo);
						st1.setString(12, bank_name);
						st1.setString(13, branch);
						st1.setString(14, address.toUpperCase());
						st1.setString(15, mobile);
						st1.setString(16, nominee_name.toUpperCase());
						st1.setString(17, nominee_relation);
						st1.setTimestamp(18, ndbdt);
						st1.setString(19, nominee_address.toUpperCase());
						st1.setString(20, applicant_photoPath);
						st1.setString(21, "active");
						st1.setDouble(22, noOfShare);
						st1.setDouble(23, shareAmount);
						st1.setDouble(24, totalAmount);
						st1.setString(25, perAddress);
						st1.setString(26, category);
						st1.setString(27, signPath);
						st1.setString(28, formPath);
						st1.setString(29, "");
						st1.setString(30, crNo);
						st1.setString(31, votrId);
						st1.setString(32, uniqueId);
						st1.setString(33, rationNo);
						st1.setString(34, dlNo);
						st1.setString(35, electBill);
						st1.setString(36, resCert);
						st1.setString(37, appCheque);
						st1.setString(38, gCheque);
						st1.setString(39, submittedBankName);
						st1.setString(40, tBill);
						st1.setString(41, paymentMode);
						st1.setString(42, bankNameCheque);
						st1.setString(43, chequeNo);
						st1.setString(44, doc1Path);
						st1.setString(45, doc2Path);
						st1.setString(46, doc3Path);
						st1.setString(47, doc4Path);
						st1.setString(48, doc5Path);
						st1.setInt(49, issueShare);
						st1.setString(50, userId);	
						st1.setString(51, chqStatus);
						st1.setInt(52, branchId);
						
						int i = st1.executeUpdate();
						if(i>0)
						{
							dataInsertInQueryTable(String.valueOf(st1), conn);
							
						}
						
						generatedKeys = st1.getGeneratedKeys();
						if (generatedKeys.next()) 
						{
							updateCompanyShares(conn);
							
				           return generatedKeys.getInt(1);
				        }
					} 
					catch (Exception e) 
					{
						 e.printStackTrace();fileCreation(e.getMessage());
					}
					finally
					{
						try 
						{
							if(st!=null)
							{
								st.close();
							}
							if(generatedKeys!=null)
							{
								generatedKeys.close();
							}
						} 
						catch (Exception e2) 
						{
							e2.printStackTrace();
						}
					}
					return j;
				}

        public int addNewMemberWithTransfer(int branchId,String office_application_no,
		Date office_date, String shareNo, String first_applicantName,
		Date dob, String father_husband_name, String guardian_name,
		String guardian_relation, String status, String pAN,
		String bank_accountNo, String bank_name, String branch,
		String address, String mobile, String nominee_name,
		String nominee_relation, Date nominee_dob, String nominee_address,
		String applicant_photoPath, double noOfShare, double shareAmount,
		double totalAmount, String perAddress, String signPath,
		String formPath, String category, String transferShareHolderNo,
		String paymentMode, String bankNameCheque, String chequeNo, String tBill, String submittedBankName, String aadharFrontPathDoc1, String doc2Path, String voterFrontPathDoc3, 
		String doc4Path, String doc5Path, int issueShare, String votrId, String uniqueId, String rationNo, String dlNo, String electBill, String resCert, 
		String tBill2, String appCheque, String gCheque,
		String doc6Path, String doc7Path, String doc8Path, String city, String relation, String gender, String maritalStatus, String keyPersonName, String keyPersonRelation,
		String telephoneIndicator, int noOfDependent, String religion, String stateCode, String pinCode, String dsaCode, String nomAadhar, String nomPan,
		String brideFhname, String brideMname, String brideAddress, String brideBusiness, String brideBusinessPlace, String brideMobileNo, String brideRemark,

		String center, String nomTitle, String nomGender,String latitude, String longitude, String  nomineeFather, String nomineeMother,
		         String nomBankName,String nomBankBranch,String nomAccNo,String nomIfscCode,String nomVoterId,String nomContactNo,
		          String aadharBackPath, String voterBackPath)

{              
        	System.out.println("recevied doc1"+aadharFrontPathDoc1);
        	System.out.println("enter in function");
        	System.out.println("no father"+nomineeFather);
	int j = 0;
	Timestamp ofcdt = new Timestamp(office_date.getTime());
	Timestamp dbdt = new Timestamp(dob.getTime());
	Timestamp ndbdt =null;
	Statement st=null;
	HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
	String userId=(String) ss1.getAttribute("username");
	
	if(nominee_dob!=null)
	{
		ndbdt=new Timestamp(nominee_dob.getTime());
	}
	try (Connection conn = DataBaseConnection.JAVAConnection();) 
	{   
		

String query = "INSERT INTO shareholder_info("
        + "office_application_no, office_date, shareholderno, first_applicantName, dob, "
        + "father_husband_name, guardian_name, guardian_relation, status, PAN, bank_accountNo, bank_name, branch, address, mobile, "
        + "nominee_name, nominee_relation, nominee_dob, nominee_address, applicant_photo, account_status, noofShare, shareAmount, "
        + "totalAmount, perAddress, category, signPhoto, formPhoto, transfer_from, pay_mode, bank_name_cheque, cheque_no, voter_id, "
        + "unique_id, ration_no, dl_no, elect_bill, res_cert, app_cheque, g_cheque, t_bill, transfer_to_bank, "
        + "doc1, doc2, doc3, doc4, doc5, issue_share, user_id, doc6, doc7, doc8, city, relation, gender, marital_status, "
        + "key_person_name, key_person_relation, telephone_indicator, no_of_dependent, religion, state_code, pin_code, dsacode, "
        + "branch_id, cheque_status, nom_aadhar, nom_pan, bride_fhname, bride_mname, bride_address, bride_business, "
        + "bride_business_place, bride_mobile_no, bride_remark, center, nom_title, nom_gender, latitude, longitude, "
        + "nominee_father, nominee_mother, nom_bank_name, nom_bank_branch, nom_acc_no, nom_ifsc_code, "
        + "nom_voter_id, nom_mobile_no, aadhar_back_doc01, voterId_back_doc03"
        + ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

		
		PreparedStatement st1 = conn.prepareStatement(query);
		st1.setString(1, office_application_no);
		st1.setTimestamp(2, ofcdt);
		st1.setString(3, shareNo);
		st1.setString(4, first_applicantName.toUpperCase());
		st1.setTimestamp(5, dbdt);
		st1.setString(6, father_husband_name.toUpperCase());
		st1.setString(7, guardian_name);
		st1.setString(8, guardian_relation);
		st1.setString(9, status);
		st1.setString(10, pAN);
		st1.setString(11, bank_accountNo);
		st1.setString(12, bank_name);
		st1.setString(13, branch);
		st1.setString(14, address.toUpperCase());
		st1.setString(15, mobile);
		st1.setString(16, nominee_name.toUpperCase());
		st1.setString(17, nominee_relation);
		st1.setTimestamp(18, ndbdt);
		st1.setString(19, nominee_address.toUpperCase());
		st1.setString(20, applicant_photoPath);
		st1.setString(21, "active");
		st1.setDouble(22, noOfShare);
		st1.setDouble(23, shareAmount);
		st1.setDouble(24, totalAmount);
		st1.setString(25, perAddress);
		st1.setString(26, category);
		st1.setString(27, signPath);
		st1.setString(28, formPath);
		st1.setString(29, transferShareHolderNo);
		st1.setString(30, paymentMode);
		st1.setString(31, bankNameCheque);
		st1.setString(32, chequeNo);
		st1.setString(33, votrId);
		st1.setString(34, uniqueId);
		st1.setString(35, rationNo);
		st1.setString(36, dlNo);
		st1.setString(37, electBill);
		st1.setString(38, resCert);
		st1.setString(39, appCheque);
		st1.setString(40, gCheque);
		st1.setString(41, tBill);
		st1.setString(42, submittedBankName);
		st1.setString(43, aadharFrontPathDoc1);
		st1.setString(44, doc2Path);
		st1.setString(45, voterFrontPathDoc3);
		st1.setString(46, doc4Path);
		st1.setString(47, doc5Path);
		st1.setInt(48, issueShare);
		st1.setString(49, userId);
		st1.setString(50, doc6Path);
		st1.setString(51, doc7Path);
		st1.setString(52, doc8Path);
		st1.setString(53, city);
		st1.setString(54, relation);
		st1.setString(55, gender);
		st1.setString(56, maritalStatus);
		st1.setString(57, keyPersonName);
		st1.setString(58, keyPersonRelation);
		st1.setString(59, telephoneIndicator);
		st1.setInt(60, noOfDependent);
		st1.setString(61, religion);
		st1.setString(62, stateCode);
		st1.setString(63, pinCode);
		st1.setString(64, dsaCode);
		st1.setInt(65, branchId);
		st1.setString(66, "cleared");
		
		st1.setString(67, nomAadhar);
		st1.setString(68, nomPan);
		st1.setString(69, brideFhname);
		st1.setString(70, brideMname);
		st1.setString(71, brideAddress);
		st1.setString(72, brideBusiness);
		st1.setString(73, brideBusinessPlace);
		st1.setString(74, brideMobileNo);
		st1.setString(75, brideRemark);
		st1.setString(76, center);
		st1.setString(77, nomTitle);
		st1.setString(78, nomGender);
		st1.setString(79, latitude);
		st1.setString(80, longitude);
		st1.setString(81, nomineeFather);
		st1.setString(82, nomineeMother);

		st1.setString(83,nomBankName);
		st1.setString(84,nomBankBranch);
		st1.setString(85,nomAccNo);
		st1.setString(86,nomIfscCode);
		st1.setString(87, nomVoterId);
		st1.setString(88,nomContactNo);
		st1.setString(89,aadharBackPath);
		st1.setString(90,voterBackPath);


		


//		System.out.println(nomineeFather);

		
		//System.out.println(st1.toString());
		int i = st1.executeUpdate();
		
		if(i>0)
		{
			dataInsertInQueryTable(String.valueOf(st1), conn);
		}
		
		ResultSet generatedKeys = st1.getGeneratedKeys();
		if (generatedKeys.next()) 
		{
			updateNoOfSharesOfTranferShareHolder(noOfShare,transferShareHolderNo);
			 st=conn.createStatement();
				int s=(int) (Math.random()*999999); 
				String qq="insert into login (userid,password,type, mobile_no, branch_id) value('"+shareNo+"', '"+s+"','user','"+mobile+"','"+branchId+"')";
			    int rr1=st.executeUpdate(qq);
			    if(rr1>0)
			    {
			    	dataInsertInQueryTable(qq, conn);
			    }
           return generatedKeys.getInt(1);
        }
	} 
	catch (Exception e) 
	{
		 e.printStackTrace();fileCreation(e.getMessage());
	}
	return j;
}

	
	private void updateNoOfSharesOfTranferShareHolder(double noOfShare, String transferShareHolderNo) 
	{
		double existingShares=obtainExistingNoOfShares(transferShareHolderNo);
		double updateShare=existingShares-noOfShare;
		Connection conn=DataBaseConnection.JAVAConnection();
		double shareAmount=extractCompanyShareAmount(conn);
		double totalAmount=shareAmount*updateShare;
		try
		{
			Statement st=conn.createStatement();
			String qq="update shareholder_info set noofShare='"+updateShare+"', totalAmount='"+totalAmount+"' where shareholderno='"+transferShareHolderNo+"'";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
				dataInsertInQueryTable(qq, conn);
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}

	public double obtainExistingNoOfShares(String transferShareHolderNo) 
	{
		double share=0;
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select * from shareholder_info where shareholderno='"+transferShareHolderNo+"'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				share=rs.getDouble("noofShare");
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return share;
	}

	public void updateCompanyShares(Connection conn)
	{
		double totalAllotedShare=totalNoOfAllotedShares()+additionalShareFromShareInfoTable(conn);
		try
		{
			Statement st=conn.createStatement();
			String qq="update company_shares set shares_alloted='"+totalAllotedShare+"'";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
				dataInsertInQueryTable(qq, conn);
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}
	
	/*public double previousAllotedShares()
	{
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select sum(noOfShare) as allotedShares from shareholder_info where account_status='active'";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rs.next())
			{
				return rs.getDouble("allotedShares");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0.0;
	}*/
	
	// not sure
	public double totalNoOfAllotedShares()
	{
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select sum(noOfShare) as allotedShares from shareholder_info where account_status='active'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getDouble("allotedShares");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0.0;
	}

	public int addLoanRequest(int branchId,String shareHolderNo, String guarantor1,String guarantor2, String loanNo, 
							  String[] idProof, double fileCharge, double loanAmount, double interst,double duration, 
							  int frequency, double emiPayment,Date requestDate, String reason, String rd_fdNo, int discount, 
							  String emiType, String appChqNo, String appAccNo, String appBankName, String appBankBranch, 
							  String g1ChqNo, String g1AccNo, String g1BankName, String g1BankBranch, String g2ChqNo, 
							  String g2AccNo, String g2BankName, String g2BankBranch, String dsaCode, double commission, 
							  double insuranceFee, String center, String planNo, String emiMode, double extraAmount, 
							  String nomChqNo, String nomAccNo, String nomBankName, String nomBankBranch, String nomBankIfsc,
							  String appBankIfsc, String g1BankIfsc, String g2BankIfsc, double processingCharge, double stamp, 
							  int advanceEMITerm, double totalAdvanceEMIAmoount)
	{
		HttpSession ss1 = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		String userId = (String) ss1.getAttribute("username");
		
		Timestamp ss = new Timestamp(requestDate.getTime());
		String idDocument = "";
		
		/*for (int i = 0; i<idProof.length; i++) 
		{
			idDocument+=idProof[i]+",";
		}
		idDocument=idDocument.substring(0,idDocument.lastIndexOf(","));*/
		
		try (Connection conn = DataBaseConnection.JAVAConnection();) 
		{
			Statement stt = conn.createStatement();
			String query = "insert into personalloan(shareholderno, loanNo, idproof, filecharge, loanAmount, interest, terms, "
						 + "frequency, emi, firstguarantor, secondguarantor, requestDate, reason, RD_FD_no, discount, emiType, "
						 + "app_chq_no, app_acc_no, app_bank_name, app_bank_branch, g1_chq_no, g1_acc_no, g1_bank_name, "
						 + "g1_bank_branch, g2_chq_no, g2_acc_no, g2_bank_name, g2_bank_branch, dsacode, commission, "
						 + "insurance_fee, user_id, center, plan_no, emi_mode, extra_amount, branch_id, nom_chq_no, nom_acc_no, "
						 + "nom_bank_name, nom_bank_branch, nom_bank_ifsc, app_bank_ifsc, g1_bank_ifsc, g2_bank_ifsc, "
						 + "processing_charge, stamp, advance_emi_term, advance_emi_amount) "
						 + "values ('" + shareHolderNo + "', '" + loanNo + "', '" + idDocument + "', '" + fileCharge + "', "
						 + "'" + loanAmount + "', '" + interst + "', '" + duration + "', '" + frequency + "', '" + emiPayment + "',"
						 + " '" + guarantor1 + "', '" + guarantor2 + "', '" + ss + "', '" + reason + "', '" + rd_fdNo + "', '" 
						 + discount + "', '" + emiType + "', '" + appChqNo + "', '" + appAccNo + "', '" + appBankName + "', '" 
						 + appBankBranch + "', '" + g1ChqNo + "', '" + g1AccNo + "', '" + g1BankName + "', '" + g1BankBranch + "', "
						 + "'" + g2ChqNo + "', '" + g2AccNo + "', '" + g2BankName + "', '" + g2BankBranch + "', '" + dsaCode + "', "
						 + "'" + commission + "', '" + insuranceFee + "', '" + userId + "', '" + center + "', '" + planNo + "', '"
						 + emiMode + "', '" + extraAmount + "', '" + branchId + "', '" + nomChqNo + "', '" + nomAccNo + "', '" 
						 + nomBankName + "', '" + nomBankBranch + "', '" + nomBankIfsc + "', '" + appBankIfsc + "', '" 
						 + g1BankIfsc + "', '" + g2BankIfsc + "','"+processingCharge+"', '" + stamp + "', '" 
						 + advanceEMITerm + "', '" + totalAdvanceEMIAmoount + "')";
                         
			int j = stt.executeUpdate(query);
			if (j >= 1) {
				dataInsertInQueryTable(query, conn);
				return 1;
			}
		} 
		catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	
	public int addSecureLoanRequest(int branchId,String shareHolderNo, String guarantor1,String guarantor2, String loanNo, String[] idProof,
	String fileCharge, double loanAmount, double interst,double duration, int frequency, double emiPayment,Date requestDate,
	String reason, String rd_fdNo,int discount,String emiType, String appChqNo, String appAccNo, String appBankName, 
	String appBankBranch, String g1ChqNo, String g1AccNo, String g1BankName, String g1BankBranch, String g2ChqNo, 
	String g2AccNo, String g2BankName, String g2BankBranch, String dsaCode, double commission, String insuranceFee, String center, String planNo, String emiMode,
	double extraAmount, String loanCat, double billAmount, double downPayment, String product, String dealer, String imeiNoI, String imeiNoII, double dptCharge, double cardFee, String categoryId)
	{
		HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		String userId=(String) ss1.getAttribute("username");
		
		Timestamp ss = new Timestamp(requestDate.getTime());
		String idDocument = "";
		/*for (int i = 0; i<idProof.length; i++) 
		{
			idDocument+=idProof[i]+",";
		}
		idDocument=idDocument.substring(0,idDocument.lastIndexOf(","));*/
		try (Connection conn = DataBaseConnection.JAVAConnection();) 
		{
			Statement stt = conn.createStatement();
			String query = "insert into secure_loan(shareholderno, loanNo, idproof, filecharge, loanAmount, interest, terms, frequency,"
			+"emi, firstguarantor, secondguarantor, requestDate,reason,RD_FD_no,discount,emiType, app_chq_no, app_acc_no, app_bank_name, app_bank_branch,"
			+ "g1_chq_no, g1_acc_no, g1_bank_name, g1_bank_branch, g2_chq_no, g2_acc_no, g2_bank_name, g2_bank_branch,dsacode,commission, insurance_fee,user_id,center"
			+ ",plan_no, emi_mode,extra_amount, security_type,branch_id,mob_bill_amount,mob_down_payment,mob_imei_no_1,mob_imei_no_2,mob_dealer,mob_product,mob_dpt_charge,mob_card_fee,category_id)"
			+ "values('"+shareHolderNo+"','"+loanNo+"','"+ idDocument+"',"
			+ "'"+fileCharge+ "','"+ loanAmount+ "','"+ interst+ "','"+ duration+"','"+frequency+"','"+emiPayment+"','"+guarantor1+"',"
			+ "'"+ guarantor2+ "','"+ ss+ "','"+reason+"','"+rd_fdNo+"','"+discount+"','"+emiType+"','"+appChqNo+"','"+appAccNo+"','"+appBankName+"','"+appBankBranch+"',"
					+ "'"+g1ChqNo+"','"+g1AccNo+"','"+g1BankName+"','"+g1BankBranch+"','"+g2ChqNo+"','"+g2AccNo+"',"
							+ "'"+g2BankName+"','"+g2BankBranch+"','"+dsaCode+"','"+commission+"','"+insuranceFee+"','"+userId+"','"+center+"','"+planNo+"','"+emiMode+"',"
									+ "'"+extraAmount+"', '"+loanCat+"','"+branchId+"','"+billAmount+"','"+downPayment+"','"+imeiNoI+"','"+imeiNoII+"','"+dealer+"','"+product+"','"+dptCharge+"','"+cardFee+"','"+categoryId+"')";
			
			int j = stt.executeUpdate(query);
			if (j >= 1) {
				dataInsertInQueryTable(query, conn);
				return 1;
			}
		}
		catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public int addBusinessLoanRequest(int branchId,String shareHolderNo, String guarantor1,String guarantor2, String loanNo, String[] idProof,
	String fileCharge, double loanAmount, double interst,double duration, int frequency, double emiPayment,Date requestDate,
	String reason, String rd_fdNo,int discount,String emiType, String appChqNo, String appAccNo, String appBankName, 
	String appBankBranch, String g1ChqNo, String g1AccNo, String g1BankName, String g1BankBranch, String g2ChqNo, 
	String g2AccNo, String g2BankName, String g2BankBranch, String dsaCode, double commission, String insuranceFee, String center, String planNo, String emiMode,
	double extraAmount)
	{
		HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		String userId=(String) ss1.getAttribute("username");
		
		Timestamp ss = new Timestamp(requestDate.getTime());
		String idDocument = "";
		
		for (int i = 0; i<idProof.length; i++) 
		{
			idDocument+=idProof[i]+",";
		}
		
		idDocument=idDocument.substring(0,idDocument.lastIndexOf(","));
		try (Connection conn = DataBaseConnection.JAVAConnection();) 
		{
			Statement stt = conn.createStatement();
			String query = "insert into business_loan(shareholderno, loanNo, idproof, filecharge, loanAmount, interest, terms, frequency,"
			+"emi, firstguarantor, secondguarantor, requestDate,reason,RD_FD_no,discount,emiType, app_chq_no, app_acc_no, app_bank_name, app_bank_branch,"
			+ "g1_chq_no, g1_acc_no, g1_bank_name, g1_bank_branch, g2_chq_no, g2_acc_no, g2_bank_name, g2_bank_branch,dsacode,commission, insurance_fee,user_id,center,plan_no, emi_mode,extra_amount,branch_id)"
			+ "values('"+shareHolderNo+"','"+loanNo+"','"+ idDocument+"',"
			+ "'"+fileCharge+ "','"+ loanAmount+ "','"+ interst+ "','"+ duration+"','"+frequency+"','"+emiPayment+"','"+guarantor1+"',"
			+ "'"+ guarantor2+ "','"+ ss+ "','"+reason+"','"+rd_fdNo+"','"+discount+"','"+emiType+"','"+appChqNo+"','"+appAccNo+"','"+appBankName+"','"+appBankBranch+"',"
					+ "'"+g1ChqNo+"','"+g1AccNo+"','"+g1BankName+"','"+g1BankBranch+"','"+g2ChqNo+"','"+g2AccNo+"',"
							+ "'"+g2BankName+"','"+g2BankBranch+"','"+dsaCode+"','"+commission+"','"+insuranceFee+"','"+userId+"','"+center+"','"+planNo+"','"+emiMode+"','"+extraAmount+"','"+branchId+"')";
			
			int j = stt.executeUpdate(query);
			if (j >= 1) {
				dataInsertInQueryTable(query, conn);
				return 1;
			}
		} 
		catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public int addVechileLoanRequest(int branchId,String shareHolderNo, String guarantor1,String guarantor2, String loanNo, String[] idProof,
	String fileCharge, double loanAmount, double interst,double duration, double frequency, double emiPayment,Date requestDate,
	String category, String vechileName,String model, String engineNo,String macNo, String rd_fdNo,int discount,String emiType, 
	String appChqNo, String appAccNo, String appBankName, String appBankBranch, String g1ChqNo, String g1AccNo, String g1BankName, String g1BankBranch, 
	String g2ChqNo, String g2AccNo, String g2BankName, String g2BankBranch, String dsaCode, double commission, String insuranceFee, String center, String planNo) 
	{
		HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		String userId=(String) ss1.getAttribute("username");
		
		Timestamp ss = new Timestamp(requestDate.getTime());
		String idDocument = "";
		for (int i = 0; i<idProof.length; i++) 
		{
			idDocument+=idProof[i]+",";
		}
		
		idDocument=idDocument.substring(0,idDocument.lastIndexOf(","));
		try (Connection conn = DataBaseConnection.JAVAConnection();) 
		{
			Statement stt = conn.createStatement();
			String query = "insert into vechicleloan(shareholderno, loanNo, idproof, filecharge, loanAmount, interest, terms,frequency,"
			+ "emi,firstguarantor,secondguarantor,requestDate,category,vechileName,model,engineno,macNo,RD_FD_no,discount,emiType, app_chq_no, app_acc_no, app_bank_name, "
			+ "app_bank_branch,g1_chq_no, g1_acc_no, g1_bank_name, g1_bank_branch, g2_chq_no, g2_acc_no, g2_bank_name, g2_bank_branch,dsacode,commission, "
			+ "insurance_fee,user_id,cneter, plan_no, branch_id)values('"+shareHolderNo+"','"+loanNo
			+ "','"+ idDocument+ "','"+ fileCharge+ "','"+ loanAmount+ "','"+ interst+ "','"+ duration+ "','"+ frequency+ "','"+ emiPayment
			+ "','"+guarantor1+"','"+guarantor2+"','"+ss+"','"+category+"','"+vechileName+"','"+model+"','"+engineNo+"','"+macNo+"','"+rd_fdNo+"','"+discount+"',"
					+ "'"+emiType+"','"+appChqNo+"','"+appAccNo+"','"+appBankName+"','"+appBankBranch+"',"
					+ "'"+g1ChqNo+"','"+g1AccNo+"','"+g1BankName+"','"+g1BankBranch+"','"+g2ChqNo+"','"+g2AccNo+"','"+g2BankName+"','"+g2BankBranch+"','"+dsaCode+"',"
							+ "'"+commission+"','"+insuranceFee+"','"+userId+"','"+center+"','"+planNo+"','"+branchId+"')";
			int j = stt.executeUpdate(query);
			if (j >= 1) 
			{
				dataInsertInQueryTable(query, conn);
				return 1;
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public int addPropertyLoanRequest(int branchId,String shareHolderNo, String guarantor1,String guarantor2, String loanNo, String[] idProof,
	String fileCharge, double loanAmount, double interst,double duration, double frequency, double emiPayment,Date requestDate,
	String category, String registryNo,String verified, String jamabandi, String patta, String authorityPatta, String rd_fdNo,int discount,String emiType, String appChqNo,
	String appAccNo, String appBankName, String appBankBranch, String g1ChqNo, String g1AccNo, String g1BankName, String g1BankBranch, String g2ChqNo, 
	String g2AccNo, String g2BankName, String g2BankBranch, String dsaCode, double commission,String insuranceFee,String center, String plan_no) 
	{
		HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		String userId=(String) ss1.getAttribute("username");
		
		Timestamp ss = new Timestamp(requestDate.getTime());
		String idDocument = "";
		for (int i = 0; i<idProof.length; i++) 
		{
			idDocument+=idProof[i]+",";
		}
		idDocument=idDocument.substring(0,idDocument.lastIndexOf(","));
		try (Connection conn = DataBaseConnection.JAVAConnection();) 
		{
			Statement stt = conn.createStatement();
			String query = "insert into propertyloan(shareholderno, loanNo, idproof, filecharge, loanAmount, interest, terms,frequency,"
			+"emi, firstguarantor, secondguarantor, requestDate, category, registryNo, verified,jamabandi,patta,authorityPatta,RD_FD_no,discount,emiType, "
			+ "app_chq_no, app_acc_no, app_bank_name, app_bank_branch,g1_chq_no, g1_acc_no, g1_bank_name, g1_bank_branch, g2_chq_no, g2_acc_no, g2_bank_name,"
			+ " g2_bank_branch,dsacode,commission, insurance_fee,user_id, center,plan_no, branch_id)values"
			+ "('"+shareHolderNo+"','"+ loanNo+"','"+idDocument+"','"+fileCharge+ "','"+ loanAmount+"','"+interst+"','"+duration+"',"
			+ "'"+frequency+"','"+emiPayment+"','"+guarantor1+"','"+guarantor2+"','"+ss+"','"+category+"','"+registryNo+"','"+verified
			+"','"+jamabandi+"','"+patta+"','"+authorityPatta+"','"+rd_fdNo+"','"+discount+"','"+emiType+"','"+appChqNo+"','"+appAccNo+"','"+appBankName+"','"+appBankBranch+"',"
					+ "'"+g1ChqNo+"','"+g1AccNo+"','"+g1BankName+"','"+g1BankBranch+"','"+g2ChqNo+"','"+g2AccNo+"','"+g2BankName+"','"+g2BankBranch+"'"
							+ ",'"+dsaCode+"','"+commission+"','"+insuranceFee+"','"+userId+"','"+center+"','"+plan_no+"','"+branchId+"')";
			
			int j = stt.executeUpdate(query);
			if (j >= 1) 
			{
				dataInsertInQueryTable(query, conn);
				return 1;
			}
		} catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}

		return 0;
	}

	public ArrayList<SelectItem> allcenter(int branchId, String dsaCode,Connection conn)
	{
		ArrayList<SelectItem> centerList=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		String query="";
		
		try
		{
			st=conn.createStatement();
			if(dsaCode.equalsIgnoreCase("all") || dsaCode.equalsIgnoreCase(""))
			{
				query="select * from center";
			}
			else
			{
				query="select * from center where dsacode='"+dsaCode+"' ";
			}
			rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				SelectItem info=new SelectItem();
				info.setValue(rr.getString("id"));
				info.setLabel(rr.getString("centerName")+"/"+rr.getString("centerCode"));
				centerList.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	
		return centerList;
	}
	
	// This Method return's the List of DD/RD/FD/Loan Plan's add By User...
	public ArrayList<SelectItem> allPlans(int branchId,String type)
	{
		ArrayList<SelectItem> centerList=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from plans where type='"+type+"' and status='active' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				SelectItem info=new SelectItem();
				info.setValue(rr.getString("idplans"));
				info.setLabel(rr.getString("plan"));
				centerList.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return centerList;
	}

	// Add New Group Loan Request
	public int addGroupLoanRequest(int branchId, String shareHolderNo, String loanNo, String[] idProof, String fileCharge, double loanAmount,
			double interst, double duration, double frequency,double emiPayment, Date requestDate, ArrayList<UserInfo> userList,String center, String rd_fdNo,int discount, 
			String emiType, String appChqNo, String appAccNo, String appBankName, String appBankBranch, String g1ChqNo, String g1AccNo, String g1BankName, String g1BankBranch, String g2ChqNo, 
			String g2AccNo, String g2BankName, String g2BankBranch, String dsaCode, double commission, String appType, String subLoanNo, String insuranceFee, String groupType, String plan_no, 
			double extraAmount, String loanCategory, String loanCycle, String loanPurpose, String repaymentFreq, double processingCharge) 
			{
				String member = "";
				String arr[]=loanNo.split("-");
				//String tempNo=arr[1];
				String tempNo=arr[1].substring(arr[1].length()-4);
				
				HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
				String userId=(String) ss1.getAttribute("username");
				
				for(UserInfo ls:userList)
				{
					if(member=="")
					{
						member=ls.getShareHolderNo();
					}
					else
					{
						member=member+", "+ls.getShareHolderNo();
					}
				}
				Timestamp ss = new Timestamp(requestDate.getTime());

				String idDocument = "";
				for (int i = 0; i<idProof.length; i++) 
				{
					idDocument+=idProof[i]+",";
				}
				idDocument=idDocument.substring(0,idDocument.lastIndexOf(","));
				try (Connection conn = DataBaseConnection.JAVAConnection();) 
				{
					Statement stt = conn.createStatement();
					String query = "insert into grouploan(teamLeader, loanNo, idproof, filecharge, loanAmount, interest, terms, frequency,"
							+ " emi, requestDate,members, center,RD_FD_no,discount,emiType, app_chq_no, app_acc_no, app_bank_name,"
							+ " app_bank_branch,g1_chq_no, g1_acc_no, g1_bank_name, g1_bank_branch, g2_chq_no, g2_acc_no, g2_bank_name, "
							+ "g2_bank_branch,dsacode,commission,application_type,sub_loan_no, insurance_fee, temp_no,user_id,plan_no, extra_amount, "
							+ "loan_category, loan_cycle, loan_purpose, repayment_frequency,branch_id, processing_charge)"
							+ "values('"+ shareHolderNo+ "','"+ loanNo+"','"+idDocument+"','"+fileCharge+ "',"
							+ "'"+ loanAmount+"','"+ interst+"','"+duration+ "','"+ frequency+ "','"+ emiPayment+ "','"+ss+"','"+member+"',"
							+ "'"+center+"','"+rd_fdNo+"','"+discount+"','"+emiType+"','"+appChqNo+"','"+appAccNo+"','"+appBankName+"',"
							+ "'"+appBankBranch+"','"+g1ChqNo+"','"+g1AccNo+"','"+g1BankName+"','"+g1BankBranch+"','"+g2ChqNo+"',"
							+ "'"+g2AccNo+"','"+g2BankName+"','"+g2BankBranch+"','"+dsaCode+"','"+commission+"','"+appType+"',"
							+ "'"+subLoanNo+"', '"+insuranceFee+"','"+tempNo+"','"+userId+"','"+plan_no+"', '"+extraAmount+"',"
							+ "'"+loanCategory+"','"+loanCycle+"','"+loanPurpose+"','"+repaymentFreq+"','"+branchId+"', "
							+ "'"+processingCharge+"')";
					
					int j = stt.executeUpdate(query);
					if (j >= 1) 
					{
						dataInsertInQueryTable(query, conn);
						if(groupType.equals("2"))
						{
							updateMemberByLoanNo(loanNo, member);
						}
						return 1;
					}
				}
				catch (Exception e) {
					 e.printStackTrace();fileCreation(e.getMessage());
				}

				return 0;
			}

	private void updateMemberByLoanNo(String loanNo, String member) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update grouploan set members='"+member+"' where loanNo='"+loanNo+"' ";
		int j=	st.executeUpdate(qq);
		if(j>0)
		{
			dataInsertInQueryTable(qq, conn);
		}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}

	public int checkMemberInList(ArrayList<UserInfo> userList, String guarantor1) 
	{
		int i=0;
		for(UserInfo ls:userList)
		{
			if(ls.getShareHolderNo().equals(guarantor1))
			{
				i++;
			}
		}
		return i;
	}
    
	public ArrayList<LoanInfo> personalLoanList(int branchId,String dsaCode, String loanSearchType, String searchType, String searchLoan) 
    {
		String query="";
		int count=1;
		ArrayList<LoanInfo> list=new ArrayList<>();
		
		/*if(status.equalsIgnoreCase("All"))
		{
			query="select * from personalloan INNER JOIN shareholder_info on personalloan.shareholderno=shareholder_info.shareholderno where shareholder_info.branch_id='"+branchId+"' order by personalloan.loanNo asc";
		}
		else if(status.equalsIgnoreCase("Approve") || status.equalsIgnoreCase("notApprove") || status.equalsIgnoreCase("pending"))
		{
			query="select * from personalloan INNER JOIN shareholder_info on personalloan.shareholderno=shareholder_info.shareholderno  where personalloan.status='"+status+"' and shareholder_info.branch_id='"+branchId+"' order by personalloan.loanNo asc";
		}
		else
		{
			if(searchLoan.equalsIgnoreCase("all"))
			{
				query="select * from personalloan INNER JOIN shareholder_info on personalloan.shareholderno=shareholder_info.shareholderno  where (personalloan.frequency='"+status+"' || personalloan.frequency='"+status+".0') and shareholder_info.branch_id='"+branchId+"' order by personalloan.loanNo asc" ; 
			}
			else
			{
				query="select * from personalloan INNER JOIN shareholder_info on personalloan.shareholderno=shareholder_info.shareholderno  where (personalloan.frequency='"+status+"' || personalloan.frequency='"+status+".0') and personalloan.loanNo='"+searchLoan+"' and shareholder_info.branch_id='"+branchId+"' order by personalloan.loanNo asc" ; 
			}
		}*/
		
		query="select * from personalloan INNER JOIN shareholder_info on personalloan.shareholderno=shareholder_info.shareholderno where personalloan.status!='notApprove'  ";
		
		if(searchLoan!=null && !searchLoan.equalsIgnoreCase("-1") && !searchLoan.equalsIgnoreCase("all") && !searchLoan.trim().equalsIgnoreCase(""))
		{
			query+=" and loanNo='"+searchLoan+"' ";
		}
		
		if(!searchType.equalsIgnoreCase("-1") && !searchType.equalsIgnoreCase("all"))
		{
			query+=" and (frequency='"+searchType+"' || frequency='"+searchType+".0') ";
		}
		
		if(!dsaCode.equalsIgnoreCase("-1") && !dsaCode.equalsIgnoreCase("all"))
		{
			query+=" and personalloan.dsacode='"+dsaCode+"' ";
		}
		
		query+=" and paidStatus='"+loanSearchType+"' and shareholder_info.branch_id='"+branchId+"' order by personalloan.loanNo asc";
		//System.out.println(query);
		
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
			Statement stt=conn.createStatement();
			ResultSet ss=stt.executeQuery(query);
			while(ss.next())
			{
				//if(!ss.getString("loanNo").contains("R"))
				{
					LoanInfo info=new LoanInfo();
					
					String shareHolderNo=ss.getString("personalloan.shareholderno");
					info.setSno(count++);
					info.setShareHolderNo(shareHolderNo);
					info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
					info.setRelation(ss.getString("shareholder_info.relation"));
					info.setFatherHusbandName(ss.getString("shareholder_info.father_husband_name"));
					info.setContactNo(ss.getString("shareholder_info.mobile"));
					info.setId(ss.getString("personalloan.id"));
					info.setTerms(ss.getInt("terms"));
					info.setAddress(ss.getString("shareholder_info.address"));
					info.setEmiType(ss.getString("personalloan.emiType"));
					info.setEmiMode(ss.getString("personalloan.emi_mode"));
					info.setLoanAmount(ss.getString("loanAmount"));
					info.setLoanInterest(String.valueOf(Double.parseDouble(df.format(Double.valueOf(ss.getString("personalloan.interest"))))));
					info.setDiscount(ss.getInt("discount"));
					info.setLoanTerm(ss.getString("personalloan.terms"));
					info.setInstallAmount(ss.getDouble("personalloan.emi"));
					info.setLoanType("Personal Loan");
					info.setRequestDate(ss.getDate("requestDate"));
					info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
					info.setFirstGuarantor(ss.getString("firstguarantor"));
					info.setSecondGuarantor(ss.getString("secondguarantor"));
					info.setIdProof(ss.getString("idproof"));
					info.setLoanNo(ss.getString("loanNo"));
					info.setDoc11Path(ss.getString("doc11"));
					
					if(ss.getString("fileCharge").trim().equals(""))
					{
						info.setFileCharge("0");
					}
					
					else
					{
						info.setFileCharge(ss.getString("fileCharge"));
					}
					
					info.setProcessingCharge(ss.getDouble("processing_charge"));
					info.setReason(ss.getString("reason"));
					info.setRd_fdNo(ss.getString("RD_FD_no"));
					info.setFrequency(String.valueOf(ss.getInt("frequency")));
					info.setFrequencyVal(ss.getInt("frequency"));
					info.setFreqLable(frequencyLabel(info.getFrequency()));
					
					if(ss.getDate("approvalDate")!=null)
					{
						info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
						info.setEmiPaidDate(ss.getDate("approvalDate"));
					}
					
					
					if(ss.getDate("emi_due_date")!=null)
					{
						info.setEmiPaidDate(ss.getDate("emi_due_date"));
					}
					info.setStatus(ss.getString("personalloan.status"));
					info.setAppChqNo(ss.getString("personalloan.app_chq_no"));
					info.setAppAccNo(ss.getString("personalloan.app_acc_no"));
					info.setAppBankName(ss.getString("personalloan.app_bank_name"));
					info.setAppBankBranch(ss.getString("personalloan.app_bank_branch"));
					info.setAppBankIfsc(ss.getString("personalloan.app_bank_ifsc"));
					
					info.setG1ChqNo(ss.getString("personalloan.g1_chq_no"));
					info.setG1AccNo(ss.getString("personalloan.g1_acc_no"));
					info.setG1BankName(ss.getString("personalloan.g1_bank_name"));
					info.setG1BankBranch(ss.getString("personalloan.g1_bank_branch"));
					info.setG1BankIfsc(ss.getString("personalloan.g1_bank_ifsc"));
					
					info.setG2ChqNo(ss.getString("personalloan.g2_chq_no"));
					info.setG2AccNo(ss.getString("personalloan.g2_acc_no"));
					info.setG2BankName(ss.getString("personalloan.g2_bank_name"));
					info.setG2BankBranch(ss.getString("personalloan.g2_bank_branch"));
					info.setG2BankIfsc(ss.getString("personalloan.g2_bank_ifsc"));
					DbYashwant dby = new DbYashwant();
					info.setDsacode(dby.manageEmployeeId(ss.getString("dsacode") ));
					info.setDsaName(dsaNameById(ss.getString("dsacode"), conn));
					info.setCommission(ss.getDouble("commission"));
					info.setEmiType(ss.getString("emiType"));
					if(ss.getString("insurance_fee").trim().equals(""))
					{
						info.setInsuranceFee("0");
					}
					else
					{
						info.setInsuranceFee(ss.getString("insurance_fee"));
					}
					
					if(ss.getDate("emi_due_date")!=null)
					{
						info.setStrEmiDueDate(sf.format(ss.getDate("emi_due_date")));
						info.setEmiDate(ss.getDate("emi_due_date"));
					}
					
					info.setCenter(ss.getString("center"));
					info.setCenterName(centerNameById(ss.getString("center"),conn));
					
					info.setGuarantarName(firstApplicantNameBySHNo(ss.getString("firstguarantor"),conn));
					info.setGuarantarFatherName(shareHolderDetailByColumnName(ss.getString("firstguarantor"), "father_husband_name", conn));
					info.setGuarantorShareHno(ss.getString("firstguarantor"));
					info.setGuarantarAddress(shareHolderDetailByColumnName(ss.getString("firstguarantor"), "address", conn));
					
					info.setSecGuarantarName(firstApplicantNameBySHNo(ss.getString("secondguarantor"),conn));
					info.setSecGuarantarFatherName(shareHolderDetailByColumnName(ss.getString("secondguarantor"), "father_husband_name", conn));
					info.setSecGuarantarAddress(shareHolderDetailByColumnName(ss.getString("secondguarantor"), "address", conn));
					info.setSecGuarantorShareHno(ss.getString("secondguarantor"));
					
					
					// File Charge and Insurance Fee Editable
					if(ss.getString("personalloan.status").equalsIgnoreCase("notApprove") || ss.getString("personalloan.paidStatus").equalsIgnoreCase("paid"))
					{
						info.setDisable(true);
					}
					else
					{
						info.setDisable(false);
					}
					info.setNomineePersonalLoanName(shareHolderDetailByColumnName(shareHolderNo, "nominee_name", conn));
					info.setNomineeAddress(shareHolderDetailByColumnName(shareHolderNo, "nominee_address", conn));
					info.setNomRel(shareHolderDetailByColumnName(shareHolderNo, "nominee_relation", conn));
					info.setNomFaName(shareHolderDetailByColumnName(shareHolderNo, "first_applicantName", conn));
					info.setExtraAmt(ss.getDouble("personalloan.extra_amount"));
					info.setTotalAmount(info.getInstallAmount()+info.getExtraAmt());
					
					// to bind First EMI Date Variable 
					double amt=loanPaidAmountByUser("personalloan", info.getLoanNo(), conn);
					if(amt>0 || ss.getString("personalloan.status").equalsIgnoreCase("notApprove") || ss.getString("personalloan.paidStatus").equalsIgnoreCase("paid"))
					{
						info.setDisBtn(true);
					}
					else
					{
						info.setDisBtn(false);
					}
					
					list.add(info);
				}
				
			}
			
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	public ArrayList<LoanInfo> personalLoanListByDate(int branchId,String dsaCode, String loanSearchType, String searchType, String searchLoan) 
    {
		String query="";
		int count=1;
		ArrayList<LoanInfo> list=new ArrayList<>();
		
		/*if(status.equalsIgnoreCase("All"))
		{
			query="select * from personalloan INNER JOIN shareholder_info on personalloan.shareholderno=shareholder_info.shareholderno where shareholder_info.branch_id='"+branchId+"' order by personalloan.loanNo asc";
		}
		else if(status.equalsIgnoreCase("Approve") || status.equalsIgnoreCase("notApprove") || status.equalsIgnoreCase("pending"))
		{
			query="select * from personalloan INNER JOIN shareholder_info on personalloan.shareholderno=shareholder_info.shareholderno  where personalloan.status='"+status+"' and shareholder_info.branch_id='"+branchId+"' order by personalloan.loanNo asc";
		}
		else
		{
			if(searchLoan.equalsIgnoreCase("all"))
			{
				query="select * from personalloan INNER JOIN shareholder_info on personalloan.shareholderno=shareholder_info.shareholderno  where (personalloan.frequency='"+status+"' || personalloan.frequency='"+status+".0') and shareholder_info.branch_id='"+branchId+"' order by personalloan.loanNo asc" ; 
			}
			else
			{
				query="select * from personalloan INNER JOIN shareholder_info on personalloan.shareholderno=shareholder_info.shareholderno  where (personalloan.frequency='"+status+"' || personalloan.frequency='"+status+".0') and personalloan.loanNo='"+searchLoan+"' and shareholder_info.branch_id='"+branchId+"' order by personalloan.loanNo asc" ; 
			}
		}*/
		
		query="select * from personalloan INNER JOIN shareholder_info on personalloan.shareholderno=shareholder_info.shareholderno where personalloan.status!='notApprove' ";
		
		if(searchLoan!=null && !searchLoan.equalsIgnoreCase("-1") && !searchLoan.equalsIgnoreCase("all") && !searchLoan.trim().equalsIgnoreCase(""))
		{
			query+=" and loanNo='"+searchLoan+"' ";
		}
		
		if(!searchType.equalsIgnoreCase("-1") && !searchType.equalsIgnoreCase("all"))
		{
			query+=" and (frequency='"+searchType+"' || frequency='"+searchType+".0') ";
		}
		
		if(!dsaCode.equalsIgnoreCase("-1") && !dsaCode.equalsIgnoreCase("all"))
		{
			query+=" and personalloan.dsacode='"+dsaCode+"' ";
		}
		
		query+=" and paidStatus='"+loanSearchType+"' and shareholder_info.branch_id='"+branchId+"' order by personalloan.loanNo asc";
		//System.out.println(query);
		
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
			Statement stt=conn.createStatement();
			ResultSet ss=stt.executeQuery(query);
			
			while(ss.next())
			{			
				//if(!ss.getString("loanNo").contains("R"))
				{
					LoanInfo info=new LoanInfo();
					
					String shareHolderNo=ss.getString("personalloan.shareholderno");
					info.setSno(count++);
					info.setShareHolderNo(shareHolderNo);
					info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
					info.setRelation(ss.getString("shareholder_info.relation"));
					info.setFatherHusbandName(ss.getString("shareholder_info.father_husband_name"));
					info.setContactNo(ss.getString("shareholder_info.mobile"));
					info.setId(ss.getString("personalloan.id"));
					info.setTerms(ss.getInt("terms"));
					info.setAddress(ss.getString("shareholder_info.address"));
					info.setEmiType(ss.getString("personalloan.emiType"));
					info.setEmiMode(ss.getString("personalloan.emi_mode"));
                	info.setLoanAmount(ss.getString("loanAmount"));
					
					info.setLoanAmountWord(
						    new NumberToWord().convertNumberToWords(
						        (int) Double.parseDouble(ss.getString("loanAmount"))
						    )
						);

						info.setLoanPurpose(ss.getString("reason"));
					
					info.setLoanInterest(String.valueOf(Double.parseDouble(df.format(Double.valueOf(ss.getString("personalloan.interest"))))));
					info.setDiscount(ss.getInt("discount"));
					info.setLoanTerm(ss.getString("personalloan.terms"));
					info.setInstallAmount(ss.getDouble("personalloan.emi"));
					info.setLoanType("Personal Loan");
					info.setRequestDate(ss.getDate("requestDate"));
					info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
					info.setFirstGuarantor(ss.getString("firstguarantor"));
					info.setSecondGuarantor(ss.getString("secondguarantor"));
					info.setIdProof(ss.getString("idproof"));
					info.setLoanNo(ss.getString("loanNo"));
					info.setDoc11Path(ss.getString("doc11"));
					
					if(ss.getString("fileCharge").trim().equals(""))
					{
						info.setFileCharge("0");
					}
					
					else
					{
						info.setFileCharge(ss.getString("fileCharge"));
					}
					
					info.setProcessingCharge(ss.getDouble("processing_charge"));
					info.setReason(ss.getString("reason"));
					info.setRd_fdNo(ss.getString("RD_FD_no"));
					info.setFrequency(String.valueOf(ss.getInt("frequency")));
					info.setFrequencyVal(ss.getInt("frequency"));
					info.setFreqLable(frequencyLabel(info.getFrequency()));
					
					if(ss.getDate("approvalDate")!=null)
					{
						info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
						info.setEmiPaidDate(ss.getDate("approvalDate"));
					}
					
					
					if(ss.getDate("emi_due_date")!=null)
					{
						info.setEmiPaidDate(ss.getDate("emi_due_date"));
					}
					info.setStatus(ss.getString("personalloan.status"));
					info.setAppChqNo(ss.getString("personalloan.app_chq_no"));
					info.setAppAccNo(ss.getString("personalloan.app_acc_no"));
					info.setAppBankName(ss.getString("personalloan.app_bank_name"));
					info.setAppBankBranch(ss.getString("personalloan.app_bank_branch"));
					info.setAppBankIfsc(ss.getString("personalloan.app_bank_ifsc"));
					
					info.setG1ChqNo(ss.getString("personalloan.g1_chq_no"));
					info.setG1AccNo(ss.getString("personalloan.g1_acc_no"));
					info.setG1BankName(ss.getString("personalloan.g1_bank_name"));
					info.setG1BankBranch(ss.getString("personalloan.g1_bank_branch"));
					info.setG1BankIfsc(ss.getString("personalloan.g1_bank_ifsc"));
					
					info.setG2ChqNo(ss.getString("personalloan.g2_chq_no"));
					info.setG2AccNo(ss.getString("personalloan.g2_acc_no"));
					info.setG2BankName(ss.getString("personalloan.g2_bank_name"));
					info.setG2BankBranch(ss.getString("personalloan.g2_bank_branch"));
					info.setG2BankIfsc(ss.getString("personalloan.g2_bank_ifsc"));
					DbYashwant dby = new DbYashwant();
					info.setDsacode(dby.manageEmployeeId(ss.getString("dsacode") ));
					info.setDsaName(dsaNameById(ss.getString("dsacode"), conn));
					info.setCommission(ss.getDouble("commission"));
					info.setEmiType(ss.getString("emiType"));
					if(ss.getString("insurance_fee").trim().equals(""))
					{
						info.setInsuranceFee("0");
					}
					else
					{
						info.setInsuranceFee(ss.getString("insurance_fee"));
					}
					
					if(ss.getDate("emi_due_date")!=null)
					{
						info.setStrEmiDueDate(sf.format(ss.getDate("emi_due_date")));
						info.setEmiDate(ss.getDate("emi_due_date"));
					}
					
					info.setCenter(ss.getString("center"));
					info.setCenterName(centerNameById(ss.getString("center"),conn));
					
					info.setGuarantarName(firstApplicantNameBySHNo(ss.getString("firstguarantor"),conn));
					info.setGuarantarFatherName(shareHolderDetailByColumnName(ss.getString("firstguarantor"), "father_husband_name", conn));
					info.setGuarantorShareHno(ss.getString("firstguarantor"));
					info.setGuarantarAddress(shareHolderDetailByColumnName(ss.getString("firstguarantor"), "address", conn));
					
//					info.setSecGuarantarName(firstApplicantNameBySHNo(ss.getString("secondguarantor"),conn));
//					info.setSecGuarantarFatherName(shareHolderDetailByColumnName(ss.getString("secondguarantor"), "father_husband_name", conn));
//					info.setSecGuarantarAddress(shareHolderDetailByColumnName(ss.getString("secondguarantor"), "address", conn));
//					info.setSecGuarantorShareHno(ss.getString("secondguarantor"));
					
					String secondGuarantor = ss.getString("secondguarantor");

					if (secondGuarantor == null || secondGuarantor.trim().isEmpty())
					{
					    info.setSecGuarantarName("");
					    info.setSecGuarantarFatherName("");
					    info.setGuarantarAddress("");
					    info.setGuarantorShareHno("");
					}
					else
					{
						info.setSecGuarantarName(firstApplicantNameBySHNo(ss.getString("secondguarantor"),conn));
						info.setSecGuarantarFatherName(shareHolderDetailByColumnName(ss.getString("secondguarantor"), "father_husband_name", conn));
						info.setSecGuarantarAddress(shareHolderDetailByColumnName(ss.getString("secondguarantor"), "address", conn));
						info.setSecGuarantorShareHno(ss.getString("secondguarantor"));
					}
					
					// File Charge and Insurance Fee Editable
					if(ss.getString("personalloan.status").equalsIgnoreCase("notApprove") || ss.getString("personalloan.paidStatus").equalsIgnoreCase("paid"))
					{
						info.setDisable(true);
					}
					else
					{
						info.setDisable(false);
					}
					info.setNomineePersonalLoanName(shareHolderDetailByColumnName(shareHolderNo, "nominee_name", conn));
					info.setNomineeAddress(shareHolderDetailByColumnName(shareHolderNo, "nominee_address", conn));
					info.setNomRel(shareHolderDetailByColumnName(shareHolderNo, "nominee_relation", conn));
					info.setNomFaName(shareHolderDetailByColumnName(shareHolderNo, "first_applicantName", conn));
					info.setNomFatherName(shareHolderDetailByColumnName(shareHolderNo, "nominee_father", conn));
					info.setExtraAmt(ss.getDouble("personalloan.extra_amount"));
					info.setTotalAmount(info.getInstallAmount()+info.getExtraAmt());
					info.setNomBankName(ss.getString("nom_bank_name"));
					info.setNomBankBranch(ss.getString("nom_bank_branch"));
					info.setNomBankAccountNo(ss.getString("nom_acc_no"));
					info.setNomBankIfsc(ss.getString("nom_ifsc_code"));
					
					// to bind First EMI Date Variable 
					double amt=loanPaidAmountByUser("personalloan", info.getLoanNo(), conn);
					if(amt>0 || ss.getString("personalloan.status").equalsIgnoreCase("notApprove") || ss.getString("personalloan.paidStatus").equalsIgnoreCase("paid"))
					{
						info.setDisBtn(true);
					}
					else
					{
						info.setDisBtn(false);
					}
					
					info.setStamp(ss.getDouble("stamp"));
					info.setAdvanceTerm(ss.getInt("advance_emi_term"));
					info.setAdvanceEMIAmount(ss.getDouble("advance_emi_amount"));
					
					list.add(info);
				}
				
			}
			
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	
	public ArrayList<LoanInfo> secureLoanList(int branchId,String dsaCode, String loanSearchType, String searchType, String searchLoan, String securityType) 
    {
		String query="";
		int count=1;
		ArrayList<LoanInfo> list=new ArrayList<>();
		/*if(status.equalsIgnoreCase("All"))
		{
			query="select * from secure_loan INNER JOIN shareholder_info on secure_loan.shareholderno=shareholder_info.shareholderno where shareholder_info.branch_id='"+branchId+"'  order by secure_loan.loanNo asc";
		}
		else if(status.equalsIgnoreCase("Approve") || status.equalsIgnoreCase("notApprove") || status.equalsIgnoreCase("pending"))
		{
			query="select * from secure_loan INNER JOIN shareholder_info on secure_loan.shareholderno=shareholder_info.shareholderno  where secure_loan.status='"+status+"'  and shareholder_info.branch_id='"+branchId+"' order by secure_loan.loanNo asc";
		}
		else
		{
			query="select * from secure_loan INNER JOIN shareholder_info on secure_loan.shareholderno=shareholder_info.shareholderno  where (secure_loan.frequency='"+status+"' || secure_loan.frequency='"+status+".0') and shareholder_info.branch_id='"+branchId+"'  order by secure_loan.loanNo asc" ; 
		}*/
		
		query="select * from secure_loan INNER JOIN shareholder_info on secure_loan.shareholderno=shareholder_info.shareholderno where secure_loan.status!='notApprove' and  secure_loan.security_type ='"+securityType+"' ";
		
		if(searchLoan!=null && !searchLoan.equalsIgnoreCase("-1") && !searchLoan.equalsIgnoreCase("all") && !searchLoan.trim().equalsIgnoreCase(""))
		{
			query+=" and loanNo='"+searchLoan+"' ";
		}
		
		if(!searchType.equalsIgnoreCase("-1") && !searchType.equalsIgnoreCase("all"))
		{
			query+=" and (frequency='"+searchType+"' || frequency='"+searchType+".0') ";
		}
		
		if(!dsaCode.equalsIgnoreCase("-1") && !dsaCode.equalsIgnoreCase("all"))
		{
			query+=" and secure_loan.dsacode='"+dsaCode+"' ";
		}
		
		query+=" and paidStatus='"+loanSearchType+"' and shareholder_info.branch_id='"+branchId+"' order by secure_loan.loanNo asc";
		
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
			Statement stt=conn.createStatement();
			ResultSet ss=stt.executeQuery(query);
			while(ss.next())
			{
				if(!ss.getString("loanNo").contains("R"))
				{
					LoanInfo info=new LoanInfo();
				    
					String shareHolderNo=ss.getString("secure_loan.shareholderno");
					info.setSno(count++);
					info.setShareHolderNo(shareHolderNo);
					info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
					info.setRelation(ss.getString("shareholder_info.relation"));
					info.setFatherHusbandName(ss.getString("shareholder_info.father_husband_name"));
					info.setContactNo(ss.getString("shareholder_info.mobile"));
					info.setId(ss.getString("secure_loan.id"));
					info.setTerms(ss.getInt("terms"));
					info.setAddress(ss.getString("shareholder_info.address"));
					info.setEmiType(ss.getString("secure_loan.emiType"));
					info.setEmiMode(ss.getString("secure_loan.emi_mode"));
					info.setLoanAmount(ss.getString("loanAmount"));
					info.setLoanInterest(String.valueOf(Double.parseDouble(df.format(Double.valueOf(ss.getString("secure_loan.interest"))))));
					info.setDiscount(ss.getInt("discount"));
					info.setLoanTerm(ss.getString("secure_loan.terms"));
					info.setInstallAmount(ss.getDouble("secure_loan.emi"));
					info.setLoanType("Secure Loan");
					info.setRequestDate(ss.getDate("requestDate"));
					info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
					info.setFirstGuarantor(ss.getString("firstguarantor")+" - "+firstApplicantNameBySHNo(ss.getString("firstguarantor"),conn));
					info.setfGuarantor(ss.getString("firstguarantor"));
				     String gFName= DataBaseMethodsHemant.guarantorNameByShareHolderNo(info.getfGuarantor(),conn);
				     info.setGuarantorFName(gFName);
					info.setSecondGuarantor(ss.getString("secondguarantor")+" - "+firstApplicantNameBySHNo(ss.getString("secondguarantor"),conn));
					info.setIdProof(ss.getString("idproof"));
					info.setLoanNo(ss.getString("loanNo"));
					if(ss.getString("fileCharge").trim().equals(""))
					{
						info.setFileCharge("0");
					}
					else
					{
						info.setFileCharge(ss.getString("fileCharge"));
					}
					info.setReason(ss.getString("reason"));
					info.setRd_fdNo(ss.getString("RD_FD_no"));
					info.setFrequency(String.valueOf(ss.getInt("frequency")));
					info.setFrequencyVal(ss.getInt("frequency"));
					info.setFreqLable(frequencyLabel(info.getFrequency()));

					if(ss.getDate("approvalDate")!=null)
					{
						info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
						info.setEmiPaidDate(ss.getDate("approvalDate"));
					}
					
					
					if(ss.getDate("emi_due_date")!=null)
					{
						info.setEmiPaidDate(ss.getDate("emi_due_date"));
					}
					info.setStatus(ss.getString("secure_loan.status"));
					info.setAppChqNo(ss.getString("secure_loan.app_chq_no"));
					info.setAppAccNo(ss.getString("secure_loan.app_acc_no"));
					info.setAppBankName(ss.getString("secure_loan.app_bank_name"));
					info.setAppBankBranch(ss.getString("secure_loan.app_bank_branch"));
					
					info.setG1ChqNo(ss.getString("secure_loan.g1_chq_no"));
					info.setG1AccNo(ss.getString("secure_loan.g1_acc_no"));
					info.setG1BankName(ss.getString("secure_loan.g1_bank_name"));
					info.setG1BankBranch(ss.getString("secure_loan.g1_bank_branch"));
					
					info.setG2ChqNo(ss.getString("secure_loan.g2_chq_no"));
					info.setG2AccNo(ss.getString("secure_loan.g2_acc_no"));
					info.setG2BankName(ss.getString("secure_loan.g2_bank_name"));
					info.setG2BankBranch(ss.getString("secure_loan.g2_bank_branch"));
					info.setDsacode(ss.getString("dsacode"));
					info.setCommission(ss.getDouble("commission"));
					info.setEmiType(ss.getString("emiType"));
					if(ss.getString("insurance_fee").trim().equals(""))
					{
						info.setInsuranceFee("0");
					}
					else
					{
						info.setInsuranceFee(ss.getString("insurance_fee"));
					}
					
					info.setCenter(ss.getString("center"));
					info.setCenterName(centerNameById(ss.getString("center"),conn));
					
					info.setGuarantarName(firstApplicantNameBySHNo(ss.getString("firstguarantor"), conn));
					info.setGuarantarFatherName(shareHolderDetailByColumnName(ss.getString("firstguarantor"), "father_husband_name", conn));
					info.setAddress(shareHolderDetailByColumnName(ss.getString("firstguarantor"), "address", conn));
					info.setGuarantorShareHno(ss.getString("firstguarantor"));
					info.setGuarantarAddress(shareHolderDetailByColumnName(ss.getString("firstguarantor"), "address", conn));
					
					info.setSecGuarantarName(firstApplicantNameBySHNo(ss.getString("secondguarantor"), conn));
					info.setSecGuarantarFatherName(shareHolderDetailByColumnName(ss.getString("secondguarantor"), "father_husband_name", conn));
					info.setSecGuarantarAddress(shareHolderDetailByColumnName(ss.getString("secondguarantor"), "address", conn));
					info.setSecGuarantorShareHno(ss.getString("secondguarantor"));
					info.setBillAmount(ss.getDouble("mob_bill_amount"));
					info.setDownPayment(ss.getDouble("mob_down_payment"));
					info.setImeiNoI(ss.getString("mob_imei_no_1"));
					info.setImeiNoII(ss.getString("mob_imei_no_2"));
					info.setProduct(ss.getString("mob_product"));
					info.setDealer(ss.getString("mob_dealer"));
					info.setSecurityype(ss.getString("security_type"));
					info.setDptCharge(ss.getDouble("mob_dpt_charge"));
					info.setCardCharge(ss.getDouble("mob_card_fee"));
					
					if(ss.getString("secure_loan.status").equalsIgnoreCase("notApprove") || ss.getString("secure_loan.paidStatus").equalsIgnoreCase("paid"))
					{
						info.setDisable(true);
					}
					else
					{
						info.setDisable(false);
					}
					
					info.setNomineePersonalLoanName(shareHolderDetailByColumnName(shareHolderNo, "nominee_name", conn));
					info.setNomineeAddress(shareHolderDetailByColumnName(shareHolderNo, "nominee_address", conn));
					info.setNomRel(shareHolderDetailByColumnName(shareHolderNo, "nominee_relation", conn));
					System.out.println("nom re1 is:"+info.getNomRel());
					String nommRe1=DataBaseMethodsHemant.highMarkLabelByValues(info.getNomRel(), conn);
					System.out.println("nommRe1 is:"+nommRe1);
					info.setNomineeRel(nommRe1);
					info.setNomFaName(shareHolderDetailByColumnName(shareHolderNo, "first_applicantName", conn));
					info.setExtraAmt(ss.getDouble("secure_loan.extra_amount"));
					info.setFrequency(String.valueOf(ss.getInt("frequency")));
					info.setFreqLable(frequencyLabel(info.getFrequency()));
					if(ss.getDate("emi_due_date")!=null)
					{
						info.setStrEmiDueDate(sf.format(ss.getDate("emi_due_date")));
						info.setEmiDate(ss.getDate("emi_due_date"));
					}
				
					list.add(info);
				}
				
			}
			
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	
	public ArrayList<LoanInfo> businessLoanList(int branchId,String status) 
    {
		String query="";
		int count=1;
		ArrayList<LoanInfo> list=new ArrayList<>();
		if(status.equalsIgnoreCase("All"))
		{
			query="select * from business_loan INNER JOIN shareholder_info on business_loan.shareholderno=shareholder_info.shareholderno  where shareholder_info.branch_id='"+branchId+"'  order by business_loan.loanNo asc";
		}
		else if(status.equalsIgnoreCase("Approve") || status.equalsIgnoreCase("notApprove") || status.equalsIgnoreCase("pending"))
		{
			query="select * from business_loan INNER JOIN shareholder_info on business_loan.shareholderno=shareholder_info.shareholderno  where business_loan.status='"+status+"' and shareholder_info.branch_id='"+branchId+"'  order by business_loan.loanNo asc";
		}
		else
		{
			query="select * from business_loan INNER JOIN shareholder_info on business_loan.shareholderno=shareholder_info.shareholderno  where (business_loan.frequency='"+status+"' || business_loan.frequency='"+status+".0') and shareholder_info.branch_id='"+branchId+"' order by business_loan.loanNo asc" ; 
		}
		
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
			Statement stt=conn.createStatement();
			ResultSet ss=stt.executeQuery(query);
			while(ss.next())
			{
				if(!ss.getString("loanNo").contains("R"))
				{
					LoanInfo info=new LoanInfo();
					
					String shareHolderNo=ss.getString("business_loan.shareholderno");
					info.setSno(count++);
					info.setShareHolderNo(shareHolderNo);
					info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
					info.setRelation(ss.getString("shareholder_info.relation"));
					info.setFatherHusbandName(ss.getString("shareholder_info.father_husband_name"));
					info.setContactNo(ss.getString("shareholder_info.mobile"));
					info.setId(ss.getString("business_loan.id"));
					info.setTerms(ss.getInt("terms"));
					info.setAddress(ss.getString("shareholder_info.address"));
					info.setEmiType(ss.getString("business_loan.emiType"));
					info.setLoanAmount(ss.getString("loanAmount"));
					info.setLoanInterest(String.valueOf(Double.parseDouble(df.format(Double.valueOf(ss.getString("business_loan.interest"))))));
					info.setDiscount(ss.getInt("discount"));
					info.setLoanTerm(ss.getString("business_loan.terms"));
					info.setInstallAmount(ss.getDouble("business_loan.emi"));
					info.setLoanType("Secure Loan");
					info.setRequestDate(ss.getDate("requestDate"));
					info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
					info.setFirstGuarantor(ss.getString("firstguarantor")+" - "+firstApplicantNameBySHNo(ss.getString("firstguarantor"),conn));
					info.setSecondGuarantor(ss.getString("secondguarantor")+" - "+firstApplicantNameBySHNo(ss.getString("secondguarantor"),conn));
					info.setIdProof(ss.getString("idproof"));
					info.setLoanNo(ss.getString("loanNo"));
					if(ss.getString("fileCharge").trim().equals(""))
					{
						info.setFileCharge("0");
					}
					else
					{
						info.setFileCharge(ss.getString("fileCharge"));
					}
					info.setReason(ss.getString("reason"));
					info.setRd_fdNo(ss.getString("RD_FD_no"));
					info.setFrequency(String.valueOf(ss.getInt("frequency")));

					if(ss.getDate("approvalDate")!=null)
					{
						info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
						info.setEmiPaidDate(ss.getDate("approvalDate"));
					}
					
					
					if(ss.getDate("emi_due_date")!=null)
					{
						info.setEmiPaidDate(ss.getDate("emi_due_date"));
					}
					info.setStatus(ss.getString("business_loan.status"));
					info.setAppChqNo(ss.getString("business_loan.app_chq_no"));
					info.setAppAccNo(ss.getString("business_loan.app_acc_no"));
					info.setAppBankName(ss.getString("business_loan.app_bank_name"));
					info.setAppBankBranch(ss.getString("business_loan.app_bank_branch"));
					
					info.setG1ChqNo(ss.getString("business_loan.g1_chq_no"));
					info.setG1AccNo(ss.getString("business_loan.g1_acc_no"));
					info.setG1BankName(ss.getString("business_loan.g1_bank_name"));
					info.setG1BankBranch(ss.getString("business_loan.g1_bank_branch"));
					
					info.setG2ChqNo(ss.getString("business_loan.g2_chq_no"));
					info.setG2AccNo(ss.getString("business_loan.g2_acc_no"));
					info.setG2BankName(ss.getString("business_loan.g2_bank_name"));
					info.setG2BankBranch(ss.getString("business_loan.g2_bank_branch"));
					info.setDsacode(ss.getString("dsacode"));
					info.setCommission(ss.getDouble("commission"));
					info.setEmiType(ss.getString("emiType"));
					if(ss.getString("insurance_fee").trim().equals(""))
					{
						info.setInsuranceFee("0");
					}
					else
					{
						info.setInsuranceFee(ss.getString("insurance_fee"));
					}
					
					info.setCenter(ss.getString("center"));
					info.setCenterName(centerNameById(ss.getString("center"),conn));
					
					info.setGuarantarName(firstApplicantNameBySHNo(ss.getString("firstguarantor"), conn));
					info.setGuarantarFatherName(shareHolderDetailByColumnName(ss.getString("firstguarantor"), "father_husband_name", conn));
					info.setAddress(shareHolderDetailByColumnName(ss.getString("firstguarantor"), "address", conn));
					info.setGuarantorShareHno(ss.getString("firstguarantor"));
					info.setGuarantarAddress(shareHolderDetailByColumnName(ss.getString("firstguarantor"), "address", conn));
					
					info.setSecGuarantarName(firstApplicantNameBySHNo(ss.getString("secondguarantor"), conn));
					info.setSecGuarantarFatherName(shareHolderDetailByColumnName(ss.getString("secondguarantor"), "father_husband_name", conn));
					info.setSecGuarantarAddress(shareHolderDetailByColumnName(ss.getString("secondguarantor"), "address", conn));
					info.setSecGuarantorShareHno(ss.getString("secondguarantor"));
					
					if(ss.getString("business_loan.status").equalsIgnoreCase("notApprove") || ss.getString("business_loan.paidStatus").equalsIgnoreCase("paid"))
					{
						info.setDisable(true);
					}
					else
					{
						info.setDisable(false);
					}
					info.setNomineePersonalLoanName(shareHolderDetailByColumnName(shareHolderNo, "nominee_name", conn));
					info.setNomineeAddress(shareHolderDetailByColumnName(shareHolderNo, "nominee_address", conn));
					info.setNomRel(shareHolderDetailByColumnName(shareHolderNo, "nominee_relation", conn));
					info.setNomFaName(shareHolderDetailByColumnName(shareHolderNo, "first_applicantName", conn));
					info.setExtraAmt(ss.getDouble("business_loan.extra_amount"));
					
					list.add(info);
				}
				
			}
			
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	
	public ArrayList<LoanInfo> vehicleLoanList(int branchId,String status) 
    {
		String query="";
		int count=1;
		ArrayList<LoanInfo> list=new ArrayList<>();
		if(status.equals("All"))
		{
			query="select * from vechicleloan INNER JOIN shareholder_info on vechicleloan.shareholderno=shareholder_info.shareholderno where shareholder_info.branch_id='"+branchId+"'  order by vechicleloan.id desc";

		}
		else
		{
			query="select * from vechicleloan INNER JOIN shareholder_info on vechicleloan.shareholderno=shareholder_info.shareholderno where vechicleloan.status='"+status+"' and shareholder_info.branch_id='"+branchId+"' order by vechicleloan.id desc";

		}
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
			Statement stt=conn.createStatement();
			ResultSet ss=stt.executeQuery(selectQueWithBranch(query,branchId));
			while(ss.next())
			{
				if(!ss.getString("loanNo").contains("R"))
				{
					LoanInfo info=new LoanInfo();
					
					info.setSno(count++);
					info.setId(ss.getString("vechicleloan.id"));
					info.setShareHolderNo(ss.getString("vechicleloan.shareholderno"));
					info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
					info.setContactNo(ss.getString("shareholder_info.mobile"));
					info.setLoanAmount(ss.getString("loanAmount"));
					info.setLoanInterest(ss.getString("vechicleloan.interest"));
					info.setLoanType("Vehicle Loan");
					info.setDiscount(ss.getInt("discount"));
					info.setLoanTerm(ss.getString("vechicleloan.terms"));
					info.setInstallAmount(ss.getDouble("vechicleloan.emi"));
					info.setRequestDate(ss.getDate("requestDate"));
					info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
					info.setFirstGuarantor(ss.getString("firstguarantor"));
					info.setSecondGuarantor(ss.getString("secondguarantor"));
					info.setIdProof(ss.getString("idproof"));
					info.setLoanNo(ss.getString("loanNo"));
					info.setCategory(ss.getString("category"));
					info.setVechiclename(ss.getString("vechileName"));
					info.setVechileModel(ss.getString("model"));
					info.setEngineNo(ss.getString("engineno"));
					info.setMacNo(ss.getString("macNo"));
					info.setRd_fdNo(ss.getString("RD_FD_no"));
					info.setFrequency(String.valueOf(ss.getInt("frequency")));
					info.setFileCharge(ss.getString("fileCharge"));
					if(ss.getString("status").equals("pending"))
					{
						info.setDisable(false);
					}
					else
					{
						info.setDisable(true);
					}
					if(ss.getDate("approvalDate")!=null)
					{
						info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
					}


					info.setAppChqNo(ss.getString("vechicleloan.app_chq_no"));
					info.setAppAccNo(ss.getString("vechicleloan.app_acc_no"));
					info.setAppBankName(ss.getString("vechicleloan.app_bank_name"));
					info.setAppBankBranch(ss.getString("vechicleloan.app_bank_branch"));
					
					info.setG1ChqNo(ss.getString("vechicleloan.g1_chq_no"));
					info.setG1AccNo(ss.getString("vechicleloan.g1_acc_no"));
					info.setG1BankName(ss.getString("vechicleloan.g1_bank_name"));
					info.setG1BankBranch(ss.getString("vechicleloan.g1_bank_branch"));
					
					info.setG2ChqNo(ss.getString("vechicleloan.g2_chq_no"));
					info.setG2AccNo(ss.getString("vechicleloan.g2_acc_no"));
					info.setG2BankName(ss.getString("vechicleloan.g2_bank_name"));
					info.setG2BankBranch(ss.getString("vechicleloan.g2_bank_branch"));

					info.setDsacode(ss.getString("dsacode"));
					info.setCommission(ss.getDouble("commission"));
					info.setEmiType(ss.getString("emiType"));
					info.setInsuranceFee(ss.getString("insurance_fee"));
					info.setCenter(ss.getString("center"));
					info.setCenterName(centerNameById(ss.getString("center"),conn));
					
					list.add(info);
				}
				
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public ArrayList<CenterInfo> allCenterInfo(int branchId,String dsaCode,Connection conn) 
	{    
		int number = 0;
		String query="";
		ArrayList<CenterInfo> centerList=new ArrayList<>();
		int i=0;
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			 if(dsaCode.equalsIgnoreCase("all"))
				{
					query="select * from center";
				}
				else
				{
					query="select * from center where dsacode='"+dsaCode+"' " ;
				}
			rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				CenterInfo info=new CenterInfo();
				
				info.setId(rr.getString("id"));
				info.setCenterName(rr.getString("centerName"));
				info.setCenterCode(rr.getString("centerCode"));
				info.setDescription(rr.getString("description"));
				info.setGroupNo(groupLoanNoCenterWise(info.getId(), conn));
				info.setTotalLoan(totalLoanCenterWise(branchId,info.getId(),conn));
				info.setDsacode(rr.getString("dsacode"));
				info.setDsaName(dsaNameById(rr.getString("dsacode"), conn));
				info.setSno(++i);
				if(info.getTotalLoan()>0)
				{
					info.setDisBtn(true);
				}
				info.setCenterLeaderName(rr.getString("center_leader_name"));
				info.setCenterTime(rr.getString("center_time"));
				centerList.add(info); 
				
				number++;
			}
			System.out.println("toatl center :"+number);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return centerList;
	}
	
	public CenterInfo selectedCenterInfo(String center) 
	{
		CenterInfo info=new CenterInfo();
		Statement st=null;
		ResultSet rr=null;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			 st=conn.createStatement();
			 String query="select * from center where id='"+center+"' " ;
			rr=st.executeQuery(query);
			if(rr.next())
			{
				info.setId(rr.getString("id"));
				info.setCenterName(rr.getString("centerName"));
				info.setCenterCode(rr.getString("centerCode"));
				info.setDescription(rr.getString("description"));
				info.setGroupNo(groupLoanNoCenterWise(info.getId(), conn));
				//info.setTotalLoan(totalLoanCenterWise(branchId,info.getId(),conn));
				info.setDsacode(rr.getString("dsacode"));
				info.setDsaName(dsaNameById(rr.getString("dsacode"), conn));
				info.setCenterLeaderName(rr.getString("center_leader_name"));
				info.setCenterTime(rr.getString("center_time"));
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return info;
	}

	private String groupLoanNoCenterWise(String center, Connection conn) 
	{
		String groupNo="";
		try
		{
			Statement st=conn.createStatement();
			String qq="select loanNo from grouploan where center='"+center+"' and status='Approve' and paidStatus='unpaid' group by loanNo " ;
			////System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				if(groupNo.equalsIgnoreCase(""))
				{
					groupNo=rr.getString("loanNo");
				}
				else
				{
					groupNo+=", "+rr.getString("loanNo");
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return groupNo;
	}
	private int totalLoanCenterWise(int branchId,String string, Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select count(*) from grouploan where center='"+string+"' and status='Approve' and paidStatus='unpaid' " ;
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getInt("count(*)");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}

	public ArrayList<CenterInfo> allPlanInfo(int branchId,String planType) 
	{
		String query="";
		ArrayList<CenterInfo> list=new ArrayList<>();
		int i=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(planType.equals("all"))
			{
				query="select * from plans where status='active'  ";
			}
			else
			{
				query="select * from plans where status='active' and type='"+planType+"' ";
			}
			query=selectQueWithBranch(query,branchId)+" order by idplans desc";
			ResultSet rr=st.executeQuery(query);
			while(rr.next())
			{
				CenterInfo info=new CenterInfo();
				
				info.setId(rr.getString("idplans"));
				info.setType(rr.getString("type"));
				info.setPlan(rr.getString("plan"));
				info.setInterest(rr.getString("interest"));
				info.setFileChargePlan(rr.getDouble("file_charge_plan"));
				info.setInsuranceFeePlan(rr.getDouble("insurance_fee_plan"));
				info.setProcessingChargePlan(rr.getDouble("processing_charge_plan"));
				info.setSno(++i);
				info.setPenaltyAnnual(rr.getDouble("penalty_annual"));
				info.setPenaltyBasis(rr.getString("penalty_basis"));
				boolean val=chkplan(branchId,rr.getString("idplans"), conn);
				if(val==true)
				{
					info.setStatus("true");
				}
				else
				{
					info.setStatus("false");
				}
				
				info.setLoanAmount(rr.getInt("loan_amount"));
				info.setTerms(rr.getInt("terms"));
				info.setFrequency(rr.getInt("frequency"));
				info.setEmi(rr.getInt("emi"));
				info.setEmiType(rr.getString("emi_type"));
				
				list.add(info);
			}
		}
		catch(Exception ex)
		{
		ex.printStackTrace();
		}
		return list;
	}
	
	public CenterInfo selectedPlanInfo(String planId) 
	{
		CenterInfo info=new CenterInfo();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from plans where status='active' and idplans='"+planId+"' ";
			ResultSet rr=st.executeQuery(query);
			if(rr.next())
			{
				info.setId(rr.getString("idplans"));
				info.setType(rr.getString("type"));
				info.setPlan(rr.getString("plan"));
				info.setInterest(rr.getString("interest"));
				info.setInterestRate(rr.getDouble("interest"));
				info.setFileChargePlan(rr.getDouble("file_charge_plan"));
				info.setInsuranceFeePlan(rr.getDouble("insurance_fee_plan"));
				info.setPenaltyAnnual(rr.getDouble("penalty_annual"));
				info.setPenaltyBasis(rr.getString("penalty_basis"));
				info.setLoanAmount(rr.getInt("loan_amount"));
				info.setTerms(rr.getInt("terms"));
				info.setFrequency(rr.getInt("frequency"));
				info.setEmi(rr.getInt("emi"));
				info.setEmiType(rr.getString("emi_type"));
			}
		}
		catch(Exception ex)
		{
		ex.printStackTrace();
		}
		return info;
	}
	
	// confusion
	public boolean chkplan(int branchId,String id, Connection conn)
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="(select plan_no from customer_info where plan_no='"+id+"' and branch_id='"+branchId+"') union(select plan_no from personalloan where plan_no='"+id+"' and branch_id='"+branchId+"')";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
		 e.printStackTrace();fileCreation(e.getMessage());
		}
		return false;
	}
	
	public int updateCenter(String id, String centerName, String centerCode,String descriptoin, String dsaCode, String centerLeaderName, String centerTime, Connection conn)
	{
		Statement st=null;
		try
		{
	         st=conn.createStatement();
		     String query="update center set centerName='"+centerName+"', centerCode='"+centerCode+"', description='"+descriptoin+"', dsacode='"+dsaCode+"',"
		     		+ " center_leader_name='"+centerLeaderName+"', center_time='"+centerTime+"' where id='"+id+"' ";	
		     int i=st.executeUpdate(query);
		     if(i==1)
		     {
		    	 dataInsertInQueryTable(query, conn);
		    	return 1;
		     }
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	public int updatePlan(String id, String type, String plan,String interest, double fileChargePlan, double insuranceFeePlan, double penaltyAnnual,
			String penaltyBasis, int loanAmount, int terms, int emi, int frequency, String emiType, double processingChargePlan)
	{
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
	         Statement stt=conn.createStatement();
		     String query="update plans set type='"+type+"', plan='"+plan+"', interest='"+interest+"', file_charge_plan='"+fileChargePlan+"',"
		     		+ " insurance_fee_plan='"+insuranceFeePlan+"', penalty_annual='"+penaltyAnnual+"', penalty_basis='"+penaltyBasis+"', loan_amount="+loanAmount+""
		     				+ ", terms="+terms+", emi="+emi+", frequency="+frequency+", emi_type='"+emiType+"', processing_charge_plan='"+processingChargePlan+"' where idplans='"+id+"' ";
		     //System.out.println(query);
		     int i=stt.executeUpdate(query);
		     if(i==1)
		     {
		    	 dataInsertInQueryTable(query, conn);
		    	return 1;
		     }
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public int deleteCenter(String id) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
	         Statement stt=conn.createStatement();
		     String query="delete from center where id='"+id+"' ";	
		     int i=stt.executeUpdate(query);
		     if(i==1)
		     {
		    	 dataInsertInQueryTable(query, conn);
		    	 return 1;
		     }
		     
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}

		return 0;
	}  
	
	public int deletePlan(String id) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
	         Statement stt=conn.createStatement();
		     String query="delete from plans where idplans='"+id+"' ";
		     int i=stt.executeUpdate(query);
		     if(i==1)
		     {
		    	 dataInsertInQueryTable(query, conn);
		    	 return 1;
		     }
		     
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}

		return 0;
	}
	
	public String centerNameCodeById(String id, Connection conn) 
	{			
		String name="";
		Statement stt=null;
		ResultSet rr=null;
		try
		{
	         stt=conn.createStatement();
		     String query="select * from center where id='"+id+"' ";	
		     rr=stt.executeQuery(query);
		     if(rr.next())
		     {
		    	 name=rr.getString("centerName")+"/"+rr.getString("centerCode");
		    	 System.out.println(name);
		     }		     
		} 
		 
		
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return name;
	}  
	
	/*public ArrayList<UserInfo> allShareHolders(Connection conn) 
	{
		ArrayList<UserInfo> list = new ArrayList<>();
		int i = 1;
		Statement stt=null;
		ResultSet ss =null;
		try 
		{
			stt = conn.createStatement();
			String query = "select * from shareholder_info where noofShare>0 order by id desc";
			ss= stt.executeQuery(selectQueWithBranch(query,branchId));
			while (ss.next()) 
			{
				UserInfo uu = new UserInfo();
				//uu = userInfoById(ss);
				uu.setId(ss.getString("id"));
				uu.setFirst_applicantName(ss.getString("first_applicantName"));
				uu.setContactNo(ss.getString("mobile"));
				uu.setShareHolderNo(ss.getString("shareholderno"));
				uu.setFather_husband_name(ss.getString("father_husband_name"));
				uu.setOffice_application_no(ss.getString("office_application_no"));
				uu.setSno(i++);
				if(ss.getString("transfer_from").equals(""))
				{
					uu.setTransferFrom("");
					uu.setDisable(true);
				}
				else
				{
					uu.setTransferFrom(ss.getString("transfer_from"));
					uu.setDisable(false);
				}
				
				filePathDetail(conn);
				if(onlineFileViewPath==null || onlineFileViewPath.trim().equals(""))
				{
					uu.setApplicant_photo(ss.getString("applicant_photo"));
				}
					else
					{
						uu.setApplicant_photo(onlineFileViewPath+ss.getString("applicant_photo"));
				}
				if(ss.getString("account_status").equals("inactive"))
				{
					uu.setShowReportType(true);
				}
				else
				{
					uu.setShowReportType(false);
				}
				list.add(uu);
			}
		} 
		catch (Exception e) {
            e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(ss!=null)
				{
					ss.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}

		return list;
	}*/
	
	
	// New method develop by CHETAN GARG update due to Share Return
	public ArrayList<UserInfo> allShareHolders(int branchId,String dsaType, Connection conn)
	{
		boolean shareCheck=checkShareAllotmentFromMember();
		String query ="";
		ArrayList<UserInfo> list = new ArrayList<>();
		int i = 1;
		Statement stt=null;
		ResultSet ss =null;
		try
		{
			stt = conn.createStatement();
			if(shareCheck==true && dsaType.equalsIgnoreCase("all"))
			{
				query = "select * from shareholder_info a where noofShare >0 ";
			}
			else if(shareCheck==false && dsaType.equalsIgnoreCase("all"))
			{
				query = "select * from shareholder_info ";
			}
			else if(shareCheck==true && !dsaType.equalsIgnoreCase("all"))
			{
				query = "select * from shareholder_info a where noofShare >0 and dsacode='"+dsaType+"' ";
			}
			else if(shareCheck==false && !dsaType.equalsIgnoreCase("all"))
			{
				query = "select * from shareholder_info where dsacode='"+dsaType+"' ";
			}
			query=selectQueWithBranch(query,branchId)+" order by id desc"; 
			ss= stt.executeQuery(query);
			while (ss.next())
			{
				UserInfo uu = new UserInfo();
				uu.setId(ss.getString("id"));
				uu.setOffice_date(ss.getDate("office_date"));
				uu.setFirst_applicantName(ss.getString("first_applicantName"));
				uu.setContactNo(ss.getString("mobile"));
				uu.setAltMobileNo(ss.getString("alt_mobile_no"));
				
				uu.setShareHolderNo(ss.getString("shareholderno"));
				uu.setFather_husband_name(ss.getString("father_husband_name"));
				uu.setOffice_application_no(ss.getString("office_application_no"));
				uu.setTotalAmount(ss.getDouble("totalAmount"));
				uu.setCrNo(ss.getString("crNo"));
				uu.setAddress(ss.getString("address"));
				uu.setNoOfShare(ss.getInt("noofShare"));
				uu.setTransferFrom(ss.getString("transfer_from"));
				uu.setAccount_status(ss.getString("account_status"));
				uu.setSno(i++);
				
				
//				if(ss.getString("transfer_from").equals(""))
//				{
//					uu.setTransferFrom("");
//					uu.setDisable(true);
//				}
//				else
//				{
//					uu.setTransferFrom(ss.getString("transfer_from"));
//					uu.setDisable(false);
//				}
			
				filePathDetail(conn);
				if(onlineFileViewPath==null || onlineFileViewPath.trim().equals(""))
				{
					uu.setApplicant_photo(ss.getString("applicant_photo"));
				} 
				else
				{
					uu.setApplicant_photo(onlineFileViewPath+ss.getString("applicant_photo"));
				}
				if(ss.getString("account_status").equals("inactive"))
				{
					uu.setShowReportType(true);
					uu.setCheckForReturnShare(false);
				}
				else
				{
					uu.setShowReportType(false);
					uu.setCheckForReturnShare(true);
				}
				uu.setDsaCode(ss.getString("dsacode"));
				uu.setCenterId(ss.getString("center"));
				uu.setCenterName(centerNameCodeById(ss.getString("center"), conn));
				uu.setCreditLimit(ss.getDouble("credit_limit"));
				list.add(uu);
			}
		}
		catch (Exception e) {
		           e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
			if(stt!=null)
			{
			stt.close();
			}
			if(ss!=null)
			{
			ss.close();
			}
			} catch (Exception e2) {
			// TODO: handle exception
			}
		}
	
		return list;
	}
	
	// New method develop by CHETAN GARG for member center wise jan 2024
	public ArrayList<UserInfo> centerAllotListMethod(int branchId,String center, Connection conn)
	{
		String query ="";
		ArrayList<UserInfo> list = new ArrayList<>();
		int i = 1;
		Statement stt=null;
		ResultSet ss =null;
		try
		{
			stt = conn.createStatement();
			query = "select * from shareholder_info where center='"+center+"' ";
			query=selectQueWithBranch(query,branchId);  //+" order by id desc";
			ss= stt.executeQuery(query);
			while (ss.next())
			{
				UserInfo uu = new UserInfo();
				uu.setId(ss.getString("id"));
				uu.setFirst_applicantName(ss.getString("first_applicantName"));
				uu.setContactNo(ss.getString("mobile"));
				uu.setShareHolderNo(ss.getString("shareholderno"));
				uu.setFather_husband_name(ss.getString("father_husband_name"));
				uu.setAddress(ss.getString("address"));
				uu.setSno(i++);
				uu.setDsaCode(ss.getString("dsacode"));
				uu.setCenterId(ss.getString("center"));
				uu.setCenterName(centerNameCodeById(ss.getString("center"), conn));
				
				list.add(uu);
			}
		}
		catch (Exception e) {
		           e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
			if(stt!=null)
			{
			stt.close();
			}
			if(ss!=null)
			{
			ss.close();
			}
			} catch (Exception e2) {
			// TODO: handle exception
			}
		}
		return list;
	}
		
	
	public UserInfo allShareHoldersForView(String shareHolderNo, UserInfo info) 
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		int i = 1;
		Statement stt=null;
		ResultSet ss =null;
		
		try 
		{   
			stt = conn.createStatement();
			String query="select * from shareholder_info where shareholderno='"+shareHolderNo+"' ";
			ss= stt.executeQuery(query);
			if (ss.next()) 
			{
				
				info = userInfoById(ss,conn);
				info .setSno(i++);
				
				if(ss.getString("account_status").equals("inactive"))
				{
					info .setShowReportType(true);
				}
				else
				{
					info .setShowReportType(false);
				}
				
			}
		} 
		catch (Exception e) {
            e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try 
			{
				if(stt!=null)
				{
					stt.close();
				}
				if(ss!=null)
				{
					ss.close();
				}
			} 
			catch (Exception e2) {
				// TODO: handle exception
			}
		}

		return info ;
	}
	
	public ArrayList<UserInfo> allShareHoldersOfParticularTransferor(int branchId,String shno) 
	{
		ArrayList<UserInfo> list = new ArrayList<>();
		int i = 1;
		try (Connection conn = DataBaseConnection.JAVAConnection();) 
		{
			Statement stt = conn.createStatement();
			String query = "select * from shareholder_info where transfer_from='"+shno+"'";
			ResultSet ss = stt.executeQuery(selectQueWithBranch(query,branchId));
			while (ss.next()) 
			{
				UserInfo uu = new UserInfo();
				uu = userInfoById(ss, conn);
				uu.setSno(i++);
				if(ss.getString("account_status").equals("inactive"))
				{
					uu.setShowReportType(true);
				}
				else
				{
					uu.setShowReportType(false);
				}
				list.add(uu);
			}
		} 
		catch (Exception e) {
            e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public String userAuth(String username, String password, Connection conn)
	{
		if(username.contains("'") || password.contains("'"))
		{
			return "";
		}
		try
		{ 
			Statement st=conn.createStatement();
			String query="select * from login where userid='"+username+"'and password='"+password+"' and status='active' ";
			ResultSet ss=st.executeQuery(query);
			if(ss.next())
			{
				if(ss.getString("type").equals("employee"))
				{
					boolean check=new DataBaseMethodsDuplicate().checkUserNameDuplicacy(username);
					if(check==true)
					{
						return ss.getString("type");
					}
					else
					{
						return "";
					}
				}
				else
				{
					return ss.getString("type");
				}
				
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}

	// Add New Saving Account
	public int addSavingAcount(int branchId,String shareHolderNo, String accountNo,Date requestDate, double amount, double interest, double minBal,
	int minDaysForClose, double accCloseCharge, String dsaCode, String center) 
	{
		HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		String userId=(String) ss1.getAttribute("username");
		
		Timestamp ss=new Timestamp(requestDate.getTime());
		try(Connection conn=DataBaseConnection.JAVAConnection();)
		{
			Statement stt=conn.createStatement();
			String query="insert into savingaccount(shareHolderNo, accountNo, openDate, amount, interest, minBal, minDayForClose,"
			+" accCloseCharge,user_id, dsacode, branch_id,center) values('"+shareHolderNo+"','"+accountNo+"','"+ss+"','"+amount+"','"+interest+"','"+minBal+"','"+minDaysForClose+"',"
					+ "'"+accCloseCharge+"','"+userId+"','"+dsaCode+"', '"+branchId+"','"+center+"')";
			int i=stt.executeUpdate(query);
		    if(i>=1)
		    {
		    	dataInsertInQueryTable(query, conn);
		    	return 1;
		    }
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public String shareHolderNoBySavingAccountNO(String accno) 
	{
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq = "select shareHolderNo from savingaccount where accountNo='"+accno+"'";
		
			ResultSet rs = st.executeQuery(qq);
			if(rs.next()) 
			{
			   return rs.getString("shareHolderNo")	;
			}
		}
		catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}
	
	// Return Share Holder No using Loan No
	public String shareHolderNoByLoanNo(String accno) 
	{
		String table="",qq="";
		if(accno.contains("VL"))
		{
			table="vechicleloan";
		}
		
		else if(accno.contains("GL"))
		{
			table="grouploan";
		}
		
		else if(accno.contains("BL"))
		{
			table="business_loan";
		}
		
		else if(accno.contains("SL"))
		{
			table="secure_loan";
		}
		
		else if(accno.contains("PPL"))
		{
			table="propertyloan";
		}
		else
		{
			table="personalloan";
		}
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			if(!table.equals(""))
			{
				Statement st = con.createStatement();
				if(table.equals("grouploan"))
				{
					qq = "select teamLeader from "+table+" where sub_loan_no='"+accno+"' ";
				}
				else
				{
					qq = "select shareholderno from "+table+" where loanNo='"+accno+"' ";
				}
				ResultSet rs = st.executeQuery(qq);
				if(rs.next()) 
				{
					if(table.equals("grouploan"))
					{
						return rs.getString("teamLeader");
					}
				   return rs.getString("shareholderno")	;
				}
			}
		}
		catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
		
	}
	
	// Return Share Holder No using Loan No
	public String shareHolderNoByLoanNoLoanType(String accno, String table) 
	{
		String qq="";
		
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			if(!table.equals(""))
			{
				Statement st = con.createStatement();
				if(table.equals("grouploan"))
				{
					qq = "select teamLeader from "+table+" where sub_loan_no='"+accno+"' ";
				}
				else
				{
					qq = "select shareholderno from "+table+" where loanNo='"+accno+"' ";
				}
				ResultSet rs = st.executeQuery(qq);
				if(rs.next()) 
				{
					if(table.equals("grouploan"))
					{
						return rs.getString("teamLeader");
					}
				   return rs.getString("shareholderno")	;
				}
			}
		}
		catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
		
	}
	
	// to Find the Share Holder no. using Deposit (DD/RD/FD) No.
	public String shareHolderNoByRdFdNo(String accno) 
	{
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq = "select shareHolderNo from customer_info where user_no='"+accno+"'";
		
			ResultSet rs = st.executeQuery(qq);
			if(rs.next()) 
			{
			   return rs.getString("shareHolderNo")	;
			}
		}
		catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}
	
	
	// Amount Deposit in Saving Account 
	public int userDeposit(int branchId,String accno, String amount, Date currentDate,String paymentMode, String chequeNo,Date chequeDate,String bankName,String status, 
			String submittedBankName, String remark, String dsaCode)
	{
		int j=0;
		if(accno!=null && !accno.trim().equalsIgnoreCase(""))
		{
			Timestamp crdt=null,chDate=null;
			crdt=new Timestamp(currentDate.getTime());
			crdt.setHours(0);
			crdt.setMinutes(0);
			crdt.setSeconds(0);
			crdt.setNanos(0);
			
			HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			String userId=(String) ss1.getAttribute("username");
			
			if(chequeDate!=null)
			{
				chDate=new Timestamp(chequeDate.getTime());
			}
			
			String chequeStatus="";
			if(paymentMode.equalsIgnoreCase("Cash") || paymentMode.equalsIgnoreCase("Transfer"))
			{
				chequeStatus="cleared";
			}
			else
			{
				chequeStatus="uncleared";
			}
			
			try(Connection conn=DataBaseConnection.JAVAConnection();) 
			{
				String query="insert into customer_deposit(account_no, amount, date,payment_mode, cheque_dd_no, cheque_dd_date,from_bank_name,status,"
						+ "transfer_to_bank,chequeStatus,user_id, remark,branch_id, dsa_code) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				PreparedStatement st1=conn.prepareStatement(query);
				st1.setString(1,accno);
				st1.setString(2,amount);
				st1.setTimestamp(3,crdt);
				st1.setString(4,paymentMode);
				st1.setString(5,chequeNo);
				st1.setTimestamp(6,chDate);
				st1.setString(7,bankName);
				st1.setString(8, status);
				st1.setString(9, submittedBankName);
				st1.setString(10, chequeStatus);
				st1.setString(11, userId);
				st1.setString(12, remark);
				st1.setInt(13, branchId);
				st1.setString(14, dsaCode);
				int i=st1.executeUpdate();
				if(i>=1)
				{
					dataInsertInQueryTable(String.valueOf(st1), conn);
					j++;
				}
			}
			catch (Exception e) 
			{
				 e.printStackTrace();fileCreation(e.getMessage());
			}
		}	
		return j;
	}
	
	//  Entry Insert, of Amount Withdrawal from Saving Account by user 
	public int userWithdrwal(int branchId,String accno,String amount,Date currentDate,String paymentMode, String chequeNo,Date chequeDate, String bankName, String bankBranch, 
			String status1, String remark, String dsaCode)
	{
		int j=0;
		if(accno!=null && !accno.trim().equalsIgnoreCase(""))
		{
			String userId=userId();
			String status="";
			Timestamp crdt=null,chDate=null;
			crdt=new Timestamp(currentDate.getTime());
			crdt.setHours(0);crdt.setMinutes(0);crdt.setSeconds(0);crdt.setNanos(0);
			if(chequeDate!=null)
			{
				chDate=new Timestamp(chequeDate.getTime());
			}
			
			if(paymentMode.equalsIgnoreCase("Cash") || paymentMode.equalsIgnoreCase("Transfer"))
			{
				status="cleared";
				bankName="N/A";
			}
			else
			{
				status="uncleared";
			}
			
			
			try(Connection conn=DataBaseConnection.JAVAConnection();) 
			{
				String query="insert into customer_withdrwal(account_no,amount,date,payment_mode,cheque_dd_no,cheque_dd_date,from_bank_name,status,bankBranch,chequeStatus, "
						+ "user_id, remark,branch_id, dsa_code) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				PreparedStatement st1=conn.prepareStatement(query);
				st1.setString(1,accno);
				st1.setString(2,amount);
				st1.setTimestamp(3,crdt);
				st1.setString(4,paymentMode);
				st1.setString(5,chequeNo);
				st1.setTimestamp(6,chDate);
				st1.setString(7,bankName);
				st1.setString(8, status1);
				st1.setString(9, bankBranch);
				st1.setString(10, status);
				st1.setString(11, userId);
				st1.setString(12, remark);
				st1.setInt(13, branchId);
				st1.setString(14, dsaCode);
				// //System.out.println(String.valueOf(st1));
				int i=st1.executeUpdate();
				if(i>=1)
				{
					dataInsertInQueryTable(String.valueOf(st1) , conn);
					j++;
				}
			}
			catch (Exception e) 
			{
				 e.printStackTrace();fileCreation(e.getMessage());
			}
		}	
		return j;
	}
	
	// Return the Current Balace of selected Saving Account No.
	public double acconuntHolderAmountByAccountNo(String accno) 
	{
	    try(Connection conn=DataBaseConnection.JAVAConnection();)
	    {
		   Statement stt=conn.createStatement();
		   String query="select amount from savingaccount where accountNo='"+accno+"'";
		   ResultSet ss=stt.executeQuery(query);
		   if(ss.next())
		   {
			   return ss.getDouble("amount");
		   }
		} 
	    catch (Exception e) 
	    {
			 e.printStackTrace();fileCreation(e.getMessage());
		}	
		return 0;
	}

	// Update the saving Account Balance
	public void updateSavingAmountByAccountNo(String accno, Double newAmount)
	{
		try(Connection conn=DataBaseConnection.JAVAConnection()) 
		{
			Statement stt=conn.createStatement();
			String query="update savingaccount set amount='"+newAmount+"' where accountNo='"+accno+"' and accountStatus='open'";
			stt.executeUpdate(query);
			//dataInsertInQueryTable(query, conn);
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage()); 
		}
	}

	// Update the Promotor Account Balance
	public void updatePromotorAmountByID(String id, Double newAmount)
	{
		try(Connection conn=DataBaseConnection.JAVAConnection()) 
		{
			Statement stt=conn.createStatement();
			String query="update promotors set amount='"+newAmount+"' where id='"+id+"' and status='active'";
			
			stt.executeUpdate(query);
			//dataInsertInQueryTable(query, conn);
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage()); 
		}
	}
 
	/*public void calculateSavingAmountDetails(String accountNo)
	{
		ArrayList<SavingAccountInfo> depositAmount,withdrwalAmount,finalList=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection();)
		{
		    Statement stt=conn.createStatement();
		    String query="select * from savingaccount where accountNo='"+accountNo+"'";
		    ResultSet ss=stt.executeQuery(selectQueWithBranch(query,branchId));
		    if(ss.next())
		    {
	            if(ss.getDate("updateDate")!=null)
	            {
	            	Date updateDate=ss.getDate("updateDate");
	            	depositAmount=depositValueBetweenDate(accountNo,updateDate);
	            	
	            	SavingAccountInfo ll=new SavingAccountInfo();
	   			 	ll.setAccountNo(ss.getString("accountNo"));
	   			 	ll.setEntryDate(ss.getDate("updateDate"));
	   			 	ll.setAmount(ss.getDouble("amount"));
	   			 	ll.setFinalAmount(ll.getAmount());
	   			 	ll.setStatus("deposit");
	   			 	depositAmount.add(ll);
	   			 	
	            	withdrwalAmount=withdrwalValueBetweenDate(accountNo, updateDate);                  	
	            }
	            else
	            {
	            	 Date updateDate=ss.getDate("openDate");
	            	 depositAmount=depositValueBetweenDate(accountNo,updateDate);
	            	 
	            	 SavingAccountInfo ll=new SavingAccountInfo();
		   			 ll.setAccountNo(ss.getString("accountNo"));
		   		 	 ll.setEntryDate(ss.getDate("openDate"));
		   		 	 ll.setAmount(ss.getDouble("amount"));
		  			 ll.setFinalAmount(ll.getAmount());
		  			 ll.setStatus("deposit");
		   			 depositAmount.add(ll);
	            	 withdrwalAmount=withdrwalValueBetweenDate(accountNo, updateDate);
	            }
	             	
	            finalList.addAll(depositAmount);
	            finalList.addAll(withdrwalAmount);
	            Collections.sort(finalList); 
	            calculateMainValue(finalList,ss.getDouble("interest"));
		    }	
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}   
	}*/

	/*public ArrayList<SavingAccountInfo> depositValueBetweenDate(String accountNo, Date updateDate) 
	{
		 ArrayList<SavingAccountInfo> list=new ArrayList<>(); 
		 Timestamp uDate=new Timestamp(updateDate.getTime());
		 try(Connection conn=DataBaseConnection.JAVAConnection();) 
         {
			 Statement stt=conn.createStatement();
			 String query="select * from customer_deposit where account_no='"+accountNo+"' and date>='"+uDate+"'";
			 ResultSet ss=stt.executeQuery(selectQueWithBranch(query,branchId));
			 while(ss.next())
			 {
				SavingAccountInfo info=new SavingAccountInfo();
			    info.setAccountNo(ss.getString("account_no"));
			    info.setEntryDate(ss.getDate("date"));
			    info.setAmount(ss.getDouble("amount"));
			   	info.setFinalAmount(info.getAmount());
			    info.setStatus("deposit");
		        list.add(info);
			 }
         }
         catch (Exception e) 
         {
        	  e.printStackTrace();fileCreation(e.getMessage());
         }
		 return list;
	}

	public ArrayList<SavingAccountInfo> withdrwalValueBetweenDate(String accountNo, Date updateDate) 
	{
		 ArrayList<SavingAccountInfo> list=new ArrayList<>(); 
		 Timestamp uDate=new Timestamp(updateDate.getTime());
		 try(Connection conn=DataBaseConnection.JAVAConnection();) 
         {
			 Statement stt=conn.createStatement();
			 String query="select * from customer_withdrwal where account_no='"+accountNo+"' and date>='"+uDate+"'";
			 ResultSet ss=stt.executeQuery(selectQueWithBranch(query,branchId));
			 while(ss.next())
			 {
				SavingAccountInfo info=new SavingAccountInfo();
			    info.setAccountNo(ss.getString("account_no"));
			    info.setEntryDate(ss.getDate("date"));
			    info.setAmount(ss.getDouble("amount"));
			   	info.setFinalAmount(info.getAmount());
			    info.setStatus("withdrwal");
		        list.add(info);
			 }
         }
         catch (Exception e) 
         {
        	  e.printStackTrace();fileCreation(e.getMessage());
         }
		 return list;
	}*/
	 
	public void calculateMainValue(int branchId,ArrayList<SavingAccountInfo> finalList, double rate)
	{

		 double inter=0;
		 for(int i=0;i<finalList.size();i++)
		 {
			 if(i!=0)
			 {
				 Date startDate=finalList.get(i-1).getEntryDate();
				 Date endDate=finalList.get(i).getEntryDate();
				 if(startDate.getMonth()==endDate.getMonth())
				 {
					 long day=getDifferenceDays(startDate, endDate);
					 double interest=Double.parseDouble(df.format(finalList.get(i-1).getFinalAmount()*day*rate/36500));
					 inter+=interest;
					 finalList.get(i-1).setInterest(interest);
					 if(finalList.get(i).getStatus().equals("deposit"))
					 {
						 finalList.get(i).setFinalAmount(finalList.get(i-1).getFinalAmount()+finalList.get(i).getFinalAmount());
					 }
					 else
					 {
						 finalList.get(i).setFinalAmount(finalList.get(i-1).getFinalAmount()-finalList.get(i).getFinalAmount());
					 }
				 }
				 else
				 {
					 Date tempDate=createDate(startDate);
					 long day=getDifferenceDays(startDate,tempDate);
					 double interest=Double.parseDouble(df.format(finalList.get(i-1).getFinalAmount()*day*rate/36500));
					 inter+=interest;
					 finalList.get(i-1).setInterest(interest);
					 finalList.get(i-1).setFinalAmount(finalList.get(i-1).getFinalAmount()+inter);
					 inter=0;
					 
					 tempDate.setDate(tempDate.getDate()+1);
					 while(endDate.after(tempDate))
					 {
						 Date tmp2=createDate(tempDate);
						 if(tmp2.getMonth()==endDate.getMonth())
						 {
							 tmp2=endDate;
							 day=getDifferenceDays(tempDate,tmp2);
							 interest=Double.parseDouble(df.format(finalList.get(i-1).getFinalAmount()*day*rate/36500));
							 inter+=interest;
							 finalList.get(i).setInterest(interest);
							 if(finalList.get(i).getStatus().equals("deposit"))
							 {
								 finalList.get(i).setFinalAmount(finalList.get(i-1).getFinalAmount()+finalList.get(i).getFinalAmount());
							 }
							 else
							 {
								 finalList.get(i).setFinalAmount(finalList.get(i-1).getFinalAmount()-finalList.get(i).getFinalAmount());
							 }
						 }
						 else
						 {
							 day=getDifferenceDays(tempDate,tmp2);
							 interest=Double.parseDouble(df.format(finalList.get(i-1).getFinalAmount()*day*rate/36500));
							 inter+=interest;
							 finalList.get(i-1).setInterest(interest);
							 finalList.get(i-1).setFinalAmount(finalList.get(i-1).getFinalAmount()+inter); 
						 }
						 
						 inter=0;
						 tempDate=tmp2;
						 tempDate.setDate(tempDate.getDate()+1);
					 }
					 
				 }
			 }
		 }
		 
    }
	
	public Date createDate(Date date)
	{
		Date dt=new Date();
		int date1=monthDay(date.getMonth()+1,date.getYear());
        dt.setDate(date1);
        dt.setMonth(date.getMonth());
        dt.setYear(date.getYear());
		return dt;
		
	}

	public static int monthDay(int month,int year)
	{
		int day=30;
		if(month==1 ||month==3 ||month==5 ||month==7 ||month==8 ||month==10 ||month==12)
		day=31;
		else if(month==2 && year%4==0)
		day=29;
		else if(month==2)
		day=28;
	
		return day;
	}
	
	public int daysInMonth(int month,int year)
	{
		//System.out.println("month: "+month);
		int day=30;
		if(month==1 ||month==3 ||month==5 ||month==7 ||month==8 ||month==10 ||month==12)
		day=31;
		else if(month==2 && year%4==0)
		day=29;
		else if(month==2)
		day=28;
		return day;
	}

	/*public static long getDifferenceDays(Date d1, Date d2) 
	{
		
	    long diff = ((d2.getTime() - d1.getTime())/ (1000 * 60 * 60 * 24));
	    return diff;
	}*/
	
	public void differenceMethod(Date firstDate, Date secondDate)
	{
	   long dd=getDifferenceDays(firstDate, secondDate);
	        
	   Date fix=secondDate;
	   long fixmnth=fix.getMonth()+1;
	//   // // // //System.out.println("fix : "+fixmnth);
	   secondDate.setDate(secondDate.getDate()+1);
	   long crrmnth=secondDate.getMonth()+1;
	 //  // // // //System.out.println("current : "+crrmnth);
	   if(fixmnth<crrmnth)
	   {
		   dd+=1;
	   }
	        
	  // // // // //System.out.println("Difference Days :- "+dd);
	}
	    
	public static long getDifferenceDays(Date d1, Date d2) 
	{
		long diff = d2.getTime() - d1.getTime();
	//	// // // //System.out.println("diff: "+diff);
		return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
	}
	
	public ArrayList<LoanInfo> groupLoanList(int branchId,String status) 
	{
		String query="";
		int count=1;
		ArrayList<LoanInfo> list=new ArrayList<>();
		if(status.equalsIgnoreCase("All"))
		{
			query="select * from grouploan INNER JOIN shareholder_info on grouploan.teamLeader=shareholder_info.shareholderno and grouploan.status!='notApprove' where shareholder_info.branch_id='"+branchId+"'  order by grouploan.loanNo asc";
		}
		else if(status.equalsIgnoreCase("Approve") || status.equalsIgnoreCase("notApprove") || status.equalsIgnoreCase("pending"))
		{
			query="select * from grouploan INNER JOIN shareholder_info on grouploan.teamLeader=shareholder_info.shareholderno where grouploan.status='"+status+"' and shareholder_info.branch_id='"+branchId+"'  order by grouploan.loanNo asc";
		}
		else
		{
			query="select * from grouploan INNER JOIN shareholder_info on grouploan.teamLeader=shareholder_info.shareholderno where grouploan.center='"+status+"' and grouploan.status!='notApprove'  and shareholder_info.branch_id='"+branchId+"'  order by grouploan.loanNo asc";
		}
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
			Statement stt=conn.createStatement();
			ResultSet ss=stt.executeQuery(query);
			while(ss.next())
			{
				if(!ss.getString("loanNo").contains("R"))
				{
					LoanInfo info=new LoanInfo();
					
					info.setSno(count++);
					info.setShareHolderNo(ss.getString("grouploan.teamLeader"));
					info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
					info.setFatherHusbandName(ss.getString("shareholder_info.father_husband_name"));
					info.setContactNo(ss.getString("shareholder_info.mobile"));
					info.setId(ss.getString("grouploan.id"));
					info.setLoanAmount(ss.getString("loanAmount"));
					info.setLoanAmtInt(ss.getInt("loanAmount"));
					info.setLoanInterest(ss.getString("grouploan.interest"));
					info.setLoanTerm(ss.getString("grouploan.terms"));
					info.setInstallAmount(ss.getDouble("grouploan.emi"));
					info.setLoanType("Group Loan");
					info.setEmiType(ss.getString("grouploan.emiType"));
					info.setDiscount(ss.getInt("discount"));
					info.setRequestDate(ss.getDate("requestDate"));
					info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
					info.setIdProof(ss.getString("idproof"));
					info.setTerms(ss.getInt("terms"));
					info.setLoanNo(ss.getString("loanNo")+" / "+ss.getString("sub_loan_no"));
					info.setSubLoanNo(ss.getString("sub_loan_no"));
					if(ss.getString("fileCharge").trim().equals(""))	
					{
						info.setFileCharge("0");
					}
					else
					{
				     info.setFileCharge(ss.getString("fileCharge"));
					}
					info.setAppChqNo(ss.getString("app_cheque"));
//					info.setNomBankName(ss.getString("nom_bank_name"));
//					info.setNomBankBranch(ss.getString("nom_bank_branch"));
//					info.setNomBankAccountNo(ss.getString("nom_acc_no"));
//					info.setNomBankIfsc(ss.getString("nom_bank_ifsc"));
//					
					info.setAddress(ss.getString("address"));
					info.setNomAddress(ss.getString("nominee_address"));
					info.setCenter(ss.getString("center"));
					info.setCenterName(centerNameById(ss.getString("center"), conn));
					info.setMembers(ss.getString("members"));
					info.setRd_fdNo(ss.getString("RD_FD_no"));
					info.setFrequency(String.valueOf(ss.getInt("frequency")));
					info.setFrequencyVal(ss.getInt("frequency"));
					
					info.setFreqLable(frequencyLabel(info.getFrequency()));
					double paidAmt=loanPaidAmountByUser("grouploan", ss.getString("sub_loan_no"),conn);
					if(paidAmt>0)
					{
						info.setDisable(true);
					}
					else
					{
						info.setDisable(false);
					}
					
					if(ss.getDate("approvalDate")!=null)
					{
						info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
						info.setEmiPaidDate(ss.getDate("approvalDate"));
					}
					
					if(ss.getDate("emi_due_date")!=null)
					{
						info.setStrEmiDueDate(sf.format(ss.getDate("emi_due_date")));
						info.setEmiDate(ss.getDate("emi_due_date"));
						info.setEmiPaidDateStr(sf.format(ss.getDate("emi_due_date")));
						info.setEmiPaidDate(ss.getDate("emi_due_date"));
					}
  
                    info.setStatus(ss.getString("status"));
					info.setAppChqNo(ss.getString("grouploan.app_chq_no"));
					info.setAppAccNo(ss.getString("grouploan.app_acc_no"));
					info.setAppBankName(ss.getString("grouploan.app_bank_name"));
					info.setAppBankBranch(ss.getString("grouploan.app_bank_branch"));
					
					info.setG1ChqNo(ss.getString("grouploan.g1_chq_no"));
					info.setG1AccNo(ss.getString("grouploan.g1_acc_no"));
					info.setG1BankName(ss.getString("grouploan.g1_bank_name"));
					info.setG1BankBranch(ss.getString("grouploan.g1_bank_branch"));
					
					info.setG2ChqNo(ss.getString("grouploan.g2_chq_no"));
					info.setG2AccNo(ss.getString("grouploan.g2_acc_no"));
					info.setG2BankName(ss.getString("grouploan.g2_bank_name"));
					info.setG2BankBranch(ss.getString("grouploan.g2_bank_branch"));

					info.setDsacode(ss.getString("dsacode"));
					info.setDsaName(dsaNameById(ss.getString("dsacode"), conn));
					info.setCommission(ss.getDouble("commission"));
					info.setEmiType(ss.getString("emiType"));
					if(ss.getString("insurance_fee").trim().equals(""))
					{
						info.setInsuranceFee("0");
					}
					else
					{
					info.setInsuranceFee(ss.getString("insurance_fee"));
					}
					info.setExtraAmt(ss.getDouble("grouploan.extra_amount"));
					info.setLoanCategory(ss.getString("loan_category"));
					info.setLoanCategoryLabel(highMarkLabelByValue("Loan Category", ss.getString("loan_category"), conn));
					info.setLoanCycle(ss.getString("loan_cycle"));
					info.setLoanPurpose(ss.getString("loan_purpose"));
					info.setRepaymentFreq(ss.getString("repayment_frequency"));
					info.setRepaymentFreqLabel(highMarkLabelByValue("Repayment Frequency", ss.getString("repayment_frequency"), conn));
					info.setPaidStatus(ss.getString("paidStatus"));
					
					list.add(info);
				}
				
			}
			
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	
	public String frequencyLabel(String frequency)
	{
		String freq="";
		if(frequency.equals("52") || frequency.equals("52.0"))
		{
			freq="1 week";
		}
		else if(frequency.equals("26") || frequency.equals("26.0"))
		{
			freq="2 week";
		}
		else if(frequency.equals("13") || frequency.equals("13.0"))
		{
			freq="4 week";
		}
		else if(frequency.equals("365") || frequency.equals("365.0"))
		{
			freq="Daily";
		}
		else if(frequency.equals("36") || frequency.equals("36.0"))
		{
			freq="10 Days";
		}
		else if(frequency.equals("24") || frequency.equals("24.0"))
		{
			freq="15 Days";
		}
		else if(frequency.equals("12") || frequency.equals("12.0"))
		{
			freq="Monthly";
		}
		else if(frequency.equals("4") || frequency.equals("4.0"))
		{
			freq="Quarterly";
		}
		else if(frequency.equals("2") || frequency.equals("2.0"))
		{
			freq="Half Yearly";
		}
		else if(frequency.equals("1") || frequency.equals("1.0"))
		{
			freq="Yearly";
		}
		return freq;
	}
	
	public int frequencyValue(String frequency)
	{
		int days=0;
		if(frequency.equals("52") || frequency.equals("52.0"))
		{
			days=7;
		}
		else if(frequency.equals("26") || frequency.equals("26.0"))
		{
			days=14;
		}
		else if(frequency.equals("13") || frequency.equals("13.0"))
		{
			days=28;
		}
		else if(frequency.equals("365") || frequency.equals("365.0"))
		{
			days=1;
		}
		else if(frequency.equals("36") || frequency.equals("36.0"))
		{
			days=10;
		}
		else if(frequency.equals("24") || frequency.equals("24.0"))
		{
			days=15;
		}
		else if(frequency.equals("12") || frequency.equals("12.0"))
		{
			days=30;
		}
		else if(frequency.equals("4") || frequency.equals("4.0"))
		{
			days=90;
		}
		else if(frequency.equals("2") || frequency.equals("2.0"))
		{
			days=180;
		}
		else if(frequency.equals("1") || frequency.equals("1.0"))
		{
			days=360;
		}
		return days;
	}
	
	public LoanInfo groupLoanListByLoanNo(String loanNo,Connection conn) 
	{
		Statement st=null;
		ResultSet ss=null;
		LoanInfo info=null;
		try
		{
			st=conn.createStatement();
			
			String query="select * from grouploan where sub_loan_no='"+loanNo+"'";
			
			ss=st.executeQuery(query);
			
			if(ss.next())
			{
				info=new LoanInfo();
				info.setShareHolderNo(ss.getString("teamLeader"));
				info.setApplicantName(applicantNameByShareHolderNo(info.getShareHolderNo(), conn));
				info.setId(ss.getString("id"));
				info.setLoanAmount(ss.getString("loanAmount"));
				info.setLoanAmtInt(ss.getInt("loanAmount"));
				info.setLoanInterest(ss.getString("interest"));
				info.setLoanTerm(ss.getString("terms"));
				info.setInstallAmount(ss.getDouble("emi"));
				info.setEmiMode("both");
				info.setLoanType("Group Loan");
				info.setDiscount(ss.getInt("discount"));
				info.setRd_fdNo(ss.getString("RD_FD_no"));
				info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
				info.setApprovalDate(ss.getDate("approvalDate"));
				if(info.getApprovalDate()!=null)
				{
					info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
				}
				else
				{
					info.setStrApprovalDate("");
				}
				
				if(ss.getDate("emi_due_date")!=null)
				{
					info.setDayOfWeek(new SimpleDateFormat("EE").format(ss.getDate("emi_due_date")));
				}
				info.setGroupLeaderName(groupLeaderNameByLoanNo(ss.getString("loanNo"),conn));
				info.setIdProof(ss.getString("idproof"));
				info.setLoanNo(ss.getString("loanNo"));
				info.setSubLoanNo(ss.getString("sub_loan_no"));
				info.setFileCharge(ss.getString("fileCharge"));
				info.setCenter(ss.getString("center"));
				info.setCenterName(centerNameById(ss.getString("center"), conn));
				info.setMembers(ss.getString("members"));
				info.setFrequencyVal(ss.getInt("frequency"));
				info.setEmiType(ss.getString("emiType"));
				info.setFrequency(frequencyLabel(ss.getString("frequency")));
				info.setIncreaseAmount(ss.getDouble("increase_amount"));
				info.setReason(ss.getString("reason"));
				info.setPlanNo(ss.getString("plan_no"));
				info.setDsacode(ss.getString("dsacode"));
				info.setPlanName(planNameByPlanId(info.getPlanNo(), conn));
				info.setDsaName(dsaNameById(ss.getString("dsacode"), conn));
				info.setInsuranceFee(ss.getString("insurance_fee"));
				info.setExtraAmt(ss.getDouble("extra_amount"));
				info.setTerms(ss.getInt("terms"));
				info.setProcessingCharge(ss.getDouble("processing_charge"));
			}
			
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(ss!=null)
				{
					ss.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return info;
	}
	

	public String groupLeaderNameByLoanNo(String loanNo,Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select teamLeader from grouploan where loanNo='"+loanNo+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return applicantNameByShareHolderNo(rr.getString("teamLeader"), conn);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}

		return "";
	}

	public ArrayList<LoanInfo> propertyLoanList(int branchId,String status) 
	{
		String query="";
		int count=1;
		ArrayList<LoanInfo> list=new ArrayList<>();
		if(status.equals("All"))
		{
			query="select * from propertyloan INNER JOIN shareholder_info on propertyloan.shareholderno=shareholder_info.shareholderno  where shareholder_info.branch_id='"+branchId+"' order by propertyloan.id desc ";

		}
		else
		{
			query="select * from propertyloan INNER JOIN shareholder_info on propertyloan.shareholderno=shareholder_info.shareholderno where propertyloan.status='"+status+"' and shareholder_info.branch_id='"+branchId+"' order by propertyloan.id desc";

		}
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
			Statement stt=conn.createStatement();
			ResultSet ss=stt.executeQuery(query);
			while(ss.next())
			{
				if(!ss.getString("loanNo").contains("R"))
				{
					LoanInfo info=new LoanInfo();
					
					info.setSno(count++);
					UserInfo uu=userInfoByShareHolderNo(ss.getString("shareholderno"),conn);
					info.setShareHolderNo(ss.getString("propertyloan.shareholderno"));
					info.setApplicantName(uu.getFirst_applicantName());
					info.setContactNo(ss.getString("shareholder_info.mobile"));
					info.setId(ss.getString("propertyloan.id"));
					info.setLoanAmount(ss.getString("propertyloan.loanAmount"));
					info.setLoanInterest(ss.getString("propertyloan.interest"));
					info.setLoanTerm(ss.getString("propertyloan.terms"));
					info.setInstallAmount(ss.getDouble("propertyloan.emi"));
					info.setLoanType("Property Loan");
					info.setDiscount(ss.getInt("discount"));
					info.setRequestDate(ss.getDate("requestDate"));
					info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
					info.setFirstGuarantor(ss.getString("firstguarantor"));
					info.setSecondGuarantor(ss.getString("secondguarantor"));
					info.setIdProof(ss.getString("idproof"));
					info.setLoanNo(ss.getString("loanNo"));
					info.setFileCharge(ss.getString("fileCharge"));
					info.setCategory(ss.getString("category"));
					info.setRegistryNo(ss.getString("registryNo"));
					info.setVerified(ss.getString("verified"));
					if(ss.getDate("approvalDate")!=null)
					{
						info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
					}
					info.setPatta(ss.getString("patta"));
					info.setAuthorityPatta(ss.getString("authorityPatta"));
					info.setJamabandi(ss.getString("jamabandi"));
					info.setRd_fdNo(ss.getString("RD_FD_no"));
					if(ss.getString("status").equals("pending"))
					{
						info.setDisable(false);
					}
					else
					{
						info.setDisable(true);
					}
					info.setFrequency(String.valueOf(ss.getInt("frequency")));

					info.setAppChqNo(ss.getString("propertyloan.app_chq_no"));
					info.setAppAccNo(ss.getString("propertyloan.app_acc_no"));
					info.setAppBankName(ss.getString("propertyloan.app_bank_name"));
					info.setAppBankBranch(ss.getString("propertyloan.app_bank_branch"));
					
					info.setG1ChqNo(ss.getString("propertyloan.g1_chq_no"));
					info.setG1AccNo(ss.getString("propertyloan.g1_acc_no"));
					info.setG1BankName(ss.getString("propertyloan.g1_bank_name"));
					info.setG1BankBranch(ss.getString("propertyloan.g1_bank_branch"));
					
					info.setG2ChqNo(ss.getString("propertyloan.g2_chq_no"));
					info.setG2AccNo(ss.getString("propertyloan.g2_acc_no"));
					info.setG2BankName(ss.getString("propertyloan.g2_bank_name"));
					info.setG2BankBranch(ss.getString("propertyloan.g2_bank_branch"));

					info.setDsacode(ss.getString("dsacode"));
					info.setCommission(ss.getDouble("commission"));
					info.setEmiType(ss.getString("emiType"));
					info.setInsuranceFee(ss.getString("insurance_fee"));
					info.setCenter(ss.getString("center"));
					info.setCenterName(centerNameById(ss.getString("center"),conn));
					
					list.add(info);
				}
				
			}
			
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	
	public LoanInfo propertyLoanListByLoanNo(String loanNo,Connection conn) 
	{
		ResultSet ss=null;
		Statement st=null;
		LoanInfo info=null;
		try
		{
			st=conn.createStatement();
			String query="select * from propertyloan where loanNo='"+loanNo+"'";
			ss=st.executeQuery(query);
			if(ss.next())
			{
				info=new LoanInfo();
				info.setShareHolderNo(ss.getString("shareholderno"));
				info.setApplicantName(applicantNameByShareHolderNo(info.getShareHolderNo(),conn));
				info.setId(ss.getString("id"));
				info.setLoanAmount(ss.getString("loanAmount"));
				info.setLoanInterest(ss.getString("interest"));
				info.setLoanTerm(ss.getString("terms"));
				info.setInstallAmount(ss.getDouble("emi"));
				info.setLoanType("Property Loan");
				info.setDiscount(ss.getInt("discount"));
				info.setRequestDate(ss.getDate("requestDate"));
				info.setApprovalDate(ss.getDate("approvalDate"));
				if(info.getApprovalDate()!=null)
				{
					info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
				}
				else
				{
					info.setStrApprovalDate("");
				}
				info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
				info.setFirstGuarantor(ss.getString("firstguarantor"));
				info.setSecondGuarantor(ss.getString("secondguarantor"));
				info.setIdProof(ss.getString("idproof"));
				info.setLoanNo(ss.getString("loanNo"));
				info.setRd_fdNo(ss.getString("RD_FD_no"));
				info.setFileCharge(ss.getString("fileCharge"));
				info.setCategory(ss.getString("category"));
				info.setRegistryNo(ss.getString("registryNo"));
				info.setVerified(ss.getString("verified"));
				info.setFrequencyVal(ss.getInt("frequency"));
				info.setFrequency(frequencyLabel(ss.getString("frequency")));
				info.setEmiType(ss.getString("emiType"));
				info.setIncreaseAmount(ss.getDouble("increase_amount"));
				info.setReason(ss.getString("reason"));
				info.setPlanNo(ss.getString("plan_no"));
				info.setDsacode(ss.getString("dsacode"));
			}
			
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(ss!=null)
				{
					ss.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return info;
	}
	

	public UserInfo userInfoByLoanNoLoanType(String loanNo,String loanType, Connection conn)
	{
		Statement st=null;
		ResultSet rs=null;
		UserInfo uu=null;
		String hno=null;
		String qq="";
		try
		{
			st=conn.createStatement();
			if(loanType.equalsIgnoreCase("grouploan"))
			{
				qq="select * from "+loanType+" where sub_loan_no='"+loanNo+"' ";
			}
			else
			{
				qq="select * from "+loanType+" where loanNo='"+loanNo+"' ";
			}
			rs=st.executeQuery(qq);
			if(rs.next())
			{
				if(loanType.equalsIgnoreCase("grouploan"))
				{
					hno=rs.getString("teamLeader");
				}
				else
				{
					hno=rs.getString("shareholderno");
				}
				
				uu=userInfoByShareHolderNo(hno, conn);
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return uu;
	}
    
	public LoanInfo loanInfoByLoanNoLoanType(String loanNo, String loanType,Connection conn) 
	{
		Statement st=null;
		ResultSet rs=null;
		LoanInfo ll=null;
		String qq="";
		try
		{
			st=conn.createStatement();
			if(loanType.equalsIgnoreCase("grouploan"))
			{
				qq="select * from "+loanType+" where sub_loan_no='"+loanNo+"' and status='Approve'";
				System.out.println(qq);
			}
			else
			{
				// qq="select * from "+loanType+" where loanNo='"+loanNo+"' and status='Approve'";				
				qq="select * from "+loanType+" where loanNo='"+loanNo+"' "; //RR 14/7/2025

			}
		
			rs=st.executeQuery(qq);
			if(rs.next())
			{
				if(loanType.equals("personalloan"))
				{
					ll=personalLoanListByLoanNo(loanNo,conn);
				}
				else if(loanType.equals("vechicleloan"))
				{
					ll=vehicleLoanListByLoanNo(loanNo, conn);
				}
				else if(loanType.equals("propertyloan"))
				{
					ll=propertyLoanListByLoanNo(loanNo, conn);
				}
				else if(loanType.equals("grouploan"))
				{
					ll=groupLoanListByLoanNo(loanNo, conn);
				}
				else if(loanType.equals("secure_loan"))
				{
					ll=secureLoanListByLoanNo(loanNo, conn);
				}
				else if(loanType.equals("business_loan"))
				{
					ll=businessLoanListByLoanNo(loanNo, conn);
				}
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return ll;
	}
	
	public LoanInfo personalLoanListByLoanNo(String loanNo, Connection conn) 
    {
		Statement st=null;
		ResultSet ss=null;
		LoanInfo info=null;
		try
		{
			st=conn.createStatement();
			String query="select * from personalloan where loanNo='"+loanNo+"'";
			ss=st.executeQuery(query);
			if(ss.next())
			{
				info=new LoanInfo();
				info.setShareHolderNo(ss.getString("shareholderno"));
				info.setApplicantName(applicantNameByShareHolderNo(info.getShareHolderNo(), conn));
				info.setId(ss.getString("id"));
				info.setLoanAmount(ss.getString("loanAmount"));
				info.setLoanAmtInt(ss.getInt("loanAmount"));
				info.setLoanInterest(ss.getString("interest"));
				info.setLoanTerm(ss.getString("terms"));
				info.setTerms(ss.getInt("terms"));
				info.setInstallAmount(ss.getDouble("emi"));
				info.setLoanType("Personal Loan");
				info.setEmiMode(ss.getString("emi_mode"));
				info.setRequestDate(ss.getDate("requestDate"));
				info.setDiscount(ss.getInt("discount"));
				
				info.setEmiDate(ss.getDate("emi_due_date"));
				info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
				info.setApprovalDate(ss.getDate("approvalDate"));
				if(info.getApprovalDate()!=null)
				{
					info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
				}
				else
				{
					info.setStrApprovalDate("");
				}
				info.setFirstGuarantor(ss.getString("firstguarantor"));
				info.setSecondGuarantor(ss.getString("secondguarantor"));
				info.setIdProof(ss.getString("idproof"));
				info.setLoanNo(ss.getString("loanNo"));
				info.setFileCharge(ss.getString("fileCharge"));
				info.setRd_fdNo(ss.getString("RD_FD_no"));
				info.setFrequencyVal(ss.getInt("frequency"));
				info.setFrequency(frequencyLabel(ss.getString("frequency")));
				info.setEmiType(ss.getString("emiType"));
				info.setIncreaseAmount(ss.getDouble("increase_amount"));
				info.setReason(ss.getString("reason"));
				info.setPlanNo(ss.getString("plan_no"));
				info.setPlanName(planNameByPlanId(info.getPlanNo(), conn));
				info.setDsacode(ss.getString("dsacode"));
				info.setDsaName(dsaNameById(ss.getString("dsacode"), conn));
				info.setInsuranceFee(ss.getString("insurance_fee"));
				
				
				info.setProcessingCharge(ss.getDouble("processing_charge"));;
				info.setExtraAmt(ss.getDouble("extra_amount"));
				info.setStamp(ss.getDouble("stamp"));
				info.setAdvanceTerm(ss.getInt("advance_emi_term"));
				info.setTotalAdvanceEMIAmount(ss.getDouble("advance_emi_amount"));
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(ss!=null)
				{
					ss.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return info;
	}
	
	public LoanInfo secureLoanListByLoanNo(String loanNo, Connection conn) 
    {
		Statement st=null;
		ResultSet ss=null;
		LoanInfo info=null;
		try 
		{
			st=conn.createStatement();
			String query="select * from secure_loan where loanNo='"+loanNo+"'";
			ss=st.executeQuery(query);
			if(ss.next())
			{
				info=new LoanInfo();
				info.setShareHolderNo(ss.getString("shareholderno"));
				info.setApplicantName(applicantNameByShareHolderNo(info.getShareHolderNo(), conn));
				info.setId(ss.getString("id"));
				info.setLoanAmount(ss.getString("loanAmount"));
				info.setLoanAmtInt(ss.getInt("loanAmount"));
				info.setLoanInterest(ss.getString("interest"));
				info.setLoanTerm(ss.getString("terms"));
				info.setTerms(ss.getInt("terms"));
				info.setInstallAmount(ss.getDouble("emi"));
				info.setLoanType("Secure Loan");
				info.setEmiMode(ss.getString("emi_mode"));
				info.setRequestDate(ss.getDate("requestDate"));
				info.setDiscount(ss.getInt("discount"));
				info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
				info.setApprovalDate(ss.getDate("approvalDate"));
				if(info.getApprovalDate()!=null)
				{
					info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
				}
				else
				{
					info.setStrApprovalDate("");
				}
				info.setFirstGuarantor(ss.getString("firstguarantor"));
				info.setSecondGuarantor(ss.getString("secondguarantor"));
				info.setIdProof(ss.getString("idproof"));
				info.setLoanNo(ss.getString("loanNo"));
				info.setFileCharge(ss.getString("fileCharge"));
				info.setRd_fdNo(ss.getString("RD_FD_no"));
				info.setFrequencyVal(ss.getInt("frequency"));
				info.setFrequency(frequencyLabel(ss.getString("frequency")));
				info.setEmiType(ss.getString("emiType"));
				info.setIncreaseAmount(ss.getDouble("increase_amount"));
				info.setReason(ss.getString("reason"));
				info.setPlanNo(ss.getString("plan_no"));
				info.setDsacode(ss.getString("dsacode"));
				info.setPlanName(planNameByPlanId(info.getPlanNo(), conn));
				info.setDsaName(dsaNameById(ss.getString("dsacode"), conn));
				info.setInsuranceFee(ss.getString("insurance_fee"));
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(ss!=null)
				{
					ss.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return info;
	}
	
	
	public LoanInfo businessLoanListByLoanNo(String loanNo, Connection conn) 
    {
		Statement st=null;
		ResultSet ss=null;
		LoanInfo info=null;
		try
		{
			st=conn.createStatement();
			String query="select * from business_loan where loanNo='"+loanNo+"'";
			ss=st.executeQuery(query);
			if(ss.next())
			{
				info=new LoanInfo();
				info.setShareHolderNo(ss.getString("shareholderno"));
				info.setApplicantName(applicantNameByShareHolderNo(info.getShareHolderNo(), conn));
				info.setId(ss.getString("id"));
				info.setLoanAmount(ss.getString("loanAmount"));
				info.setLoanInterest(ss.getString("interest"));
				info.setLoanTerm(ss.getString("terms"));
				info.setInstallAmount(ss.getDouble("emi"));
				info.setLoanType("Business Loan");
				info.setEmiMode(ss.getString("emi_mode"));
				info.setRequestDate(ss.getDate("requestDate"));
				info.setDiscount(ss.getInt("discount"));
				info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
				info.setApprovalDate(ss.getDate("approvalDate"));
				if(info.getApprovalDate()!=null)
				{
					info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
				}
				else
				{
					info.setStrApprovalDate("");
				}
				info.setFirstGuarantor(ss.getString("firstguarantor"));
				info.setSecondGuarantor(ss.getString("secondguarantor"));
				info.setIdProof(ss.getString("idproof"));
				info.setLoanNo(ss.getString("loanNo"));
				info.setFileCharge(ss.getString("fileCharge"));
				info.setRd_fdNo(ss.getString("RD_FD_no"));
				info.setFrequencyVal(ss.getInt("frequency"));
				info.setFrequency(frequencyLabel(ss.getString("frequency")));
				info.setEmiType(ss.getString("emiType"));
				info.setIncreaseAmount(ss.getDouble("increase_amount"));
				info.setReason(ss.getString("reason"));
				info.setPlanNo(ss.getString("plan_no"));
				info.setDsacode(ss.getString("dsacode"));
				info.setInsuranceFee(ss.getString("insurance_fee"));
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(ss!=null)
				{
					ss.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return info;
	}
	
	public LoanInfo vehicleLoanListByLoanNo(String loanNo, Connection conn) 
    {
		Statement st=null;
		ResultSet ss=null;
		LoanInfo info=null;
		try
		{
			st=conn.createStatement();
			String query="select * from vechicleloan where loanNo='"+loanNo+"'";
			ss=st.executeQuery(query);
			if(ss.next())
			{
				info=new LoanInfo();
				info.setId(ss.getString("id"));
				info.setShareHolderNo(ss.getString("shareholderno"));
				info.setApplicantName(applicantNameByShareHolderNo(info.getShareHolderNo(), conn));
				info.setLoanAmount(ss.getString("loanAmount"));
				info.setLoanInterest(ss.getString("interest"));
				info.setLoanTerm(ss.getString("terms"));
				info.setInstallAmount(ss.getDouble("emi"));
				info.setLoanType("Vehicle Loan");
				info.setRequestDate(ss.getDate("requestDate"));
				info.setDiscount(ss.getInt("discount"));
				info.setRd_fdNo(ss.getString("RD_FD_no"));
				info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
				info.setApprovalDate(ss.getDate("approvalDate"));
				if(info.getApprovalDate()!=null)
				{
					info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
				}
				else
				{
					info.setStrApprovalDate("");
				}
				info.setFirstGuarantor(ss.getString("firstguarantor"));
				info.setSecondGuarantor(ss.getString("secondguarantor"));
				info.setIdProof(ss.getString("idproof"));
				info.setLoanNo(ss.getString("loanNo"));
				info.setCategory(ss.getString("category"));
				info.setVechiclename(ss.getString("vechileName"));
				info.setVechileModel(ss.getString("model"));
				info.setEngineNo(ss.getString("engineno"));
				info.setEmiType(ss.getString("emiType"));
				info.setFileCharge(ss.getString("fileCharge"));
				info.setFrequencyVal(ss.getInt("frequency"));
				info.setFrequency(frequencyLabel(ss.getString("frequency")));
				info.setIncreaseAmount(ss.getDouble("increase_amount"));
				info.setReason(ss.getString("reason"));
				info.setPlanNo(ss.getString("plan_no"));
				info.setDsacode(ss.getString("dsacode"));
				info.setInsuranceFee(ss.getString("insurance_fee"));
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(ss!=null)
				{
					ss.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return info;
	}
	
	public ArrayList<UserInfo> groupMemberInfo(String members,Connection conn)
	{
		String member[]=members.split(",");
		ArrayList<UserInfo> list=new ArrayList<>();
		for(int i=0;i<member.length;i++)
		{
			UserInfo uu=userInfoByShareHolderNo(member[i].trim(),conn);
			list.add(uu);
		}
		
		return list;
	}

	public ArrayList<SelectItem> allCategoryList() 
	{
		ArrayList<SelectItem> list = new ArrayList<SelectItem>();
		list.add(new SelectItem("General","General"));
		list.add(new SelectItem("OBC","OBC"));
		list.add(new SelectItem("SC","SC"));
		list.add(new SelectItem("ST","ST"));
		list.add(new SelectItem("Muslim","Muslim"));
		return list;
	}
	
	public ArrayList<UserInfo> allRdFdOfUser(String shareHolderNo) 
	{
		ArrayList<UserInfo> list = new ArrayList<UserInfo>();
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			int i=0;
			Statement st = con.createStatement();
			String qq = "select * from customer_info where account_status='active' and shareHolderNo='"+shareHolderNo+"'";
			ResultSet rs = st.executeQuery(qq);
			while (rs.next())
			{
				i=i+1;
				UserInfo uu = new UserInfo();
				uu.setSno(i);
         		uu.setId(rs.getString("id"));			
         		uu.setOffice_application_no(rs.getString("office_application_no"));
    			uu.setOffice_date(rs.getDate("office_date"));
    			uu.setStrOffcDate(sf.format(rs.getDate("office_date")));
				uu.setUser_no(rs.getString("user_no"));
				uu.setScheme_type(rs.getString("scheme_type"));
				uu.setPlan_no(rs.getString("plan_no"));
				uu.setTerms(rs.getInt("terms"));
				uu.setFrequency(rs.getInt("frequency"));
				uu.setApplicant_fees(rs.getDouble("applicant_fees"));
				uu.setInstallment_amount(rs.getDouble("installment_amount"));
				uu.setInterest(rs.getDouble("interest"));
				uu.setMaturity_value(rs.getDouble("maturity_value"));
				uu.setMaturity_date(rs.getDate("maturity_date"));
				uu.setStrMatDate(sf.format(rs.getDate("maturity_date")));

				list.add(uu);
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	public ArrayList<UserInfo> depositPaymentList(int branchId)
	{
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		ArrayList<UserInfo> list=new ArrayList<UserInfo>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from customer_deposit  INNER JOIN savingaccount on customer_deposit.account_no=savingaccount.accountNo"
					+ " INNER JOIN shareholder_info on savingaccount.shareHolderNo=shareholder_info.shareHolderNo"
					+ " where customer_deposit.status='pending' and shareholder_info.branch_id='"+branchId+"'";
			ResultSet rr=st.executeQuery(query);
			while(rr.next())
			{
				UserInfo ll=new UserInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("transfer_to_bank"),conn);
				
				ll.setId(rr.getString("customer_deposit.id"));
				ll.setAccountNo(rr.getString("customer_deposit.account_no"));
				ll.setFirst_applicantName(rr.getString("shareholder_info.first_applicantName"));
				ll.setEntryDate(rr.getDate("customer_deposit.date"));
				ll.setEntryDateStr(sf.format(ll.getEntryDate()));
				ll.setAmount(rr.getDouble("customer_deposit.amount"));
				ll.setStatus("Deposit");
				
				ll.setPayMode(rr.getString("payment_mode"));
				ll.setBank_name(rr.getString("from_bank_name"));
				ll.setChq_ddNo(rr.getString("cheque_dd_no"));
				ll.setChq_ddDate(rr.getDate("cheque_dd_date"));
				if(ll.getChq_ddDate()!=null)
				{
					ll.setChq_ddDateStr(sf.format(ll.getChq_ddDate()));
				}
				
				if(ll.getChq_ddDate().after(tdyDt))
				{
					ll.setDisable(true);
				}
				
				ll.setSubmittedToBank(rr.getString("transfer_to_bank"));
				ll.setTransferredToBankName(bb.getBank_name()+"-"+bb.getAcc_no());
				
				list.add(ll);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public ArrayList<UserInfo> withdrawPaymentList(int branchId)
	{
		ArrayList<UserInfo> list=new ArrayList<UserInfo>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			//String query="select * from customer_withdrwal where status='pending'";
			String query="select * from customer_withdrwal"
					+ " INNER JOIN savingaccount on customer_withdrwal.account_no=savingaccount.accountNo"
					+ " INNER JOIN shareholder_info on savingaccount.shareHolderNo=shareholder_info.shareHolderNo"
					+ " where customer_withdrwal.status='pending' and shareholder_info.branch_id='"+branchId+"'";
			ResultSet rr=st.executeQuery(query);
			while(rr.next())
			{
				UserInfo ll=new UserInfo();
				ll.setId(rr.getString("customer_withdrwal.id"));
				ll.setAccountNo(rr.getString("customer_withdrwal.account_no"));
				ll.setFirst_applicantName(rr.getString("shareholder_info.first_applicantName"));
				ll.setEntryDate(rr.getDate("customer_withdrwal.date"));
				ll.setEntryDateStr(sf.format(ll.getEntryDate()));
				ll.setAmount(rr.getDouble("customer_withdrwal.amount"));
				ll.setStatus("Withdrwal");
				
				ll.setPayMode(rr.getString("payment_mode"));
				ll.setBank_name(rr.getString("from_bank_name"));
				ll.setChq_ddNo(rr.getString("cheque_dd_no"));
				ll.setChq_ddDate(rr.getDate("cheque_dd_date"));
				if(ll.getChq_ddDate()!=null)
				{
					ll.setChq_ddDateStr(sf.format(ll.getChq_ddDate()));
				}

				list.add(ll);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public ArrayList<UserInfo> allPayReceipt(int branchId)
	{
		ArrayList<UserInfo> list=new ArrayList<UserInfo>();
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from payment_receipt "
					+ "INNER JOIN customer_info on payment_receipt.user_no=customer_info.user_no "
					+ "INNER JOIN shareholder_info on customer_info.shareHolderNo=shareholder_info.shareHolderNo "
					+ "where payment_receipt.receipt_status='pending' and shareholder_info.branch_id='"+branchId+"'";
			ResultSet rr=st.executeQuery(query);
			while(rr.next())
			{
				UserInfo ll=new UserInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("transfer_to_bank"),conn);
				
				ll.setId(rr.getString("payment_receipt.id"));
				ll.setAccountNo(rr.getString("payment_receipt.user_no"));
				ll.setShareHolderNo(rr.getString("shareholder_info.shareHolderNo"));
				ll.setOffice_application_no(rr.getString("customer_info.office_application_no"));
				ll.setScheme_type(rr.getString("customer_info.scheme_type"));
				ll.setPlan_no(rr.getString("customer_info.plan_no"));
				ll.setFrequency(rr.getInt("customer_info.frequency"));
				ll.setOffice_date(rr.getDate("customer_info.office_date"));
				ll.setStrMatDate(sf.format(rr.getDate("customer_info.maturity_date")));
				ll.setMaturity_value(rr.getDouble("customer_info.maturity_value"));
				ll.setFirst_applicantName(rr.getString("shareholder_info.first_applicantName"));
				ll.setEntryDate(rr.getDate("payment_receipt.date"));
				ll.setEntryDateStr(sf.format(ll.getEntryDate()));
				ll.setAmount(rr.getDouble("payment_receipt.amount"));
				ll.setInstallment_amount(rr.getDouble("customer_info.installment_amount"));
				ll.setStatus("Payment For RD");
				ll.setPayMode(rr.getString("payment_mode"));
				ll.setPenalty(rr.getDouble("penalty"));
				ll.setReceiptNo(rr.getString("receipt_no"));
				ll.setBank_name(rr.getString("bank_name"));
				ll.setChq_ddNo(rr.getString("cheque_no"));
				ll.setChq_ddDate(rr.getDate("cheque_date"));
				if(ll.getChq_ddDate()!=null)
				{
					ll.setChq_ddDateStr(sf.format(ll.getChq_ddDate()));
					if(ll.getChq_ddDate().after(tdyDt))
					{
						ll.setDisable(true);
					}
				}

				
				
				ll.setSubmittedToBank(rr.getString("transfer_to_bank"));
				ll.setTransferredToBankName(bb.getBank_name()+"-"+bb.getAcc_no());
				
				list.add(ll);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public ArrayList<UserInfo> allLoanPayReceipt(int branchId)
	{
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		ArrayList<UserInfo> list=new ArrayList<UserInfo>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from loanpayment where receipt_status='pending'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				String lno=rr.getString("loanNo");
				String ltp=rr.getString("loanType");
				String shno=new DataBaseReportMethods().shareHolderNoByLoanNoLoanType(lno, ltp);
				double loan_emi=new DataBaseReportMethods().loanEmiByLoanNoLoanType(lno,ltp);
				String applicant_name=new DataBaseReportMethods().applicantNameByLoanNoLoanType(lno,ltp);
				UserInfo ll=new UserInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("transfer_to_bank"),conn);
				
				ll.setId(rr.getString("id"));
				ll.setScheme_type(ltp);
				ll.setLoanNo(rr.getString("loanNo"));
				ll.setShareHolderNo(shno);
				//ll.setAccountNo(shno);
				ll.setAccountNo(rr.getString("loanNo"));
				ll.setFirst_applicantName(applicant_name);
				ll.setEntryDate(rr.getDate("pay_date"));
				ll.setEntryDateStr(sf.format(ll.getEntryDate()));
				ll.setReceiptNo(rr.getString("receipt_no"));
				ll.setPenalty(rr.getDouble("penalty"));
				ll.setAmount(rr.getDouble("amount"));
				ll.setInstallment_amount(loan_emi);
				ll.setStatus("EMI Payment");
				ll.setPayMode(rr.getString("pay_mode"));
				ll.setBank_name(rr.getString("bank_name"));
				ll.setChq_ddNo(rr.getString("chq_no"));
				ll.setChq_ddDate(rr.getDate("chq_date"));
				if(ll.getChq_ddDate()!=null)
				{
					ll.setChq_ddDateStr(sf.format(ll.getChq_ddDate()));
					if(ll.getChq_ddDate().after(tdyDt))
					{
						ll.setDisable(true);
					}
				}
				
				ll.setSubmittedToBank(rr.getString("transfer_to_bank"));
				ll.setTransferredToBankName(bb.getBank_name()+"-"+bb.getAcc_no());
				
				list.add(ll);	
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	public int approveTransaction(UserInfo selectedItem, Date chqClearDate)
	{
		Timestamp tt=new Timestamp(chqClearDate.getTime());
		int i=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="";
			if(selectedItem.getStatus().equals("Deposit"))
			{
				query="update customer_deposit set status='approved',chequeStatus='cleared', date='"+tt+"' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Payment For RD"))
			{
				query="update payment_receipt set receipt_status='approved',chequeStatus='cleared', date='"+tt+"'  where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("EMI Payment"))
			{
				query="update loanpayment set receipt_status='approved',chequeStatus='cleared', pay_date='"+tt+"' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Fixed_Deposit_Cr"))
			{
				query="update fixed_deposit_income set chequeStatus='cleared', date='"+tt+"' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Fixed_Asset_Cr"))
			{
				query="update income_table set chequeStatus='cleared', income_date='"+tt+"' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Other_Cr"))
			{
				query="update income_table set chequeStatus='cleared', income_date='"+tt+"' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Return Instant Loan"))
			{
				query="update lender_record set chequeStatus='cleared', lender_date='"+tt+"' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Instant Borrow"))
			{
				query="update borrower_record set chequeStatus='cleared', borrow_date='"+tt+"' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Promotor Capital"))
			{
				query="update promotors_capital set chequeStatus='cleared', income_date='"+tt+"' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Share Holder"))
			{
			query="update shareholder_info set cheque_status='cleared' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Extra Share Holder"))
			{
			query="update share_info set cheque_status='cleared' where id='"+selectedItem.getId()+"'";
			}
		//	// // // //System.out.println(query);
			i=st.executeUpdate(query);
			if(i>=1)
			{
				dataInsertInQueryTable(query, conn);
				//// //System.out.println("if "+selectedItem.getStatus().equals("Other_Cr"));
				if(selectedItem.getStatus().equals("EMI Payment"))
				{
					/*double interestAmount=0.0,principleAmount=0.0;
					ArrayList<LoanInfo> loanEMIList=new ArrayList<>();
					loanEMIList=loanInstallment(selectedItem.getScheme_type(),selectedItem.getLoanNo());
					for(LoanInfo ll:loanEMIList)
					{
						if(ll.getStatus().equals("Paid"))
						{
							interestAmount=Double.parseDouble(ll.getInterestAmount());
							principleAmount=Double.parseDouble(ll.getPrincipalAmount());
						}
					}
					updateInterestAmountInLoanPayReceipt(Integer.parseInt(selectedItem.getId()), interestAmount);
					decreaseSharedCompanyAmount(principleAmount);
					double preResAmt=checkForRestructure(selectedItem.getLoanNo(),selectedItem.getScheme_type());
					if(preResAmt<=0)
					{
						updateInterestAmountInLoanPayReceiptWithoutIncreasingCompanyCapital(Integer.parseInt(selectedItem.getId()), interestAmount);
					}*/
					
					increaseBankBalance(selectedItem.getSubmittedToBank(), selectedItem.getAmount(),conn);
				}
				else if(selectedItem.getStatus().equals("Payment For RD"))
				{
					increaseBankBalance(selectedItem.getSubmittedToBank(), selectedItem.getAmount(),conn);
				}
				else if(selectedItem.getStatus().equals("Deposit"))
				{
					double preAmount=acconuntHolderAmountByAccountNo(selectedItem.getAccountNo());
					Double newAmount=preAmount+(selectedItem.getAmount());
					updateSavingAmountByAccountNo(selectedItem.getAccountNo(),newAmount);
					increaseBankBalance(selectedItem.getSubmittedToBank(), selectedItem.getAmount(),conn);
				}
				else if(selectedItem.getStatus().equals("Fixed_Deposit_Cr"))
				{
					increaseBankBalance(selectedItem.getSubmittedToBank(), selectedItem.getAmount(),conn);
				}
				else if(selectedItem.getStatus().equals("Fixed_Asset_Cr"))
				{
					increaseBankBalance(selectedItem.getSubmittedToBank(), selectedItem.getAmount(),conn);
				}
				
				else if(selectedItem.getStatus().equals("Other_Cr"))
				{
					increaseBankBalance(selectedItem.getSubmittedToBank(), selectedItem.getAmount(),conn);
				}
				else if(selectedItem.getStatus().equals("Return Instant Loan"))
				{
					increaseBankBalance(selectedItem.getSubmittedToBank(), selectedItem.getAmount(),conn);
				}
				else if(selectedItem.getStatus().equals("Instant Borrow"))
				{
					increaseBankBalance(selectedItem.getSubmittedToBank(), selectedItem.getAmount(),conn);
				}
				else if(selectedItem.getStatus().equals("Promotor Capital"))
				{
					increaseBankBalance(selectedItem.getSubmittedToBank(), selectedItem.getAmount(),conn);
					DsaListInfo promotorDetail=selectedPromotorDetail(selectedItem.getPromotorId());
					Double newAmount=promotorDetail.getAmount()+selectedItem.getAmount();
					updatePromotorAmountByID(promotorDetail.getId(),newAmount);
				}
				else if(selectedItem.getStatus().equals("Share Holder"))
				{
				increaseBankBalance(selectedItem.getSubmittedToBank(), selectedItem.getAmount(),conn);
				}
				else if(selectedItem.getStatus().equals("Extra Share Holder"))
				{
				increaseBankBalance(selectedItem.getSubmittedToBank(), selectedItem.getAmount(),conn);
				}
			}
			
			
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}
	
	public int denyTransaction(UserInfo selectedItem)
	{
		int i=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="";
			if(selectedItem.getStatus().equals("Deposit"))
			{
				query="update customer_deposit set status='not approved',chequeStatus='returned' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Payment For RD"))
			{
				query="update payment_receipt set receipt_status='not approved',chequeStatus='returned' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("EMI Payment"))
			{
				int charge=chequeBounceCharge();
				query="update loanpayment set receipt_status='not approved',chequeStatus='returned', cheque_bounce_charge='"+charge+"' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Fixed_Deposit_Cr"))
			{
				query="update fixed_deposit_income set chequeStatus='returned' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Fixed_Asset_Cr"))
			{
				query="update income_table set chequeStatus='returned' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Other_Cr"))
			{
				query="update income_table set chequeStatus='returned' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Return Instant Loan"))
			{
				query="update lender_record set chequeStatus='returned' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Instant Borrow"))
			{
				query="update borrower_record set chequeStatus='returned' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Promotor Capital"))
			{
				query="update promotors_capital set chequeStatus='returned' where id='"+selectedItem.getId()+"'";
			}
			else if(selectedItem.getStatus().equals("Share Holder"))
			{
			query="update shareholder_info set cheque_status='returned' where id='"+selectedItem.getId()+"'";
			}
			i=st.executeUpdate(query);
			dataInsertInQueryTable(query, conn);
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}
	
	private int chequeBounceCharge() 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection()) 
		{
			Statement st=conn.createStatement();
			String qq="select bounce_charge from cheque_bounce";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getInt("bounce_charge");
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	
	public String checkSchemeByUserNo(String user_no)
	{
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq = "select * from customer_info where user_no='" + user_no+ "'";
			ResultSet rs = st.executeQuery(qq);
			if (rs.next()) 
			{
				return rs.getString("scheme_type");
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return null;
	}
	
	public int updatePersonalLoanRequest(String id,String[] idProof,String guarantor1,String guarantor2, String fileCharge,
	double loanAmount, double interst, double duration, int frequency,double emiPayment,Date requestDate,String rd_fdNo,String reason,
	int discount, String appChqNo, String appAccNo, String appBankName, String appBankBranch, String g1ChqNo, String g1AccNo, String g1BankName, 
	String g1BankBranch, String g2ChqNo, String g2AccNo, String g2BankName, String g2BankBranch, String dsaCode, double commission, String emiType, 
	String insuranceFee, String center, double extraAmount, double processingCharge)
	{
		Timestamp reqdt=new Timestamp(requestDate.getTime());
		String idDocument = "";
		for (int i = 0; i<idProof.length; i++) 
		{
			idDocument+=idProof[i]+",";
		}
		idDocument=idDocument.substring(0,idDocument.lastIndexOf(","));
		try (Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement stt=conn.createStatement();
			String query="update personalloan set requestDate='"+reqdt+"',idproof='"+idDocument+"',filecharge='"+fileCharge+"',loanAmount='"+loanAmount+"',"
					+ "interest='"+interst+"',terms='"+duration+"',frequency='"+frequency+"',emi='"+emiPayment+"',firstguarantor='"+guarantor1+"',"
							+ "secondguarantor='"+guarantor2+"',reason='"+reason+"',RD_FD_no='"+rd_fdNo+"',discount='"+discount+"',"
									+ "app_chq_no='"+appChqNo+"', app_acc_no='"+appAccNo+"', app_bank_name='"+appBankName+"', app_bank_branch='"+appBankBranch+"'"
											+ ", g1_Chq_No='"+g1ChqNo+"', g1_Acc_No='"+g1AccNo+"', g1_Bank_Name='"+g1BankName+"', g1_Bank_Branch='"+g1BankBranch+"', g2_Chq_No='"+g2ChqNo+"', "
													+ "g2_Acc_No='"+g2AccNo+"', g2_Bank_Name='"+g2BankName+"', g2_Bank_Branch='"+g2BankBranch+"',dsacode='"+dsaCode+"',commission='"+commission+"',"
															+ "emiType='"+emiType+"', insurance_fee='"+insuranceFee+"',center='"+center+"', "
																	+ " extra_amount='"+extraAmount+"', processing_charge='"+processingCharge+"' where id='"+id+"' ";
			int i=stt.executeUpdate(query);
			if(i>=1)
			{ dataInsertInQueryTable(query, conn);
				return 1;
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;

	}

	public int updateSecureLoanRequest(String id,String[] idProof,String guarantor1,String guarantor2, String fileCharge,
	double loanAmount, double interst, double duration, int frequency,double emiPayment,Date requestDate,String rd_fdNo,String reason,
	int discount, String appChqNo, String appAccNo, String appBankName, String appBankBranch, String g1ChqNo, String g1AccNo, String g1BankName, 
	String g1BankBranch, String g2ChqNo, String g2AccNo, String g2BankName, String g2BankBranch, String dsaCode, double commission, String emiType, 
	String insuranceFee, String center, double extraAmount, double billAmount, double downPayment, String imeiNoI, String imeiNoII, String product, String dealer, double dptCharge, double cardFee)
	{
		Timestamp reqdt=new Timestamp(requestDate.getTime());
		String idDocument = "";
		for (int i = 0; i<idProof.length; i++) 
		{
			idDocument+=idProof[i]+",";
		}
		idDocument=idDocument.substring(0,idDocument.lastIndexOf(","));
		try (Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement stt=conn.createStatement();
			String query="update secure_loan set requestDate='"+reqdt+"',idproof='"+idDocument+"',filecharge='"+fileCharge+"',loanAmount='"+loanAmount+"',"
					+ "interest='"+interst+"',terms='"+duration+"',frequency='"+frequency+"',emi='"+emiPayment+"',firstguarantor='"+guarantor1+"',"
							+ "secondguarantor='"+guarantor2+"',reason='"+reason+"',RD_FD_no='"+rd_fdNo+"',discount='"+discount+"',"
									+ "app_chq_no='"+appChqNo+"', app_acc_no='"+appAccNo+"', app_bank_name='"+appBankName+"', app_bank_branch='"+appBankBranch+"'"
											+ ", g1_Chq_No='"+g1ChqNo+"', g1_Acc_No='"+g1AccNo+"', g1_Bank_Name='"+g1BankName+"', g1_Bank_Branch='"+g1BankBranch+"', g2_Chq_No='"+g2ChqNo+"', "
													+ "g2_Acc_No='"+g2AccNo+"', g2_Bank_Name='"+g2BankName+"', g2_Bank_Branch='"+g2BankBranch+"',dsacode='"+dsaCode+"',commission='"+commission+"',"
															+ "emiType='"+emiType+"', insurance_fee='"+insuranceFee+"',center='"+center+"', "
																	+ " extra_amount='"+extraAmount+"',mob_bill_amount='"+billAmount+"',mob_down_payment='"+downPayment+"',mob_imei_no_1='"+imeiNoI+"',mob_imei_no_2='"+imeiNoII+"',mob_dealer='"+dealer+"',mob_product='"+product+"',mob_dpt_charge='"+dptCharge+"' ,mob_card_fee='"+cardFee+"' where id='"+id+"' ";
			int i=stt.executeUpdate(query);
			if(i>=1)
			{ dataInsertInQueryTable(query, conn);
				return 1;
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;

	}

	public int updateBusinessLoanRequest(String id,String[] idProof,String guarantor1,String guarantor2, String fileCharge,
	double loanAmount, double interst, double duration, int frequency,double emiPayment,Date requestDate,String rd_fdNo,String reason,
	int discount, String appChqNo, String appAccNo, String appBankName, String appBankBranch, String g1ChqNo, String g1AccNo, String g1BankName, 
	String g1BankBranch, String g2ChqNo, String g2AccNo, String g2BankName, String g2BankBranch, String dsaCode, double commission, String emiType, 
	String insuranceFee, String center, double extraAmount)
	{
		Timestamp reqdt=new Timestamp(requestDate.getTime());
		String idDocument = "";
		for (int i = 0; i<idProof.length; i++) 
		{
			idDocument+=idProof[i]+",";
		}
		idDocument=idDocument.substring(0,idDocument.lastIndexOf(","));
		try (Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement stt=conn.createStatement();
			String query="update business_loan set requestDate='"+reqdt+"',idproof='"+idDocument+"',filecharge='"+fileCharge+"',loanAmount='"+loanAmount+"',"
					+ "interest='"+interst+"',terms='"+duration+"',frequency='"+frequency+"',emi='"+emiPayment+"',firstguarantor='"+guarantor1+"',"
							+ "secondguarantor='"+guarantor2+"',reason='"+reason+"',RD_FD_no='"+rd_fdNo+"',discount='"+discount+"',"
									+ "app_chq_no='"+appChqNo+"', app_acc_no='"+appAccNo+"', app_bank_name='"+appBankName+"', app_bank_branch='"+appBankBranch+"'"
											+ ", g1_Chq_No='"+g1ChqNo+"', g1_Acc_No='"+g1AccNo+"', g1_Bank_Name='"+g1BankName+"', g1_Bank_Branch='"+g1BankBranch+"', g2_Chq_No='"+g2ChqNo+"', "
													+ "g2_Acc_No='"+g2AccNo+"', g2_Bank_Name='"+g2BankName+"', g2_Bank_Branch='"+g2BankBranch+"',dsacode='"+dsaCode+"',commission='"+commission+"',"
															+ "emiType='"+emiType+"', insurance_fee='"+insuranceFee+"',center='"+center+"', "
																	+ " extra_amount='"+extraAmount+"' where id='"+id+"' ";
			int i=stt.executeUpdate(query);
			if(i>=1)
			{ 
				dataInsertInQueryTable(query, conn);
				return 1;
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;

	}
	
	public int updatePropertyLoanRequest(String id,String[] idProof,String guarantor1,String guarantor2,String category,String registryNo, String verified, String fileCharge,double loanAmount, double interst, double duration, int frequency,
			double emiPayment,Date requestDate,String category2,String registryNo2, String verified2, String jamabandi,String patta, String authorityPatta, 
			String rd_fdNo,int discount, String appChqNo, String appAccNo, String appBankName, String appBankBranch, String g1ChqNo, String g1AccNo, String g1BankName, 
			String g1BankBranch, String g2ChqNo, String g2AccNo, String g2BankName, String g2BankBranch, String dsaCode, 
			double commission, String emiType, String insuranceFee, String center) 
	{
		Timestamp reqdt=new Timestamp(requestDate.getTime());
		String idDocument = "";
		for (int i = 0; i<idProof.length; i++) 
		{
			idDocument+=idProof[i]+",";
		}
		idDocument=idDocument.substring(0,idDocument.lastIndexOf(","));
		try (Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement stt=conn.createStatement();
			String query="update propertyloan set requestDate='"+reqdt+"',idproof='"+idDocument+"',category='"+category+"',registryNo='"+registryNo+"',jamabandi='"+jamabandi+"',patta='"+patta+"',authorityPatta='"+authorityPatta+"',verified='"+verified+"',filecharge='"+fileCharge+"',loanAmount='"+loanAmount+"',interest='"+interst+"',terms='"+duration+"',frequency='"+frequency+"',emi='"+emiPayment+"',firstguarantor='"+guarantor1+"',secondguarantor='"+guarantor2+"',RD_FD_no='"+rd_fdNo+"',discount='"+discount+"',app_chq_no='"+appChqNo+"', app_acc_no='"+appAccNo+"', app_bank_name='"+appBankName+"', app_bank_branch='"+appBankBranch+"',g1_Chq_No='"+g1ChqNo+"', g1_Acc_No='"+g1AccNo+"', g1_Bank_Name='"+g1BankName+"', g1_Bank_Branch='"+g1BankBranch+"', g2_Chq_No='"+g2ChqNo+"', "
						+ "g2_Acc_No='"+g2AccNo+"',emiType='"+emiType+"', g2_Bank_Name='"+g2BankName+"', g2_Bank_Branch='"+g2BankBranch+"',dsacode='"+dsaCode+"',"
								+ "commission='"+commission+"', insurance_fee='"+insuranceFee+"',center='"+center+"' where id='"+id+"'";
			int i=stt.executeUpdate(query);
			if(i>=1)
			{
				dataInsertInQueryTable(query, conn);
				return 1;
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public int updateVehicleLoanRequest(String id,String[] idProof,String guarantor1, String guarantor2, String category,
	String vechileName, String model, String engineNo, String macNo,String fileCharge, double loanAmount, double interst,
	double duration, int frequency, double emiPayment,Date requestDate, String rd_fdNo,int discount, String appChqNo, String appAccNo, String appBankName, 
	String appBankBranch, String g1ChqNo, String g1AccNo, String g1BankName, String g1BankBranch, String g2ChqNo, String g2AccNo, String g2BankName, 
	String g2BankBranch, String dsaCode, double commission, String emiType, String insuranceFee, String center)
	{
		Timestamp reqdt=new Timestamp(requestDate.getTime());
		String idDocument = "";
		for (int i = 0; i<idProof.length; i++) 
		{
			idDocument+=idProof[i]+",";
		}
		idDocument=idDocument.substring(0,idDocument.lastIndexOf(","));
		try (Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement stt=conn.createStatement();
			String query="update vechicleloan set requestDate='"+reqdt+"',idproof='"+idDocument+"',category='"+category+"',vechileName='"+vechileName+"',model='"+model+"',engineno='"+engineNo+"',macNo='"+macNo+"',filecharge='"+fileCharge+"',loanAmount='"+loanAmount+"',interest='"+interst+"',terms='"+duration+"',frequency='"+frequency+"',emi='"+emiPayment+"',firstguarantor='"+guarantor1+"',secondguarantor='"+guarantor2+"',RD_FD_no='"+rd_fdNo+"',discount='"+discount+"',app_chq_no='"+appChqNo+"', app_acc_no='"+appAccNo+"', app_bank_name='"+appBankName+"', app_bank_branch='"+appBankBranch+"',g1_Chq_No='"+g1ChqNo+"', g1_Acc_No='"+g1AccNo+"', g1_Bank_Name='"+g1BankName+"', g1_Bank_Branch='"+g1BankBranch+"', g2_Chq_No='"+g2ChqNo+"', "
													+ "g2_Acc_No='"+g2AccNo+"', g2_Bank_Name='"+g2BankName+"', g2_Bank_Branch='"+g2BankBranch+"',dsacode='"+dsaCode+"',"
															+ "commission='"+commission+"',emiType='"+emiType+"', insurance_fee='"+insuranceFee+"',center='"+center+"' where id='"+id+"'";
			int i=stt.executeUpdate(query);
			if(i>=1)
			{
				dataInsertInQueryTable(query, conn);
				return 1;
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	
	public String loanPayReceiptNoByLoanNo(int i,String loanNo,Connection con)
    {
         Statement st=null;
         ResultSet rr=null;
        try
        {
           st=con.createStatement();
            String query="select receipt_no from loanpayment where emi_no='"+i+"' and loanNo='"+loanNo+"' and restructure='No' and receipt_status='approved' and chequeStatus='cleared' ";
            rr=st.executeQuery(query);
            if(rr.next())
            {
                return rr.getString("receipt_no");
            }
        }
        catch(Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        finally
        {
            try {
                if(st!=null)
                {
                    st.close();
                }
                if(rr!=null)
                {
                    rr.close();
                }
            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
        return "";
    }

	public int UpdateGroupLoanRequest(String id, String[] idProof,String fileCharge, double loanAmount, double interst,double duration,
	double frequency, double emiPayment,Date requestDate, ArrayList<UserInfo> userList, String center,String rd_fdNo, 
	int discount, String appChqNo, String appAccNo, String appBankName, String appBankBranch, String g1ChqNo, String g1AccNo, String g1BankName, String g1BankBranch, 
	String g2ChqNo, String g2AccNo, String g2BankName, String g2BankBranch, String dsaCode, double commission, String insuranceFee, String emiType, double extraAmount, 
	String loanCategory, String loanCycle, String loanPurpose, String repaymentFreq) 
	{
		String member = "";
		for(UserInfo ls:userList)
		{
			if(member=="")
			{
				member=ls.getShareHolderNo();
			}
			else
			{
				member=member+","+ls.getShareHolderNo();
			}
		}
		Timestamp ss = new Timestamp(requestDate.getTime());

		String idDocument = "";
		for (int i = 0; i<idProof.length; i++) 
		{
			idDocument+=idProof[i]+",";
		}
		idDocument=idDocument.substring(0,idDocument.lastIndexOf(","));
		try (Connection conn = DataBaseConnection.JAVAConnection();) 
		{
			Statement stt = conn.createStatement();
			String query = "update grouploan set idproof='"+idDocument+"', filecharge='"+fileCharge+"', loanAmount='"+loanAmount+"', interest='"+interst+"', terms='"+duration+"',"
					+ " frequency='"+frequency+"', emi='"+emiPayment+"', requestDate='"+ss+"',members='"+member+"', center='"+center+"',RD_FD_no='"+rd_fdNo+"',discount='"+discount+"',"
							+ "app_chq_no='"+appChqNo+"', app_acc_no='"+appAccNo+"', app_bank_name='"+appBankName+"', app_bank_branch='"+appBankBranch+"',g1_Chq_No='"+g1ChqNo+"',"
									+ " g1_Acc_No='"+g1AccNo+"', g1_Bank_Name='"+g1BankName+"', g1_Bank_Branch='"+g1BankBranch+"', g2_Chq_No='"+g2ChqNo+"', "
													+ "g2_Acc_No='"+g2AccNo+"', g2_Bank_Name='"+g2BankName+"', g2_Bank_Branch='"+g2BankBranch+"',dsacode='"+dsaCode+"',"
															+ "commission='"+commission+"',emiType='"+emiType+"', insurance_fee='"+insuranceFee+"' "
																	+ " , extra_amount='"+extraAmount+"' , loan_category='"+loanCategory+"', loan_cycle='"+loanCycle+"', "
																			+ "loan_purpose='"+loanPurpose+"', repayment_frequency='"+repaymentFreq+"' where id='"+id+"'";
			int j = stt.executeUpdate(query);
			if (j >= 1) {
				dataInsertInQueryTable(query, conn);
				return 1;
			}
		}
		catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	/*public ArrayList<LoanInfo> loanInstallment(String loanType,String loanNo)
    {
        double temp=0;
        String qq="";
        int j=0;
        ArrayList<LoanInfo> list = new ArrayList<LoanInfo>();
        try (Connection con = DataBaseConnection.JAVAConnection();)
        {
            Statement st = con.createStatement();
            if(loanType.equals("grouploan"))
            {
                qq = "select * from "+loanType+" where sub_loan_no='"+loanNo+"' and status='approve'";
            }
            else
            {
                qq = "select * from "+loanType+" where loanNo='"+loanNo+"' and status='approve'";
            }
           
        //    // // // //System.out.println(qq);
            ResultSet rs = st.executeQuery(selectQueWithBranch(qq,branchId));
            if(rs.next())
            {
                if(rs.getString("emiType").equals("reducing"))
                {
                    double discount=discountOnLastEMI(loanType,loanNo);
                    double paidAmount=loanPaidAmountByUser(loanType,loanNo);
                    int terms = rs.getInt("terms");
                    int frequency=rs.getInt("frequency");
                    double emi=rs.getDouble("emi");
                    double interstRate=rs.getDouble("interest");
                    double loanAmount=rs.getDouble("loanAmount");
                    Date offcdt =null;
                    if(rs.getDate("emi_due_date")==null)
                    {
                        offcdt =rs.getDate("approvalDate");
                    }
                    else
                    {
                        offcdt = rs.getDate("emi_due_date");
                    }
                    //double interestMonthly =Double.parseDouble(new DecimalFormat("##.###").format(interstRate / (100.00 * frequency)));
                    double fr=(double) frequency;
                    Date installDate=null;
                    j=365/frequency;
                    if(rs.getDate("emi_due_date")==null)
                    {
                        installDate=rs.getDate("approvalDate");
                    }
                    else
                    {
                        installDate=rs.getDate("emi_due_date");
                        if(frequency==12)
                        {
                            installDate.setMonth(installDate.getMonth()-1);
                        }
                        else
                        {
                            installDate.setDate(installDate.getDate()-j);
                        }
                    }   
                   int y=1;
                    for (int i = 1; i<= terms; i++)
                    {
                        LoanInfo ll=new LoanInfo();
                        //int j=365/frequency;
                        ll.setSno(i);
                        if(i==terms)
                        {
                            emi=emi-discount;
                            ll.setInstallAmount(emi);
                        }
                        else
                        {
                            ll.setInstallAmount(emi);
                        }
                       
                        if(paidAmount>=emi)
                        {
                            ll.setStatus("Paid");
                            ll.setPaidAmount(emi);
                            ll.setDueAmount(0);
                            paidAmount=Double.parseDouble(df.format(paidAmount-emi));
                        }
                        else
                        {
                            ll.setStatus("Due");
                            ll.setPaidAmount(paidAmount);
                            ll.setDueAmount(Double.parseDouble(df.format(emi-paidAmount)));
                            paidAmount=0;
                        }
                   
                        Date dt=installDate;
                        if(rs.getDate("emi_due_date")==null)
                        {
                            dt.setDate(dt.getDate()+j);
                        }
                        else
                        {
                        	 if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
                             {
                                   if(frequency==4)
                                   {
                                       y=4;
                                       //x=terms/3;
                                   }
                                   else if(frequency==2)
                                   {
                                       y=6;
                                       //x=terms/6;
                                   }
                                   else if(frequency==1)
                                   {
                                       y=12;
                                       //x=terms/12;
                                   }
                                   else if(frequency==12)
                                   {
                                       y=1;
                                       //x=terms;
                                   }
                                 offcdt=createDate2(offcdt,y,terms,offcdt.getDate(),rs.getDate("emi_due_date"));
                             }
                          
                            else
                            {
                                dt.setDate(dt.getDate()+j);
                            }
                           
                        }
                        if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
                        {
                            ll.setStrInstlmntDate(sf.format(offcdt));
                            SimpleDateFormat dd=sf;
                            Date ss=dd.parse(ll.getStrInstlmntDate());
                            ll.setInstallDate(ss);
                        }
                        else
                        {
                        ll.setStrInstlmntDate(sf.format(dt));
                        SimpleDateFormat dd=sf;
                        Date ss=dd.parse(ll.getStrInstlmntDate());
                        ll.setInstallDate(ss);
                        }
                       
                        ll.setPaidDate(loanPaidDate(i, loanNo));
                        if(ll.getPaidAmount() > 0)
                        {
                            
                        if(ll.getPaidDate()==null)
                        {
                            ll.setPaidDateStr("- - - -");
                        }
                        else
                        {
                            ll.setPaidDateStr(new SimpleDateFormat("dd/MM/yyyy").format(loanPaidDate(i, loanNo)));
                            ll.setReceiptNo(loanPayReceiptNoByLoanNo(i, loanNo, con));
                        }
                        }
                        else
                        {
                            ll.setPaidDateStr("- - - -");
                        }
                       
                        
                        double frstIntrstAmnt=(loanAmount*interstRate)/(100*fr);
                        ll.setInterestAmount(df.format((frstIntrstAmnt)));
                       
                        double paidPrincipalAmnt=emi-(frstIntrstAmnt);
                        ll.setPrincipalAmount(df.format(paidPrincipalAmnt));
                       
                        double principalRemaining=loanAmount-paidPrincipalAmnt;
                       
                        list.add(ll);
                        loanAmount=principalRemaining;
                    }
                }
                else
                {
                	String emiMode="";
                	if(loanType.equalsIgnoreCase("personalloan"))
                	{
                		emiMode=rs.getString("emi_mode");
                	}
                	else
                	{
                		emiMode="both";
                	}
                	if(emiMode.equalsIgnoreCase("both"))
                	{
                		  double discount=discountOnLastEMI(loanType,loanNo);
                          double paidAmount=loanPaidAmountByUser(loanType,loanNo);
                          int terms = rs.getInt("terms");
                          int frequency=rs.getInt("frequency");
                          Date offcdt =null;
                          if(rs.getDate("emi_due_date")==null)
                          {
                              offcdt =rs.getDate("approvalDate");
                          }
                          else
                          {
                              offcdt = rs.getDate("emi_due_date");
                          }
                          double emi=rs.getDouble("emi");
                          double interstRate=rs.getDouble("interest");
                          double loanAmount=rs.getDouble("loanAmount");
                          double totalInterest=Double.parseDouble(df.format((emi*terms)-loanAmount));
                          //double interestMonthly=(totalInterest-rs.getDouble("discount"))/terms;
                          double interestMonthly=totalInterest/terms;
                          Date installDate=null;
                          j=365/frequency;
                         
                          if(rs.getDate("emi_due_date")==null)
                          {
                              installDate=rs.getDate("approvalDate");
                          }
                          else
                          {
                              installDate=rs.getDate("emi_due_date");
                              if(frequency==12)
                              {
                                  installDate.setMonth(installDate.getMonth()-1);
                              }
                              else
                              {
                                  installDate.setDate(installDate.getDate()-j);
                              }
                          }
                          int y=1;
                          for (int i = 1; i<= terms; i++)
                          {
                              LoanInfo ll=new LoanInfo();
                              ll.setSno(i);
                              if(i==terms)
                              {
                              	emi=emi-discount;
                                  ll.setInstallAmount(emi);
                              }
                              else
                              {
                                  ll.setInstallAmount(emi);
                              }
                             
                              if(paidAmount>=emi)
                              {
                                  ll.setStatus("Paid");
                                  ll.setPaidAmount(emi);
                                  ll.setDueAmount(0);
                                  paidAmount=Double.parseDouble(df.format(paidAmount-emi));
                              }
                              else
                              {
                                  ll.setStatus("Due");
                                  ll.setPaidAmount(paidAmount);
                                  ll.setDueAmount(Double.parseDouble(df.format(emi-paidAmount)));
                                  paidAmount=0;
                              }
                         
                              Date dt=installDate;
                              if(rs.getDate("emi_due_date")==null)
                              {
                                  dt.setDate(dt.getDate()+j);
                              }
                              else
                              {
                            	  if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
                                  {
                                        if(frequency==4)
                                        {
                                            y=4;
                                            //x=terms/3;
                                        }
                                        else if(frequency==2)
                                        {
                                            y=6;
                                            //x=terms/6;
                                        }
                                        else if(frequency==1)
                                        {
                                            y=12;
                                            //x=terms/12;
                                        }
                                        else if(frequency==12)
                                        {
                                            y=1;
                                            //x=terms;
                                        }
                                      offcdt=createDate2(offcdt,y,terms,offcdt.getDate(),rs.getDate("emi_due_date"));
                                  }
                                  else
                                  {
                                      dt.setDate(dt.getDate()+j);
                                  }
                              }

                              if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
                              {
                                  ll.setStrInstlmntDate(sf.format(offcdt));
                                  SimpleDateFormat dd=sf;
                                  Date ss=dd.parse(ll.getStrInstlmntDate());
                                  ll.setInstallDate(ss);
                              }
                              else
                              {
                              ll.setStrInstlmntDate(sf.format(dt));
                              SimpleDateFormat dd=sf;
                              Date ss=dd.parse(ll.getStrInstlmntDate());
                              ll.setInstallDate(ss);
                              }
                              ll.setPaidDate(loanPaidDate(i, loanNo));
                              if(ll.getPaidAmount() > 0)
                              {
                                  
                              if(ll.getPaidDate()==null)
                              {
                                  ll.setPaidDateStr("- - - -");
                              }
                              else
                              {
                                  ll.setPaidDateStr(new SimpleDateFormat("dd/MM/yyyy").format(loanPaidDate(i, loanNo)));
                                  ll.setReceiptNo(loanPayReceiptNoByLoanNo(i, loanNo,con));
                              }
                              }
                              else
                              {
                                  ll.setPaidDateStr("- - - -");
                              }
                            
                              
                              double frstIntrstAmnt=interestMonthly;
                              ll.setInterestAmount(df.format((frstIntrstAmnt)));
                             
                              double paidPrincipalAmnt=emi-(frstIntrstAmnt);
                              ll.setPrincipalAmount(df.format(paidPrincipalAmnt));
                             
                              //double principalRemaining=loanAmount-paidPrincipalAmnt;
                             
                              list.add(ll);
                              //loanAmount=principalRemaining;
                          }
                	}
                	else
                	{
                		double discount=rs.getDouble("discount");
						double paidAmount=loanPaidAmountByUser(loanType,loanNo);
						int terms = rs.getInt("terms");
						int frequency=rs.getInt("frequency");
						double emi=rs.getDouble("emi");
						double interstRate=rs.getDouble("interest");
						double loanAmount=rs.getDouble("loanAmount");
						//double interestMonthly =Double.parseDouble(new DecimalFormat("##.#######").format(interstRate / (100.00 * frequency)));
						double totalInterest=Double.parseDouble(df.format((emi*terms)));
						
						double interestMonthly=totalInterest/terms;
						Date installDate=null;
						boolean chk=true;

						if(rs.getDate("emi_due_date")==null)
						{
							installDate=rs.getDate("approvalDate");
						}
						else
						{
							installDate=rs.getDate("emi_due_date");
						}
						for (int i = 1; i<= terms; i++) 
						{
							LoanInfo ll=new LoanInfo();
							int jj=365/frequency;
							ll.setSno(i);
							if(i==terms)
							{
								emi=emi-discount;
								ll.setInstallAmount(emi);
							}
							else
							{
								ll.setInstallAmount(emi);
							}
							
							if(paidAmount>=emi)
							{
								ll.setStatus("Paid");
								ll.setPaidAmount(emi);
								ll.setDueAmount(0);
								paidAmount=Double.parseDouble(df.format(paidAmount-emi));
							}
							else
							{
								ll.setStatus("Due");
								ll.setPaidAmount(paidAmount);
								ll.setDueAmount(Double.parseDouble(df.format(emi-paidAmount)));
								paidAmount=0;
							}
							Date dt=installDate;
							if(rs.getDate("emi_due_date")==null)
							{
								dt.setDate(dt.getDate()+jj);
							}
							else
							{
								if(chk==true)
								{
									dt.setMonth(dt.getMonth());
									chk=false;
								}
								else
								{
									dt.setMonth(dt.getMonth()+1);
								}
							}
							ll.setInstallDate(dt);
							
							 ll.setPaidDate(loanPaidDate(i, loanNo));
		                        if(ll.getPaidAmount() > 0)
		                        {
		                            
		                        if(ll.getPaidDate()==null)
		                        {
		                            ll.setPaidDateStr("- - - -");
		                        }
		                        else
		                        {
		                            ll.setPaidDateStr(new SimpleDateFormat("dd/MM/yyyy").format(loanPaidDate(i, loanNo)));
		                            ll.setReceiptNo(loanPayReceiptNoByLoanNo(i, loanNo, con));
		                        }
		                        }
		                        else
		                        {
		                            ll.setPaidDateStr("- - - -");
		                        }
		                       
		                        
							ll.setStrInstlmntDate(new SimpleDateFormat("dd/MM/yyyy").format(dt));
							
							double frstIntrstAmnt=interestMonthly;
							ll.setInterestAmount(df.format((frstIntrstAmnt)));
							double paidPrincipalAmnt=emi-(frstIntrstAmnt);
							ll.setPrincipalAmount(df.format(paidPrincipalAmnt));
							list.add(ll);
						}
                	}
                  
                }
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
       
        int i=0;
        loopx:for(LoanInfo ll: list)
        {
            if(ll.getStatus().equalsIgnoreCase("Paid"))
            {
                i=i+1;
                // // // //System.out.println(i);
                //lastPaidDate=ll.getInstallDate();
                // // // //System.out.println(ll.getInstallDate());
                break loopx;
            }
           
        }
        return list;
    }
*/
	
	
	public ArrayList<LoanInfo> loanInstallmentByUnpaidStatus(String loanType,String loanNo, Connection conn)
    {
        double temp=0;
        String qq="";
        int j=0, x = 0;
        
        DbYashwant dby = new DbYashwant();
        
        Statement st=null;
		ResultSet rs=null;
		boolean checkGroupLoanEmi=false;
        ArrayList<LoanInfo> list = new ArrayList<LoanInfo>();
        try
        {
            st = conn.createStatement();
            if(loanType.equals("grouploan"))
            {
                qq = "select * from "+loanType+" where sub_loan_no='"+loanNo+"' and status='Approve' " ;
               
            }
            else
            {
                 qq = "select * from "+loanType+" where loanNo='"+loanNo+"' and status='Approve'"  ;
            }  
            
            System.out.println("qiery is :"+qq);
            
           
            checkGroupLoanEmi=checkGroupLoanEmiFromTable(loanNo,conn);
            
            if (checkGroupLoanEmi) 
            {
            	x = firstGroupLoanEmiNoFromTable(loanNo, conn);
			}
            
            rs = st.executeQuery(qq);
            if(rs.next())
            {   
                if(rs.getString("emiType").equals("reducing"))
                {
                    double discount=discountOnLastEMI(loanType,loanNo,conn);
                    double paidAmount=loanPaidAmountByUser(loanType,loanNo,conn);
                    int terms = rs.getInt("terms");
                    int frequency=rs.getInt("frequency");
                    double emi=rs.getDouble("emi");
                    Date offcdt =null;
                    if(rs.getDate("emi_due_date")==null)
                    {
                        offcdt =rs.getDate("approvalDate");
                       
                    }
                    else
                    {
                    	
                        offcdt = rs.getDate("emi_due_date");
                        System.out.println("value of the emi Due Date :"+offcdt);
                        
                    }
                    double interstRate=rs.getDouble("interest");
                    double loanAmount=rs.getDouble("loanAmount");
                    double fr=(double) frequency;
                    Date installDate=null;
                    j=365/frequency;
                    if(rs.getDate("emi_due_date")==null)
                    {
                        installDate=rs.getDate("approvalDate");
                    }
                    else
                    {
                        installDate=rs.getDate("emi_due_date");
                        if(frequency==12)
                        {
                            installDate.setMonth(installDate.getMonth()-1);
                        }
                        else
                        {
                            installDate.setDate(installDate.getDate()-j);
                        }
                    }  
                    
                   
                    
                    int y=1;
                    for (int i = 1; i<= terms; i++)
                    {
                        LoanInfo ll=new LoanInfo();
                        //int j=365/frequency;

                        
                        ll.setSno(i);
                        if(i==terms)
                        {
                            emi=emi-discount;
                            ll.setInstallAmount(emi);
                        }
                        else
                        {
                            ll.setInstallAmount(emi);
                        }
                        
                        if(paidAmount>=emi)
                        {
                            ll.setStatus("Paid");
                            
                            
                            ll.setPaidAmount(emi);
                            ll.setDueAmount(0);
                            paidAmount=Double.parseDouble(df.format(paidAmount-emi));
                        }
                        else
                        {
                            ll.setStatus("Due");
                            ll.setPaidAmount(paidAmount);
                            ll.setDueAmount(Double.parseDouble(df.format(emi-paidAmount)));
                            	
                            paidAmount=0;
                        }
                  
                        Date dt=installDate;
                        if(rs.getDate("emi_due_date")==null)
                        {
                            dt.setDate(dt.getDate()+j);
                        }
                        else
                        {
                            if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
                              {
                                    if(frequency==4)
                                    {
                                        y=4;
                                        //x=terms/3;
                                    }
                                    else if(frequency==2)
                                    {
                                        y=6;
                                        //x=terms/6;
                                    }
                                    else if(frequency==1)
                                    {
                                        y=12;
                                        //x=terms/12;
                                    }
                                    else if(frequency==12)
                                    {
                                        y=1;
                                        //x=terms;
                                    }
                                  offcdt=createDate2(offcdt,y,i,offcdt.getDate(),rs.getDate("emi_due_date"));
                              }
                            else
                            {
                                dt.setDate(dt.getDate()+j);
                            }
                          
                        }
                        
                        if(checkGroupLoanEmi==false && (frequency==12 || frequency==4 || frequency==2 || frequency==1))
                        {
                            ll.setStrInstlmntDate(sf.format(offcdt));
                            SimpleDateFormat dd=sf;
                            Date ss=dd.parse(ll.getStrInstlmntDate());
                            ll.setInstallDate(ss);
                        }
                        else
                        {
                        	  if(checkGroupLoanEmi==true && x==i)  // Condition for Manage Meeting Day Change
                        	  {
                        		  dt=groupLoanEmiDateFromTable(i,loanNo,conn);
                        		  x++;
                        	  }
	                        ll.setStrInstlmntDate(sf.format(dt));
	                        SimpleDateFormat dd=sf;
	                        Date ss=dd.parse(ll.getStrInstlmntDate());
	                        ll.setInstallDate(ss);
                        }
                        
                       // ll.setPaidDate(loanPaidDate(i, loanNo, conn));
                        
                        Date paidDate = loanPaidDate(i, loanNo, conn);     //work by raviKumar
                        System.out.println("paid date is:"+paidDate);
                        
                        
                        ll.setPaidDate(paidDate);
                        ll.setEmiPaidDate(paidDate);
                        
                        
                        if (paidDate != null)
                        {
                            ll.setEmiPaidDateStr(new SimpleDateFormat("dd/MM/yyyy").format(paidDate));
                        }
                        
                        else
                        {
                            ll.setEmiPaidDateStr("- - - -");
                        }
                        
                       // ll.setEmiPaidDateStr( new SimpleDateFormat("dd/MM/yyyy").format(loanPaidDate(i, loanNo, conn)));
                        
                       /* if(ll.getPaidAmount() > 0)
                        {
                           
                        if(ll.getPaidDate()==null)
                        {
                            ll.setPaidDateStr("- - - -");
                        }
                        else
                        {
                            ll.setPaidDateStr(new SimpleDateFormat("dd/MM/yyyy").format(loanPaidDate(i, loanNo, conn)));
                            ll.setReceiptNo(loanPayReceiptNoByLoanNo(i, loanNo, conn));
                        }
                        }
                        else
                        {
                            ll.setPaidDateStr("- - - -");
                        }*/// comment by GARG on 07 jan 2020 
                        ll.setPaidDateStr("- - - -");
                      
                       
                        double frstIntrstAmnt=(loanAmount*interstRate)/(100*fr);
                        ll.setInterestAmount(df.format((frstIntrstAmnt)));
                        ll.setInterest(Double.parseDouble(df.format(frstIntrstAmnt)));
                      
                        double paidPrincipalAmnt=emi-(frstIntrstAmnt);
                        ll.setPrincipalAmount(df.format(paidPrincipalAmnt));
                        ll.setPrincipal(Double.parseDouble(df.format(paidPrincipalAmnt)));
                      
                        double principalRemaining=loanAmount-paidPrincipalAmnt;
                        ll.setPrincipalBalanceStr(df.format(principalRemaining));
                        
                        list.add(ll);
                        loanAmount=principalRemaining;
                    }
                }
                else
                {
                	 String emiMode="";
                    if(loanType.equalsIgnoreCase("grouploan"))
                    {
                    	emiMode="both";
                    }
                    else
                    {
                    	emiMode=rs.getString("emi_mode");
                    }
                    if(emiMode.equalsIgnoreCase("both"))
                    {
                          double discount=discountOnLastEMI(loanType,loanNo, conn);
                             Date offcdt =null;
                             if(rs.getDate("emi_due_date")==null)
                             {
                                 offcdt =rs.getDate("approvalDate");
                             }
                             else
                             {
                                 offcdt = rs.getDate("emi_due_date");
                             }
                            
                          double paidAmount=loanPaidAmountByUser(loanType,loanNo, conn);
                          int terms = rs.getInt("terms");
                          int frequency=rs.getInt("frequency");
                          double emi=rs.getDouble("emi");
                          double interstRate=rs.getDouble("interest");
                          double loanAmount=rs.getDouble("loanAmount");
                          double totalInterest=Double.parseDouble(df.format((emi*terms)-loanAmount));
                          //double interestMonthly=(totalInterest-rs.getDouble("discount"))/terms;
                          double interestMonthly=totalInterest/terms;
                          Date installDate=null;
                          j=365/frequency;
                        
                          if(rs.getDate("emi_due_date")==null)
                          {
                              installDate=rs.getDate("approvalDate");
                          }
                          else
                          {
                              installDate=rs.getDate("emi_due_date");
                              if(frequency==12)
                              {
                                  installDate.setMonth(installDate.getMonth()-1);
                              }
                              else
                              {
                                  installDate.setDate(installDate.getDate()-j);
                              }
                          }
                          int y=1;
                          for (int i = 1; i<= terms; i++)
                          {
                              	                        	  
                        	  LoanInfo ll=new LoanInfo();
                        	  ll.setEmiPaidDate1(dby.selectEmiPaidDate(i,loanNo,conn));
                        	  Date paidDate = loanPaidDate(i, loanNo, conn);
	  	                      ll.setPaidDate(paidDate);
	  	                      ll.setEmiPaidDate(paidDate);
                              ll.setSno(i);
                              if(i==terms)
                              {
                                  emi=emi-discount;
                                  ll.setInstallAmount(emi);
                              }
                              else
                              {
                                  ll.setInstallAmount(emi);
                              }
                            
                              if(paidAmount>=emi)
                              {
                                  ll.setStatus("Paid");
                                  ll.setPaidAmount(emi);
                                  ll.setDueAmount(0);
                                  paidAmount=Double.parseDouble(df.format(paidAmount-emi));
                              }
                              else
                              {
                                  ll.setStatus("Due");
                                  ll.setPaidAmount(paidAmount);
                                  ll.setDueAmount(Double.parseDouble(df.format(emi-paidAmount)));
                                  paidAmount=0;
                              }
                        
                              Date dt=installDate;
                              if(rs.getDate("emi_due_date")==null)
                              {
                                  dt.setDate(dt.getDate()+j);
                              }
                              else
                              {
                                  if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
                                  {
                                        if(frequency==4)
                                        {
                                            y=4;
                                            //x=terms/3;
                                        }
                                        else if(frequency==2)
                                        {
                                            y=6;
                                            //x=terms/6;
                                        }
                                        else if(frequency==1)
                                        {
                                            y=12;
                                            //x=terms/12;
                                        }
                                        else if(frequency==12)
                                        {
                                            y=1;
                                            //x=terms;
                                        }
                                      offcdt=createDate2(offcdt,y,i,offcdt.getDate(),rs.getDate("emi_due_date"));
                                  }
                                  else
                                  {
                                      dt.setDate(dt.getDate()+j);
                                  }
                              }
                              if(checkGroupLoanEmi==false && (frequency==12 || frequency==4 || frequency==2 || frequency==1))
                              {
                                  // System.out.println("hsjhhjhjhjhjhjhh "+offcdt);
                                  ll.setStrInstlmntDate(sf.format(offcdt));
                                  SimpleDateFormat dd=sf;
                                  Date ss=dd.parse(ll.getStrInstlmntDate());
                                  ll.setInstallDate(ss);
                              }
                              else
                              {
                            	  if(checkGroupLoanEmi==true)  // Condition for Manage Meeting Day Change
                            	  {
                            		  dt=groupLoanEmiDateFromTable(i,loanNo,conn);
                            	  }
	                              ll.setStrInstlmntDate(sf.format(dt));
	                              SimpleDateFormat dd=sf;
	                              Date ss=dd.parse(ll.getStrInstlmntDate());
	                              ll.setInstallDate(ss);
                              }
                             
                             /* ll.setPaidDate(loanPaidDate(i, loanNo, conn));
                              if(ll.getPaidAmount() > 0)
                              {
                                 
                              if(ll.getPaidDate()==null)
                              {
                                  ll.setPaidDateStr("- - - -");
                              }
                              else
                              {
                                  ll.setPaidDateStr(new SimpleDateFormat("dd/MM/yyyy").format(loanPaidDate(i, loanNo, conn)));
                                  ll.setReceiptNo(loanPayReceiptNoByLoanNo(i, loanNo,conn));
                              }
                              }
                              else
                              {
                                  ll.setPaidDateStr("- - - -");
                              }*/
                           // comment by GARG on 07 jan 2020 
  	                        ll.setPaidDateStr("- - - -");
                             
                              double frstIntrstAmnt=interestMonthly;
                              ll.setInterestAmount(df.format((frstIntrstAmnt)));
                              ll.setInterest(Double.parseDouble(df.format(frstIntrstAmnt)));
                            
                              double paidPrincipalAmnt=emi-(frstIntrstAmnt);
                              ll.setPrincipalAmount(df.format(paidPrincipalAmnt));
                              ll.setPrincipal(Double.parseDouble(df.format(paidPrincipalAmnt)));
	                            
                              //double principalRemaining=loanAmount-paidPrincipalAmnt;
                            
                              list.add(ll);
                              //loanAmount=principalRemaining;
                          }
                    }
                    else
                    {
                        double discount=rs.getDouble("discount");
                        Date offcdt =null;
                        if(rs.getDate("emi_due_date")==null)
                        {
                            offcdt =rs.getDate("approvalDate");
                        }
                        else
                        {
                            offcdt = rs.getDate("emi_due_date");
                        }
                        double paidAmount=loanPaidAmountByUser(loanType,loanNo, conn);
                        int terms = rs.getInt("terms");
                        int frequency=rs.getInt("frequency");
                        double emi=rs.getDouble("emi");
                        double interstRate=rs.getDouble("interest");
                        double loanAmount=rs.getDouble("loanAmount");
                        //double interestMonthly =Double.parseDouble(new DecimalFormat("##.#######").format(interstRate / (100.00 * frequency)));
                        double totalInterest=Double.parseDouble(df.format((emi*terms)));
                       System.out.println("Total interst :"+totalInterest);
                        double interestMonthly=totalInterest/terms;
                        System.out.println("Total interst :"+totalInterest);
                        Date installDate=null;
                        boolean chk=true;
                        j=365/frequency;
                        double fr=(double) frequency;

                        if(rs.getDate("emi_due_date")==null)
                        {
                            installDate=rs.getDate("approvalDate");
                        }
                        else
                          {
                              installDate=rs.getDate("emi_due_date");
                              if(frequency==12)
                              {
                                  installDate.setMonth(installDate.getMonth()-1);
                              }
                              else if(frequency==4)
                              {
                                  installDate.setMonth(installDate.getMonth()-3);
                              }
                              else
                              {
                                  installDate.setDate(installDate.getDate()-j);
                              }
                          }
                        
                        int y=1;
                        for (int i = 1; i<= terms; i++)
                        {
                            LoanInfo ll=new LoanInfo();
//                            ll.setEmiPaidDate1(dby.selectEmiPaidDate(i,loanNo));
                            //int jj=365/frequency;
                            ll.setSno(i);
                            if(i==terms)
                            {
                                emi=emi-discount;
                                ll.setInstallAmount(emi);
                            }
                            else
                            {
                                ll.setInstallAmount(emi);
                            }
                           
                            if(paidAmount>=emi)
                            {
                                ll.setStatus("Paid");
                                ll.setPaidAmount(emi);
                                ll.setDueAmount(0);
                                paidAmount=Double.parseDouble(df.format(paidAmount-emi));
                            }
                            else
                            {
                                ll.setStatus("Due");
                                ll.setPaidAmount(paidAmount);
                                ll.setDueAmount(Double.parseDouble(df.format(emi-paidAmount)));
                                paidAmount=0;
                            }
                            
                            //comment on 23-oct-2019 due to problem in MTOS nidhi
                            /*Date dt=installDate;
                            if(rs.getDate("emi_due_date")==null)
                            {
                                dt.setDate(dt.getDate()+jj);
                            }
                            else
                            {
                                if(chk==true)
                                {
                                    dt.setMonth(dt.getMonth());
                                    chk=false;
                                }
                                else
                                {
                                    dt.setMonth(dt.getMonth()+1);
                                }
                            }
                            ll.setInstallDate(dt);
                            */
                            

                            Date dt=installDate;
                              if(rs.getDate("emi_due_date")==null)
                              {
                                  dt.setDate(dt.getDate()+j);
                              }
                              else
                              {
                                  if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
                                  {
                                        if(frequency==4)
                                        {
                                            y=4;
                                            //x=terms/3;
                                        }
                                        else if(frequency==2)
                                        {
                                            y=6;
                                            //x=terms/6;
                                        }
                                        else if(frequency==1)
                                        {
                                            y=12;
                                            //x=terms/12;
                                        }
                                        else if(frequency==12)
                                        {
                                            y=1;
                                            //x=terms;s
                                        }
                                        offcdt=createDate2(offcdt,y,i,offcdt.getDate(),rs.getDate("emi_due_date"));
                                  }
                                  else
                                  {
                                      dt.setDate(dt.getDate()+j);
                                  }
                              }
                              if(checkGroupLoanEmi==false && (frequency==12 || frequency==4 || frequency==2 || frequency==1))
                              {
                                  // System.out.println("hsjhhjhjhjhjhjhh "+offcdt);
                                  ll.setStrInstlmntDate(sf.format(offcdt));
                                  SimpleDateFormat dd=sf;
                                  Date ss=dd.parse(ll.getStrInstlmntDate());
                                  ll.setInstallDate(ss);
                              }
                              else
                              {
                            	  if(checkGroupLoanEmi==true)  // Condition for Manage Meeting Day Change
                            	  {
                            		  dt=groupLoanEmiDateFromTable(i,loanNo,conn);
                            	  }
	                              ll.setStrInstlmntDate(sf.format(dt));
	                              SimpleDateFormat dd=sf;
	                              Date ss=dd.parse(ll.getStrInstlmntDate());
	                              ll.setInstallDate(ss);
                              }
                           
                             /*ll.setPaidDate(loanPaidDate(i, loanNo, conn));
                                if(ll.getPaidAmount() > 0)
                                {
                                   
                                if(ll.getPaidDate()==null)
                                {
                                    ll.setPaidDateStr("- - - -");
                                }
                                else
                                {
                                    ll.setPaidDateStr(new SimpleDateFormat("dd/MM/yyyy").format(loanPaidDate(i, loanNo, conn)));
                                    ll.setReceiptNo(loanPayReceiptNoByLoanNo(i, loanNo, conn));
                                }
                                }
                                else
                                {
                                    ll.setPaidDateStr("- - - -");
                                }*/// comment by GARG on 07 jan 2020 
	                        ll.setPaidDateStr("- - - -");
                              
                               
                          //  ll.setStrInstlmntDate(new SimpleDateFormat("dd/MM/yyyy").format(dt));
                           
                            double frstIntrstAmnt=interestMonthly;
                            ll.setInterestAmount(df.format((frstIntrstAmnt)));
                            ll.setInterest(Double.parseDouble(df.format(frstIntrstAmnt)));
                            
                            double paidPrincipalAmnt=emi-(frstIntrstAmnt);
                            ll.setPrincipalAmount(df.format(paidPrincipalAmnt));
                            ll.setPrincipal(Double.parseDouble(df.format(paidPrincipalAmnt)));
                       
                            list.add(ll);
                        }
                    }
                 
                }
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
      
        /*int i=0;
        loopx:for(LoanInfo ll: list)
        {
            if(ll.getStatus().equalsIgnoreCase("Paid"))
            {
                i=i+1;
                // // // //System.out.println(i);
                //lastPaidDate=ll.getInstallDate();
                // // // //System.out.println(ll.getInstallDate());
                break loopx;
            }
          
        }*/
        return list;
    }

	
	public ArrayList<LoanInfo> loanInstallment(String loanType,String loanNo, Connection conn)
    {
        double temp=0;
        String qq="";
        int j=0, x = 0;
        
        DbYashwant dby = new DbYashwant();
        
        Statement st=null;
		ResultSet rs=null;
		boolean checkGroupLoanEmi=false;
        ArrayList<LoanInfo> list = new ArrayList<LoanInfo>();
        try
        {
            st = conn.createStatement();
            if(loanType.equals("grouploan"))
            {
                qq = "select * from "+loanType+" where sub_loan_no='"+loanNo+"' and status='Approve' " ;
               
            }
            else
            {
                 qq = "select * from "+loanType+" where loanNo='"+loanNo+"' and status='Approve'"  ;
            }  
            
            System.out.println("qiery is :"+qq);
            
           
            checkGroupLoanEmi=checkGroupLoanEmiFromTable(loanNo,conn);
            
            if (checkGroupLoanEmi) 
            {
            	x = firstGroupLoanEmiNoFromTable(loanNo, conn);
			}
            
            rs = st.executeQuery(qq);
            if(rs.next())
            {   
                if(rs.getString("emiType").equals("reducing"))
                {
                    double discount=discountOnLastEMI(loanType,loanNo,conn);
                    double paidAmount=loanPaidAmountByUser(loanType,loanNo,conn);
                    int terms = rs.getInt("terms");
                    int frequency=rs.getInt("frequency");
                    double emi=rs.getDouble("emi");
                    Date offcdt =null;
                    if(rs.getDate("emi_due_date")==null)
                    {
                        offcdt =rs.getDate("approvalDate");
                       
                    }
                    else
                    {
                    	
                        offcdt = rs.getDate("emi_due_date");
                        System.out.println("value of the emi Due Date :"+offcdt);
                        
                    }
                    double interstRate=rs.getDouble("interest");
                    double loanAmount=rs.getDouble("loanAmount");
                    double fr=(double) frequency;
                    Date installDate=null;
                    j=365/frequency;
                    if(rs.getDate("emi_due_date")==null)
                    {
                        installDate=rs.getDate("approvalDate");
                    }
                    else
                    {
                        installDate=rs.getDate("emi_due_date");
                        if(frequency==12)
                        {
                            installDate.setMonth(installDate.getMonth()-1);
                        }
                        else
                        {
                            installDate.setDate(installDate.getDate()-j);
                        }
                    }  
                    
                   
                    
                    int y=1;
                    for (int i = 1; i<= terms; i++)
                    {
                        LoanInfo ll=new LoanInfo();
                        //int j=365/frequency;

                        
                        ll.setSno(i);
                        if(i==terms)
                        {
                            emi=emi-discount;
                            ll.setInstallAmount(emi);
                        }
                        else
                        {
                            ll.setInstallAmount(emi);
                        }
                        
                        if(paidAmount>=emi)
                        {
                            ll.setStatus("Paid");
                            
                            
                            ll.setPaidAmount(emi);
                            ll.setDueAmount(0);
                            paidAmount=Double.parseDouble(df.format(paidAmount-emi));
                        }
                        else
                        {
                            ll.setStatus("Due");
                            ll.setPaidAmount(paidAmount);
                            ll.setDueAmount(Double.parseDouble(df.format(emi-paidAmount)));
                            	
                            paidAmount=0;
                        }
                  
                        Date dt=installDate;
                        if(rs.getDate("emi_due_date")==null)
                        {
                            dt.setDate(dt.getDate()+j);
                        }
                        else
                        {
                            if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
                              {
                                    if(frequency==4)
                                    {
                                        y=4;
                                        //x=terms/3;
                                    }
                                    else if(frequency==2)
                                    {
                                        y=6;
                                        //x=terms/6;
                                    }
                                    else if(frequency==1)
                                    {
                                        y=12;
                                        //x=terms/12;
                                    }
                                    else if(frequency==12)
                                    {
                                        y=1;
                                        //x=terms;
                                    }
                                  offcdt=createDate2(offcdt,y,i,offcdt.getDate(),rs.getDate("emi_due_date"));
                              }
                            else
                            {
                                dt.setDate(dt.getDate()+j);
                            }
                          
                        }
                        
                        if(checkGroupLoanEmi==false && (frequency==12 || frequency==4 || frequency==2 || frequency==1))
                        {
                            ll.setStrInstlmntDate(sf.format(offcdt));
                            SimpleDateFormat dd=sf;
                            Date ss=dd.parse(ll.getStrInstlmntDate());
                            ll.setInstallDate(ss);
                        }
                        else
                        {
                        	  if(checkGroupLoanEmi==true && x==i)  // Condition for Manage Meeting Day Change
                        	  {
                        		  dt=groupLoanEmiDateFromTable(i,loanNo,conn);
                        		  x++;
                        	  }
	                        ll.setStrInstlmntDate(sf.format(dt));
	                        SimpleDateFormat dd=sf;
	                        Date ss=dd.parse(ll.getStrInstlmntDate());
	                        ll.setInstallDate(ss);
                        }
                        
                       // ll.setPaidDate(loanPaidDate(i, loanNo, conn));
                        
                        Date paidDate = loanPaidDate(i, loanNo, conn);     //work by raviKumar
                        System.out.println("paid date is:"+paidDate);
                        
                        
                        ll.setPaidDate(paidDate);
                        ll.setEmiPaidDate(paidDate);
                        
                        
                        if (paidDate != null)
                        {
                            ll.setEmiPaidDateStr(new SimpleDateFormat("dd/MM/yyyy").format(paidDate));
                        }
                        
                        else
                        {
                            ll.setEmiPaidDateStr("- - - -");
                        }
                        
                       // ll.setEmiPaidDateStr( new SimpleDateFormat("dd/MM/yyyy").format(loanPaidDate(i, loanNo, conn)));
                        
                       /* if(ll.getPaidAmount() > 0)
                        {
                           
                        if(ll.getPaidDate()==null)
                        {
                            ll.setPaidDateStr("- - - -");
                        }
                        else
                        {
                            ll.setPaidDateStr(new SimpleDateFormat("dd/MM/yyyy").format(loanPaidDate(i, loanNo, conn)));
                            ll.setReceiptNo(loanPayReceiptNoByLoanNo(i, loanNo, conn));
                        }
                        }
                        else
                        {
                            ll.setPaidDateStr("- - - -");
                        }*/// comment by GARG on 07 jan 2020 
                        ll.setPaidDateStr("- - - -");
                      
                       
                        double frstIntrstAmnt=(loanAmount*interstRate)/(100*fr);
                        ll.setInterestAmount(df.format((frstIntrstAmnt)));
                        ll.setInterest(Double.parseDouble(df.format(frstIntrstAmnt)));
                      
                        double paidPrincipalAmnt=emi-(frstIntrstAmnt);
                        ll.setPrincipalAmount(df.format(paidPrincipalAmnt));
                        ll.setPrincipal(Double.parseDouble(df.format(paidPrincipalAmnt)));
                      
                        double principalRemaining=loanAmount-paidPrincipalAmnt;
                        ll.setPrincipalBalanceStr(df.format(principalRemaining));
                        
                        list.add(ll);
                        loanAmount=principalRemaining;
                    }
                }
                else
                {
                	 String emiMode="";
                    if(loanType.equalsIgnoreCase("grouploan"))
                    {
                    	emiMode="both";
                    }
                    else
                    {
                    	emiMode=rs.getString("emi_mode");
                    }
                    if(emiMode.equalsIgnoreCase("both"))
                    {
                          double discount=discountOnLastEMI(loanType,loanNo, conn);
                             Date offcdt =null;
                             if(rs.getDate("emi_due_date")==null)
                             {
                                 offcdt =rs.getDate("approvalDate");
                             }
                             else
                             {
                                 offcdt = rs.getDate("emi_due_date");
                             }
                            
                          double paidAmount=loanPaidAmountByUser(loanType,loanNo, conn);
                          int terms = rs.getInt("terms");
                          int frequency=rs.getInt("frequency");
                          double emi=rs.getDouble("emi");
                          double interstRate=rs.getDouble("interest");
                          double loanAmount=rs.getDouble("loanAmount");
                          double totalInterest=Double.parseDouble(df.format((emi*terms)-loanAmount));
                          //double interestMonthly=(totalInterest-rs.getDouble("discount"))/terms;
                          double interestMonthly=totalInterest/terms;
                          Date installDate=null;
                          j=365/frequency;
                        
                          if(rs.getDate("emi_due_date")==null)
                          {
                              installDate=rs.getDate("approvalDate");
                          }
                          else
                          {
                              installDate=rs.getDate("emi_due_date");
                              if(frequency==12)
                              {
                                  installDate.setMonth(installDate.getMonth()-1);
                              }
                              else
                              {
                                  installDate.setDate(installDate.getDate()-j);
                              }
                          }
                          int y=1;
                          for (int i = 1; i<= terms; i++)
                          {
                              	                        	  
                        	  LoanInfo ll=new LoanInfo();
                        	  ll.setEmiPaidDate1(dby.selectEmiPaidDate(i,loanNo,conn));
                        	  Date paidDate = loanPaidDate(i, loanNo, conn);
	  	                      ll.setPaidDate(paidDate);
	  	                      ll.setEmiPaidDate(paidDate);
                              ll.setSno(i);
                              if(i==terms)
                              {
                                  emi=emi-discount;
                                  ll.setInstallAmount(emi);
                              }
                              else
                              {
                                  ll.setInstallAmount(emi);
                              }
                            
                              if(paidAmount>=emi)
                              {
                                  ll.setStatus("Paid");
                                  ll.setPaidAmount(emi);
                                  ll.setDueAmount(0);
                                  paidAmount=Double.parseDouble(df.format(paidAmount-emi));
                              }
                              else
                              {
                                  ll.setStatus("Due");
                                  ll.setPaidAmount(paidAmount);
                                  ll.setDueAmount(Double.parseDouble(df.format(emi-paidAmount)));
                                  paidAmount=0;
                              }
                        
                              Date dt=installDate;
                              if(rs.getDate("emi_due_date")==null)
                              {
                                  dt.setDate(dt.getDate()+j);
                              }
                              else
                              {
                                  if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
                                  {
                                        if(frequency==4)
                                        {
                                            y=4;
                                            //x=terms/3;
                                        }
                                        else if(frequency==2)
                                        {
                                            y=6;
                                            //x=terms/6;
                                        }
                                        else if(frequency==1)
                                        {
                                            y=12;
                                            //x=terms/12;
                                        }
                                        else if(frequency==12)
                                        {
                                            y=1;
                                            //x=terms;
                                        }
                                      offcdt=createDate2(offcdt,y,i,offcdt.getDate(),rs.getDate("emi_due_date"));
                                  }
                                  else
                                  {
                                      dt.setDate(dt.getDate()+j);
                                  }
                              }
                              if(checkGroupLoanEmi==false && (frequency==12 || frequency==4 || frequency==2 || frequency==1))
                              {
                                  // System.out.println("hsjhhjhjhjhjhjhh "+offcdt);
                                  ll.setStrInstlmntDate(sf.format(offcdt));
                                  SimpleDateFormat dd=sf;
                                  Date ss=dd.parse(ll.getStrInstlmntDate());
                                  ll.setInstallDate(ss);
                              }
                              else
                              {
                            	  if(checkGroupLoanEmi==true)  // Condition for Manage Meeting Day Change
                            	  {
                            		  dt=groupLoanEmiDateFromTable(i,loanNo,conn);
                            	  }
	                              ll.setStrInstlmntDate(sf.format(dt));
	                              SimpleDateFormat dd=sf;
	                              Date ss=dd.parse(ll.getStrInstlmntDate());
	                              ll.setInstallDate(ss);
                              }
                             
                             /* ll.setPaidDate(loanPaidDate(i, loanNo, conn));
                              if(ll.getPaidAmount() > 0)
                              {
                                 
                              if(ll.getPaidDate()==null)
                              {
                                  ll.setPaidDateStr("- - - -");
                              }
                              else
                              {
                                  ll.setPaidDateStr(new SimpleDateFormat("dd/MM/yyyy").format(loanPaidDate(i, loanNo, conn)));
                                  ll.setReceiptNo(loanPayReceiptNoByLoanNo(i, loanNo,conn));
                              }
                              }
                              else
                              {
                                  ll.setPaidDateStr("- - - -");
                              }*/
                           // comment by GARG on 07 jan 2020 
  	                        ll.setPaidDateStr("- - - -");
                             
                              double frstIntrstAmnt=interestMonthly;
                              ll.setInterestAmount(df.format((frstIntrstAmnt)));
                              ll.setInterest(Double.parseDouble(df.format(frstIntrstAmnt)));
                            
                              double paidPrincipalAmnt=emi-(frstIntrstAmnt);
                              ll.setPrincipalAmount(df.format(paidPrincipalAmnt));
                              ll.setPrincipal(Double.parseDouble(df.format(paidPrincipalAmnt)));
	                            
                              //double principalRemaining=loanAmount-paidPrincipalAmnt;
                            
                              list.add(ll);
                              //loanAmount=principalRemaining;
                          }
                    }
                    else
                    {
                        double discount=rs.getDouble("discount");
                        Date offcdt =null;
                        if(rs.getDate("emi_due_date")==null)
                        {
                            offcdt =rs.getDate("approvalDate");
                        }
                        else
                        {
                            offcdt = rs.getDate("emi_due_date");
                        }
                        double paidAmount=loanPaidAmountByUser(loanType,loanNo, conn);
                        int terms = rs.getInt("terms");
                        int frequency=rs.getInt("frequency");
                        double emi=rs.getDouble("emi");
                        double interstRate=rs.getDouble("interest");
                        double loanAmount=rs.getDouble("loanAmount");
                        //double interestMonthly =Double.parseDouble(new DecimalFormat("##.#######").format(interstRate / (100.00 * frequency)));
                        double totalInterest=Double.parseDouble(df.format((emi*terms)));
                       System.out.println("Total interst :"+totalInterest);
                        double interestMonthly=totalInterest/terms;
                        System.out.println("Total interst :"+totalInterest);
                        Date installDate=null;
                        boolean chk=true;
                        j=365/frequency;
                        double fr=(double) frequency;

                        if(rs.getDate("emi_due_date")==null)
                        {
                            installDate=rs.getDate("approvalDate");
                        }
                        else
                          {
                              installDate=rs.getDate("emi_due_date");
                              if(frequency==12)
                              {
                                  installDate.setMonth(installDate.getMonth()-1);
                              }
                              else if(frequency==4)
                              {
                                  installDate.setMonth(installDate.getMonth()-3);
                              }
                              else
                              {
                                  installDate.setDate(installDate.getDate()-j);
                              }
                          }
                        
                        int y=1;
                        for (int i = 1; i<= terms; i++)
                        {
                            LoanInfo ll=new LoanInfo();
//                            ll.setEmiPaidDate1(dby.selectEmiPaidDate(i,loanNo));
                            //int jj=365/frequency;
                            ll.setSno(i);
                            if(i==terms)
                            {
                                emi=emi-discount;
                                ll.setInstallAmount(emi);
                            }
                            else
                            {
                                ll.setInstallAmount(emi);
                            }
                           
                            if(paidAmount>=emi)
                            {
                                ll.setStatus("Paid");
                                ll.setPaidAmount(emi);
                                ll.setDueAmount(0);
                                paidAmount=Double.parseDouble(df.format(paidAmount-emi));
                            }
                            else
                            {
                                ll.setStatus("Due");
                                ll.setPaidAmount(paidAmount);
                                ll.setDueAmount(Double.parseDouble(df.format(emi-paidAmount)));
                                paidAmount=0;
                            }
                            
                            //comment on 23-oct-2019 due to problem in MTOS nidhi
                            /*Date dt=installDate;
                            if(rs.getDate("emi_due_date")==null)
                            {
                                dt.setDate(dt.getDate()+jj);
                            }
                            else
                            {
                                if(chk==true)
                                {
                                    dt.setMonth(dt.getMonth());
                                    chk=false;
                                }
                                else
                                {
                                    dt.setMonth(dt.getMonth()+1);
                                }
                            }
                            ll.setInstallDate(dt);
                            */
                            

                            Date dt=installDate;
                              if(rs.getDate("emi_due_date")==null)
                              {
                                  dt.setDate(dt.getDate()+j);
                              }
                              else
                              {
                                  if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
                                  {
                                        if(frequency==4)
                                        {
                                            y=4;
                                            //x=terms/3;
                                        }
                                        else if(frequency==2)
                                        {
                                            y=6;
                                            //x=terms/6;
                                        }
                                        else if(frequency==1)
                                        {
                                            y=12;
                                            //x=terms/12;
                                        }
                                        else if(frequency==12)
                                        {
                                            y=1;
                                            //x=terms;s
                                        }
                                        offcdt=createDate2(offcdt,y,i,offcdt.getDate(),rs.getDate("emi_due_date"));
                                  }
                                  else
                                  {
                                      dt.setDate(dt.getDate()+j);
                                  }
                              }
                              if(checkGroupLoanEmi==false && (frequency==12 || frequency==4 || frequency==2 || frequency==1))
                              {
                                  // System.out.println("hsjhhjhjhjhjhjhh "+offcdt);
                                  ll.setStrInstlmntDate(sf.format(offcdt));
                                  SimpleDateFormat dd=sf;
                                  Date ss=dd.parse(ll.getStrInstlmntDate());
                                  ll.setInstallDate(ss);
                              }
                              else
                              {
                            	  if(checkGroupLoanEmi==true)  // Condition for Manage Meeting Day Change
                            	  {
                            		  dt=groupLoanEmiDateFromTable(i,loanNo,conn);
                            	  }
	                              ll.setStrInstlmntDate(sf.format(dt));
	                              SimpleDateFormat dd=sf;
	                              Date ss=dd.parse(ll.getStrInstlmntDate());
	                              ll.setInstallDate(ss);
                              }
                           
                             /*ll.setPaidDate(loanPaidDate(i, loanNo, conn));
                                if(ll.getPaidAmount() > 0)
                                {
                                   
                                if(ll.getPaidDate()==null)
                                {
                                    ll.setPaidDateStr("- - - -");
                                }
                                else
                                {
                                    ll.setPaidDateStr(new SimpleDateFormat("dd/MM/yyyy").format(loanPaidDate(i, loanNo, conn)));
                                    ll.setReceiptNo(loanPayReceiptNoByLoanNo(i, loanNo, conn));
                                }
                                }
                                else
                                {
                                    ll.setPaidDateStr("- - - -");
                                }*/// comment by GARG on 07 jan 2020 
	                        ll.setPaidDateStr("- - - -");
                              
                               
                          //  ll.setStrInstlmntDate(new SimpleDateFormat("dd/MM/yyyy").format(dt));
                           
                            double frstIntrstAmnt=interestMonthly;
                            ll.setInterestAmount(df.format((frstIntrstAmnt)));
                            ll.setInterest(Double.parseDouble(df.format(frstIntrstAmnt)));
                            
                            double paidPrincipalAmnt=emi-(frstIntrstAmnt);
                            ll.setPrincipalAmount(df.format(paidPrincipalAmnt));
                            ll.setPrincipal(Double.parseDouble(df.format(paidPrincipalAmnt)));
                       
                            list.add(ll);
                        }
                    }
                 
                }
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
      
        /*int i=0;
        loopx:for(LoanInfo ll: list)
        {
            if(ll.getStatus().equalsIgnoreCase("Paid"))
            {
                i=i+1;
                // // // //System.out.println(i);
                //lastPaidDate=ll.getInstallDate();
                // // // //System.out.println(ll.getInstallDate());
                break loopx;
            }
          
        }*/
        return list;
    }



	public boolean checkGroupLoanEmiFromTable(String loanNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from grouploan_emi where sub_loan_no='"+loanNo+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return false;
	}
	
	
	
	public int firstGroupLoanEmiNoFromTable(String loanNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from grouploan_emi where sub_loan_no='"+loanNo+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getInt("emi_no");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 1;
	}
	
	

	public Date groupLoanEmiDateFromTable(int i, String loanNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select emi_date from grouploan_emi where sub_loan_no='"+loanNo+"' and emi_no='"+i+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDate("emi_date");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return null;
	}

	public ArrayList<Date> loanEmiDateList(int frequency, int terms, Date emi_due_date, Date approvalDate)
	  {
		  boolean chk=true;
		  ArrayList<Date> dateList=new ArrayList<>();
		  Date dt =null;
          if(emi_due_date==null)
          {
              dt =approvalDate;
          }
          else
          {
        	  dt =emi_due_date;
          }
		  int y = 0;  
		  int j=365/frequency;
		  for(int i=1; i<=terms; i++)
		  {
	           if(emi_due_date==null)
	           {
	               dt.setDate(dt.getDate()+j);
	           }
	           else
	           {
	               if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
	                 {
	                       if(frequency==4)
	                       {
	                           y=4;
	                           //x=terms/3;
	                       }
	                       else if(frequency==2)
	                       {
	                           y=6;
	                           //x=terms/6;
	                       }
	                       else if(frequency==1)
	                       {
	                           y=12;
	                           //x=terms/12;
	                       }
	                       else if(frequency==12)
	                       {
	                           y=1;
	                           //x=terms;
	                       }
	                     dt=createDate2(dt,y,i,dt.getDate(),emi_due_date);
	                 }
	               else
	               {
	            	   if(chk==true)
                       {
	            		   dt.setDate(dt.getDate());
                           chk=false;
                       }
                       else
                       {
                    	   dt.setDate(dt.getDate()+j);
                       }
	               }
	           }
	           dateList.add(dt);
		  }
		  return dateList;
	  }

	  public ArrayList<String> loanEmiStrDateList(int frequency, int terms, Date emi_due_date, Date approvalDate, String subLoanNo, Connection conn)
	  {
		  ArrayList<String> dateList=new ArrayList<>();
		  boolean checkGroupLoanEmi=checkGroupLoanEmiFromTable(subLoanNo,conn);
		  if(checkGroupLoanEmi==false)
		  {
			  boolean chk=true;
			  Date dt =null;
	          if(emi_due_date==null)
	          {
	              dt =approvalDate;
	          }
	          else
	          {
	        	  dt =emi_due_date;
	          }
			  int y = 0;  
			  int j=365/frequency;
			  for(int i=1; i<=terms; i++)
			  {
		           if(emi_due_date==null)
		           {
		               dt.setDate(dt.getDate()+j);
		           }
		           else
		           {
		               if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
		                 {
		                       if(frequency==4)
		                       {
		                           y=4;
		                           //x=terms/3;
		                       }
		                       else if(frequency==2)
		                       {
		                           y=6;
		                           //x=terms/6;
		                       }
		                       else if(frequency==1)
		                       {
		                           y=12;
		                           //x=terms/12;
		                       }
		                       else if(frequency==12)
		                       {
		                           y=1;
		                           //x=terms;
		                       }
		                     dt=createDate2(dt,y,i,dt.getDate(),emi_due_date);
		                 }
		               else
		               {
		            	   if(chk==true)
	                       {
		            		   dt.setDate(dt.getDate());
	                           chk=false;
	                       }
	                       else
	                       {
	                    	   dt.setDate(dt.getDate()+j);
	                       }
		               }
		           }
		           dateList.add(sf.format(dt));
			  }
		  }
		  else
		  {
			  	Statement st=null;
				ResultSet rr=null;
				try
				{
					st=conn.createStatement();
					String qq="select emi_date from grouploan_emi where sub_loan_no='"+subLoanNo+"' ";
					rr=st.executeQuery(qq);
					while(rr.next())
					{
						dateList.add(sf.format(rr.getDate("emi_date")));
					}
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					try {
						if(st!=null)
						{
							st.close();
						}
						if(rr!=null)
						{
							rr.close();
						}
					} catch (Exception e2) {
						// TODO: handle exception
					}
				}
		  }
		 
		  return dateList;
	  }
	
	  public Date loanPaidDate(int i,String loanNo, Connection conn)
	    {
		  Statement st=null;
			ResultSet rr=null;
	        try
	        {
	            st=conn.createStatement();
	            String query="select pay_date from loanpayment where emi_no='"+i+"' and loanNo='"+loanNo+"' and restructure='No' and receipt_status='approved' and chequeStatus='cleared' ";
	            rr=st.executeQuery(query);
	            if(rr.next())
	            {
	                return rr.getDate("pay_date");
	            }
	        }
	        catch(Exception e)
	        {
	             e.printStackTrace();fileCreation(e.getMessage());
	        }
	        finally
			{
				try {
					if(st!=null)
					{
						st.close();
					}
					if(rr!=null)
					{
						rr.close();
					}
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
	        return null;
	    }
	public ArrayList<LoanInfo> findInstallmentNoForLoan(String loanType,String loanNo, int id, double installment_amount) 
	{
		int prevPaidAmount=0;
		String qr="";
		ArrayList<LoanInfo> list = new ArrayList<LoanInfo>();
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq="select sum(amount) from loanpayment where loanType='"+loanType+"' and loanNo='"+loanNo+"' and id<'"+id+"' and receipt_status='approved'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				prevPaidAmount=rs.getInt("sum(amount)");
			}
			
			if(loanType.equalsIgnoreCase("grouploan"))
			{
				qr = "select * from "+loanType+" where sub_loan_no='"+loanNo+"' and status='approve'";
			}
			else
			{
				qr = "select * from "+loanType+" where loanNo='"+loanNo+"' and status='approve'";
			}
			
			ResultSet rr = st.executeQuery(qr);
			if(rr.next()) 
			{
				double paidAmount=prevPaidAmount;
				double paidAmountAfterTransaction=paidAmount+installment_amount;
				int terms = rr.getInt("terms");
				double emi=rr.getDouble("emi");
				for (int i = 1; i<= terms; i++) 
				{
					LoanInfo ll=new LoanInfo();
					
					if(paidAmount>=emi)
					{
						ll.setStatus("Paid");
						if(ll.getStatus()=="Paid")
						{
							ll.setTemp1(i);
						}
						paidAmount=Double.parseDouble(df.format(paidAmount-emi));
					}
					else
					{
						ll.setStatus("Due");
						paidAmount=0;
					}
					list.add(ll);
				}
				
				for (int i = 1; i<= terms; i++) 
				{
					LoanInfo ll=new LoanInfo();
					
					if(paidAmountAfterTransaction>0)
					{
						ll.setStatus("Paid");
						if(ll.getStatus()=="Paid")
						{
							ll.setTemp2(i);
						}
						paidAmountAfterTransaction=Double.parseDouble(df.format(paidAmountAfterTransaction-emi));
					}
					list.add(ll);
				}
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	
	public int loanPayReceiptNo() 
	{
		int i=1;
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq = "select receipt_no from loanpayment  order by id desc";
			ResultSet rs = st.executeQuery(qq);
			if (rs.next()) 
			{
				i= rs.getInt("receipt_no")+1;
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}
	
	public double loanPaidAmountByUser(String loanType,String loanNo,Connection conn)
	{
		double paidAmount=0;
		Statement st=null;
		ResultSet rr=null;
		if(loanType.equalsIgnoreCase("vehicleLoan"))
		{
			loanType="vechicleLoan";
		}
		try
		{
			st=conn.createStatement();
			String query="select sum(amount) from loanpayment where loanNo='"+loanNo+"' and restructure='No' and receipt_status='approved' and chequeStatus='cleared' ";
			//System.out.println(query);
			rr=st.executeQuery(query);
			if(rr.next())
			{
				paidAmount=rr.getDouble(1);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return paidAmount;
	}
    
	public double discountOnLastEMI(String loanType,String loanNo,Connection conn)
	{
		Statement st=null;
		ResultSet rr=null;
		double amount=0;
		String query="";
		if(loanType.equalsIgnoreCase("vehicleLoan"))
		{
			loanType="vechicleLoan";
		}
		try
		{
			st=conn.createStatement();
			
			if(loanType.equals("grouploan"))
			{
				query="select * from "+loanType+" where sub_loan_no='"+loanNo+"' and status='Approve'";
			}
			
			else
			{
				query="select * from "+loanType+" where loanNo='"+loanNo+"' and status='Approve'";
			}
			rr=st.executeQuery(query);
			if(rr.next())
			{
				amount=rr.getDouble("discount");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return amount;
	}
	
	public int payLoanEMI(int branchId,String loanNo,String loanType,double amount,Date currentDate,String paymentMode,String chequeNo,Date chequeDate,
	String bankName, double penalty, String receipt_no, String submittedBankName, String restructureStatus, double discount, int emiNo, String dsaCode, String attendance, String remark)
	{
		int j = 0;
		HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		String userId=(String) ss1.getAttribute("username");
		
		Timestamp crdt = new Timestamp(currentDate.getTime());
		Timestamp chdate = null;
		if (chequeDate != null) 
		{
			chdate = new Timestamp(chequeDate.getTime());
		}
		String status="pending",chequeStatus="";
		if(paymentMode.equalsIgnoreCase("Cash"))
		{
			paymentMode="cash";
			status="approved";
			chequeStatus="cleared";
		}
		else if(paymentMode.equalsIgnoreCase("Transfer") || paymentMode.equalsIgnoreCase("online"))
		{
			status="approved";
			chequeStatus="cleared";
		}
		else if(paymentMode.equalsIgnoreCase("NACH"))
		{
			chequeStatus="uncleared";
		}
		else {
			status="approved";
			chequeStatus="cleared";
		}

		try (Connection conn = DataBaseConnection.JAVAConnection();)
		{
			String query = "insert into loanpayment(loanType, loanNo, pay_date, amount, pay_mode, chq_no, chq_date, bank_name, penalty,"
			+" receipt_no,receipt_status,transfer_to_bank,chequeStatus,restructure, discount, emi_no,user_id, dsa_code, attendance,remark,branch_id) "
			+ "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			PreparedStatement st1 = conn.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
			st1.setString(1, loanType);
			st1.setString(2, loanNo);
			st1.setTimestamp(3, crdt);
			st1.setDouble(4, amount);
			st1.setString(5, paymentMode);
			st1.setString(6, chequeNo);
			st1.setTimestamp(7, chdate);
			st1.setString(8, bankName);
			st1.setDouble(9, penalty);
			st1.setString(10, receipt_no);
			st1.setString(11, status);
			st1.setString(12, submittedBankName);
			st1.setString(13, chequeStatus);
			st1.setString(14, restructureStatus);
			st1.setDouble(15, discount);
			st1.setInt(16, emiNo);
			st1.setString(17, userId);
			st1.setString(18, dsaCode);
			st1.setString(19, attendance);
			st1.setString(20, remark);
			st1.setInt(21, branchId);
			
			
			st1.executeUpdate();
			ResultSet generatedKeys = st1.getGeneratedKeys();
			if (generatedKeys.next()) 
			{
				////System.out.println(String.valueOf(st1));
				dataInsertInQueryTable(String.valueOf(st1), conn);
	           return generatedKeys.getInt(1);
	        }
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return j;
	}

	public boolean rd_FdPayStatus(String user_no)
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from payment_receipt where user_no='"+user_no+"' and receipt_status='pending'";
			ResultSet rr=st.executeQuery(query);
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return false;
	}

	public boolean loanPayemntStatus(String loanType, String loanNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from loanpayment where loanType='"+loanType+"' and loanNo='"+loanNo+"' and receipt_status='pending'";
			ResultSet rr=st.executeQuery(query);
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return false;
	}

	public boolean withdrawalPayStatus(String accno)
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from customer_withdrwal where account_no='"+accno+"' and status='pending'";
			ResultSet rr=st.executeQuery(query);
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return false;
	}

	public boolean depositPayStatus(String accno) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from customer_deposit where account_no='"+accno+"' and status='pending'";
			ResultSet rr=st.executeQuery(query);
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return false;
	}
	public ArrayList<LoanEmiReceiptInfo> loanReceiptInfoByLoanNoLoanType(int branchId,String loanNo, String loanType)
	{
		int i=1;
		ArrayList<LoanEmiReceiptInfo> list=new ArrayList<>();
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();

			String query="select * from loanpayment where loanType='"+loanType+"' and loanNo='"+loanNo+"' and receipt_status in ('approved')  and chequeStatus in ('cleared') ";
	
			query = selectQueWithBranch(query, branchId);
			
			query += " ORDER BY pay_date ASC";
						 
			ResultSet rr=st.executeQuery(query);

			while(rr.next())
			{   
				LoanEmiReceiptInfo ll=new LoanEmiReceiptInfo();
				
				ll.setSno(i);
				ll.setId(rr.getString("id"));
				ll.setLoanType(rr.getString("loanType"));
				ll.setLoanNo(rr.getString("loanNo"));
				ll.setAmount(rr.getDouble("amount"));
				ll.setPay_date(rr.getDate("pay_date"));
				ll.setInterestAmount(rr.getDouble("interestAmount"));
				ll.setStrPayDate(sf.format(rr.getDate("pay_date")));
				ll.setPay_mode(rr.getString("pay_mode"));
				ll.setStatus(rr.getString("receipt_status"));
				
				if(ll.getStatus().equalsIgnoreCase("pending"))
				{
					ll.setDisableEdit(false);
				}
				else
				{
					ll.setDisableEdit(true);
				}
				
				if (!rr.getString("pay_mode").equalsIgnoreCase("cash") && !rr.getString("pay_mode").equalsIgnoreCase("transfer"))
				{
					ll.setChq_no(rr.getString("chq_no"));
					ll.setChq_date(rr.getDate("chq_date"));
					ll.setBank_name(rr.getString("bank_name"));
					if (rr.getDate("chq_date") != null)	
					{
						ll.setStrChqDate(sf.format(rr.getDate("chq_date")));
					}
				}
				else
				{
				    	ll.setChq_no("");
				}
				
				ll.setPenalty(rr.getDouble("penalty"));
				ll.setReceipt_no(rr.getString("receipt_no"));
				ll.setTransferBank(rr.getString("transfer_to_bank"));
				ll.setTransferToBankName(bankNameById(rr.getString("transfer_to_bank")));
				ll.setEmiNo(rr.getInt("emi_no"));
				ll.setEmiNoStr(rr.getString("emi_no"));
				
				list.add(ll);
				i++;	
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}

	public int removeLoanEmiPayReceipt(String id) 
	{
		int i = 0;
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq = "update loanpayment set receipt_status='inactive' where id='"+ id + "'";
			int x = st.executeUpdate(qq);
			if (x >= 1) 
			{
				dataInsertInQueryTable(qq, con);
				i++;
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}

	public double checkForLoanPaymentReceipt(String loanNo, String loanType) 
	{
		double payableAmount = 0;
		try (Connection conn = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = conn.createStatement();
			String qq = "select * from "+loanType+" where loanNo='" + loanNo+"' and status='Approve'";
			ResultSet rs = st.executeQuery(qq);
			if (rs.next()) 
			{
				double emi = rs.getDouble("emi");
				int trms = rs.getInt("terms");
				payableAmount = emi * trms;
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return payableAmount;
	}

	public int updateLoanEmiReceipt(String id, double amount, Date currentDate,
			String chequeNo, Date chequeDate, String bankName, double penalty)
	{
		int j = 0;
		Timestamp dt = new Timestamp(currentDate.getTime());
		Timestamp cdt = null;
		if (chequeDate != null)
		{
			cdt = new Timestamp(chequeDate.getTime());
		}
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			String query = "update loanpayment set pay_date=?,amount='"+ amount+"', chq_no='"+chequeNo+"',chq_date=?,"
					+ "bank_name='" + bankName+ "', penalty='" + penalty + "' where id='" + id + "'";
			PreparedStatement st1 = con.prepareStatement(query);
			st1.setTimestamp(1, dt);
			st1.setTimestamp(2, cdt);
			int i = st1.executeUpdate();
			if (i >= 1)
			{
				dataInsertInQueryTable(String.valueOf(st1), con);
				j++;
		} }
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return j;
	}
	
	public String firstApplicantNameBySHNo(String string, Connection conn)
	{
		String name="";
		try
		{
			Statement st = conn.createStatement();
			String qq = "select first_applicantName from shareholder_info where shareholderno='"+string+"'";
			////System.out.println(qq);
			ResultSet rr = st.executeQuery(qq);
			if(rr.next())
			{
				name = rr.getString("first_applicantName");
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return name;
	}

	public ArrayList<UserInfo> allSavingAccountBean(int branchId) 
	{
		int i=1;
		ArrayList<UserInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from savingaccount INNER JOIN shareholder_info on savingaccount.shareHolderNo=shareholder_info.shareholderno where shareholder_info.branch_id='"+branchId+"'";
			ResultSet rr=st.executeQuery(query);
			while(rr.next())
			{
				UserInfo ll=new UserInfo();
				ll.setSno(i++);
				ll.setId(rr.getString("savingaccount.id"));
				ll.setShareHolderNo(rr.getString("savingaccount.shareHolderNo"));
				ll.setFirst_applicantName(rr.getString("shareholder_info.first_applicantName"));
				ll.setFather_husband_name(rr.getString("shareholder_info.father_husband_name"));
				ll.setAddress(rr.getString("shareholder_info.address"));
				ll.setAccountNo(rr.getString("accountNo"));
				ll.setAmount(Double.parseDouble(df.format(rr.getDouble("amount"))));
				ll.setEntryDate(rr.getDate("openDate"));
				ll.setEntryDateStr(sf.format(ll.getEntryDate()));
				ll.setInterest(rr.getDouble("interest"));
				ll.setAccCloseCharge(rr.getDouble("accCloseCharge"));
				ll.setMinBal(rr.getDouble("minBal"));
				ll.setMinDaysForClose(rr.getInt("minDayForClose"));
				ll.setPayoutDate(rr.getDate("updateDate"));
				ll.setAccount_status(rr.getString("accountStatus"));
				ll.setDsaCode(rr.getString("savingaccount.dsacode"));
				if(ll.getPayoutDate()!=null)
				{
					ll.setStrPayOutDate(sf.format(ll.getPayoutDate()));
				}
				else
				{
					ll.setStrPayOutDate("");
				}
				
				if(ll.getAccount_status().equals("open"))
				{
					ll.setDisableDelete(false);
					ll.setDisableClose(false);
				}
				else if(ll.getAccount_status().equals("inactive") || ll.getAccount_status().equals("close"))
				{
					ll.setDisableDelete(true);
					ll.setDisableClose(true);
				}
				
				
				
				ll.setPaidAmount(rr.getDouble("paidAmount"));
				list.add(ll);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	public String nextDueDate(int id,String user_no) 
	{
		String date="";
		double paidAmount=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement stt = conn.createStatement();
			String qs = "select sum(amount) as amt from payment_receipt where user_no='"+ user_no + "' and id<='"+id+"' and receipt_status='approved'";
			ResultSet rr = stt.executeQuery(qs);
			if (rr.next()) 
			{
				paidAmount = rr.getDouble("amt");
			}
			Statement st = conn.createStatement();
			String qq = "select * from customer_info where user_no='" + user_no+ "' and account_status='active'";
			ResultSet rs = st.executeQuery(qq);
			if (rs.next()) 
			{
				Date offcdt = rs.getDate("office_date");
				int terms = rs.getInt("terms");
				int frequency=rs.getInt("frequency");
				double instlmnt_amnt = rs.getDouble("installment_amount");
				double intrst = rs.getDouble("interest");
				double mnthly_intrst = intrst / frequency;
				double instlmnt = instlmnt_amnt;
				
				/*int x=0,y=1;
				if(frequency==4)
			    {
					y=4;
			    	x=terms/3;
			    }
			    else if(frequency==2)
			    {
			    	y=6;
			    	x=terms/6;
			    }
			    else if(frequency==1)
			    {
			    	y=12;
			    	x=terms/12;
			    }
			    else if(frequency==12)
			    {
			    	y=1;
			    	x=terms;
			    }*/
				
				int x=0,y=1,z=0;
				if(frequency==4)
			    {
					y=4;
			    	//x=terms/3;
			    }
			    else if(frequency==2)
			    {
			    	y=6;
			    	//x=terms/6;
			    }
			    else if(frequency==1)
			    {
			    	y=12;
			    	//x=terms/12;
			    }
			    else if(frequency==12)
			    {
			    	y=1;
			    	//x=terms;
			    }
			    else if(frequency==365)
		        {
			    	z=1;
		        	//z=terms;
		        }
		        else if(frequency==36)
		        {
		        	z=10;
		        	//z=terms*10;
		        }
		        else if(frequency==24)
		        {
		        	z=15;
		        	//z=terms*15;
		        }
		        else if(frequency==52)
		        {
		        	z=7;
		        }
		        else if(frequency==26)
		        {
		        	z=14;
		        }
		        else if(frequency==13)
		        {
		        	z=28;
		        }
				
				if (rs.getString("scheme_type").equals("RD")) 
				{
					int d=offcdt.getDate();
					for (int i = 1; i <= terms; i++) 
					{
						InstallmentInfo ii = new InstallmentInfo();
						ii.setIns_date(sf.format(offcdt));
						ii.setInstlmntDate(offcdt);
						if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
				        {
							offcdt=createDate2(offcdt,y,terms,d,rs.getDate("customer_info.office_date"));
				        }
						else
						{
							offcdt=createDate3(offcdt,z);
						}
						if(paidAmount>=instlmnt)
						{}
						else if(paidAmount < instlmnt && paidAmount > 0) 
						{
							ii.setPaidAmount(paidAmount);
							ii.setStatus("Due");
							date=ii.getIns_date();
							return date;
						}
						else 
						{
							ii.setStatus("Due");
							date=ii.getIns_date();
							return date;
						}
						paidAmount = paidAmount - instlmnt;
						ii.setCalc_interest(Math.round(instlmnt_amnt* (mnthly_intrst / 100)));
						instlmnt_amnt = instlmnt_amnt+ (Math.round(instlmnt_amnt* (mnthly_intrst / 100)));
						if (i != terms) 
						{
							instlmnt_amnt = instlmnt_amnt + instlmnt;
						}
					}
				} 
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return date;
	}
	
	public String loanNextDueDate(int branchId,int id,String loanNo,String loanType) 
	{
		String date="",qq="";
		double paidAmount=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement stt = conn.createStatement();
			String query="select sum(amount) as amt from loanpayment where loanType='"+loanType+"' and loanNo='"+loanNo+"' and id<='"+id+"' and receipt_status='approved'";
			ResultSet rr = stt.executeQuery(selectQueWithBranch(query,branchId));
			if (rr.next()) 
			{
				paidAmount = rr.getDouble("amt");
			}
			Statement st = conn.createStatement();
			if(loanType.equalsIgnoreCase("grouploan"))
			{
				qq = "select * from "+loanType+" where sub_loan_no='"+loanNo+"' and status='approve'";
			}
			else
			{
				qq = "select * from "+loanType+" where loanNo='"+loanNo+"' and status='approve'";
			}
			
			ResultSet rs = st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rs.next()) 
			{
				int terms = rs.getInt("terms");
				int frequency=rs.getInt("frequency");
				double emi=rs.getDouble("emi");
				Date installDate=rs.getDate("approvalDate");
				for (int i = 1; i<= terms; i++) 
				{
					LoanInfo ll=new LoanInfo();
					int j=365/frequency;
					if(paidAmount>=emi)
					{
						ll.setStatus("Paid");
						paidAmount=Double.parseDouble(df.format(paidAmount-emi));
					}
					else
					{
						ll.setStatus("Due");
						paidAmount=0;
					}
					Date dt=installDate;
					dt.setDate(dt.getDate()+j);
					ll.setStrInstlmntDate(sf.format(dt));
					if(ll.getStatus().equalsIgnoreCase("Due"))
					{
						date=ll.getStrInstlmntDate();
						return date;
					}
				}
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return date;
	}
	
	
	public String firstReceiptNoOfRdFd(String rd_fd)
	{
		String receiptNo="0<`>0";
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement stt = conn.createStatement();
			String qs = "select * from payment_receipt where user_no='"+ rd_fd + "' and receipt_status='approved'";
		//	// // // //System.out.println(qs);
			ResultSet rr = stt.executeQuery(qs);
			if(rr.next()) 
			{
				receiptNo =rr.getString("receipt_no");
				receiptNo+="<`>"+rr.getString("id");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return receiptNo;
	}

	public void updateStatusOfLoan(String loanType, String loanNo) 
	{
		String query="";
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			if(loanType.equalsIgnoreCase("grouploan"))
			{
				query = "update "+loanType+" set paidStatus='paid' where sub_loan_no='"+loanNo+"' and status='approve'";
			}
			else
			{
				query = "update "+loanType+" set paidStatus='paid' where loanNo='"+loanNo+"' and status='approve'";
			}

			int i=st.executeUpdate(query);
			if(i>0)
			{
				dataInsertInQueryTable(query, con);
			} 
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}

	// Check Loan/Deposit Account is active or not of selected Member/Share Holder. This Method is use when Member Close..
	public String checkShareHolderAllAccount(UserInfo selecteduser) 
	{
		try(Connection conn= DataBaseConnection.JAVAConnection()) 
		{
			Statement st=conn.createStatement();
			String query="select user_no from customer_info where shareHolderNo='"+selecteduser.getShareHolderNo()+"' and paid_status='unpaid'";
			ResultSet rr=st.executeQuery(query);
			if(rr.next())
			{
				return rr.getString("scheme_type")+" No. " +rr.getString("user_no");
			}
			
			query="select loanNo from personalloan where shareholderno='"+selecteduser.getShareHolderNo()+"' and paidStatus='unpaid'";
			rr=st.executeQuery(query);
			if(rr.next())
			{
				return "Personal Loan No. " +rr.getString("loanNo");
			}
			
			/*query="select * from propertyloan where shareholderno='"+selecteduser.getShareHolderNo()+"' and paidStatus='unpaid'";
			rr=st.executeQuery(selectQueWithBranch(query,branchId));
			if(rr.next())
			{
				i++;
			}
			
			query="select * from vechicleloan where shareholderno='"+selecteduser.getShareHolderNo()+"' and paidStatus='unpaid'";
			rr=st.executeQuery(selectQueWithBranch(query,branchId));
			if(rr.next())
			{
				i++;
			}*/
			
			query="select sub_loan_no from grouploan where teamLeader='"+selecteduser.getShareHolderNo()+"' and paidStatus='unpaid'";
			rr=st.executeQuery(query);
			if(rr.next())
			{
				return "Group Loan No. " +rr.getString("sub_loan_no");
			}
			
			query="select accountNo from savingaccount where shareHolderNo='"+selecteduser.getShareHolderNo()+"' and accountStatus='open'";
			rr=st.executeQuery(query);
			if(rr.next())
			{
				return "Saving Account No. " +rr.getString("accountNo");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}

	public int closeAccountOfShareHolder(UserInfo selecteduser)
	{
		int i=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="update shareholder_info set account_status='inactive' where shareholderno='"+selecteduser.getShareHolderNo()+"'";
			i=st.executeUpdate(query);
			dataInsertInQueryTable(query, conn);
			
			if(selecteduser.getTransferFrom()==null || selecteduser.getTransferFrom().equals(""))
			{
				addRemovedSharesToCompanyShares(selecteduser.getNoOfShare());
			}
			/*else
			{
				int transferId=obtainIdOfShareHolder(selecteduser.getTransferFrom());
				double share=obtainExistingNoOfShares(selecteduser.getTransferFrom());
				double updateShare=share+selecteduser.getNoOfShare();
				double shareAmount=extractCompanyShareAmount(conn);
				double totalAmount=shareAmount*updateShare;
				String qq="update shareholder_info set noofShare='"+updateShare+"',totalAmount='"+totalAmount+"' where shareholderno='"+selecteduser.getTransferFrom()+"'";
				i=st.executeUpdate(qq);
				if(i>=1)
				{
					dataInsertInQueryTable(qq, conn);
					increaseCertificationNoOfTransferShareHolder(transferId,selecteduser.getNoOfShare());
				}
			}*/
			
			// Close Due to Share Certification No. 
			// Share Return is manage on other option --->> Return Share 
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}
	
	public void addRemovedSharesToCompanyShares(Double noOfShares)
	{
		double allotedShares=totalAllotedSharesOfCompany();
		allotedShares=allotedShares-noOfShares;
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="Update company_shares set shares_alloted='"+allotedShares+"'";
			st.executeUpdate(qq);
			dataInsertInQueryTable(qq, con);
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}
	
	public double totalAllotedSharesOfCompany() 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select * from company_shares";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getDouble("shares_alloted");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return 0.0;
	}

	public double totalSharedAmountOfCompany(int branchId)
	{
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select * from company_shares";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq, branchId));
			if(rs.next())
			{
				return rs.getDouble("amount_shared");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return 0.0;
	}
	
	public double totalCompanyCapitalAmount(int branchId)
	{
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select * from company_shares";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq, branchId));
			if(rs.next())
			{
				return rs.getDouble("company_capital_amount");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return 0.0;
	}
	
	public double remainingCompanyCapitalAmount(int branchId,Connection conn)
	{
		Statement st=null;
		ResultSet rs=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from company_shares";
			rs=st.executeQuery(selectQueWithBranch(qq, branchId));
			if(rs.next())
			{
				double remainingAmount=rs.getDouble("company_capital_amount")-rs.getDouble("amount_shared");
				return remainingAmount;
			}
		}
		
		catch (Exception e)
		{    
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}

	public double extractCompanyShareAmount(Connection conn)
	{
		   Statement stt=null;
		   ResultSet rs=null;
		try
		{
          stt=conn.createStatement();
		     String query="select * from company_shares";	
		    rs=stt.executeQuery(query);
		     if(rs.next())
		     {
		    	 return rs.getDouble("share_amount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	
	public double checkRemainingCompanyShares()
	{
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
             Statement stt=conn.createStatement();
		     String query="select * from company_shares";	
		     ResultSet rs=stt.executeQuery(query);
		     if(rs.next())
		     {
		    	 double remainingShares=rs.getDouble("no_of_shares")-rs.getDouble("shares_alloted");
		    	 return remainingShares;
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0.0;
	}
	
	public int insertCompanyShare(int branchId,double noOfShare, double shareAmount) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
             Statement stt=conn.createStatement();
             String qq="select * from company_shares";
             ResultSet rs=stt.executeQuery(qq);
             if(rs.next())
             {
            	 double oldCapitalAmount=rs.getDouble("company_capital_amount");
            	 double share=rs.getDouble("no_of_shares");
           	 	 double incresedCapitalAmount=noOfShare*shareAmount;
           	 	 double updateShares=share+noOfShare;
           	 	 double newCapitalAmount=oldCapitalAmount+incresedCapitalAmount;
            	 Statement stmt=conn.createStatement();
            	 String qr="update company_shares set no_of_shares='"+updateShares+"',share_amount='"+shareAmount+"',company_capital_amount='"+newCapitalAmount+"'";
            	 int j=stmt.executeUpdate(qr);
            	 if(j>=1)
            	 {
            		 dataInsertInQueryTable(qr, conn);
            		 return 1;
            	 }
             }
             else
             {
            	 double capitalAmount=noOfShare*shareAmount;

            	 Statement st=conn.createStatement();
            	 String query="insert into company_shares(no_of_shares, share_amount,company_capital_amount)values('"+noOfShare+"','"+shareAmount+"','"+capitalAmount+"')";	
    		     int i=st.executeUpdate(query);
    		     if(i>=1)
    		     {
    		    	 dataInsertInQueryTable(query, conn);
    		    	 return 1;
    		     } 
             }
		     
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public void updateInterestAmountInLoanPayReceipt(int branchId,int myId,double interestAmount)
	{
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="update loanpayment set interestAmount='"+interestAmount+"' where id='"+myId+"'";
			st.executeUpdate(qq);
			dataInsertInQueryTable(qq, con);
			increaseCompanyCapitalAmount(branchId,interestAmount,con);
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}

	public void decreaseSharedCompanyAmount(int branchId,double principleAmount) 
	{
		double sharedAmount=totalSharedAmountOfCompany(branchId);
		double updatedAmount=sharedAmount-principleAmount;
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="update company_shares set amount_shared='"+updatedAmount+"'";
			st.executeUpdate(selectQueWithBranch(qq, branchId));
			//dataInsertInQueryTable(qq, con);
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}

	public boolean checkNoOfSharesForTransfer(double noOfShare, String transferShareHolderNo) 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select * from shareholder_info where shareholderno='"+transferShareHolderNo+"'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				if(noOfShare>rs.getDouble("noofShare"))
				{
					return true;
				}
				else
				{
					return false;
				}
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return false;
	}

	public void insertCertificationNoOfShareHolder(String crNo, int id)
	{
		try(Connection conn=DataBaseConnection.JAVAConnection();)
		{
			Statement st=conn.createStatement();
			String qq="update shareholder_info set crNo='"+crNo+"' where id='"+id+"'";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
				dataInsertInQueryTable(qq, conn);
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}
	
	public void insertCertificationNoOfShareHolderNewShareInfoTable(String crNo, int id)
	{
		try(Connection conn=DataBaseConnection.JAVAConnection();)
		{
			Statement st=conn.createStatement();
			String qq="update share_info set crNo='"+crNo+"' where id='"+id+"'";
			////System.out.println(qq);
			int i=st.executeUpdate(qq);
			if(i>0)
			{
				dataInsertInQueryTable(qq, conn);
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}

	public boolean checkShareHolderExistence(String transferShareHolderNo) 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select * from shareholder_info where shareholderno='"+transferShareHolderNo+"' and account_status='active'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return true;
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return false;
	}

	public int obtainIdOfShareHolder(String transferShareHolderNo) 
	{
		int id=0;
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select * from shareholder_info where shareholderno='"+transferShareHolderNo+"'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				id=rs.getInt("id");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return id;
	}

	public void updateCertificationNoOfTransferShareholder(int transferId, double noOfShare) 
	{
		String accStart="";
		String accLast="";
		String accFinal="";
		String crt="";
		//int nos=(int)noOfShare;
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select * from shareholder_info where id = '"+transferId+"'"; 
			ResultSet rr = st.executeQuery(qq);
			if(rr.next())
			{
				crt=rr.getString("crNo");
				String[] crtf=crt.split("-");
				accStart=crtf[0];
				String last=crtf[1];
				int lst= Integer.parseInt(last);
				String reqrd_share=String.valueOf(lst-(int)noOfShare);
				int len=reqrd_share.length();

				if(len>0)
				{
					while(accLast.length()!=10-len)
					{
						accLast+="0";
					}
					accLast=accLast+(lst-(int)noOfShare);
				}
				
				accFinal=accStart+"-"+accLast;
			}
			
			
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		insertCertificationNoOfShareHolder(accFinal, transferId);
		
	}
	
	public void increaseCertificationNoOfTransferShareHolder(int branchId,int transferId, double noOfShare)
	{
		String accStart="";
		String accLast="";
		String accFinal="";
		String crt="";
		//int nos=(int)noOfShare;
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select * from shareholder_info where id = '"+transferId+"'"; 
			ResultSet rr = st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				crt=rr.getString("crNo");
				String[] crtf=crt.split("-");
				accStart=crtf[0];
				String last=crtf[1];
				int lst= Integer.parseInt(last);
				String reqrd_share=String.valueOf(lst+(int)noOfShare);
				int len=reqrd_share.length();

				if(len>0)
				{
					while(accLast.length()!=10-len)
					{
						accLast+="0";
					}
					accLast=accLast+(lst+(int)noOfShare);
				}
				
				accFinal=accStart+"-"+accLast;
			}
			
			
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		insertCertificationNoOfShareHolder(accFinal, transferId);
		
	}

	public String certificationNoOfNewShareHolderNoFromTransfer(int transferId,
			double noOfShare) 
	{
		String accStart="";
		String accLast="";
		String accFinal="";
		String crt="";
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select * from shareholder_info where id = '"+transferId+"'"; 
			ResultSet rr = st.executeQuery(qq);
			if(rr.next())
			{
				crt=rr.getString("crNo");
				
				String[] crtf=crt.split("-");
				String first=crtf[0];
				String last=crtf[1];
				
				int fst= Integer.parseInt(first);
				int temp_lst=Integer.parseInt(last)+1;
				int lst= Integer.parseInt(last);
				
				String start_from=String.valueOf(temp_lst);
				int lenOfSum=start_from.length();
				
				String reqrd_share=String.valueOf(lst+(int)noOfShare);
				int len=reqrd_share.length();
				
				if(lenOfSum>0)
				{
					while(accStart.length()!=10-lenOfSum)
					{
						accStart+="0";
					}
					
					accStart=accStart+(temp_lst);
				}

				if(len>0)
				{
					while(accLast.length()!=10-len)
					{
						accLast+="0";
					}
					accLast=accLast+(lst+(int)noOfShare);
				}
				
				accFinal=accStart+"-"+accLast;
			}
			
			
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return accFinal;
	}
	
	
	public String addDsaCommision(int branchId,Connection conn, String type, String userNo, String emiNo, Date creditDate, double amount, String dsaCode) 
	{
		int i=0;
		PreparedStatement st=null;
		ResultSet rr=null;
		String query="insert into dsa_commission(type, user_no, dsa_code, amount, credit_date, emi_no, branch_id)values(?,?,?,?,?,?,?)";
        try
		{
			st=conn.prepareStatement(query);
			st.setString(1, type);
			st.setString(2, userNo);
			st.setString(3, dsaCode);
			st.setDouble(4, amount);
			st.setTimestamp(5,new Timestamp(creditDate.getTime()));
			st.setString(6, emiNo);
			st.setInt(7, branchId);
			i=st.executeUpdate();
			if(i >0)
			{
				dataInsertInQueryTable(String.valueOf(st), conn);
				return "i";
			}
		}
		catch (Exception e)
		{
			  e.printStackTrace();fileCreation(e.getMessage());
		}
        finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		
		}
		return "";
	}

	public int addBank(int branchId,Date entryDate, String bankName, String bankBranch,
			String bankAddress, String accNo, String bankCode, String bankIFSC,
			String description, String amount, Connection conn) 
	{
		int i=0;
		PreparedStatement st=null;
		ResultSet rr=null;
		String query="insert into bank_table(entry_date, bank_name, bank_branch, address, acc_no, bank_code, bank_IFSC, description, current_balance, branch_id)values(?,?,?,?,?,?,?,?,?,?)";
        try
		{
			st=conn.prepareStatement(query);
			st.setTimestamp(1,new Timestamp(entryDate.getTime()));
			st.setString(2, bankName);
			st.setString(3, bankBranch);
			st.setString(4, bankAddress);
			st.setString(5, accNo);
			st.setString(6, bankCode);
			st.setString(7, bankIFSC);
			st.setString(8, description);
			st.setString(9, amount);
			st.setInt(10, branchId);

			i=st.executeUpdate();
			if(i>0){
			dataInsertInQueryTable(String.valueOf(st), conn);
		}}
		catch (Exception e)
		{
			  e.printStackTrace();fileCreation(e.getMessage());
		}
        finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		
		}
		return i;
	}

	public ArrayList<BankInfo> allBankInfo()
	{
		ArrayList<BankInfo> bankList=new ArrayList<>();
		int i=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from bank_table";
			ResultSet rr=st.executeQuery(query);
			while(rr.next())
			{
				BankInfo info=new BankInfo();
				info.setSno(++i);
				info.setId(rr.getString("id"));
				info.setEntry_date(rr.getDate("entry_date"));
				info.setStrEntryDate(sf.format(rr.getDate("entry_date")));
				info.setBank_name(rr.getString("bank_name"));
				info.setBank_branch(rr.getString("bank_branch"));
				info.setAddress(rr.getString("address"));
				info.setAcc_no(rr.getString("acc_no"));
				info.setBank_code(rr.getString("bank_code"));
				info.setBank_IFSC(rr.getString("bank_IFSC"));
				info.setDescription(rr.getString("description"));
				info.setCurrent_balance(df.format(rr.getDouble("current_balance")));	

				bankList.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return bankList;

	}

	public int updateBank(String id, Date entryDate, String bankName,
			String bankBranch, String bankAddress, String accNo,
			String bankCode, String bankIFSC, String description, double currentBalance) 
	{
		Timestamp entrydt=new Timestamp(entryDate.getTime());
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
	         Statement stt=conn.createStatement();
		     String query="update bank_table set entry_date='"+entrydt+"', bank_name='"+bankName+"', bank_branch='"+bankBranch+"',"
		     		+ " address='"+bankAddress+"', acc_no='"+accNo+"', bank_code='"+bankCode+"',"
		     		+ " bank_IFSC='"+bankIFSC+"', description='"+description+"', current_balance='"+currentBalance+"' where id='"+id+"' ";	
		     int i=stt.executeUpdate(query);
		     if(i==1)
		     {
		    	 dataInsertInQueryTable(query, conn);
		    	return 1;
		     }
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public BankInfo obtainBankInfoById(String bankName, Connection conn) 
	{
		BankInfo info=new BankInfo();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			String query="select * from bank_table where id='"+bankName+"'";
			 rr=st.executeQuery(query);
			while(rr.next())
			{
				info.setId(rr.getString("id"));
				info.setEntry_date(rr.getDate("entry_date"));
				info.setStrEntryDate(sf.format(rr.getDate("entry_date")));
				info.setBank_name(rr.getString("bank_name"));
				info.setBank_branch(rr.getString("bank_branch"));
				info.setAddress(rr.getString("address"));
				info.setAcc_no(rr.getString("acc_no"));
				info.setBank_code(rr.getString("bank_code"));
				info.setBank_IFSC(rr.getString("bank_IFSC"));
				info.setDescription(rr.getString("description"));
				info.setCurrent_balance(rr.getString("current_balance"));	
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return info;
	}

	public double currentBankBalance(String bankName, Connection conn)
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select * from bank_table where id='"+bankName+"'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getDouble("current_balance");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return 0.0;
	}
	
	public void increaseBankBalance(String bankName ,double amount, Connection conn)
	{
		double oldAmount=currentBankBalance(bankName, conn);
		double updatedAmount=oldAmount+amount;
		updatedAmount=Double.parseDouble(df.format(updatedAmount));
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			String qq="update bank_table set current_balance='"+updatedAmount+"' where id='"+bankName+"'";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
				//dataInsertInQueryTable(qq, conn);
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}

		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
	}
	
	public void decreaseBankBalance(String bankName ,double amount, Connection conn)
	{
		double oldAmount=currentBankBalance(bankName, conn);
		double updatedAmount=oldAmount-amount;
		Statement st=null;
		updatedAmount=Double.parseDouble(df.format(updatedAmount));
		try
		{
			st=conn.createStatement();
			String qq="update bank_table set current_balance='"+updatedAmount+"' where id='"+bankName+"'";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
				//dataInsertInQueryTable(qq, conn);
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}

	public double calculateLoanEmiForCalculator(double principalBal, double duration, double interstRate, int frequency, String emiMode) 
	{
		double monthlyPayment=0, intrest;
		try
		{
			intrest=(principalBal*interstRate*duration)/(100*frequency);
			if(emiMode.equalsIgnoreCase("both"))
			{
				monthlyPayment=(principalBal+intrest)/duration;
			}
			else
			{
				monthlyPayment=intrest/duration;
			}
			monthlyPayment=Double.parseDouble(df.format(monthlyPayment));
		}
		catch(Exception e)
		{
			monthlyPayment=0;
		}
		return Math.round(monthlyPayment);
	}
	
	public double calculateLoanInterestForCalculator(double principalBal, double duration, double emi, int frequency) 
	{
		double interestRate=0, intrest;
		try
		{
			intrest=(emi*duration)-principalBal;
			interestRate=(intrest*100*frequency)/(principalBal*duration);
			interestRate=Double.parseDouble(new DecimalFormat("##.####").format(interestRate));
		}
		catch(Exception e)
		{
			interestRate=0;
		}
		return interestRate;
	}
	
	public double findLoanAmountByLoanNoLoanType(String loanCategory,
			String loanNo, String shareHolderNo, Connection conn)
	{
		String qq="";
		Statement st=null;
		ResultSet rs=null;

		try
		{
			 st=conn.createStatement();
			if(loanCategory.equals("grouploan"))
			{
				qq="select loanAmount,increase_amount from "+loanCategory+" where sub_loan_no='"+loanNo+"' and teamLeader='"+shareHolderNo+"' and status='Approve'";
			}
			else
			{
				qq="select loanAmount,increase_amount from "+loanCategory+" where loanNo='"+loanNo+"' and shareholderno='"+shareHolderNo+"' and status='Approve'"; 
			}
			
			rs=st.executeQuery(qq);
			if(rs.next())
			{
//				if(loanNo.contains("R"))
//				{
//					return rs.getDouble("increase_amount");
//				}
//				else
				{
					return rs.getDouble("loanAmount");
				}
				
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}

		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
			
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	
		
		return 0.0;
	}

	public int addDebitLoan(int branchId,String shareHolderNo, String loanCategory,
			String loanNo, double amount, String paymentMode, String bankName,
			String bankBranch, String chequeNo, Date chequeDate, Date date ,String umrnNo)
	{
		int i=0;
		String status="";
		Timestamp chdate = null;
		if (chequeDate != null) 
		{
			chdate = new Timestamp(chequeDate.getTime());
		}
		
		if(paymentMode.equalsIgnoreCase("Cash") || paymentMode.equalsIgnoreCase("transfer"))
		{
			status="cleared";
			bankName="N/A";
		}
		else 
		{
			if (chequeDate==null) 
			{
				chdate = new Timestamp(new Date().getTime());
			}
			status="uncleared";
		}
		
		String query="insert into debit_loan(shareholderno, loanType, loanNo, amount, paymentMode, bankName, bankBranch,"
				+ " chequeNo, chequeDate, status,date, branch_id,umrn_no) values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
		
		System.out.println(query);
        try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			PreparedStatement st=conn.prepareStatement(query);
			st.setString(1, shareHolderNo);
			st.setString(2, loanCategory);
			st.setString(3, loanNo);
			st.setDouble(4, amount);
			st.setString(5, paymentMode);
			st.setString(6, bankName);
			st.setString(7, bankBranch);
			st.setString(8, chequeNo);
			st.setTimestamp(9,chdate);
			st.setString(10, "cleared");
			st.setTimestamp(11,new Timestamp(date.getTime()));
			st.setInt(12, branchId);
			st.setString(13, umrnNo);

			//System.out.println(st);
			i=st.executeUpdate();
			
			if(i>0){
			dataInsertInQueryTable(String.valueOf(st), conn);
		}}
		catch (Exception e)
		{
			  e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}
	

	
	public ArrayList<DebitInfo> viewDebitLoanHistory(String loanCategory, String loanNo, String shareHolderNo, Connection conn) 
	{
		ArrayList<DebitInfo> history=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;

		int i=0;
		try
		{
			 st=conn.createStatement();
			String query="select * from debit_loan where loanType='"+loanCategory+"' and loanNo='"+loanNo+"' and shareholderno='"+shareHolderNo+"' and status='cleared'";
			 rr=st.executeQuery(query);
			while(rr.next())
			{
				DebitInfo info=new DebitInfo();
				info.setSno(++i);
				info.setId(rr.getString("id"));
				info.setChequeDate(rr.getDate("chequeDate"));
				if(info.getChequeDate()!=null)
				{
					info.setStrChequeDate(sf.format(rr.getDate("chequeDate")));
				}
				info.setBankName(bankNameById(rr.getString("bankName")));
				info.setBankBranch(rr.getString("bankBranch"));
				info.setChequeNo(rr.getString("chequeNo"));
				info.setLoanNo(rr.getString("loanNo"));
				info.setLoanType(rr.getString("loanType"));
				info.setShareholderno(rr.getString("shareholderno"));
				info.setAmount(rr.getString("amount"));
				info.setPaymentMode(rr.getString("paymentMode"));	
				info.setPayDate(rr.getDate("date"));
				info.setStrPayDate(sf.format(rr.getDate("date")));

				history.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return history;
	
	}
	
	public String bankNameById(String bankId) throws SQLException
	{
		Connection con=DataBaseConnection.JAVAConnection();
		try
		{
			Statement st=con.createStatement();
			String qq="select * from bank_table where id='"+bankId+"'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getString("bank_name");
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			con.close();
		}
		return "";
	}

	/*
	 * public String selectStaffName(Date date,String loanNo) { String staffName="";
	 * try(Connection con =DataBaseConnection.JAVAConnection()) { Statement
	 * st=con.createStatement();
	 * 
	 * String
	 * qq="select user_id from loanpayment where loanNo='"+loanNo+"' AND pay_date='"
	 * +date+"'";
	 * 
	 * 
	 * ResultSet rr=st.executeQuery(qq); while(rr.next()) { staffName=
	 * rr.getString("user_id"); System.out.println("gg"+staffName); }
	 * 
	 * 
	 * 
	 * } catch (Exception e) { // TODO: handle exception }
	 * 
	 * return staffName; }
	 */


	public ArrayList<DueDebitInfo> pendingDebitLoanList(int branchId)
	{
		ArrayList<DueDebitInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from debit_loan where status='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				DueDebitInfo info=new DueDebitInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("bankName"),conn);
				info.setSno(++i);
				info.setId(rr.getString("id"));
				info.setChequeDate(rr.getDate("chequeDate"));
				info.setShareHolderNo(rr.getString("shareholderno"));
				if(info.getChequeDate().after(tdyDt))
				{
					info.setDisable(true);
				}
				info.setStrChequeDate(sf.format(rr.getDate("chequeDate")));
				info.setBankId(rr.getString("bankName"));
				info.setBankName(bankNameById(rr.getString("bankName")));
				//info.setBankBranch(rr.getString("bankBranch"));
				info.setChequeNo(rr.getString("chequeNo"));
				info.setAccNo(bb.getAcc_no());
				info.setItem_loan_fdr(rr.getString("loanNo"));
				info.setType(rr.getString("loanType"));
				//info.setShareholderno(rr.getString("shareholderno"));
				info.setAmount(rr.getString("amount"));

				list.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}

	public ArrayList<DueDebitInfo> pendingExpenseList(int branchId) 
	{
		ArrayList<DueDebitInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from expense_table where chequeStatus='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				DueDebitInfo info=new DueDebitInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("bank_name"),conn);
				info.setSno(++i);
				info.setId(rr.getString("id"));
				info.setChequeDate(rr.getDate("chq_dd_date"));
				if(info.getChequeDate().after(tdyDt))
				{
					info.setDisable(true);
					
				}
				info.setStrChequeDate(sf.format(rr.getDate("chq_dd_date")));
				info.setBankId(rr.getString("bank_name"));
				info.setBankName(bankNameById(rr.getString("bank_name")));
				//info.setBankBranch(rr.getString("bankBranch"));
				info.setChequeNo(rr.getString("chq_dd_no"));
				info.setAccNo(bb.getAcc_no());
				info.setItem_loan_fdr(rr.getString("item"));
				info.setType(rr.getString("category"));
				//info.setShareholderno(rr.getString("shareholderno"));
				info.setAmount(rr.getString("amount"));
				info.setDescription(rr.getString("description"));

				list.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}
	
	public ArrayList<DueDebitInfo> pendingTdsSubList(int branchId) 
	{
		ArrayList<DueDebitInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from tds_submission where chequeStatus='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				DueDebitInfo info=new DueDebitInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("bank_name"),conn);
				info.setSno(++i);
				info.setId(rr.getString("id"));
				info.setChequeDate(rr.getDate("chq_dd_date"));
				if(info.getChequeDate().after(tdyDt))
				{
					info.setDisable(true);
					
				}
				info.setStrChequeDate(sf.format(rr.getDate("chq_dd_date")));
				info.setBankId(rr.getString("bank_name"));
				info.setBankName(bankNameById(rr.getString("bank_name")));
				//info.setBankBranch(rr.getString("bankBranch"));
				info.setChequeNo(rr.getString("chq_dd_no"));
				info.setAccNo(bb.getAcc_no());
			//	info.setItem_loan_fdr(rr.getString("item"));
				info.setType(rr.getString("category"));
				//info.setShareholderno(rr.getString("shareholderno"));
				info.setAmount(rr.getString("amount"));

				list.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}

	public ArrayList<DueDebitInfo> pendingFdrExpenseList(int branchId) 
	{
		ArrayList<DueDebitInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from fixed_deposit_expense where chequeStatus='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				DueDebitInfo info=new DueDebitInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("bankName"),conn);
				info.setSno(++i);
				info.setId(rr.getString("id"));
				info.setChequeDate(rr.getDate("chequeDate"));
				if(info.getChequeDate().after(tdyDt))
				{
					info.setDisable(true);
					
				}
				info.setStrChequeDate(sf.format(rr.getDate("chequeDate")));
				info.setBankId(rr.getString("bankName"));
				info.setBankName(bankNameById(rr.getString("bankName")));
				//info.setBankBranch(rr.getString("bankBranch"));
				info.setChequeNo(rr.getString("chequeNo"));
				info.setAccNo(bb.getAcc_no());
				info.setItem_loan_fdr(rr.getString("fdr_no"));
				info.setType("Fixed_Deposit_Dr");
				//info.setShareholderno(rr.getString("shareholderno"));
				info.setAmount(rr.getString("amount"));

				list.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}

	public int updateChequeStatusForDebit(String type, String notificationId, String identity, String userNo, Date chqClearDate) 
	{
		int i=0;
		String table="",statusField="",status="", expDate="";
		Timestamp tt=new Timestamp(chqClearDate.getTime());
		
		if(type.equals("personalloan") || type.equals("propertyloan") || type.equals("vechicleloan") || type.equals("grouploan") || type.equals("secure_loan") || type.equals("business_loan"))
		{
			table="debit_loan";
			statusField="status";
			expDate="date";
		}
		else if(type.equals("Fixed_Deposit_Dr"))
		{
			table="fixed_deposit_expense";
			statusField="chequeStatus";
			expDate="date";
		}
		else if(type.equals("Instant Loan"))
		{
			table="lender_record";
			statusField="chequeStatus";
			expDate="lender_date";
		}
		else if(type.equals("Return Promotor Capital"))
		{
			table="return_promotors_capital";
			statusField="chequeStatus";
			expDate="income_date";
		}
		else if(type.equals("Return Instant Borrow"))
		{
			table="borrower_record";
			statusField="chequeStatus";
			expDate="borrow_date";
		}
		else if(type.equals("Return DSA Comm."))
		{
			table="return_dsa";
			statusField="chequeStatus";
			expDate="pay_date";
		}
		else if(type.equals("Employee Salary Payout"))
		{
			table="salary_ledger";
			statusField="chequeStatus";
			expDate="payDate";
		}
		else if(type.equals("TDS Submission"))
		{
			table="tds_submission";
			statusField="chequeStatus";
			expDate="expense_date";
		}
		else if(type.equals("Fixed_Asset_Dr") || type.equals("Other_Dr") || type.equals("Liability_Dr"))
		{
			table="expense_table";
			statusField="chequeStatus";
			expDate="expense_date";
		}
		else if(type.equals("Maturity Amount(RD/FD)"))
		{
			table="returned_amount_info";
			statusField="chequeStatus";
			expDate="date";
		}
		else if(type.equals("Savings Account Withdrawl"))
		{
			table="customer_withdrwal";
			statusField="chequeStatus";
			expDate="date";
		}
		
		
		if(identity.equals("approve"))
		{
			status="cleared";
		}
		else
		{
			status="returned";
		}
		
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			String qq="";
			Statement st=con.createStatement();
			if(status.equals("cleared"))
			{
				qq="update "+table+" set "+statusField+"='"+status+"', "+expDate+"='"+tt+"' where id='"+notificationId+"'";
			}
			else
			{
				qq="update "+table+" set "+statusField+"='"+status+"' where id='"+notificationId+"'";
			}
			int x=st.executeUpdate(qq);
			if (x >= 1) 
			{
				dataInsertInQueryTable(qq, con);
				if(type.equals("Maturity Amount(RD/FD)") && identity.equals("approve"))
				{
					String qr="update customer_info set paid_status='paid',account_status='inactive' where user_no='"+userNo+ "'";
					int z = st.executeUpdate(qr);
					if (z >= 1) 
					{
						dataInsertInQueryTable(qr, con);
						i++;
					}
				}
				else
				{
					i++;
				}
			}	
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}

	public double paidDebitLoanAmount(String type, String loanNo,
			String shareHolderNo, Connection conn) 
	{
		double amount=0;
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			String qq="select * from debit_loan where loanType='"+type+"' and shareholderno='"+shareHolderNo+"' and loanNo='"+loanNo+"' and status='cleared'";
			rr=st.executeQuery(qq);
			while(rr.next())
			{
				amount=amount+rr.getDouble("amount");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}

finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return amount;
	}

	public ArrayList<SelectItem> groupHeadSelectList(Connection conn, String selectedCategoy)
	{
		Statement st=null;ResultSet rr=null;
		ArrayList<SelectItem> OtherList=new ArrayList<>();
		try
		{
			if(selectedCategoy.equalsIgnoreCase("Other_Cr"))
			{
				selectedCategoy="Income";
			}
			else if(selectedCategoy.equalsIgnoreCase("Liability_Cr"))
			{
				selectedCategoy="Liability";
			}
			
			st=conn.createStatement();
			String query="select * from group_head where group_head_type='"+selectedCategoy+"'";
			rr=st.executeQuery(query);
			while(rr.next())
			{
				SelectItem info=new SelectItem();
				
				info.setValue(rr.getString("group_head_name"));
				info.setLabel(rr.getString("group_head_name"));
				
				OtherList.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return OtherList;

	}


	public void updateInterestAmountInLoanPayReceiptWithoutIncreasingCompanyCapital(int myId, double interestAmount) 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="update loanpayment set interestAmount='"+interestAmount+"' where id='"+myId+"'";
			int i=st.executeUpdate(qq);
			if(i>0){
			dataInsertInQueryTable(qq, con);
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
	}

	public Double acconuntHolderTotalDepositedAmountByAccountNo(int branchId,String accno) 
	{
		double amount=0.0;
		try(Connection conn=DataBaseConnection.JAVAConnection();)
	    {
		   Statement stt=conn.createStatement();
		   String query="select * from customer_deposit where account_no='"+accno+"' and status='approved'";
		   ResultSet ss=stt.executeQuery(selectQueWithBranch(query,branchId));
		   while(ss.next())
		   {
			   amount+=ss.getDouble("amount");
		   }
		} 
	    catch (Exception e) 
	    {
			 e.printStackTrace();fileCreation(e.getMessage());
		}	
		return amount;
	}

	public ArrayList<UserInfo> pendingIncomeList(int branchId)
	{
		ArrayList<UserInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from income_table where chequeStatus='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				UserInfo ll=new UserInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("transfer_to_bank"),conn);
				
				ll.setId(rr.getString("id"));
				ll.setAccountNo(rr.getString("item"));
				ll.setEntryDate(rr.getDate("income_date"));
				ll.setEntryDateStr(sf.format(ll.getEntryDate()));
				ll.setAmount(rr.getDouble("amount"));
				ll.setStatus(rr.getString("category"));
				ll.setPayMode(rr.getString("payment_mode"));
				ll.setBank_name(rr.getString("bank_name"));
				ll.setChq_ddNo(rr.getString("chq_dd_no"));
				if(rr.getDate("chq_dd_date")!=null)
				{
					ll.setChq_ddDate(rr.getDate("chq_dd_date"));
					ll.setChq_ddDateStr(sf.format(ll.getChq_ddDate()));
					
					if(ll.getChq_ddDate().after(tdyDt))
					{
						ll.setDisable(true);
					}
				}
				
				ll.setSubmittedToBank(rr.getString("transfer_to_bank"));
				ll.setTransferredToBankName(bb.getBank_name()+"-"+bb.getAcc_no());
				if(rr.getString("loan_no")!=null && !rr.getString("loan_no").equals(""))
				{
					ll.setFirst_applicantName(firstApplicantNameBySHNo(shareHolderNoByLoanNo(rr.getString("loan_no")),conn));
				}
				
				list.add(ll);			
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}

	public ArrayList<UserInfo> pendingFdrIncomeList(int branchId) 
	{
		ArrayList<UserInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from fixed_deposit_income where chequeStatus='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				UserInfo ll=new UserInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("transfer_to_bank"),conn);
				
				ll.setId(rr.getString("id"));
				ll.setAccountNo(rr.getString("bank")+"-"+rr.getString("fdr_no"));
				ll.setEntryDate(rr.getDate("date"));
				ll.setEntryDateStr(sf.format(ll.getEntryDate()));
				ll.setAmount(rr.getDouble("amount"));
				ll.setStatus("Fixed_Deposit_Cr");
				ll.setPayMode(rr.getString("paymentMode"));
				ll.setBank_name(rr.getString("bankName"));
				ll.setChq_ddNo(rr.getString("chequeNo"));
				ll.setChq_ddDate(rr.getDate("chequeDate"));
				ll.setChq_ddDateStr(sf.format(ll.getChq_ddDate()));
				
				if(ll.getChq_ddDate().after(tdyDt))
				{
					ll.setDisable(true);
				}
				ll.setSubmittedToBank(rr.getString("transfer_to_bank"));
				ll.setTransferredToBankName(bb.getBank_name()+"-"+bb.getAcc_no());
				
				
				list.add(ll);			
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}

	public ArrayList<DueDebitInfo> pendingReturnAmountRdFdList(int branchId)
	{
		ArrayList<DueDebitInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from returned_amount_info where chequeStatus='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				DueDebitInfo info=new DueDebitInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("bankName"),conn);
				info.setSno(++i);
				info.setId(rr.getString("id"));
				info.setChequeDate(rr.getDate("chequeDate"));
				
				if(info.getChequeDate()!=null && info.getChequeDate().after(tdyDt)  )
				{
					info.setDisable(true);
					
				}
				if(info.getChequeDate()!=null)
				{
					info.setStrChequeDate(sf.format(rr.getDate("chequeDate")));
				}
				
				info.setBankId(rr.getString("bankName"));
				info.setBankName(bankNameById(rr.getString("bankName")));
				//info.setBankBranch(rr.getString("bankBranch"));
				info.setChequeNo(rr.getString("chequeNo"));
				info.setAccNo(bb.getAcc_no());
				info.setItem_loan_fdr(rr.getString("user_no"));
				info.setType("Maturity Amount(RD/FD)");
				info.setAmount(rr.getString("maturity_value"));

				list.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}
	
	

	public double obtainMaturityValueByUserNo(String user_no) 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select * from customer_info where user_no='"+user_no+"'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getDouble("maturity_value");
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public double obtainPaidMaturityValueByUserNo(String user_no) 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select * from returned_amount_info where user_no='"+user_no+"' and chequeStatus='cleared'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getDouble("maturity_value");
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public boolean existingValueInReturnedAmountTable(String user_no) 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select * from returned_amount_info where chequeStatus='uncleared' and user_no='"+user_no+"'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return true;
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return false;
	}

	public ArrayList<DueDebitInfo> pendingWithdrawList(int branchId) 
	{
		ArrayList<DueDebitInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from customer_withdrwal where chequeStatus='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				DueDebitInfo info=new DueDebitInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("from_bank_name"),conn);
				info.setSno(++i);
				info.setId(rr.getString("id"));
				info.setChequeDate(rr.getDate("cheque_dd_date"));
				if(info.getChequeDate().after(tdyDt))
				{
					info.setDisable(true);
					
				}
				info.setStrChequeDate(sf.format(rr.getDate("cheque_dd_date")));
				info.setBankId(rr.getString("from_bank_name"));
				info.setBankName(bankNameById(rr.getString("from_bank_name")));
				//info.setBankBranch(rr.getString("bankBranch"));
				info.setChequeNo(rr.getString("cheque_dd_no"));
				info.setAccNo(bb.getAcc_no());
				info.setItem_loan_fdr(rr.getString("account_no"));
				info.setType("Savings Account Withdrawl");
				info.setAmount(rr.getString("amount"));

				list.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}

	public void updateStatusForWithDrawl(String notificationId, String status) 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="update customer_withdrwal set status='"+status+"' where id='"+notificationId+"'";
		int i=	st.executeUpdate(qq);
		if(i>0){	
		dataInsertInQueryTable(qq, con);
		}}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}

	public String shareHolderNameByShareHolderNo(String transferShareHolderNo, Connection conn)
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from shareholder_info where shareholderno='"+transferShareHolderNo+"'";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("first_applicantName");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}

	public String certificateNoOfShareHolderByShareNo(int branchId,String transferorNo) 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select * from shareholder_info where shareholderno='"+transferorNo+"'";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rs.next())
			{
				return rs.getString("crNo");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}

	public void decreaseCapitalCompanyAmount(int branchId,Double amt)
	{
		double capitalAmount=totalCompanyCapitalAmount(branchId);
		double updatedAmount=capitalAmount-amt;
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="update company_shares set company_capital_amount='"+updatedAmount+"'";
			int i=	st.executeUpdate(selectQueWithBranch(qq,branchId));
			if(i>0)
			{
				//dataInsertInQueryTable(qq, con);
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
	}

	public void updateInterestAmountInCustomerDeposit(int branchId,String accountNo,
			double finalAmount, Timestamp updateDate, Connection conn)
	{
		try
		{
			String query="insert into customer_deposit(account_no, amount, date,payment_mode, status,chequeStatus,type,branch_id) values(?,?,?,?,?,?,?,?)";
			PreparedStatement st1=conn.prepareStatement(query);
			st1.setString(1,accountNo);
			st1.setDouble(2,finalAmount);
			st1.setTimestamp(3,updateDate);
			st1.setString(4,"Cash");
			st1.setString(5, "approved");
			st1.setString(6, "cleared");
			st1.setString(7, "interest");
			st1.setInt(8, branchId);
			
		int i=	st1.executeUpdate();
		if(i>0){	
		dataInsertInQueryTable(String.valueOf(st1), conn);
		}}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
	}

	public void updatePaidAmountAndDateInSavingAccount(String accountNo,
			double finalTotal, double accBalance, Timestamp updateDate, Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="update savingaccount set updateDate='"+updateDate+"', paidAmount='"+finalTotal+"', amount='"+accBalance+"' where accountNo='"+accountNo+"'"; 
			st.executeUpdate(qq);
			dataInsertInQueryTable(qq, conn);
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
	}

	public ArrayList<InstallmentInfo> interestListOfCustomerDeposit(int branchId) 
	{
		ArrayList<InstallmentInfo> list=new ArrayList<>();
		int i=1;
		try(Connection con=DataBaseConnection.JAVAConnection();)  
		{
			Statement st=con.createStatement();
			String qq="select * from customer_deposit where type='interest' ";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rs.next())
			{
				InstallmentInfo ii=new InstallmentInfo();
				
				ii.setSno(i++);
				ii.setUser_no(rs.getString("account_no"));
				ii.setShareHolderNo(shareHolderNoBySavingAccountNO(ii.getUser_no()));
				ii.setName(firstApplicantNameBySHNo(ii.getShareHolderNo(), con));
				ii.setInterest(rs.getDouble("amount"));
				ii.setPayoutDate(rs.getDate("date"));
				ii.setStrPayOutDate(sf.format(ii.getPayoutDate()));
				
				list.add(ii);
			}
				
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	
	public ArrayList<InstallmentInfo> interestListOfCustomerDeposit(int branchId,Timestamp start,Timestamp end) 
	{
		ArrayList<InstallmentInfo> list=new ArrayList<>();
		String stdt=String.valueOf(start).substring(0,10);
		String endt=String.valueOf(end).substring(0,10);
		int i=1;
		try(Connection con=DataBaseConnection.JAVAConnection();)  
		{
			Statement st=con.createStatement();
			String qq="select * from customer_deposit where date>='"+stdt+"' and date<='"+endt+"' and type='interest' order by account_no asc";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rs.next())
			{
				InstallmentInfo ii=new InstallmentInfo();
				
				ii.setSno(i++);
				ii.setUser_no(rs.getString("account_no"));
				ii.setShareHolderNo(shareHolderNoBySavingAccountNO(ii.getUser_no()));
				ii.setName(firstApplicantNameBySHNo(ii.getShareHolderNo(),con));
				ii.setInterest(rs.getDouble("amount"));
				ii.setPayoutDate(rs.getDate("date"));
				ii.setStrPayOutDate(sf.format(ii.getPayoutDate()));
				
				list.add(ii);
			}
				
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	
	public ArrayList<InstallmentInfo> interestListOfLoanPayment(int branchId) 
	{
		ArrayList<InstallmentInfo> list=new ArrayList<>();
		int i=1;
		try(Connection con=DataBaseConnection.JAVAConnection();)  
		{
			Statement st=con.createStatement();
			String qq="select * from loanpayment where receipt_status='approved'";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rs.next())
			{
				InstallmentInfo ii=new InstallmentInfo();
				
				ii.setSno(i++);
				ii.setUser_no(rs.getString("loanNo"));
				ii.setInterest(rs.getDouble("interestAmount"));
				ii.setPayoutDate(rs.getDate("pay_date"));
				ii.setStrPayOutDate(sf.format(ii.getPayoutDate()));
				
				list.add(ii);
			}
				
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	
	public ArrayList<InstallmentInfo> interestListOfLoanPayment(int branchId,Timestamp start,Timestamp end) 
	{
		ArrayList<InstallmentInfo> list=new ArrayList<>();
		String stdt=String.valueOf(start).substring(0,10);
		String endt=String.valueOf(end).substring(0,10);
		int i=1;
		try(Connection con=DataBaseConnection.JAVAConnection();)  
		{
			Statement st=con.createStatement();
			String qq="select * from loanpayment where receipt_status='approved' and pay_date>='"+stdt+"' and pay_date<='"+endt+"'";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rs.next())
			{
				InstallmentInfo ii=new InstallmentInfo();
				
				ii.setSno(i++);
				ii.setUser_no(rs.getString("loanNo"));
				ii.setInterest(rs.getDouble("interestAmount"));
				ii.setPayoutDate(rs.getDate("pay_date"));
				ii.setStrPayOutDate(sf.format(ii.getPayoutDate()));
				
				list.add(ii);
			}
				
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	
	
	public ArrayList<BankInfo> allBankTransactionInfo(int branchId,Date startDate, Date endDate)
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		ArrayList<BankInfo> list=new ArrayList<>();
		int i=1;
		BankInfo toBank=new BankInfo();
		BankInfo fromBank=new BankInfo();		
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select * from debit_current_asset_bank where date>='"+sDate+"' and date<='"+eDate+"' ";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rs.next())
			{
				BankInfo ii=new BankInfo();
				
				fromBank=obtainBankInfoById(rs.getString("bank_name"),con);
				
				if(!rs.getString("transfer_to_bank").equals("N/A"))
				{
					toBank=obtainBankInfoById(rs.getString("transfer_to_bank"),con);
					ii.setTransfer_acc(toBank.getAcc_no());
					ii.setTransferBankId(rs.getString("transfer_to_bank"));
					ii.setTransfer_bank(bankNameById(rs.getString("transfer_to_bank")));
				}
				else
				{
					ii.setTransfer_acc("N/A");
					ii.setTransferBankId("N/A");
					ii.setTransfer_bank("N/A");
				}
				ii.setDisableForFreezingData(checkDataFreezing(branchId,DataBaseMethods.selectedSessionDetail(), con));
				ii.setSno(i++);
				ii.setId(rs.getString("id"));
				ii.setEntry_date(rs.getDate("date"));
				ii.setStrEntryDate(sf.format(rs.getDate("date")));
				ii.setBankId(rs.getString("bank_name"));
				ii.setBank_name(bankNameById(rs.getString("bank_name")));
				ii.setAcc_no(fromBank.getAcc_no());
				ii.setStatus(rs.getString("type"));
				ii.setAmount(rs.getDouble("amount"));
				ii.setPayment_mode(rs.getString("paymentMode"));
				ii.setCheque_no(rs.getString("chequeNo"));
				ii.setDescription(rs.getString("description"));
				
		//		// // // //System.out.println(ii.getStatus());
				
				list.add(ii);
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	public int deleteBankTransactionEntry(String id) 
	{
		int i=0;
        try(Connection conn=DataBaseConnection.JAVAConnection())
        {
			Statement stt=conn.createStatement();
			String query="delete from debit_current_asset_bank where id='"+id+"'";
			i=stt.executeUpdate(query);
			if(i>0){
			dataInsertInQueryTable(query, conn);
		} }
        catch (Exception e)
        {
        	 e.printStackTrace();fileCreation(e.getMessage());
		} 		
		return i;
	}
	public double extractTotalShares()
	{
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
             Statement stt=conn.createStatement();
		     String query="select * from company_shares";	
		     ResultSet rs=stt.executeQuery(query);
		     if(rs.next())
		     {
		    	 return rs.getDouble("no_of_shares");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0.0;
	}
	
	public double extractTotalIssueShares(int branchId)
	{
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
             Statement stt=conn.createStatement();
		     String query="SELECT sum(issue_share) FROM shareholder_info where cheque_status='cleared' ";	
		     ResultSet rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("sum(issue_share)");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0.0;
	}
	
	/*public double extractTotalIssueSharesFromShareInfoTable()
	{
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
             Statement stt=conn.createStatement();
		     String query="SELECT sum(issue_share) FROM share_info ";	
		     ResultSet rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("sum(issue_share)");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0.0;
	}*/
	
	public double totalDDRDAmountTaken(int branchId,Date startDate, Date endDate, String schemeType) 
	{
		Timestamp start=null;
		Timestamp end=new Timestamp(endDate.getTime());
		String query="";
		if(startDate!=null)
		{
			start=new Timestamp(startDate.getTime());
			query ="select sum(amount) as totalRDAmount from payment_receipt where receipt_status='approved' and  scheme_type='"+schemeType+"' and date >='"+start+"' and date <= '"+end+"'";
		}
		else
		{
			query ="select sum(amount) as totalRDAmount from payment_receipt where receipt_status='approved' and   scheme_type='"+schemeType+"' and date <= '"+end+"'";
		}
		
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
             Statement stt=conn.createStatement();
		     ResultSet rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalRDAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0.0;
	}
	
	// to find total Active DD/RD/FD Deposit From customer_info table and Calculate Amount From payment_receipt table
	public double totalActiveDepositAmountTaken(int branchId,String schemeType, Connection conn, String sDate, String eDate) 
	{
		double total=0;
		Statement stt=null, stt1=null;
		ResultSet rs=null, rs1=null;
		try 
		{
			 stt1=conn.createStatement();
             String query1 ="select user_no from customer_info where scheme_type='"+schemeType+"'  ";;
     		 rs1=stt1.executeQuery(selectQueWithBranch(query1,branchId));
     		 total=0;
		     while(rs1.next())
		     {
     			
		    	 total+=paidRdAmountBetweenDate(rs1.getString("user_no"), sDate, eDate);
		     }	 
        }
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(stt1!=null)
				{
					stt1.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
				if(rs1!=null)
				{
					rs1.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return total;
	}
	
	// Total FD Deposit Amount Receive from From user's
	public double totalFDAmountTaken(int branchId,Date startDate, Date endDate) 
	{
		Timestamp start=null;
		Timestamp end=new Timestamp(endDate.getTime());
		String query="";
		if(startDate!=null)
		{
			start=new Timestamp(startDate.getTime());
			query ="select sum(amount) as totalFDAmount from payment_receipt where receipt_status='approved' and scheme_type='FD' and date >='"+start+"' and date <= '"+end+"'";
		}
		else
		{
			query ="select sum(amount) as totalFDAmount from payment_receipt where receipt_status='approved' and scheme_type='FD' and date <= '"+end+"'";
		}
	//	// // // //System.out.println(query);
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
             Statement stt=conn.createStatement();
		     ResultSet rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalFDAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0.0;
	}
	
	// Total Deposit Amount in Saving Account from customer_deposit table
	public double totalDepositedAmount(int branchId,Date startDate, Date endDate, Connection conn) 
	{
		Timestamp start=null;
		Timestamp end=new Timestamp(endDate.getTime());
		String query="";
		Statement stt=null;
		ResultSet rs=null;
		if(startDate!=null)
		{
			start=new Timestamp(startDate.getTime());
			query ="select sum(amount) as totalAmount from customer_deposit where status='approved' and type='deposit' and date >= '"+start+"' and date <= '"+end+"'";
		}
		else
		{
			query ="select sum(amount) as totalAmount from customer_deposit where status='approved' and type='deposit' and date <= '"+end+"'";
		}
		//query+=" and payment_mode!='Transfer' ";
		
		//// //System.out.println(query);
		try
		{
             stt=conn.createStatement();
		    	
		     rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	
	// Total Withdrawl Amount from Saving Account by user's from customer_withdrwal table
	public double totalWithdrawlAmount(int branchId,Date startDate, Date endDate, Connection conn) 
	{
		Timestamp start=null;
		Timestamp end=new Timestamp(endDate.getTime());
		String query="";
		Statement stt=null;
		 ResultSet rs=null;
		if(startDate!=null)
		{
			start=new Timestamp(startDate.getTime());
			query ="select sum(amount) as totalAmount from customer_withdrwal where status='approved' and date >= '"+start+"' and date <= '"+end+"'";
		}
		else
		{
			query ="select sum(amount) as totalAmount from customer_withdrwal where status='approved' and date <= '"+end+"'";
		}
		//// //System.out.println(query);
		try
		{
             stt=conn.createStatement();
		    rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	
	// Total find the Total Saving Interest Amount from customer_deposit table 
	public double totalSavingsInterestAmount(int branchId,Date startDate, Date endDate,Connection conn) 
	{
		Timestamp start=null;
		Timestamp end=new Timestamp(endDate.getTime());
		String query="";
		Statement stt=null;
		 ResultSet rs=null;
		if(startDate!=null)
		{
			start=new Timestamp(startDate.getTime());
			query ="select sum(amount) as totalAmount from customer_deposit where status='approved' and type='interest' and date >= '"+start+"' and date <= '"+end+"'";
		}
		else
		{
			 query="select sum(amount) as totalAmount from customer_deposit where status='approved' and type='interest' and date <= '"+end+"'";
		}
		try
		{
             stt=conn.createStatement();
		    	
		    rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	
	// to find Total Current Balance From All Bank's account
	public double allBankBalance(int branchId,Connection conn)
	{
		Statement stt=null;
		ResultSet rs=null;
		try 
		{
             stt=conn.createStatement();
		     String query="select sum(current_balance) as totalAmount from bank_table";	
		    rs =stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	
	// to find Total Loan Amount Given Between Date to user's from debit_loan table 
	public double totalLoanAmount(int branchId,Date startDate, Date endDate)
	{
		Timestamp start=null;
		Timestamp end=new Timestamp(endDate.getTime());
		String query="";
		if(startDate!=null)
		{
			start=new Timestamp(startDate.getTime());
			query ="select sum(amount) as totalAmount from debit_loan where status='cleared' and date >= '"+start+"' and date <= '"+end+"'";
		}
		else
		{
			query ="select sum(amount) as totalAmount from debit_loan where status='cleared' and date <= '"+end+"'";
		}
		
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
             Statement stt=conn.createStatement();
		     ResultSet rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0.0;
	}
	public double totalGoodsExpenseAmount(int branchId,Date startDate, Date endDate, Connection conn)
	{
		Timestamp start=null;
		Timestamp end=new Timestamp(endDate.getTime());
		String query="";
		Statement stt=null;
		ResultSet rs=null;
		if(startDate!=null)
		{
			start=new Timestamp(startDate.getTime());
			query ="select sum(amount) as totalAmount from expense_table where category='Fixed_Asset_Dr' and status='active' and chequeStatus='cleared' and expense_date >= '"+start+"' and expense_date <= '"+end+"'";
		}
		else
		{
			 query="select sum(amount) as totalAmount from expense_table where category='Fixed_Asset_Dr' and status='active' and chequeStatus='cleared' and expense_date <= '"+end+"'";	
		}
		
		try
		{
             stt=conn.createStatement();
		     rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	
	
	public double totalGoodsIncomeAmount(int branchId,Date startDate, Date endDate, Connection conn)
	{
		Timestamp start=null;
		Timestamp end=new Timestamp(endDate.getTime());
		String query="";
		Statement stt=null;
		ResultSet rs=null;
		if(startDate!=null)
		{
			start=new Timestamp(startDate.getTime());
			query ="select sum(amount) as totalAmount from income_table where category='Fixed_Asset_Cr' and chequeStatus='cleared' and income_date >= '"+start+"' and income_date <= '"+end+"'";
		}
		else
		{
			 query="select sum(amount) as totalAmount from income_table where category='Fixed_Asset_Cr' and chequeStatus='cleared' and income_date <= '"+end+"'";	
		}
		
		try
		{
             stt=conn.createStatement();
		     rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	
	public double totalFdrExpenseAmount(int branchId,Date startDate, Date endDate, Connection conn) 
	{
		Timestamp start=null;
		Timestamp end=new Timestamp(endDate.getTime());
		String query="";
		Statement stt=null;
		 ResultSet rs=null;
		if(startDate!=null)
		{
			start=new Timestamp(startDate.getTime());
			query ="select sum(amount) as totalAmount from fixed_deposit_expense where chequeStatus='cleared' and date >= '"+start+"' and date <= '"+end+"'";
		}
		else
		{
			 query="select sum(amount) as totalAmount from fixed_deposit_expense where chequeStatus='cleared' and date <= '"+end+"'";	
		}
		
		try
		{
             stt=conn.createStatement();
		     rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	
	public double totalFdrBalanceAmountForBalanceSheet(int branchId,Date startDate, Date endDate, Connection conn) 
	{
		double totalAmt=0;
		Timestamp start=null;
		Timestamp end=new Timestamp(endDate.getTime());
		String query="";
		Statement stt=null;
		ResultSet rs=null;
		if(startDate!=null)
		{
			start=new Timestamp(startDate.getTime());
			query ="select sum(amount) from fixed_deposit_expense where chequeStatus='cleared' and date >= '"+start+"' and date <= '"+end+"'";
		}
		else
		{
			 query="select sum(amount) from fixed_deposit_expense where chequeStatus='cleared' and date <= '"+end+"'";	
		}
		//System.out.println(query);
		try
		{
             stt=conn.createStatement();
		     rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 totalAmt=rs.getDouble("sum(amount)");
		    	 Statement st=conn.createStatement();
		    	 String qq="select sum(old_amount) from fixed_deposit_income where chequeStatus='cleared' and date >= '"+start+"' and date <= '"+end+"' ";
		    	//System.out.println(qq);
		    	 ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
		    	 if(rr.next())
		    	 {
		    		 //System.out.println(totalAmt);
		    		 totalAmt=totalAmt-rr.getDouble("sum(old_amount)");
		    		 //System.out.println(totalAmt);
		    	 }
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return totalAmt;
	}
	
	public double totalFdrInterestAmount(int branchId,Date startDate, Date endDate,Connection conn) 
	{
		Timestamp start=null;
		Timestamp end=new Timestamp(endDate.getTime());
		String query="";
		Statement stt=null; ResultSet rs=null;
		if(startDate!=null)
		{
			start=new Timestamp(startDate.getTime());
			query ="select sum(interest) as totalAmount from fdr_interest where status='active' and date >= '"+start+"' and date <= '"+end+"'";
		}
		else
		{
			query="select sum(interest) as totalAmount from fdr_interest where status='active' and date <= '"+end+"'";	
		}
		
		try
		{
             stt=conn.createStatement();
		    rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	public double totalApplicantFee(int branchId,Date startDate, Date endDate,Connection conn)
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		Statement stt=null;
		ResultSet rs=null;
		try 
		{
             stt=conn.createStatement();
		     String query="select sum(applicant_fees) as totalAmount from customer_info where office_date>='"+sDate+"' and office_date <= '"+eDate+"'";	
		     rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	
	public double totalApplicantFeeForOpening(int branchId,Date startDate, Connection conn)
	{
		String sDate=sdfForDb.format(startDate);
		Statement stt=null;
		ResultSet rs=null;
		try 
		{
             stt=conn.createStatement();
		     String query="select sum(applicant_fees) as totalAmount from customer_info where office_date < '"+sDate+"'";	
		     rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	
	public double totalApplicantFeeBetweenDate(int branchId,Date startDate, Date endDate, Connection conn)
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		Statement stt=null;
		ResultSet rs=null;
		try 
		{
             stt=conn.createStatement();
		     String query="select sum(applicant_fees) as totalAmount from customer_info where office_date >= '"+sDate+"' and  office_date <= '"+eDate+"' ";	
		     rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	
	public double totalLoanInterest(int branchId,Date startDate, Date endDate,Connection conn) 
	{
		Statement stt=null;
		 ResultSet rs=null;
		/*Timestamp start=new Timestamp(startDate.getTime());
		Timestamp end=new Timestamp(endDate.getTime());*/
		
		 String start=sdfForDb.format(startDate);
		 String end=sdfForDb.format(endDate);
		 
		 try 
		{
             stt=conn.createStatement();
		     String query="select sum(interestAmount) as totalAmount from loanpayment where chequeStatus='cleared' and receipt_status='approved' and pay_date>='"+start+"'  and pay_date <= '"+end+"'";	
		     rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	
	public double totalLoanInterestByLoanNo(Date startDate, Date endDate, Connection conn, String loanNo) 
	{
		Statement stt=null;
		 ResultSet rs=null;
		/*Timestamp start=new Timestamp(startDate.getTime());
		Timestamp end=new Timestamp(endDate.getTime());*/
		
		 String start=sdfForDb.format(startDate);
		 String end=sdfForDb.format(endDate);
		 
		 try 
		{
             stt=conn.createStatement();
		     String query="select sum(interestAmount) as totalAmount from loanpayment where loanNo='"+loanNo+"' and  chequeStatus='cleared' and receipt_status='approved' and pay_date>='"+start+"'  and pay_date <= '"+end+"'";	
		     //// //System.out.println(query);
		     rs=stt.executeQuery(query);
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	
	public double totalLoanPrinciple(int branchId,Date startDate, Date endDate) 
	{
		Timestamp start=null;
		Timestamp end=new Timestamp(endDate.getTime());
		String query="";
		if(startDate!=null)
		{
			start=new Timestamp(startDate.getTime());
			query ="select sum(interestAmount) as interest,sum(amount) as total from loanpayment where receipt_status='approved' and chequeStatus='cleared' and pay_date >= '"+start+"' and pay_date <= '"+end+"'";
		}
		else
		{
			query ="select sum(interestAmount) as interest,sum(amount) as total from loanpayment where receipt_status='approved' and chequeStatus='cleared' and pay_date <= '"+end+"'";
		}
	//	// // // //System.out.println(query);
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
             Statement stt=conn.createStatement();
		     ResultSet rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return (rs.getDouble("total")-rs.getDouble("interest"));
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0.0;
	}
	public double totalFdrInterestAmountFromFdrIncomeTable(int branchId,Date startDate,Date endDate,Connection conn) 
	{
		Timestamp start=new Timestamp(startDate.getTime());
		Timestamp end=new Timestamp(endDate.getTime());
		Statement stt=null;
		 ResultSet rs=null;
		try
		{
             stt=conn.createStatement();
		     String query="select sum(amount) as totalAmount,sum(old_amount) as totalOldAmount from fixed_deposit_income where chequeStatus='cleared' and date>='"+start+"' and date <= '"+end+"'";	
		    rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return (rs.getDouble("totalAmount")-rs.getDouble("totalOldAmount"));
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	public double totalOtherIncomeAmount(int branchId,Date startDate, Date endDate, Connection conn)
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
	    Statement stt=null;
	    ResultSet rs=null;
		try
		{
           stt=conn.createStatement();
		     String query="select sum(amount) as totalAmount from income_table where chequeStatus='cleared' and category='Other_Cr' and status='active' and income_date>='"+sDate+"' and income_date <= '"+eDate+"'";
		    rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	public double totalOtherExpenseAmount(int branchId,Date startDate, Date endDate, Connection conn) 
	{
		Timestamp start=new Timestamp(startDate.getTime());
		Timestamp end=new Timestamp(endDate.getTime());
		Statement stt=null;
		 ResultSet rs=null;
		try 
		{
             stt=conn.createStatement();
		     String query="select sum(amount) as totalAmount from expense_table where chequeStatus='cleared' and category='Other_Dr' and status='active' and "
		     		+ "expense_date >='"+start+"' and expense_date <= '"+end+"'";	
		    // // //System.out.println(query);
		    rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	public ArrayList<UserInfo> returnedRdAmountList(int branchId,Date startDate, Date endDate, String depositType, Connection conn)
	{
		ArrayList<UserInfo> list=new ArrayList<>();
		Timestamp start=new Timestamp(startDate.getTime());
		Timestamp end=new Timestamp(endDate.getTime());
		Statement st=null;
		ResultSet rs=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from returned_amount_info where chequeStatus='cleared' and  date>= '"+start+"' and date <= '"+end+"' ";
			rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rs.next())
			{
				UserInfo uu=new UserInfo();
				
				uu.setUser_no(rs.getString("user_no"));
				uu.setAmount(rs.getDouble("maturity_value"));
				String dpt=depositTypeByDepositNo(rs.getString("user_no"));
				if(dpt.equalsIgnoreCase(depositType))
				{
					list.add(uu);
				}
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}
	
	public String depositTypeByDepositNo(String userNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select scheme_type from customer_info where user_no='"+userNo+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("scheme_type");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}

	public double paidAmountForRdList(Date startDate,Date endDate, String user_no, Connection conn) 
	{
		Timestamp start=new Timestamp(startDate.getTime());
		Timestamp end=new Timestamp(endDate.getTime());
		Statement st=null;
		ResultSet rs=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount) as totalAmount from payment_receipt where user_no='"+user_no+"' and chequeStatus='cleared' and receipt_status='approved' and date <= '"+end+"'";
			rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getDouble("totalAmount");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return 0.0;
	}
	
	public double paidAmountForRdList1(Date startDate,Date endDate, String user_no, int branchId, Connection conn) 
	{
		Timestamp start=new Timestamp(startDate.getTime());
		Timestamp end=new Timestamp(endDate.getTime());
		Statement st=null;
		ResultSet rs=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount) as totalAmount from payment_receipt where user_no='"+user_no+"' and chequeStatus='cleared' and receipt_status='approved' and date <= '"+end+"'";
			rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rs.next())
			{
				return rs.getDouble("totalAmount");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return 0.0;
	}
	
	public ArrayList<UserInfo> returnedFdAmountList(int branchId,Date startDate, Date endDate)
	{
		ArrayList<UserInfo> list=new ArrayList<>();
		Timestamp start=new Timestamp(startDate.getTime());
		Timestamp end=new Timestamp(endDate.getTime());
		
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select * from returned_amount_info where user_no like 'GF-%' and chequeStatus='cleared' and date <= '"+end+"'";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rs.next())
			{
				UserInfo uu=new UserInfo();
				
				uu.setUser_no(rs.getString("user_no"));
				uu.setAmount(rs.getDouble("maturity_value"));
				
				list.add(uu);
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	
	public double paidAmountForFdList(Date startDate,
			Date endDate, String user_no) 
	{
		Timestamp start=new Timestamp(startDate.getTime());
		Timestamp end=new Timestamp(endDate.getTime());

		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select sum(amount) as totalAmount from payment_receipt where user_no='"+user_no+"' and receipt_status='approved' and chequeStatus='cleared' and date <= '"+end+"'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getDouble("totalAmount");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return 0.0;
	}
	
	public double paidAmountForFdList1(Date startDate, Date endDate, String user_no , int branchId) 
	{
		Timestamp start=new Timestamp(startDate.getTime());
		Timestamp end=new Timestamp(endDate.getTime());

		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select sum(amount) as totalAmount from payment_receipt where user_no='"+user_no+"' and receipt_status='approved' and chequeStatus='cleared' and date <= '"+end+"'";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rs.next())
			{
				return rs.getDouble("totalAmount");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return 0.0;
	}
	
	public int deleteSavingsAccount(String id, String status)
	{
		int i=0;
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="update savingaccount set accountStatus='"+status+"' where id='"+id+"'";
			//// //System.out.println(qq);
			i=st.executeUpdate(qq);
			if(i>0)
			{
				dataInsertInQueryTable(qq, con);
			} 
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}
	
	public Date checkAccountOpeningDate(String accno) 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select * from savingaccount where accountNo='"+accno+"'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getDate("openDate");
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return null;
	}
	public void updateCompanyCapital(int branchId,String fileCharge, String oldFilecharge, double capital) 
	{
		double flchrg=0,oflchrg=0;
		if(fileCharge==null||fileCharge.equals(""))
		{
			flchrg=0;
		}
		else
		{
			flchrg=Double.valueOf(fileCharge);
		}
		
		if(oldFilecharge==null||oldFilecharge.equals(""))
		{
			oflchrg=0;
		}
		else
		{
			oflchrg=Double.valueOf(oldFilecharge);
		}
		
		double updateAmount=(capital-oflchrg)+flchrg;
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="update company_shares set company_capital_amount='"+updateAmount+"'";
		int i=	st.executeUpdate(selectQueWithBranch(qq,branchId));
		if(i>0){	
		//dataInsertInQueryTable(qq, con);
		}}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}
	public void updateStatusForIncomeTable(int branchId,String item, String category) 
	{
		try(Connection connection=DataBaseConnection.JAVAConnection();)
		{
			Statement st=connection.createStatement();
			String qq="update expense_table set status='active' where item='"+item+"' and category='"+category+"'";
		int i=	st.executeUpdate(selectQueWithBranch(qq,branchId));
			if(i>0){
			dataInsertInQueryTable(qq, connection);
		}}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}
	
	public double totalReturnedFDAmount(int branchId,Date startDate, Date endDate) 
	{
		Timestamp start=new Timestamp(startDate.getTime());
		Timestamp end=new Timestamp(endDate.getTime());
		
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select sum(maturity_value) as totalAmount from returned_amount_info where user_no like 'GF-%' and chequeStatus='cleared' and date >= '"+start+"' and date <= '"+end+"'";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rs.next())
			{
				return	rs.getDouble("totalAmount");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public double totalReturnedRDAmount(int branchId,Date startDate, Date endDate) 
	{
		Timestamp start=new Timestamp(startDate.getTime());
		Timestamp end=new Timestamp(endDate.getTime());
		
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select sum(maturity_value) as totalAmount from returned_amount_info where user_no like 'GR-%' and chequeStatus='cleared' and date >= '"+start+"' and date <= '"+end+"'";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rs.next())
			{
				return	rs.getDouble("totalAmount");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public double totalInterestForDiscount(double loanAmount, double duration,
			double interst, int frequency, double emiPayment)
	{
		double finalTotal=0;
		ArrayList<LoanInfo> list = new ArrayList<LoanInfo>();
		
				int terms = (int) duration;
				double emi=emiPayment;
				double discount=0;
				double interstRate=interst;
				double fr=(double) frequency;
				for (int i = 1; i<= terms; i++) 
				{
					LoanInfo ll=new LoanInfo();
					int j=365/frequency;
					ll.setSno(i);
					if(i==terms)
					{
						emi=emi-discount;
						ll.setInstallAmount(emi);
					}
					else
					{
						ll.setInstallAmount(emi);
					}
	
					double frstIntrstAmnt=(loanAmount*interstRate)/(100.00 * fr);
					ll.setInterestAmount(df.format((frstIntrstAmnt)));
					
					double paidPrincipalAmnt=emi-(frstIntrstAmnt);
					ll.setPrincipalAmount(df.format(paidPrincipalAmnt));
					
					
					double principalRemaining=loanAmount-paidPrincipalAmnt;
					
					list.add(ll);
					loanAmount=principalRemaining;
		}
		
		
		for(LoanInfo oo : list)
		{
			finalTotal+=Double.valueOf(oo.getInterestAmount());
		}
		
		return finalTotal;
	}

	public int updateCategoryInExpenseTable(String incomeId,
			String expenseCategory) 
	{
		int i=0;
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="update expense_table set category='"+expenseCategory+"' where id='"+incomeId+"'";
			i=st.executeUpdate(qq);
			if(i>0){
			dataInsertInQueryTable(qq, con);
		} }
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return i;
	}

	public int addPlan(int branchId,String type, String plan, String interest, double penaltyAnnual, String penaltyBasis, double fileCharge, double insuranceFee, 
			int loanAmount, int terms, int emi, int frequency, String emiType, double processingChargePlan) 
	{
		int i=0;
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			
			String qq="insert into plans(type,plan,interest, penalty_annual, penalty_basis, file_charge_plan, insurance_fee_plan, branch_id, loan_amount, terms, emi, frequency, emi_type, processing_charge_plan)"
					+ " values('"+type+"','"+plan+"','"+interest+"', '"+penaltyAnnual+"', '"+penaltyBasis+"', '"+fileCharge+"', '"+insuranceFee+"','"+branchId+"', "
							+ ""+loanAmount+","+terms+", "+emi+", "+frequency+", '"+emiType+"','"+processingChargePlan+"')";
			//System.out.println(qq);
			i=st.executeUpdate(qq);
			if(i>0){
			dataInsertInQueryTable(qq, con);}
			ResultSet ss=st.getGeneratedKeys();
			if(ss.next())
			{
				//// // // //System.out.println("heloo id "+ss.getInt(1)); 
				i=ss.getInt(1);
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return i;
	}

	public double interestByPlanNo(String plan_no)
	{
		double i=0;
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select * from plans where idplans='"+plan_no+"'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getDouble("interest");
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return i;
	}

	public int registerEmployee(String name, String fname, Date dob, Date doj,
			String address, String mobile, String center, String uname,
			String pwd, double leave, double salary, String paddress, String altContactNo, String nickName, String emailId, String gender, String maritalStatus,
			String bloodGroup, String category, String religion, String department, String designation, String pinCode, String city, String panCard, String dlNo, 
			String aadharCard, String voterId, String passport, String rationCard, String tenth, String twelveth, String graduation, String other, Date anniversaryDate, 
			String code, int branchId, int backDays, String bankName, String bankAccountNo, String bankBranch, String bankIfsc, String pfAcc, String uan, boolean cibilCheck , String esic) 
	{
		int i=0;
		Timestamp tt=null;
		if(anniversaryDate!=null)
		{
			tt=new Timestamp(anniversaryDate.getTime());
		}
		
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="insert into employee(name, fname, dob, doj, address, mobile, center, uname, pwd, leave_allowed, salary, p_address, alt_contact_no,nick_name, "
					+ "email_id, gender, marital_status, blood_group, category, religion, department, designation, pin_code, city, pan_card, dl_no, aadhar_card, voter_id, "
					+ "passport, ration_card, tenth, twelveth, graduation, other, anniversary_date,dsacode,branch_id,entry_back_days,bank_name,bank_account_no,bank_branch,"
					+ "bank_ifsc,pf_acc,uan,cibil_check,esic)"
					+ " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			
			
			PreparedStatement st1 = con.prepareStatement(qq);
			st1.setString(1, name.toUpperCase());
			st1.setString(2, fname.toUpperCase());
			st1.setTimestamp(3, new Timestamp(dob.getTime()));
			st1.setTimestamp(4, new Timestamp(doj.getTime()));
			st1.setString(5, address.toUpperCase());
			st1.setString(6, mobile);
			st1.setString(7, center);
			st1.setString(8, uname);
			st1.setString(9, pwd);
			st1.setDouble(10, leave);
			st1.setDouble(11, salary);
			st1.setString(12, paddress.toUpperCase());
			st1.setString(13, altContactNo);
			st1.setString(14,nickName.toUpperCase());
			st1.setString(15,emailId);
			st1.setString(16,gender);
			st1.setString(17, maritalStatus);
			st1.setString(18, bloodGroup);
			st1.setString(19, category);
			st1.setString(20, religion);
			st1.setString(21, department);
			st1.setString(22, designation);
			st1.setString(23, pinCode);
			st1.setString(24, city);
			st1.setString(25, panCard);
			st1.setString(26, dlNo);
			st1.setString(27, aadharCard);
			st1.setString(28, voterId.toUpperCase());
			st1.setString(29, passport);
			st1.setString(30, rationCard);
			st1.setString(31, tenth);
			st1.setString(32, twelveth);
			st1.setString(33, graduation);
			st1.setString(34, other);
			st1.setTimestamp(35, tt);
			st1.setString(36, code);
			st1.setInt(37, branchId);
			st1.setInt(38, backDays);
			st1.setString(39, bankName);
			st1.setString(40, bankAccountNo);
			st1.setString(41, bankBranch);
			st1.setString(42, bankIfsc);
			st1.setString(43, pfAcc);
			st1.setString(44, uan);
			st1.setBoolean(45, cibilCheck);
			st1.setString(46, esic);
			
			i=st1.executeUpdate();
			if(i>0){
			dataInsertInQueryTable(qq, con);
		} }
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}

		return i;
	}

	public void insertEmployeeInLogin(String uname, String pwd, String type, String mobile, int branchId, Connection conn)
	{
		Statement st=null;
		try
		{
		 st=conn.createStatement();
			String qq="insert into login(userid,password,type, mobile_no,branch_id) values('"+uname+"','"+pwd+"','"+type+"','"+mobile+"','"+branchId+"')";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
			    String userId = branchUserId(uname, pwd, conn);
			   insertBranchEmp(userId,branchId,conn);
			   dataInsertInQueryTable(qq, conn);
		}   }
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}

		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
	public void insertBranchEmp(String uname, int branchId, Connection conn)
	{
		Statement st=null;
		String branchName = branchNameByBranchId(branchId,conn);
		try
		{
		    st=conn.createStatement();
			String qq="insert into branch_allocate_table(branch_id,branch_name,user_id, status) values('"+branchId+"','"+branchName+"','"+uname+"','active')";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
			   //insertBranchEmp(uname,branchId,conn);
			   dataInsertInQueryTable(qq, conn);
		}   }
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}

		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	
		
	}


	public String branchNameByBranchId(int branchId, Connection conn) 
	{
        Statement st = null; ResultSet rs =null;
		double i=0;
		try
		{
			st=conn.createStatement();
			String qq="select branch_name from firm_detail where id='"+branchId+"'";
			rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getString("branch_name");
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally {
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	
	}
	
	public int branchIdByBranchName(String branchName, Connection conn) 
	{
        Statement st = null; ResultSet rs =null;
		double i=0;
		try
		{
			st=conn.createStatement();
			String qq="select id from firm_detail where branch_name='"+branchName+"'";
			//System.out.println(qq);
			rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getInt("id");
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally {
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	
	}


	public void updateContactInLoginTable(String uname, String mobile, Connection conn)
	{
		Statement st=null;
		try
		{
		 st=conn.createStatement();
			String qq="update login set mobile_no='"+mobile+"' where userid='"+uname+"' ";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
				dataInsertInQueryTable(qq, conn);
			} 
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}

		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}


	public ArrayList<EmpInfo> allEmpInfo(int branchId,String empStatus, Connection conn)
	{
		
		System.out.println("branchId in empInfo is:"+branchId );
		int i=1;
		ArrayList<EmpInfo> list=new ArrayList<>();
		Timestamp st=null;
		Timestamp en=null;
		Statement stt=null;
		ResultSet rr=null;
		
		String qq="select * from employee where status='"+empStatus+"'  ";
	    
		if(branchId!=-1)
		{ 
			qq+=" and branch_id="+branchId+" ";
		}
		
		System.out.println(qq);
		try
		{   
			stt=conn.createStatement();
			ResultSet rs=stt.executeQuery(qq);;
			while(rs.next())
			{
				EmpInfo uu = new EmpInfo();
				uu = empInfoById(rs);
				uu.setSno(i++);

				list.add(uu);
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public String bNameById(int branchId) {
		
		String branchName="";
		
		try(Connection conn = DataBaseConnection.JAVAConnection()){

			String qq="select branch_name from firm_detail where id='"+branchId+"'";
		
			try(PreparedStatement ps = conn.prepareStatement(qq)){
				
				ResultSet rr = ps.executeQuery();
				
				while(rr.next()) {
					
					branchName= rr.getString("branch_name");
					
				}
				
			}catch(Exception e) {
			
				e.printStackTrace();
			 	
			}
			
			
		}
		catch(Exception e)
		{
			
			e.printStackTrace();
			
		}
		
		return branchName;
		
	}
	
	public EmpInfo empInfoById(ResultSet rs) 
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		EmpInfo uu = new EmpInfo();
		try 
		{
			uu.setId(rs.getString("id"));
			uu.setDoj(rs.getDate("doj"));
			uu.setStrDoj(sf.format(rs.getDate("doj")));
			uu.setName(rs.getString("name"));
			uu.setDob(rs.getDate("dob"));
			uu.setStrDob(sf.format(rs.getDate("dob")));
			uu.setFname(rs.getString("fname"));
			uu.setUname(rs.getString("uname"));
			uu.setStatus(rs.getString("status"));
			uu.setPwd(rs.getString("pwd"));
			uu.setCenter(rs.getString("center"));
			uu.setAddress(rs.getString("address"));
			uu.setMobile(rs.getString("mobile"));
			uu.setSalary(rs.getDouble("salary"));
			uu.setLeaves(rs.getDouble("leave_allowed"));
			uu.setAltContactNo(rs.getString("alt_contact_no"));
			uu.setpAddress(rs.getString("p_address"));
			uu.setNickName(rs.getString("nick_name"));
			uu.setEmailId(rs.getString("email_id"));
			uu.setGender(rs.getString("gender"));
			uu.setMaritalStatusId(rs.getString("marital_status"));
			uu.setMaritalStatus(hrmBasicNameById(rs.getString("marital_status"),conn));
			
			uu.setBloodGroupId(rs.getString("blood_group"));
			uu.setBloodGroup(hrmBasicNameById(rs.getString("blood_group"),conn));
			
			uu.setCategoryId(rs.getString("category"));
			uu.setCategory(hrmBasicNameById(rs.getString("category"),conn));
			
			uu.setReligionId(rs.getString("religion"));
			uu.setReligion(hrmBasicNameById(rs.getString("religion"),conn));
			
			uu.setDepartmentId(rs.getString("department"));
			uu.setDepartment(hrmBasicNameById(rs.getString("department"),conn));
			
			uu.setDesignationId(rs.getString("designation"));
			uu.setDesignation(hrmBasicNameById(rs.getString("designation"),conn));
			
			uu.setPinCode(rs.getString("pin_code"));
			uu.setCity(rs.getString("city"));
			uu.setPanCard(rs.getString("pan_card"));
			uu.setDlNo(rs.getString("dl_no"));
			uu.setAadharCard(rs.getString("aadhar_card"));
			uu.setVoterId(rs.getString("voter_id"));
			uu.setPassport(rs.getString("passport"));
			uu.setRationCard(rs.getString("ration_card"));
			uu.setTenth(rs.getString("tenth"));
			uu.setTwelveth(rs.getString("twelveth"));
			uu.setGraduation(rs.getString("graduation"));
			uu.setOther(rs.getString("other"));
			uu.setCibilCheck(rs.getBoolean("cibil_check"));
			uu.setInactiveDate(rs.getDate("inactive_date"));
			uu.setInactiveDescription(rs.getString("inactive_description"));
			
			uu.setTransferDate(rs.getString("transfer_date"));
			
			if(rs.getDate("anniversary_date")!=null)
			{
				uu.setAnniversaryDateStr(sf.format(rs.getDate("anniversary_date")));
				uu.setAnniversaryDate(rs.getDate("anniversary_date"));
			}
			
			if(rs.getString("center").equals("0"))
			{
				uu.setCenterName("All");
			}
			else
			{
				uu.setCenterName(centerNameById(rs.getString("center"),conn));
			}
			

			uu.setDsaCode(rs.getString("dsacode"));
			System.out.println("emp code is:"+rs.getString("dsacode"));
			filePathDetail(conn);  //for set online view path if exist
			if(onlineFileViewPath==null || onlineFileViewPath.trim().equals(""))
			{
				uu.setPanCardPath(rs.getString("pan_card_photo"));
				uu.setDlNoPath(rs.getString("dl_no_photo"));
				uu.setAadharCardPath(rs.getString("aadhar_card_photo"));
				uu.setVoterIdPath(rs.getString("voter_id_photo"));
				uu.setPassportPath(rs.getString("passport_photo"));
				uu.setRationCardPath(rs.getString("ration_card_photo")); 
				uu.setTenthPath(rs.getString("tenth_photo"));
				uu.setTwelvethPath(rs.getString("twelveth_photo"));
				uu.setGraduationPath(rs.getString("graduation_photo")); 
				uu.setOtherPath(rs.getString("other_photo"));
			}
			else
			{
				uu.setPanCardPath(onlineFileViewPath+rs.getString("pan_card_photo"));
				uu.setDlNoPath(onlineFileViewPath+rs.getString("dl_no_photo"));
				uu.setAadharCardPath(onlineFileViewPath+rs.getString("aadhar_card_photo"));
				uu.setVoterIdPath(onlineFileViewPath+rs.getString("voter_id_photo"));
				uu.setPassportPath(onlineFileViewPath+rs.getString("passport_photo"));
				uu.setRationCardPath(onlineFileViewPath+rs.getString("ration_card_photo")); 
				uu.setTenthPath(onlineFileViewPath+rs.getString("tenth_photo"));
				uu.setTwelvethPath(onlineFileViewPath+rs.getString("twelveth_photo"));
				uu.setGraduationPath(onlineFileViewPath+rs.getString("graduation_photo")); 
				uu.setOtherPath(onlineFileViewPath+rs.getString("other_photo"));
			}
			
			uu.setPanCardPathForEdit(rs.getString("pan_card_photo"));
			uu.setDlNoPathForEdit(rs.getString("dl_no_photo"));
			uu.setAadharCardPathForEdit(rs.getString("aadhar_card_photo"));
			uu.setVoterIdPathForEdit(rs.getString("voter_id_photo"));
			uu.setPassportPathForEdit(rs.getString("passport_photo"));
			uu.setRationCardPathForEdit(rs.getString("ration_card_photo")); 
			uu.setTenthPathForEdit(rs.getString("tenth_photo"));
			uu.setTwelvethPathForEdit(rs.getString("twelveth_photo"));
			uu.setGraduationPathForEdit(rs.getString("graduation_photo")); 
			uu.setOtherPathForEdit(rs.getString("other_photo"));
			DbYashwant dby =new DbYashwant();
			uu.setDsaCode(dby.manageEmployeeId(rs.getString("dsacode")));
			uu.setBackDays(rs.getInt("entry_back_days"));
			uu.setBankName(rs.getString("bank_name"));
			uu.setBankAccountNo(rs.getString("bank_account_no"));
			uu.setBankBranch(rs.getString("bank_branch"));
			uu.setBankIfsc(rs.getString("bank_ifsc"));
			uu.setPfAcc(rs.getString("pf_acc"));
			uu.setUan(rs.getString("uan"));
			uu.setBranchId(rs.getInt("branch_id"));
		} 
		catch (SQLException e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return uu;
	}
	
	public String hrmBasicNameById(String id, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			 String qq="select name from hrm_basic where id='"+id+"' ";
			 rr=st.executeQuery(qq);
			 if(rr.next())
			 {
				 return rr.getString("name");
			 }
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}

	public EmployeeInfo employeeInfoById(ResultSet rs) 
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		EmployeeInfo uu = new EmployeeInfo();
		try 
		{
			uu.setId(rs.getString("id"));
			uu.setDoj(rs.getDate("doj"));
			uu.setStrDoj(sf.format(rs.getDate("doj")));
			uu.setName(rs.getString("name"));
			uu.setDob(rs.getDate("dob"));
			uu.setStrDob(sf.format(rs.getDate("dob")));
			uu.setFname(rs.getString("fname"));
			uu.setUname(rs.getString("uname"));
			uu.setUserName(rs.getString("uname"));
			uu.setTransferDate(rs.getString("transfer_date"));
			uu.setStatus(rs.getString("status"));
			uu.setPwd(rs.getString("pwd"));
			uu.setCenter(rs.getString("center"));
			uu.setAddress(rs.getString("address"));
			uu.setMobile(rs.getString("mobile"));
			uu.setSalary(rs.getDouble("salary"));
			uu.setTotalLeave(rs.getDouble("leave_allowed"));
			
			if(rs.getString("center").equals("0"))
			{
				uu.setCenterName("All");
			}
			else
			{
				uu.setCenterName(centerNameById(rs.getString("center"),conn));
			}
			
			uu.setBankName(rs.getString("bank_name"));
			uu.setBankAccountNo(rs.getString("bank_account_no"));
			uu.setBankBranch(rs.getString("bank_branch"));
			uu.setBankIfsc(rs.getString("bank_ifsc"));
			uu.setPfAcc(rs.getString("pf_acc"));
			uu.setUan(rs.getString("uan"));
			uu.setPanCard(rs.getString("pan_card"));
			uu.setAadharCard(rs.getString("aadhar_card"));	
		} 
		catch (SQLException e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return uu;
	}
	
	public ArrayList<SelectItem> employeeList(int branchId,Connection conn)
	{
		ArrayList<SelectItem> list=new ArrayList<>();

		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			String query="select * from employee where status='active' ";
			 rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				SelectItem ll=new SelectItem();
				
				ll.setLabel(rr.getString("name")); //piyush
				ll.setValue(rr.getString("uname"));
				
				list.add(ll);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}
	
	public String centerNameById(String id, Connection conn)
	{Statement st=null;
	ResultSet rs=null;
	try
	{
		st=conn.createStatement();
		String qq="select * from center where id='"+id+"'";
		//// // // //System.out.println(qq);
		rs=st.executeQuery(qq);
		if(rs.next())
		{
			return (rs.getString("centerCode")+"/"+rs.getString("centerName"));
			//return (rs.getString("centerCode"));
		}
	} 
	catch (Exception e)
	{
		 e.printStackTrace();fileCreation(e.getMessage());
	}
	finally
	{
		try {
			if(st!=null)
			{
				st.close();
			}
			if(rs!=null)
			{
				rs.close();
			}
			
		} catch (Exception e2) {
			// TODO: handle exception
		}
	}
	return "";}
	
	public String centerNameByCenterId(String id, Connection conn)
	{
		Statement st=null;
		ResultSet rs=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from center where id='"+id+"'";
			//// // // //System.out.println(qq);
			rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getString("centerName");
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}
	
	public String centerCodeByCenterId(String id, Connection conn)
	{
		Statement st=null;
		ResultSet rs=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from center where id='"+id+"'";
			//// // // //System.out.println(qq);
			rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getString("centerCode");
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}

	public int updateEmployee(String name, String fname, Date dob, Date doj,String address, String mobile, String center, String id, double leave, double salary, 
			String pAddress, String altContactNo, String nickName, String emailId, String gender, String maritalStatus, String bloodGroup, String category, 
			String religion, String department, String designation, String pinCode, String city, String panCard, String dlNo, String aadharCard, String voterId, 
			String passport, String rationCard, String tenth, String twelveth, String graduation, String other, Date anniversaryDate, int backDays, String bankName,
			String bankAccountNo, String bankBranch, String bankIfsc, String pfAcc, String uan, boolean cibilCheck)
	{
		Timestamp db=new Timestamp(dob.getTime());
		Timestamp dj=new Timestamp(doj.getTime());
		Timestamp tt=null;
		if(anniversaryDate!=null)
		{
			tt=new Timestamp(anniversaryDate.getTime());
		}
		
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
	         Statement stt=conn.createStatement();
		     String query="update employee set name=?, fname=?, dob=?,doj=?, address=?, mobile=?, center=?,leave_allowed=?,salary=?, p_address=?"
		     				+ " , alt_contact_no=?, nick_name=?, email_id=?, gender=?,marital_status=?, blood_group=?, category=?, religion=?,department=?, designation=?,"
		     				+ " pin_code=?, city=?, pan_card=?, dl_no=?, aadhar_card=?, voter_id=?,passport=?, ration_card=?, tenth=?, twelveth=?,graduation=?, other=?,"
		     				+ " anniversary_date=?, entry_back_days=?, bank_name=?, bank_account_no=?, bank_branch=?, bank_ifsc=?, pf_acc=?, uan=? ,cibil_check=? where id='"+id+"'";	
		     
		 	PreparedStatement st1 = conn.prepareStatement(query);
			st1.setString(1, name);
			st1.setString(2, fname);
			st1.setTimestamp(3, db);
			st1.setTimestamp(4, dj);
			st1.setString(5, address);
			st1.setString(6, mobile);
			st1.setString(7, center);
			st1.setDouble(8, leave);
			st1.setDouble(9, salary);
			st1.setString(10, pAddress);
			st1.setString(11, altContactNo);
			st1.setString(12,nickName);
			st1.setString(13,emailId);
			st1.setString(14,gender);
			st1.setString(15, maritalStatus);
			st1.setString(16, bloodGroup);
			st1.setString(17, category);
			st1.setString(18, religion);
			st1.setString(19, department);
			st1.setString(20, designation);
			st1.setString(21, pinCode);
			st1.setString(22, city);
			st1.setString(23, panCard);
			st1.setString(24, dlNo);
			st1.setString(25, aadharCard);
			st1.setString(26, voterId);
			st1.setString(27, passport);
			st1.setString(28, rationCard);
			st1.setString(29, tenth);
			st1.setString(30, twelveth);
			st1.setString(31, graduation);
			st1.setString(32, other);
			st1.setTimestamp(33, tt);
			st1.setInt(34, backDays);
			st1.setString(35, bankName);
			st1.setString(36, bankAccountNo);
			st1.setString(37, bankBranch);
			st1.setString(38, bankIfsc);
			st1.setString(39, pfAcc);
			st1.setString(40, uan);
			st1.setBoolean(41, cibilCheck);
			
			int i=st1.executeUpdate();
		     if(i==1)
		     {
		    	 dataInsertInQueryTable(query, conn);
		    	return 1;
		     }
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public int deleteEmp(String id, String userId, Connection conn, Date inactiveDate, String inactiveDescription) 
	{
		try
		{
			Timestamp tt=new Timestamp(inactiveDate.getTime());
	         Statement stt=conn.createStatement();
		     String query="update employee set status='inactive', inactive_date='"+tt+"', inactive_description='"+inactiveDescription+"' where id='"+id+"' ";	
		     int i=stt.executeUpdate(query);
		     
		     if(i==1)
		     {
		    	 dataInsertInQueryTable(query, conn);
		    	 updateLoginStatusByUserId(userId, "inactive");
		    	 return 1;
		     }
		     
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}

		return 0;
	}  

	public int updatePassword(String userId,String password,String newPass) 
	{
		int i=0;
		if(userId!=null && !userId.trim().equalsIgnoreCase("") && password!=null && !password.trim().equalsIgnoreCase("") &&
				newPass!=null && !newPass.trim().equalsIgnoreCase(""))
		{
			try(Connection conn=DataBaseConnection.JAVAConnection())
			{
				Statement st=conn.createStatement();
				String query="select * from login where userid='"+userId+"' and password='"+password+"'";
				ResultSet rr=st.executeQuery(query);
				if(rr.next())
				{
					query="update login set password='"+newPass+"' where userid='"+userId+"'";
					i=st.executeUpdate(query);
					if(i>0){
					dataInsertInQueryTable(query, conn);
				}}
				else
				{
					i=-1;
				}
			}
			catch(Exception e)
			{
				 e.printStackTrace();fileCreation(e.getMessage());
			}
		}
		
		return i;
	}

	
	public void updatePasswordInEmployeeTable(String userId, String newPass)
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="update employee set pwd='"+newPass+"' where uname='"+userId+"'";
			int i=st.executeUpdate(query);
			if(i>0){
			dataInsertInQueryTable(query, conn);
		}}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}

	public void sendLoginMessageToAdmin(int branchId,String userId) throws UnsupportedEncodingException 
	{
		Date dt=new Date();
		Timestamp ldt=new Timestamp(dt.getTime());
		String name=employeeNameByUsername(userId);
		String cnt="9461030604";  //MOBILE NO. OF SUBHASH JI//
		String message="Hello Admin! Employee : "+name+" has started working. Login date and time : "+ldt;
	//	// // // //System.out.println("bef : "+message);
		message=URLEncoder.encode(message,"UTF-8");
	//	// // // //System.out.println("aftr : "+message);
		/*String url="http://sms.bulksmsserviceproviders.com/api/send_http.php?authkey=9e9aea370d1557654c04fd3de4092631&mobiles="+cnt+"&message="+message+"&sender=bachpn&route=B";
		try 
		{
		    URL myURL = new URL(url);
		    myURL.openStream();
		} 
		catch (Exception e) 
		{   
			 e.printStackTrace();fileCreation(e.getMessage());
		}*/
		
		//API is of bachpan school...need to be changed
	}

	public String employeeNameByUsername(String userId)
	{
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select name from employee where uname='"+userId+"'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getString("name");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}

	
	public ArrayList<TrialInfo> trialBalanceOtherExpense(int branchId,Date startDate, Date endDate, Connection conn) 
	{
		ArrayList<TrialInfo> list=new ArrayList<>();
		
		TrialInfo tt1=new TrialInfo();
		tt1.setParticular("Depreciation");
		tt1.setCredit(0);
		double amt1=totalDepreciationOnFaYearWise(branchId,endDate.getYear());
		tt1.setDebit(amt1);
		list.add(tt1);
		Statement st=null;ResultSet rr=null;
		boolean chk=true;
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		
		
		try
		{
			 st=conn.createStatement();
			String qq="select * from group_head where group_head_type='Expense' ";
			rr=st.executeQuery(qq);
			while(rr.next())
			{
				TrialInfo tt=new TrialInfo();
				
				//if(chk==true)
				{
					tt.setCategory("Expense (Indirect)");
					chk=false;
				}
				tt.setOpeningDr(openingExpenseAmount(branchId,rr.getString("group_head_name"), sDate, conn));
				tt.setParticular(rr.getString("group_head_name"));
				tt.setCredit(0);
				double amt=otherExpenseAmount(rr.getString("group_head_name"), sDate, eDate,branchId);
				tt.setDebit(amt);
			
				list.add(tt);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}
		return list;
	}

	private double totalDepreciationOnFaYearWise(int branchId,int year) 
	{	
		year+=1900;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(dep_value) from depreciation where dep_year='"+year+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(dep_value)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}



	private double otherFixedAssetsExpenseAmount(int branchId,String string, String sDate, String eDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from expense_table where item='"+string+"' and expense_date>='"+sDate+"' and expense_date<='"+eDate+"' and category='Fixed_Asset_Dr' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
			   return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	

	private double otherFixedAssetsIncomeAmount(int branchId,String string, String sDate, String eDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from income_table where item='"+string+"' and income_date>='"+sDate+"' and income_date<='"+eDate+"' and category='Fixed_Asset_Cr' ";
		//	// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
			   return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	
	public ArrayList<TrialInfo> trialBalanceCapital(int branchId,Date startDate, Date endDate) 
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		double shareAmount=extractCompanyShareAmount(conn);
		double totalShares=extractTotalShares();
		double shareCapital=shareAmount*totalShares;
		
		
		ArrayList<TrialInfo> list=new ArrayList<>();
		
		TrialInfo tt=new TrialInfo();
		
		tt.setCategory("Share Capital");
		tt.setParticular("Share Capital");
		tt.setCredit(shareCapital);
		tt.setDebit(0);
		list.add(tt);

		return list;
	}	

	public double closingCashInBalance(int branchId,String sDate, Connection conn, String searchReport) 
	{
		DataBaseReportMethods dbmr=new DataBaseReportMethods();
		String bankName="N/A";
		double totalIn = 0;
		HeaderBean hh=new HeaderBean();
		String ssDate="";
		if(searchReport.equalsIgnoreCase("TB"))
		{
			ssDate="2010-04-01";	
		}
		else
		{
			ssDate=hh.getStartFinYear()+"-04-01";
		}
		
		double a=dbmr.loanEmiPaymentForOpeningBalance(branchId,sDate, ssDate,conn);
		
		double b=dbmr.rdPayListForOpeningBalance(branchId,sDate, ssDate,conn);
		
		double c=dbmr.depositPayForOpeningBalance(branchId,sDate, ssDate,conn);
		double h=dbmr.appFeeForOpeningBalance(branchId,sDate, ssDate,conn);
		double i=dbmr.extraIncomeForOpeningBalance(branchId,sDate, ssDate,conn);
		double j=dbmr.fdIncomeForOpeningBalance(branchId,sDate, ssDate,conn);
		double k=dbmr.bankTransferAmountForOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		double l=dbmr.PromotorAmountForOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		double m=dbmr.instantBorrowForOpeningBalance(branchId,sDate, "credit", "cash", ssDate,conn);
		double n=dbmr.instantLoanForOpeningBalance(branchId,sDate, "debit", "cash",ssDate,conn);
		double o=dbmr.odLoanReturnAmountForOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		double trasnCr=dbmr.cashTransferBtDate(branchId, sDate, ssDate,"Cr",conn);
		       
		totalIn=a+b+c+h+i+j+l+m+n+o+trasnCr;
		
		double x=dbmr.bankToBankAmountForOpeningBalance(branchId,sDate, ssDate,conn);
		double z=dbmr.bankToBankTransferForOpeningBalance(branchId,sDate, ssDate,conn);
		
		totalIn+=x+z;
		
		totalIn=Double.parseDouble(df.format(totalIn));
		
		return totalIn;
	}
	

	public double closingCashOutBalance(int branchId,String sDate, Connection conn, String searchReport) 
	{
		DataBaseReportMethods dbmr=new DataBaseReportMethods();
		String bankName="N/A";
		double totalOut=0;
		HeaderBean hh=new HeaderBean();
		String ssDate="";
		if(searchReport.equalsIgnoreCase("TB"))
		{
			ssDate="2010-04-01";	
		}
		else
		{
			ssDate=hh.getStartFinYear()+"-04-01";
		}
		double a=dbmr.loanAmountForOpeningBalance(branchId,sDate, ssDate,conn);
		double b=dbmr.withdrawAmountForOpeningBalance(branchId,sDate, ssDate,conn);
		double c=dbmr.returnAmountForOpeningBalance(branchId,sDate, ssDate,conn);
		double d=dbmr.expenseForOpeningBalance(branchId,sDate, ssDate,conn);
		double e=dbmr.fdExpenseForOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		double f=dbmr.transferAmountForOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		double g=dbmr.returnPromotorAmountForOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		double j=dbmr.returnDSACommForOpeningBalance(branchId,sDate, ssDate,conn);
		double k=dbmr.salaryPayoutForOpeningBalance(branchId,sDate, ssDate,conn);
		double l=dbmr.tdsForOpeningBalance(branchId,sDate, ssDate,conn);
		double s=dbmr.instantBorrowForOpeningBalance(branchId,sDate, "debit", "cash", ssDate,conn);
		double t=dbmr.instantLoanForOpeningBalance(branchId,sDate, "credit", "cash", ssDate,conn);
		double trasnDr=dbmr.cashTransferBtDate(branchId, sDate, ssDate,"Dr",conn);
		totalOut=a+b+c+d+e+f+g+j+k+l+s+t+trasnDr;
		
		double y=dbmr.companyAmountToBankForOpeningBalance(branchId,sDate, ssDate,conn);
		
		totalOut+=y;
		totalOut=Double.parseDouble(df.format(totalOut));
		
		return totalOut;
	}
	
	
	
	

	private double fileChargeOfAllLoan(int branchId,Date startDate, Date endDate) 
	{
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(filecharge) from personalloan where requestDate>='"+sDate+"' and requestDate<'"+eDate+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(filecharge)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	private double intrestReceiveAllLoan(int branchId,Date startDate, Date endDate) 
	{
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(interestAmount) from loanpayment where pay_date>='"+sDate+"' and pay_date<='"+eDate+"' and receipt_status='approved' and chequeStatus='cleared' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(interestAmount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	private double openingIntrestReceiveAllLoan(int branchId,Date startDate) 
	{
		String sDate=sdfForDb.format(startDate.getTime());
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(interestAmount) from loanpayment where pay_date<'"+sDate+"' and receipt_status='approved' and chequeStatus='cleared' ";
		//	// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return  Double.parseDouble(df.format(rr.getDouble("sum(interestAmount)")));
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public ArrayList<TrialInfo> trialBalanceAllLoanPayementAndReceipt(int branchId,Date startDate, Date endDate, Connection conn) 
	{
		boolean chk=true;
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		ArrayList<TrialInfo> list=new ArrayList<>();
		ArrayList<SelectItem> loanList=new ArrayList<>();
		HeaderBean hh=new HeaderBean();
		loanList=hh.getLoanTypeList();
		Statement st=null;ResultSet rr=null;		
		try
		{
			String qq="";
			st=conn.createStatement();
			for(SelectItem ll: loanList)
			{
				if(ll.getValue().equals("grouploan"))
				{
					qq="select sub_loan_no,teamLeader from "+ll.getValue()+" ";
				}
				else
				{
					qq="select loanNo,shareholderno from "+ll.getValue()+" ";
				}
				
				qq+="  where status='Approve' ";
			
				rr=st.executeQuery(selectQueWithBranch(qq,branchId));
				while(rr.next())
				{
					TrialInfo tt=new TrialInfo();
					//if(chk==true)
					{
						tt.setCategory("Loan");
						chk=false;	
					}
					String loanNo="", memberNo="";
					if(ll.getValue().equals("grouploan"))
					{
						loanNo=rr.getString("sub_loan_no");
						memberNo=rr.getString("teamLeader");
					}
					else
					{
						loanNo=rr.getString("loanNo");
						memberNo=rr.getString("shareholderno");
					}
					
					tt.setParticular(loanNo+" / "+firstApplicantNameBySHNo(memberNo,conn));
					double crAmt=creditLoanAmountByLoanNoOpeningBalance(loanNo, sDate);
					double drAmt=debitLoanAmountByLoanNoOpeningBalance(loanNo, sDate);
					tt.setOpeningCr(Math.abs(Double.parseDouble(df.format(crAmt))));
					tt.setOpeningDr(Math.abs(Double.parseDouble(df.format(drAmt))));
					tt.setDebit(Double.parseDouble(df.format(debitLoanAmountByLoanNo(loanNo, sDate, eDate, conn))));
					tt.setCredit(Double.parseDouble(df.format(creditLoanAmountByLoanNo(loanNo, sDate, eDate, conn))));
					
					list.add(tt);
				}
			}	
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}
		return list;
	}

	public double creditLoanAmountByLoanNo(String string, String sDate, String eDate, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount), sum(interestAmount) from loanpayment where loanNo='"+string+"' and pay_date>='"+sDate+"' and pay_date<='"+eDate+"' and chequeStatus='cleared' and receipt_status='approved' ";
		//	// // // //System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
			   return rr.getDouble("sum(amount)")-rr.getDouble("sum(interestAmount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) 
			{
				// TODO: handle exception
		
			}
		}
		return 0;
	}
	
	private double creditOdLoanAmountByLoanNo(String string, String sDate, String eDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(od_return_amount),sum(od_return_interest) from od_loan_return where od_loan_no='"+string+"' and od_return_date>='"+sDate+"' and od_return_date<='"+eDate+"' and status='active' ";
		//	// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
			   return rr.getDouble("sum(od_return_amount)")-rr.getDouble("sum(od_return_interest)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	
	private double creditLoanAmountByLoanNoOpeningBalance(String string, String sDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount), sum(interestAmount) from loanpayment where loanNo='"+string+"' and pay_date<'"+sDate+"' and chequeStatus='cleared' and receipt_status='approved' ";
		//	// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
			   return rr.getDouble("sum(amount)")-rr.getDouble("sum(interestAmount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	private double debitLoanAmountByLoanNo(String string, String sDate, String eDate, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount) from debit_loan where loanNo='"+string+"' and date>='"+sDate+"' and date<='"+eDate+"' and status='cleared'   ";
			//// // // //System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
			   return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) 
			{
				// TODO: handle exception
		
			}
		}
		return 0;
	}
	
	private double debitOdLoanAmountByLoanNo(String string, String sDate, String eDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(od_amount) from od_loan where od_loan_no='"+string+"' and od_date>='"+sDate+"' and od_date<='"+eDate+"'    ";
			//// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
			   return rr.getDouble("sum(od_amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public double odLoanTotalAmount(Connection conn, Date startDate, Date endDate) 
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		try
		{
			Statement st=conn.createStatement();
			String qq="select sum(od_amount) from od_loan where od_date>='"+sDate+"' and od_date<='"+eDate+"'    ";
			//// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
			   return rr.getDouble("sum(od_amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public double odLoanReturnTotalAmount(int branchId,Connection conn, Date startDate, Date endDate) 
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		try
		{
			Statement st=conn.createStatement();
			String qq="select sum(od_return_amount),sum(od_return_interest)  from od_loan_return where od_return_date>='"+sDate+"' and od_return_date<='"+eDate+"'    ";
			//// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
			   return rr.getDouble("sum(od_return_amount)")-rr.getDouble("sum(od_return_interest)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	private double debitLoanAmountByLoanNoOpeningBalance(String string, String sDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from debit_loan where loanNo='"+string+"' and date<='"+sDate+"' and status='cleared' ";
		//	// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
			   return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public ArrayList<TrialInfo> trialBalanceFixedAssetsExpense(int branchId,Date startDate, Date endDate, Connection conn) 
	{
		boolean chk=true;
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		ArrayList<TrialInfo> list=new ArrayList<>();
		Statement st=null;ResultSet rr=null;
		try
		{
		st=conn.createStatement();
			String qq="select * from group_head where group_head_type='Assets' ";
			 rr=st.executeQuery(qq);
			while(rr.next())
			{
				TrialInfo tt=new TrialInfo();
				
				//if(chk==true)
				{
					tt.setCategory("Fixed Assets");
					chk=false;
				}
				
				tt.setOpeningDr(openingBalanceFromTrialBalanceTable(branchId,rr.getString("group_head_name"), "2016-2017", "Fixed Assets"));
				tt.setParticular(rr.getString("group_head_name"));
				// // // //System.out.println(tt.getParticular()+"=========="+tt.getOpeningDr());
				tt.setCredit(otherFixedAssetsIncomeAmount(branchId,rr.getString("group_head_name"), sDate, eDate));
				double amt=otherFixedAssetsExpenseAmount(branchId,rr.getString("group_head_name"), sDate, eDate);
				tt.setDebit(amt);
				
				list.add(tt);
				
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		/*try
		{
			 st=conn.createStatement();
			String qq="select * from expense_table where expense_date>='"+sDate+"' and expense_date<='"+eDate+"' and category='Fixed_Asset_Dr' and chequeStatus='cleared' ";
		//	// // // //System.out.println(qq);
			 rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{	
				TrialInfo tt=new TrialInfo();
				
				if(chk==true)
				{
					tt.setCategory("Fixed Assets");
					chk=false;
				}
				
				tt.setParticular(rr.getString("item"));
				tt.setCredit(calculateDepOnFa(rr.getString("id")));
				tt.setDebit(rr.getDouble("amount"));
				
				list.add(tt);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}*/
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}

		return list;
	}

	

	public ArrayList<TrialInfo> trialBalanceFdRd(int branchId,Date startDate, Date endDate, String string, Connection conn) 
	{
		boolean chk=true;
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		ArrayList<TrialInfo> list=new ArrayList<>();

		Statement st=null;ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			String qq="select * from customer_info where scheme_type='"+string+"' ";
			 rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				TrialInfo tt=new TrialInfo();
				tt.setParticular(rr.getString("user_no")+" / "+firstApplicantNameBySHNo(rr.getString("shareHolderNo"),conn));
				tt.setCategory(string);
				tt.setOpeningDr(Double.parseDouble(df.format(openingReturnRdFdDdAmount(branchId,rr.getString("user_no"), sDate, conn))));
				tt.setOpeningCr(Double.parseDouble(df.format(openingPaidRdFdAmount(branchId,rr.getString("user_no"), sDate, conn))));
				tt.setDebit(Double.parseDouble(df.format(returnRdFdDdAmountBetweenDate(branchId,rr.getString("user_no"), sDate, eDate))));
				tt.setCredit(Double.parseDouble(df.format(paidRdAmountBetweenDate(rr.getString("user_no"), sDate, eDate))));
				
				list.add(tt);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}  finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}

		return list;
	}

	private double openingBalanceFromTrialBalanceTable(int branchId,String accNo, String finYear, String tbHead) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select closing_balance from trial_balance where account_no='"+accNo+"' and financial_year='"+finYear+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("closing_balance");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	private double openingPaidRdFdAmount(int branchId,String particular, String sDate, Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from payment_receipt where date<'"+sDate+"' and user_no='"+particular+"' and receipt_Status='approved' and chequeStatus='cleared' ";
		//	// //System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public double paidRdAmountBetweenDate(String particular, String sDate, String eDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from payment_receipt where date>='"+sDate+"' and date<='"+eDate+"' and receipt_status='approved' and user_no='"+particular+"' and chequeStatus='cleared' and payment_mode!='transfer_saving' ";
		//	// // // //System.out.println("hello: "+qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	
	private double openingReturnRdFdDdAmount(int branchId,String particular, String sDate, Connection conn) 
	{
		String qq="";
		try
		{
			Statement st=conn.createStatement();
			if(particular.equals("all"))
			{
				qq="select sum(maturity_value) from returned_amount_info where date<'"+sDate+"' and chequeStatus='cleared' and paymentMode!='transfer_saving' ";
			}
			else
			{
				qq="select sum(maturity_value) from returned_amount_info where date<'"+sDate+"' and user_no='"+particular+"' and chequeStatus='cleared' and paymentMode!='transfer_saving' ";
			}
			// // //System.out.println("hello: "+qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(maturity_value)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	private double returnRdFdDdAmountBetweenDate(int branchId,String particular, String sDate, String eDate) 
	{
		String qq="";
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(particular.equals("all"))
			{
				qq="select sum(maturity_value) from returned_amount_info where date>='"+sDate+"' and date<='"+eDate+"' and chequeStatus='cleared' and paymentMode!='transfer_saving' ";
			}
			else
			{
				qq="select sum(maturity_value) from returned_amount_info where date>='"+sDate+"' and date<='"+eDate+"' and user_no='"+particular+"' and chequeStatus='cleared' and paymentMode!='transfer_saving' ";
			}
			//// //System.out.println("hello: "+qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				 if(rr.getString("sum(maturity_value)")!=null)
                 {
					 return rr.getDouble("sum(maturity_value)");
                 } 
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	/*public double totalDDRDFDAmountReturnSchemeTypeWise(Date startDate, Date endDate, String schemeType, Connection conn) 
	{
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		Statement st=null, st1=null;
		ResultSet rr=null, rr1=null;
		double amt=0;
		try
		{
			st1=conn.createStatement();
			String qq1="SELECT user_no FROM customer_info where scheme_type='"+schemeType+"' ";
			rr1=st1.executeQuery(qq1);
			while(rr1.next())
			{
				st=conn.createStatement();
				String qq="select sum(maturity_value) from returned_amount_info where date>='"+sDate+"' and date<='"+eDate+"' and user_no='"+rr1.getString("user_no")+"' and chequeStatus='cleared' and paymentMode!='transfer_saving' ";
				rr=st.executeQuery(selectQueWithBranch(qq,branchId));
				if(rr.next())
				{
					amt+=rr.getDouble("sum(maturity_value)");
				}
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return Double.parseDouble(df.format(amt));
	}*/

	
	
	public double totalDDRDFDAmountReturnSchemeTypeWise(int branchId,Date startDate, Date endDate, String schemeType, 
														Connection conn)
    {
        String sDate=sdfForDb.format(startDate);
        String eDate=sdfForDb.format(endDate);
        Statement st=null, st1=null;
        ResultSet rr=null, rr1=null;
        double amt=0;
        
        try
        {
            st1=conn.createStatement();
            String qq1="SELECT user_no FROM customer_info where scheme_type='"+schemeType+"' ";

            rr1=st1.executeQuery(selectQueWithBranch(qq1,branchId));
            while(rr1.next())
            {
                st=conn.createStatement();
                String qq="select sum(maturity_value) from returned_amount_info where user_no='"+rr1.getString("user_no")+"' and chequeStatus='cleared' and paymentMode!='transfer_saving' and date>='"+sDate+"' and date<='"+eDate+"' ";
                
                rr=st.executeQuery(qq);
                if(rr.next())
                {
                    if(rr.getString("sum(maturity_value)")!=null)
                    {
                    	amt =amt+calculateTotalDepositInSelectedRd(rr1.getString("user_no"),conn);
                    }
                }
            	 //amt+=returnRdFdDdAmountBetweenDate(rr1.getString("user_no"),sDate,eDate);
                
                ////System.out.println(qq);
            }
        }
        catch(Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(st1!=null)
				{
					st1.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
				if(rr1!=null)
				{
					rr1.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		
		}
        return amt;
    }
	
	public ArrayList<TrialInfo> trialBalanceSavingAccount(int branchId,Date startDate,Date endDate) 
	{
		boolean chk=true;
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		ArrayList<TrialInfo> list=new ArrayList<>();
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from savingaccount  where openDate>='"+sDate+"' and openDate<='"+eDate+"' ";
			//// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				TrialInfo tt=new TrialInfo();
				
				if(chk==true)
				{
					tt.setCategory("Saving Account");
					chk=false;
				}
				tt.setParticular(rr.getString("accountNo"));
				tt.setDebit(0);
				tt.setCredit(Double.parseDouble(df.format(rr.getDouble("amount"))));
				
				if(tt.getDebit()>0 || tt.getCredit()>0)
				{
					list.add(tt);
				}
				
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public double penaltyAmountPaidByApplicant(int branchId,String loanNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(penalty) from loanpayment where loanNo='"+loanNo+"' ";
			//// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(penalty)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	

	public ArrayList<TrialInfo> trialBalanceBankAccount(int branchId,Date endDate, Date startDate, Connection conn) 
	{
		Date dt=endDate;
		boolean chk=true;
	//	dt.setDate(dt.getDate()+1);
		String eDate=sdfForDb.format(dt.getTime());
		
		Date sd=startDate;
		String sDate=sdfForDb.format(sd.getTime());
		
		Date tempdt=endDate;
		Calendar cal = Calendar.getInstance();
        cal.setTime(tempdt);
        cal.add(Calendar.DATE, 1);
        tempdt = cal.getTime();
        String tempDtStr=sdfForDb.format(tempdt.getTime());

        Statement st=null;ResultSet rr=null;
		ArrayList<TrialInfo> list=new ArrayList<>();
		
		try
		{
			 st=conn.createStatement();
			String qq="select * from bank_table";
			 rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				TrialInfo tt=new TrialInfo();
				
				//if(chk==true)
				{
					tt.setCategory("Bank Detail");
					chk=false;
				}
				tt.setParticular(rr.getString("bank_name"));
				double amt=closingBalanceOfBankOut(branchId,rr.getString("id"), tempDtStr,conn, "tb");
				double amt2=closingBalanceOfBankOut(branchId,rr.getString("id"), sDate,conn, "tb");
				
				double amt3=closingBalanceOfBankIn(branchId,rr.getString("id"), tempDtStr,conn, "tb");
				double amt4=closingBalanceOfBankIn(branchId,rr.getString("id"), sDate,conn, "tb");
				double amt5=amt4-amt2;
				
				double temp=new DataBaseReportMethods().companyIssueShareCapitalOpeningBalance(branchId,sDate,rr.getString("id"),conn);
				temp+=new DataBaseReportMethods().companyIssueShareCapitalOpeningBalanceFromShareInfoTable(branchId,sDate,rr.getString("id"),conn);
				//// //System.out.println("amt4: "+amt4+" amt2: "+amt2);
				double val=temp+(amt4-amt2);
				if(val>0)
				{
					tt.setOpeningDr(Math.abs(val));
				}
				else
				{
					tt.setOpeningCr(Math.abs(val));
				}
				
		
				double tempBetween=new DataBaseReportMethods().companyIssueShareCapital(branchId,sDate,rr.getString("id"),conn, eDate);
				tempBetween+=new DataBaseReportMethods().companyIssueShareCapitalFromShareInfoTable(branchId,sDate,rr.getString("id"),conn, eDate);
				
				tt.setDebit(tempBetween+(amt3-amt4));
				tt.setCredit(amt-amt2);
			//	tt.setBalance(tt.getDebit()-tt.getCredit());
				
				list.add(tt);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}

		
		return list;
	}

	public double closingBalanceOfBankIn(int branchId,String bankName, String sDate, Connection conn, String searchReport) 
	{
		DataBaseReportMethods dbmr=new DataBaseReportMethods();
		double totalIn = 0, totalOut = 0, openingBalance=0;
		HeaderBean hh=new HeaderBean();
		String ssDate="";
		if(searchReport.equalsIgnoreCase("TB"))
		{
			ssDate="2010-04-01";	
		}
		else
		{
			ssDate=hh.getStartFinYear()+"-04-01";
		}
		
		double a=dbmr.loanEmiPayForBankOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		System.out.println(" a loan emi pay bank in"+a);
		double b=dbmr.allPayReceiptForBankOpeningBalance(sDate, bankName, ssDate,conn);
		double c=dbmr.depositForBankOpeningBalance(sDate, bankName, ssDate,conn);
		double d=dbmr.allIncomePayForBankOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		double e=dbmr.allFixedDepositForBankOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		double f=dbmr.amountTransferForBankOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		double g=dbmr.otherDepositForBankOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		double h=dbmr.bankToBankTransferForBankOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		
		double i=dbmr.instantBorrowForOpeningBalance(branchId,sDate, "credit", bankName, ssDate,conn);
		double j=dbmr.instantLoanForOpeningBalance(branchId,sDate, "debit", bankName, ssDate,conn);
		double k=dbmr.PromotorAmountForOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		
		totalIn+=a+b+c+d+e+g+h+i+j+k;
		totalIn=Double.parseDouble(df.format(totalIn));
		
//		System.out.println("a: "+a);
//		System.out.println("b: "+b);
//		System.out.println("c: "+c);
//		System.out.println("d: "+d);
//		System.out.println("e: "+e);
//		System.out.println("f: "+f);
//		System.out.println("g: "+g);
//		System.out.println("h: "+h);
//		System.out.println("i: "+i);
//		System.out.println("j: "+j);
//		System.out.println("k: "+k);
		
		return totalIn;
	}
	
	public double closingBalanceOfBankOut(int branchId,String bankName, String sDate, Connection conn, String searchReport) 
	{
		DataBaseReportMethods dbmr=new DataBaseReportMethods();;
		HeaderBean hh=new HeaderBean();
		String ssDate="";
		if(searchReport.equalsIgnoreCase("TB") || searchReport.equalsIgnoreCase("Trial Balance"))
		{
			ssDate="2010-04-01";	
		}
		else
		{
			ssDate=hh.getStartFinYear()+"-04-01";
		}
		double totalIn = 0, totalOut = 0, openingBalance=0;
		
		double m=dbmr.loanAmountForBankOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		System.out.println("lm"+m);
		double n=dbmr.withdrawForBankOpeningBalance(sDate, bankName, ssDate,conn);
		System.out.println("withdrawl amt"+n);
		double o=dbmr.returnAmountForBankOpeningBalance(sDate, bankName, ssDate,conn);
		System.out.println("return amont"+o);
		double p=dbmr.allExpensePayForBankOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		System.out.println("expense"+p);
		double q=dbmr.allFdExpenseForBankOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		System.out.println("fd exp"+q);
		double r=dbmr.amountTransferToCompanyForBankOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		System.out.println("amount trns comp to cpmp"+r);
		double s=dbmr.instantBorrowForOpeningBalance(branchId,sDate, "debit", bankName, ssDate,conn);
		System.out.println("instant borrow"+s);
		double t=dbmr.instantLoanForOpeningBalance(branchId,sDate, "credit", bankName, ssDate,conn);
		System.out.println("instant lioan op blc"+t);
		double u=dbmr.returnPromotorAmountForOpeningBalance(branchId,sDate, bankName, ssDate,conn);
		double v=dbmr.returnDSACommForBankOpeningBalance(sDate, bankName, ssDate,conn);
		double w=dbmr.salaryPayoutForBankOpeningBalance(sDate, bankName, ssDate,conn, branchId);
		System.out.println("salary : " + w);
		double x=dbmr.allTdsPayForBankOpeningBalance(sDate, bankName, ssDate,conn);
		
		totalOut+=m+n+o+p+q+r+s+t+u+v+w+x;
		
		totalOut=Double.parseDouble(df.format(totalOut));
		
		return totalOut;
	}
	

	public ArrayList<TrialInfo> trialBalanceDirectExpenseList(int branchId,Date startDate,
			Date endDate, double rdInterest, double fdInterest) 
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		double savingsInterest=totalSavingsInterestAmount(branchId,startDate,endDate,conn);
		ArrayList<TrialInfo> list=new ArrayList<>();
		
	
		
		TrialInfo tt2=new TrialInfo();
		
		tt2.setParticular("Intrest On RD");
		tt2.setCredit(0);
		tt2.setDebit(rdInterest);
		list.add(tt2);
		
		TrialInfo tt3=new TrialInfo();
		
		tt3.setParticular("Intrest On FD");
		tt3.setCredit(0);
		tt3.setDebit(fdInterest);
		list.add(tt3);
		
		
	
		TrialInfo tt1=new TrialInfo();
		tt1.setCategory("Expenses (Direct)");
		tt1.setParticular("Intrest On Saving Account");
		tt1.setCredit(0);
		tt1.setDebit(savingsInterest);
		list.add(tt1);
		
		

		return list;
	}

	public ArrayList<TrialInfo> trialBalanceShareCapital(int branchId,Date startDate, Date endDate, Connection conn) 
	{	
		DataBaseReportMethods dbmrLocal= new DataBaseReportMethods();
		ArrayList<TrialInfo> list=new ArrayList<>();
		Date dt=endDate;
		String eDate=sdfForDb.format(dt.getTime());
		
		Date sd=startDate;
		String sDate=sdfForDb.format(sd.getTime());
		
		TrialInfo tt4=new TrialInfo();
		
		tt4.setCategory("Liabilities");
		tt4.setParticular("Share Capital");
		double shareAmt=dbmrLocal.companyIssueShareCapital(branchId,sDate,"all",conn,eDate);
		double shareAmtOpening=dbmrLocal.companyIssueShareCapitalOpeningBalance(branchId,sDate,"all",conn);
		shareAmtOpening+=dbmrLocal.companyIssueShareCapitalOpeningBalanceFromShareInfoTable(branchId,sDate,"all",conn);
		shareAmt+=dbmrLocal.companyIssueShareCapitalFromShareInfoTable(branchId,sDate,"all",conn,eDate);
		tt4.setOpeningCr(shareAmtOpening);
		tt4.setDebit(0);
		tt4.setCredit(shareAmt);
		list.add(tt4);
		
		return list;
	}
	
	public ArrayList<TrialInfo> trialBalanceRemainingEntry(int branchId,Date startDate, Date endDate, double rdInterest, double fdInterest) 
	{	
		DataBaseReportMethods dbmrLocal= new DataBaseReportMethods();
		Connection conn=DataBaseConnection.JAVAConnection();
		double savingsInterest=totalSavingsInterestAmount(branchId,startDate,endDate,conn);
		ArrayList<TrialInfo> list=new ArrayList<>();
	
		Date dt=endDate;
		boolean chk=true;
		String eDate=sdfForDb.format(dt.getTime());
		
		Date sd=startDate;
		String sDate=sdfForDb.format(sd.getTime());
		
		
		
		
		TrialInfo tt5=new TrialInfo();
		tt5.setCategory("Liabilities");
		tt5.setParticular("Interest On FDR");
		tt5.setCredit(0);
		tt5.setDebit(0);
		list.add(tt5);
		
		
		
		
		TrialInfo tt6=new TrialInfo();
		tt6.setCategory("Assets");
		tt6.setParticular("Interest On Loan");
		tt6.setOpeningCr(openingIntrestReceiveAllLoan(branchId,startDate));
		tt6.setCredit(intrestReceiveAllLoan(branchId,startDate, endDate));
		tt6.setDebit(0);
		list.add(tt6);
		
		TrialInfo tt7=new TrialInfo();
		tt7.setCategory("Income (Indirect)");
		double applicantOpFee=Double.parseDouble(df.format(totalApplicantFeeForOpening(branchId,startDate,conn)));
		double applicantFee=Double.parseDouble(df.format(totalApplicantFeeBetweenDate(branchId,startDate,endDate,conn)));
		tt7.setParticular("Deposit Application Fee");
		tt7.setOpeningCr(applicantOpFee);
		tt7.setCredit(applicantFee);
		tt7.setDebit(0);
		list.add(tt7);
		
		
		
		//double bankBalance=allBankBalance();
//		double cashBalance=remainingCompanyCapitalAmount();
//		cashBalance=Double.parseDouble(df.format(cashBalance));
		//// // // //System.out.println(cashBalance+"bank: "+bankBalance);
		
		TrialInfo tt8=new TrialInfo();
		
		Date tempdt=endDate;
		Calendar cal = Calendar.getInstance();
        cal.setTime(tempdt);
        cal.add(Calendar.DATE, 1);
        tempdt = cal.getTime();
        String tempDtStr=sdfForDb.format(tempdt.getTime());
		
    	tt8.setCategory("Assets");
		tt8.setParticular("Cash Balance");
		double amt1=closingCashOutBalance(branchId,tempDtStr,conn, "tb");
		double amt2=closingCashOutBalance(branchId,sDate,conn, "tb");
	//	// // // //System.out.println(endDate+"total out "+amt1+startDate+" total out: "+amt2);
		
		double amt3=closingCashInBalance(branchId,tempDtStr,conn, "tb");
		double amt4=closingCashInBalance(branchId,sDate,conn, "tb");
		
		double shareOpening=dbmrLocal.companyIssueShareCapitalOpeningBalance(branchId,sDate,"cash",conn);
		
		shareOpening+=dbmrLocal.companyIssueShareCapitalOpeningBalanceFromShareInfoTable(branchId,sDate,"cash",conn);
		//// //System.out.println("amt4: "+amt4+" amt2: "+amt2);
		double val=shareOpening+(amt4-amt2);
		if(val>0)
		{
			tt8.setOpeningDr(Math.abs(val));
		}
		else
		{
			tt8.setOpeningCr(Math.abs(val));
		}
		
		
		/*double vall=shareOpening+(openingBalanceFromTrialBalanceTable("CASH IN HAND", "2016-2017", "Cash"));
		if(vall>0)
		{
			tt8.setOpeningDr(Math.abs(vall));
		}
		else
		{
			tt8.setOpeningCr(Math.abs(vall));
		}*/
		
	//	// // // //System.out.println(endDate+"total in "+amt3+startDate+" total in: "+amt4);
		tt8.setCredit(amt1-amt2);
		
		double shareBetwwen=dbmrLocal.companyIssueShareCapital(branchId,sDate,"cash",conn, eDate);
		
		tt8.setDebit(shareBetwwen+(amt3-amt4));
		
		
		list.add(tt8);
		
		
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return list;
  }
	
	public ArrayList<TrialInfo> trialBalanceFixedDeposit(int branchId,Date startDate, Date endDate, Connection conn) 
	{
		boolean chk=true;
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		ArrayList<TrialInfo> list=new ArrayList<>();

		Statement st=null;ResultSet rr=null;
		try
		{
		 st=conn.createStatement();
			String qq="select * from fixed_deposit_expense where date<='"+eDate+"'";
			 rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				TrialInfo tt=new TrialInfo();
				
				tt.setOpeningCr(openingFdrReturnAmountByFdrNo(branchId,rr.getString("fdr_no"), sDate, conn));
				tt.setOpeningDr(openingFdrAmountByFdrNo(branchId,rr.getString("fdr_no"), sDate, conn));
				//if(chk==true)
				{
					tt.setCategory("Investments");
					chk=false;
				}
				tt.setParticular(rr.getString("fdr_no"));
				tt.setCredit(fdrReturnAmountByFdrNo(branchId,rr.getString("fdr_no"), sDate, eDate,conn));
				tt.setDebit(fdrAmountByFdrNo(branchId,rr.getString("fdr_no"), sDate, eDate, conn));
				
				list.add(tt);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}

		return list;
	}

	private double fdrReturnAmountByFdrNo(int branchId,String fdrNo, String sDate, String eDate, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select amount from fixed_deposit_income where fdr_no='"+fdrNo+"' and date>='"+sDate+"' and date<='"+eDate+"'";
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("amount");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	private double openingFdrAmountByFdrNo(int branchId,String fdrNo, String sDate, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select amount from fixed_deposit_expense where fdr_no='"+fdrNo+"' and date<'"+sDate+"' ";
			rr=st.executeQuery(selectQueWithBranch(qq, branchId));
			if(rr.next())
			{
				return rr.getDouble("amount");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	private double openingFdrReturnAmountByFdrNo(int branchId,String fdrNo, String sDate, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select amount from fixed_deposit_income where fdr_no='"+fdrNo+"' and date<'"+sDate+"' ";
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("amount");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	private double fdrAmountByFdrNo(int branchId,String fdrNo, String sDate, String eDate, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select amount from fixed_deposit_expense where fdr_no='"+fdrNo+"' and date>='"+sDate+"' and date<='"+eDate+"' ";
			rr=st.executeQuery(selectQueWithBranch(qq, branchId));
			if(rr.next())
			{
				return rr.getDouble("amount");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	public ArrayList<FixedAssetsInfo> fixedAssetsList(int branchId,String dt, String year) 
	{
		int count=1;
		ArrayList<FixedAssetsInfo> list=new ArrayList<>();
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from expense_table where category='Fixed_Asset_Dr' and expense_date<='"+dt+"' and status='active' ";
		//	// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				FixedAssetsInfo ff=new FixedAssetsInfo();
				
				ff.setFaPurchaseId(rr.getString("id"));
				ff.setName(rr.getString("item"));
				ff.setPurchaseDate(rr.getDate("expense_Date"));
				ff.setPurchaseDateStr(sf.format(ff.getPurchaseDate()));
				
				ff.setPurchaseValue(rr.getDouble("item_rate"));
				ff.setDepDeduct(calculateDepOnFaPrevious(ff.getFaPurchaseId(), year,branchId));
				ff.setPresentValue(ff.getPurchaseValue()-calculateDepOnFa(branchId,ff.getFaPurchaseId()));
				ff.setNoOfItem(rr.getInt("no_of_item"));
				ff.setNoOfItemSale(noOfFixedAssetSale(branchId,ff.getFaPurchaseId()));
				ff.setStockBalance(ff.getNoOfItem()-ff.getNoOfItemSale());
				boolean check=checkDepreciationDuplicacy(branchId,year, ff.getFaPurchaseId());
				if(check==true)
				{
					ff.setDisDep(true);
					ff.setDepValue(calculateDepOnFa(branchId,ff.getFaPurchaseId()));
					ff.setAfterDepValue(ff.getPurchaseValue()-ff.getDepValue());
				}
				else
				{
					ff.setDisDep(false);
				}
					
				
				if(ff.getStockBalance()>0)
				{
					ff.setSno(count++);
					list.add(ff);
				}
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}

	public int addDepreciation(int branchId,ArrayList<FixedAssetsInfo> list, String year, String depType) 
	{
		int i=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			for(FixedAssetsInfo ff: list)
			{
				if(ff.getDepPercent()>0)
				{
					String qq="insert into depreciation(fa_purchase_id, present_value, dep_percent, dep_value, after_dep_value, dep_year, dep_type, no_of_item,branch_id) "
							+ "values('"+ff.getFaPurchaseId()+"', '"+ff.getPresentValue()+"','"+ff.getDepPercent()+"','"+ff.getDepValue()+"','"+ff.getAfterDepValue()+"',"
									+ "'"+year+"','"+depType+"','"+ff.getNoOfItem()+"','"+branchId+"')";
			//		// // // //System.out.println(qq);
					i=st.executeUpdate(qq);
					if(i>0){
					dataInsertInQueryTable(qq, conn);
				}}
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}

	public String findResLoanNo(int branchId,String loanNo, String loanType)
	{
		String temp="NA",lno="";
		if(loanNo.contains("R"))
		{
			String tmp[]=loanNo.split("R");
			lno=tmp[0];
		}
		else
		{
			lno=loanNo;
		}
		
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select loanNo from "+loanType+" where loanNo like '"+lno+"R%' and branch_id='"+branchId+"' order by id desc limit 1";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				temp=rs.getString("loanNo");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return temp;
	}
	
	public String findSubLoanNo(int branchId,String loanNo)
	{
		String temp="NA",lno="";
		if(loanNo.contains("S"))
		{
			String tmp[]=loanNo.split("S");
			lno=tmp[0];
		}
		else
		{
			lno=loanNo;
		}
		
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select sub_loan_no from grouploan where sub_loan_no like '"+lno+"S%' and branch_id='"+branchId+"' order by id desc limit 1";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				temp=rs.getString("sub_loan_no");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return temp;
	}

	public double checkForRestructure(int branchId,String loanNo,String loanType) 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select amount from loanpayment where loanType='"+loanType+"' and loanNo='"+loanNo+"' and restructure!='No'";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rs.next())
			{
				return rs.getDouble("amount");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public boolean checkRestructureOrNot(String loanNo,String loanType) 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select id from loanpayment where loanType='"+loanType+"' and loanNo='"+loanNo+"' and restructure!='No'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return true;
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return false;
	}
	
	public int personalLoanRestructure(int branchId,String loanType,String shareHolderNo, String loanResNo,
			LoanInfo loan_info, int i, double remainingPrincipal,
			int remainingTerms, double newEmi, Date currentDate,
			int newDiscountOnLastEmi, double newRate, double increaseAmount) 
	{
		Timestamp ss = new Timestamp(currentDate.getTime());
		try (Connection conn = DataBaseConnection.JAVAConnection();) 
		{
			Statement stt = conn.createStatement();
			String query = "insert into personalloan(shareholderno, loanNo, idproof, filecharge, loanAmount, interest, terms, frequency,"
			+"emi, firstguarantor, secondguarantor, requestDate,status,reason,RD_FD_no,paidStatus,discount,increase_amount,emiType,branch_id)values('"+shareHolderNo+"','"+loanResNo+"','"+ loan_info.getIdProof()+"',"
			+ "'"+i+ "','"+ remainingPrincipal+ "','"+ newRate+ "','"+ remainingTerms+"','"+loan_info.getFrequencyVal()+"','"+newEmi+"','"+loan_info.getFirstGuarantor()+"',"
			+ "'"+ loan_info.getSecondGuarantor()+ "','"+ ss+ "','pending','restructure','"+loan_info.getRd_fdNo()+"','unpaid','"+newDiscountOnLastEmi+"','"+increaseAmount+"','"+loan_info.getEmiType()+"','"+branchId+"')";
			int j = stt.executeUpdate(query);
			if (j >= 1) {
				dataInsertInQueryTable(query, conn);
				return 1;
			}
		} 
		catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public int propertyLoanRestructure(int branchId,String loanType,String shareHolderNo, String loanResNo,
			LoanInfo loan_info, int i, double remainingPrincipal,
			int remainingTerms, double newEmi, Date currentDate,
			int newDiscountOnLastEmi, double newRate, double increaseAmount) 
	{
		Timestamp ss = new Timestamp(currentDate.getTime());
		try (Connection conn = DataBaseConnection.JAVAConnection();) 
		{
			Statement stt = conn.createStatement();
			String query = "insert into propertyloan(shareholderno, loanNo, idproof, filecharge, loanAmount, interest, terms,frequency,"
			+"emi, firstguarantor, secondguarantor, requestDate,status, category, registryNo, verified,jamabandi,patta,authorityPatta,RD_FD_no,paidStatus,discount,increase_amount,emiType,reason,branch_id)values"
			+ "('"+shareHolderNo+"','"+ loanResNo+"','"+loan_info.getIdProof()+"','"+i+ "','"+ remainingPrincipal+"','"+newRate+"','"+remainingTerms+"',"
			+ "'"+loan_info.getFrequencyVal()+"','"+newEmi+"','"+loan_info.getFirstGuarantor()+"','"+loan_info.getSecondGuarantor()+"','"+ss+"','pending','"+loan_info.getCategory()+"','"+loan_info.getRegistryNo()+"','"+loan_info.getVerified()
			+"','"+loan_info.getJamabandi()+"','"+loan_info.getPatta()+"','"+loan_info.getAuthorityPatta()+"','"+loan_info.getRd_fdNo()+"','unpaid','"+newDiscountOnLastEmi+"','"+increaseAmount+"','"+loan_info.getEmiType()+"','restructure','"+branchId+"')";
			
			int j = stt.executeUpdate(query);
			if (j >= 1) 
			{
				dataInsertInQueryTable(query, conn);
				return 1;
			}
		} catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}

		return 0;
	}

	public int vechicleLoanRestructure(int branchId,String loanType,String shareHolderNo, String loanResNo,
			LoanInfo loan_info, int i, double remainingPrincipal,
			int remainingTerms, double newEmi, Date currentDate,
			int newDiscountOnLastEmi, double newRate, double increaseAmount) 
	{
		Timestamp ss = new Timestamp(currentDate.getTime());
		try (Connection conn = DataBaseConnection.JAVAConnection();) 
		{
			Statement stt = conn.createStatement();
			String query = "insert into vechicleloan(shareholderno, loanNo, idproof, filecharge, loanAmount, interest, terms,frequency,"
			+ "emi,firstguarantor,secondguarantor,requestDate,status,category,vechileName,model,engineno,macNo,RD_FD_no,paidStatus,discount,increase_amount,emiType,reason, branch_id)values('"+shareHolderNo+"','"+ loanResNo+"',"
					+ "'"+loan_info.getIdProof()+"','"+i+ "','"+ remainingPrincipal+"','"+newRate+"','"+remainingTerms+"',"
			+ "'"+loan_info.getFrequencyVal()+"','"+newEmi+"','"+loan_info.getFirstGuarantor()+"','"+loan_info.getSecondGuarantor()+"','"+ss+"','pending',"
					+ "'"+loan_info.getCategory()+"','"+loan_info.getVechiclename()+"','"+loan_info.getVechileModel()+"','"+loan_info.getEngineNo()+"',"
							+ "'"+loan_info.getMacNo()+"','"+loan_info.getRd_fdNo()+"','unpaid','"+newDiscountOnLastEmi+"','"+increaseAmount+"','"+loan_info.getEmiType()+"','restructure','"+branchId+"')";
			int j = stt.executeUpdate(query);
			if (j >= 1) 
			{
				dataInsertInQueryTable(query, conn);
				return 1;
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;	
		
	}
	
	public int groupLoanRestructure(int branchId,String loanType,String shareHolderNo, String loanResNo,
			LoanInfo loan_info, int i, double remainingPrincipal,
			int remainingTerms, double newEmi, Date currentDate,
			int newDiscountOnLastEmi,double newRate, double increaseAmount) 
	{
		Timestamp ss = new Timestamp(currentDate.getTime());
		try (Connection conn = DataBaseConnection.JAVAConnection();) 
		{
			Statement stt = conn.createStatement();
			String query = "insert into grouploan(teamLeader, loanNo, idproof, filecharge, loanAmount, interest, terms, frequency,"
					+ " emi, requestDate,status,members, center,approvalDate,RD_FD_no,paidStatus,discount,increase_amount,emiType,reason, branch_id) values('"+shareHolderNo+"','"+ loanResNo+"',"
					+ "'"+loan_info.getIdProof()+"','"+i+ "','"+ remainingPrincipal+"','"+newRate+"','"+remainingTerms+"',"
			+ "'"+loan_info.getFrequencyVal()+"','"+newEmi+"','"+ss+"','pending','"+loan_info.getMembers()+"',"
					+ "'"+loan_info.getCenter()+"','"+loan_info.getRd_fdNo()+"','unpaid','"+newDiscountOnLastEmi+"','"+increaseAmount+"','"+loan_info.getEmiType()+"','restructure','"+branchId+"')";
			
			int j = stt.executeUpdate(query);
			if (j >= 1) 
			{
				dataInsertInQueryTable(query, conn);
				return 1;
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;	
		
	}


	public int checkPenaltyAnnulRate(int branchId,String loanType) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select penalty_annual from loan_table where loan_type='"+loanType+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getInt("penalty_annual");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public int checkGroupLoanLimit() 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select group_limit from loan_table where loan_type='grouploan' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getInt("group_limit");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}


	public ArrayList<String> emiPaidDateList(int branchId,String loanNo) 
	{
		ArrayList<String> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select pay_date from loanpayment where loanNo='"+loanNo+"' and receipt_status='approved' ";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				if(rr.getDate("pay_date")!=null)
				{
					list.add(sf.format(rr.getDate("pay_date")));
				}
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public ArrayList<LoanInfo> emiPaidDateListByLoanNoAndEmiNo(String loanNo, int emiNo) 
	{
		ArrayList<LoanInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select pay_date,amount from loanpayment where loanNo='"+loanNo+"' and emi_no='"+emiNo+"' and receipt_status='approved'  order by pay_date asc";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				if(rr.getDate("pay_date")!=null)
				{
					LoanInfo ll=new LoanInfo();
					
					ll.setPaidAmount(rr.getDouble("amount"));
					ll.setEmiPaidDateStr(sf.format(rr.getDate("pay_date")));
					ll.setEmiPaidDate(rr.getDate("pay_date"));
					list.add(ll);
				}
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	/*public ArrayList<LoanInfo> penaltyCalculationMethod(String loanType, String loanNo, ArrayList<LoanInfo> loanEMIList) throws ParseException 
	{
		int x=0;
		//ArrayList<String> emiPay=new ArrayList<>();
		ArrayList<LoanInfo> paidDateList=new ArrayList<>();
		
		emiPay=emiPaidDateList(loanNo);
		// // // //System.out.println("pay size: "+emiPay.size());
		for(int i=0; i<emiPay.size(); i++)
		{
			// // // //System.out.println(i+" hello");
			loanEMIList.get(i).setEmiPaidDateStr(emiPay.get(i));
		}
		
		// EMI Penalty Calculation method
		int penaltyRate=checkPenaltyAnnulRate(loanType);
		int penaltyDays=checkPenaltyBasis(loanType);
		double p1=0,p2=0,amt=0,tmp=0;
		
		for(int i=0; i<loanEMIList.size(); i++)
		{
			p1=p2=amt=tmp=0;
			paidDateList=emiPaidDateListByLoanNoAndEmiNo(loanNo,loanEMIList.get(i).getSno());
			//// // // //System.out.println("sno : "+loanEMIList.get(i).getSno());
			loanEMIList.get(i).setInstallDate(sf.parse(loanEMIList.get(i).getStrInstlmntDate()));
			
			// Interest Calculation on Paid EMI List 
			if(loanEMIList.get(i).getStatus().equalsIgnoreCase("paid"))
			{
				Date dt=new Date();tmp=0;double paid1=0;x=0;
				Date tempDate=new Date();
				if(paidDateList.size()>0)
				{
					for(LoanInfo pd : paidDateList)
					{
						tempDate=sf.parse(pd.getEmiPaidDateStr());
						loanEMIList.get(i).setEmiPaidDate(sf.parse(pd.getEmiPaidDateStr()));
						paid1=paidAmountOfEmi(loanNo, loanEMIList.get(i).getSno(), loanEMIList.get(i).getEmiPaidDate());
						
						if(loanEMIList.get(i).getInstallDate().before(loanEMIList.get(i).getEmiPaidDate()))
						{
							//if(loanEMIList.get(i).getInstallDate().before(loanEMIList.get(i).getEmiPaidDate()))
							if(tmp==0)
							{
								int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
								p1=p1+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid1));
							}
							else
							{
								int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - paidDateList.get(x-1).getEmiPaidDate().getTime()) / (1000 * 60 * 60 * 24));
								p1=p1+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid1));
							}
							
							tmp=1;
							
						}
						
						x++;
						
					}
					
					//loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p1/100)));
					if(tempDate.before(dt))
					{
						int days = (int) ((dt.getTime() - tempDate.getTime()) / (1000 * 60 * 60 * 24));
						p1=p1+(penaltyRate*days*loanEMIList.get(i).getDueAmount());
						loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p1/(100*penaltyDays))));
					}
				}
				else
				{
					if(loanEMIList.get(i).getInstallDate().before(dt))
					{
						int days = (int) ((dt.getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
						p1=p1+(penaltyRate*days*loanEMIList.get(i).getInstallAmount());
						loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p1/(100*penaltyDays))));
					}
				}
			}
			
			// Interest Calculation on Pending EMI List 
			else
			{
				double paid=0;
				x=0;tmp=0;
				Date dt=new Date();
				Date tempDate=new Date();
				if(paidDateList.size()>0)
				{
					for(LoanInfo pd : paidDateList)
					{
						tempDate=sf.parse(pd.getEmiPaidDateStr());
						loanEMIList.get(i).setEmiPaidDate(sf.parse(pd.getEmiPaidDateStr()));
						paid=paidAmountOfEmi(loanNo, loanEMIList.get(i).getSno(), loanEMIList.get(i).getEmiPaidDate());
						//// // // //System.out.println("paid : "+paid);
						if(loanEMIList.get(i).getInstallDate().before(loanEMIList.get(i).getEmiPaidDate()))
						{
							if(tmp==0)
							{
								int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
								p2=p2+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid));
								//.println("p2-1:"+p2);
							}
							else
							{
								int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - paidDateList.get(x-1).getEmiPaidDate().getTime()) / (1000 * 60 * 60 * 24));
								p2=p2+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid));
								//// // // //System.out.println("p2-2:"+p2);
							}
							
							tmp=1;
							
						}
						
						x++;
					}
					
					if(p2>0)
					{
						loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p2/100)));
					}
					else
					{
					if(tmp==1)
					{
						if(tempDate.before(dt))
						{
							int days = (int) ((dt.getTime() - tempDate.getTime()) / (1000 * 60 * 60 * 24));
							p2=p2+(penaltyRate*days*loanEMIList.get(i).getDueAmount());
							//// // // //System.out.println("p2-3:"+p2);
							loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p2/(100*penaltyDays))));
						}
					}
					else
					{
						if(loanEMIList.get(i).getInstallDate().before(dt))
						{
							int days = (int) ((dt.getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
							p2=p2+(penaltyRate*days*loanEMIList.get(i).getDueAmount());
							//// // // //System.out.println("p3-3:"+p2);
							loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p2/(100*penaltyDays))));
						}
					}
						
					//}
						
				}
				else
				{
					if(loanEMIList.get(i).getInstallDate().before(dt))
					{
						int days = (int) ((dt.getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
						p2=p2+(penaltyRate*days*loanEMIList.get(i).getInstallAmount());
						loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p2/(100*penaltyDays))));
					}
				}
					
			}
		}
		return loanEMIList;
	}*/
	
	
	/*// New Method
	public ArrayList<LoanInfo> penaltyCalculationMethod(String loanType, String loanNo, ArrayList<LoanInfo> loanEMIList) throws ParseException
    {
        int x=0;
        //ArrayList<String> emiPay=new ArrayList<>();
        ArrayList<LoanInfo> paidDateList=new ArrayList<>();
       
        emiPay=emiPaidDateList(loanNo);
        // // // // // //System.out.println("pay size: "+emiPay.size());
        for(int i=0; i<emiPay.size(); i++)
        {
            // // // // // //System.out.println(i+" hello");
            loanEMIList.get(i).setEmiPaidDateStr(emiPay.get(i));
        }
       
        // EMI Penalty Calculation method
        int penaltyRate=checkPenaltyAnnulRate(loanType);
        int penaltyDays=checkPenaltyBasis(loanType);
        double p1=0,p2=0,amt=0,tmp=0;
       
        for(int i=0; i<loanEMIList.size(); i++)
        {
            p1=p2=amt=tmp=0;
            paidDateList=emiPaidDateListByLoanNoAndEmiNo(loanNo,loanEMIList.get(i).getSno());
            loanEMIList.get(i).setInstallDate(sf.parse(loanEMIList.get(i).getStrInstlmntDate()));
           
            // Interest Calculation on Paid EMI List
            if(loanEMIList.get(i).getStatus().equalsIgnoreCase("paid"))
            {
                Date dt=new Date();tmp=0;double paid1=0;x=0;
                Date tempDate=new Date();
                if(paidDateList.size()>0)
                {
                    for(LoanInfo pd : paidDateList)
                    {
                        tempDate=sf.parse(pd.getEmiPaidDateStr());
                        loanEMIList.get(i).setEmiPaidDate(sf.parse(pd.getEmiPaidDateStr()));
                        paid1=paidAmountOfEmi(loanNo, loanEMIList.get(i).getSno(), loanEMIList.get(i).getEmiPaidDate());
                       
                        if(loanEMIList.get(i).getInstallDate().before(loanEMIList.get(i).getEmiPaidDate()))
                        {
                            //if(loanEMIList.get(i).getInstallDate().before(loanEMIList.get(i).getEmiPaidDate()))
                            if(tmp==0)
                            {
                                int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
                           
                                p1=p1+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid1));
                                loanEMIList.get(i).setPenaltydays(days);
                            }
                            else
                            {
                                int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - paidDateList.get(x-1).getEmiPaidDate().getTime()) / (1000 * 60 * 60 * 24));
                                p1=p1+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid1));
                                loanEMIList.get(i).setPenaltydays(days);
                            }
                           
                            tmp=1;
                           
                        }
                       
                        x++;
                       
                    }
                   
                    //loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p1/100)));
                    if(tempDate.before(dt))
                    {
                        int days = (int) ((dt.getTime() - tempDate.getTime()) / (1000 * 60 * 60 * 24));
                        p1=p1+(penaltyRate*days*loanEMIList.get(i).getDueAmount());
                        loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p1/(100*penaltyDays))));
                        if(p1 > 0)
                        {
                            loanEMIList.get(i).setPenaltydays(loanEMIList.get(i).getPenaltydays());
                        }
                       
                    }
                }
                else
                {
                    if(loanEMIList.get(i).getInstallDate().before(dt))
                    {
                        int days = (int) ((dt.getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
                        p1=p1+(penaltyRate*days*loanEMIList.get(i).getInstallAmount());
                    //    loanEMIList.get(i).setPenaltydays(days);
                    //    // //System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa "+p1);
                        loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p1/(100*penaltyDays))));
                        if(p1 > 0)
                        {
                            loanEMIList.get(i).setPenaltydays(loanEMIList.get(i).getPenaltydays());
                        }
                    }
                }
            }
           
            // Interest Calculation on Pending EMI List
            else
            {
                double paid=0;
                x=0;tmp=0;
                Date dt=new Date();
                Date tempDate=new Date();
                if(paidDateList.size()>0)
                {
                    for(LoanInfo pd : paidDateList)
                    {
                        tempDate=sf.parse(pd.getEmiPaidDateStr());
                        loanEMIList.get(i).setEmiPaidDate(sf.parse(pd.getEmiPaidDateStr()));
                        paid=paidAmountOfEmi(loanNo, loanEMIList.get(i).getSno(), loanEMIList.get(i).getEmiPaidDate());
                        //// // // // // //System.out.println("paid : "+paid);
                        if(loanEMIList.get(i).getInstallDate().before(loanEMIList.get(i).getEmiPaidDate()))
                        {
                            if(tmp==0)
                            {
                                int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
                                p2=p2+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid));
                                //.println("p2-1:"+p2);
                                loanEMIList.get(i).setPenaltydays(days);
                            }
                            else
                            {
                                int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - paidDateList.get(x-1).getEmiPaidDate().getTime()) / (1000 * 60 * 60 * 24));
                                p2=p2+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid));
                                //// // // // // //System.out.println("p2-2:"+p2);
                                loanEMIList.get(i).setPenaltydays(days);
                            }
                           
                            tmp=1;
                           
                        }
                       
                        x++;
                    }
                   
                    if(p2>0)
                    {
                        loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p2/100)));
                    }
                    else
                    {
                    if(tmp==1)
                    {
                        if(tempDate.before(dt))
                        {
                            int days = (int) ((dt.getTime() - tempDate.getTime()) / (1000 * 60 * 60 * 24));
                            p2=p2+(penaltyRate*days*loanEMIList.get(i).getDueAmount());
                            //// // // // // //System.out.println("p2-3:"+p2);
                            loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p2/(100*penaltyDays))));
                    //        // //System.out.println("bbbbbbbbbbbbbbbbbbbbbbbb "+p2);
                            if(p2 > 0)
                            {
                                loanEMIList.get(i).setPenaltydays(loanEMIList.get(i).getPenaltydays());
                            }
                        }
                    }
                    else
                    {
                        if(loanEMIList.get(i).getInstallDate().before(dt))
                        {
                            int days = (int) ((dt.getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
                            p2=p2+(penaltyRate*days*loanEMIList.get(i).getDueAmount());
                            //// // // // // //System.out.println("p3-3:"+p2);
                        //    loanEMIList.get(i).setPenaltydays(days);
                            loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p2/(100*penaltyDays))));
                        //    // //System.out.println("cccccccccccccccccccccccc "+p2);
                            if(p2 > 0)
                            {
                                loanEMIList.get(i).setPenaltydays(loanEMIList.get(i).getPenaltydays());
                            }
                        }
                    }
                       
                    //}
                       
                }
                else
                {
                    if(loanEMIList.get(i).getInstallDate().before(dt))
                    {
                        int days = (int) ((dt.getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
                        p2=p2+(penaltyRate*days*loanEMIList.get(i).getInstallAmount());
                        // // //System.out.println("asdklaskdlasd "+p2);
                        // // //System.out.println("asdklasasasasasasasa "+penaltyDays);
                        // // //System.out.println("dddddddddddddddddddddddddddddddddddddddd "+p2);
                        loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format((p2)/(100*penaltyDays))));
                        if(p2 > 0)
                        {
                            loanEMIList.get(i).setPenaltydays(days);
                        }
                    }
                }
                   
            }
        }
        return loanEMIList;
    }*/
	

	public ArrayList<LoanInfo> penaltyCalculationMethod(String loanType, String loanNo, ArrayList<LoanInfo> loanEMIList, Connection conn) throws ParseException
    {
		HttpSession ss = (HttpSession) FacesContext.getCurrentInstance()
		        .getExternalContext()
		        .getSession(false);

		String companyType = ss != null
		        ? (String) ss.getAttribute("companyType")
		        : "MFi";

		if (companyType == null) {
		    companyType = "MFi";
		}
	//if(companyType.equalsIgnoreCase("NBFC"))
		if("NBFC".equalsIgnoreCase(companyType))
		{
			
//			Date date1 = new Date();
//			
//			for(int y=0; y<loanEMIList.size();y++)
			{
//				Date emiDate=sf.parse((loanEMIList.get(y).getStrInstlmntDate())) ;
//				
//				if(emiDate.before(date1) && loanEMIList.get(y).getStatus().equals("Due")) 
//				{
//					
//					long diffInMillis = date1.getTime() - emiDate.getTime();
//
//				    // Convert milliseconds to days
//				    long diffInDays = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);
//
//				    // Calculate how many full 7-day periods (weeks) have passed
//				    long weeksOverdue = diffInDays / 8;
//
//				    // Multiply by ₹250 per week
//				    int penaltyAmount = (int)(weeksOverdue * 250);
//				    
//                    loanEMIList.get(y).setPenaltyDue(250+penaltyAmount);
//
//				}
//				

				
		        int x=0;
		        ArrayList<LoanInfo> paidDateList=new ArrayList<>();
		        
		        String planId=penaltyIdByLoanNo(loanNo, loanType);
		        int penaltyRate=checkPenaltyDetailByPlanId(planId, "penalty_annual", conn);
		        int penaltyDays=checkPenaltyDetailByPlanId(planId, "penalty_basis", conn);
		        double p1=0,p2=0,tmp=0;
		        
		       
		        if(penaltyRate>0)
		        {
		        	 for(int i=0; i<loanEMIList.size(); i++)
		             {
		                 p1=p2=tmp=0;
		                 paidDateList=emiPaidDateListByLoanNoAndEmiNo(loanNo,loanEMIList.get(i).getSno());
		                 loanEMIList.get(i).setInstallDate(sf.parse(loanEMIList.get(i).getStrInstlmntDate()));
		                
		                 // Interest Calculation on Paid EMI List
		                 if(loanEMIList.get(i).getStatus().equalsIgnoreCase("paid"))
		                 {
		                     Date dt=new Date();tmp=0;double paid1=0;x=0;
		                     Date tempDate=new Date();
		                     Date intallDate=sf.parse((loanEMIList.get(i).getStrInstlmntDate())) ;
		                     System.out.println(intallDate+"kk");
		                     
		                     
		                     if(paidDateList.size()>0)
		                     {
		                         for(LoanInfo pd : paidDateList)
		                         {
		                             tempDate=sf.parse(pd.getEmiPaidDateStr());
		                             loanEMIList.get(i).setEmiPaidDate(sf.parse(pd.getEmiPaidDateStr()));
		                             paid1=paidAmountOfEmi(loanNo, loanEMIList.get(i).getSno(), loanEMIList.get(i).getEmiPaidDate());
		                            
		                             if(loanEMIList.get(i).getInstallDate().before(loanEMIList.get(i).getEmiPaidDate()))
		                             {
		                                 //if(loanEMIList.get(i).getInstallDate().before(loanEMIList.get(i).getEmiPaidDate()))
		                                 if(tmp==0)
		                                 {
		                                     int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
		                                
		                                     p1=p1+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid1));
		                                     loanEMIList.get(i).setPenaltydays(days);
		                                 }
		                                 else
		                                 {
		                                     int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - paidDateList.get(x-1).getEmiPaidDate().getTime()) / (1000 * 60 * 60 * 24));
		                                     p1=p1+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid1));
		                                     loanEMIList.get(i).setPenaltydays(days);
		                                 }
		                                
		                                 tmp=1;
		                                
		                             }
		                            
		                             x++;
		                            
		                         }
		                        
		                         //loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p1/100)));
		                         
		                         System.out.println(tempDate+"gg"+intallDate);
		                         if(intallDate.before(tempDate))
		                         {
		                             int days = (int) ((intallDate.getTime() - tempDate.getTime()) / (1000 * 60 * 60 * 24));
		                             p1=p1+(penaltyRate*days*loanEMIList.get(i).getDueAmount());
		                             //System.out.println("pdddddddddd:"+penaltyDays);
		                             //System.out.println("total: "+p1/(100*penaltyDays));
		                             long diffInMillis =  tempDate.getTime()-intallDate.getTime() ;

		         				    // Convert milliseconds to days
		         				    long diffInDays = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);

		         				    // Calculate how many full 7-day periods (weeks) have passed
		         				    long weeksOverdue = diffInDays / 7;

		         				    // Multiply by ₹250 per week
		         				    int penaltyAmount = (int)(weeksOverdue * 250);
		         				   int pd=0;
		         				   
		         				  
		         				     if(diffInMillis !=0)
		         				     {
		         				    	 pd =250;
		         				     }
		                             loanEMIList.get(i).setPenaltyDue(pd+penaltyAmount);
		                             
		                             System.out.println(pd+penaltyAmount+"kk");
		                             if(p1 > 0)
		                             {
		                                 loanEMIList.get(i).setPenaltydays(loanEMIList.get(i).getPenaltydays());
		                             }
		                            
		                         }
		                     }
		                     else
		                     {
		                         if(loanEMIList.get(i).getInstallDate().before(dt))
		                         {
		                             int days = (int) ((dt.getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
		                             p1=p1+(penaltyRate*days*loanEMIList.get(i).getInstallAmount());
		                         //    loanEMIList.get(i).setPenaltydays(days);
		                         //    // //System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa "+p1);
		                             
		                             
		                             long diffInMillis = dt.getTime() - loanEMIList.get(i).getInstallDate().getTime();

		         				    // Convert milliseconds to days
		         				    long diffInDays = TimeUnit.DAYS.convert(days, TimeUnit.MILLISECONDS);

		         				    // Calculate how many full 7-day periods (weeks) have passed
		         				    long weeksOverdue = diffInDays / 7;

		         				    // Multiply by ₹250 per week
		         				    int penaltyAmount = (int)(weeksOverdue * 250);
		         				     int pd=0;
		         				     if(days !=0)
		         				     {
		         				    	 pd =250;
		         				     }
		                             loanEMIList.get(i).setPenaltyDue(pd+penaltyAmount);
		                             System.out.println(pd+penaltyAmount+"kki");
		                             if(p1 > 0)
		                             {
		                                 loanEMIList.get(i).setPenaltydays(loanEMIList.get(i).getPenaltydays());
		                             }
		                         }
		                     }
		                 }
		                
		                 // Interest Calculation on Pending EMI List
		                 else
		                 {
		                     double paid=0;
		                     x=0;tmp=0;
		                     Date dt=new Date();
		                     Date tempDate=new Date();
		                     if(paidDateList.size()>0)
		                     {
		                         for(LoanInfo pd : paidDateList)
		                         {
		                             tempDate=sf.parse(pd.getEmiPaidDateStr());
		                             loanEMIList.get(i).setEmiPaidDate(sf.parse(pd.getEmiPaidDateStr()));
		                             paid=paidAmountOfEmi(loanNo, loanEMIList.get(i).getSno(), loanEMIList.get(i).getEmiPaidDate());
		                             if(loanEMIList.get(i).getInstallDate().before(loanEMIList.get(i).getEmiPaidDate()))
		                             {
		                                 if(tmp==0)
		                                 {
		                                     int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
		                                     p2=p2+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid));
		                                     loanEMIList.get(i).setPenaltydays(days);
		                                 }
		                                 else
		                                 {
		                                     int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - paidDateList.get(x-1).getEmiPaidDate().getTime()) / (1000 * 60 * 60 * 24));
		                                     p2=p2+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid));
		                                     loanEMIList.get(i).setPenaltydays(days);
		                                 }
		                                 tmp=1;
		                             }
		                             x++;
		                         }
		                        
		                         if(p2>0)
		                         {
		                             loanEMIList.get(i).setPenaltyDue(250.0);
		                         }
		                         else
		                         {
		     	                    if(tmp==1)
		     	                    {
		     	                        if(tempDate.before(dt))
		     	                        {
		     	                            int days = (int) ((dt.getTime() - tempDate.getTime()) / (1000 * 60 * 60 * 24));
		     	                            p2=p2+(penaltyRate*days*loanEMIList.get(i).getDueAmount());
		     	                            //// // // // // //System.out.println("p2-3:"+p2);
		     	                            
		     	                           long diffInMillis = dt.getTime() - tempDate.getTime();

				         				    // Convert milliseconds to days
				         				    long diffInDays = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);

				         				    // Calculate how many full 7-day periods (weeks) have passed
				         				    long weeksOverdue = diffInDays /7;
				         				    // Multiply by ₹250 per week
				         				    int penaltyAmount = (int)(weeksOverdue * 250);
		     	                            loanEMIList.get(i).setPenaltyDue(250.0+penaltyAmount);
		     	                    //        // //System.out.println("bbbbbbbbbbbbbbbbbbbbbbbb "+p2);
		     	                            if(p2 > 0)
		     	                            {
		     	                                loanEMIList.get(i).setPenaltydays(loanEMIList.get(i).getPenaltydays());
		     	                            }
		     	                        }
		     	                    }
		     	                    else
		     	                    {
		     	                        if(loanEMIList.get(i).getInstallDate().before(dt))
		     	                        {
		     	                            int days = (int) ((dt.getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
		     	                            p2=p2+(penaltyRate*days*loanEMIList.get(i).getDueAmount());
		     	                        //    loanEMIList.get(i).setPenaltydays(days);
		     	                           long diffInMillis = dt.getTime() - loanEMIList.get(i).getInstallDate().getTime();

				         				    // Convert milliseconds to days
				         				    long diffInDays = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);

				         				    // Calculate how many full 7-day periods (weeks) have passed
				         				    long weeksOverdue = diffInDays / 7;
				         				   
				         				    // Multiply by ₹250 per week
				         				    int penaltyAmount = (int)(weeksOverdue * 250);
		     	                            loanEMIList.get(i).setPenaltyDue(250.0+penaltyAmount);
		     	                        //    // //System.out.println("cccccccccccccccccccccccc "+p2);
		     	                            if(p2 > 0)
		     	                            {
		     	                                loanEMIList.get(i).setPenaltydays(loanEMIList.get(i).getPenaltydays());
		     	                            }
		     	                        }
		     	                    }
		     	                       
		                         }
		                            
		                     }
		                     else
		                     {
		                         if(loanEMIList.get(i).getInstallDate().before(dt))
		                         {
		                             int days = (int) ((dt.getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
		                             p2=p2+(penaltyRate*days*loanEMIList.get(i).getInstallAmount());
		                             
		                             long diffInMillis = dt.getTime() - loanEMIList.get(i).getInstallDate().getTime();

			         				    // Convert milliseconds to days
			         				    long diffInDays = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);

			         				    // Calculate how many full 7-day periods (weeks) have passed
			         				    long weeksOverdue = diffInDays / 7;
			         				   
			         				    // Multiply by ₹250 per week
			         				    int penaltyAmount = (int)(weeksOverdue * 250);
		                             loanEMIList.get(i).setPenaltyDue(250.0+penaltyAmount);
		                             if(p2 > 0)
		                             {
		                                 loanEMIList.get(i).setPenaltydays(days);
		                             }
		                         }
		                     }
		                        
		                 }
		             }
		        }
			
				
				
				
				
			 
				
				
			}
			
		}
	else {
		
        int x=0;
        ArrayList<LoanInfo> paidDateList=new ArrayList<>();
        
        DataBaseMethodTaheer dbmt = new DataBaseMethodTaheer();
        
        String planId=penaltyIdByLoanNo(loanNo, loanType);
//        int penaltyRate=checkPenaltyDetailByPlanId(planId, "penalty_annual", conn);
        double penaltyRate=dbmt.checkPenaltyDetailByPlanId(planId, "penalty_annual", conn);
        int penaltyDays=checkPenaltyDetailByPlanId(planId, "penalty_basis", conn);
        double p1=0,p2=0,tmp=0;
        
       
        if(penaltyRate>0)
        {
        	 for(int i=0; i<loanEMIList.size(); i++)
             {
                 p1=p2=tmp=0;
                 paidDateList=emiPaidDateListByLoanNoAndEmiNo(loanNo,loanEMIList.get(i).getSno());
                 loanEMIList.get(i).setInstallDate(sf.parse(loanEMIList.get(i).getStrInstlmntDate()));
                
                 // Interest Calculation on Paid EMI List
                 if(loanEMIList.get(i).getStatus().equalsIgnoreCase("paid"))
                 {
                     Date dt=new Date();tmp=0;double paid1=0;x=0;
                     Date tempDate=new Date();
                     if(paidDateList.size()>0)
                     {
                         for(LoanInfo pd : paidDateList)
                         {
                             tempDate=sf.parse(pd.getEmiPaidDateStr());
                             loanEMIList.get(i).setEmiPaidDate(sf.parse(pd.getEmiPaidDateStr()));
                             paid1=paidAmountOfEmi(loanNo, loanEMIList.get(i).getSno(), loanEMIList.get(i).getEmiPaidDate());
                            
                             if(loanEMIList.get(i).getInstallDate().before(loanEMIList.get(i).getEmiPaidDate()))
                             {
                                 //if(loanEMIList.get(i).getInstallDate().before(loanEMIList.get(i).getEmiPaidDate()))
                                 if(tmp==0)
                                 {
                                     int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
                                
                                     p1=p1+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid1));
                                     loanEMIList.get(i).setPenaltydays(days);
                                 }
                                 else
                                 {
                                     int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - paidDateList.get(x-1).getEmiPaidDate().getTime()) / (1000 * 60 * 60 * 24));
                                     p1=p1+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid1));
                                     loanEMIList.get(i).setPenaltydays(days);
                                 }
                                
                                 tmp=1;
                                
                             }
                            
                             x++;
                            
                         }
                        
                         //loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p1/100)));
                         if(tempDate.before(dt))
                         {
                             int days = (int) ((dt.getTime() - tempDate.getTime()) / (1000 * 60 * 60 * 24));
                             p1=p1+(penaltyRate*days*loanEMIList.get(i).getDueAmount());
                             //System.out.println("pdddddddddd:"+penaltyDays);
                             //System.out.println("total: "+p1/(100*penaltyDays));
                             loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p1/(100*penaltyDays))));
                             if(p1 > 0)
                             {
                                 loanEMIList.get(i).setPenaltydays(loanEMIList.get(i).getPenaltydays());
                             }
                            
                         }
                     }
                     else
                     {
                         if(loanEMIList.get(i).getInstallDate().before(dt))
                         {
                             int days = (int) ((dt.getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
                             p1=p1+(penaltyRate*days*loanEMIList.get(i).getInstallAmount());
                         //    loanEMIList.get(i).setPenaltydays(days);
                         //    // //System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa "+p1);
                             loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p1/(100*penaltyDays))));
                             if(p1 > 0)
                             {
                                 loanEMIList.get(i).setPenaltydays(loanEMIList.get(i).getPenaltydays());
                             }
                         }
                     }
                 }
                
                 // Interest Calculation on Pending EMI List
                 else
                 {
                     double paid=0;
                     x=0;tmp=0;
                     Date dt=new Date();
                     Date tempDate=new Date();
                     if(paidDateList.size()>0)
                     {
                         for(LoanInfo pd : paidDateList)
                         {
                             tempDate=sf.parse(pd.getEmiPaidDateStr());
                             loanEMIList.get(i).setEmiPaidDate(sf.parse(pd.getEmiPaidDateStr()));
                             paid=paidAmountOfEmi(loanNo, loanEMIList.get(i).getSno(), loanEMIList.get(i).getEmiPaidDate());
                             if(loanEMIList.get(i).getInstallDate().before(loanEMIList.get(i).getEmiPaidDate()))
                             {
                                 if(tmp==0)
                                 {
                                     int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
                                     p2=p2+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid));
                                     loanEMIList.get(i).setPenaltydays(days);
                                 }
                                 else
                                 {
                                     int days = (int) ((loanEMIList.get(i).getEmiPaidDate().getTime() - paidDateList.get(x-1).getEmiPaidDate().getTime()) / (1000 * 60 * 60 * 24));
                                     p2=p2+(penaltyRate*days*(loanEMIList.get(i).getInstallAmount()-paid));
                                     loanEMIList.get(i).setPenaltydays(days);
                                 }
                                 tmp=1;
                             }
                             x++;
                         }
                        
                         if(p2>0)
                         {
                             loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p2/(100*penaltyDays))));
                         }
                         else
                         {
     	                    if(tmp==1)
     	                    {
     	                        if(tempDate.before(dt))
     	                        {
     	                            int days = (int) ((dt.getTime() - tempDate.getTime()) / (1000 * 60 * 60 * 24));
     	                            p2=p2+(penaltyRate*days*loanEMIList.get(i).getDueAmount());
     	                            //// // // // // //System.out.println("p2-3:"+p2);
     	                            loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p2/(100*penaltyDays))));
     	                    //        // //System.out.println("bbbbbbbbbbbbbbbbbbbbbbbb "+p2);
     	                            if(p2 > 0)
     	                            {
     	                                loanEMIList.get(i).setPenaltydays(loanEMIList.get(i).getPenaltydays());
     	                            }
     	                        }
     	                    }
     	                    else
     	                    {
     	                        if(loanEMIList.get(i).getInstallDate().before(dt))
     	                        {
     	                            int days = (int) ((dt.getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
     	                            p2=p2+(penaltyRate*days*loanEMIList.get(i).getDueAmount());
     	                        //    loanEMIList.get(i).setPenaltydays(days);
     	                            loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format(p2/(100*penaltyDays))));
     	                        //    // //System.out.println("cccccccccccccccccccccccc "+p2);
     	                            if(p2 > 0)
     	                            {
     	                                loanEMIList.get(i).setPenaltydays(loanEMIList.get(i).getPenaltydays());
     	                            }
     	                        }
     	                    }
     	                       
                         }
                            
                     }
                     else
                     {
                         if(loanEMIList.get(i).getInstallDate().before(dt))
                         {
                             int days = (int) ((dt.getTime() - loanEMIList.get(i).getInstallDate().getTime()) / (1000 * 60 * 60 * 24));
                             p2=p2+(penaltyRate*days*loanEMIList.get(i).getInstallAmount());
                             loanEMIList.get(i).setPenaltyDue(Double.parseDouble(df.format((p2)/(100*penaltyDays))));
                             if(p2 > 0)
                             {
                                 loanEMIList.get(i).setPenaltydays(days);
                             }
                         }
                     }
                        
                 }
             }
        }
	}
        return loanEMIList;
    }


	private int checkPenaltyDetailByPlanId(String planId, String string, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select "+string+" from plans where idplans='"+planId+"' ";
			////System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				if(rr.getString(string)!=null && !rr.getString(string).equalsIgnoreCase(""))
				{
					return rr.getInt(string);
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	public double penaltyAmountReceiveByLoanNoAndDate(String loanNo, String dt,Connection conn) 
	{
		Statement st=null;
		ResultSet rs=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount) from income_table where income_date='"+dt+"' and item='Receive Penalty' and loan_no='"+loanNo+"' and status='active' ";
			//System.out.println(qq);
			rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} 
			catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}


	private String penaltyIdByLoanNo(String loanNo, String loanType) 
	{
		String qq="", planId="";
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(loanType.equalsIgnoreCase("grouploan") || loanType.equalsIgnoreCase("Group Loan"))
			{
				
				qq="select plan_no from grouploan where sub_loan_no='"+loanNo+"' ";
			}
			else
			{
				qq="select plan_no from "+loanType+" where loanNo='"+loanNo+"' ";
			}
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				planId=rr.getString("plan_no");
			}
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return planId;
	}

	
	// Check Penalty Basis Using loan Type (Monthly Or Yearly).......
		public int checkPenaltyBasis(String loanType) 
		{
			int day=0;
			try(Connection conn=DataBaseConnection.JAVAConnection())
			{
				Statement st=conn.createStatement();
				String qq="select penalty_basis from loan_table where loan_type='"+loanType+"' ";
				ResultSet rr=st.executeQuery(qq);
				if(rr.next())
				{
					String dd=rr.getString("penalty_basis");
					if(dd.equalsIgnoreCase("monthly"))
					{
						day=30;
					}
					else if(dd.equalsIgnoreCase("yearly"))
					{
						day=365;
					}
					else
					{
						day=1;
					}
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();fileCreation(e.getMessage());
			}
			return day;
		}
		
	private double paidAmountOfEmi(String loanNo, int sno, Date emiPaidDate) 
	{
		Timestamp tt=new Timestamp(emiPaidDate.getTime());
		try(Connection conn=DataBaseConnection.JAVAConnection();)
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from loanpayment where loanNo='"+loanNo+"' and emi_no='"+sno+"' and receipt_status='approved' and chequeStatus='cleared' and pay_date<'"+tt+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public ArrayList<BorrowerLenderInfo> emiPenaltyRateList() 
	{
		int count=1;
		ArrayList<BorrowerLenderInfo> list=new ArrayList<>();
		try(Connection con=DataBaseConnection.JAVAConnection())
		{
			Statement st=con.createStatement();
			String qq="select * from loan_table where loan_permission='true' ";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				BorrowerLenderInfo bb=new BorrowerLenderInfo();
				
				bb.setSno(count++);
				bb.setId(rr.getString("id_loan_type"));
				bb.setLoanType(rr.getString("loan_type"));
				bb.setPenaltyAnnualRate(rr.getDouble("penalty_annual"));
				bb.setPenaltyBasis(rr.getString("penalty_basis"));
				
				list.add(bb);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}


	public int updatePenaltyDetail(String id, double rate, String penanltyBasis) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update loan_table set penalty_annual='"+rate+"', penalty_basis='"+penanltyBasis+"' where id_loan_type='"+id+"' ";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
				dataInsertInQueryTable(qq, conn);
				return i;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public double calculatePenaltyAndChequeBounceCharges(String loanNo, String itemName, String loanType, Connection conn) 
	{
		double total=0;
		Statement st=null;
		ResultSet rr=null;
		String qq="";
		try
		{
			st=conn.createStatement();
			
			if(itemName.contains("Penalty"))
			{
				ArrayList<LoanInfo> loanEMIList;
				//String loanType=loanTypeByLoanNo(loanNo);
				loanEMIList=loanInstallment(loanType, loanNo,conn);
				
				loanEMIList=penaltyCalculationMethod(loanType, loanNo, loanEMIList,conn);
				for(LoanInfo ll: loanEMIList)
				{
					total+=ll.getPenaltyDue();
				}
				//// // // //System.out.println("total pen: "+total);
				
			}
			else
			{   
				qq="select sum(cheque_bounce_charge) from loanpayment where loanNo='"+loanNo+"' ";
				//// // // //System.out.println(qq);
				rr=st.executeQuery(qq);
				if(rr.next())
				{
					total+=rr.getDouble("sum(cheque_bounce_charge)");
				}
				
				String qq1="select sum(amount) from manual_charges where loan_no='"+loanNo+"' and loan_type='"+loanType+"' ";
				//System.out.println(qq);
				ResultSet rr1=st.executeQuery(qq1);
				if(rr1.next())
				{
					total+=rr1.getDouble("sum(amount)");
				}
			}
			
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return total;
	}
	
	public double totalPaidPenaltyAndChequeBounceCharges(String loanNo, String itemName, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		String qq="";
		try
		{
			st=conn.createStatement();
			
			if(itemName.contains("Penalty"))
			{   
				qq="select sum(amount) from income_table where loan_no='"+loanNo+"' and item like '%Penalty%' ";
			}
			else
			{
				qq="select sum(amount) from income_table where loan_no='"+loanNo+"' and item like '%Cheque Bounce%' ";
			}
			//// // // //System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	public double discountOnPenaltyByLoanNo(String loanNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount),sum(discount) from income_table where loan_no='"+loanNo+"' and item like '%Penalty%' ";
			//// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(discount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	
	public double showChequeBounceCharge() 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from cheque_bounce";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("bounce_charge");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public int updateChequeBounceCharge(double charge) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq1="select * from cheque_bounce";
			ResultSet rr=st.executeQuery(qq1);
			if(rr.next())
			{
				String qq="update cheque_bounce set bounce_charge='"+charge+"' ";
				int i=st.executeUpdate(qq);
				if(i>0)
				{
					dataInsertInQueryTable(qq, conn);
					return i;
				}
			}
			else
			{
				String qq="insert into cheque_bounce(bounce_charge) values('"+charge+"') ";
				int i=st.executeUpdate(qq);
				if(i>0)
				{
					dataInsertInQueryTable(qq, conn);
					return i;
				}
			}
			
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;	
	}
	
	public int getPromotorCode(int branchId) 
	{
		try (Connection cnt = DataBaseConnection.JAVAConnection();)
		{
			Statement stt = cnt.createStatement();
			String query = "select * from promotors where branch_id='"+branchId+"'order by code desc";
			ResultSet rr  = stt.executeQuery(query);
			if(rr.next())
			{
				return rr.getInt("code");
			}
			
		} catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public int addPromotors(String code, String name, String address,
			String mobile, Date openDate, double interestRate,int branchId,Connection conn) 
	{
		Timestamp tt=new Timestamp(openDate.getTime());
		Statement stt=null;
		ResultSet rs=null;
		try 
		{
			stt = conn.createStatement();
			String query ="insert into promotors (code, name, mobile, address, status, open_date, interest, branch_id)values('"+code+"','"+name+"','"+mobile+"',"
					+ "'"+address+"','active', '"+tt+"', '"+interestRate+"','"+branchId+"')";
			 int er = stt.executeUpdate(query);
			 if(er>0)
			 {
				 dataInsertInQueryTable(query, conn);
				 return er;
			 }
			
		} catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}


	public int deletePromotors(String idp) 
	{
		try (Connection cnt = DataBaseConnection.JAVAConnection();)
		{
			Statement stt = cnt.createStatement();
			String query ="update promotors set status='inactive' where id = '"+idp+"'";
			int re = stt.executeUpdate(query);
			if(re>0)
			{
				dataInsertInQueryTable(query, cnt);
				return re;
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}


	public int updatePromotors(String id, String name, String mobile,String address) 
	{
		try (Connection cnt = DataBaseConnection.JAVAConnection();)
		{
			Statement stt = cnt.createStatement();
			String query ="update promotors set name='"+name+"', mobile='"+mobile+"', address='"+address+"' where id = '"+id+"'";
		//	// // // //System.out.println(query);
			int re = stt.executeUpdate(query);
			if(re>0)
			{
				dataInsertInQueryTable(query, cnt);
				return re;
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}


	public ArrayList<SelectItem> allPromotorsNameList(int branchId) 
	{
	
		 
		ArrayList<SelectItem> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from promotors where status='active' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				SelectItem tt=new SelectItem();
				
				tt.setLabel("P"+rr.getString("code")+"-"+rr.getString("name"));
				tt.setValue(rr.getString("id"));
				
				list.add(tt);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}


	public ArrayList<UserInfo> pendingPromotorsCapitalList(int branchId) 
	{
		ArrayList<UserInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from promotors_capital where chequeStatus='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				UserInfo ll=new UserInfo();
				//BankInfo bb=obtainBankInfoById(rr.getString("bank_name"));
				
				ll.setId(rr.getString("id"));
				ll.setPromotorId(rr.getString("promotor_id"));
				ll.setFirst_applicantName(promotorsNameById(rr.getString("promotor_id")));
				ll.setEntryDate(rr.getDate("income_date"));
				ll.setEntryDateStr(sf.format(ll.getEntryDate()));
				ll.setAmount(rr.getDouble("amount"));
				ll.setStatus("Promotor Capital");
				ll.setPayMode(rr.getString("payment_mode"));
				if(ll.getPayMode().equals("rtgs")||ll.getPayMode().equals("rtgs"))
				{
					ll.setPayMode("NEFT/RTGS/IMPS");
				}
				ll.setBank_name(rr.getString("bank_name"));
				ll.setChq_ddNo(rr.getString("chq_dd_no"));
				ll.setChq_ddDate(rr.getDate("chq_dd_date"));
				ll.setChq_ddDateStr(sf.format(ll.getChq_ddDate()));
				
				if(ll.getChq_ddDate().after(tdyDt))
				{
					ll.setDisable(true);
				}
				ll.setSubmittedToBank(rr.getString("transfer_to_bank"));
				//ll.setTransferredToBankName(bb.getBank_name()+"-"+bb.getAcc_no());
				
				
				list.add(ll);			
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}
	
	public ArrayList<DueDebitInfo> pendingReturnPromotorsCapitalList(int branchId) 
	{
		ArrayList<DueDebitInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from return_promotors_capital where chequeStatus='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				DueDebitInfo info=new DueDebitInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("transfer_to_bank"),conn);
				info.setSno(++i);
				info.setId(rr.getString("id"));
				info.setChequeDate(rr.getDate("chq_dd_date"));
				if(info.getChequeDate().after(tdyDt))
				{
					info.setDisable(true);
					
				}
				info.setStrChequeDate(sf.format(rr.getDate("chq_dd_date")));
				info.setBankId(rr.getString("transfer_to_bank"));
				info.setBankName(bankNameById(rr.getString("transfer_to_bank")));
				//info.setBankBranch(rr.getString("bankBranch"));
				info.setChequeNo(rr.getString("chq_dd_no"));
				info.setAccNo(bb.getAcc_no());
				info.setItem_loan_fdr(promotorsNameById(rr.getString("promotor_id")));
				info.setPromotorId(rr.getString("promotor_id"));
				info.setType("Return Promotor Capital");
				info.setAmount(rr.getString("amount"));

				list.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}

	public String promotorsNameById(String string) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select name from promotors where id='"+string+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("name");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}
	
	public String promotorsIdByName(String string) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select id from promotors where name='"+string+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("id");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}
	
	public ArrayList<DsaListInfo> viewPromotors(int branchId) 
	{
		int j=1;
		ArrayList<DsaListInfo> list = new ArrayList<>();
		try (Connection cnt = DataBaseConnection.JAVAConnection();){
			Statement stt = cnt.createStatement();
			String query = "select * from promotors where status='active'";
			ResultSet rr = stt.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				DsaListInfo obj = new DsaListInfo();
				
				obj.setCode(rr.getString("code"));
				obj.setSno(j);
				obj.setAddress(rr.getString("address"));
				obj.setMobile(rr.getString("mobile"));
				obj.setName(rr.getString("name"));
				obj.setId(rr.getString("id"));
				obj.setOpenDate(rr.getDate("open_date"));
				obj.setInterest(rr.getDouble("interest")); 
				obj.setAmount(rr.getDouble("amount"));
				if(rr.getDouble("amount")>0)
				{
					obj.setDisBtn(true);
				}
				if(rr.getDate("open_date")!=null)
				{
					obj.setOpenDateStr(sf.format(rr.getDate("open_date")));
				}
				
				list.add(obj);
			}
			
			
		} catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public DsaListInfo selectedPromotorDetail(String selectedPromotor) 
	{
		DsaListInfo obj = new DsaListInfo();
		try (Connection cnt = DataBaseConnection.JAVAConnection();)
		{
			Statement stt = cnt.createStatement();
			String query = "select * from promotors where status='active' and id='"+selectedPromotor+"' ";
			ResultSet rr = stt.executeQuery(query);
			if(rr.next())
			{
				obj.setCode(rr.getString("code"));
				obj.setAddress(rr.getString("address"));
				obj.setMobile(rr.getString("mobile"));
				obj.setName(rr.getString("name"));
				obj.setId(rr.getString("id"));
				obj.setOpenDate(rr.getDate("open_date"));
				obj.setInterest(rr.getDouble("interest")); 
				obj.setAmount(rr.getDouble("amount"));
				obj.setOpenDateStr(sf.format(rr.getDate("open_date")));
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return obj;
	}


	
	private double returnAmountPromotorWise(String promotorId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from return_promotors_capital where promotor_id='"+promotorId+"' and chequeStatus='cleared' and status='active' "; 
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	
	
	public ArrayList<LoanInfo> pendingAllLoanListForLoanDisburse(int branchId,String loanType, String center) 
	{
		int count=1;
		String query="";
		DbYashwant dby= new DbYashwant();
		DataBaseMethodsRaviK dbrk = new DataBaseMethodsRaviK();
		ArrayList<LoanInfo> list=new ArrayList<>();
		
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
			Statement stt=conn.createStatement();
			if(loanType.equals("grouploan"))
			{
				if(center.equalsIgnoreCase("-1"))
				{
					query="select * from "+loanType+" inner join shareholder_info where shareholder_info.shareholderno="+loanType+".teamLeader and  "+loanType+".status='Approve' and paidStatus='unpaid' and shareholder_info.branch_id='"+branchId+"' order by "+loanType+".id desc";
				}
				else
				{
					query="select * from "+loanType+" inner join shareholder_info where shareholder_info.shareholderno="+loanType+".teamLeader and "+loanType+".status='Approve' and paidStatus='unpaid' and "+loanType+".center='"+center+"' and shareholder_info.branch_id='"+branchId+"' order by "+loanType+".id desc";
				}
			}
			else
			{
				query="select * from "+loanType+" inner join shareholder_info where shareholder_info.shareholderno="+loanType+".shareholderno and  "+loanType+".status='Approve' and paidStatus='unpaid' and shareholder_info.branch_id='"+branchId+"' order by "+loanType+".id desc";
			}
			System.out.println(query);
			ResultSet ss=stt.executeQuery(query);
			while(ss.next())
			{
				LoanInfo info=new LoanInfo();
				boolean check=false;
				
				
				
				if(loanType.equals("grouploan"))
				{
					info.setShareHolderNo(ss.getString("teamLeader"));
					info.setLoanNo(ss.getString("loanNo"));
					info.setSubLoanNo(ss.getString("sub_loan_no"));
					check=checkDisburse(info.getSubLoanNo(), conn);
					
					String previousLoan = dbrk.selectLoanPreLoanNo(conn, info.getSubLoanNo(), loanType, info.getShareHolderNo());
					info.setPreviousLoan(previousLoan);
				}
				else
				{
					info.setShareHolderNo(ss.getString("shareholderno"));
					info.setLoanNo(ss.getString("loanNo"));
					info.setSubLoanNo("");
					check=checkDisburse(info.getLoanNo(), conn);
					
					String previousLoan = dbrk.selectLoanPreLoanNo(conn, info.getLoanNo(), loanType, info.getShareHolderNo());
					info.setPreviousLoan(previousLoan);
				}
				
				if(loanType.equals("secure_loan"))
				{
					info.setBillAmount(ss.getDouble("mob_bill_amount"));
					info.setDownPayment(ss.getDouble("mob_down_payment"));
					info.setImeiNoI(ss.getString("mob_imei_no_1"));
					info.setImeiNoII(ss.getString("mob_imei_no_2"));
					info.setDealer(ss.getString("mob_dealer"));
					info.setProduct(ss.getString("mob_product"));
					System.out.println("info sec..."+ss.getString("security_type"));
					info.setSecurityype(ss.getString("security_type"));
					
					info.setDealerName(dby.selectDealer(conn, ss.getString("mob_dealer")));	
				}
				
				if(check==true)
				{
					info.setColorStatus("done");
				}
				else
				{
					info.setColorStatus("pending");
				}
				
				//UserInfo uu=userInfoByShareHolderNo(info.getShareHolderNo(), conn);
				
				info.setLoanNo(ss.getString("loanNo"));
				info.setApplicantName(ss.getString("first_applicantName"));
				info.setFatherHusbandName(ss.getString("father_husband_name"));
				info.setId(ss.getString("id"));
				
				info.setAddress(ss.getString("address"));
				String arr[]=info.getApplicantName().split("\\s+");
				info.setNickName(arr[0]);
				info.setBankAccNo(ss.getString("bank_accountNo"));
				
				if("PUNJAB NATIONAL BANK".equalsIgnoreCase(ss.getString("bank_name")))
				{
					info.setNetwork("PMT");
				}
				else
				{
					info.setNetwork("NFT");
				}
				
				info.setBankIfsc(ss.getString("bank_ifsc"));
				
//				if(ss.getString("loanNo").contains("R"))
//				{
//					info.setLoanAmount(ss.getString("increase_amount"));
//				}
//				else // comment on 01 nov due RK RISE NIDHI
				{
					info.setLoanAmount(ss.getString("loanAmount"));
				}
				
				info.setFileCharge(ss.getString("filecharge"));
				info.setInsuranceFee(ss.getString("insurance_fee"));
				
				if(loanType.equalsIgnoreCase("personalloan") || loanType.equals("grouploan"))
				{
					info.setProcessingCharge(ss.getDouble("processing_charge"));
					System.out.println(ss.getDouble("processing_charge")+"fdji");
				}
				
				info.setLoanInterest(ss.getString("interest"));
				info.setLoanTerm(ss.getString("terms"));
				info.setInstallAmount(ss.getDouble("emi"));
				info.setLoanType(loanType);
				info.setRequestDate(ss.getDate("requestDate"));
				info.setApprovalDate(ss.getDate("approvalDate"));
				info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
				info.setFrequency(String.valueOf(ss.getInt("frequency")));
				double chkAmt=0;
				if(loanType.equalsIgnoreCase("grouploan"))
				{
					chkAmt=checkLoanDisburse(info.getSubLoanNo(), conn);
				}
				else
				{
					chkAmt=checkLoanDisburse(info.getLoanNo(), conn);
				}
				
				/*if(loanType.equals("grouploan"))
				{
					check=checkDisburse(info.getSubLoanNo(), conn);
				}
				else
				{
					check=checkDisburse(info.getLoanNo(), conn);
				}*/
				// Extra Method
				
				if(chkAmt>0)
				{
					info.setColorStatus("done");
				}
				else
				{
					info.setColorStatus("pending");
				}
				
				// for set pending status of Loan
				if(chkAmt!=0)
				{
					info.setDisable(true);
				}
				
				//System.out.println(info.getLoanAmount());
				if(chkAmt<Double.valueOf(info.getLoanAmount()))
				{
					info.setSno(count++);
					info.setLoanAmount(String.valueOf(Double.valueOf(info.getLoanAmount())-chkAmt));
					list.add(info);
				}
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	


	private boolean checkDisburse(String loanNo, Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select * from debit_loan where loanNo='"+loanNo+"' and status='cleared' ";
			//System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return false;
	}

	public double checkLoanDisburse(String loanNo, Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from debit_loan where loanNo='"+loanNo+"' and status='cleared'";
		//	// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return 0;
	}

	public UserInfo savingAccountDetailByAccountNo(String savingAccountNo) 
	{
		UserInfo ll=new UserInfo();
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from savingaccount INNER JOIN shareholder_info on savingaccount.shareHolderNo=shareholder_info.shareholderno where savingaccount.accountNo='"+savingAccountNo+"'";
			ResultSet rr=st.executeQuery(query);
			if(rr.next())
			{
				ll.setId(rr.getString("id"));
				ll.setShareHolderNo(rr.getString("savingaccount.shareHolderNo"));
				ll.setFirst_applicantName(rr.getString("shareholder_info.first_applicantName"));
				ll.setAccountNo(rr.getString("accountNo"));
				ll.setAmount(rr.getDouble("amount"));
				ll.setEntryDate(rr.getDate("openDate"));
				ll.setEntryDateStr(sf.format(ll.getEntryDate()));
				ll.setInterest(rr.getDouble("interest"));
				ll.setAccCloseCharge(rr.getDouble("accCloseCharge"));
				ll.setMinBal(rr.getDouble("minBal"));
				ll.setMinDaysForClose(rr.getInt("minDayForClose"));
				ll.setPayoutDate(rr.getDate("updateDate"));
				ll.setAccount_status(rr.getString("accountStatus"));
				if(ll.getPayoutDate()!=null)
				{
					ll.setStrPayOutDate(sf.format(ll.getPayoutDate()));
				}
				else
				{
					ll.setStrPayOutDate("");
				}
				
				if(ll.getAccount_status().equals("open"))
				{
					ll.setDisableDelete(false);
					ll.setDisableClose(false);
				}
				else if(ll.getAccount_status().equals("inactive") || ll.getAccount_status().equals("close"))
				{
					ll.setDisableDelete(true);
					ll.setDisableClose(true);
				}
				
				
				
				ll.setPaidAmount(rr.getDouble("paidAmount"));
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return ll;
	}
	
	public UserInfo savingAccountDetailByShareHolderNo(String shNo) 
	{
		UserInfo ll=new UserInfo();
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from savingaccount INNER JOIN shareholder_info on savingaccount.shareHolderNo=shareholder_info.shareholderno where savingaccount.shareHolderNo='"+shNo+"' and savingaccount.accountStatus='open'";
			//System.out.println(query);
			ResultSet rr=st.executeQuery(query);
			if(rr.next())
			{
				ll.setId(rr.getString("id"));
				ll.setAccountNo(rr.getString("accountNo"));
				ll.setShareHolderNo(rr.getString("savingaccount.shareHolderNo"));
				ll.setFirst_applicantName(rr.getString("shareholder_info.first_applicantName"));
				ll.setFather_husband_name(rr.getString("shareholder_info.father_husband_name"));
				ll.setContactNo(rr.getString("shareholder_info.mobile"));
				ll.setAddress(rr.getString("shareholder_info.address"));
				ll.setAmount(rr.getDouble("amount"));
				ll.setEntryDate(rr.getDate("openDate"));
				ll.setEntryDateStr(sf.format(ll.getEntryDate()));
				ll.setInterest(rr.getDouble("interest"));
				ll.setAccCloseCharge(rr.getDouble("accCloseCharge"));
				ll.setMinBal(rr.getDouble("minBal"));
				ll.setMinDaysForClose(rr.getInt("minDayForClose"));
				ll.setPayoutDate(rr.getDate("updateDate"));
				ll.setAccount_status(rr.getString("accountStatus"));
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return ll;
	}

	public double tdsPercentFormTable(String string) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from tds_detail where pan_card='"+string+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("tds_percent");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	///// instant borrow and loan method
	
	public int nextNo(String string,int branchId)
	{
		int account = 0;
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq = "select max(convert(no,decimal)) as num from borrower_lender where type='"+string+"'";
			qq= selectQueWithBranch(qq,branchId)+"order by id desc limit 1";
			ResultSet rs = st.executeQuery(qq);
			if (rs.next())
			{
				account=rs.getInt("num");
				account=account+1;
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return account;
	}
	
	
	public ArrayList<SelectItem> allBorrowerOrLenderList(int branchId,String string) 
	{
		ArrayList<SelectItem> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from borrower_lender where type='"+string+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				SelectItem info=new SelectItem();
				
				info.setLabel(rr.getString("no")+" - "+rr.getString("name"));
				info.setValue(rr.getString("id"));
				
				list.add(info);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
 		return list;
	}
	
	
	/*public ArrayList<SelectItem> allBorrowerOrLenderList(String string) 
	{
		ArrayList<SelectItem> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from borrower_lender where type='"+string+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				SelectItem info=new SelectItem();
				
				info.setLabel(rr.getString("no")+" - "+rr.getString("name"));
				info.setValue(rr.getString("id"));
				
				list.add(info);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
 		return list;
	}*/


	public int addBorrowerLenderName(int no, String name, String string,int branchId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="insert into borrower_lender(no, name, type,branch_id) values('"+no+"','"+name+"','"+string+"','"+branchId+"')";
			//// // // //System.out.println(query);
			int i=st.executeUpdate(query);
			if(i>0){
			dataInsertInQueryTable(query, conn);
			return i;
		}}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}


	public int addInstantLoan(int branchId,String selectedName, double amount,
			String description, Date borrowDate, String type, String chequeNo, Date chequeDate, String bankName, String bankBranch, String paymentMode) 
	{
		Timestamp tt=new Timestamp(borrowDate.getTime());
		String status="";
		if(paymentMode.equalsIgnoreCase("Cash"))
		{
			status="cleared";
			bankName="N/A";
		}
		else
		{
			status="uncleared";
		}
		
		Timestamp cDate=null;
		if(chequeDate!=null)
		{
			cDate=new Timestamp(chequeDate.getTime());
		}
		String query="insert into lender_record(lender_id, amount, description, status, lender_date, chq_dd_no, chq_dd_date, bank_name, bank_branch, chequeStatus, payment_mode, branch_id) "
				+ "values(?,?,?,?,?,?,?,?,?,?,?,?)";
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			PreparedStatement st=conn.prepareStatement(query);
			st.setString(1, selectedName);
			st.setDouble(2, amount);
			st.setString(3, description);
			st.setString(4, type);
			st.setTimestamp(5,new Timestamp(borrowDate.getTime()));
			st.setString(6, chequeNo);
			st.setTimestamp(7, cDate);
			st.setString(8,bankName);
			st.setString(9,bankBranch);
			st.setString(10, status);
			st.setString(11, paymentMode);
			st.setInt(12, branchId);
			int i=st.executeUpdate();
			if(i>0){
			dataInsertInQueryTable(String.valueOf(st), conn);
			return i;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}


	public int checkInstantLoanAmount(int branchId,String selectedName, String string) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select sum(amount) from lender_record where status='"+string+"' and chequeStatus='cleared' and lender_id='"+selectedName+"' ";
			//// // // //System.out.println(query);
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			if(rr.next())
			{
				return rr.getInt("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}


	public ArrayList<DueDebitInfo> pendingInstantLoanList(int branchId) 
	{
		ArrayList<DueDebitInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from lender_record where status='credit' and chequeStatus='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				DueDebitInfo info=new DueDebitInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("bank_name"),conn);
				info.setSno(++i);
				info.setId(rr.getString("id"));
				info.setChequeDate(rr.getDate("chq_dd_date"));
				if(info.getChequeDate()!=null && info.getChequeDate().after(tdyDt))
				{
					info.setDisable(true);
				}
				info.setStrChequeDate(sf.format(rr.getDate("chq_dd_date")));
				info.setBankId(rr.getString("bank_name"));
				info.setBankName(bankNameById(rr.getString("bank_name")));
				//info.setBankBranch(rr.getString("bankBranch"));
				info.setChequeNo(rr.getString("chq_dd_no"));
				info.setAccNo(bb.getAcc_no());
				info.setItem_loan_fdr(borrowerLenderNameById(rr.getString("lender_id")));
				info.setType("Instant Loan");
				//info.setShareholderno(rr.getString("shareholderno"));
				info.setAmount(rr.getString("amount"));
				info.setEntryDateStr(sf.format(rr.getDate("lender_date")));
				info.setPaymentMode(rr.getString("payment_mode"));
				if(info.getPaymentMode().equals("rtgs") || info.getPaymentMode().equals("neft"))
				{
					info.setPaymentMode("RTGS/NEFT/IMPS");
				}
				
				list.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}


	public ArrayList<UserInfo> pendingReturnInstantLoanList(int branchId) 
	{
		ArrayList<UserInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from lender_record where status='debit' and chequeStatus='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				UserInfo ll=new UserInfo();
				//BankInfo bb=obtainBankInfoById(rr.getString("transfer_to_bank"));
				
				ll.setId(rr.getString("id"));
				//ll.setAccountNo(rr.getString("item"));
				ll.setFirst_applicantName(borrowerLenderNameById(rr.getString("lender_id")));
				ll.setEntryDate(rr.getDate("lender_date"));
				ll.setEntryDateStr(sf.format(ll.getEntryDate()));
				ll.setAmount(rr.getDouble("amount"));
				ll.setStatus("Return Instant Loan");
				ll.setPayMode(rr.getString("payment_mode"));
				if(ll.getPayMode().equals("rtgs")||ll.getPayMode().equals("rtgs"))
				{
					ll.setPayMode("NEFT/RTGS/IMPS");
				}
				ll.setBank_name(rr.getString("bank_name"));
				ll.setChq_ddNo(rr.getString("chq_dd_no"));
				ll.setChq_ddDate(rr.getDate("chq_dd_date"));
				ll.setChq_ddDateStr(sf.format(ll.getChq_ddDate()));
				
				if(ll.getChq_ddDate().after(tdyDt))
				{
					ll.setDisable(true);
				}
				ll.setSubmittedToBank(rr.getString("bank_name"));
				//ll.setTransferredToBankName(bb.getBank_name()+"-"+bb.getAcc_no());
				
				
				list.add(ll);			
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}


	public int addInstantBorrow(String selectedName, double amount,
			String description, Date borrowDate, String type,
			String chequeNo, Date chequeDate, String bankName,
			String bankBranch, String paymentMode,int branchId) 
	{
		Timestamp tt=new Timestamp(borrowDate.getTime());
		String status="";
		if(paymentMode.equalsIgnoreCase("Cash"))
		{
			status="cleared";
			bankName="N/A";
		}
		else
		{
			status="uncleared";
		}
		
		Timestamp cDate=null;
		if(chequeDate!=null)
		{
			cDate=new Timestamp(chequeDate.getTime());
		}
		String query="insert into borrower_record(borrower_id, amount, description, status, borrow_date, chq_dd_no, chq_dd_date, bank_name, bank_branch, chequeStatus, payment_mode,branch_id) "
				+ "values(?,?,?,?,?,?,?,?,?,?,?,?)";
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			PreparedStatement st=conn.prepareStatement(query);
			st.setString(1, selectedName);
			st.setDouble(2, amount);
			st.setString(3, description);
			st.setString(4, type);
			st.setTimestamp(5,new Timestamp(borrowDate.getTime()));
			st.setString(6, chequeNo);
			st.setTimestamp(7, cDate);
			st.setString(8,bankName);
			st.setString(9,bankBranch);
			st.setString(10, status);
			st.setString(11, paymentMode);
			st.setInt(12, branchId);
			
			int i=st.executeUpdate();
			if(i>0){
			dataInsertInQueryTable(String.valueOf(st), conn);
			return i;
		}}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}


	public int checkInstantBorrowAmount(String selectedName, String string,int branchId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select sum(amount) from borrower_record where status='"+string+"' and chequeStatus='cleared' and borrower_id='"+selectedName+"' ";
		//	// // // //System.out.println(query);
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			if(rr.next())
			{
				return rr.getInt("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}


	public ArrayList<UserInfo> pendingInstantBorrowList(int branchId) 
	{
		ArrayList<UserInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from borrower_record where status='credit' and chequeStatus='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				UserInfo ll=new UserInfo();
				//BankInfo bb=obtainBankInfoById(rr.getString("bank_name"));
				
				ll.setId(rr.getString("id"));
				ll.setFirst_applicantName(borrowerLenderNameById(rr.getString("borrower_id")));
				ll.setEntryDate(rr.getDate("borrow_date"));
				ll.setEntryDateStr(sf.format(ll.getEntryDate()));
				ll.setAmount(rr.getDouble("amount"));
				ll.setStatus("Instant Borrow");
				ll.setPayMode(rr.getString("payment_mode"));
				if(ll.getPayMode().equals("rtgs")||ll.getPayMode().equals("rtgs"))
				{
					ll.setPayMode("NEFT/RTGS/IMPS");
				}
				ll.setBank_name(rr.getString("bank_name"));
				ll.setChq_ddNo(rr.getString("chq_dd_no"));
				ll.setChq_ddDate(rr.getDate("chq_dd_date"));
				ll.setChq_ddDateStr(sf.format(ll.getChq_ddDate()));
				
				if(ll.getChq_ddDate().after(tdyDt))
				{
					ll.setDisable(true);
				}
				ll.setSubmittedToBank(rr.getString("bank_name"));
				//ll.setTransferredToBankName(bb.getBank_name()+"-"+bb.getAcc_no());
				
				
				list.add(ll);			
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}


	public ArrayList<DueDebitInfo> pendingReturnInstantBorrowList(int branchId) 
	{
		ArrayList<DueDebitInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from borrower_record where status='debit' and chequeStatus='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				DueDebitInfo info=new DueDebitInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("bank_name"),conn);
				info.setSno(++i);
				info.setId(rr.getString("id"));
				info.setChequeDate(rr.getDate("chq_dd_date"));
				if(info.getChequeDate().after(tdyDt))
				{
					info.setDisable(true);
				}
				info.setStrChequeDate(sf.format(rr.getDate("chq_dd_date")));
				info.setBankId(rr.getString("bank_name"));
				info.setBankName(bankNameById(rr.getString("bank_name")));
				//info.setBankBranch(rr.getString("bankBranch"));
				info.setChequeNo(rr.getString("chq_dd_no"));
				info.setAccNo(bb.getAcc_no());
				info.setItem_loan_fdr(borrowerLenderNameById(rr.getString("borrower_id")));
				info.setType("Return Instant Borrow");
				//info.setShareholderno(rr.getString("shareholderno"));
				info.setAmount(rr.getString("amount"));
				info.setEntryDateStr(sf.format(rr.getDate("borrow_date")));
				info.setPaymentMode(rr.getString("payment_mode"));
				if(info.getPaymentMode().equals("rtgs") || info.getPaymentMode().equals("neft"))
				{
					info.setPaymentMode("RTGS/NEFT/IMPS");
				}
				
				list.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}

	public ArrayList<DueDebitInfo> pendingReturnDSAList(int branchId) 
	{
		ArrayList<DueDebitInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from return_dsa where chequeStatus='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				DueDebitInfo info=new DueDebitInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("bank_name"),conn);
				info.setSno(++i);
				info.setId(rr.getString("id"));
				info.setChequeDate(rr.getDate("chq_dd_date"));
				if(info.getChequeDate().after(tdyDt))
				{
					info.setDisable(true);
				}
				info.setStrChequeDate(sf.format(rr.getDate("chq_dd_date")));
				info.setBankId(rr.getString("bank_name"));
				info.setBankName(bankNameById(rr.getString("bank_name")));
				//info.setBankBranch(rr.getString("bankBranch"));
				info.setChequeNo(rr.getString("chq_dd_no"));
				info.setAccNo(bb.getAcc_no());
				info.setItem_loan_fdr(dsaNameById(rr.getString("code"),conn));
				info.setType("Return DSA Comm.");
				//info.setShareholderno(rr.getString("shareholderno"));
				info.setAmount(rr.getString("amount"));
				info.setEntryDateStr(sf.format(rr.getDate("pay_date")));
				info.setPaymentMode(rr.getString("payment_mode"));
				if(info.getPaymentMode().equals("rtgs") || info.getPaymentMode().equals("neft"))
				{
					info.setPaymentMode("RTGS/NEFT/IMPS");
				}
				
				list.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}

	public ArrayList<DueDebitInfo> pendingSalPayoutList(int branchId) 
	{
		ArrayList<DueDebitInfo> list=new ArrayList<>();
		
		int i=0;
		Date tdyDate=new Date();
		Timestamp tdyDt=new Timestamp(tdyDate.getTime());
		tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from salary_ledger where chequeStatus='uncleared'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				DueDebitInfo info=new DueDebitInfo();
				BankInfo bb=obtainBankInfoById(rr.getString("bank_name"),conn);
				info.setSno(++i);
				info.setId(rr.getString("id"));
				info.setChequeDate(rr.getDate("chq_dd_date"));
				
				if(info.getChequeDate()!= null)
				{	
					info.setStrChequeDate(sf.format(rr.getDate("chq_dd_date")));
					if(info.getChequeDate().after(tdyDt))
					{
						info.setDisable(true);
					}	
				}
			

				info.setBankId(rr.getString("bank_name"));
				info.setBankName(bankNameById(rr.getString("bank_name")));
				//info.setBankBranch(rr.getString("bankBranch"));
				info.setChequeNo(rr.getString("chq_dd_no"));
				info.setAccNo(bb.getAcc_no());
				info.setItem_loan_fdr(employeeNameByUsername(rr.getString("empId")));
				info.setType("Employee Salary Payout");
				//info.setShareholderno(rr.getString("shareholderno"));
				info.setAmount(rr.getString("amount"));
				info.setEntryDateStr(sf.format(rr.getDate("payDate")));
				info.setPaymentMode(rr.getString("payment_mode"));
				if(info.getPaymentMode().equals("rtgs") || info.getPaymentMode().equals("neft"))
				{
					info.setPaymentMode("RTGS/NEFT/IMPS");
				}
				
				list.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return list;
	}


	public String borrowerLenderNameById(String id) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select name from borrower_lender where id='"+id+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("name");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}
	
	public int deleteInstantBorrow(BorrowerLenderInfo selectedRow) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="delete from borrower_record where id='"+selectedRow.getId()+"' ";
			int i=st.executeUpdate(query);
			if(i>0){
			dataInsertInQueryTable(query, conn);
			return i;
			}
			}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public int deleteInstantLoan(BorrowerLenderInfo selectedRow) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="delete from lender_record where id='"+selectedRow.getId()+"' ";
			int i=st.executeUpdate(query);
			if(i>0){
			dataInsertInQueryTable(query, conn);
			return i;
		}}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public double emiPaidAmountByEmiNo(String loanNo, int emiNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount) from loanpayment where loanNo='"+loanNo+"' and emi_no='"+emiNo+"' and receipt_status='approved' and chequeStatus='cleared' ";
			//// // // //System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}	
		return 0;
	}
	
	public double emiPaidInterestByEmiNo(String loanNo, int emiNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(interestAmount) from loanpayment where loanNo='"+loanNo+"' and emi_no='"+emiNo+"' and receipt_status='approved' and chequeStatus='cleared' ";
			//// // // //System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(interestAmount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	public double totalPrincipalPaidByLoanNo(String loanNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount), sum(interestAmount) from loanpayment where loanNo='"+loanNo+"' and receipt_status='approved' and chequeStatus='cleared' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return Double.parseDouble(df.format(rr.getDouble("sum(amount)")-rr.getDouble("sum(interestAmount)")));
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public double totalIntrestPaidByLoanNo(String loanNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(interestAmount) from loanpayment where loanNo='"+loanNo+"' and receipt_status='approved' and chequeStatus='cleared' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return Double.parseDouble(df.format(rr.getDouble("sum(interestAmount)")));
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public ArrayList<LoanInfo> checkEmiPaidDetailByloanNo(String loanNo) 
	{
		double total=0;
		int count=1;
		ArrayList<LoanInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from loanpayment where loanNo='"+loanNo+"' and chequeStatus='cleared' and receipt_status='approved' order by pay_date asc ";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				LoanInfo ll=new LoanInfo();
				
				ll.setSno(count++);
				ll.setEmiPaidDate(rr.getDate("pay_date"));
				ll.setEmiPaidDateStr(sf.format(ll.getEmiPaidDate()));
				if(rr.getString("emi_no").equalsIgnoreCase("-1"))
				{
					ll.setEmiNo("Loan Closed");
				}
				else
				{
					ll.setEmiNo("EMI "+rr.getString("emi_no"));
				}
				ll.setPaidAmount(rr.getDouble("amount"));
				total+=ll.getPaidAmount();
				ll.setBalance(total);
				ll.setReceiptNo(rr.getString("receipt_no"));
				ll.setRemark(rr.getString("remark"));
			
				list.add(ll);	
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	public ArrayList<LoanInfo> checkEmiPaidDetailByloanNoWithoutDateGrouping(String loanNo) 
	{
		double total=0;
		int count=1;
		ArrayList<LoanInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq= "SELECT emi_no, SUM(amount) AS total_amount, " 
					+             "	MAX(pay_date) AS pay_date, "
					+             "MAX(receipt_no) AS receipt_no, " 
					+             "MAX(user_id) AS user_id ,"
					+             "MAX(remark) AS remark ,"
					+             "MAX(pay_mode) AS pay_mode ,"
					+             "MAX(entry_date) AS entry_date "
					+             "FROM loanpayment " 
					+             "WHERE loanNo='"+loanNo+"' AND chequeStatus='cleared' AND receipt_status='approved' "
					+             "GROUP BY emi_no " 
					+             "ORDER BY pay_date ASC";
					
			////System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				LoanInfo ll=new LoanInfo();
				
				ll.setSno(count++);
				ll.setEmiPaidDate(rr.getDate("pay_date"));
				ll.setEmiPaidDateStr(sf.format(ll.getEmiPaidDate()));
				if(rr.getString("emi_no").equalsIgnoreCase("-1"))
				{
					ll.setEmiNo("Loan Closed");
				}
				else
				{
					ll.setEmiNo("EMI "+rr.getString("emi_no"));
				}
				ll.setPaidAmount(rr.getDouble("total_amount"));
				total+=ll.getPaidAmount();
				ll.setBalance(total);
				ll.setReceiptNo(rr.getString("receipt_no"));
				ll.setRemark(rr.getString("remark"));
				ll.setPaymentMode(rr.getString("pay_mode"));
				ll.setUserId(rr.getString("user_id"));
				ll.setStrEntryDateTime(rr.getString("entry_date"));
			
				list.add(ll);	
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public ArrayList<InstallmentInfo> checkRdFdPaidDetailByUserNo(String user_no) 
	{
		double total=0;
		int count=1;
		ArrayList<InstallmentInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from payment_receipt where user_no='"+user_no+"' and chequeStatus='cleared' and receipt_status='approved' order by date asc ";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				InstallmentInfo ll=new InstallmentInfo();
				
				ll.setSno(count++);
				ll.setEmiPaidDate(rr.getDate("date"));
				ll.setEmiPaidDateStr(sf.format(ll.getEmiPaidDate()));
				ll.setPaidAmount(rr.getDouble("amount"));
				if(ll.getPaidAmount()==0)
				{
					ll.setPaidAmount(rr.getDouble("credit_amount"));
				}
				total+=ll.getPaidAmount();
				ll.setTot_sum(total);
				ll.setReceiptNo(rr.getString("receipt_no"));
				
				list.add(ll);	
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public ArrayList<SelectItem> loanTypeList(Connection conn)
	{
		ArrayList<SelectItem> list=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;

		try
		{
			st=conn.createStatement();
			String qq="select * from loan_table where loan_permission='true'";
			rr=st.executeQuery(qq);
			while(rr.next())
			{
				SelectItem ss=new SelectItem();
				
				ss.setLabel(rr.getString("loan_label"));
				ss.setValue(rr.getString("loan_type"));
				
				list.add(ss);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}

finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return list;
	}

	public String findShareholderPanCardNo(String shareHolderNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select PAN from shareholder_info where shareholderno='"+shareHolderNo+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("PAN");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}

	/*public ArrayList<String> allApproveLoanNo(String loanType) 
	{
		ArrayList<String> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select loanNo from "+loanType+" where status='Approve' and paidStatus='unpaid' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				list.add(rr.getString("loanNo"));
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}*/

	public ArrayList<LoanInfo> penaltyOfallApproveLoanNo(int branchId,String loanType) 
	{
		int count=1;
		ArrayList<LoanInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from "+loanType+" where status='Approve' and paidStatus='unpaid' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				LoanInfo ll=new LoanInfo();
				
				String shno="", loanNo="";
				double penaltyAmount=0,penaltyPaid=0,penaltyDue=0;
				
				if(loanType.equals("grouploan"))
				{
					shno=rr.getString("teamLeader");
					loanNo=rr.getString("sub_loan_no");
				}
				else
				{
					loanNo=rr.getString("loanNo");
					shno=rr.getString("shareholderno");
				}
				
				
				penaltyAmount=calculatePenaltyAndChequeBounceCharges(loanNo, "Penalty", loanType, conn);
				penaltyPaid=totalPaidPenaltyAndChequeBounceCharges(loanNo, "Penalty", conn);
				double penaltyDiscount=discountOnPenaltyByLoanNo(loanNo);
				penaltyDue=penaltyAmount-(penaltyPaid+penaltyDiscount);
				
				
				
				ll.setSno(count++);
				ll.setShareHolderNo(shno);
				ll.setLoanNo(loanNo);
				ll.setApplicantName(firstApplicantNameBySHNo(ll.getShareHolderNo(),conn));
				ll.setPenalty(Double.parseDouble(df.format(penaltyAmount)));
				ll.setPenaltyPaid(Double.parseDouble(df.format(penaltyPaid)));
				ll.setPenaltyDue(Double.parseDouble(df.format(penaltyDue)));
				ll.setPenaltyDiscount(penaltyDiscount);
				
				list.add(ll);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	

	public int checkReleaseLoanAmount(String loanNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select sum(amount) from debit_loan where loanNo='"+loanNo+"' and status='cleared' ";
			ResultSet rr=st.executeQuery(query);
			if(rr.next())
			{
				return rr.getInt("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public int addTdsDetail(int branchId,ArrayList<FixedAssetsInfo> list,String tdsBasis) 
	{
		int i=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			for(FixedAssetsInfo ff: list)
			{
				String qq="insert into tds_detail(tds_percent, pan_card, tds_basis,branch_id) values('"+ff.getTdsPercent()+"','"+ff.getPanCard()+"','"+tdsBasis+"','"+branchId+"')";
			//	// // // //System.out.println(qq);
				int z=st.executeUpdate(qq);
				if(z>0)
				{
					dataInsertInQueryTable(qq, conn);
					i=1;
				}
			}
			
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}

	public ArrayList<FixedAssetsInfo> viewTdsDetail(int branchId) 
	{
		int count=1;
		ArrayList<FixedAssetsInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from tds_detail";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				FixedAssetsInfo ff=new FixedAssetsInfo();
				
				ff.setSno(count++);
				ff.setPanCard(rr.getString("pan_card"));
				ff.setTdsPercent(rr.getDouble("tds_percent"));
				ff.setTdsBasis(rr.getString("tds_basis"));
				
				list.add(ff);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	public String checkTdsBasis(int branchId,Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select tds_basis from tds_detail";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getString("tds_basis");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}
	
	public String dsaAccountNo(int branchId,Connection conn) 
	{
		String account="";

		Statement st=null;
		ResultSet rs=null;

		try 
		{
	        st = conn.createStatement();
			String qq = "select code from dsa order by id desc limit 1";
			 rs = st.executeQuery(qq);
			int accLen=accountNoLengthFromMasterTable("DSA",branchId);
			if (rs.next()) 
			{
				String no=rs.getString("code");
				account=String.valueOf(Integer.parseInt(no.substring(no.length() - 4))+ 1);
			}
			String initial=accountNoInitialFromMasterTable(branchId,"DSA");
			account=initial+commonNo(account,accLen);
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}


		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return account;
	}

	public int adddsa(String code1, String name, String address, String mobile, String commissionType, double commissionValue,int branchId,Connection conn) 
	{

		Statement stt=null;
		try 
		{
			 stt = conn.createStatement();
			String query ="insert into dsa (code, name, mobile, address, status,commission_type,commission_value,branch_id) "
					+ "values('"+code1+"','"+name+"','"+mobile+"','"+address+"','active','"+commissionType+"','"+commissionValue+"','"+branchId+"')";
			 int er = stt.executeUpdate(query);
			 if(er>0)
			 {
				 dataInsertInQueryTable(query, conn);
				 return er;
			 }
			
		} catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	public ArrayList<DsaListInfo> viewAllDsa(int branchId,Connection conn) 
	{
		int j=1;
		ArrayList<DsaListInfo> list = new ArrayList<>();
		try
		{
			Statement stt = conn.createStatement();
			String query = "select * from dsa  where status='active' ";
			ResultSet rr = stt.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				
				DsaListInfo obj = new DsaListInfo();
				
				obj.setCode(rr.getString("code"));
				obj.setSno(j++);
				obj.setAddress(rr.getString("address"));
				obj.setMobile(rr.getString("mobile"));
				obj.setName(rr.getString("name"));
				obj.setId(rr.getString("id"));
				obj.setCommission_type(rr.getString("commission_type"));
				obj.setCommission_value(rr.getDouble("commission_value"));
				boolean val=chkDsa(rr.getString("code"));
				if(val==true)
				{
					obj.setStatus("true");
				}
				else
				{
					obj.setStatus("false");
				}
				list.add(obj);
			}
			
			
		} catch (Exception e) {
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public boolean chkDsa(String dsaCode)
	{

	   try(Connection conn=DataBaseConnection.JAVAConnection())
		{
		Statement st=conn.createStatement();
	
		String qq="(select dsa_code from customer_info where dsa_code='"+dsaCode+"') union(select dsacode from personalloan where dsacode='"+dsaCode+"')"
		+ "union(select dsacode from grouploan where dsacode='"+dsaCode+"')";
		ResultSet rr=st.executeQuery(qq);
		if(rr.next())
		{
			return true;
		}
		}
		catch(Exception e)
		{
		 e.printStackTrace();fileCreation(e.getMessage());
		}
	   return false;
	}
	
	public int updateDsa(String code, String name, String mobile, String address, String commission_type, double commission_value) 
	{
		try (Connection cnt = DataBaseConnection.JAVAConnection();)
		{
			Statement stt = cnt.createStatement();
			String query ="update dsa set name='"+name+"', mobile='"+mobile+"', address='"+address+"', "
					+ "commission_type='"+commission_type+"',commission_value='"+commission_value+"' where code = '"+code+"'";
			int re = stt.executeUpdate(query);
			if(re>0)
			{
				dataInsertInQueryTable(query, cnt);
				return re;
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public int deletedsa(String idp) 
	{
		try (Connection cnt = DataBaseConnection.JAVAConnection();)
		{
			Statement stt = cnt.createStatement();
			String query ="update dsa set status='inactive' where id = '"+idp+"'";
			int re = stt.executeUpdate(query);
			if(re>0)
			{
				dataInsertInQueryTable(query, cnt);
				return re;
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public String dsaNameById(String id, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select name from dsa where code='"+id+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("name");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}
		return "";
	}
	
	public DsaListInfo dsaInfoByCode(String dsaCode,String type) 
	{
		DsaListInfo info=new DsaListInfo();
		int i=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from dsa where code='"+dsaCode+"' and status='active' ";
		//	// // // //System.out.println(query);
			ResultSet rr=st.executeQuery(query);
			if(rr.next())
			{
				
				info.setSno(++i);
				info.setId(rr.getString("id"));
				info.setName(rr.getString("name"));
				info.setAddress(rr.getString("address"));
				info.setCode(rr.getString("code"));
				info.setMobile(rr.getString("mobile"));
				info.setCommission_type(rr.getString("commission_type"));
				info.setCommission_value(rr.getDouble("commission_value"));

			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return info;
	}

	public int addDSAReturn(String selectedName, double amount,
			String description, Date payDate, String chequeNo, Date chequeDate,
			String bankName, String bankBranch, String paymentMode,int branchId)
	{
		Timestamp tt=new Timestamp(payDate.getTime());
		String status="";
		if(paymentMode.equalsIgnoreCase("Cash") || paymentMode.equalsIgnoreCase("Transfer"))
		{
			status="cleared";
			bankName="N/A";
		}
		else if(paymentMode.equalsIgnoreCase("Cheque") || paymentMode.equalsIgnoreCase("Demand Draft")|| paymentMode.equalsIgnoreCase("neft"))
		{
			status="uncleared";
		}
		
		Timestamp cDate=null;
		if(chequeDate!=null)
		{
			cDate=new Timestamp(chequeDate.getTime());
		}
		
		String query="insert into return_dsa(code, amount, pay_date, payment_mode, chq_dd_no, chq_dd_date, bank_name,"
				+ " bank_branch, chequeStatus, description,branch_id) "
				+ "values(?,?,?,?,?,?,?,?,?,?,?)";
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			PreparedStatement st=conn.prepareStatement(query);
			st.setString(1, selectedName);
			st.setDouble(2, amount);
			st.setTimestamp(3,new Timestamp(payDate.getTime()));
			st.setString(4, paymentMode);
			st.setString(5, chequeNo);
			st.setTimestamp(6, cDate);
			st.setString(7,bankName);
			st.setString(8,bankBranch);
			st.setString(9, status);
			st.setString(10, description);
			st.setInt(11, branchId);
			
			int i=st.executeUpdate();
			if(i>0)
			{
			dataInsertInQueryTable(String.valueOf(st), conn);
			return i;
		}}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public ArrayList<DsaListInfo> dsaCreditList(int branchId,String dsaCode)
	{
		String qq="";
		ArrayList<DsaListInfo> list=new ArrayList<>();
		ArrayList<SelectItem> loanList=new ArrayList<>();
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			loanList=loanTypeList(con);
			for(SelectItem ss : loanList)
			{
				qq="select * from "+ss.getValue()+" where dsacode='"+dsaCode+"' and status='Approve'";
				ResultSet rs=st.executeQuery(qq);
				while(rs.next())
				{
					DsaListInfo dd=new DsaListInfo();
					dd.setParticular("Commission Credited : "+rs.getString("loanNo"));
					dd.setEntryDate(rs.getDate("approvalDate"));
					dd.setStrEntryDate(sf.format(dd.getEntryDate()));
					dd.setPayMode("Auto Credit");
					dd.setCreditAmount(rs.getDouble("commission"));
					dd.setDebitAmount(0);
					
					list.add(dd);
				}
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	
	public ArrayList<DsaListInfo> dsaCommisionList(int branchId,Connection conn)
	{
		String qq="";
		int i=1;
		ArrayList<DsaListInfo> list=new ArrayList<>();
		try
		{
			Statement st=conn.createStatement();
				qq="select * from dsa_commission where user_no='all' ";
				ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
				while(rs.next())
				{
					DsaListInfo dd=new DsaListInfo();
					dd.setSno(i++);
					dd.setId(rs.getString("id"));
					dd.setType(rs.getString("type"));
					dd.setDsaCode(rs.getString("dsa_code"));
					dd.setAmount(rs.getDouble("amount"));
					dd.setCreditDatestr(sf.format(rs.getDate("credit_date")));
					dd.setEmiNoStr(rs.getString("emi_no"));
					dd.setDebitAmount(0);
					
					list.add(dd);
				}
			
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public ArrayList<DsaListInfo> dsaCreditListFromDsaCommissionTable(String dsaCode, Date startDate, Date endDate)
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		ArrayList<DsaListInfo> list=new ArrayList<>();
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select * from dsa_commission where dsa_code='"+dsaCode+"' and credit_date>='"+sDate+"' and credit_date<='"+eDate+"' ";
			ResultSet rs=st.executeQuery(qq);
			while(rs.next())
			{
				DsaListInfo dd=new DsaListInfo();
				dd.setPayMode("Auto Credit: ");
				dd.setParticular("Commission Credited : "+rs.getString("user_no")+" Type:"+rs.getString("type")+" EMI No. "+rs.getString("emi_no"));
				dd.setEntryDate(rs.getDate("credit_date"));
				dd.setStrEntryDate(sf.format(dd.getEntryDate()));
				dd.setCreditAmount(rs.getDouble("amount"));
				dd.setDebitAmount(0);
				
				list.add(dd);
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public ArrayList<DsaListInfo> dsaDebitList(String dsaCode, Date startDate, Date endDate)
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		ArrayList<DsaListInfo> list=new ArrayList<>();
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select * from return_dsa where code='"+dsaCode+"' and chequeStatus='cleared' and pay_date>='"+sDate+"' and pay_date<='"+eDate+"' ";
			ResultSet rs=st.executeQuery(qq);
			while(rs.next())
			{
				DsaListInfo dd=new DsaListInfo();
				
				dd.setParticular("Amount Returned");
				dd.setEntryDate(rs.getDate("pay_date"));
				dd.setStrEntryDate(sf.format(dd.getEntryDate()));
				dd.setPayMode(rs.getString("payment_mode"));
				dd.setCreditAmount(0);
				dd.setDebitAmount(rs.getDouble("amount"));
				
				list.add(dd);
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public ArrayList<SelectItem> allDsaList(int branchId,String type, Connection conn) 	
	{   
		System.out.println("busnness report branchidi is:"+branchId);
		
		ArrayList<SelectItem> list=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		String query="";
		try
		{
			st=conn.createStatement();
			
			if(branchId==-1)
			{
				query="select code,name from dsa where code in (select dsacode from employee where uname in( select userid from login where id in "
						+ "(select user_id from branch_allocate_table) and status='active' and type='employee')) and status='active'";
			} 
			
			else
			{
				query="select code,name from dsa where code in (select dsacode from employee where uname in( select userid from login where id in "
						+ "(select user_id from branch_allocate_table where branch_id='"+branchId+"') and status='active' and type='employee')) and status='active'";
			} 
		    System.out.println(query);
			rr=st.executeQuery(query);
			while(rr.next())
			{
				SelectItem ll=new SelectItem();
				
				DbYashwant dby = new DbYashwant();
						
				String codes=rr.getString("code");
				System.out.println(codes);
				String names= rr.getString("name");
				System.out.println(names);
				
				ll.setLabel(dby.manageEmployeeId(rr.getString("code"))+"-"+rr.getString("name"));
				
				ll.setValue(rr.getString("code"));
				
				list.add(ll);
				System.out.println("employee list is:"+list);
				System.out.println("employee list is:"+list.size());
			
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}
		return list;
	}
	
	
	
	public ArrayList<SelectItem> allDsaListForCommision(String type,int branchId, Connection conn) 
	{
		ArrayList<SelectItem> list=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select * from dsa where status='active'  ";
			rr=st.executeQuery(selectQueWithBranch(query,branchId));
		//	// // // //System.out.println(query);
			while(rr.next())
			{
				SelectItem ll=new SelectItem();
				
				ll.setLabel(rr.getString("code")+"-"+rr.getString("name"));
				ll.setValue(rr.getString("code")+"-"+rr.getString("name"));
				
				list.add(ll);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}
		return list;
	}

	public Date uniqueDate() 
	{
		Date today=new Date();
		return today;
	}

	public int addSalaryPayout(String selectedName, double amount,
			String type, Date payDate, String paymentMode, String chequeNo,
			Date chequeDate, String bankName, String bankBranch,
			String description,int branchId,String month,String year)
	{
		Timestamp tt=new Timestamp(payDate.getTime());
		String status="";
		if(paymentMode.equalsIgnoreCase("Cash") || paymentMode.equalsIgnoreCase("Transfer"))
		{
			status="cleared";
			bankName="N/A";
		}
		else
		{
			status="uncleared";
		}
		
		Timestamp cDate=null;
		if(chequeDate!=null)
		{
			cDate=new Timestamp(chequeDate.getTime());
		}
		
		String query="insert into salary_ledger(empId, amount, type, payDate, payment_mode, chq_dd_no, chq_dd_date, bank_name,"
				+ " bank_branch, chequeStatus, description, branch_id,month,year) "
				+ "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			PreparedStatement st=conn.prepareStatement(query);
			st.setString(1, selectedName);
			st.setDouble(2, amount);
			st.setString(3, type);
			st.setTimestamp(4,new Timestamp(payDate.getTime()));
			st.setString(5, paymentMode);
			st.setString(6, chequeNo);
			st.setTimestamp(7, cDate);
			st.setString(8,bankName);
			st.setString(9,bankBranch);
			st.setString(10, "cleared");
			st.setString(11, description);
			st.setInt(12, branchId);
			st.setString(13, month);
			st.setString(14, year);
			
			
			int i=st.executeUpdate();
			if(i>0){
			dataInsertInQueryTable(String.valueOf(st), conn);
			return i;
		}}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public String generateVoucherNo(int branchId,String string,Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		String maxInvNo="";
		try
		{
			st=conn.createStatement();
			String query="select max(convert(voucher_no,decimal)) as num from "+string+" ";
			rr=st.executeQuery(selectQueWithBranch(query,branchId));
			if(rr.next())
			{
				maxInvNo=rr.getString("num");
				if(maxInvNo==null)
				{
					return maxInvNo="1";
				}
				else
				{
					return String.valueOf(Integer.parseInt(maxInvNo)+1);
				}
			}
			
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}

	public void insertTdsDeductionDetail(String user_no, Date current_date,
			double tdsValue, String type, int selectYear, double tdsPercent,int branchId) 
	{
		Timestamp tt=new Timestamp(current_date.getTime());
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="insert into tds_deduction(user_no, tds_date, tds_amount,type, year, tds_percent,branch_id) "
					+ "values('"+user_no+"','"+tt+"','"+tdsValue+"','"+type+"','"+selectYear+"','"+tdsPercent+"','"+branchId+"')";
		int i=	st.executeUpdate(qq);
			if(i>0)
			{
			dataInsertInQueryTable(qq, conn);
		}}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}

	public boolean checkTdsDeductionDuplicacy(String type, Date endDate,int branchId) 
	{
		String dt=sdfForDb.format(endDate);
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from tds_deduction where type='"+type+"' and tds_date='"+dt+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return false;
	}

	public int addEmplyeeSubmission(Date payDate, String string,
			String paymentMode, double amount, String chequeNo,
			String bankBranch, String bankName, Date chequeDate,
			String description, String selectedEmployee,int branchId) 
	{
		int i=0;
		String status="";
		if(paymentMode.equals("Cash"))
		{
			status="cleared";
			bankName="N/A";
		}
		else if(paymentMode.equals("Cheque") || paymentMode.equals("Demand Draft"))
		{
			status="cleared";
		}
		else if(paymentMode.equalsIgnoreCase("Bank Deduction"))
		{
			status="cleared";
		}
			
		
		Timestamp cDate=null;
		if(chequeDate!=null)
		{
			cDate=new Timestamp(chequeDate.getTime());
		}
		
		String query="insert into emp_paydeduct_submission(expense_date,category,payment_mode,amount,chq_dd_no,chq_dd_date,bank_name,bank_branch,"
		+ " description,chequeStatus, empId, branch_id)values(?,?,?,?,?,?,?,?,?,?,?,?)";
        try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			PreparedStatement st=conn.prepareStatement(query);
			st.setTimestamp(1,new Timestamp(payDate.getTime()));
			st.setString(2, string);
			st.setString(3, paymentMode);
			st.setDouble(4, amount);
			st.setString(5, chequeNo);
			st.setTimestamp(6,cDate);
			st.setString(7,bankName);
			st.setString(8,bankBranch);
			st.setString(9, description);
			st.setString(10, status);
			st.setString(11, selectedEmployee);
			st.setInt(12, branchId);
			i=st.executeUpdate();
			if(i>0)
			{
			dataInsertInQueryTable(String.valueOf(st), conn);
		}}
		catch (Exception e)
		{
			  e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}
	
	public int addTdsSubmission(Date payDate, String string,
			String paymentMode, double amount, String chequeNo,
			String bankBranch, String bankName, Date chequeDate,
			String description,int branchId) 
	{
		int i=0;
		String status="";
		if(paymentMode.equals("Cash"))
		{
			status="cleared";
			bankName="N/A";
		}
		else if(paymentMode.equals("Cheque") || paymentMode.equals("Demand Draft"))
		{
			status="cleared";
		}
		else if(paymentMode.equalsIgnoreCase("Bank Deduction"))
		{
			status="cleared";
		}
			
		
		Timestamp cDate=null;
		if(chequeDate!=null)
		{
			cDate=new Timestamp(chequeDate.getTime());
		}
		
		String query="insert into tds_submission(expense_date,category,payment_mode,amount,chq_dd_no,chq_dd_date,bank_name,bank_branch,"
		+ " description,chequeStatus,branch_id)values(?,?,?,?,?,?,?,?,?,?,?)";
        try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			PreparedStatement st=conn.prepareStatement(query);
			st.setTimestamp(1,new Timestamp(payDate.getTime()));
			st.setString(2, string);
			st.setString(3, paymentMode);
			st.setDouble(4, amount);
			st.setString(5, chequeNo);
			st.setTimestamp(6,cDate);
			st.setString(7,bankName);
			st.setString(8,bankBranch);
			st.setString(9, description);
			st.setString(10, status);
			st.setInt(11, branchId);
			i=st.executeUpdate();
			if(i>0)
			{
			dataInsertInQueryTable(String.valueOf(st), conn);
			}}
		catch (Exception e)
		{
			  e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}

	public ArrayList<FixedAssetsInfo> allFixedAssetsList(int branchId) 
	{
		int count=1;
		ArrayList<FixedAssetsInfo> list=new ArrayList<>();
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from expense_table where category='Fixed_Asset_Dr' and status='active' ";
	//		// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				FixedAssetsInfo ff=new FixedAssetsInfo();
				
				
				ff.setFaPurchaseId(rr.getString("id"));
				ff.setName(rr.getString("item"));
				ff.setPurchaseDate(rr.getDate("expense_Date"));
				ff.setPurchaseDateStr(sf.format(ff.getPurchaseDate()));
				ff.setPurchaseValue(rr.getDouble("item_rate"));
				ff.setNoOfItem(rr.getInt("no_of_item"));
				ff.setNoOfItemSale(noOfFixedAssetSale(branchId,ff.getFaPurchaseId()));
				ff.setStockBalance(ff.getNoOfItem()-ff.getNoOfItemSale());
				ff.setDepValue(calculateDepOnFa(branchId,ff.getFaPurchaseId()));
				ff.setPresentValue(ff.getPurchaseValue()-ff.getDepValue());
				
				if(ff.getStockBalance()>0)
				{
					ff.setSno(count++);
					list.add(ff);
				}
				
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}

	private double calculateDepOnFaPrevious(String faPurchaseId,String year,int branchId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(dep_value) from depreciation where fa_purchase_id='"+faPurchaseId+"' and dep_year<'"+year+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getInt("sum(dep_value)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public double calculateDepOnFa(int branchId,String faPurchaseId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(dep_value) from depreciation where fa_purchase_id='"+faPurchaseId+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(dep_value)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public double calculateDepOnFaSale(String faPurchaseId, String year,int branchId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(dep_value) from depreciation where fa_purchase_id='"+faPurchaseId+"' and dep_year<='"+year+"' ";
		//	// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getInt("sum(dep_value)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	private int noOfFixedAssetSale(int branchId,String faPurchaseId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(no_of_item) from income_table where fa_purchase_id='"+faPurchaseId+"' and chequeStatus='cleared' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getInt("sum(no_of_item)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public boolean checkDepreciationDuplicacy(int branchId,String year, String faId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from depreciation where dep_year='"+year+"' and fa_purchase_id='"+faId+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return false;
	}

	public ArrayList<FixedAssetsInfo> viewDepYearWise(int branchId,String year) 
	{
		int count=1;
		ArrayList<FixedAssetsInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from depreciation where dep_year='"+year+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				FixedAssetsInfo ff=new FixedAssetsInfo();
				FixedAssetsInfo ff1=new DataBaseReportMethods().selectedFAPurchaseDetail(branchId,rr.getString("fa_purchase_id"));
				
				ff.setSno(count++);
				ff.setIdDep(rr.getString("id_depreciation"));
				ff.setName(ff1.getName());
				ff.setDepValue(rr.getDouble("dep_value"));
				ff.setPurchaseDateStr(ff1.getPurchaseDateStr());
				boolean check=checkFaSaleOrNot(branchId,rr.getString("fa_purchase_id"));
				if(check==true)
				{
					ff.setDisDep(true);
				}
				else
				{
					ff.setDisDep(false);
				}
				
				list.add(ff);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	public int deleteDep(String idDep) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="delete from depreciation where id_depreciation='"+idDep+"' ";
			int i=st.executeUpdate(qq);
			if(i>0){
			dataInsertInQueryTable(qq, conn);
			return i;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public boolean checkFaSaleOrNot(int branchId,String faId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from income_table where fa_purchase_id='"+faId+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return false;
	}

	public ArrayList<EmpInfo> findDeductionOfAllemployeeMonthWise(int branchId,String selectedYear, String selectedMonth) 
	{
		int count=1;
		ArrayList<EmpInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from employee where status='active' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				EmpInfo ee=new EmpInfo();
				EmpInfo pp=employeePayDeductionDetail(selectedYear, selectedMonth, rr.getString("uname"));
				
				ee.setId(rr.getString("id"));
				ee.setSno(count++);
				ee.setUname(rr.getString("uname"));
				ee.setFname(rr.getString("fname"));
				ee.setName(rr.getString("name"));
				ee.setEsic(pp.getEsic());
				ee.setTds(pp.getTds());
				ee.setPf(pp.getPf());
				ee.setTotal(ee.getEsic()+ee.getTds()+ee.getPf());
				
				list.add(ee);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	private EmpInfo employeePayDeductionDetail(String selectedYear, String selectedMonth, String uname) 
	{
		EmpInfo pp=new EmpInfo();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from salary_table where empId='"+uname+"' and month='"+selectedMonth+"' and year='"+selectedYear+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				pp.setEsic(rr.getDouble("esi"));
				pp.setPf(rr.getDouble("pf"));
				pp.setTds(rr.getDouble("tds"));
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return pp;
	}

	public double employeePayDeductAmount(String empPayCat, String selectedEmployee) 
	{
		String qq="";
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(empPayCat.equalsIgnoreCase("tds"))
			{
				qq="select sum(tds) as total from salary_table where empId='"+selectedEmployee+"' ";
			}
			else if(empPayCat.equalsIgnoreCase("esic"))
			{
				qq="select sum(esi) as total from salary_table where empId='"+selectedEmployee+"' ";
			}
			else
			{
				qq="select sum(pf) as total from salary_table where empId='"+selectedEmployee+"' ";
			}
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("total");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public double employeeSubmitPayDeductAmount(int branchId,String empPayCat) 
	{
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from emp_paydeduct_submission where category='"+empPayCat+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public ArrayList<EmpInfo> allEmlSalaryFormationReport(int branchId,String selectedYear, String selectedMonth) 
	{
		int count=1;
		ArrayList<EmpInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from employee where status='active' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				EmpInfo ff=new EmpInfo();
				
				ff.setSno(count++);
				ff.setUname(rr.getString("uname"));
				ff.setName(rr.getString("name"));
				ff.setMobile(rr.getString("mobile"));
				ff.setSalary(new DataBaseMethodsSalary().viewPreparedSalaryAmount(ff.getUname(), selectedMonth, selectedYear));
				if(ff.getSalary()>0)
				{
					ff.setStatus("Created");
				}
				else
				{
					ff.setStatus("Pending");
				}
			
				list.add(ff);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	public double findMatureFdBetweenDate(String user_no, Date startDate, Date endDate) 
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select maturity_value from returned_amount_info where date>='"+sDate+"' and date<='"+eDate+"'  and user_no='"+user_no+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("maturity_value");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public double findTdsDeductionAmountOnFd(String user_no) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select tds_amount from tds_deduction where user_no='"+user_no+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("tds_amount");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public ArrayList<SelectItem> loanResNoList(String loanNo, String loanType) 
	{
		String qq="";
		loanNo=loanNo.substring(0, 9);
		ArrayList<SelectItem> list=new ArrayList<>();
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			if(!loanType.equals("grouploan"))
			{
				qq="SELECT loanNo,shareholderno FROM "+loanType+" where loanNo like '"+loanNo+"%'";
			}
			
			ResultSet rs=st.executeQuery(qq);
			while(rs.next())
			{
				SelectItem ss=new SelectItem();
				
				if(rs.getString("loanNo").contains("R"))
				{
					String name=applicantNameByShareHolderNo(rs.getString("shareholderno"), con);
					ss.setLabel(rs.getString("loanNo")+"/"+name);
					ss.setValue(rs.getString("loanNo")+"/"+name);
					
					list.add(ss);
				}
				
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}

	public ArrayList<LoanInfo> loanListInGroupLoan(String loanNo, Connection conn)
	{
		int count=1;
		Statement st=null;
		ResultSet rs=null;
		ArrayList<LoanInfo> list=new ArrayList<>();
		try
		{
			st=conn.createStatement();
			String qq="select * from grouploan where loanNo='"+loanNo+"' and status='Approve' and paidStatus='unpaid'  ";
			 rs=st.executeQuery(qq);
			while(rs.next())
			{
				LoanInfo uu=new LoanInfo();
				
				uu.setSno(count++);
				uu.setLoanAmount(rs.getString("loanAmount"));
				uu.setSubLoanNo(rs.getString("sub_loan_no"));
				uu.setApplicantName(applicantNameByShareHolderNo(rs.getString("teamLeader"), conn));
				uu.setLoanInterest(rs.getString("interest"));
				uu.setLoanTerm(rs.getString("terms"));
				uu.setTotalAmount(rs.getDouble("terms")*rs.getDouble("emi"));
				uu.setTotalPaid(loanPaidAmountByUser("grouploan", rs.getString("sub_loan_no"), conn));
				uu.setTotalLeft(uu.getTotalAmount()-uu.getTotalPaid());
				uu.setFrequency(frequencyLabel(rs.getString("frequency")));
				uu.setInstallAmount(rs.getDouble("emi"));
				uu.setDiscount(rs.getInt("discount"));
				uu.setCenterName(centerNameById(rs.getString("center"), conn));
				uu.setFatherHusbandName(shareHolderDetailByColumnName(rs.getString("teamLeader"), "father_husband_name", conn));
				
				list.add(uu);
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				conn.close();
			} 
			catch (Exception e2) 
			{
				// TODO: handle exception
			}
		}
		return list;
	}

	public String checkAppTypeForGroupLoan(String loanNo) 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select application_type from grouploan where loanNo='"+loanNo+"'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getString("application_type");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}

	public String memberLoanNoForGroupLoan(String loanNo, String shareHolderNo) 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select sub_loan_no from grouploan where teamLeader='"+shareHolderNo+"' and loanNo='"+loanNo+"'";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getString("sub_loan_no");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}
	
	public String fileViewPathDetail(Connection conn)
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select * from firm_detail limit 1";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getString("file_view_path");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		} 
		return "";
	}
	
	public String fileUploadPathDetail() {
	    String query = "SELECT file_upload_path FROM firm_detail LIMIT 1";
	    
	    try (Connection con = DataBaseConnection.JAVAConnection();
	         PreparedStatement ps = con.prepareStatement(query);
	         ResultSet rs = ps.executeQuery()) {

	        if (rs.next()) {
	            return rs.getString("file_upload_path");
	        }
	    } catch (Exception e) {
	        e.printStackTrace(); // Consider replacing with a logger
	        System.err.println("fileUploadPathDetail error: " + e.getMessage());

	    }

	    return "/home/delights/public_html/soft_files";
	}


	public ArrayList<String> existingMemberListByGroupLoanNo(String groupLoanNo) 
	{
		ArrayList<String> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select teamLeader from grouploan where loanNo='"+groupLoanNo+"' and status='Approve' and paidStatus='unpaid' ";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				list.add(rr.getString("teamLeader"));
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public boolean checkMemberListInGLTableByCenter(String center, String memberNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select teamLeader from grouploan where center='"+center+"' and teamLeader='"+memberNo+"' and status='Approve' and paidStatus='unpaid' ";
			//System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return false;
	}

	// Wrong when one emi deposit in two-three.. more  parts // comment on 09 june 2019
	/*public int totalEMIPaidByLoanNo(String loanNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select count(*) from loanpayment where loanNo='"+loanNo+"' and receipt_status='approved' and chequeStatus='cleared' ";
		//	// // // //System.out.println(qq);
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getInt("count(*)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}*/
	
	public int totalEMIPaidByLoanNo(String loanNo, Connection conn) 
	{
		int count=0;
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select emi_no from loanpayment where loanNo='"+loanNo+"' and receipt_status='approved' and chequeStatus='cleared'  group by emi_no ";
		//	// // // //System.out.println(qq);
			rr=st.executeQuery(qq);
			while(rr.next())
			{
				++count;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		System.out.println("Paid Emi of LoanNo :"+loanNo+" Is :"+count);
		return count;
	}
	
	
//	public int totalEMIPaidByLoanNo(String loanNo, Connection conn) {
//		
//		int i = 0 ;
//		
//		try(Connection connn= DataBaseConnection.JAVAConnection()){
//			
//			String query = "select * from loanpayment where loanNo= ? and receipt_status='approved' and chequeStatus='cleared'";
//    
//			try(PreparedStatement ps = conn.prepareStatement(query)){
//				
//			 ps.setString(1, loanNo);	
//	
//			  ResultSet rs = ps.executeQuery();
//			  System.out.println(query +"lN"+loanNo);
//			  while(rs.next()) {
//				  
//				  i++;
//				  
//			  }
//			  System.out.println("Paid Emi of LoanNo :"+loanNo+" Is :"+i);
//				
//			}catch(Exception e) {
//				
//				e.printStackTrace();
//				
//			}
//		}catch(Exception e) {
//			
//			e.printStackTrace();
//			
//			
//		}
//		
//		return i;
//	}
	
	
	
	public ArrayList<TrialInfo> trialBalancePromotorCapital(Date startDate, Date endDate,int branchId,Connection conn) 
	{
		boolean chk=true;
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		ArrayList<TrialInfo> list=new ArrayList<>();
		Statement st=null;ResultSet rs=null;
		try
		{
			 st=conn.createStatement();
			String qq="select * from promotors where status='active' ";
			 rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rs.next())
			{
				TrialInfo tt=new TrialInfo();
				
				//if(chk==true)
				{
					tt.setCategory("Promotors Capital");
					chk=false;
				}
				String pid=rs.getString("id");
				tt.setParticular(promotorsNameById(pid));
				double val=openingPromotorCapital(pid, sDate);
				if(val>0)
				{
					tt.setOpeningCr(Math.abs(val));
				}
				else
				{
					tt.setOpeningDr(Math.abs(val));
				}
				tt.setCredit(promotorAmount(branchId,pid, sDate, eDate));
				tt.setDebit(returnAmountPromotorWise(branchId,pid, sDate, eDate));
			//	tt.setBalance((tt.getOpening()+tt.getDebit())-tt.getCredit());
				
				list.add(tt);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}

		return list;
	}

	private double openingPromotorCapital(String pid, String sDate) 
	{
		double amount=0, amountCr=0,amountDr=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from promotors_capital where promotor_id='"+pid+"' and income_date<'"+sDate+"' and status='active' and chequeStatus='cleared'  "; 
			//System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				amountCr=rr.getDouble("sum(amount)");
			}
			
			Statement st1=conn.createStatement();
			String qq1="select sum(amount) from return_promotors_capital where promotor_id='"+pid+"' and income_date<'"+sDate+"' and status='active' and chequeStatus='cleared'  "; 
			//System.out.println(qq1);
			ResultSet rr1=st1.executeQuery(qq1);
			if(rr1.next())
			{
				amountDr=rr1.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		amount=amountCr-amountDr;
		return amount;
	}
	
	public ArrayList<UserInfo> allPromotersCapital(int branchId) 
	{
		ArrayList<UserInfo> list=new ArrayList<>();
		int i=1;
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select * from promotors_capital where status='active' and chequeStatus='cleared' ";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rs.next())
			{
				UserInfo ii=new UserInfo();
				
				ii.setSno(i++);
				ii.setFirst_applicantName(promotorsNameById(rs.getString("promotor_id")));
				ii.setId(rs.getString("id"));
				ii.setEntryDateStr(sf.format(rs.getDate("income_date")));
				ii.setAmount(rs.getDouble("amount"));
				ii.setPayMode(rs.getString("payment_mode"));
				ii.setChq_ddNo(rs.getString("chq_dd_no"));
				ii.setReturnAmount(returnAmountPromotorWise(ii.getPromotorId()));
				ii.setBalance(ii.getAmount()-ii.getReturnAmount());
				ii.setSubmittedToBank(rs.getString("transfer_to_bank"));
				
				list.add(ii);
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	
	public ArrayList<UserInfo> allReturnPromotersCapital(int branchId) 
	{
		ArrayList<UserInfo> list=new ArrayList<>();
		int i=1;
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select * from return_promotors_capital where status='active' and chequeStatus='cleared' ";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rs.next())
			{
				UserInfo ii=new UserInfo();
				
				ii.setSno(i++);
				ii.setFirst_applicantName(promotorsNameById(rs.getString("promotor_id")));
				ii.setId(rs.getString("id"));
				ii.setEntryDateStr(sf.format(rs.getDate("income_date")));
				ii.setAmount(rs.getDouble("amount"));
				ii.setPayMode(rs.getString("payment_mode"));
				ii.setChq_ddNo(rs.getString("chq_dd_no"));
				ii.setReturnAmount(returnAmountPromotorWise(ii.getPromotorId()));
				ii.setBalance(ii.getAmount()-ii.getReturnAmount());
				ii.setSubmittedToBank(rs.getString("transfer_to_bank"));
				
				list.add(ii);
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	
	public ArrayList<UserInfo> allPromotersCapitalForReturn(int branchId) 
	{
		ArrayList<UserInfo> list=new ArrayList<>();
		int i=1;
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select * from promotors where status='active' ";
			ResultSet rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rs.next())
			{
				UserInfo ii=new UserInfo();
				
				ii.setSno(i++);
				ii.setPromotorId(rs.getString("id"));
				ii.setFirst_applicantName(rs.getString("name"));
				ii.setId(rs.getString("id"));
				ii.setAmount(promotorAmount(ii.getPromotorId()));
				ii.setReturnAmount(returnAmountPromotorWise(ii.getPromotorId()));
				ii.setBalance(ii.getAmount()-ii.getReturnAmount());
				
				list.add(ii);
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	
	
	public double returnAmountPromotorWise(int branchId,String promotorId, String sDate, String eDate) 
	{
		String qq="";
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(promotorId.equals("-1"))
			{
				qq="select sum(amount) from return_promotors_capital where income_date>='"+sDate+"' and income_date<='"+eDate+"' and chequeStatus='cleared' and status='active' "; 
			}
			else
			{
				qq="select sum(amount) from return_promotors_capital where promotor_id='"+promotorId+"' and income_date>='"+sDate+"' and income_date<='"+eDate+"' and chequeStatus='cleared' and status='active'"; 
			}
			//// //System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public double openingReturnAmountPromotor(int branchId,String promotorId, String sDate) 
	{
		String qq="";
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(promotorId.equals("-1"))
			{
				qq="select sum(amount) from return_promotors_capital where income_date<'"+sDate+"' and chequeStatus='cleared' and status='active' "; 
			}
			else
			{
				qq="select sum(amount) from return_promotors_capital where promotor_id='"+promotorId+"' and income_date<'"+sDate+"' and chequeStatus='cleared' and status='active'"; 
			}
			//System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public double promotorAmount(int branchId,String promotorId, String sDate, String eDate) 
	{
		String qq="";
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(promotorId.equals("-1"))
			{
				qq="select sum(amount) from promotors_capital where  income_date>='"+sDate+"' and income_date<='"+eDate+"' and status='active' and chequeStatus='cleared' "; 
			}
			else
			{
				qq="select sum(amount) from promotors_capital where promotor_id='"+promotorId+"' and income_date>='"+sDate+"' and income_date<='"+eDate+"' and status='active' and chequeStatus='cleared' "; 
			}
			
			System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public double openingPromotorAmount(int branchId,String promotorId, String sDate) 
	{
		String qq="";
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(promotorId.equals("-1"))
			{
				qq="select sum(amount) from promotors_capital where  income_date<'"+sDate+"' and status='active' and chequeStatus='cleared' "; 
			}
			else
			{
				qq="select sum(amount) from promotors_capital where promotor_id='"+promotorId+"' and income_date<'"+sDate+"' and status='active' and chequeStatus='cleared' "; 
			}
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public double returnPromotorAmount(String promotorId, String sDate, String eDate,int branchId) 
	{
		String qq="";
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(promotorId.equals("-1"))
			{
				qq="select sum(amount) from return_promotors_capital where  income_date>='"+sDate+"' and income_date<='"+eDate+"' and status='active' and chequeStatus='cleared' "; 
			}
			else
			{
				qq="select sum(amount) from return_promotors_capital where promotor_id='"+promotorId+"' and income_date>='"+sDate+"' and income_date<='"+eDate+"' and status='active' and chequeStatus='cleared' "; 
			}
			//// //System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public double promotorAmountForCashBook(Date startDate, Date endDate, String payMode,int branchId,Connection conn, 
											String bank) 
	{
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		String qq="";
		try
		{
			Statement st=conn.createStatement();
			if(payMode.equalsIgnoreCase("cash"))
			{
				qq="select sum(amount) from promotors_capital where payment_mode='cash' and income_date>='"+sDate+"' and income_date<='"+eDate+"' and status='active' and chequeStatus='cleared' "; 
			}
			else
			{
				qq="select sum(amount) from promotors_capital where payment_mode!='cash' and income_date>='"+sDate+"' and income_date<='"+eDate+"' and status='active' and chequeStatus='cleared' "; 
			
				if (!bank.equalsIgnoreCase("All"))
				{
					qq += " and transfer_to_bank = '"+bank+"' ";
				}
			}
		System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{System.out.println(rr.getDouble("sum(amount)"));
				return rr.getDouble("sum(amount)");
				
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public double returnPromotorAmountForCashBook(Date startDate, Date endDate, String payMode,int branchId, Connection conn, String bank) 
	{
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		String qq="";
		try
		{
			Statement st=conn.createStatement();
			if(payMode.equalsIgnoreCase("cash"))
			{
				qq="select sum(amount) from return_promotors_capital where payment_mode='cash' and income_date>='"+sDate+"' and status='active' and income_date<='"+eDate+"' and chequeStatus='cleared' "; 
			}
			else
			{
				qq="select sum(amount) from return_promotors_capital where payment_mode!='cash' and income_date>='"+sDate+"' and status='active' and income_date<='"+eDate+"' and chequeStatus='cleared' "; 
			
				if (!bank.equalsIgnoreCase("All"))
				{
					qq += " and transfer_to_bank = '"+bank+"' ";
				}
			}
		//	// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public double promotorAmount(String promotorId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from promotors_capital where promotor_id='"+promotorId+"' and chequeStatus='cleared' and status='active' "; 
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public ArrayList<TrialInfo> trialBalanceAllRemainingExpense(Date startDate, Date endDate,int branchId, Connection conn) 
	{
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		ArrayList<TrialInfo> list=new ArrayList<>();
		
		TrialInfo tt=new TrialInfo();
		tt.setCategory("Expense (Indirect)");
		tt.setParticular("Salary Payout");
		tt.setOpeningDr(openingSalaryBalance(branchId,sDate));
		double amt=salaryPayoutAmountBetweenDate(branchId,sDate, eDate);
		tt.setDebit(amt);
		tt.setCredit(0);		
		list.add(tt);
		
		TrialInfo tt1=new TrialInfo();
		tt1.setCategory("Expense (Indirect)");
		tt1.setParticular("DSA Commission");
		tt1.setOpeningDr(openingDsaBalance(branchId,sDate));
		double amt1=dsaPayoutAmountBetweenDate(branchId,sDate, eDate);
		tt1.setDebit(amt1);
		tt1.setCredit(0);		
		list.add(tt1);
		
		return list;
	}

	private double dsaPayoutAmountBetweenDate(int branchId,String sDate, String eDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from return_dsa where pay_date>='"+sDate+"' and pay_date<='"+eDate+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	private double openingDsaBalance(int branchId,String sDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from return_dsa where pay_date<'"+sDate+"'  ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	private double salaryPayoutAmountBetweenDate(int branchId,String sDate, String eDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from salary_ledger where payDate>='"+sDate+"' and payDate<='"+eDate+"' and type='Debit' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	private double openingSalaryBalance(int branchId,String sDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from salary_ledger where payDate<'"+sDate+"' and type='Debit' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public ArrayList<TrialInfo> trialBalanceInstantLoan(Date startDate, Date endDate,int branchId, Connection conn) 
	{
		boolean chk=true;
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		ArrayList<TrialInfo> list=new ArrayList<>();
		Statement st=null;ResultSet rs=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from borrower_lender where type='lender' ";
			 rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rs.next())
			{
				TrialInfo tt=new TrialInfo();
				
				//if(chk==true)
				{
					tt.setCategory("Instant Loan");
					chk=false;
				}
				String pid=rs.getString("id");
				tt.setParticular(rs.getString("name"));
				double val=openingInstantLoan(sDate, pid, "debit")-openingInstantLoan(sDate, pid, "credit");
				if(val>0)
				{
					tt.setOpeningCr(Math.abs(val));
				}
				else
				{
					tt.setOpeningDr(Math.abs(val));
				}
				tt.setCredit(new DataBaseReportMethods().instantLoanAmount(branchId,startDate,endDate, pid, "debit"));
				tt.setDebit(new DataBaseReportMethods().instantLoanAmount(branchId,startDate,endDate, pid, "credit"));
				
				list.add(tt);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}

		return list;
	}

	private double openingInstantLoan(String sDate, String pid, String string) 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select sum(amount) from lender_record where lender_date<'"+sDate+"' and lender_id='"+pid+"' and status='"+string+"' and chequeStatus='cleared' ";
			//// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public ArrayList<TrialInfo> trialBalanceInstantBorrow(Date startDate, Date endDate,int branchId, Connection conn) 
	{
		boolean chk=true;
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		ArrayList<TrialInfo> list=new ArrayList<>();
		Statement st=null;ResultSet rs=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from borrower_lender where type='borrower' ";
			 rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rs.next())
			{
				TrialInfo tt=new TrialInfo();
				
			//	if(chk==true)
				{
					tt.setCategory("Instant Borrow");
					chk=false;
				}
				String pid=rs.getString("id");
				double val=openingBorrowAmount(sDate, pid, "credit")-openingBorrowAmount(sDate, pid, "debit");
				if(val>0)
				{
					tt.setOpeningCr(Math.abs(val));
				}
				else
				{
					tt.setOpeningDr(Math.abs(val));
				}
				tt.setParticular(rs.getString("name"));
				tt.setCredit(new DataBaseReportMethods().instantBorrowAmount(branchId,startDate,endDate, pid, "credit"));
				tt.setDebit(new DataBaseReportMethods().instantBorrowAmount(branchId,startDate,endDate, pid, "debit"));
				
				list.add(tt);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}

		return list;
	}

	private double openingBorrowAmount(String sDate, String pid, String string) 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();)
		{
			Statement st=con.createStatement();
			String qq="select sum(amount) from borrower_record where borrow_date<'"+sDate+"' and borrower_id='"+pid+"' and status='"+string+"' and chequeStatus='cleared' ";
			//// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public ArrayList<TrialInfo> trialBalanceAllIncome(Date startDate,Date endDate,int branchId, Connection conn) 
	{
		boolean chk=true;
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		ArrayList<TrialInfo> list=new ArrayList<>();
		Statement st=null;ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			String qq="select * from group_head where group_head_type='income' ";
			 rr=st.executeQuery(qq);
			while(rr.next())
			{
				TrialInfo tt=new TrialInfo();
				//if(chk==true)
				{
					//// // // //System.out.println("exp Indirect");
					tt.setCategory("Income (Indirect)");
					chk=false;
				}
				tt.setParticular(rr.getString("group_head_name"));
				tt.setOpeningCr(openingIncomeBalance(branchId,rr.getString("group_head_name"), sDate,conn));
				double amt=otherIncomeAmount(branchId,rr.getString("group_head_name"), sDate, eDate);
				tt.setCredit(amt);
				tt.setDebit(0);
				
				list.add(tt);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}

		return list;
	}

	public double openingIncomeBalance(int branchId,String itemName, String sDate, Connection conn) 
	{
		Statement st=null;ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount) from income_table where  income_date<'"+sDate+"' and category='Other_Cr' and chequeStatus='cleared' ";
			if(!itemName.equalsIgnoreCase("all"))
			{
				qq+=" and item='"+itemName+"' ";
			}
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
			   return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
			}
		}	
		return 0;
	}
	
	public double openingFixedAssetsPurchaseBalance(int branchId,String itemName, String sDate, Connection conn) 
	{
		Statement st=null;ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount) from expense_table where  expense_date<'"+sDate+"' and category='Fixed_Asset_Dr' and chequeStatus='cleared' and status='active' ";
			if(!itemName.equalsIgnoreCase("all"))
			{
				qq+=" and item='"+itemName+"' ";
			}
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
			   return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
			}
		}	
		return 0;
	}

	public double openingExpenseAmount(int branchId,String itemName, String sDate, Connection conn) 
	{
		Statement st=null;ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount) from expense_table where item='"+itemName+"' and expense_date<'"+sDate+"' and category!='Fixed_Asset_Dr' and chequeStatus='cleared' and status='active' ";
			if(!itemName.equalsIgnoreCase("all"))
			{
				qq+=" and item='"+itemName+"' ";
			}
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
			   return rr.getDouble("sum(amount)");
			  
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
			}
		}	
		return 0;
	}

	private double otherExpenseAmount(String string, String sDate, String eDate,int branchId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from expense_table where item='"+string+"' and expense_date>='"+sDate+"' and expense_date<='"+eDate+"' and category!='Fixed_Asset_Dr' and chequeStatus='cleared' and status='active'";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
			   return rr.getDouble("sum(amount)");
			  
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	private double otherIncomeAmount(int branchId,String string, String sDate, String eDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from income_table where item='"+string+"' and income_date>='"+sDate+"' and income_date<='"+eDate+"' and category='Other_Cr' and status='active' and chequeStatus='cleared' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
			   return rr.getDouble("sum(amount)");
			  
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public void updateFileChargeAndInsuranceFeeInIncomeTable(String loanNo, String fileCharge, String string,Connection conn)
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="update income_table set amount='"+fileCharge+"' where loan_no='"+loanNo+"' and item='"+string+"' ";
			int i=	st.executeUpdate(qq);
			if(i>0)
			{	
				dataInsertInQueryTable(qq, conn);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}

	public ArrayList<SelectItem> loanNoList(String loanType,int branchId) 
	{
		String loanNo, shno="";
		ArrayList<SelectItem> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from  "+loanType+" where status='Approve' and paidStatus='unpaid' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				SelectItem ss=new SelectItem();
				
				if(loanType.equals("grouploan"))
				{
					shno=rr.getString("teamLeader");
					loanNo=rr.getString("sub_loan_no");
				}
				else
				{
					loanNo=rr.getString("loanNo");
					shno=rr.getString("shareholderno");
				}
				String name=firstApplicantNameBySHNo(shno,conn);
				
				
				ss.setLabel(loanNo+"/"+name);
				ss.setValue(loanNo);
				
				list.add(ss);
			}
			
			
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	

	public double salaryExpenseAmount(int branchId,Date startDate, Date endDate, Connection conn) 
	{   
		System.out.println("branch is is:"+branchId);
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		Statement st=null;
		ResultSet rr=null;
		try
		{   
			st=conn.createStatement();
			String qq="select sum(amount) from salary_ledger where payDate>='"+sDate+"' and payDate<='"+eDate+"' and type='Debit' AND branch_id='"+branchId+"' ";   //and payment_mode!='Transfer'
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			System.out.println("salary payout : " + qq);
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	public double dsaCommissionExpenseAmount(int branchId,Date startDate, Date endDate,Connection conn) 
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount) from return_dsa where pay_date>='"+sDate+"' and pay_date<='"+eDate+"'  ";       ///and payment_mode!='Transfer' 
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	
	public double totalEmiReceiveAmount(Date startDate, Date endDate,int branchId, Connection conn) 
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount),sum(interestAmount) from loanpayment  where pay_date>='"+sDate+"' and pay_date<='"+eDate+"' and receipt_status='approved' and chequeStatus='cleared' ";
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)")-rr.getDouble("sum(interestAmount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	public double totalInstantBorrowAmount(Date startDate, Date endDate,int branchId, Connection conn) 
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		double totalDr = 0, totalCr = 0, total = 0;
		try
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from borrower_record  where borrow_date>='"+sDate+"' and borrow_date<='"+eDate+"' and status='credit' and chequeStatus='cleared' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				totalCr=rr.getDouble("sum(amount)");
			}
			
			String qq1="select sum(amount) from borrower_record  where borrow_date>='"+sDate+"' and borrow_date<='"+eDate+"' and status='debit' and chequeStatus='cleared' ";
			ResultSet rr1=st.executeQuery(selectQueWithBranch(qq1,branchId));;
			if(rr1.next())
			{
				totalDr=rr1.getDouble("sum(amount)");
			}
			
			total=totalCr-totalDr;
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return total;
	}

	public double totalInstantLoanAmount(Date startDate, Date endDate,int branchId,Connection conn) 
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		Statement st=null;ResultSet rr=null;
		double totalDr = 0, totalCr = 0, total = 0;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount) from lender_record  where lender_date>='"+sDate+"' and lender_date<='"+eDate+"' and status='credit' and chequeStatus='cleared' ";
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				totalCr=rr.getDouble("sum(amount)");
			}
			
			String qq1="select sum(amount) from lender_record  where lender_date>='"+sDate+"' and lender_date<='"+eDate+"' and status='debit' and chequeStatus='cleared' ";
			ResultSet rr1=st.executeQuery(selectQueWithBranch(qq1,branchId));;
			if(rr1.next())
			{
				totalDr=rr1.getDouble("sum(amount)");
			}
			
			total=totalCr-totalDr;
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return total;
	}
	
	
	public void updateOldLoanRestructureStatus(String loanNo, String loanType) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update "+loanType+" set restructure_Status='yes' where loanNo='"+loanNo+"' ";
		      int i = st.executeUpdate(qq);
			if(i>0){
			dataInsertInQueryTable(qq, conn);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}

	public ArrayList<String> collectionlist(Date endDate, ArrayList<SelectItem> loanTypeList, String reportType,int branchId, String dsaCode,String center, Connection conn)
	{
		Statement st=null;
		ResultSet rs=null;
		String eDate=sdfForDb.format(endDate);
		ArrayList<String> list= new ArrayList<>();
		
			try
					{
					if(reportType.equals("Loan"))
						{
						for(SelectItem ff:loanTypeList)
						 {
							st=conn.createStatement();
							String query="select * from "+ff.getValue()+" where status='Approve' and paidStatus='unpaid' ";
							if(!dsaCode.equalsIgnoreCase("-1") && !dsaCode.equalsIgnoreCase("all"))
							{
								query+=" and dsacode='"+dsaCode+"' ";
							}
							
							if(!center.equalsIgnoreCase("-1") && !center.equalsIgnoreCase("all"))
							{
								query+=" and center='"+center+"' ";
							}
							
							rs= st.executeQuery(selectQueWithBranch(query,branchId));
						    while(rs.next())
							    {
							    	if(ff.getValue().equals("grouploan"))
										{
											list.add(rs.getString("sub_loan_no"));
										}
							    	else
								    	{
								    	list.add(rs.getString("loanNo"));
								    	}
							    }   
						    }
						}
					else
						{

						st=conn.createStatement();
						String query="select * from "+reportType+" where status='Approve' and paidStatus='unpaid' ";
						if(!dsaCode.equalsIgnoreCase("-1") && !dsaCode.equalsIgnoreCase("all"))
						{
							query+=" and dsacode='"+dsaCode+"' ";
						}
						
						if(!center.equalsIgnoreCase("-1") && !center.equalsIgnoreCase("all"))
						{
							query+=" and center='"+center+"' ";
						}
						
						rs= st.executeQuery(selectQueWithBranch(query,branchId));
					    while(rs.next())
						    {
						    	if(reportType.equals("grouploan"))
									{
										list.add(rs.getString("sub_loan_no"));
									}
						    	else
							    	{
							    	   list.add(rs.getString("loanNo"));
							    	}
						    }   
					    
						
						}
					}
	
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
			finally
			{
				try {
					if(st!=null)
					{
						st.close();
					}
					if(rs!=null)
					{
						rs.close();
					}
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
		return list;
		
	}

	public String ApproveDate(String string,int branchId)
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from personalloan where loanNo='"+string+"' ";
		    ResultSet rs= st.executeQuery(selectQueWithBranch(query,branchId));
			if(rs.next())
			{
				return rs.getString("approvalDate");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return null;
	}

	public int term(String string,int branchId) {
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from personalloan where loanNo='"+string+"' ";
		    ResultSet rs= st.executeQuery(selectQueWithBranch(query,branchId));
			if(rs.next())
			{
				return rs.getInt("terms");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public double amountPaid(String loanNo, Date endDate,Connection conn) {
		String eDate=sdfForDb.format(endDate);
		ArrayList<String> list= new ArrayList<>();
		Statement st=null;
		ResultSet rs=null;
		double amount=0.00;
		try
		{
			
			st=conn.createStatement();
			String query="select sum(amount) from loanpayment where loanNo='"+loanNo+"' and  pay_date<='"+eDate+"' and receipt_status='approved' and chequeStatus='cleared'";
		     rs= st.executeQuery(query);
			if(rs.next())
			{
				amount=rs.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try 
			{
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} 
			catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return amount;
	}

	public ArrayList<LoanInfo> loanInstallment1(ArrayList<SelectItem> loanTypeList,String loanNo,Connection conn)
    {
        double temp=0;
        String qq="";
        int j=0,count=0;
        Statement st=null;
        ResultSet rs=null;
        String loanType="";
        ArrayList<LoanInfo> list = new ArrayList<LoanInfo>();
        try 
        {
        	for(SelectItem ff:loanTypeList)
        	{
        		if(count==0)
        		{
        		 loanType=(String) ff.getValue();
        	
        	
        	
             st = conn.createStatement();
            if(loanType.equals("grouploan"))
            {
                qq = "select * from "+loanType+" where sub_loan_no='"+loanNo+"' and status='approve'";
            }
            else
            {
                qq = "select * from "+loanType+" where loanNo='"+loanNo+"' and status='approve'";
            }
           
            rs = st.executeQuery(qq);
            if(rs.next())
            {
                count=count+1;	
                if(rs.getString("emiType").equals("reducing"))
                {
                    double discount=discountOnLastEMI(loanType,loanNo, conn);
                    double paidAmount=loanPaidAmountByUser(loanType,loanNo,conn);
                    int terms = rs.getInt("terms");
                    int frequency=rs.getInt("frequency");
                    double emi=rs.getDouble("emi");
                    double interstRate=rs.getDouble("interest");
                    double loanAmount=rs.getDouble("loanAmount");
                    double interestMonthly =Double.parseDouble(new DecimalFormat("##.###").format(interstRate / (100.00 * frequency)));
                    Date installDate=null;
                    j=365/frequency;
                    if(rs.getDate("emi_due_date")==null)
                    {
                        installDate=rs.getDate("approvalDate");
                    }
                    else
                    {
                        installDate=rs.getDate("emi_due_date");
                        if(frequency==12)
                        {
                            installDate.setMonth(installDate.getMonth()-1);
                        }
                        else
                        {
                            installDate.setDate(installDate.getDate()-j);
                        }
                    }   
                   
                    for (int i = 1; i<= terms; i++)
                    {
                        LoanInfo ll=new LoanInfo();
                        ll.setSno(i);
                        if(i==terms)
                        {
                            emi=emi-discount;
                            ll.setInstallAmount(emi);
                        }
                        else
                        {
                            ll.setInstallAmount(emi);
                        }
                       
                        if(paidAmount>=emi)
                        {
                            ll.setStatus("Paid");
                            ll.setPaidAmount(emi);
                            ll.setDueAmount(0);
                            paidAmount=Double.parseDouble(df.format(paidAmount-emi));
                        }
                        else
                        {
                            ll.setStatus("Due");
                            ll.setPaidAmount(paidAmount);
                            ll.setDueAmount(Double.parseDouble(df.format(emi-paidAmount)));
                            paidAmount=0;
                        }
                   
                        Date dt=installDate;
                        if(rs.getDate("emi_due_date")==null)
                        {
                            dt.setDate(dt.getDate()+j);
                        }
                        else
                        {
                            if(frequency==12)
                            {
                                dt.setMonth(dt.getMonth()+1);
                            }
                            else
                            {
                                dt.setDate(dt.getDate()+j);
                            }
                           
                        }

                        ll.setStrInstlmntDate(sf.format(dt));
                       
                       
                        SimpleDateFormat dd=sf;
                        Date ss=dd.parse(ll.getStrInstlmntDate());
                        ll.setInstallDate(ss);
                       
                        double frstIntrstAmnt=loanAmount*interestMonthly;
                        ll.setInterestAmount(df.format((frstIntrstAmnt)));
                       
                        double paidPrincipalAmnt=emi-(frstIntrstAmnt);
                        ll.setPrincipalAmount(df.format(paidPrincipalAmnt));
                       
                        double principalRemaining=loanAmount-paidPrincipalAmnt;
                       
                        list.add(ll);
                        loanAmount=principalRemaining;
                    }
                }
                else
                {
                    double discount=discountOnLastEMI(loanType,loanNo, conn);
                    double paidAmount=loanPaidAmountByUser(loanType,loanNo, conn);
                    int terms = rs.getInt("terms");
                    int frequency=rs.getInt("frequency");
                    double emi=rs.getDouble("emi");
                    double interstRate=rs.getDouble("interest");
                    double loanAmount=rs.getDouble("loanAmount");
                    double totalInterest=Double.parseDouble(df.format((emi*terms)-loanAmount));
                    double interestMonthly=(totalInterest-rs.getDouble("discount"))/terms;
                    Date installDate=null;
                    j=365/frequency;
                   
                    if(rs.getDate("emi_due_date")==null)
                    {
                        installDate=rs.getDate("approvalDate");
                    }
                    else
                    {
                        installDate=rs.getDate("emi_due_date");
                        if(frequency==12)
                        {
                            installDate.setMonth(installDate.getMonth()-1);
                        }
                        else
                        {
                            installDate.setDate(installDate.getDate()-j);
                        }
                    }
                    for (int i = 1; i<= terms; i++)
                    {
                        LoanInfo ll=new LoanInfo();
                        ll.setSno(i);
                        if(i==terms)
                        {
                            emi=emi-discount;
                            ll.setInstallAmount(emi);
                        }
                        else
                        {
                            ll.setInstallAmount(emi);
                        }
                       
                        if(paidAmount>=emi)
                        {
                            ll.setStatus("Paid");
                            ll.setPaidAmount(emi);
                            ll.setDueAmount(0);
                            paidAmount=Double.parseDouble(df.format(paidAmount-emi));
                        }
                        else
                        {
                            ll.setStatus("Due");
                            ll.setPaidAmount(paidAmount);
                            ll.setDueAmount(Double.parseDouble(df.format(emi-paidAmount)));
                            paidAmount=0;
                        }
                   
                        Date dt=installDate;
                        if(rs.getDate("emi_due_date")==null)
                        {
                            dt.setDate(dt.getDate()+j);
                        }
                        else
                        {
                            if(frequency==12)
                            {
                                dt.setMonth(dt.getMonth()+1);
                            }
                            else
                            {
                                dt.setDate(dt.getDate()+j);
                            }
                        }

                        ll.setStrInstlmntDate(sf.format(dt));
                        SimpleDateFormat dd=sf;
                        Date ss=dd.parse(ll.getStrInstlmntDate());
                        ll.setInstallDate(ss);
                        double frstIntrstAmnt=interestMonthly;
                        ll.setInterestAmount(df.format((frstIntrstAmnt)));
                        double paidPrincipalAmnt=emi-(frstIntrstAmnt);
                        ll.setPrincipalAmount(df.format(paidPrincipalAmnt));
                        list.add(ll);
                    }
                }
            }
            }
        }
    }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        finally
        {
        	try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
        }
       
        return list;
        
        
    }

	public ArrayList<String> listRdFd(Date endDate, String reportType,int branchId, String dsaCode) 
	{
		String eDate=sdfForDb.format(endDate.getTime());
		ArrayList<String> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select user_no from customer_info where scheme_type='"+reportType+"' and account_status='active' and paid_status='unpaid' ";
			if(!dsaCode.equalsIgnoreCase("-1") && !dsaCode.equalsIgnoreCase("all"))
			{
				qq+=" and dsa_code='"+dsaCode+"' ";
			}
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
		//	// // // //System.out.println(qq);
			while(rr.next())
			{
			    list.add(rr.getString("user_no"));
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	public Double amountWithInDateRange(String loanNo, Date startDate, Date endDate,Connection conn)
	{
		String eDate=sdfForDb.format(endDate);
		String sDate=sdfForDb.format(startDate);
		ArrayList<String> list= new ArrayList<>();
		double amount=0.00;
		Statement st=null;
		ResultSet rs=null;
		try
		{
			
			st=conn.createStatement();
			String query="select sum(amount) from loanpayment where loanNo='"+loanNo+"' and pay_date>='"+sDate+"' AND pay_date<='"+eDate+"' and receipt_status='approved' and chequeStatus='cleared'";
		    rs= st.executeQuery(query);
		//    // // // //System.out.println(query);
			if(rs.next())
			{
				amount=rs.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try
			{
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} 
			catch (Exception e2)
			{
				// TODO: handle exception
			}
		}
		return amount;
	}
	public double rdAmountPaid(String loanNo, Date endDate) {
		String eDate=sdfForDb.format(endDate);
		ArrayList<String> list= new ArrayList<>();
		double amount=0.00;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			
			Statement st=conn.createStatement();
			String query="select sum(amount) from payment_receipt where user_no='"+loanNo+"' and date<='"+eDate+"' and receipt_status='approved' and chequeStatus='cleared'";
		    ResultSet rs= st.executeQuery(query);
		//	// // // //System.out.println(query);
		    if(rs.next())
			{
				amount=rs.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return amount;
	}
	public Double rdAmountWithInDateRange(String loanNo, Date startDate, Date endDate)
	{
		String eDate=sdfForDb.format(endDate);
		String sDate=sdfForDb.format(startDate);
		ArrayList<String> list= new ArrayList<>();
		double amount=0.00;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			
			Statement st=conn.createStatement();
			String query="select sum(amount) from payment_receipt where user_no='"+loanNo+"' and date<='"+eDate+"' And Date>='"+sDate+"' and receipt_status='approved' and chequeStatus='cleared'";
		//	// // // //System.out.println(query);
		    ResultSet rs= st.executeQuery(query);
			if(rs.next())
			{
				amount=rs.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return amount;
	}
	public ArrayList<SelectItem> loanTypeList1()
	{
		ArrayList<SelectItem> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from loan_table where loan_permission='true' ";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				SelectItem ss=new SelectItem();
				
				ss.setLabel(rr.getString("loan_label"));
				ss.setValue(rr.getString("loan_type"));
				
				list.add(ss);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}

	public ArrayList<LoanInfo> allDDList(String dsaCode, String searchType, Date payDate, String center,String searchBase, int branchId)
	{
		ArrayList<LoanInfo> list=new ArrayList<>();
		int sNo=1;
		String userId="";
		boolean checkCenter=false;
		String qq="";
		double amountLeftToPaid=0.00;
		String strPayDate=sdfForDb.format(payDate);
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(dsaCode.equals("-1"))
			{
				 qq="SELECT * FROM customer_info where scheme_type='"+searchType+"' ";
			}
			else
			{
				qq="SELECT * FROM customer_info where scheme_type='"+searchType+"' and dsa_code='"+dsaCode+"' ";
			}
			qq+=" and account_status='active' and branch_id='"+branchId+"' and office_date<='"+strPayDate+"' order by user_no asc ";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next()) 
			{
				LoanInfo cate = new LoanInfo();
				userId=rr.getString("user_no");
				if(!center.equalsIgnoreCase("-1"))
				{
					checkCenter=checkCenterForDepositInGroupLoan(rr.getString("shareHolderNo"), center, conn);  // Code Develope for RD show Center Wise
				}
				if(center.equalsIgnoreCase("-1") || checkCenter==true)
				{
					  amountLeftToPaid=amountToPaidList(rr.getString("user_no"))-amountPaidList(rr.getString("user_no"),conn);
						if(amountLeftToPaid!=0.00)
						{
							cate.setId(rr.getString("id"));
							cate.setUserId(userId);
							cate.setPaidAmount(0.00);
							cate.setInstallAmount(rr.getDouble("installment_amount"));
						    cate.setTotalAmountToBePaid(amountToPaidList(userId));
						    cate.setAmountPaid(amountPaidList(userId, conn));
							cate.setShareHolderNo(rr.getString("shareHolderNo"));
							cate.setApplicantName(shareHolderNameByShareHolderNo(rr.getString("shareHolderNo"),conn));
							cate.setContactNo(applicantContactNoByShareHolderNo(rr.getString("shareHolderNo"), conn));
							cate.setAddress(shareHolderDetailByColumnName(rr.getString("shareHolderNo"), "address", conn));
							cate.setAmountLeftPaid(amountLeftToPaid);
							cate.setDsacode(rr.getString("dsa_code"));
							cate.setDsaName(dsaNameById(rr.getString("dsa_code"),conn));
							cate.setPlanNo(rr.getString("plan_no"));
							
							if(searchType.equals("DD"))
							{
								cate.setSno(sNo++);
								
								int days =(int) ((new Date().getTime() - rr.getDate("office_date").getTime()) / (1000 * 60 * 60 * 24));
								/*String datStr=String.valueOf(daysdb);
								String arr[]=datStr.split(".//")
								int days=
								//System.out.println(days+"==="+new Date().getTime()+"============"+rr.getDate("office_date").getTime());*/
								if(days<=rr.getInt("terms"))
								{
									double tot=days*cate.getInstallAmount();
									cate.setTillLeft(tot-cate.getAmountPaid());
								}
								cate.setDisBtn(false);
								list.add(cate);
							}
							else if(searchType.equals("FD"))
							{
								cate.setDisBtn(true);
								cate.setSno(sNo++);
								list.add(cate);
							}	
							else 
							{
								/*if(rr.getInt("frequency")==12)
								{
									Date date=rr.getDate("office_date");
									SimpleDateFormat sdf = new SimpleDateFormat("dd");
									int day = Integer.parseInt(sdf.format(date));
									int day2=payDate.getDate();
									if(day==day2)
									{
										// //System.out.println(day+"==="+day2+" deposit date: "+rr.getDate("office_date"));
										cate.setSno(sNo++);
										list.add(cate);
									}
								}*/  //temp solution
								
								// Code written on 27-Feb-2021 
								ArrayList<InstallmentInfo> rdEmilist=showInstallment(userId,conn);
								for(int l=0;l<rdEmilist.size();l++)
								{
									Date dt=new Date();
									if(rdEmilist.get(l).getStatus().equalsIgnoreCase("due"))
									{
										if(rdEmilist.get(l).getInstlmntDate().before(dt))
										{
											cate.setTillLeft(cate.getTillLeft()+rdEmilist.get(l).getDueAmount());
										}	
									}
								}
								
								if(searchBase.equalsIgnoreCase("all"))
								{
									cate.setSno(sNo++);
									cate.setDisBtn(false);
									list.add(cate);
								}
								else
								{
									ArrayList<String> dateList=createRdDateList(rr, conn);
									for(String dd: dateList)
									{
										String payDateStr=sdfForDb.format(payDate);
										//System.out.println(dd+"List ====="+payDate);
										if(payDateStr.equals(dd))
										{
											cate.setSno(sNo++);
											cate.setDisBtn(false);
											list.add(cate);
										}
									}
								}
							}
							
						}
				}
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}
	
	
	private boolean checkCenterForDepositInGroupLoan(String memberNo, String center, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select center from grouploan where teamLeader='"+memberNo+"' and status='Approve' and paidStatus='unpaid' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				if(rr.getString("center").equals(center))
				{
					return true;
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return false;
	}

	public ArrayList<String> createRdDateList(ResultSet rr,Connection conn) throws SQLException 
	{
		boolean checkEMIForward=checkGroupLoanEmiFromTable(rr.getString("user_no"), conn);
		ArrayList<String> dateList=new ArrayList<>();
		Date offcdt = rr.getDate("customer_info.office_date");
		String user_no=rr.getString("user_no");
		int terms = rr.getInt("customer_info.terms");
		int frequency=rr.getInt("customer_info.frequency");
		double instlmnt_amnt = rr.getDouble("customer_info.installment_amount");
		double intrst =rr.getDouble("customer_info.interest");
		double paidAmount = paidAmountByUser(user_no,conn);
		double mnthly_intrst =intrst / frequency;
		double instlmnt = instlmnt_amnt;
		
		int x=0,y=1,z=0;
		if(frequency==4)
	    {
			y=4;
	    }
	    else if(frequency==2)
	    {
	    	y=6;
	    }
	    else if(frequency==1)
	    {
	    	y=12;
	    }
	    else if(frequency==12)
	    {
	    	y=1;
	    }
	    else if(frequency==365)
        {
	    	z=1;
        }
        else if(frequency==36)
        {
        	z=10;
        }
        else if(frequency==24)
        {
        	z=15;
        }
        else if(frequency==52)
        {
        	z=7;
        }
        else if(frequency==26)
        {
        	z=14;
        }
        else if(frequency==13)
        {
        	z=28;
        }
        
		int i;
		int d=offcdt.getDate();
		for (i = 1; i <= terms; i++) 
		{
			
			if (paidAmount >= instlmnt)
			{
				
			}
			else if (paidAmount < instlmnt && paidAmount > 0) 
			{
				dateList.add(sdfForDb.format(offcdt));
			}
			else 
			{
				dateList.add(sdfForDb.format(offcdt));
			}
			//// //System.out.println(user_no+"==="+offcdt);
			paidAmount = paidAmount - instlmnt;
			
			if(checkEMIForward==false)
			{
				if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
		        {
					offcdt=createDate2(offcdt,y,terms,d,rr.getDate("customer_info.office_date"));
				}
				else
				{
					offcdt=createDate3(offcdt,z);
				}
			}
			else
			{
				offcdt=groupLoanEmiDateFromTable(i, user_no, conn);
			}
			
			
			Date toDate=new Date();
			if(offcdt.after(toDate))
			{
				break;
			}
		}	
		return dateList;
	}


	
	public ArrayList<LoanInfo> allDailyLoanList(String dsaCode,int branchId,  String searchType, Date payDate)
	{
		ArrayList<LoanInfo> list=new ArrayList<>();
		int sNo=1;
		String qq="";
		double amountLeftToPaid=0.00;
		String frequencylabel="";
		String strPayDate=sdfForDb.format(payDate);
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(dsaCode.equals("-1"))
			{
				qq="SELECT * FROM "+searchType+" where frequency in('365','365.0') ";
			}
			else
			{
				qq="SELECT * FROM "+searchType+" where frequency in('365','365.0') and dsacode='"+dsaCode+"' ";
			}
			qq+=" and status='Approve' and paidStatus='unpaid' and restructure_status='no' and approvalDate<='"+strPayDate+"' and branch_id='"+branchId+"' order by loanNo asc";
			System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				LoanInfo cate = new LoanInfo();
				String loanNo=rr.getString("loanNo");
				double totPayble=rr.getDouble("emi")*rr.getDouble("terms");
				double savingTotal=rr.getDouble("extra_amount")*rr.getDouble("terms");
				double loanAmtPaid=loanPaidAmountByUser(searchType,loanNo, conn);
				double savingAmtPaid=savingPaidAmountByUser(branchId,loanNo,conn);
			    amountLeftToPaid=totPayble-loanAmtPaid;
				if(amountLeftToPaid>0.00)
				{
					cate.setSno(sNo++);
					cate.setUserId(loanNo);
					cate.setId(rr.getString("id"));
					//cate.setPaidAmount(0.00);
					cate.setInstallAmount(rr.getDouble("emi"));
				    cate.setLoanAmount(String.valueOf(rr.getDouble("loanAmount")));
				    cate.setInterestAmount(String.valueOf(totPayble-rr.getDouble("loanAmount")));
				    cate.setSavingTotal(savingTotal); //For Saving
					cate.setTotalAmountToBePaid(totPayble);
					cate.setTotalAmountToBePaidSaving(totPayble+savingTotal);  //For Saving
				    cate.setAmountPaid(loanAmtPaid);
				    cate.setAmountPaidSaving(loanAmtPaid+savingAmtPaid);
				    cate.setShareHolderNo(rr.getString("shareholderno"));
				    UserInfo uu=memberBasicDetail(cate.getShareHolderNo(), conn);      // update on 03-march-2021
					cate.setApplicantName(uu.getName());
					cate.setContactNo(uu.getContactNo());
					cate.setFatherHusbandName(uu.getFather_husband_name());
					cate.setAddress(uu.getAddress());
					cate.setStrApprovalDate(sf.format(rr.getDate("approvalDate")));
					
					cate.setAmountLeftPaid(amountLeftToPaid);
					cate.setAmountLeftPaidSaving(cate.getTotalAmountToBePaidSaving()-cate.getAmountPaidSaving());
					cate.setDsacode(rr.getString("dsacode"));
					cate.setDsaName(dsaNameById(rr.getString("dsacode"),conn));
					cate.setPlanNo(rr.getString("plan_no"));
					cate.setExtraAmt(rr.getDouble("extra_amount"));
					cate.setTotEmiAmt(cate.getInstallAmount()+cate.getExtraAmt());
					
					
					Date dt=null;
					if(rr.getDate("emi_due_date")!=null)
					{
						dt=rr.getDate("emi_due_date");
					}
					else
					{
						dt=rr.getDate("approvalDate");
					}
					int days =(int) ((new Date().getTime() - dt.getTime()) / (1000 * 60 * 60 * 24));
					int holiDay= new DataBaseMethodsSalary().countHolidayBetweenDate(payDate, dt, conn);
					days=days-holiDay;
					cate.setDays(days);
					if(days<=rr.getInt("terms"))
					{
						double tot=days*cate.getInstallAmount();
						double totSv=days*rr.getInt("extra_amount");
						cate.setTillLeft(tot-cate.getAmountPaid());
						cate.setTillLeftSaving((tot+totSv)-cate.getAmountPaidSaving());
					}
					else
					{
						double tot=rr.getInt("terms")*cate.getInstallAmount();
						double totSv=rr.getInt("terms")*rr.getInt("extra_amount");
						cate.setTillLeft(tot-cate.getAmountPaid());
						cate.setTillLeftSaving((tot+totSv)-cate.getAmountPaidSaving());
					}
					

				    list.add(cate);
				}
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}

	public double savingPaidAmountByUser(int branchId,String loanNo, Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from customer_deposit where remark like '%"+loanNo+"%' and status='approved' and type='deposit' ";
			//System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}

	public double amountToPaidList(String userId)
	{
		ArrayList<LoanInfo> list=new ArrayList<>();
		int sNo=1;
		double totalAmountToBePaid=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
			{
				Statement st=conn.createStatement();
				String qq="SELECT * FROM customer_info where user_no ='"+userId+"'";
				ResultSet rr=st.executeQuery(qq);
				if(rr.next())
					{
						if(rr.getString("scheme_type").equalsIgnoreCase("FD"))
						{
							totalAmountToBePaid=rr.getDouble("installment_amount");
						}
						else
						{
							double terms=rr.getDouble("terms");
							double instlAmount=rr.getDouble("installment_amount");
							totalAmountToBePaid=terms*instlAmount;
						}
						
						return totalAmountToBePaid;
					}
			}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return 0;
	}

	public double amountPaidList(String userId, Connection conn)
	{
		ArrayList<LoanInfo> list=new ArrayList<>();
		int sNo=1;
		try
			{
				Statement st=conn.createStatement();
				String qq="SELECT sum(amount) FROM payment_receipt where user_no='"+userId+"'and receipt_status='approved' and chequeStatus='cleared'";
				ResultSet rr=st.executeQuery(qq);
				if(rr.next())
					{
					  return rr.getDouble("sum(amount)");
					}
			}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return 0;
	}
	
	public double depositAmountPaidTillDate(Date searchDate,String userNo, Connection conn)
	{
		String sDate=sdfForDb.format(searchDate);
		ArrayList<LoanInfo> list=new ArrayList<>();
		int sNo=1;
		try
		{
			Statement st=conn.createStatement();
			String qq="SELECT sum(amount) FROM payment_receipt where user_no='"+userNo+"' and date<='"+sDate+"' and receipt_status='approved' and chequeStatus='cleared'";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
			  return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	 int insertLogDetails(String userId,int branchId,  Connection conn)
	 {
	        Timestamp ts;
	        ts = new Timestamp((new Date()).getTime());
	        ts.setNanos(0);
	        conn = DataBaseConnection.JAVAConnection();
	        int i;
	        String query1 = "insert into log_table(user_name,login_time,branch_id) value(?,?,?)";
	        try
	        {
	           PreparedStatement pst = conn.prepareStatement(query1);
	           pst.setString(1, userId);
	           pst.setTimestamp(2, ts);
	           pst.setInt(3, branchId);
	           i = pst.executeUpdate();
	           if(i == 1)
	           {
	        	   //dataInsertInQueryTable(String.valueOf(pst), conn);
	               return 1;
	        }}
	        catch(Exception ex)
	        {
	           ex.printStackTrace();
	        }
	        finally
	        {
	            try 
	            {conn.close();}
	            catch (SQLException e)
	            { e.printStackTrace();fileCreation(e.getMessage());}
	        }    
	        return 0;
	}

	public void logout(String userId)
	{
	
	        
	        Timestamp ts = new Timestamp((new Date()).getTime());
	        ts.setNanos(0);
	        try(Connection conn = DataBaseConnection.JAVAConnection();)
	        {
	            Statement st = conn.createStatement();
	            String query="update log_table set logout_time='"+ts+"' where user_name='"+userId+"' order by id desc limit 1 ";
	            int i= st.executeUpdate(query);
	            if(i>0)
	            {
	              dataInsertInQueryTable(query, conn);
	            }
	           
	        }
	        catch(Exception e)
	        {
	             e.printStackTrace();fileCreation(e.getMessage());
	            fileCreation(e.getMessage());
	        }
	    }

	
	public ArrayList<EmployeeInfo> logReportByDate(Date startDate, Date endDate,int branchId) 
    {
        Timestamp tt=new Timestamp(startDate.getTime());
        Timestamp et=new Timestamp(endDate.getTime());
        
        int i=1;
        ArrayList<EmployeeInfo> list=new ArrayList<>();
        try(Connection conn=DataBaseConnection.JAVAConnection())
	        {
	            Statement st=conn.createStatement();
	            String query="select * from log_table where login_time between '"+tt+"' and '"+et+"' order by login_time desc ";
	            ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
	            while(rr.next())
		            {
		                EmployeeInfo ll=new EmployeeInfo();
		                ll.setUserId(rr.getString("user_name"));
		                ll.setLoginTime(rr.getString("login_time"));
		                ll.setLogoutTime(rr.getString("logout_time"));
		                ll.setsNo(String.valueOf(i++));
		                list.add(ll);
		            }
	        }
        catch(Exception e)
	        {
	             e.printStackTrace();fileCreation(e.getMessage());
	        }
        return list;
    }

	public ArrayList<LoanInfo> detailsList(String code)
	{
		ArrayList<LoanInfo> list=new ArrayList<>();
		int sNo=1;
        try(Connection conn=DataBaseConnection.JAVAConnection())
	        {
	            Statement st=conn.createStatement();
	            String query="select * from dsa where code='"+code+"'";
	            ResultSet rr=st.executeQuery(query);
	            while(rr.next())
		            {
	            	   LoanInfo cate = new LoanInfo();
	            	   cate.setSno(sNo++);
	            	   cate.setId(rr.getString("id"));
	            	   cate.setCategory(rr.getString("category_type"));
	            	   cate.setCommission(rr.getDouble("commission_value"));
	            	   cate.setCommissionType(rr.getString("commission_type"));
	            	   list.add(cate);
		            }
	        }
        catch(Exception e)
	        {
	             e.printStackTrace();fileCreation(e.getMessage());
	        }
        return list;
	}
	
	public int calculateTotalDepositInSelectedRd(String user_no,Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount) from payment_receipt where user_no='"+user_no+"' and receipt_status='approved' and chequeStatus='cleared' ";

			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getInt("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	    finally
			{
				try {
					if(st!=null)
					{
						st.close();
					}
					if(rr!=null)
					{
						rr.close();
					}
					
				} catch (Exception e2) {
					// TODO: handle exception
				}
			
			}
		return 0;
	}
	
	public ArrayList<UserInfo> showUserSelectedType(String searchType, String dsaCode,String accountStatus, String searchDeposit, int branchId) 
	{
		String qq ="";
		Date dt= new Date();
		ArrayList<UserInfo> list = new ArrayList<UserInfo>();
		 Timestamp tsDt = new Timestamp(dt.getTime());
		 SimpleDateFormat sdf = sdfForDb;
	     String dd = sdf.format(tsDt.getTime());
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			int i=0;
			Statement st = con.createStatement();
//			if(searchType.equalsIgnoreCase("All") && dsaCode.equalsIgnoreCase("All"))
//			{
//				qq = "select * from customer_info where account_status!='pending' ";
//			}
//			else if(searchType.equalsIgnoreCase("All") && !dsaCode.equalsIgnoreCase("All"))
//			{
//				qq = "select * from customer_info where account_status!='pending' and dsa_code='"+dsaCode+"' ";
//			}
//			else if(!searchType.equalsIgnoreCase("All") && dsaCode.equalsIgnoreCase("All"))
//			{
//				qq = "select * from customer_info where scheme_type='"+searchType+"' and account_status!='pending' ";
//			}
//			else if(!searchType.equalsIgnoreCase("All") && !dsaCode.equalsIgnoreCase("All"))
//			{
//				qq = "select * from customer_info where scheme_type='"+searchType+"' and account_status!='pending' and dsa_code='"+dsaCode+"'   ";
//			}
			
			qq = "select * from customer_info where account_status!='pending' ";
			
			if(searchType!=null && !searchType.equalsIgnoreCase("All"))
			{
				qq+=" and scheme_type='"+searchType+"'";
			}
			
			if(dsaCode!=null && !dsaCode.equalsIgnoreCase("All"))
			{
				qq+=" and dsa_code='"+dsaCode+"' ";
			}
			 
			if(accountStatus!=null && !accountStatus.equalsIgnoreCase("all"))
			{
				qq+=" and account_status='"+accountStatus+"' ";
			}
			
			if(searchDeposit!=null && !searchDeposit.equalsIgnoreCase("all"))
			{
				qq+=" and user_no='"+searchDeposit+"' ";
			}
			qq+=" and branch_id='"+branchId+"' order by id desc";
			ResultSet rs = st.executeQuery(qq);
			while (rs.next())
			{
				i=i+1;
				String hno=rs.getString("shareHolderNo");
				UserInfo uu = new UserInfo();
				uu=userInfoByShareHolderNo(hno, con);
				uu.setSno(i);
         		uu.setId(rs.getString("id"));
         		uu.setShareHolderNo(rs.getString("shareHolderNo"));
         		uu.setOffice_application_no(rs.getString("office_application_no"));
    			uu.setOffice_date(rs.getDate("office_date"));
    			uu.setStrOffcDate(sf.format(rs.getDate("office_date")));
				uu.setUser_no(rs.getString("user_no"));
				uu.setScheme_type(rs.getString("scheme_type"));
				uu.setPlan_no(rs.getString("plan_no"));
				uu.setTerms(rs.getInt("terms"));
				uu.setFrequency(rs.getInt("frequency"));
				uu.setApplicant_fees(rs.getDouble("applicant_fees"));
				uu.setInstallment_amount(rs.getDouble("installment_amount"));
				uu.setInterest(rs.getDouble("interest"));
				uu.setMaturity_value(rs.getDouble("maturity_value"));
				System.out.println("value of the maturity_Value :"+rs.getDouble("maturity_value")+"of User :"+rs.getString("shareHolderNo"));
				uu.setMaturity_date(rs.getDate("maturity_date"));
				uu.setStrMatDate(sf.format(rs.getDate("maturity_date")));
				uu.setDsaCode(rs.getString("dsa_code"));
				uu.setDsaName(dsaNameById(rs.getString("dsa_code"), con));
				uu.setPaidStatus(rs.getString("paid_status"));
				uu.setAccountStatus(rs.getString("account_status"));
				
				if(uu.getAccountStatus().equalsIgnoreCase("close"))
				{
					uu.setColorStatus("blue");
				}
				if(uu.getPaidStatus().equalsIgnoreCase("paid"))
				{
					uu.setColorStatus("orange");
				}
				
				if(uu.getAccountStatus().equalsIgnoreCase("active"))
				{
					uu.setDisable(false);
					uu.setColorStatus("green");
				}
				else
				{
					uu.setDisable(true);
				}
				double amt=paidAmountByUser(rs.getString("user_no"), con);
				uu.setPaidAmount(amt);
				if(amt>0)
				{
					uu.setDisableDelete(true);
				}
				else
				{
					uu.setDisableDelete(false);
					uu.setColorStatus("red");
				}
				
				list.add(uu);
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	
	public UserInfo selectedDepositDetail(String userNo,Connection con) 
	{
		UserInfo uu = new UserInfo();
		String qq ="";
		Date dt= new Date();
		 Timestamp tsDt = new Timestamp(dt.getTime());
		 SimpleDateFormat sdf = sdfForDb;
	     String dd = sdf.format(tsDt.getTime());
		try
		{
			int i=0;
			Statement st = con.createStatement();
			qq = "select * from customer_info where user_no='"+userNo+"' and account_status!='pending' ";
			ResultSet rs = st.executeQuery(qq);
			if (rs.next())
			{
				String hno=rs.getString("shareHolderNo");
				
         		uu.setId(rs.getString("id"));
         		uu.setShareHolderNo(rs.getString("shareHolderNo"));
         		uu.setOffice_application_no(rs.getString("office_application_no"));
    			uu.setOffice_date(rs.getDate("office_date"));
    			uu.setStrOffcDate(sf.format(rs.getDate("office_date")));
				uu.setUser_no(rs.getString("user_no"));
				uu.setScheme_type(rs.getString("scheme_type"));
				uu.setPlan_no(rs.getString("plan_no"));
				uu.setTerms(rs.getInt("terms"));
				uu.setFrequency(rs.getInt("frequency"));
				uu.setApplicant_fees(rs.getDouble("applicant_fees"));
				uu.setInstallment_amount(rs.getDouble("installment_amount"));
				uu.setInterest(rs.getDouble("interest"));
				uu.setMaturity_value(rs.getDouble("maturity_value"));
				uu.setMaturity_date(rs.getDate("maturity_date"));
				uu.setStrMatDate(sf.format(rs.getDate("maturity_date")));
				uu.setDsaCode(rs.getString("dsa_code"));
				uu.setDsaName(dsaNameById(rs.getString("dsa_code"), con));
				uu.setPaidStatus(rs.getString("paid_status"));
				uu.setAccountStatus(rs.getString("account_status"));
				uu.setTotalAmount(paidAmountByUser(uu.getUser_no(), con));
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return uu;
	}
	
	
	
	public ArrayList<UserInfo> pendingUserList(int branchId) 
	{
		Date dt= new Date();
		ArrayList<UserInfo> list = new ArrayList<UserInfo>();
		 Timestamp tsDt = new Timestamp(dt.getTime());
		 SimpleDateFormat sdf = sdfForDb;
	     String dd = sdf.format(tsDt.getTime());
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			int i=0;
			Statement st = con.createStatement();
			
			String qq = "select * from customer_info where account_status='pending' ";
			ResultSet rs = st.executeQuery(selectQueWithBranch(qq,branchId));
			while (rs.next())
			{
				i=i+1;
				String hno=rs.getString("shareHolderNo");
				UserInfo uu = new UserInfo();
				uu=userInfoByShareHolderNo(hno, con);
				uu.setSno(i);
         		uu.setId(rs.getString("id"));
         		uu.setShareHolderNo(rs.getString("shareHolderNo"));
         		uu.setOffice_application_no(rs.getString("office_application_no"));
    			uu.setOffice_date(rs.getDate("office_date"));
    			uu.setStrOffcDate(sf.format(rs.getDate("office_date")));
				uu.setUser_no(rs.getString("user_no"));
				uu.setScheme_type(rs.getString("scheme_type"));
				uu.setPlan_no(rs.getString("plan_no"));
				uu.setTerms(rs.getInt("terms"));
				uu.setFrequency(rs.getInt("frequency"));
				uu.setFrequencyLabel(frequencyLabel(String.valueOf(rs.getInt("frequency"))));
				uu.setApplicant_fees(rs.getDouble("applicant_fees"));
				uu.setInstallment_amount(rs.getDouble("installment_amount"));
				uu.setInterest(rs.getDouble("interest"));
				uu.setMaturity_value(rs.getDouble("maturity_value"));
				uu.setMaturity_date(rs.getDate("maturity_date"));
				uu.setStrMatDate(sf.format(rs.getDate("maturity_date")));
				list.add(uu);
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}


	public Date findDateOfJoiningOfEmployee(int branchId,String selectedEmployee) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select doj from employee where uname='"+selectedEmployee+"' and status='active' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDate("doj");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return null;
	}

	public void insertInCommissionTable(String plan, int i,String commissionType, double commissionValue,
			String commissionBase, double emiNo,ArrayList<DsaListInfo> emiCommissionList,int branchId) 
	{
		String qq="";
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(plan.equalsIgnoreCase("RD"))
			{
				commissionBase="collection";
				for(DsaListInfo dd:emiCommissionList)
				{
					if(dd.getCommission_value()>0)
					{
						qq="insert into commission_table(plan_id, commission_type, commission_value, commission_base, emi_no,branch_id) values('"+i+"', '"+commissionType+"', "
								+ "'"+dd.getCommission_value()+"', '"+commissionBase+"', '"+dd.getEmiNo()+"','"+branchId+"')";
					int j=	st.executeUpdate(qq);
					if(j>0)
					{
					dataInsertInQueryTable(qq, conn);
					}
					}
				}
			}
			else
			{
				
				qq="insert into commission_table(plan_id, commission_type, commission_value, commission_base, emi_no,branch_id) values('"+i+"', '"+commissionType+"', "
						+ "'"+commissionValue+"', '"+commissionBase+"', '"+emiNo+"','"+branchId+"')";
			int k=st.executeUpdate(qq);
				if(k>0)
				{
				dataInsertInQueryTable(qq, conn);
				}
			}
			
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}

	public ArrayList<DsaListInfo> selectedPlanCommissionDetail(String id) 
	{
		int count=1;
		ArrayList<DsaListInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from commission_table where plan_id='"+id+"' ";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				DsaListInfo ff=new DsaListInfo();
				
				ff.setSno(count++);
				ff.setCommission_type(rr.getString("commission_type"));
				ff.setCommission_value(rr.getDouble("commission_value"));
				ff.setCommissionBase(rr.getString("commission_base"));
				ff.setEmiNo(rr.getInt("emi_no"));
				
				list.add(ff);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		return list;
	}

	public DsaListInfo checkPlanCommissionDetail(String plan_no, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		DsaListInfo ff=new DsaListInfo();
		try
		{
			st=conn.createStatement();
			String qq="select * from commission_table where plan_id='"+plan_no+"' ";
		//	//System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				ff.setCommission_type(rr.getString("commission_type"));
				ff.setCommission_value(rr.getDouble("commission_value"));
				ff.setCommissionBase(rr.getString("commission_base"));
				ff.setEmiNo(rr.getInt("emi_no"));
				ff.setMaxEmi(rr.getInt("max_emi_commission"));
				ff.setStatusNullCheck("1");
			}
			else
			{
				ff.setStatusNullCheck("0");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return ff;
	}

	public int insertDataInDsaCommissionTable(int branchId,String scheme_type,String user_no, String dsaCode, double dsaCommission,Date office_date, String emiNo) 
	{	
		Timestamp ofcdt = new Timestamp(office_date.getTime());
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			if(!dsaCode.equalsIgnoreCase("") && dsaCommission>0)
			{
				Statement st=conn.createStatement();
				String qq="insert into dsa_commission(type, user_no, dsa_code, amount, credit_date, emi_no,branch_id) values('"+scheme_type+"','"+user_no+"',"
						+ "'"+dsaCode+"','"+dsaCommission+"','"+ofcdt+"','"+emiNo+"','"+branchId+"')";
				// //System.out.println(qq);
				int i=st.executeUpdate(qq);
				if(i>0)
				{
					dataInsertInQueryTable(qq, conn);
				return i;
			}}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public ArrayList<DsaListInfo> dsaCommissionListDateWise(int branchId,String dsaCode, Date startDate, Date endDate, String searchType, Connection conn) 
	{
		int count=1;
		String qq="";
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		Statement st=null;
		ResultSet rr=null;
		ArrayList<DsaListInfo> list=new ArrayList<>();
		try
		{
			st=conn.createStatement();
			if(searchType.equals("all"))
			{
				qq="select * from dsa_commission where dsa_code='"+dsaCode+"' and credit_date>='"+sDate+"' and credit_date<='"+eDate+"' ";
			}
			else
			{
				qq="select * from dsa_commission where dsa_code='"+dsaCode+"' and credit_date>='"+sDate+"' and credit_date<='"+eDate+"' and type='"+searchType+"' ";
			}
		//	// // // //System.out.println(qq);
			rr=st.executeQuery(qq);
			while(rr.next())
			{
				DsaListInfo dd=new DsaListInfo();
				
				dd.setSno(count++);
				dd.setId(rr.getString("id"));
				dd.setAccountNo(rr.getString("user_no"));
				dd.setAccountType(rr.getString("type"));
				dd.setDsaCode(rr.getString("dsa_code"));
				dd.setCommission_value(rr.getDouble("amount"));
				dd.setEntryDate(rr.getDate("credit_date"));
				dd.setEntryDateStr(new SimpleDateFormat("dd-MMM-yyyy").format(dd.getEntryDate()));
				dd.setEmiNoStr(rr.getString("emi_no"));
				list.add(dd);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try 
			{
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} 
			catch (Exception e2) 
			{
				// TODO: handle exception
			}
		}
		return list;
	}

	public ArrayList<SelectItem> dsaCommissionTypeList(String dsaCode, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		ArrayList<SelectItem> tList=new ArrayList<>();
		try
		{
			st=conn.createStatement();
			String qq="select * from dsa_commission where dsa_code='"+dsaCode+"' ";
			rr=st.executeQuery(qq);
			while(rr.next())
			{
				SelectItem ss=new SelectItem();
				
				ss.setLabel(rr.getString("type"));
				ss.setValue(rr.getString("type"));
				
				tList.add(ss);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());	
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}
		return tList;
	}

	public DsaListInfo checkPlanCommissionDetailForRd(String plan_no, int emiNo) 
	{
		DsaListInfo ff=new DsaListInfo();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from commission_table where plan_id='"+plan_no+"' and emi_no='"+emiNo+"' ";
	
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				ff.setCommission_type(rr.getString("commission_type"));
				ff.setCommission_value(rr.getDouble("commission_value"));
				ff.setCommissionBase(rr.getString("commission_base"));
				ff.setEmiNo(rr.getInt("emi_no"));
				ff.setStatusNullCheck("1");
			}
			else
			{
				ff.setStatusNullCheck("0");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return ff;
	}

	public void deleteFromDsaCommissionTable(String loanNo, int emiNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="delete from dsa_commission where user_no='"+loanNo+"' and emi_no='"+emiNo+"' ";
		int i=	st.executeUpdate(qq);
		if(i>0)
		{
			dataInsertInQueryTable(qq, conn);
		}}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}

	public int deleteFromDsaCommissionTableById(String id) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="delete from dsa_commission where id='"+id+"' ";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
			dataInsertInQueryTable(qq, conn);
			return i;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public boolean checkDuplicacyInDsaCommissionTable(String user_no, String emiiiNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from dsa_commission where user_no='"+user_no+"' and emi_no='"+emiiiNo+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return false;
	}
	
	public ArrayList<UserInfo> ddList(int branchId,String dsaType, String date, Connection conn, String searchType)
    {
		Statement st=null,st1=null;
		ResultSet rr=null,rr1=null;
         ArrayList<UserInfo>list= new  ArrayList<>();
         int sno=1;
         String query="";
         try
	     {
	         if(searchType.equalsIgnoreCase("DD") || searchType.equalsIgnoreCase("RD"))
	         {
	        	  if(dsaType.equals("all"))
	              {
	                  query="select * from customer_info where account_status='active'";
	              }
	              else if((searchType.equalsIgnoreCase("DD") || searchType.equalsIgnoreCase("RD")) || !dsaType.equals("all"))
	              {
	                  query="select * from customer_info where dsa_code='"+dsaType+"' and  account_status='active'";
	              }
	              query+=" and scheme_type='"+searchType+"' ";
	             st=conn.createStatement();
	              	rr=st.executeQuery(selectQueWithBranch(query,branchId));
	               while(rr.next())
	               {
	                   UserInfo cat= new UserInfo();
	                   cat.setSno(sno++);
	                   cat.setScheme_type(planNameByPlanId(rr.getString("plan_no"), conn));
	                   cat.setDsaName(dsaNameById(rr.getString("dsa_code"),conn));
	                   cat.setAccountNo(rr.getString("user_no"));
	                   cat.setFirst_applicantName(applicantNameByShareHolderNo(rr.getString("shareHolderNo"), conn));
	                   cat.setFather_husband_name(shareHolderDetailByColumnName(rr.getString("shareHolderNo"), "father_husband_name", conn));
	                   cat.setMobile(shareHolderDetailByColumnName(rr.getString("shareHolderNo"), "mobile", conn));
	                   cat.setOpeningAmt(rr.getInt("installment_amount"));
	                   cat.setDepositAmt(paidAmountByUser(rr.getString("user_no"),conn));
	                   list.add(cat);
	               }
	             
	         }
	         else if(searchType.equalsIgnoreCase("DL"))
	         {
	        	 if(dsaType.equals("all"))
	             {
	                 query="select * from personalloan where (frequency='365' || frequency='365.0' ) and paidStatus='unpaid' and status='Approve'";
	             }
	        	 else
	             {
	                query="select * from personalloan where (frequency='365' || frequency='365.0' ) and paidStatus='unpaid' and status='Approve' and dsacode='"+dsaType+"'";   
	             }
	        	// //System.out.println(query);
	                   st1=conn.createStatement();
	                   rr1=st1.executeQuery(selectQueWithBranch(query,branchId));;
	                  while(rr1.next())
	                  {
	                      UserInfo cat= new UserInfo();
	                      cat.setSno(sno++);
	                      cat.setScheme_type(planNameByPlanId(rr1.getString("plan_no"), conn));
	                      cat.setDsaName(dsaNameById(rr1.getString("dsacode"),conn));
	                      cat.setAccountNo(rr1.getString("loanNo"));
	                      cat.setFirst_applicantName(applicantNameByShareHolderNo(rr1.getString("shareholderno"), conn));
	                      cat.setOpeningAmt(rr1.getInt("emi")+rr1.getInt("extra_amount"));
	                      cat.setDepositAmt(loanPaidAmountByUser("personalloan", rr1.getString("loanNo"),conn));
	                      cat.setDueAmt(String.valueOf(Double.valueOf(rr1.getString("terms"))*Double.valueOf(rr1.getString("emi"))- Double.valueOf(cat.getDepositAmt())));
	                      cat.setFather_husband_name(shareHolderDetailByColumnName(rr1.getString("shareholderno"), "father_husband_name", conn));
		                   cat.setMobile(shareHolderDetailByColumnName(rr1.getString("shareholderno"), "mobile", conn));
	                      list.add(cat);
	                  }
	         }
	         
	         else if(searchType.equalsIgnoreCase("PL"))
	         {
	        	 if(dsaType.equals("all"))
	             {
	                 query="select * from personalloan where (frequency!='365' && frequency!='365.0' ) and paidStatus='unpaid' and status='Approve'";
	             }
	        	 else
	             {
	                query="select * from personalloan where (frequency!='365' && frequency!='365.0' ) and paidStatus='unpaid' and status='Approve' and dsacode='"+dsaType+"'";   
	             }
	        	// //System.out.println(query);
                   st1=conn.createStatement();
                   rr1=st1.executeQuery(selectQueWithBranch(query,branchId));;
                  while(rr1.next())
                  {
                      UserInfo cat= new UserInfo();
                      cat.setSno(sno++);
                      cat.setScheme_type(planNameByPlanId(rr1.getString("plan_no"), conn));
                      cat.setDsaName(dsaNameById(rr1.getString("dsacode"),conn));
                      cat.setAccountNo(rr1.getString("loanNo"));
                      cat.setFirst_applicantName(applicantNameByShareHolderNo(rr1.getString("shareholderno"), conn));
                      cat.setOpeningAmt(rr1.getInt("emi")+rr1.getInt("extra_amount"));
                      cat.setDepositAmt(loanPaidAmountByUser("personalloan", rr1.getString("loanNo"),conn));
                      cat.setDueAmt(String.valueOf(Double.valueOf(rr1.getString("terms"))*Double.valueOf(rr1.getString("emi"))- Double.valueOf(cat.getDepositAmt())));
                      cat.setFather_husband_name(shareHolderDetailByColumnName(rr1.getString("shareholderno"), "father_husband_name", conn));
	                   cat.setMobile(shareHolderDetailByColumnName(rr1.getString("shareholderno"), "mobile", conn));
                      list.add(cat);
                  }
	         }
	         
	         else if(searchType.equalsIgnoreCase("GL"))
	         {
	        	 if(dsaType.equals("all"))
	             {
	                 query="select * from grouploan where (frequency!='365' && frequency!='365.0' ) and paidStatus='unpaid' and status='Approve'";
	             }
	        	 else
	             {
	                query="select * from grouploan where (frequency!='365' && frequency!='365.0' ) and paidStatus='unpaid' and status='Approve' and dsacode='"+dsaType+"'";   
	             }
	        	// //System.out.println(query);
	                   st1=conn.createStatement();
	                   rr1=st1.executeQuery(selectQueWithBranch(query,branchId));;
	                  while(rr1.next())
	                  {
	                      UserInfo cat= new UserInfo();
	                      cat.setSno(sno++);
	                      cat.setScheme_type(planNameByPlanId(rr1.getString("plan_no"), conn));
	                      cat.setDsaName(dsaNameById(rr1.getString("dsacode"),conn));
	                      cat.setAccountNo(rr1.getString("sub_loan_no"));
	                      cat.setFirst_applicantName(applicantNameByShareHolderNo(rr1.getString("teamLeader"), conn));
	                      cat.setOpeningAmt(rr1.getInt("emi")+rr1.getInt("extra_amount"));
	                      cat.setDepositAmt(loanPaidAmountByUser("grouploan", rr1.getString("sub_loan_no"),conn));
	                      cat.setDueAmt(String.valueOf(Double.valueOf(rr1.getString("terms"))*Double.valueOf(rr1.getString("emi"))- Double.valueOf(cat.getDepositAmt())));
	                      cat.setFather_husband_name(shareHolderDetailByColumnName(rr1.getString("teamLeader"), "father_husband_name", conn));
		                   cat.setMobile(shareHolderDetailByColumnName(rr1.getString("teamLeader"), "mobile", conn));
	                      list.add(cat);
	                  }
	         }
	         
	     } 
         catch(Exception e)
         {
              e.printStackTrace();fileCreation(e.getMessage());
         }
               
          finally
          {
              try {
                  if(st!=null)
                  {
                      st.close();
                  }
                  if(rr!=null)
                  {
                      rr.close();
                  }
                  if(st1!=null)
                  {
                      st1.close();
                  }
                  if(rr1!=null)
                  {
                      rr1.close();
                  }
              } catch (Exception e2) {
                  // TODO: handle exception
         
              }
          }
      return list;
    }

	public String planNameByPlanId(String planId, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select plan from plans where idplans='"+planId+"' and status='active' ";
			// // // //System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("plan");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally 
        {
            try 
            {
                // Close the writer regardless of what happens...
            	if(st!=null)
            	{
            		  st.close();
                }
            	if(rr!=null)
            	{
            	     rr.close();
                }
            } 
            catch (Exception s) 
            {
                s.printStackTrace();
                fileCreation(s.getMessage());
            }
        }
		return null;
	}

	public ArrayList<TrialInfo> trialBalanceSavingAccountList(Date startDate, Date endDate,int branchId, Connection conn) 
	{
		boolean chk=true;
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		ArrayList<TrialInfo> list=new ArrayList<>();
		Statement st=null;ResultSet rs=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from savingaccount ";
			rs=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rs.next())
			{
				TrialInfo tt=new TrialInfo();
				
				//if(chk==true)
				{
					tt.setCategory("Saving Accounts");
					chk=false;
				}
				String accNo=rs.getString("accountNo");
				tt.setParticular(accNo+" / "+firstApplicantNameBySHNo(rs.getString("shareHolderNo"),conn));
				double val=openingSavingDeposit(accNo, sDate)-openingSavingWithdraw(accNo, sDate);
				if(val>0)
				{
					tt.setOpeningCr(Math.abs(val));
				}
				else
				{
					tt.setOpeningDr(Math.abs(val));
				}
				
				//tt.setOpeningCr(openingBalanceFromTrialBalanceTable(accNo, "2016-2017", "Saving"));
				tt.setCredit(savingDepositBetweenDate(accNo, sDate, eDate));
				tt.setDebit(savingWithdrawBetweenDate(accNo, sDate, eDate));
			//	tt.setBalance((tt.getOpening()+tt.getDebit())-tt.getCredit());
				
				list.add(tt);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}

		return list;
	}

	private double savingWithdrawBetweenDate(String accNo, String sDate, String eDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from customer_withdrwal where account_no='"+accNo+"' and date>='"+sDate+"' and date<='"+eDate+"' and chequeStatus='cleared' and status='approved' ";
		//	// // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public double savingTotalCurrentBalance(int branchId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from savingaccount where accountStatus='open' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public double savingDepositBetweenDate(String accNo, String sDate, String eDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from customer_deposit where account_no='"+accNo+"' and date>='"+sDate+"' and date<='"+eDate+"' and type='deposit' and chequeStatus='cleared' and status='approved' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	private double openingSavingWithdraw(String accNo, String sDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from customer_withdrwal where account_no='"+accNo+"' and date<'"+sDate+"' and chequeStatus='cleared' and status='approved' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	private double openingSavingDeposit(String accNo, String sDate) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from customer_deposit where account_no='"+accNo+"' and date<'"+sDate+"' and type='deposit' and chequeStatus='cleared' and status='approved' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public ArrayList<EmpInfo> allMessageModule() 
	{
		int count=1;
		ArrayList<EmpInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from message_setting ";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				EmpInfo ee=new EmpInfo();
				
				ee.setSno(count++);
				ee.setId(rr.getString("id"));
				ee.setUname(rr.getString("module_name"));
				ee.setStatus(rr.getString("status"));
				ee.setName(rr.getString("module_label"));
				if(rr.getString("status").equalsIgnoreCase("active"))
				{
					ee.setDisActive(true);
					ee.setDisInactive(false);
				}
				else
				{
					ee.setDisActive(false);
					ee.setDisInactive(true);
				}
				
				list.add(ee);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public int updateMessageModuleStatus(String id, String status) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update message_setting set status='"+status+"' where id='"+id+"' ";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
			dataInsertInQueryTable(qq, conn);
			return i;
		}}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public ArrayList<LoanInfo> shareHolderListForMsg(int branchId) 
	{
		int count=1;
		ArrayList<LoanInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from shareholder_info";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				LoanInfo ll=new LoanInfo();
				
				ll.setSno(count++);
				ll.setId(rr.getString("id"));
				ll.setLoanNo(rr.getString("shareholderno"));
				ll.setLoanType("Share Holder");
				ll.setContactNo(rr.getString("mobile"));
				ll.setApplicantName(rr.getString("first_applicantName"));
				
				list.add(ll);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public String checkStatusInMessageSettingTable(String string) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select status from message_setting where module_name='"+string+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("status");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "inactive";
	}
	
	
	public String checkSMessageApiDetailFromTable(String columnName, String checkStatus, Connection conn) 
	{
		String qq="";
		try
		{   
			Statement st=conn.createStatement();
			if(columnName.equalsIgnoreCase("admin_app") || columnName.equalsIgnoreCase("user_app") || columnName.equalsIgnoreCase("employee_app") || columnName.equalsIgnoreCase("software_type")
					|| checkStatus.equalsIgnoreCase("active") || checkStatus.equalsIgnoreCase("message_status") || columnName.equalsIgnoreCase("employee_attendance") || columnName.equalsIgnoreCase("employee_wise_data")
					 || columnName.equalsIgnoreCase("gps_tracking") || columnName.equalsIgnoreCase("nach_no") || columnName.equalsIgnoreCase("crif_no") || columnName.equalsIgnoreCase("equifax_no") || columnName.equalsIgnoreCase("experial_no") || columnName.equalsIgnoreCase("saving_percent"))
			{
				qq="select * from message_api ";
			}
			
			else 
			{ 
				qq="select * from message_api where message_status='active' ";
			} 
			
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString(columnName);
			}
			
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}
	
	public boolean checkDepositModuleStatus(Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select show_deposit from message_api ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getBoolean("show_deposit");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return true;
	}
	
	public String checkMessageApiStatus(Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select message_status from message_api ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("message_status");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "inactive";
	}
	
	public String checkWhatsAppAPI(Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select balance_api from message_api";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("balance_api");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}
	
	public String checkWhatsAppAPIUrl(Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select api_url from message_api";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("api_url");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}
	
	public ArrayList<SelectItem> bankNameSelectItemList(Connection con) 
	{
		ArrayList<SelectItem> viewBankName =new ArrayList<SelectItem>();
		try
		{
			Statement stt = con.createStatement();
			String qry = "select * from bankname ";

			ResultSet rr = stt.executeQuery(qry);

			while (rr.next()) 
			{
				SelectItem p = new SelectItem();
				
				p.setValue(rr.getString("bankname"));
				p.setLabel(rr.getString("bankname"));
				
				viewBankName.add(p);
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return viewBankName;
	}
	

	public ArrayList<SelectItem> bankNameFromBankTable(Connection con) 
	{
		ArrayList<SelectItem> viewBankName =new ArrayList<SelectItem>();
		try
		{
			Statement stt = con.createStatement();
			String qry = "select * from bank_table ";

			ResultSet rr = stt.executeQuery(qry);

			while (rr.next()) 
			{
				SelectItem p = new SelectItem();
				
				p.setValue(rr.getString("id"));
				p.setLabel(rr.getString("bank_name"));
				
				viewBankName.add(p);
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return viewBankName;
	}
	
	public ArrayList<BankInfo> cityNameViewList(int branchId,Connection conn) 
	{
		int i = 1;
		Statement st=null;
		ResultSet rr=null;

		ArrayList<BankInfo> viewBankName =new ArrayList<BankInfo>();
		try
		{
			 st = conn.createStatement();
			String qry = "select * from cityname ";

			 rr = st.executeQuery(selectQueWithBranch(qry,branchId));;

			while (rr.next()) 
			{
				BankInfo p = new BankInfo();
				p.setSno(i++);
				p.setId(rr.getString("id"));
				p.setBankName(rr.getString("cityname"));
				
				viewBankName.add(p);
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		
		}
		return viewBankName;
	}
	
	public ArrayList<BankInfo> bankNameList(Connection conn) 
	{
		int i = 1;
		Statement st=null;
		ResultSet rr=null;

		ArrayList<BankInfo> viewBankName =new ArrayList<BankInfo>();
		try
		{
			 st = conn.createStatement();
			String qry = "select * from bankname ";

			 rr = st.executeQuery(qry);;

			while (rr.next()) 
			{
				BankInfo p = new BankInfo();
				p.setSno(i++);
				p.setId(rr.getString("id"));
				p.setBankName(rr.getString("bankname"));
				
				viewBankName.add(p);
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		
		}
		return viewBankName;
	}
	
	
	public ArrayList<SelectItem> cityNameList(int branchId, Connection conn) 
	{
		int i = 1;
		Statement st=null;
		ResultSet rr=null;

		ArrayList<SelectItem> viewBankName =new ArrayList<SelectItem>();
		try
		{
			 st = conn.createStatement();
			String qry = "select * from cityname ";

			 rr = st.executeQuery(selectQueWithBranch(qry,branchId));;

			while (rr.next()) 
			{
				SelectItem  p = new SelectItem();
				
				p.setValue(rr.getString("id"));
				p.setLabel(rr.getString("cityname"));
				
				viewBankName.add(p);
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		
		}
		return viewBankName;
	}
	
	public ArrayList<BankInfo> allBankListOfCompany(Connection conn) 
	{
		ArrayList<BankInfo> bankList=new ArrayList<>();
		Statement stt=null;
		  ResultSet ss=null;
		try
		{
		   stt=conn.createStatement();
		   String query="select * from bank_table";
		 ss=stt.executeQuery(query);
		   while(ss.next())
		   {
			   BankInfo info=new BankInfo();
			   info.setBank_name(ss.getString("bank_name"));
			   info.setId(ss.getString("id"));
			   bankList.add(info);
		   }
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();
		}
		finally
		 {
			 try {
				if(stt!=null)
				{
					stt.close();
				}
				if(ss!=null)
				{
					ss.close();
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		 }
		return bankList;
	}
	
	public int addBankName(String bankName, Connection conn) 
	{

		Statement st=null;

		try 
		{
			 st = conn.createStatement();
			String query = "insert into bankname ( bankname) values('"+ bankName + "')";
			int rr = st.executeUpdate(query);
			if(rr>0)
			{
			dataInsertInQueryTable(query, conn);
			return rr;
		}}
		
		catch (Exception e) {
			// TODO: handle exception
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		
		}
		return 0;
	}
	
	public int addCityName(String cityName,int branchId,Connection conn) 
	{

		Statement st=null;

		try 
		{
			 st = conn.createStatement();
			String query = "insert into cityname (cityname,branch_id) values('"+ cityName + "','"+branchId+"')";
			int rr = st.executeUpdate(query);
			if(rr>0)
			{
			dataInsertInQueryTable(query, conn);
			return rr;
		}}
		
		catch (Exception e) {
			// TODO: handle exception
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		
		}
		return 0;
	}
	
	
	
	
	public Date lastShareLoanDepositNoDate(String lastDepositNo, String searchType)
	{
		String column="", qq="";
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			if(searchType.equalsIgnoreCase("Deposit"))
			{
				qq = "select office_date from customer_info where user_no='"+lastDepositNo+"'";
				column="office_date";
			}
			else if(searchType.equalsIgnoreCase("Share Holder"))
			{
				qq = "select office_date from shareholder_info where shareholderno='"+lastDepositNo+"'";
				column="office_date";
			}
			else if(searchType.equalsIgnoreCase("Personal Loan"))
			{
				qq = "select requestDate from personalloan where loanNo='"+lastDepositNo+"'";
				column="requestDate";
			}
			
			ResultSet rs = st.executeQuery(qq);
			if (rs.next()) 
			{
				return rs.getDate(column);
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return null;
	}
	

	public String lastShareLoanDepositNo(String searchType)
	{
		String column="", qq="";
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			if(searchType.equalsIgnoreCase("Deposit"))
			{
				qq = "select user_no from customer_info order by id desc limit 1";
				column="user_no";
			}
			else if(searchType.equalsIgnoreCase("Share Holder"))
			{
				qq = "select shareholderno from shareholder_info order by id desc limit 1";
				column="shareholderno";
			}
			else if(searchType.equalsIgnoreCase("Personal Loan"))
			{
				qq = "select loanNo from personalloan order by id desc limit 1";
				column="loanNo";
			}
			ResultSet rs = st.executeQuery(qq);
			if (rs.next()) 
			{
				return rs.getString(column);
			}
		} 
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}

	public ArrayList<TrialInfo> dataFromTrialBalanceTable(String head, String fyear,int branchId, Connection conn) 
	{Statement st=null;ResultSet rr=null;
		int count=1;
		boolean check=true;
		ArrayList<TrialInfo> list=new ArrayList<>();
		try
		{
			st=conn.createStatement();
			String qq="select * from trial_balance where tb_head='"+head+"' and financial_year='"+fyear+"'  ";
			 rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				TrialInfo tt=new TrialInfo();
				
				tt.setSno(count++);
				//if(check==true)
				{
					tt.setCategory(head);
				}
				check=false;
				
				tt.setParticular(rr.getString("account_no"));
				tt.setOpeningDr(rr.getDouble("closing_balance"));
				
				list.add(tt);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
	}
}

		return list;
	}
	
	
	public String addLoanCloser(String receipt_no, double totalPenaltyRemain, double totalIntrestRemain, double totalChqChargeRemain, 
			double totalRemaining, double discount, double amount, Date paidDate, String paymentMode, String transfer, String loanNo,
			double discountInterest, double discountPenalty, double discountChequeBounce, String chequeNo, Date chequeDate, double totalPrincipalRemain,
			String dsaName,int branchId, double foreclosureCharges, String rating,String remark,double CalculatedIntAmtAfterTenureTillDate, double disCalIntAmtAfterTenureTillDate)
	{
		Timestamp tt=null;
		Timestamp ss=null;
		if(chequeDate!=null ){
		 tt=new Timestamp(chequeDate.getTime());
		
		}
		if(paidDate!=null ){
		ss = new Timestamp(paidDate.getTime());
		}
		try(Connection conn=DataBaseConnection.JAVAConnection();) 
		{
			
             
		     String query="insert into add_loan_closer(receipt_no, total_penalty_remain, total_intrest_remain, total_chq_charge_remain, total_remaining, discount, amount,"
		     		+ " paid_date, payment_mode, transfer, loan_no, discount_penalty, discount_chequebounce, discount_interest, cheque_date, cheque_no,"
		     		+ "principal_amount_remaining,dsa_name,branch_id,foreclosure_charges,rating,remark,calIntAmt_aftertenure,disIntAmt_aftertenure)values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";	
		    PreparedStatement stt=conn.prepareStatement(query);
		    stt.setString(1, receipt_no);
		    stt.setDouble(2, totalPenaltyRemain);
		    stt.setDouble(3, totalIntrestRemain);
		    stt.setDouble(4, totalChqChargeRemain);
		    stt.setDouble(5, totalRemaining);
		    stt.setDouble(6, discount);
		    stt.setDouble(7, amount);
		    stt.setTimestamp(8, ss);
		    stt.setString(9, paymentMode);
		    stt.setString(10, transfer);
		    stt.setString(11, loanNo);
		    stt.setDouble(12, discountPenalty);
		    stt.setDouble(13, discountChequeBounce);
		    stt.setDouble(14, discountInterest);
		    stt.setTimestamp(15, tt);
		    stt.setString(16, chequeNo);
		    stt.setDouble(17, totalPrincipalRemain);
		    stt.setString(18, dsaName);
		    stt.setInt(19, branchId);
		    stt.setDouble(20, foreclosureCharges);
		    stt.setString(21, rating);
		    stt.setString(22, remark);
		    stt.setDouble(23, CalculatedIntAmtAfterTenureTillDate);
		    stt.setDouble(24, disCalIntAmtAfterTenureTillDate);
		    
		    int i = stt.executeUpdate();
		    if(i>0)
		    {
		    dataInsertInQueryTable(String.valueOf(stt), conn);
		}}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}
	
	public ArrayList<String> listDueRd(String schemeType, String dsaCode,int branchId,Connection conn)
	{
		ArrayList<String> list = new ArrayList<>();
		String qq="";
		try
		{
			Statement st=conn.createStatement();
			
			if(dsaCode.equalsIgnoreCase("all"))
			{
				  qq="SELECT user_no FROM customer_info where account_status='active' and scheme_type='"+schemeType+"' ";
			}
			else
			{
				  qq="SELECT user_no FROM customer_info where account_status='active' and scheme_type='"+schemeType+"' and dsa_code='"+dsaCode+"' ";
			}
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				list.add(rr.getString("user_no"));
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	
	}

	public ArrayList<ReportInfo> dailyRDFDReport(String user_no, String scheme_type, Connection con)
	{
		ArrayList<ReportInfo> list = new ArrayList<ReportInfo>();
		ResultSet rs=null;
		Statement st=null;
		String loantp="";
		double total=0;
		int count=0;
		try 
		{
			st = con.createStatement();
			String qq = "select sum(amount),date,receipt_no from payment_receipt  where user_no='"+user_no+"' and scheme_type='"+scheme_type+"' and receipt_status='approved' group by date,receipt_no";
			rs = st.executeQuery(qq);
			while (rs.next())
			{
				ReportInfo obj= new ReportInfo();
				obj.setAmount(rs.getDouble("sum(amount)"));
				total+=obj.getAmount();
				obj.setBalance(total);
				obj.setCreditAmount(obj.getAmount());
				obj.setStatus(scheme_type+" No. "+user_no+" Deposit EMI Amount: ");
				obj.setDate(rs.getDate("date"));
				obj.setDateStr(sf.format(rs.getDate("date")));
				obj.setReceiptNo(rs.getString("receipt_no"));
				obj.setsNo(++count);
				list.add(obj);
			}
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try
			{
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			}
			catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}
	
	


	public Date paidAmountDate(String user_no, Connection conn) 
   {
	   Statement stt=null;
	   ResultSet rr =null;
	   Date dt=null;
		double amount = 0;
		try 
		{
			stt = conn.createStatement();
			String qs = "select date from payment_receipt where user_no='"+ user_no + "' and receipt_status='approved' order by date desc";
			rr= stt.executeQuery(qs);
			if (rr.next()) 
			{
			  dt=rr.getDate("date");
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return dt;
	}

	public double calculateTdsPayableAmount(Date startDate, Date endDate,Connection conn) 
	{
		double tdsPayble=0;
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		Statement st=null;
		ResultSet rr =null;
		Statement st1=null;
		ResultSet rr1=null;
		try 
		{
			st = conn.createStatement();
			String qs = "select sum(tds_amount) from tds_deduction where tds_date>='"+sDate+"' and tds_date<='"+eDate+"' ";
			rr= st.executeQuery(qs);
			if (rr.next()) 
			{
				st1 = conn.createStatement();
				String qs1 = "select sum(amount) from tds_submission where expense_date>='"+sDate+"' and expense_date<='"+eDate+"' and status='active' and chequeStatus='cleared' ";
				rr1= st1.executeQuery(qs1);
				if(rr1.next()) 
				{
					tdsPayble=rr.getDouble("sum(tds_amount)")-rr1.getDouble("sum(amount)");
				}
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
				
				if(st1!=null)
				{
					st1.close();
				}
				if(rr1!=null)
				{
					rr1.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return tdsPayble;
	}
	

	public ArrayList<String> allActiveLoan(int branchId,String loanType) 
	{
		String qq="";
		ArrayList<String> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(loanType.equalsIgnoreCase("grouploan"))
			{
				qq="select sub_loan_no from grouploan where status='Approve' and paidStatus='unpaid' and restructure_status='no' and branch_id='"+branchId+"' order by sub_loan_no asc ";
			}
			else
			{
				qq="select loanNo from "+loanType+" where status='Approve' and paidStatus='unpaid' and restructure_status='no' and branch_id='"+branchId+"' order by loanNo asc ";
			}
			
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				if(loanType.equalsIgnoreCase("grouploan"))
				{
					list.add(rr.getString("sub_loan_no"));
				}
				else
				{
					list.add(rr.getString("loanNo"));
				}
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	
	public ArrayList<String> allActiveLoanForAccruedLoan(String loanType, Date startDate, Date endDate, int branchId) 
	{
		String start=sdfForDb.format(startDate);
		String end=sdfForDb.format(endDate);
		String qq="";
		ArrayList<String> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(loanType.equalsIgnoreCase("grouploan"))
			{
				qq="select sub_loan_no from grouploan";
			}
			else
			{
				qq="select loanNo from "+loanType+" ";
			}
			
			qq+="  where status='Approve' and approvalDate>='"+start+"' and approvalDate<='"+end+"' and restructure_status='no'";
			
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				if(loanType.equalsIgnoreCase("grouploan"))
				{
					list.add(rr.getString("sub_loan_no"));
				}
				else
				{
					list.add(rr.getString("loanNo"));
				}
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	public double loanPaidAmountTillDate(int branchId,Date startDate,String loanNo, Connection conn)
    {
        double paidAmount=0;
        String sDate=sdfForDb.format(startDate);
        try
        {
            Statement st=conn.createStatement();
            String query="select sum(amount) from loanpayment where pay_date<='"+sDate+"' and loanNo='"+loanNo+"' and restructure='No' and receipt_status='approved' and chequeStatus='cleared' ";
            ResultSet rr=st.executeQuery(query);
            if(rr.next())
            {
                paidAmount=rr.getDouble(1);
            }
        }
        catch(Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return paidAmount;
    }
	
	public double loanPaidAmountByparticularDate(Date startDate,String loanNo)
    {
        double paidAmount=0;
       
        try(Connection conn=DataBaseConnection.JAVAConnection())
        {
            Statement st=conn.createStatement();
            String query="select sum(amount) from loanpayment where pay_date='"+new Timestamp(startDate.getTime())+"' and loanNo='"+loanNo+"' and restructure='No' and receipt_status='approved' and chequeStatus='cleared' ";
           
            ResultSet rr=st.executeQuery(query);
            if(rr.next())
            {
                paidAmount=rr.getDouble(1);
            }
        }
        catch(Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return paidAmount;
    }

	public double openingSavingAccountForBalanceSheet(Date startDate,int branchId,Connection conn) 
	{
		double total=0, totalCr=0, totalDr=0;
		Statement st1=null;
		ResultSet rs1=null;
		
		Statement st2=null;
		ResultSet rs2=null;
		
		String eDate=sdfForDb.format(startDate);
		
		String query1 ="select sum(amount) from customer_deposit where status='approved' and chequeStatus='cleared' and date<'"+eDate+"' ";
		String query2 ="select sum(amount) from customer_withdrwal where status='approved' and chequeStatus='cleared' and date<'"+eDate+"'";
		
		
		try
		{
             st1=conn.createStatement();
             st2=conn.createStatement();
 		    	
		     rs1=st1.executeQuery(selectQueWithBranch(query1,branchId));
		     if(rs1.next())
		     {
		    	 totalCr=rs1.getDouble("sum(amount)");
		     }
		     
		     rs2=st2.executeQuery(selectQueWithBranch(query2,branchId));
		     if(rs2.next())
		     {
		    	 totalDr=rs2.getDouble("sum(amount)");
		     }
		     total=Double.parseDouble(df.format(totalCr-totalDr));
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st1!=null)
				{
					st1.close();
				}
				
				if(st2!=null)
				{
					st2.close();
				}
				
				if(rs1!=null)
				{
					rs1.close();
				}
				
				if(rs2!=null)
				{
					rs2.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return total;
	}

	public ArrayList<UserInfo> activeDepositAmountDetailList(String searchType, Connection conn, String eDate,int branchId) 
	{
		int count=1;
		ArrayList<UserInfo> list=new ArrayList<>();
		Statement stt=null;
		ResultSet rs=null;
		try 
		{
			 stt=conn.createStatement();
             String query1 ="select * from customer_info where account_status='active' and scheme_type='"+searchType+"' ";;
     		 rs=stt.executeQuery(selectQueWithBranch(query1,branchId));
     		 while(rs.next())
		     {
		    	 UserInfo uu=new UserInfo();
		    	
		    	 uu.setSno(count++);
		    	 uu.setShareHolderNo(rs.getString("shareHolderNo"));
		    	 uu.setAccountNo(rs.getString("user_no"));
		    	 uu.setName(firstApplicantNameBySHNo(uu.getShareHolderNo(),conn));
		    	 uu.setDepositAmt(paidAmountByUserByDate(uu.getAccountNo(), conn, eDate));
		    	
		    	 list.add(uu);
		    }	 
        }
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				
				if(rs!=null)
				{
					rs.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return list;
	}
	
	public ArrayList<UserInfo> activeSavingAmountDetailList(int branchId,Connection conn) 
	{
		int count=1;
		ArrayList<UserInfo> list=new ArrayList<>();
		Statement stt=null;
		ResultSet rs=null;
		try 
		{
			 stt=conn.createStatement();
             String query1 ="select * from savingaccount where accountStatus='open' ";
     		 rs=stt.executeQuery(selectQueWithBranch(query1,branchId));
     		 while(rs.next())
		     {
		    	 UserInfo uu=new UserInfo();
		    	
		    	 uu.setSno(count++);
		    	 uu.setShareHolderNo(rs.getString("shareHolderNo"));
		    	 uu.setAccountNo(rs.getString("accountNo"));
		    	 uu.setName(firstApplicantNameBySHNo(uu.getShareHolderNo(),conn));
		    	 uu.setDepositAmt(Double.parseDouble(df.format(rs.getDouble("amount"))));
		    	 uu.setInterest(savingAccInterest(uu.getAccountNo(),branchId,conn));
		    	 list.add(uu);
		    }	 
        }
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				
				if(rs!=null)
				{
					rs.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return list;
	}

	public double savingAccInterest(String string,int branchId, Connection conn) 
	{
		String qq="";
		try
		{
			Statement st=conn.createStatement();
			if(string.equals("all"))
			{
				qq="select sum(amount) from customer_deposit where type='interest' and chequeStatus='cleared' and status='approved' ";
			}
			else
			{
				qq="select sum(amount) from customer_deposit where account_no='"+string+"' and type='interest' and chequeStatus='cleared' and status='approved' ";
			}
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public int deletePromotorsCapital(String idp, Connection cnt)
    {
        try
        {
            Statement stt = cnt.createStatement();
            String query ="update promotors_capital set status='inactive' where id = '"+idp+"'";
            int re = stt.executeUpdate(query);
            if(re>0)
            {
            	dataInsertInQueryTable(query, cnt);
                return re;
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return 0;
    }
	
	public int deleteReturnPromotorsCapital(String idp, Connection cnt)
    {
        try
        {
            Statement stt = cnt.createStatement();
            String query ="update return_promotors_capital set status='inactive' where id = '"+idp+"'";
            int re = stt.executeUpdate(query);
            if(re>0)
            {
            	dataInsertInQueryTable(query, cnt);
                return re;
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return 0;
    }
	
	public ArrayList<SelectItem> allPlansForOdLoan(int branchId,Connection conn)
    {
        Statement st=null;
        ResultSet rr=null;
        ArrayList<SelectItem> centerList=new ArrayList<>();
        try
        {
             st=conn.createStatement();
            String query="select * from plans ";
             rr=st.executeQuery(selectQueWithBranch(query,branchId));
            while(rr.next())
            {
                SelectItem info=new SelectItem();
                info.setValue(rr.getString("idplans"));
                info.setLabel(rr.getString("plan"));
                centerList.add(info);
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            try {
                if(st!=null)
                {
                    st.close();
                }
                if(rr!=null)
                {
                    rr.close();
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        return centerList;
    }
	
	public String odLoanNo(int branchId)
    {
        String account="";
        try (Connection con = DataBaseConnection.JAVAConnection();)
        {
            Statement st = con.createStatement();
            String qq = "select od_loan_no from od_loan where od_loan_no not like '%R%' order by id desc limit 1";
            ResultSet rs = st.executeQuery(qq);
            int accLen=accountNoLengthFromMasterTable("Personal Loan",branchId);
            if (rs.next())
            {
                String no=rs.getString("od_loan_no");
                account=String.valueOf(Integer.parseInt(no.substring(no.length()-accLen,no.length()))+ 1);
            }
            String initial=accountNoInitialFromMasterTable(branchId,"Od Loan");
            account=initial+commonNo(account,accLen);
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return account;
    }
	
	
	public double interestForLoan(String idplan, Connection conn)
    {
        int i = 1;
        Statement stt=null;
        ResultSet rs=null;
        double interest=0;
        try
        {
             stt = conn.createStatement();
            String qq = "SELECT plan,interest FROM plans where idplans='"+idplan+"' and status='active'";
            rs = stt.executeQuery(qq);
            if(rs.next())
            {
            interest=rs.getDouble("interest");
                
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        finally
        {
            try
            {
                if(stt!=null)
                {
                    stt.close();
                }
                if(rs!=null)
                {
                    rs.close();
                }
            }
            catch (Exception e2)
            {
                // TODO: handle exception
            }
        }
        return interest;
    }
	
	
	
	

	
	public ArrayList<SelectItem> selectedListInDeposit(String shareHolderNo, Connection conn)
    {
        ArrayList<SelectItem> list = new ArrayList<SelectItem>();
        int i = 1;
        Statement stt=null;
        ResultSet rs=null;
        try
        {
             stt = conn.createStatement();
            String qq = "SELECT scheme_type,user_no FROM customer_info where shareHolderNo='"+shareHolderNo+"' and account_status='active'";
             rs = stt.executeQuery(qq);
            while (rs.next())
            {
                SelectItem pp = new SelectItem();
                pp.setLabel(rs.getString("user_no"));
                pp.setValue(rs.getString("user_no"));
                list.add(pp);
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        finally
        {
            try
            {
                if(stt!=null)
                {
                    stt.close();
                }
                if(rs!=null)
                {
                    rs.close();
                }
            }
            catch (Exception e2)
            {
                // TODO: handle exception
            }
        }
        return list;
    }
	
	public String savingAccountByShareHolderNo(String shareHolderNo)
    {
        try (Connection con = DataBaseConnection.JAVAConnection();)
        {
            Statement st = con.createStatement();
            String qq = "select accountNo from savingaccount where shareHolderNo='"+shareHolderNo+"'";
            ResultSet rs = st.executeQuery(qq);
            if(rs.next())
            {
               return rs.getString("accountNo")    ;
            }
        }
        catch (Exception e) {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return "";
    }
	
	public String planSchemeType(String id)
    {
        String aa="";
        try(Connection conn=DataBaseConnection.JAVAConnection())
        {
            Statement st=conn.createStatement();
            String query="select plan from plans where idplans='"+id+"'";
            ResultSet rr=st.executeQuery(query);
            if(rr.next())
            {
                aa=rr.getString("plan");
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return aa;
    }
	
	
	public ArrayList<LoanInfo> odLoanDetails(int branchId,Connection conn)
    {
        String query="";
        int count=1;
        ArrayList<LoanInfo> list=new ArrayList<>();
        Statement stt=null;
        ResultSet ss=null;
        query="select * from od_loan INNER JOIN shareholder_info on od_loan.share_holder_no=shareholder_info.shareholderno where  od_loan.status='active' and shareholder_info.branch_id='"+branchId+"' order by od_loan.id desc";
        try
        {
            stt=conn.createStatement();
            ss=stt.executeQuery(query);
            while(ss.next())
            {
                    LoanInfo info=new LoanInfo();
                   
                    info.setSno(count++);
                    info.setOdLoanDate(ss.getDate("od_loan.od_date"));
                    info.setBankId(ss.getString("od_loan.bank_id"));
                    info.setSavingAccountNo(ss.getString("od_loan.saving_account_no"));
                    info.setOdScheme(ss.getString("od_loan.select_od_scheme"));
                    info.setOdLoanDepositType(ss.getString("od_loan.od_deposit_type"));
                    info.setOdLoanId(ss.getString("od_loan.id"));
                    info.setShareHolderNo(ss.getString("od_loan.share_holder_no"));
                    info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
                    info.setContactNo(ss.getString("shareholder_info.mobile"));
                    info.setOdLoanNo(ss.getString("od_loan.od_loan_no"));
                    info.setStrOdDate(sf.format(ss.getDate("od_loan.od_date")));
                    info.setPaymentMode(ss.getString("od_loan.paymentmode"));
                    info.setOdAmount(ss.getDouble("od_loan.od_amount"));
                    info.setOdInterest(ss.getDouble("od_loan.od_interest"));
                    info.setChqNo(ss.getString("od_loan.paymentmode"));
                    info.setDepositNo(ss.getString("user_no"));
                    list.add(info);
               
            }
           
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        finally
        {
            try
            {
                if(stt!=null)
                {
                    stt.close();
                }

                if(ss!=null)
                {
                    ss.close();
                }
            }
            catch (Exception e2) {
                // TODO: handle exception
            }
        }
        return list;
    }
	
	public String deleteOdLoan(String odLoanNo)
    {
        String a="";
        
        try(Connection con=DataBaseConnection.JAVAConnection();)
        {
            Statement st=con.createStatement();
            String qq="update od_loan set status='inactive' where od_loan_no='"+odLoanNo+"' ";
            int x=st.executeUpdate(qq);
            if(x>0)
            {
            	dataInsertInQueryTable(qq, con);
                return "i";
            }
            
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return "";
    }
public int userWithdrawalForOdLoan(String accno, String amount, Date currentDate,String paymentMode, 
		String chequeNo,Date chequeDate,String bankName,String status, String submittedBankName,int branchId)
    {
		int j=0;
		if(accno!=null && !accno.trim().equalsIgnoreCase(""))
		{
        
	        Timestamp crdt=new Timestamp(currentDate.getTime()),chDate=null;
	        crdt.setHours(0);crdt.setMinutes(0);crdt.setSeconds(0);crdt.setNanos(0);
	        
	        HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
	        String userId=(String) ss1.getAttribute("username");
	        if(paymentMode.equals("Saving Account"))
	        {
	            paymentMode="Transfer From OD Account";
	        }
	        if(chequeDate!=null)
	        {
	            chDate=new Timestamp(chequeDate.getTime());
	        }
	        
	        String chequeStatus="";
	        if(paymentMode.equalsIgnoreCase("Cash") || paymentMode.equalsIgnoreCase("Transfer") || paymentMode.equalsIgnoreCase("Transfer From OD Account"))
	        {
	            chequeStatus="cleared";
	        }
	        else
	        {
	            chequeStatus="uncleared";
	        }
	        try(Connection conn=DataBaseConnection.JAVAConnection();)
	        {
	            String query="insert into customer_withdrwal(account_no,amount,date,payment_mode,cheque_dd_no,cheque_dd_date,from_bank_name,status,bankBranch,chequeStatus, user_id,branch_id) values(?,?,?,?,?,?,?,?,?,?,?,?)";
	        PreparedStatement st1=conn.prepareStatement(query);
	        st1.setString(1,accno);
	        st1.setString(2,amount);
	        st1.setTimestamp(3,crdt);
	        st1.setString(4,paymentMode);
	        st1.setString(5,chequeNo);
	        st1.setTimestamp(6,chDate);
	        st1.setString(7,bankName);
	        st1.setString(8, status);
	        st1.setString(9, "");
	        st1.setString(10, chequeStatus);
	        st1.setString(11, userId);
	        st1.setInt(12, branchId);
	            
	            int i=st1.executeUpdate();
	            if(i>=1)
	            {
	            	dataInsertInQueryTable(query, conn);
	                j++;    
	            }
	        }
	        catch (Exception e)
	        {
	             e.printStackTrace();fileCreation(e.getMessage());
	        }
		}    
        return j;
    }

public UserInfo selectedInfoForDepositList(String shareHolderNo, String searchType, Connection conn)
{
    UserInfo uu=new UserInfo();
    int i = 1;
    Statement stt=null;
    ResultSet rs=null;
    try
    {
         stt = conn.createStatement();
        String qq = "SELECT * FROM customer_info where shareHolderNo='"+shareHolderNo+"' and user_no='"+searchType+"' and account_status='active'";
        rs = stt.executeQuery(qq);
        if(rs.next())
        {
            
            uu.setShareHolderNo(rs.getString("shareHolderNo"));
             uu.setOffice_application_no(rs.getString("office_application_no"));
             if(rs.getDate("office_date")!=null)
             {
                 uu.setOffice_date(rs.getDate("office_date"));
             }
            uu.setOdAmount(paidAmountByUser(rs.getString("user_no"), conn));
            uu.setStrOffcDate(sf.format(rs.getDate("office_date")));
            uu.setUser_no(rs.getString("user_no"));
            uu.setScheme_type(rs.getString("scheme_type"));
            uu.setPlan_no(rs.getString("plan_no"));
            uu.setPlanName(planNameByPlanId(rs.getString("plan_no"), conn));
            uu.setTerms(rs.getInt("terms"));
            uu.setFrequencyLabel(frequencyLabel(rs.getString("frequency")));
            uu.setApplicant_fees(rs.getDouble("applicant_fees"));
            uu.setInstallment_amount(rs.getDouble("installment_amount"));
            uu.setInterest(rs.getDouble("interest"));
            uu.setMaturity_value(rs.getDouble("maturity_value"));
            uu.setMaturity_date(rs.getDate("maturity_date"));
            uu.setStrMatDate(sf.format(rs.getDate("maturity_date")));
            
        }
    }
    catch (Exception e)
    {
         e.printStackTrace();fileCreation(e.getMessage());
    }
    finally
    {
        try
        {
            if(stt!=null)
            {
                stt.close();
            }
            if(rs!=null)
            {
                rs.close();
            }
        }
        catch (Exception e2)
        {
            // TODO: handle exception
        }
    }
    return uu;
}


public double savingAccountByAmount(String savingAcountNo)
{
    try (Connection con = DataBaseConnection.JAVAConnection();)
    {
        Statement st = con.createStatement();
        String qq = "select amount from savingaccount where accountNo='"+savingAcountNo+"'";
        ResultSet rs = st.executeQuery(qq);
        if(rs.next())
        {
           return rs.getDouble("amount");
        }
    }
    catch (Exception e) {
         e.printStackTrace();fileCreation(e.getMessage());
    }
    return 0;
}


public double totalSavingAmount(String savingAccountNo)
{
    try(Connection con=DataBaseConnection.JAVAConnection();)
    {
        Statement st=con.createStatement();
        String qq="select amount from savingaccount where accountNo='"+savingAccountNo+"'";
        ResultSet rs=st.executeQuery(qq);
        if(rs.next())
        {
            return rs.getDouble("amount");
        }
    }
    catch (Exception e)
    {
         e.printStackTrace();fileCreation(e.getMessage());
    }
    
    return 0.0;
}

public void increaseSavingAccountAmountForOdLoan(double amount, String savingAccountNo)
{
    double a=totalSavingAmount(savingAccountNo);
    amount=a+amount;
    amount=Double.parseDouble(df.format(amount));
    try(Connection con=DataBaseConnection.JAVAConnection();)
    {
        Statement st=con.createStatement();
        String qq="update savingaccount set amount='"+amount+"' where accountNo='"+savingAccountNo+"' ";
        int i=st.executeUpdate(qq);
        if(i>0)
        {
        dataInsertInQueryTable(qq, con);
        }
    }
    catch (Exception e)
    {
         e.printStackTrace();fileCreation(e.getMessage());
    }
}

public void decreaseSavingAccountAmountForOdLoan(double amount, String savingAccountNo)
{
    double a=totalSavingAmount(savingAccountNo);
    amount=a-amount;
    amount=Double.parseDouble(df.format(amount));
    try(Connection con=DataBaseConnection.JAVAConnection();)
    {
        Statement st=con.createStatement();
        String qq="update savingaccount set amount='"+amount+"' where accountNo='"+savingAccountNo+"' ";
        int i=st.executeUpdate(qq);
        if(i>0)
        {
        dataInsertInQueryTable(qq, con);
        }
    }
    catch (Exception e)
    {
         e.printStackTrace();fileCreation(e.getMessage());
    }
}

   
public ArrayList<LoanInfo> allOtherLoanList(int branchId,String dsaCode, Date payDate, String searchType, String selectedCenter) 
{
	ArrayList<LoanInfo> list=new ArrayList<>();
	int sNo=1;
	String qq="";
	double amountLeftToPaid=0.00;
	String strPayDate=new SimpleDateFormat("dd/MM/yyyy").format(payDate);
	try(Connection conn=DataBaseConnection.JAVAConnection())
	{
		Statement st=conn.createStatement();
		if(dsaCode.equals("-1"))
		{
			 qq="SELECT * FROM "+searchType+" where frequency not in('365','365.0') and status='Approve' and paidStatus='unpaid' and restructure_status='no' ";
		}
		else
		{
			qq="SELECT * FROM "+searchType+" where frequency not in('365','365.0') and status='Approve' and paidStatus='unpaid' and restructure_status='no' and dsacode='"+dsaCode+"' ";
		}
		
		if(searchType.equalsIgnoreCase("grouploan") && !selectedCenter.equalsIgnoreCase("-1"))
		{
			qq+=" and center='"+selectedCenter+"' ";
		}

		qq=selectQueWithBranch(qq,branchId);
		qq+=" order by loanNo asc";
		ResultSet rr=st.executeQuery(qq);
		while(rr.next())
		{
			String loanNo="", shareHolderColumnName="";
			if(searchType.equalsIgnoreCase("grouploan"))
			{
				loanNo=rr.getString("sub_loan_no");
				shareHolderColumnName="teamLeader";
			}
			else
			{
				loanNo=rr.getString("loanNo");
				shareHolderColumnName="shareholderno";
			}
			ArrayList<String> dList=loanEmiStrDateList(rr.getInt("frequency"), rr.getInt("terms"), rr.getDate("emi_due_date"),rr.getDate("approvalDate"), loanNo, conn);
			
			if(dList.contains(strPayDate))
			{
				LoanInfo cate = new LoanInfo();
				
				double savingAmtPaid=0;
			    double totPayble=rr.getDouble("emi")*rr.getDouble("terms");
				double savingTotal=rr.getDouble("extra_amount")*rr.getDouble("terms");
				double loanAmtPaid=loanPaidAmountByUser(searchType,loanNo, conn);
				if(rr.getDouble("extra_amount")>0)
				{
					savingAmtPaid=savingPaidAmountByUser(branchId,loanNo, conn);
				}
			    amountLeftToPaid=totPayble-loanAmtPaid;
				if(amountLeftToPaid>0.00)
				{
					ArrayList<LoanInfo> loanEMIList=loanInstallment(searchType, loanNo, conn);
					
					for(LoanInfo ll: loanEMIList)
					{
						if(ll.getStatus().equalsIgnoreCase("Due"))
						{
							if(ll.getStrInstlmntDate().equals(strPayDate))
							{
								cate.setSno(sNo++);
								cate.setId(rr.getString("id"));
								cate.setUserId(loanNo);
								cate.setInstallAmount(rr.getDouble("emi"));
							    cate.setLoanAmount(String.valueOf(rr.getDouble("loanAmount")));
							    cate.setInterestAmount(String.valueOf(totPayble-rr.getDouble("loanAmount")));
							    
							    
							    cate.setSavingTotal(savingTotal); //For Saving
								cate.setTotalAmountToBePaid(totPayble);
								cate.setTotalAmountToBePaidSaving(totPayble+savingTotal);  //For Saving
							    cate.setAmountPaid(loanAmtPaid);
							    cate.setAmountPaidSaving(loanAmtPaid+savingAmtPaid);
								cate.setAmountLeftPaid(amountLeftToPaid);
								cate.setAmountLeftPaidSaving(cate.getTotalAmountToBePaidSaving()-cate.getAmountPaidSaving());
								cate.setDsacode(rr.getString("dsacode"));
								cate.setDsaName(dsaNameById(rr.getString("dsacode"),conn));
								cate.setPlanNo(rr.getString("plan_no"));
								cate.setExtraAmt(rr.getDouble("extra_amount"));
								cate.setTotEmiAmt(cate.getInstallAmount()+cate.getExtraAmt());
								
								cate.setShareHolderNo(rr.getString(shareHolderColumnName));
								UserInfo uu=memberBasicDetail(cate.getShareHolderNo(), conn);
								cate.setApplicantName(uu.getName());
								cate.setContactNo(uu.getContactNo());
							    
							    cate.setFatherHusbandName(uu.getFather_husband_name());
								cate.setStrApprovalDate(sf.format(rr.getDate("approvalDate")));
								cate.setAddress(uu.getAddress());
							    cate.setStrLoanCloseDate(loanEMIList.get(loanEMIList.size()-1).getStrInstlmntDate());
							    
							    
							    int m=totalEMIPaidByLoanNo(loanNo, conn);
								int n=rr.getInt("terms")-m;
								cate.setPaidEmiTerms(Integer.toString(m));
								cate.setDueEmino(n);
								cate.setRemark(rr.getInt("terms")+"=" +m+"/"+n);
								cate.setFrequency(rr.getString("frequency")); //this is
								cate.setTerms(rr.getInt("terms"));
								
								System.out.println("finding values task1"+rr.getString("frequency"));
								System.out.println("finding values task1"+rr.getInt("terms"));
								
								list.add(cate);
							}
						}
					}
				}
			}
		}
	}
	catch(Exception e)
	{
		 e.printStackTrace();fileCreation(e.getMessage());
	}
	
	return list;
}


public ArrayList<LoanInfo> allOtherLoanListTillLeftAllLoan(int branchId,String dsaCode, Date payDate, String searchType, String selectedCenter) 
{
	ArrayList<LoanInfo> list=new ArrayList<>();
	int sNo=1;
	String qq="", shareHolderColumnName="";
	double amountLeftToPaid=0.00;
	String strPayDate=new SimpleDateFormat("dd/MM/yyyy").format(payDate);
	try(Connection conn=DataBaseConnection.JAVAConnection())
	{
		Statement st=conn.createStatement();
		if(dsaCode.equals("-1"))
		{
			 qq="SELECT * FROM "+searchType+" where frequency not in('365','365.0')  ";
		}
		else
		{
			qq="SELECT * FROM "+searchType+" where frequency not in('365','365.0') and dsacode='"+dsaCode+"' ";
		}
		
		qq+=" and status='Approve' and paidStatus='unpaid' and restructure_status='no' and approvalDate<='"+sdfForDb.format(payDate)+"'and branch_id='"+branchId+"'  ";
		
		if(searchType.equalsIgnoreCase("grouploan") && !selectedCenter.equalsIgnoreCase("-1"))
		{
			qq+="  and center='"+selectedCenter+"' ";
		}

		qq+=" order by loanNo asc";
		ResultSet rr=st.executeQuery(qq);
		while(rr.next())
		{
			LoanInfo cate = new LoanInfo();
			String loanNo="";
			if(searchType.equalsIgnoreCase("grouploan"))
			{
				loanNo=rr.getString("sub_loan_no");
				shareHolderColumnName="teamLeader";
			}
			else
			{
				loanNo=rr.getString("loanNo");
				shareHolderColumnName="shareholderno";
			}
			
			double totPayble=rr.getDouble("emi")*rr.getDouble("terms");
			double savingTotal=rr.getDouble("extra_amount")*rr.getDouble("terms");
			double loanAmtPaid=loanPaidAmountByUser(searchType,loanNo, conn);
			double savingAmtPaid=savingPaidAmountByUser(branchId,loanNo, conn);
		    amountLeftToPaid=totPayble-loanAmtPaid;
			if(amountLeftToPaid>0.00)
			{
				cate.setSno(sNo++);
				cate.setUserId(loanNo);
				cate.setId(rr.getString("id"));
				//cate.setPaidAmount(0.00);
				cate.setInstallAmount(rr.getDouble("emi"));
			    cate.setLoanAmount(String.valueOf(rr.getDouble("loanAmount")));
			    cate.setInterestAmount(String.valueOf(totPayble-rr.getDouble("loanAmount")));
			    cate.setSavingTotal(savingTotal); //For Saving
				cate.setTotalAmountToBePaid(totPayble);
				cate.setTotalAmountToBePaidSaving(totPayble+savingTotal);  //For Saving
			    cate.setAmountPaid(loanAmtPaid);
			    cate.setAmountPaidSaving(loanAmtPaid+savingAmtPaid);
			    cate.setShareHolderNo(rr.getString(shareHolderColumnName));
			    UserInfo uu=memberBasicDetail(cate.getShareHolderNo(), conn);      // update on 03-march-2021
				cate.setApplicantName(uu.getName());
				cate.setContactNo(uu.getContactNo());
				cate.setFatherHusbandName(uu.getFather_husband_name());
				cate.setAddress(uu.getAddress());
				
				cate.setAmountLeftPaid(amountLeftToPaid);
				cate.setAmountLeftPaidSaving(cate.getTotalAmountToBePaidSaving()-cate.getAmountPaidSaving());
				cate.setDsacode(rr.getString("dsacode"));
				cate.setDsaName(dsaNameById(rr.getString("dsacode"),conn));  
				cate.setPlanNo(rr.getString("plan_no"));
				cate.setExtraAmt(rr.getDouble("extra_amount"));
				cate.setTotEmiAmt(cate.getInstallAmount()+cate.getExtraAmt());
				
				int m=totalEMIPaidByLoanNo(loanNo, conn);
				int n=rr.getInt("terms")-m;
				cate.setPaidEmiTerms(Integer.toString(m));

				//cate.setRemark(rr.getInt("terms")+"=" +m+"/"+n);
				cate.setFrequency(rr.getString("frequency")); //this is
				cate.setTerms(rr.getInt("terms"));
				cate.setPaidEmiTerms(Integer.toString(m));
				
				System.out.println("finding values task1"+rr.getString("frequency"));
				System.out.println("finding values task1"+rr.getInt("terms"));
				
				// No. of Installment Due up to Search Date:
				ArrayList<LoanInfo> loanEMIList=loanInstallment(searchType,loanNo, conn);
				double currentEmiAmountDue = 0, currentDueEmi=0;
				for(int l=0;l<loanEMIList.size();l++)
				{
					if(loanEMIList.get(l).getStatus().equalsIgnoreCase("Due"))
					{
						if(loanEMIList.get(l).getInstallDate().before(payDate))
						{
							currentDueEmi+=1;
							currentEmiAmountDue+=loanEMIList.get(l).getDueAmount();
							////System.out.println(currentEmiAmountDue+"========"+loanEMIList.get(l).getDueAmount());
						}
					}
				}
				
				double totSv=currentDueEmi*rr.getInt("extra_amount");
				cate.setTillLeft(currentEmiAmountDue);
				cate.setTillLeftSaving(currentEmiAmountDue+totSv);
				
				cate.setStrApprovalDate(sf.format(rr.getDate("approvalDate")));
	            cate.setStrLoanCloseDate(loanEMIList.get(loanEMIList.size()-1).getStrInstlmntDate());
				
	            
			  
				
				
				cate.setDueEmino(n);
				
				
			    list.add(cate);
			}
		}
	}
	catch(Exception e)
	{
		 e.printStackTrace();fileCreation(e.getMessage());
	}
	
	return list;
}
	
	  public ArrayList<LoanInfo> odLoanReport(int branchId,Date startDate, Date endDate, String statusType, Connection conn)
	    {
	        String query="";
	        int count=1;
	        ArrayList<LoanInfo> list=new ArrayList<>();
	        Statement stt=null;
	        ResultSet ss=null;
	        if(statusType.equals("All"))
	        {
	            query="select * from od_loan INNER JOIN shareholder_info on od_loan.share_holder_no=shareholder_info.shareholderno where  od_loan.od_date>='"+sdfForDb.format(startDate)+"' and od_loan.od_date <='"+sdfForDb.format(endDate)+"'";
	        }
	        else
	        {
	            query="select * from od_loan INNER JOIN shareholder_info on od_loan.share_holder_no=shareholder_info.shareholderno where od_loan.od_date >='"+sdfForDb.format(startDate)+"' and od_loan.od_date <='"+sdfForDb.format(endDate)+"' and  od_loan.status='"+statusType+"'";
	        }
	       query=selectQueWithBranch(query, branchId, "shareholder_info")+"order by od_loan.id desc";
	        try
	        {
	            stt=conn.createStatement();
	            ss=stt.executeQuery(query);
	            while(ss.next())
	            {
	                    LoanInfo info=new LoanInfo();
	                   
	                    info.setSno(count++);
	                    info.setOdLoanReturnAmount(odLoanReturnAmountByOdLoanNo(ss.getString("od_loan.od_loan_no")));
	                    if(odLoanReturnDateByOdLoanNo(ss.getString("od_loan.od_loan_no"))!=null)
	                    {
	                        info.setStrOdLoanReturnDate(new SimpleDateFormat("dd/MM/yyyy").format(odLoanReturnDateByOdLoanNo(ss.getString("od_loan.od_loan_no"))));
	                    }
	                    else
	                    {
	                        info.setStrOdLoanReturnDate("-");
	                    }
	                   
	                    info.setOdLoanReturnInterest(odLoanReturnInterestByOdLoanNo(ss.getString("od_loan.od_loan_no")));
	                    info.setOdLoanDate(ss.getDate("od_loan.od_date"));
	                    info.setBankId(ss.getString("od_loan.bank_id"));
	                    info.setSavingAccountNo(ss.getString("od_loan.saving_account_no"));
	                    info.setOdScheme(ss.getString("od_loan.select_od_scheme"));
	                    info.setOdLoanDepositType(ss.getString("od_loan.od_deposit_type"));
	                    info.setOdLoanId(ss.getString("od_loan.id"));
	                    info.setShareHolderNo(ss.getString("od_loan.share_holder_no"));
	                    info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
	                    info.setContactNo(ss.getString("shareholder_info.mobile"));
	                    info.setOdLoanNo(ss.getString("od_loan.od_loan_no"));
	                    info.setStrOdDate(sf.format(ss.getDate("od_loan.od_date")));
	                    info.setPaymentMode(ss.getString("od_loan.paymentmode"));
	                    info.setOdAmount(ss.getDouble("od_loan.od_amount"));
	                    info.setOdInterest(ss.getDouble("od_loan.od_interest"));
	                    info.setChqNo(ss.getString("od_loan.paymentmode"));
	                    list.add(info);
	               
	            }
	           
	        }
	        catch (Exception e)
	        {
	             e.printStackTrace();fileCreation(e.getMessage());
	        }
	        finally
	        {
	            try
	            {
	                if(stt!=null)
	                {
	                    stt.close();
	                }

	                if(ss!=null)
	                {
	                    ss.close();
	                }
	            }
	            catch (Exception e2) {
	                // TODO: handle exception
	            }
	        }
	        return list;
	    }
	  
	  public double odLoanReturnInterestByOdLoanNo(String odLoanNo)
	    {
	        try(Connection con=DataBaseConnection.JAVAConnection();)
	        {
	            Statement st=con.createStatement();
	            String qq="select od_return_interest from od_loan_return where od_loan_no='"+odLoanNo+"'";
	            ResultSet rs=st.executeQuery(qq);
	            if(rs.next())
	            {
	                return rs.getDouble("od_return_interest");
	            }
	        }
	        catch (Exception e)
	        {
	             e.printStackTrace();fileCreation(e.getMessage());
	        }
	       
	        return 0.0;
	    }
	   
	   
	   
	    public Date odLoanReturnDateByOdLoanNo(String odLoanNo)
	    {
	        Date dd=null;
	        try(Connection con=DataBaseConnection.JAVAConnection();)
	        {
	            Statement st=con.createStatement();
	            String qq="select od_return_date from od_loan_return where od_loan_no='"+odLoanNo+"'";
	            ResultSet rs=st.executeQuery(qq);
	            if(rs.next())
	            {
	                if(rs.getDate("od_return_date")!=null)
	                {
	                    dd=rs.getDate("od_return_date");
	                }
	               
	            }
	        }
	        catch (Exception e)
	        {
	             e.printStackTrace();fileCreation(e.getMessage());
	        }
	       
	        return dd;
	    }
	   
	    public String statusOfOdLoanByUserNo(String userNo)
	    {
	        try(Connection con=DataBaseConnection.JAVAConnection();)
	        {
	            Statement st=con.createStatement();
	            String qq="select status from od_loan where user_no='"+userNo+"' and status='active'";
	            ResultSet rs=st.executeQuery(qq);
	            if(rs.next())
	            {
	                return rs.getString("status");
	            }
	        }
	        catch (Exception e)
	        {
	             e.printStackTrace();fileCreation(e.getMessage());
	        }
	       
	        return "";
	    }
	    
	    public double odLoanReturnAmountByOdLoanNo(String odLoanNo)
	    {
	        try(Connection con=DataBaseConnection.JAVAConnection();)
	        {
	            Statement st=con.createStatement();
	            String qq="select od_return_amount from od_loan_return where od_loan_no='"+odLoanNo+"'";
	            ResultSet rs=st.executeQuery(qq);
	            if(rs.next())
	            {
	                return rs.getDouble("od_return_amount");
	            }
	        }
	        catch (Exception e)
	        {
	             e.printStackTrace();fileCreation(e.getMessage());
	        }
	        
	        return 0.0;
	    }  
	    
	    public String addOdLoan(int branchId,Date odLoanDate, double odAmount, String shareHolderNo, String loanNo, double odInterest, String payMode, String bankName, String chequeNo, Date chequeDate, String odloanNo, String searchType, String searchScheme, String savingAccountNo, String submittedBankName, Connection conn)
	    {
	        int i=0;
	        PreparedStatement st=null;
	        ResultSet rr=null;
	        String query="";
	        if(chequeDate!=null)
	        {
	            query="insert into od_loan(user_no, share_holder_no, od_loan_no, od_date, od_amount, od_interest, paymentmode, chq_date, chq_no, bank_name,od_deposit_type,select_od_scheme,saving_account_no,bank_id,branch_id)values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
	        }
	        else
	        {
	            query="insert into od_loan(user_no, share_holder_no, od_loan_no, od_date, od_amount, od_interest, paymentmode,  chq_no, bank_name,od_deposit_type,select_od_scheme,saving_account_no,bank_id,branch_id)values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
	        }
	        try
	        {
	            st=conn.prepareStatement(query);
	            st.setString(1, loanNo);
	            st.setString(2, shareHolderNo);
	            st.setString(3, odloanNo);
	            st.setTimestamp(4, new Timestamp(odLoanDate.getTime()));
	            st.setDouble(5, odAmount);
	            st.setDouble(6, odInterest);
	            st.setString(7, payMode);
	            if(chequeDate!=null)
	            {
	                st.setTimestamp(8, new Timestamp(chequeDate.getTime()));
	                st.setString(9, chequeNo);
	                st.setString(10, bankName);
	                st.setString(11, searchType);
	                st.setString(12, searchScheme);
	                st.setString(13, savingAccountNo);
	                st.setString(14, submittedBankName);
	                st.setInt(15, branchId);
	            }
	            else
	            {
	            st.setString(8, chequeNo);
	            st.setString(9, bankName);
	            st.setString(10, searchType);
	            st.setString(11, searchScheme);
	            st.setString(12, savingAccountNo);
	            st.setString(13, submittedBankName);
	            st.setInt(14, branchId);
	            }
	           
	            i=st.executeUpdate();
	            if(i >0)
	            {
	            	dataInsertInQueryTable(String.valueOf(st), conn);
	                return "i";
	            }
	        }
	        catch (Exception e)
	        {
	              e.printStackTrace();fileCreation(e.getMessage());
	        }
	        finally
	        {
	            try {
	                if(st!=null)
	                {
	                    st.close();
	                }
	                if(rr!=null)
	                {
	                    rr.close();
	                }
	            } catch (Exception e2) {
	                // TODO: handle exception
	            }
	       
	        }
	        return "";
	    }

	public String depoasitNoBYUserNo(String depositType)
	    {
	        try (Connection con = DataBaseConnection.JAVAConnection();)
	        {
	            Statement st = con.createStatement();
	            String qq = "select user_no from od_loan where user_no='"+depositType+"' and status='active'";
	            ResultSet rs = st.executeQuery(qq);
	            if(rs.next())
	            {
	               return rs.getString("user_no")    ;
	            }
	        }
	        catch (Exception e) {
	             e.printStackTrace();fileCreation(e.getMessage());
	        }
	        return "";
	    }
	
	public String addOdLoanReturn(int branchId,Date odReturnDate, double odReturnAmount, String shareHolderNo, String loanNo, double odReturnInterest, String payMode, String bankName, String chequeNo, Date chequeDate, String odloanNo, String searchType, String searchScheme, String savingAccountNo, String submittedBankName, Connection conn)
    {
        int i=0;
        PreparedStatement st=null;
        ResultSet rr=null;
        String query="";
        if(chequeDate!=null)
        {
            query="insert into od_loan_return(user_no, share_holder_no, od_loan_no, od_return_date, od_return_amount, od_return_interest, paymentmode, chq_date, chq_no, bank_name,od_deposit_type,select_od_scheme,saving_account_no,bank_id,branch_id)values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        }
        else
        {
            query="insert into od_loan_return(user_no, share_holder_no, od_loan_no, od_return_date, od_return_amount, od_return_interest, paymentmode,  chq_no, bank_name,od_deposit_type,select_od_scheme,saving_account_no,bank_id,branch_id)values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        }
        try
        {
            st=conn.prepareStatement(query);
            st.setString(1, loanNo);
            st.setString(2, shareHolderNo);
            st.setString(3, odloanNo);
            st.setTimestamp(4, new Timestamp(odReturnDate.getTime()));
            st.setDouble(5, odReturnAmount);
            st.setDouble(6, odReturnInterest);
            st.setString(7, payMode);
            if(chequeDate!=null)
            {
                st.setTimestamp(8, new Timestamp(chequeDate.getTime()));
                st.setString(9, chequeNo);
                st.setString(10, bankName);
                st.setString(11, searchType);
                st.setString(12, searchScheme);
                st.setString(13, savingAccountNo);
                st.setString(14, submittedBankName);
                st.setInt(15, branchId);
            }
            else
            {
            st.setString(8, chequeNo);
            st.setString(9, bankName);
            st.setString(10, searchType);
            st.setString(11, searchScheme);
            st.setString(12, savingAccountNo);
            st.setString(13, submittedBankName);
            st.setInt(14, branchId);
            }
           
            i=st.executeUpdate();
            if(i >0)
            {
            	dataInsertInQueryTable(String.valueOf(st), conn);
                return "i";
            }
        }
        catch (Exception e)
        {
              e.printStackTrace();fileCreation(e.getMessage());
        }
        finally
        {
            try {
                if(st!=null)
                {
                    st.close();
                }
                if(rr!=null)
                {
                    rr.close();
                }
            } catch (Exception e2) {
                // TODO: handle exception
            }
       
        }
        return "";
    }
   
    public int updateStatusInOdLoan(String odLoanNo, String depositNo, Connection conn)
    {
        int i=0;
        Statement st=null;
        try
        {
             st=conn.createStatement();
            String qq="update od_loan set status='inactive' where user_no='"+depositNo+"' and od_loan_no='"+odLoanNo+"'";
            i=st.executeUpdate(qq);
            if(i>0)
            {
            	dataInsertInQueryTable(qq, conn);
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
       
        return i;
    }
    
    public ArrayList<EmpInfo> allActiveLoginUser(int branchId,String searchType, String selectUserType, Connection conn) 
	{
		int count=1;String qq="";
		ArrayList<EmpInfo> list=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			if(searchType.equalsIgnoreCase("all"))
			{
				qq="select * from login where type='"+selectUserType+"' ";
			}
			else
			{
				qq="select * from login where type='"+selectUserType+"' and status='"+searchType+"' ";
			}
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				EmpInfo ee=new EmpInfo();
				
				ee.setSno(count++);
				ee.setId(rr.getString("id"));
				ee.setUname(rr.getString("userid"));
				if(selectUserType.equalsIgnoreCase("user"))
				{
					ee.setName(applicantNameByShareHolderNo(ee.getUname(),conn));
					ee.setMobile(applicantContactNoByShareHolderNo(ee.getUname(), conn));
					ee.setFname(applicantFatherNameByShareHolderNo(ee.getUname(), conn));
				}
				else
				{
					ee.setName(employeeNameByUsername(ee.getUname()));
					ee.setMobile(rr.getString("mobile_no"));
					ee.setFname(employeeFatherNameByUsername(ee.getUname(), conn));
				}
				ee.setPwd(rr.getString("password"));
				ee.setStatus(rr.getString("status"));
				if(rr.getString("status").equalsIgnoreCase("active"))
				{
					ee.setDisActive(true);
					ee.setDisInactive(false);
				}
				else
				{
					ee.setDisActive(false);
					ee.setDisInactive(true);
				}
				
				list.add(ee);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		 {
			 try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		 }
		return list;
	}
    
    public String applicantFatherNameByShareHolderNo(String shno, Connection conn)
	{
	    System.out.println("Shareholder No = " + shno);

	    Statement st = null;
	    ResultSet rr = null;

	    try
	    {
	        st = conn.createStatement();
	        String qq = "select father_husband_name from shareholder_info where shareholderno='"+shno+"'";
	        System.out.println("Query = " + qq);

	        rr = st.executeQuery(qq);

	        if(rr.next())
	        {
	            String father = rr.getString("father_husband_name");
	            System.out.println("Father Name = " + father);
	            return father;
	        }
	        else
	        {
	            System.out.println("No Record Found");
	        }
	    }
	    catch(Exception e)
	    {
	        e.printStackTrace();
	    }

	    return "";
	}
public String employeeFatherNameByUsername(String username, Connection conn) {
		
		Statement st = null;
	    ResultSet rr = null;

	    try
	    {
	        st = conn.createStatement();

	        String qq = "select fname from employee where uname='" + username + "'";
	        rr = st.executeQuery(qq);

	        if(rr.next())
	        {
	            return rr.getString("fname");
	        }
	    }
	    catch(Exception e)
	    {
	        e.printStackTrace();
	    }
	    finally
	    {
	        try
	        {
	            if(st != null) st.close();
	            if(rr != null) rr.close();
	        }
	        catch(Exception e){}
	    }

	    return "";
	}
	
	public int updateLoginStatus(String id, String status) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update login set status='"+status+"' where id='"+id+"' ";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
				//dataInsertInQueryTable(qq, conn);
				return i;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public int updateLoginStatusByUserId(String userId, String status) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update login set status='"+status+"' where userid='"+userId+"' ";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
				//dataInsertInQueryTable(qq, conn);
				return i;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	
	public String applicantContactNoByShareHolderNo(String shno, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select mobile from shareholder_info where shareholderno='"+shno+"' and account_status='active'";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("mobile");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}
	
	public void updateMemberLoginPassword(String uname, int s) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update login set password='"+s+"' where userid='"+uname+"' ";
		int i=	st.executeUpdate(qq);
		{	
		dataInsertInQueryTable(qq, conn);
		}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}
	public int appPasswordByUserId(String shareNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select password from login where userid='"+shareNo+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getInt("password");
			}
		int i=	st.executeUpdate(qq);
		if(i>0)
		{
			dataInsertInQueryTable(qq, conn);
		}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public int updateAppPayLoanEmiStatus(String id, String string) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update loan_payment_from_app set status='"+string+"' where id='"+id+"' ";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
				dataInsertInQueryTable(qq, conn);
			return i;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public String fileChargeAndInsFeePayMode(String loanNo, Connection conn) 
	{	
		Statement st=null;
		ResultSet rr=null;
		try 
		{
			st=conn.createStatement();
			String qq="select payment_mode from income_table where loan_no='"+loanNo+"' ";
			//// //System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("payment_mode");
			}
		} 
		catch (SQLException e) {
			// TODO Auto-generated catch block
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return "";
	}

	public String contactNoForSchedularMsg(int branchId,Connection conn) 
	{
		String contactNo="";
		try
		{
			Statement st=conn.createStatement();
			String qq="select mobile_no from firm_detail where id ='"+branchId+"'";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				contactNo=rr.getString("mobile_no");
				if(contactNo==null || contactNo.equals(""))
				{
					contactNo="9982311326";
				}
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return contactNo;
	}
	
	public String contactNoForSchedularMsgForOtherDirectors(int branchId,String columnName, Connection conn) 
	{
		String contactNo="";
		try
		{
			Statement st=conn.createStatement();
			String qq="select "+columnName+" from firm_detail where id ='"+branchId+"'";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				contactNo=rr.getString(columnName);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return contactNo;
	}

	public ArrayList<TrialInfo> trialBalanceOdLoanPayementAndReceipt(int branchId,Date startDate, Date endDate, Connection conn) 
	{
		String sDate=sdfForDb.format(startDate.getTime());
		String eDate=sdfForDb.format(endDate.getTime());
		ArrayList<TrialInfo> list=new ArrayList<>();
		HeaderBean hh=new HeaderBean();
		Statement st=null;ResultSet rr=null;		
		try
		{
			st=conn.createStatement();
			String qq="select od_loan_no from od_loan ";
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				TrialInfo tt=new TrialInfo();
				//if(chk==true)
				{
					tt.setCategory("OD Loan");
				}
				String loanNo=rr.getString("od_loan_no");
				tt.setParticular(loanNo);
				tt.setOpeningCr(0);
				tt.setOpeningDr(0);
				tt.setDebit(Double.parseDouble(df.format(debitOdLoanAmountByLoanNo(loanNo, sDate, eDate))));
				tt.setCredit(Double.parseDouble(df.format(creditOdLoanAmountByLoanNo(loanNo, sDate, eDate))));
				
				list.add(tt);
			}	
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
		
			}
		}
		return list;
	}
	
	
	public double calculateCashBalance(int branchId,Date searchDate, Connection conn)
	{
		String sDate=sdfForDb.format(searchDate);
		double cashIn=closingCashInBalance(branchId,sDate, conn, "");
		double cashOut=closingCashOutBalance(branchId,sDate, conn, "");
		double balance=Double.parseDouble(df.format(cashIn-cashOut));
		return balance;
	}
	
	public double calculateBankBalance(int branchId,Date searchDate, Connection conn, String bankId)
	{
		String sDate=sdfForDb.format(searchDate);
		double bankIn=closingBalanceOfBankIn(branchId,bankId, sDate, conn, "");
		double bankOut=closingBalanceOfBankOut(branchId,bankId, sDate, conn, "");
		double balance=Double.parseDouble(df.format(bankIn-bankOut));
		
		return balance;
	}
	
	public ArrayList<String> loanEmiDueList(int branchId,String schemeType, String frequency, String dsaCode, String center[], Connection conn)
    {
        ArrayList<String> list = new ArrayList<>();
        String qq="", columnName="";
        try
        {
            Statement st=conn.createStatement();
            if(schemeType.equalsIgnoreCase("grouploan"))
            {
            	columnName="sub_loan_no";
            }
            else
            {
            	columnName="loanNo";
            }
            
            if(center==null || center.length==0)
			{
            	qq="SELECT "+columnName+",frequency,terms,emi_due_date,approvalDate,emi  FROM "+schemeType+" where status='Approve' and paidStatus='unpaid' and restructure_status='no'  ";
                
                if(!dsaCode.equalsIgnoreCase("all"))
                {
                	qq+=" and dsacode='"+dsaCode+"' ";
                }
                
                
                if(!frequency.equalsIgnoreCase("all"))
                {
                	qq+=" and frequency='"+frequency+"' ";
                }
              // //System.out.println(qq);
                ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
                while(rr.next())
                {
                	ArrayList<String> dList=loanEmiStrDateList(rr.getInt("frequency"), rr.getInt("terms"), rr.getDate("emi_due_date"),rr.getDate("approvalDate"),rr.getString(columnName), conn);
                	SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy");
            		
                	int count=0;
                	for(String dd: dList)
                	{
                		Date emiDate=f.parse(dd);
                		Date dt=new Date();
                    	if(emiDate.before(dt))
                    	{
                    		count++;
                    	}
                	}
                	
                	double totPayble=count*rr.getDouble("emi");
                	double totPay=loanPaidAmountByUser(schemeType, rr.getString(columnName), conn);
                	double totBal=totPayble-totPay;
                	if(totBal>0)
                	{
                		list.add(rr.getString(columnName));
                	}
                }	
			}
            else
            {
            	for(int k=0; k<center.length;k++)
				{
            		qq="SELECT "+columnName+",frequency,terms,emi_due_date,approvalDate,emi  FROM "+schemeType+" where status='Approve' and paidStatus='unpaid' and "
            				+ " restructure_status='no' and center='"+center[k]+"' ";
            		 ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
                    while(rr.next())
                    {
                    	ArrayList<String> dList=loanEmiStrDateList(rr.getInt("frequency"), rr.getInt("terms"), rr.getDate("emi_due_date"),rr.getDate("approvalDate"),rr.getString(columnName), conn);
                    	SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy");
                		
                    	int count=0;
                    	for(String dd: dList)
                    	{
                    		Date emiDate=f.parse(dd);
                    		Date dt=new Date();
                        	if(emiDate.before(dt))
                        	{
                        		count++;
                        	}
                    	}
                    	
                    	double totPayble=count*rr.getDouble("emi");
                    	double totPay=loanPaidAmountByUser(schemeType, rr.getString(columnName), conn);
                    	double totBal=totPayble-totPay;
                    	if(totBal>0)
                    	{
                    		list.add(rr.getString(columnName));
                    	}
                    }
				}  
            }
        }
        catch(Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return list;
    }

	// Auto Message Notification on Laon and Deposit Upcoming EMI, call through schedular
	public ArrayList<UserInfo> dataFromAutoMessageSettingTable() 
	{
		int count=1;
		ArrayList<UserInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from auto_message_setting";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				UserInfo uu=new UserInfo();
				
				uu.setSno(count++);
				uu.setId(rr.getString("id"));
				uu.setModuleType(rr.getString("module_type"));
				uu.setFrequency(rr.getInt("frequency"));
				uu.setFrequencyLabel(rr.getString("frequency_label"));
				uu.setDayBefore(rr.getInt("day_before"));
				uu.setBooleanStatus(rr.getBoolean("status"));
				uu.setModuleLabel(rr.getString("module_label"));
				
				list.add(uu);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}
	
	// Auto Message Notification on Laon and Deposit Upcoming EMI, call through schedular
	public ArrayList<UserInfo> dataFromLastEntrySettingTable(int branchId) 
	{
		int count=1;
		ArrayList<UserInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from last_entry_setting";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				UserInfo uu=new UserInfo();
				
				uu.setSno(count++);
				uu.setId(rr.getString("id"));
				uu.setBooleanStatus(rr.getBoolean("status"));
				uu.setModuleLabel(rr.getString("module_label"));
				uu.setModuleName(rr.getString("module_name"));
				
				list.add(uu);
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	public int updateAutoMessageDetail(UserInfo selectedRow)
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update auto_message_setting set day_before='"+selectedRow.getDayBefore()+"', status='"+selectedRow.isBooleanStatus()+"' where id='"+selectedRow.getId()+"' ";
			int i=st.executeUpdate(qq);
			dataInsertInQueryTable(qq, conn);
			return i;
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public int updateLastEntrySettingDetail(int branchId,UserInfo selectedRow)
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update last_entry_setting set status='"+selectedRow.isBooleanStatus()+"' where id='"+selectedRow.getId()+"' ";
			int i=st.executeUpdate(selectQueWithBranch(qq,branchId));
			if(i>0)
			{
				dataInsertInQueryTable(qq, conn);
			}
			
			return i;
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	// depend on Nidhi if amount of share taken from client at the share holder registration then this amount is auto return to client when share return
	public boolean checkShareAmountFromMember() 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select share_amt_member from company_shares";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				if(rr.getString("share_amt_member").equalsIgnoreCase("yes"))
				{
					return true;
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return false;
	}
	
	// depend on Nidhi if amount of share taken from client at the share holder registration then this amount is auto return to client when share return
	public boolean checkShareAllotmentFromMember() 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select share_check from company_shares";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				if(rr.getString("share_check").equalsIgnoreCase("yes"))
				{
					return true;
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return false;
	}

	// Return Loan Amount Release Date 
	public Date loanDisburseDateByLoanNo(String loanNo, Connection conn) 
	{
		Date cDate=new Date();
		try
		{
			Statement st=conn.createStatement();
			String qq="select date from debit_loan where loanNo='"+loanNo+"' and status='cleared' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDate("date");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return cDate;
	}
	
	// File Charge and Insurance Fee Amount Receive Either at the time of Loan Request or Loan Approve. It will depend on User Choice.
	// Default at the time of Loan Request
	public int updateMasterSettings(Connection conn, String status, String moduleName,String id)
    {
        Statement stt=null;
        int i=0;
       
        try {
            stt=conn.createStatement();
            String query="update master_setting_new set status='"+status+"' where id='"+id+"'";
            i=stt.executeUpdate(query);
            if(i>0)
            {
                return 1;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return 0;
    }

    public ArrayList<SettingInfo> showMasterSetting(int branchId,Connection conn)
    {
        Statement stt= null;
        ResultSet rr=null;
        int sNo=1;
        ArrayList<SettingInfo>list=new ArrayList<>();
        try {
            String query = "select * from master_setting_new";
            stt=conn.createStatement();
            rr=stt.executeQuery(query);
            while(rr.next())
            {
                SettingInfo ss=new SettingInfo();
               
                ss.setsNo(sNo++);
                ss.setId(rr.getString("id"));
                ss.setModuleName(rr.getString("module_name"));
                ss.setStatus(rr.getString("status"));
               
                list.add(ss);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }

    // Return File Charge and Insurance Fee Amount Receive Either at the time of Loan Request or Loan Approve. It will depend on User Choice.
	public String checkSettingFromMasterSettingNewTable(String moduleName, Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select status from master_setting_new where module_name='"+moduleName+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("status");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return "loan_request";
	}

	// If File Charge and Insurance Fee Amount Receive at the time of Loan Approve. 
	public int updateIncomeTableSelectedPendingEntryStatus(String itemName, String entryStatus, String loanNo, Connection conn, Date releaseDate) 
	{
		Timestamp tt=null;
		if(releaseDate!=null)
		{
			tt=new Timestamp(releaseDate.getTime());
		}
		
		try
		{
			String qq = "update income_table set status=?, income_date=? where item='"+itemName+"' and loan_no='"+loanNo+"' and status='pending' ";
			
			PreparedStatement st1 = conn.prepareStatement(qq);
			st1.setString(1, entryStatus);
			st1.setTimestamp(2, tt);
			int i=st1.executeUpdate();
			return i;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}
	
	// If File Charge and Insurance Fee Amount Receive at the time of Loan Approve. 
		public int updateIncomeTableSelectedActiveEntryStatus(String itemName, String entryStatus, String loanNo, Connection conn, Date releaseDate) 
		{
			Timestamp tt=null;
			if(releaseDate!=null)
			{
				tt=new Timestamp(releaseDate.getTime());
			}
			
			try
			{
				Statement st=conn.createStatement();
				String qq="update income_table set status='pending' where item='"+itemName+"' and loan_no='"+loanNo+"' and status='active' ";
				int i=st.executeUpdate(qq);
				return i;
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			return 0;
		}


	public double totalPreMaturityChargesOnDeposit(int branchId,Date startDate, Date endDate, Connection conn, String columnName) 
	{
		 Statement stt=null;
		 ResultSet rs=null;
		 String start=sdfForDb.format(startDate);
		 String end=sdfForDb.format(endDate);
		 
		 try 
		{
            stt=conn.createStatement();
		     String query="select sum("+columnName+") as totalAmount from returned_amount_info where chequeStatus='cleared' and date>='"+start+"'  and date <= '"+end+"'";	
		     rs=stt.executeQuery(selectQueWithBranch(query,branchId));
		     if(rs.next())
		     {
		    	 return rs.getDouble("totalAmount");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(stt!=null)
				{
					stt.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0.0;
	}
	
	
	public int shareReturnFromShareHolder(UserInfo selecteduser) 
	{
		int i=0;
		try(Connection conn= DataBaseConnection.JAVAConnection()) 
		{
			Statement st=conn.createStatement();
			String query="update shareholder_info set crNo='"+i+"', noofShare='"+i+"', transfer_from='"+i+"', totalAmount='"+i+"' where shareHolderNo='"+selecteduser.getShareHolderNo()+"'";
			int rr=st.executeUpdate(query);
			if(rr>0)
			{
				i++;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}


	public void enterValuesInShareReturnTable(int branchId,String transferFrom, String crNo, Date shareReturnDate, double noOfShare, String shareHolderNo) 
	{
		Timestamp sendDate=new Timestamp(new Date().getTime());
		sendDate.setNanos(0);
		sendDate.setHours(0);
		sendDate.setMinutes(0);
		sendDate.setMinutes(0);

		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="insert into share_return(transfer_from, transfer_to, crno, noofshare, return_date,branch_id) "
					+ "values('"+shareHolderNo+"','"+transferFrom+"','"+crNo+"','"+noOfShare+"','"+sendDate+"','"+branchId+"')";
			int i=st.executeUpdate(query);
			if(i>0)
			{
				dataInsertInQueryTable(query, conn);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();fileCreation(e.getMessage());
		}
	}


	public Double noOfShareofTranfershareHolder(String transferFrom) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select noofShare from shareholder_info where shareholderno='"+transferFrom+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("noofShare");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0.0;
	}


	public int updateTotalNoOfShare(String transferFrom, double totalnoofshare) 
	{
		int i=0;
		try(Connection conn= DataBaseConnection.JAVAConnection()) 
		{
			Statement st=conn.createStatement();
			String query="update shareholder_info set noofShare='"+totalnoofshare+"' where shareHolderNo='"+transferFrom+"'";
			int rr=st.executeUpdate(query);
			if(rr>0)
			{
				i++;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}
	
	public int updateTotalAmountOfShare(String transferFrom, double totalAmountShare) 
	{
		int i=0;
		try(Connection conn= DataBaseConnection.JAVAConnection()) 
		{
			Statement st=conn.createStatement();
			String query="update shareholder_info set totalAmount=(totalAmount+'"+totalAmountShare+"') where shareHolderNo='"+transferFrom+"'";
			int rr=st.executeUpdate(query);
			if(rr>0)
			{
				i++;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}
	
	
	public ArrayList<DueDebitInfo> ReturnAmountRdFdList(int branchId)
    {
        ArrayList<DueDebitInfo> list=new ArrayList<>();
        
        int i=0;
        Date tdyDate=new Date();
        Timestamp tdyDt=new Timestamp(tdyDate.getTime());
        tdyDt.setHours(0);tdyDt.setMinutes(0);tdyDt.setSeconds(0);tdyDt.setNanos(0);
        
        try(Connection conn=DataBaseConnection.JAVAConnection())
        {
            Statement st=conn.createStatement();
            String query="select * from returned_amount_info where chequeStatus='cleared'";
            ResultSet rr=st.executeQuery(selectQueWithBranch(query,branchId));
            while(rr.next())
            {
                DueDebitInfo info=new DueDebitInfo();
                
                info.setId(rr.getString("id"));
                if(rr.getDate("chequeDate")!=null)
                {
                info.setChequeDate(rr.getDate("chequeDate"));
                }
                info.setBankId(rr.getString("bankName"));
                info.setBankName(bankNameById(rr.getString("bankName")));
                
                info.setBankBranch(rr.getString("bankBranch"));
                info.setChequeNo(rr.getString("chequeNo"));
                info.setPaymentMode(rr.getString("paymentMode"));
                info.setPrematurityCharge(rr.getDouble("pre_maturity_charge"));
                info.setStationaryCharge(rr.getDouble("stationary_charge"));
                info.setOtherCharge(rr.getDouble("other_charge"));
                info.setItem_loan_fdr(rr.getString("user_no"));
                info.setIncomeDate(rr.getDate("date"));

                list.add(info);
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return list;
    }
	
	public String RdFdNoByshareHolderNo(int branchId,String accno)
    {
        try (Connection con = DataBaseConnection.JAVAConnection();)
        {
            Statement st = con.createStatement();
            String qq = "select user_no from customer_info where shareHolderNo='"+accno+"'";
            
            ResultSet rs = st.executeQuery(selectQueWithBranch(qq,branchId));
            if(rs.next())
            {
               return rs.getString("user_no");
            }
        }
        catch (Exception e) {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return "";
    }
	
	public int RdAmountByshareHolderNo(int branchId,String accno)
    {
        try (Connection con = DataBaseConnection.JAVAConnection();)
        {
            Statement st = con.createStatement();
            String qq = "select installment_amount from customer_info where shareHolderNo='"+accno+"' and account_status='active' and scheme_type='RD' ";
            //System.out.println(qq);
            ResultSet rs = st.executeQuery(selectQueWithBranch(qq,branchId));
            if(rs.next())
            {
               return rs.getInt("installment_amount")    ;
            }
        }
        catch (Exception e) {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        return 0;
    }
	
	
	public String calculateTotalDepositInSelectedRd1(String user_no, double intrst, int frequency) 
	{
		int receiveAmount=0;double maturityAmount=0.00;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from payment_receipt where user_no='"+user_no+"' and receipt_status='approved' ";
			// // // // //System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				receiveAmount=receiveAmount+ rr.getInt("amount");
			    double intr=creditDateCheck(sf.format(rr.getDate("date")),rr.getInt("amount"),intrst / frequency);
			    maturityAmount=maturityAmount+intr;
			    
				
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();fileCreation(e.getMessage());
		}
		return String.valueOf(receiveAmount+"-"+maturityAmount);
	}
	

	public double creditDateCheck(String payDateString, double amount, double intrst)
	{
		Double interestAmount=0.00;
		DateFormat formatDate = sf;
		Date payDate = null;
		try {
		payDate = formatDate.parse(payDateString);
		} catch (ParseException e) {
		e.printStackTrace();
		}
		int count=differenceInMonths(payDate);
		if(payDate.before(new Date()))
		{
		  interestAmount=(amount*count*intrst)/100;
		}
		else
		{
		  interestAmount=0.00;
		}
		return interestAmount;
	 

	}
	
	public int differenceInMonths(Date offcdt) 
	{
		Calendar startCalendar = new GregorianCalendar();
		startCalendar.setTime(offcdt);
		Calendar endCalendar = new GregorianCalendar();
		endCalendar.setTime(new Date());
	
		int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
		int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
		// // // // //System.out.println("the difference in moth is"+diffMonth);
		return diffMonth;
	}
	
	
	public double creditDateCheckClosing(String payDateString,Date closeDate, double amount, double intrst)
	{
		Double interestAmount=0.00;
		DateFormat formatDate = sf;
		Date payDate = null;
		try {
		payDate = formatDate.parse(payDateString);
		} catch (ParseException e) {
		e.printStackTrace();
		}
		int count=differenceInMonthsClosing(payDate,closeDate);
		if(payDate.before(new Date()))
		{
		  interestAmount=(amount*count*intrst)/100;
		}
		else
		{
		  interestAmount=0.00;
		}
		return interestAmount;
	}
	
	public int differenceInMonthsClosing(Date offcdt,Date closeDate) 
	{
		Calendar startCalendar = new GregorianCalendar();
		startCalendar.setTime(offcdt);
		Calendar endCalendar = new GregorianCalendar();
		endCalendar.setTime(closeDate);
	
		int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
		int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
		// // // // //System.out.println("the difference in moth is"+diffMonth);
		return diffMonth;
	}
	
	
	public LoanEmiReceiptInfo loanCloserReceiptInfo(String loanNo)
    {
        LoanEmiReceiptInfo ll=new LoanEmiReceiptInfo();
        try(Connection con=DataBaseConnection.JAVAConnection();)
        {
            Statement st=con.createStatement();
            String query="select * from loanpayment where loanNo='"+loanNo+"' and receipt_status='approved' and chequeStatus in ('cleared') and emi_no='-1' ";
             // //System.out.println(query);
            ResultSet rr=st.executeQuery(query);
            if(rr.next())
            {
                
                ll.setId(rr.getString("id"));
                ll.setLoanType(rr.getString("loanType"));
                ll.setLoanNo(rr.getString("loanNo"));
                ll.setAmount(rr.getDouble("amount"));
                ll.setPay_date(rr.getDate("pay_date"));
                ll.setInterestAmount(rr.getDouble("interestAmount"));
                ll.setStrPayDate(new SimpleDateFormat("dd/MM/yyyy").format(rr.getDate("pay_date")));
                ll.setPay_mode(rr.getString("pay_mode"));
                ll.setStatus(rr.getString("receipt_status"));
                if(ll.getStatus().equalsIgnoreCase("pending"))
                {
                    ll.setDisableEdit(false);
                }
                else
                {
                    ll.setDisableEdit(true);
                }
                
                if (rr.getString("pay_mode").equals("cheque"))
                {
                    ll.setChq_no(rr.getString("chq_no"));
                    ll.setChq_date(rr.getDate("chq_date"));
                    ll.setBank_name(rr.getString("bank_name"));
                    ll.setStrChqDate(new SimpleDateFormat("dd/MM/yyyy").format(rr.getDate("chq_date")));
                }
                ll.setPenalty(rr.getDouble("penalty"));
                ll.setReceipt_no(rr.getString("receipt_no"));
                ll.setTransferBank(rr.getString("transfer_to_bank"));
                ll.setTransferToBankName(new DataBaseMethods().bankNameById(rr.getString("transfer_to_bank")));
                ll.setEmiNoStr(rr.getString("emi_no"));
                
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return ll;
    }

	public ArrayList<SelectItem> financialYearList(int branchId,Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		ArrayList<SelectItem> fyList=new ArrayList<>();
		try
		{
			st=conn.createStatement();
			String query="select financial_year from fy_setting"; 
			rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				SelectItem ii=new SelectItem();
				
				ii.setLabel(rr.getString("financial_year"));
				ii.setValue(rr.getString("financial_year"));
				
				fyList.add(ii);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return fyList;
	}

	// check Data Freeze status financial year wise
	public boolean checkDataFreezing(int branchId,String selectedSession, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select * from fy_setting where financial_year='"+selectedSession+"' "; 
			rr=st.executeQuery(selectQueWithBranch(query,branchId));
			if(rr.next())
			{
				if(rr.getString("data_freeze_status").equalsIgnoreCase("yes"))
				{
					return true;
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return false;
	}

	public double discountOnLoanCloser(String loanNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select discount from loanpayment where emi_no='-1' and loanNo='"+loanNo+"' and receipt_status='approved' and chequeStatus='cleared' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("discount");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}
	
	public String previousFinancialYear(int branchId)
    {
        try(Connection conn=DataBaseConnection.JAVAConnection())
        {
            Statement st=conn.createStatement();
            String qq="select financial_year from fy_setting where branch_id='"+branchId+"'  order by id desc";
            ResultSet rr=st.executeQuery(qq);
            if(rr.next())
            {
                return rr.getString("financial_year");
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return "";
    }

	// Method Work when Data is finalize for Freezing
	public int insertBalanceSheetData(int branchId,ArrayList<UserInfo> bsList, String string, Connection conn) 
	{
		int i=0;
		try
		{
			Statement st=conn.createStatement();
			for(UserInfo uu: bsList)
			{
				String qq="insert into balance_sheet(liabilities_head, dr_amount, assets_head, cr_amount, financial_year,branch_id) "
						+ "values('"+uu.getLiabilitiesHead()+"','"+uu.getDrAmount()+"','"+uu.getAssetsHead()+"','"+uu.getCrAmount()+"','"+string+"','1') ";
				i=st.executeUpdate(qq);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return i;
	}

	// update on data Freeze or Unfreeze at the financial year ending
	public void updateDataFreezeStatus(int branchId,String selectedSession, String string, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="update fy_setting set data_freeze_status='"+string+"' where financial_year='"+selectedSession+"' "; 
			st.executeUpdate(selectQueWithBranch(query,branchId));
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}

	// Method for Auto No Generate to the Share Holder, DD, RD, FD, DSA etc 
	public ArrayList<UserInfo> basicSettingForAutoGenerateNo(int branchId) 
	{
		int count=1;
		ArrayList<UserInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq = "select * from master_setting";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			
			while(rr.next())
			{
				UserInfo uu=new UserInfo();
				
				uu.setSno(count++);
				uu.setAccType(rr.getString("account_type"));
				uu.setAccInitial(rr.getString("account_initial"));
				uu.setAccLength(rr.getInt("account_length"));
				uu.setId(rr.getString("id"));
				uu.setDisable(checkDisableForAccountNoGenerate(branchId,uu.getAccType(), conn));
				uu.setBrCode(branchCodeByBranchId(branchId, conn));
				list.add(uu);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}

	public String branchCodeByBranchId(int branchId, Connection conn)
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select branch_code from firm_detail where id='"+branchId+"'";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("branch_code");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return "";
	}


	private boolean checkDisableForAccountNoGenerate(int branchId,String accType, Connection conn) 
	{
		try
		{
			String qq="";
			Statement st=conn.createStatement();
			if(accType.equals("Share Holder"))
			{
				qq="select * from shareholder_info ";
			}
			else if(accType.equals("DD") || accType.equals("RD") || accType.equals("FD") || accType.equals("MIS"))
			{
				qq="select * from customer_info ";
			}
			else if(accType.equals("Saving"))
			{
				qq="select * from savingaccount ";
			}
			else if(accType.equals("DSA"))
			{
				qq="select * from dsa ";
			}
			else if(accType.equals("Personal Loan") || accType.equals("personalloan"))
			{
				qq="select * from personalloan ";
			}
			else if(accType.equals("Group Loan") || accType.equals("grouploan"))
			{
				qq="select * from grouploan ";
			}
			else if(accType.equals("Business Loan") || accType.equals("business_loan"))
			{
				qq="select * from business_loan ";
			}
			else if(accType.equals("Secure Loan") || accType.equals("secure_loan"))
			{
				qq="select * from secure_loan ";
			}
			else
			{
				return true;
			}
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return false;
	}

	public int updtaeBasicSettingForAutoGenerateNo(int branchId,UserInfo selectedRow) 
	{
		String accIni = selectedRow.getAccInitial();
//		if(selectedRow.getBrCode().equals("0"))
//		{
//			 accIni = selectedRow.getAccInitial();
//		}
//		else
//		{
//			 accIni = selectedRow.getAccInitial()+selectedRow.getBrCode();
//		}
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update master_setting set account_initial='"+accIni+"', account_length='"+selectedRow.getAccLength()+"' where id='"+selectedRow.getId()+"' ";
			int i=st.executeUpdate(selectQueWithBranch(qq,branchId));
			return i;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}
	public ArrayList<String> permissionOfUser(int branchId,String userType,Connection conn)
	{
		ResultSet rr=null;
		Statement st=null;
		ArrayList<String> list=new ArrayList<String>();
		try
		{
			st=conn.createStatement();
			String query="select permission from user_permission where user_type='"+userType+"'";
			 rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
					list.add(rr.getString("permission"));
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally 
        {
            try 
            {
            	if(st!=null)
            	{
            		  st.close();
                }
            	if(rr!=null)
            	{
            	     rr.close();
                }
            } 
            catch (Exception s) 
            {
                fileCreation(s.getMessage());
            }
        }
		return list;
	}
	
	
	public ArrayList<String> permissionOfUserForFilter(int branchId,String userType,Connection conn)
	{
		ResultSet rr=null;
		Statement st=null;
		ArrayList<String> list=new ArrayList<String>();
		try
		{
			st=conn.createStatement();
			String query="select permission from user_permission where user_type='"+userType+"'";
			 rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
					list.add(rr.getString("permission")+".xhtml");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally 
        {
            try 
            {
            	if(st!=null)
            	{
            		  st.close();
                }
            	if(rr!=null)
            	{
            	     rr.close();
                }
            } 
            catch (Exception s) 
            {
                fileCreation(s.getMessage());
            }
        }
		return list;
	}
	
	public ArrayList<SelectItem> allPageList()
	{
		ArrayList<SelectItem> list=new ArrayList<>();
		
		
		SelectItem ll=new SelectItem();
		ll.setLabel("Add Income Expense Category");
		ll.setValue("add_Income_ExpenseCategory");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("ALL");
		ll.setValue("All");
		list.add(ll);

		ll=new SelectItem();
		ll.setLabel("Current Deposit Status Report");
		ll.setValue("currentDepositReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Matured DD/RD/FD");
		ll.setValue("maturedRD");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Saving Account Income Expense Report");
		ll.setValue("savingAccountIncomeExpenseReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Nidhi TrialBalance");
		ll.setValue("nidhiTrialBalance");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Saving Account Report");
		ll.setValue("savingAccountReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Pending Transaction");
		ll.setValue("pendingTransaction");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Daily Collection Report");
		ll.setValue("dailyCollectionReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Dsa Wise Collection Report");
		ll.setValue("dsaWiseCollectionReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Deposit Report");
		ll.setValue("depositsReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("DSA Wise Commission Report");
		ll.setValue("dsaWiseCommissionReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Dsa Ledger Report");
		ll.setValue("dsaLedger");
		list.add(ll);
		ll=new SelectItem();
		ll.setLabel("view / Edit / Delete Promotors");
		ll.setValue("viewEditDeletePromotors");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("view / Edit / Delete Promotors Return");
		ll.setValue("viewDeletePromotorsCapital");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("shareHolder Registration");
		ll.setValue("shareHolderRegistration");
		list.add(ll);
		
		
		ll=new SelectItem();
		ll.setLabel("Saving A/C Deposit");
		ll.setValue("userDeposit");
		list.add(ll);
		
		
		ll=new SelectItem();
		ll.setLabel("Saving A/C Withdrawl");
		ll.setValue("userWithdrawl");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Add Account Head");
		ll.setValue("addAccountHead");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Add Bank Name");
		ll.setValue("addBankName");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Add Bank");
		ll.setValue("addBank");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Add Center");
		ll.setValue("addCenter");
		list.add(ll);
		
		
		
		ll=new SelectItem();
		ll.setLabel("Add Credit Current Asset Bank");
		ll.setValue("addCreditCurrentAssetBank");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Add Debit Current Asset Bank");
		ll.setValue("addDebitCurrentAssetBank");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Add DSA");
		ll.setValue("addDsa");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Add DSA Commision");
		ll.setValue("addDsaCommision");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Add Employee");
		ll.setValue("addEmployee");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Add Expense");
		ll.setValue("addExpense");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("add Income");
		ll.setValue("addIncome");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Add Shares Of Company");
		ll.setValue("addNoOfSharesOfCompany");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Add Plan");
		ll.setValue("addPlan");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Add Promotor");
		ll.setValue("addPromotors");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Add Promotors Capital");
		ll.setValue("addPromotorsCapital");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("All App Active");
		ll.setValue("allAppActiveUser");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("All Due EMI Report");
		ll.setValue("allDueEmiReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Balance Sheet");
		ll.setValue("balanceSheet");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Calculate Particular Date Maturity Value");
		ll.setValue("calculateParticularDateMaturityValue");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("CashBook Double Column");
		ll.setValue("cashBookDoubleColumn");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Cash Flow Report");
		ll.setValue("cashFlowReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Cash IN Out Flow");
		ll.setValue("cashInOutFlow");
		list.add(ll);
		
		
		ll=new SelectItem();
		ll.setLabel("Check Loan Request");
		ll.setValue("checkLoanRequest");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("View Loan EMI");
		ll.setValue("viewLoanEmi");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Center Wise Loan Report");
		ll.setValue("centerWiseLoanReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Change Password");
		ll.setValue("changePassword");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Check Liablities");
		ll.setValue("checkLiablities");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Cheque Bounce Report");
		ll.setValue("chequeBounceReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Collection Analysis");
		ll.setValue("collectionAnalysis");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Complete Loan Report");
		ll.setValue("completeLoanReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Curren Deposit Mentor");
		ll.setValue("currentDepositMentor");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Current Loan Report");
		ll.setValue("currentLoanReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Daily Collection Report");
		ll.setValue("dailyCollection");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("DD Report");
		ll.setValue("ddReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Debit Loan");
		ll.setValue("debitLoan");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Delete Reports");
		ll.setValue("deleteReports");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Deposit Report");
		ll.setValue("depositsReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Depreciation");
		ll.setValue("depreciation");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Depreciation Report");
		ll.setValue("depreciationReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Direct Bank deposit");
		ll.setValue("directBankDeposit");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("DSA Wise Collection Report");
		ll.setValue("dsaWisecollectionReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("DSA Wise Commision Report");
		ll.setValue("dsaWiseCommisionReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Due Cheque Debit");
		ll.setValue("dueChequeDebit");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Due Rd Report");
		ll.setValue("dueRDReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("View Edit Delete Bank");
		ll.setValue("editViewDeleteBank");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("View/Edit/Delete Center");
		ll.setValue("editViewDeleteCenter");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("View/Edit/Delete Pay Loan EMI");
		ll.setValue("editViewDeleteLoanEmiPaymentReceipt");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("View/Edit/Delete DD/RD/FD Receipt");
		ll.setValue("editViewDeletePaymentReceipt");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("View/Edit/Delete/Plan");
		ll.setValue("editViewDeletePlan");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("View/Edit/Delete Saving Account");
		ll.setValue("editViewDeleteSavingAccount");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("View/Edit/Delete ShareHolder");
		ll.setValue("editViewDeleteShareHolder");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("View/Edit/Delete GroupLoan");
		ll.setValue("editViewGroupLoan");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("View/Edit/Delete Personal Loan");
		ll.setValue("editViewPersonalLoan");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Employee Monthly Deduction Report");
		ll.setValue("employeeMonthlyDeductionReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Employee Salary Ledger");
		ll.setValue("employeeSalaryLedger");
		list.add(ll);

		ll=new SelectItem();
		ll.setLabel("Employee Salary Payout");
		ll.setValue("employeeSalaryPayout");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("File Charge Report");
		ll.setValue("fileChargeReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Fixed Asset Sale");
		ll.setValue("fixedAssetSale");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Fixed Assest Report");
		ll.setValue("fixedAssetsReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("fixed Asset Sale Report");
		ll.setValue("fixedAssetsSaleReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Group Loan");
		ll.setValue("groupLoan");
		list.add(ll);

		ll=new SelectItem();
		ll.setLabel("ID / Address /Proff Report");
		ll.setValue("idAddressProffReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Income/Expense Ledger");
		ll.setValue("incomeExpenseLedger");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("All Alloted Assignment Report");
		ll.setValue("incomeExpenseReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("instant Borrow");
		ll.setValue("instantBorrow");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("instant Borrow Report");
		ll.setValue("instantBorrowReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("instant Loan");
		ll.setValue("instantLoan");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Instant Loan report");
		ll.setValue("instantLoanReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("loan Closer");
		ll.setValue("loanCloser");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("loan Payment Release Report");
		ll.setValue("loanPaymentReleaseReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("loan Payment Report");
		ll.setValue("loanPaymentReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("loan Report");
		ll.setValue("loanReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("loan Report Particular");
		ll.setValue("loanReportParticular");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Monthly Attendance Report");
		ll.setValue("monthAttendReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("loan Summary Report");
		ll.setValue("loanSummaryReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("matured RD_FD_Report");
		ll.setValue("maturedRD_FD_Report");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("members Outstanding Report");
		ll.setValue("membersOutstandingReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("mini Statement");
		ll.setValue("miniStatement");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("od Loan");
		ll.setValue("odLoan");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("od Loan Report");
		ll.setValue("odLoanReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("od Loan Return");
		ll.setValue("odLoanReturn");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("pay Loan EMI");
		ll.setValue("payLoanEMI");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("pay DD/RD/FD EMI");
		ll.setValue("paymentReceipt");
		list.add(ll);
		

		ll=new SelectItem();
		ll.setLabel("pay Multiple DD/RD/FD Emi");
		ll.setValue("payMultipleDDEmi");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("pay Multiple Loan Emi");
		ll.setValue("payMultipleLoanEmi");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("penalty Report");
		ll.setValue("penaltyReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("pending Loan Disburse List");
		ll.setValue("pendingLoanDisburseList");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("pay Multiple Loan Emi");
		ll.setValue("payMultipleLoanEmi");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("personal Loan");
		ll.setValue("personalLoan");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("prematurity Statement");
		ll.setValue("prematurityStatement");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("profit And Loss Account");
		ll.setValue("profitAndLossAccount");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("Property Loan");
		ll.setValue("PropertyLoan");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("rd_fd_Report Particular");
		ll.setValue("rd_fd_ReportParticular");
		list.add(ll);
		
		
		ll=new SelectItem();
		ll.setLabel("rd_fd Receipt");
		ll.setValue("rd_fdReceipt");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("rd Fd Income Expense Report");
		ll.setValue("rdFdIncomeExpenseReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("rd_fd_Report Particular");
		ll.setValue("rd_fd_ReportParticular");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("rdFd Report");
		ll.setValue("rdFdReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("rdFd Saving Urgent Report");
		ll.setValue("rdFdSavingUrgentReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("report For ROC");
		ll.setValue("reportForROC");
		list.add(ll);
		
		

		ll=new SelectItem();
		ll.setLabel("return DSA Comm");
		ll.setValue("returnDSAComm");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("return Instant Borrow");
		ll.setValue("returnInstantBorrow");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("return Instant Loan");
		ll.setValue("returnInstantLoan");
		list.add(ll);
		
		
		
		ll=new SelectItem();
		ll.setLabel("return Instant Loan");
		ll.setValue("returnInstantLoan");
		list.add(ll);
		
		
		
		ll=new SelectItem();
		ll.setLabel("return Matured Amount");
		ll.setValue("returnMaturedAmount");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("salary Formation");
		ll.setValue("salaryFormation");
		list.add(ll);
		

		ll=new SelectItem();
		ll.setLabel("saving Account");
		ll.setValue("savingAccount");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("send Message");
		ll.setValue("sendMessage");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("send Message Report");
		ll.setValue("sendMessageReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("share Holder Report");
		ll.setValue("shareHolderReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("share Return Report");
		ll.setValue("shareReturnReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("share Transfer Report");
		ll.setValue("shareTransferReport");
		list.add(ll);
		
		

		ll=new SelectItem();
		ll.setLabel("tds Report");
		ll.setValue("tdsReport");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("upcoming Emi Report");
		ll.setValue("upcomingEmiOfAll");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("update Emi Penalty");
		ll.setValue("updateEmiPenalty");
		list.add(ll);
		
		
		
		
		
		ll=new SelectItem();
		ll.setLabel("user Registration");
		ll.setValue("userRegistration");
		list.add(ll);
		
		
		
		ll=new SelectItem();
		ll.setLabel("view / Delete Fixed Deposit Expense");
		ll.setValue("viewDeleteFixedDepositExpense");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("view Delete Fixed Deposit Income");
		ll.setValue("viewDeleteFixedDepositIncome");
		list.add(ll);
		
		
		ll=new SelectItem();
		ll.setLabel("View / Delete Bank Transaction");
		ll.setValue("viewDeleteBankCompanyTransaction");
		list.add(ll);
		
		
		
		ll=new SelectItem();
		ll.setLabel("view /Edit / Delete Expense");
		ll.setValue("viewEditDeleteExpense");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("view /Edit / Delete Income");
		ll.setValue("viewEditDeleteIncome");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("view/Delete/InstantBorrow");
		ll.setValue("viewDeleteInstantBorrow");
		list.add(ll);
		
		
		ll=new SelectItem();
		ll.setLabel("view/Delete/Instant Loan");
		ll.setValue("viewDeleteInstantLoan");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("view Delete Of OdLoan");
		ll.setValue("viewDeleteOfOdLoan");
		list.add(ll);
		
		
		ll=new SelectItem();
		ll.setLabel("view/Edit/Delete/Expense");
		ll.setValue("viewDeleteInstantBorrow");
		list.add(ll);
		
		
		ll=new SelectItem();
		ll.setLabel("Edit/View/Delete Bank");
		ll.setValue("editViewDeleteBank");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("edit/View/DeleteEmployee");
		ll.setValue("editViewDeleteEmployee");
		list.add(ll);
		
	
		ll=new SelectItem();
		ll.setLabel("edit/View/DeletePlan");
		ll.setValue("editViewDeletePlan");
		list.add(ll);
		
		ll=new SelectItem();
		ll.setLabel("edit/View/Delete SavingAccount");
		ll.setValue("editViewDeleteSavingAccount");
		list.add(ll);
		
		
		
		ll=new SelectItem();
		ll.setLabel("edit/View/DeletePlan");
		ll.setValue("editViewDeletePlan");
		list.add(ll);
		
	
		
		ll=new SelectItem();
		ll.setLabel("edit/View/Delete User");
		ll.setValue("editViewDeleteUser");
		list.add(ll);
		return list;
	}
	
	
	
	public ArrayList<SelectItem> userTypeList(int branchId,Connection conn)
	{
		ArrayList<SelectItem> userTypeList=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;

		
		try
		{
			st=conn.createStatement();
			String query="select type from login group by type";
			rr=st.executeQuery(selectQueWithBranch(query,branchId));
			while(rr.next())
			{
				SelectItem info=new SelectItem();
				info.setValue(rr.getString("type"));
				info.setLabel(rr.getString("type"));
				userTypeList.add(info);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	
		return userTypeList;
	}
	
	public int addPermission(int branchId,String userType, ArrayList<String> selectedValue, ArrayList<SelectItem> pageList, Connection conn) 
	{
		
		
		int i=0;String permission="",innerPermission="";
		Statement st=null;
		ResultSet rr=null;
		String query="";
		String aa="";
		try
		{
			st=conn.createStatement();
			for(String ll :selectedValue)
			{
				if(ll.equalsIgnoreCase("All"))
				{
					for(SelectItem kk : pageList)
					{
						query="insert into user_permission (user_type,permission,branch_id) values('"+userType+"','"+kk.getValue()+"','"+branchId+"')";
						i=st.executeUpdate(query);
					}
				}
				else
				{
						query="insert into user_permission (user_type,permission,branch_id) values('"+userType+"','"+ll+"','"+branchId+"')";
						i=st.executeUpdate(query);
				}
				
			
			if(i>0)
			{
				dataInsertInQueryTable(query, conn);
			}
			}
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally 
        {
            try 
            {
                // Close the writer regardless of what happens...
            	if(st!=null)
            	{
            		  st.close();
                }
            	if(rr!=null)
            	{
            	     rr.close();
                }
            } 
            catch (Exception s) 
            {
                fileCreation(s.getMessage());
            }
        }
		return i;
	}
	
	
//	public int updatePermission(int branchId,String userType, ArrayList<String> selectedValue, ArrayList<SelectItem> pageList, int count, Connection conn) 
//	{
//		int i=0;String permission="",innerPermission="";
//		Statement st=null;
//		ResultSet rr=null;
//		String query="";
//		String aa="";
//		if(count==1)
//		{
//		    deletePermission(userType);
//		}
//		try
//		{
//			st=conn.createStatement();
//			for(String ll :selectedValue)
//			{
//				if(ll.equalsIgnoreCase("All"))
//				{
//					for(SelectItem kk : pageList)
//					{
//						query="insert into user_permission (user_type,permission,branch_id) values('"+userType+"','"+kk.getValue()+"','"+branchId+"')";
//						i=st.executeUpdate(query);
//					}
//				}
//				else
//				{
//						query="insert into user_permission (user_type,permission,branch_id) values('"+userType+"','"+ll+"','"+branchId+"')";
//						i=st.executeUpdate(query);
//				}
//			if(i>0)
//			{
//				dataInsertInQueryTable(query, conn);
//			}
//			}
//			
//		}
//		catch(Exception e)
//		{
//			e.printStackTrace();
//		}
//		finally 
//        {
//            try 
//            {
//                // Close the writer regardless of what happens...
//            	if(st!=null)
//            	{
//            		  st.close();
//                }
//            	if(rr!=null)
//            	{
//            	     rr.close();
//                }
//            } 
//            catch (Exception s) 
//            {
//                fileCreation(s.getMessage());
//            }
//        }
//		return i;
//	}
	
	
	
//	public int deletePermission(String type) 
//	{
//		try(Connection conn=DataBaseConnection.JAVAConnection();) 
//		{
//	         Statement stt=conn.createStatement();
//		     String query="delete from user_permission where user_type='"+type+"' ";
//		     int i=stt.executeUpdate(selectQueWithBranch(query,branchId));
//		     if(i>0)
//		     {
//		    	 dataInsertInQueryTable(query, conn);
//		    	 return 1;
//		     }
//		     
//		} 
//		catch (Exception e) 
//		{
//			 e.printStackTrace();fileCreation(e.getMessage());
//		}
//
//		return 0;
//	}


public ArrayList<LoanInfo> personalCloseLoanList(int branchId,Connection con) 
{
	
	int count=1;
	ArrayList<LoanInfo> list=new ArrayList<>();
	String query="select * from personalloan INNER JOIN shareholder_info on personalloan.shareholderno=shareholder_info.shareholderno where loanNo IN (select loanNo from personalloan INNER JOIN add_loan_closer on personalloan.loanNo=add_loan_closer.loan_no)";
	
	try(Connection conn=DataBaseConnection.JAVAConnection();) 
	{
		Statement stt=conn.createStatement();
		ResultSet ss=stt.executeQuery(selectQueWithBranch(query,branchId));
		while(ss.next())
		{
			if(!ss.getString("loanNo").contains("R"))
			{
				LoanInfo info=new LoanInfo();
				
				info.setSno(count++);
				info.setShareHolderNo(ss.getString("personalloan.shareholderno"));
				info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
				info.setContactNo(ss.getString("shareholder_info.mobile"));
				info.setId(ss.getString("personalloan.id"));
				info.setTerms(ss.getInt("terms"));
				info.setLoanAmount(ss.getString("loanAmount"));
				info.setLoanInterest(ss.getString("personalloan.interest"));
				info.setDiscount(ss.getInt("discount"));
				info.setLoanTerm(ss.getString("personalloan.terms"));
				info.setInstallAmount(ss.getDouble("personalloan.emi"));
				info.setLoanType("Personal Loan");
				info.setRequestDate(ss.getDate("requestDate"));
				info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
				info.setFirstGuarantor(ss.getString("firstguarantor")+" - "+firstApplicantNameBySHNo(ss.getString("firstguarantor"),conn));
				info.setSecondGuarantor(ss.getString("secondguarantor")+" - "+firstApplicantNameBySHNo(ss.getString("secondguarantor"),conn));
				info.setIdProof(ss.getString("idproof"));
				info.setLoanNo(ss.getString("loanNo"));
				if(ss.getString("fileCharge").trim().equals(""))
				{
					info.setFileCharge("0");
				}
				else
				{
					info.setFileCharge(ss.getString("fileCharge"));
				}
				info.setReason(ss.getString("reason"));
				info.setRd_fdNo(ss.getString("RD_FD_no"));
				info.setFrequency(String.valueOf(ss.getInt("frequency")));

				if(ss.getDate("approvalDate")!=null)
				{
					info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
					info.setEmiPaidDate(ss.getDate("approvalDate"));
				}
				
				
				if(ss.getDate("emi_due_date")!=null)
				{
					info.setEmiPaidDate(ss.getDate("emi_due_date"));
				}
				info.setStatus(ss.getString("status"));
				info.setAppChqNo(ss.getString("personalloan.app_chq_no"));
				info.setAppAccNo(ss.getString("personalloan.app_acc_no"));
				info.setAppBankName(ss.getString("personalloan.app_bank_name"));
				info.setAppBankBranch(ss.getString("personalloan.app_bank_branch"));
				
				info.setG1ChqNo(ss.getString("personalloan.g1_chq_no"));
				info.setG1AccNo(ss.getString("personalloan.g1_acc_no"));
				info.setG1BankName(ss.getString("personalloan.g1_bank_name"));
				info.setG1BankBranch(ss.getString("personalloan.g1_bank_branch"));
				
				info.setG2ChqNo(ss.getString("personalloan.g2_chq_no"));
				info.setG2AccNo(ss.getString("personalloan.g2_acc_no"));
				info.setG2BankName(ss.getString("personalloan.g2_bank_name"));
				info.setG2BankBranch(ss.getString("personalloan.g2_bank_branch"));
				info.setDsacode(ss.getString("dsacode"));
				info.setCommission(ss.getDouble("commission"));
				info.setEmiType(ss.getString("emiType"));
				if(ss.getString("insurance_fee").trim().equals(""))
				{
					info.setInsuranceFee("0");
				}
				else
				{
					info.setInsuranceFee(ss.getString("insurance_fee"));
				}
				
			//	info.setCenter(ss.getString("center"));
				info.setCenterName(centerNameById(ss.getString("center"),conn));
				
				list.add(info);
			}
			
		}
		
	}
	catch (Exception e) 
	{
		 e.printStackTrace();
	}
	
	return list;
}


public ArrayList<LoanInfo> personalActiveLoanList(int branchId,Connection con) 
{
	
	int count=1;
	ArrayList<LoanInfo> list=new ArrayList<>();
	String query="select * from personalloan INNER JOIN shareholder_info on personalloan.shareholderno=shareholder_info.shareholderno where loanNo NOT IN (select loanNo from personalloan INNER JOIN add_loan_closer on personalloan.loanNo=add_loan_closer.loan_no)";
	try(Connection conn=DataBaseConnection.JAVAConnection();) 
	{
		Statement stt=conn.createStatement();
		ResultSet ss=stt.executeQuery(selectQueWithBranch(query,branchId));
		while(ss.next())
		{
			if(!ss.getString("loanNo").contains("R"))
			{
				LoanInfo info=new LoanInfo();
				
				info.setSno(count++);
				info.setShareHolderNo(ss.getString("personalloan.shareholderno"));
				info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
				info.setContactNo(ss.getString("shareholder_info.mobile"));
				info.setId(ss.getString("personalloan.id"));
				info.setTerms(ss.getInt("terms"));
				info.setLoanAmount(ss.getString("loanAmount"));
				info.setLoanInterest(String.valueOf(Double.parseDouble(df.format(Double.valueOf(ss.getString("personalloan.interest"))))));
				info.setDiscount(ss.getInt("discount"));
				info.setLoanTerm(ss.getString("personalloan.terms"));
				info.setInstallAmount(ss.getDouble("personalloan.emi"));
				info.setLoanType("Personal Loan");
				info.setRequestDate(ss.getDate("requestDate"));
				info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
				info.setFirstGuarantor(ss.getString("firstguarantor")+" - "+firstApplicantNameBySHNo(ss.getString("firstguarantor"),conn));
				info.setSecondGuarantor(ss.getString("secondguarantor")+" - "+firstApplicantNameBySHNo(ss.getString("secondguarantor"),conn));
				info.setIdProof(ss.getString("idproof"));
				info.setLoanNo(ss.getString("loanNo"));
				if(ss.getString("fileCharge").trim().equals(""))
				{
					info.setFileCharge("0");
				}
				else
				{
					info.setFileCharge(ss.getString("fileCharge"));
				}
				info.setReason(ss.getString("reason"));
				info.setRd_fdNo(ss.getString("RD_FD_no"));
				info.setFrequency(String.valueOf(ss.getInt("frequency")));

				if(ss.getDate("approvalDate")!=null)
				{
					info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
					info.setEmiPaidDate(ss.getDate("approvalDate"));
				}
				
				
				if(ss.getDate("emi_due_date")!=null)
				{
					info.setEmiPaidDate(ss.getDate("emi_due_date"));
				}
				info.setStatus(ss.getString("status"));
				info.setAppChqNo(ss.getString("personalloan.app_chq_no"));
				info.setAppAccNo(ss.getString("personalloan.app_acc_no"));
				info.setAppBankName(ss.getString("personalloan.app_bank_name"));
				info.setAppBankBranch(ss.getString("personalloan.app_bank_branch"));
				
				info.setG1ChqNo(ss.getString("personalloan.g1_chq_no"));
				info.setG1AccNo(ss.getString("personalloan.g1_acc_no"));
				info.setG1BankName(ss.getString("personalloan.g1_bank_name"));
				info.setG1BankBranch(ss.getString("personalloan.g1_bank_branch"));
				
				info.setG2ChqNo(ss.getString("personalloan.g2_chq_no"));
				info.setG2AccNo(ss.getString("personalloan.g2_acc_no"));
				info.setG2BankName(ss.getString("personalloan.g2_bank_name"));
				info.setG2BankBranch(ss.getString("personalloan.g2_bank_branch"));
				info.setDsacode(ss.getString("dsacode"));
				info.setCommission(ss.getDouble("commission"));
				info.setEmiType(ss.getString("emiType"));
				if(ss.getString("insurance_fee").trim().equals(""))
				{
					info.setInsuranceFee("0");
				}
				else
				{
					info.setInsuranceFee(ss.getString("insurance_fee"));
				}
				
			//	info.setCenter(ss.getString("center"));
				info.setCenterName(centerNameById(ss.getString("center"),conn));
				
				list.add(info);
			}
			
		}
		
	}
	catch (Exception e) 
	{
		 e.printStackTrace();
	}
	
	return list;
}



public String totalshareholder(int branchId,Connection con)
{

	Statement st= null;
	ResultSet rs=null;
	try 
	{
         st=con.createStatement();
	     String query="select count(id) from shareholder_info";
	     rs=st.executeQuery(selectQueWithBranch(query,branchId));
	     if(rs.next())
	     {
		     return rs.getString("count(id)");
	     }
	} 
	catch (Exception e) 
	{
		 e.printStackTrace();
	}

	finally 
    {
        try 
        {
        	if(st!=null)
        	{
        		  st.close();
            }
        	if(rs!=null)
        	{
        	     rs.close();
            }
        } 
        catch (Exception s) 
        {
           
        }
    }
	
	return "0";

}

public String totalSavingAccount(int branchId,Connection con) 
{
	Statement st= null;
	ResultSet rs=null;
	try 
	{
         st=con.createStatement();
	     String query="select count(id) from savingaccount";
	     rs=st.executeQuery(selectQueWithBranch(query,branchId));
	     if(rs.next())
	     {
		     return rs.getString("count(id)");
	     }
	} 
	catch (Exception e) 
	{
		 e.printStackTrace();
	}

	finally 
    {
        try 
        {
        	if(st!=null)
        	{
        		  st.close();
            }
        	if(rs!=null)
        	{
        	     rs.close();
            }
        } 
        catch (Exception s) 
        {
           
        }
    }
	
	return "0";

}

public String totalScheme(int branchId,Connection con) 
{
	Statement st= null;
	ResultSet rs=null;
	String total="";
	int dd=0,fd=0,rd=0;
	try 
	{
         st=con.createStatement();
	     String query="select id,scheme_type from customer_info";
	     rs=st.executeQuery(selectQueWithBranch(query,branchId));
	     while(rs.next())
	     {
		     if(rs.getString("scheme_type").equals("FD"))
		     {
		    	 fd=fd+1;
		     }
		     else if(rs.getString("scheme_type").equals("DD"))
		     {
		    	 dd=dd+1;
		     }
		     else if(rs.getString("scheme_type").equals("RD"))
		     {
		    	 rd=rd+1;
		     }
	     }
	     total=String.valueOf(fd)+"/"+String.valueOf(dd)+"/"+String.valueOf(rd);
	     return total;
	} 
	catch (Exception e) 
	{
		 e.printStackTrace();
	}

	finally 
    {
        try 
        {
        	if(st!=null)
        	{
        		  st.close();
            }
        	if(rs!=null)
        	{
        	     rs.close();
            }
        	
        } 
        catch (Exception s) 
        {
           
        }
    }
	
	return "0";

}

public String totalDD(int branchId,String schemeType, Connection con) 
{
	Date dt= new Date();
	Statement st= null;
	ResultSet rs=null;
	String total="";
	int ad=0,cd=0,md=0;
	 Timestamp tsDt = new Timestamp(dt.getTime());
	try 
	{
         st=con.createStatement();
	     String query="select id,account_status,paid_status,maturity_date from customer_info where scheme_type='"+schemeType+"' ";
	     rs=st.executeQuery(selectQueWithBranch(query,branchId));
	     while(rs.next())
	     {
	    	 /*if(rs.getString("account_status").equals("active") && rs.getString("paid_status").equals("unpaid"))
		     {
	    		 if(rs.getDate("maturity_date").before(tsDt) || rs.getDate("maturity_date").equals(tsDt))
	    		 {
	    			 md=md+1;
	    		 }
	    		 else
	    		 {
	    			 ad=ad+1;
	    		 }
		     }
	    	 
	    	 else if(rs.getString("account_status").equals("close") && rs.getString("paid_status").equals("unpaid"))
		     {
		    	 md=md+1;
		     }
		    
		     else if(rs.getString("account_status").equals("inactive") && rs.getString("paid_status").equals("paid"))
		     {
		    	 cd=cd+1;
		     }*/
		   
	    	 if(rs.getString("account_status").equalsIgnoreCase("active"))
	    	 {
	    		 ad=ad+1;
	    	 }
	    	 else  if(rs.getString("account_status").equalsIgnoreCase("close"))
	    	 {
	    		 cd=cd+1;
	    	 }
	    	 else
	    	 {
	    		 md=md+1;
	    	 }
	     }
	     total=String.valueOf(ad)+"/"+String.valueOf(md)+"/"+String.valueOf(cd);
	     return total;
	} 
	catch (Exception e) 
	{
		 e.printStackTrace();
	}

	finally 
    {
        try 
        {
        	if(st!=null)
        	{
        		  st.close();
            }
        	if(rs!=null)
        	{
        	     rs.close();
            }
        	
        } 
        catch (Exception s) 
        {
           
        }
    }
	
	return "0";

}

public String totalPlan(int branchId,Connection con)
{
	Statement st= null;
	ResultSet rs=null;
	try 
	{
         st=con.createStatement();
	     String query="select count(idplans) from plans";
	     rs=st.executeQuery(selectQueWithBranch(query,branchId));
	     if(rs.next())
	     {
		    
		   return rs.getString("count(idplans)");
	     }
	    
	} 
	catch (Exception e) 
	{
		 e.printStackTrace();
	}

	finally 
    {
        try 
        {
        	if(st!=null)
        	{
        		  st.close();
            }
        	if(rs!=null)
        	{
        	     rs.close();
            }
        } 
        catch (Exception s) 
        {
           
        }
    }
	
	return "0";

}

public String totalbank(Connection con) 
{
	Statement st= null;
	ResultSet rs=null;
	try 
	{
         st=con.createStatement();
	     String query="select count(id) from bank_table";
	     rs=st.executeQuery(query);
	     if(rs.next())
	     {
		    
		   return rs.getString("count(id)");
	     }
	    
	} 
	catch (Exception e) 
	{
		 e.printStackTrace();
	}

	finally 
    {
        try 
        {
        	if(st!=null)
        	{
        		  st.close();
            }
        	if(rs!=null)
        	{
        	     rs.close();
            }
        } 
        catch (Exception s) 
        {
           
        }
    }
	
	return "0";

}

public ArrayList<LoanInfo> personalPendingLoanList(int branchId,Connection con)
{
	
	int count=1;
	ArrayList<LoanInfo> list=new ArrayList<>();
	String query="select * from personalloan INNER JOIN shareholder_info on personalloan.shareholderno=shareholder_info.shareholderno where personalloan.status='pending'";
	try 
	{
		Statement stt=con.createStatement();
		ResultSet ss=stt.executeQuery(selectQueWithBranch(query,branchId));
		while(ss.next())
		{
			if(!ss.getString("loanNo").contains("R"))
			{
				LoanInfo info=new LoanInfo();
				
				info.setSno(count++);
				info.setShareHolderNo(ss.getString("personalloan.shareholderno"));
				info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
				info.setContactNo(ss.getString("shareholder_info.mobile"));
				info.setId(ss.getString("personalloan.id"));
				info.setTerms(ss.getInt("terms"));
				info.setLoanAmount(ss.getString("loanAmount"));
				info.setLoanInterest(ss.getString("personalloan.interest"));
				info.setDiscount(ss.getInt("discount"));
				info.setLoanTerm(ss.getString("personalloan.terms"));
				info.setInstallAmount(ss.getDouble("personalloan.emi"));
				info.setLoanType("Personal Loan");
				info.setRequestDate(ss.getDate("requestDate"));
				info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
				info.setFirstGuarantor(ss.getString("firstguarantor")+" - "+firstApplicantNameBySHNo(ss.getString("firstguarantor"),con));
				info.setSecondGuarantor(ss.getString("secondguarantor")+" - "+firstApplicantNameBySHNo(ss.getString("secondguarantor"),con));
				info.setIdProof(ss.getString("idproof"));
				info.setLoanNo(ss.getString("loanNo"));
				if(ss.getString("fileCharge").trim().equals(""))
				{
					info.setFileCharge("0");
				}
				else
				{
					info.setFileCharge(ss.getString("fileCharge"));
				}
				info.setReason(ss.getString("reason"));
				info.setRd_fdNo(ss.getString("RD_FD_no"));
				info.setFrequency(String.valueOf(ss.getInt("frequency")));

				if(ss.getDate("approvalDate")!=null)
				{
					info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
					info.setEmiPaidDate(ss.getDate("approvalDate"));
				}
				
				
				if(ss.getDate("emi_due_date")!=null)
				{
					info.setEmiPaidDate(ss.getDate("emi_due_date"));
				}
				info.setStatus(ss.getString("status"));
				info.setAppChqNo(ss.getString("personalloan.app_chq_no"));
				info.setAppAccNo(ss.getString("personalloan.app_acc_no"));
				info.setAppBankName(ss.getString("personalloan.app_bank_name"));
				info.setAppBankBranch(ss.getString("personalloan.app_bank_branch"));
				
				info.setG1ChqNo(ss.getString("personalloan.g1_chq_no"));
				info.setG1AccNo(ss.getString("personalloan.g1_acc_no"));
				info.setG1BankName(ss.getString("personalloan.g1_bank_name"));
				info.setG1BankBranch(ss.getString("personalloan.g1_bank_branch"));
				
				info.setG2ChqNo(ss.getString("personalloan.g2_chq_no"));
				info.setG2AccNo(ss.getString("personalloan.g2_acc_no"));
				info.setG2BankName(ss.getString("personalloan.g2_bank_name"));
				info.setG2BankBranch(ss.getString("personalloan.g2_bank_branch"));
				info.setDsacode(ss.getString("dsacode"));
				info.setCommission(ss.getDouble("commission"));
				info.setEmiType(ss.getString("emiType"));
				if(ss.getString("insurance_fee").trim().equals(""))
				{
					info.setInsuranceFee("0");
				}
				else
				{
					info.setInsuranceFee(ss.getString("insurance_fee"));
				}
				
			//	info.setCenter(ss.getString("center"));
				info.setCenterName(centerNameById(ss.getString("center"),con));
				
				list.add(info);
			}
			
		}
		
	}
	catch (Exception e) 
	{
		 e.printStackTrace();
	}
	
	return list;
}

public String totalPendingLoan(int branchId,String string, Connection con)
{
	Statement st= null;
	ResultSet rs=null;
	try 
	{
         st=con.createStatement();
	     String query="select count(id) from "+string+"  where status='pending' ";
	     rs=st.executeQuery(selectQueWithBranch(query,branchId));
	     if(rs.next())
	     {
		    
		   return rs.getString("count(id)");
	     }
	    
	} 
	catch (Exception e) 
	{
		 e.printStackTrace();
	}

	finally 
    {
        try 
        {
        	if(st!=null)
        	{
        		  st.close();
            }
        	if(rs!=null)
        	{
        	     rs.close();
            }
        } 
        catch (Exception s) 
        {
           
        }
    }
	
	return "0";

}

public ArrayList<LoanInfo> groupActList(int branchId,Connection con)
{
	
	int count=1;
	ArrayList<LoanInfo> list=new ArrayList<>();
	Statement st=null;
	ResultSet ss=null;
	try 
	{
		st=con.createStatement();
		String query=" select * from grouploan INNER JOIN shareholder_info on grouploan.teamLeader=shareholder_info.shareholderno where sub_loan_no NOT IN (select sub_loan_no from grouploan INNER JOIN add_loan_closer on grouploan.sub_loan_no=add_loan_closer.loan_no)  order by grouploan.loanNo asc";
		
		ss=st.executeQuery(selectQueWithBranch(query,branchId));
		while(ss.next())
		{
			if(!ss.getString("loanNo").contains("R"))
			{
				LoanInfo info=new LoanInfo();
				info.setSno(count++);
				info.setShareHolderNo(ss.getString("grouploan.teamLeader"));
				info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
				info.setContactNo(ss.getString("shareholder_info.mobile"));
				info.setId(ss.getString("grouploan.id"));
				info.setLoanAmount(ss.getString("loanAmount"));
				info.setLoanInterest(ss.getString("grouploan.interest"));
				info.setLoanTerm(ss.getString("grouploan.terms"));
				info.setInstallAmount(ss.getDouble("grouploan.emi"));
				info.setLoanType("Group Loan");
				info.setDiscount(ss.getInt("discount"));
				info.setRequestDate(ss.getDate("requestDate"));
				info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
				info.setIdProof(ss.getString("idproof"));
				info.setTerms(ss.getInt("terms"));
				info.setLoanNo(ss.getString("loanNo")+" / "+ss.getString("sub_loan_no"));
					if(ss.getString("fileCharge").trim().equals(""))	
					{
						info.setFileCharge("0");
					}
					else
					{
				     info.setFileCharge(ss.getString("fileCharge"));
					}
				info.setCenter(ss.getString("center"));
				info.setMembers(ss.getString("members"));
				info.setRd_fdNo(ss.getString("RD_FD_no"));
				info.setFrequency(String.valueOf(ss.getInt("frequency")));

				if(ss.getDate("approvalDate")!=null)
				{
					info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
				}

                info.setStatus(ss.getString("status"));
				info.setAppChqNo(ss.getString("grouploan.app_chq_no"));
				info.setAppAccNo(ss.getString("grouploan.app_acc_no"));
				info.setAppBankName(ss.getString("grouploan.app_bank_name"));
				info.setAppBankBranch(ss.getString("grouploan.app_bank_branch"));
				
				info.setG1ChqNo(ss.getString("grouploan.g1_chq_no"));
				info.setG1AccNo(ss.getString("grouploan.g1_acc_no"));
				info.setG1BankName(ss.getString("grouploan.g1_bank_name"));
				info.setG1BankBranch(ss.getString("grouploan.g1_bank_branch"));
				
				info.setG2ChqNo(ss.getString("grouploan.g2_chq_no"));
				info.setG2AccNo(ss.getString("grouploan.g2_acc_no"));
				info.setG2BankName(ss.getString("grouploan.g2_bank_name"));
				info.setG2BankBranch(ss.getString("grouploan.g2_bank_branch"));

				info.setDsacode(ss.getString("dsacode"));
				info.setCommission(ss.getDouble("commission"));
				info.setEmiType(ss.getString("emiType"));
				if(ss.getString("insurance_fee").trim().equals(""))
				{
					info.setInsuranceFee("0");
				}
				else
				{
				info.setInsuranceFee(ss.getString("insurance_fee"));
				}
				
				
				
				list.add(info);
			}
			
		}
		
	}
	catch (Exception e) 
	{
		 e.printStackTrace();fileCreation(e.getMessage());
	}
	finally {
		try {
			if(st!=null)
			{
				st.close();
			}
			if(ss!=null)
			{
				ss.close();
			}
		} catch (Exception e2) {
			// TODO: handle exception
		}
	}
	
	
	return list;
}

public ArrayList<LoanInfo> groupCloseList(int branchId,Connection con)
{
	
	int count=1;
	ArrayList<LoanInfo> list=new ArrayList<>();
	Statement st=null;
	ResultSet ss=null;
	try 
	{
		st=con.createStatement();
		String query="select * from grouploan INNER JOIN shareholder_info on grouploan.teamLeader=shareholder_info.shareholderno where sub_loan_no  IN (select sub_loan_no from grouploan INNER JOIN add_loan_closer on grouploan.sub_loan_no=add_loan_closer.loan_no)  order by grouploan.loanNo asc";
		ss=st.executeQuery(selectQueWithBranch(query,branchId));
		while(ss.next())
		{
			if(!ss.getString("loanNo").contains("R"))
			{
				LoanInfo info=new LoanInfo();
				
				info.setSno(count++);
				info.setShareHolderNo(ss.getString("grouploan.teamLeader"));
				info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
				info.setContactNo(ss.getString("shareholder_info.mobile"));
				info.setId(ss.getString("grouploan.id"));
				info.setLoanAmount(ss.getString("loanAmount"));
				info.setLoanInterest(ss.getString("grouploan.interest"));
				info.setLoanTerm(ss.getString("grouploan.terms"));
				info.setInstallAmount(ss.getDouble("grouploan.emi"));
				info.setLoanType("Group Loan");
				info.setDiscount(ss.getInt("discount"));
				info.setRequestDate(ss.getDate("requestDate"));
				info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
				info.setIdProof(ss.getString("idproof"));
				info.setTerms(ss.getInt("terms"));
				info.setLoanNo(ss.getString("loanNo")+" / "+ss.getString("sub_loan_no"));
					if(ss.getString("fileCharge").trim().equals(""))	
					{
						info.setFileCharge("0");
					}
					else
					{
				     info.setFileCharge(ss.getString("fileCharge"));
					}
				info.setCenter(ss.getString("center"));
				info.setMembers(ss.getString("members"));
				info.setRd_fdNo(ss.getString("RD_FD_no"));
				info.setFrequency(String.valueOf(ss.getInt("frequency")));

				if(ss.getDate("approvalDate")!=null)
				{
					info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
				}

                info.setStatus(ss.getString("status"));
				info.setAppChqNo(ss.getString("grouploan.app_chq_no"));
				info.setAppAccNo(ss.getString("grouploan.app_acc_no"));
				info.setAppBankName(ss.getString("grouploan.app_bank_name"));
				info.setAppBankBranch(ss.getString("grouploan.app_bank_branch"));
				
				info.setG1ChqNo(ss.getString("grouploan.g1_chq_no"));
				info.setG1AccNo(ss.getString("grouploan.g1_acc_no"));
				info.setG1BankName(ss.getString("grouploan.g1_bank_name"));
				info.setG1BankBranch(ss.getString("grouploan.g1_bank_branch"));
				
				info.setG2ChqNo(ss.getString("grouploan.g2_chq_no"));
				info.setG2AccNo(ss.getString("grouploan.g2_acc_no"));
				info.setG2BankName(ss.getString("grouploan.g2_bank_name"));
				info.setG2BankBranch(ss.getString("grouploan.g2_bank_branch"));

				info.setDsacode(ss.getString("dsacode"));
				info.setCommission(ss.getDouble("commission"));
				info.setEmiType(ss.getString("emiType"));
				if(ss.getString("insurance_fee").trim().equals(""))
				{
					info.setInsuranceFee("0");
				}
				else
				{
				info.setInsuranceFee(ss.getString("insurance_fee"));
				}
				
				list.add(info);
			}
			
		}
		
	}
	catch (Exception e) 
	{
		 e.printStackTrace();fileCreation(e.getMessage());
	}
	finally {
		try {
			if(st!=null)
			{
				st.close();
			}
			if(ss!=null)
			{
				ss.close();
			}
		} catch (Exception e2) {
			// TODO: handle exception
		}
	return list;
}
}

public ArrayList<LoanInfo> groupPendingList(int branchId,Connection con)
{
	
	int count=1;
	ArrayList<LoanInfo> list=new ArrayList<>();
	Statement st=null;
	ResultSet ss=null;
	try 
	{
		st=con.createStatement();
		String query="select * from grouploan INNER JOIN shareholder_info on grouploan.teamLeader=shareholder_info.shareholderno where grouploan.status='pending'";
		ss=st.executeQuery(selectQueWithBranch(query,branchId));
		while(ss.next())
		{
			if(!ss.getString("loanNo").contains("R"))
			{
				LoanInfo info=new LoanInfo();
				
				info.setSno(count++);
				info.setShareHolderNo(ss.getString("grouploan.teamLeader"));
				info.setApplicantName(ss.getString("shareholder_info.first_applicantName"));
				info.setContactNo(ss.getString("shareholder_info.mobile"));
				info.setId(ss.getString("grouploan.id"));
				info.setLoanAmount(ss.getString("loanAmount"));
				info.setLoanInterest(ss.getString("grouploan.interest"));
				info.setLoanTerm(ss.getString("grouploan.terms"));
				info.setInstallAmount(ss.getDouble("grouploan.emi"));
				info.setLoanType("Group Loan");
				info.setDiscount(ss.getInt("discount"));
				info.setRequestDate(ss.getDate("requestDate"));
				info.setStrRequestDate(sf.format(ss.getDate("requestDate")));
				info.setIdProof(ss.getString("idproof"));
				info.setTerms(ss.getInt("terms"));
				info.setLoanNo(ss.getString("loanNo")+" / "+ss.getString("sub_loan_no"));
					if(ss.getString("fileCharge").trim().equals(""))	
					{
						info.setFileCharge("0");
					}
					else
					{
				     info.setFileCharge(ss.getString("fileCharge"));
					}
				info.setCenter(ss.getString("center"));
				info.setMembers(ss.getString("members"));
				info.setRd_fdNo(ss.getString("RD_FD_no"));
				info.setFrequency(String.valueOf(ss.getInt("frequency")));

				if(ss.getDate("approvalDate")!=null)
				{
					info.setStrApprovalDate(sf.format(ss.getDate("approvalDate")));
				}

                info.setStatus(ss.getString("status"));
				info.setAppChqNo(ss.getString("grouploan.app_chq_no"));
				info.setAppAccNo(ss.getString("grouploan.app_acc_no"));
				info.setAppBankName(ss.getString("grouploan.app_bank_name"));
				info.setAppBankBranch(ss.getString("grouploan.app_bank_branch"));
				
				info.setG1ChqNo(ss.getString("grouploan.g1_chq_no"));
				info.setG1AccNo(ss.getString("grouploan.g1_acc_no"));
				info.setG1BankName(ss.getString("grouploan.g1_bank_name"));
				info.setG1BankBranch(ss.getString("grouploan.g1_bank_branch"));
				
				info.setG2ChqNo(ss.getString("grouploan.g2_chq_no"));
				info.setG2AccNo(ss.getString("grouploan.g2_acc_no"));
				info.setG2BankName(ss.getString("grouploan.g2_bank_name"));
				info.setG2BankBranch(ss.getString("grouploan.g2_bank_branch"));

				info.setDsacode(ss.getString("dsacode"));
				info.setCommission(ss.getDouble("commission"));
				info.setEmiType(ss.getString("emiType"));
				if(ss.getString("insurance_fee").trim().equals(""))
				{
					info.setInsuranceFee("0");
				}
				else
				{
				info.setInsuranceFee(ss.getString("insurance_fee"));
				}
				
				list.add(info);
			}
			
		}
		
	}
	catch (Exception e) 
	{
		 e.printStackTrace();fileCreation(e.getMessage());
	}
	finally {
		try {
			if(st!=null)
			{
				st.close();
			}
			if(ss!=null)
			{
				ss.close();
			}
		} catch (Exception e2) {
			// TODO: handle exception
		}
	return list;
}
}


public ArrayList<UserInfo> showMatureScheme(int branchId,String searchType) 
{
	Date dt= new Date();
	ArrayList<UserInfo> list = new ArrayList<UserInfo>();
	 Timestamp tsDt = new Timestamp(dt.getTime());
	 SimpleDateFormat sdf = sdfForDb;
     String dd = sdf.format(tsDt.getTime());
     
	try (Connection con = DataBaseConnection.JAVAConnection();) 
	{
		int i=0;
		Statement st = con.createStatement();
		String qq = "select * from customer_info where maturity_date<='"+ dd+"' and paid_status='unpaid' and (account_status='active' or account_status='close') and scheme_type='"+searchType+"' order by maturity_date asc";
		ResultSet rs = st.executeQuery(selectQueWithBranch(qq,branchId));
		while (rs.next())
		{
			i=i+1;
			String hno=rs.getString("shareHolderNo");
			UserInfo uu = new UserInfo();
			uu=userInfoByShareHolderNo(hno,con);
			uu.setSno(i);
     		uu.setId(rs.getString("id"));
     		uu.setShareHolderNo(rs.getString("shareHolderNo"));
     		uu.setOffice_application_no(rs.getString("office_application_no"));
			uu.setOffice_date(rs.getDate("office_date"));
			uu.setStrOffcDate(sf.format(rs.getDate("office_date")));
			uu.setUser_no(rs.getString("user_no"));
			uu.setScheme_type(rs.getString("scheme_type"));
			uu.setPlan_no(rs.getString("plan_no"));
			uu.setTerms(rs.getInt("terms"));
			uu.setFrequency(rs.getInt("frequency"));
			uu.setApplicant_fees(rs.getDouble("applicant_fees"));
			uu.setInstallment_amount(rs.getDouble("installment_amount"));
			uu.setInterest(rs.getDouble("interest"));
			uu.setMaturity_value(rs.getDouble("maturity_value"));
			uu.setMaturity_date(rs.getDate("maturity_date"));
			uu.setStrMatDate(sf.format(rs.getDate("maturity_date")));
			list.add(uu);
		}
	}
	catch (Exception e) 
	{
		 e.printStackTrace();fileCreation(e.getMessage());
	}
	return list;
}

public ArrayList<UserInfo> showReturnScheme(int branchId,String searchType) 
{
	ArrayList<UserInfo> list = new ArrayList<UserInfo>();
     
	try (Connection con = DataBaseConnection.JAVAConnection();) 
	{
		int i=0;
		Statement st = con.createStatement();
		String qq = "select * from customer_info where  paid_status='paid' and account_status='inactive'  and scheme_type='"+searchType+"' order by maturity_date asc";
		ResultSet rs = st.executeQuery(selectQueWithBranch(qq,branchId));
		while (rs.next())
		{
			i=i+1;
			String hno=rs.getString("shareHolderNo");
			UserInfo uu = new UserInfo();
			uu=userInfoByShareHolderNo(hno, con);
			uu.setSno(i);
     		uu.setId(rs.getString("id"));
     		uu.setShareHolderNo(rs.getString("shareHolderNo"));
     		uu.setOffice_application_no(rs.getString("office_application_no"));
			uu.setOffice_date(rs.getDate("office_date"));
			uu.setStrOffcDate(sf.format(rs.getDate("office_date")));
			uu.setUser_no(rs.getString("user_no"));
			uu.setScheme_type(rs.getString("scheme_type"));
			uu.setPlan_no(rs.getString("plan_no"));
			uu.setTerms(rs.getInt("terms"));
			uu.setFrequency(rs.getInt("frequency"));
			uu.setApplicant_fees(rs.getDouble("applicant_fees"));
			uu.setInstallment_amount(rs.getDouble("installment_amount"));
			uu.setInterest(rs.getDouble("interest"));
			uu.setMaturity_value(rs.getDouble("maturity_value"));
			uu.setMaturity_date(rs.getDate("maturity_date"));
			uu.setStrMatDate(sf.format(rs.getDate("maturity_date")));
			list.add(uu);
		}
	}
	catch (Exception e) 
	{
		 e.printStackTrace();fileCreation(e.getMessage());
	}
	return list;
}

	public Boolean pagelistEmp(Connection con, String empType, String pageName)
	{
		Statement st = null;
		ResultSet rs = null;
		try {
			st = con.createStatement();
			String query = "select status from permission_table where page_name='" + pageName + "' and emp_id='"+ empType + "'";
			
			rs = st.executeQuery(query);
			if (rs.next()) 
			{
				return Boolean.valueOf(rs.getString("status"));
			} 
			else
			{
//				if (empType.equalsIgnoreCase("admin")) 
//				{
//					return true;
//				}
				return false;
			}

		} catch (Exception e) {
			e.printStackTrace();
			fileCreation(e.getMessage());
		}
		return false;
	}
	
	public Boolean pagelistEmpE(Connection con, String empType, String pageName)
	{
		Statement st = null;
		ResultSet rs = null;
		try {
			st = con.createStatement();
			
			String query = "select edit_status from permission_table where page_name='" + pageName + "' and emp_id='"+ empType + "'";
			rs = st.executeQuery(query);
			if (rs.next()) 
			{
				return Boolean.valueOf(rs.getString("edit_status"));
			} 
			else
			{
//				if (empType.equalsIgnoreCase("admin")) 
//				{
//					return true;
//				}
				return false;
			}

		} catch (Exception e) {
			e.printStackTrace();
			fileCreation(e.getMessage());
			fileCreation(e.getMessage());
		}
		return false;
	}

	public Boolean pagelistEmpD(Connection con, String empType, String pageName)
	{
		Statement st = null;
		ResultSet rs = null;
		try 
		{
			st = con.createStatement();
			
			String query = "select delete_status from permission_table where page_name='" + pageName + "' and emp_id='"+ empType + "'";
			rs = st.executeQuery(query);
			if (rs.next()) 
			{
				return Boolean.valueOf(rs.getString("delete_status"));
			} 
			else
			{
//				if (empType.equalsIgnoreCase("admin")) 
//				{
//					return true;
//				}
				return false;
			}

		} catch (Exception e) {
			e.printStackTrace();
			fileCreation(e.getMessage());
			fileCreation(e.getMessage());
		}
		return false;
	}
public ArrayList<SelectItem> allPageList(int branchId,Connection con) 
{
        Statement st=null;
        ResultSet rr=null;
        ArrayList<SelectItem> list=new ArrayList<>();
        try
        {
            st=con.createStatement();
            String query="select page_name from page_table";
            rr=st.executeQuery(query);
            while(rr.next())
            {
                SelectItem obj= new SelectItem();
                obj.setValue(rr.getString("page_name"));
                obj.setLabel(rr.getString("page_name"));
                 list.add(obj);
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try {
                if(st!=null)
                {
                    st.close();
                }
                if(rr!=null)
                {
                    rr.close();
                }
            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
return list;
        
}

public ArrayList<SelectItem> employeeTypeList(int branchId,Connection con)
{
        Statement st=null;
        ResultSet rr=null;
        HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        String userType= (String) ss.getAttribute("type");
        ArrayList<SelectItem> list=new ArrayList<>();
        try
        {
            st=con.createStatement();
            String query="select * from login where status='active' and type='employee'";
            
            
            
            query=selectQueWithBranch(query,branchId);
            if(userType.equalsIgnoreCase("masterAdmin"))
            {     
                query = "select * from login where"
                		+ " status='active' AND (type='employee' OR type='admin')";
             
            }

            rr=st.executeQuery(query);
            while(rr.next())
            {
                SelectItem obj= new SelectItem();
                obj.setValue(rr.getString("userid"));
                obj.setLabel( "userId:-"+rr.getString("userid").toUpperCase()+"--"+"userType:-"+rr.getString("type").toUpperCase());
                list.add(obj);
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try {
                if(st!=null)
                {
                    st.close();
                }
                if(rr!=null)
                {
                    rr.close();
                }
            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
return list;
        
    }


	


	public ArrayList<String> selectPageList(Connection con, String empType, Boolean permissionVal)

	{

		Statement st = null;
		ResultSet rs = null;
		ArrayList<String> list = new ArrayList<>();
		try
		{
			st = con.createStatement();
			String query = "select * from permission_table where emp_type='" + empType + "' and status='"
					+ permissionVal + "'";

			rs = st.executeQuery(query);

			while (rs.next())

			{
              
				list.add(pageNameByPageVal(rs.getString("page_name"),con));

			}

		}

		catch (Exception e)

		{

			e.printStackTrace();
			fileCreation(e.getMessage());
			fileCreation(e.getMessage());

		}

		finally {

			try {

				if (st != null)

				{

					st.close();

				}

				if (rs != null)

				{

					rs.close();

				}

			} catch (Exception e2) {

				// TODO: handle exception

			}

		}

		return list;

	}

	

	public ArrayList<SelectItem> transferShareHolderList() 
	{
		ArrayList<SelectItem> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select shareholderno from shareholder_info limit 7";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				SelectItem ss=new SelectItem();
				
				ss.setValue(rr.getString("shareholderno"));
				ss.setLabel(rr.getString("shareholderno"));
				
				list.add(ss);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}

	public ArrayList<SelectItem> managePageList(int branchId,Connection con)
	{
        Statement st=null;
        ResultSet rr=null;
        ArrayList<SelectItem> list=new ArrayList<>();
        try
        {
            st=con.createStatement();
            String query="select * from page_table where group_val='manage'";
            rr=st.executeQuery(query);
            while(rr.next())
            {
                SelectItem obj= new SelectItem();
                obj.setValue(rr.getString("page_name"));
                obj.setLabel(rr.getString("page_val"));
                 list.add(obj);
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try {
                if(st!=null)
                {
                    st.close();
                }
                if(rr!=null)
                {
                    rr.close();
                }
            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
return list;
        
}

	public ArrayList<SelectItem> shareHolList(int branchId,Connection con, String groupVal)
	{

	        Statement st=null;
	        ResultSet rr=null;
	        ArrayList<SelectItem> list=new ArrayList<>();
	        String query="select page_name,page_val from page_table where  group_val='"+groupVal+"'";
	        try
	        {   
	            st=con.createStatement();
	            rr=st.executeQuery(query);
	            while(rr.next())
	            {   
	                SelectItem obj= new SelectItem();
	                obj.setValue(rr.getString("page_name"));
	                
	                System.out.println(rr.getString("page_val"));
	                obj.setLabel(rr.getString("page_val"));
	                 list.add(obj);
	            }
	        }
	        
	        catch(Exception e)
	        {
	            e.printStackTrace();
	        }
	        finally
	        {
	            try {
	                if(st!=null)
	                {
	                    st.close();
	                }
	                if(rr!=null)
	                {
	                    rr.close();
	                }
	            } catch (Exception e2) {
	                // TODO: handle exception
	            }
	        }
	return list;
	        
	

	}

public int addExtraPermission(String empType, ArrayList<UserInfo> pageList,Connection con)
{
	int i = 0;
	String query="";
	Statement st=null,st1=null;
	ResultSet rr=null;
	try
	 {
		st=con.createStatement();
		st1=con.createStatement();
		for(int j=0;j<pageList.size();j++)
		 {
			
			    String preQu= "select id from permission_table where page_name='"+pageList.get(j).getPageName()+"' and emp_id='"+empType+"' and edit_status='"+pageList.get(j).getEditValue()+"' and delete_status='"+pageList.get(j).getDeleteValue()+"'";
			    query="update permission_table set edit_status='"+pageList.get(j).getEditValue()+"',delete_status='"+pageList.get(j).getDeleteValue()+"' where"
			    		+ " page_name='"+pageList.get(j).getPageName()+"' and emp_id='"+empType+"'";
			    		
			    System.out.println("1234"+query);
			    
			    ////System.out.println(preQu);
			    rr=st1.executeQuery(preQu);
			    if(rr.next())
			     {
			        
			     }
			    else
			     {
			          i=st.executeUpdate(query);
			     }
			
			if(i>0)
			{
			  dataInsertInQueryTable(query, con);
			}
		}
	 }
	catch(Exception e)
	{
	e.printStackTrace();
	}
	finally 
	        {
	            try 
	            {
	                // Close the writer regardless of what happens...
	            if(st!=null)
	            {
	              st.close();
	                }
	            if(rr!=null)
	            {
	                 rr.close();
	                }
	            } 
	            catch (Exception s) 
	            {
	                fileCreation(s.getMessage());
	            }
	        }
	return i;
	}
	
	public int updateMemberDocumentDetail(String id, String applicant_photoPath,
			String signPath, String formPath, String doc1Path, String doc2Path,
			String doc3Path, String doc4Path, String doc5Path, String doc6Path,
			String doc7Path, String doc8Path , String doc9Path,
			String doc10Path, String doc11Path) 
	{
		try (Connection conn = DataBaseConnection.JAVAConnection();)
		{
			String query="update shareholder_info set applicant_photo=?,signPhoto=?,formPhoto=?,doc1=?, doc2=?, doc3=?, doc4=?, doc5=?, doc6=?, doc7=?, doc8=?, doc9=?, doc10=?, doc11=? "
					+ "where id='"+id+"'";
			
			PreparedStatement st1 = conn.prepareStatement(query);
			st1.setString(1, applicant_photoPath);
			st1.setString(2, signPath);
			st1.setString(3, formPath);
			st1.setString(4, doc1Path);
			st1.setString(5, doc2Path);
			st1.setString(6, doc3Path);
			st1.setString(7, doc4Path);
			st1.setString(8, doc5Path);
			st1.setString(9, doc6Path);
			st1.setString(10, doc7Path);
			st1.setString(11, doc8Path);
			st1.setString(12, doc9Path);
			st1.setString(13, doc10Path);																						
			st1.setString(14, doc11Path);
			int i = st1.executeUpdate();
			if (i >= 1)
			{
				dataInsertInQueryTable(String.valueOf(st1), conn);
				return i;
				
				
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public int updateEmployeeDocumentDetail(String id, String panCard,
			String dlNo, String aadharCard, String voterId, String passport,
			String rationCard, String tenth, String twelveth, String graduation,
			String other) 
	{
		try (Connection conn = DataBaseConnection.JAVAConnection();)
		{
			String query = "update employee set aadhar_card_photo = ?, voter_id_photo = ?, passport_photo = ?, "
						 + "ration_card_photo = ?, tenth_photo = ?, twelveth_photo = ?, graduation_photo = ?, other_photo = ?, "
						 + "pan_card_photo = ?, dl_no_photo = ? where id = ? ";
			
			PreparedStatement st1 = conn.prepareStatement(query);
			st1.setString(1, aadharCard);
			st1.setString(2, voterId);
			st1.setString(3, passport);
			st1.setString(4, rationCard);
			st1.setString(5, tenth);
			st1.setString(6, twelveth);
			st1.setString(7, graduation);
			st1.setString(8, other);
			st1.setString(9, panCard);
			st1.setString(10, dlNo);
			st1.setString(11, id);
			int i = st1.executeUpdate();
			if (i >= 1)
			{
				dataInsertInQueryTable(String.valueOf(st1), conn);
				return i;
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public ArrayList<UserInfo> userSavingAccountTransactionList(int branchId,String searchType, String sDate, String eDate) 
	{
		ArrayList<UserInfo> list=new ArrayList<>();
		int count=1;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from customer_"+searchType+" where status='approved' and chequeStatus='cleared' and payment_mode='cash' and date>='"+sDate+"'"
					+ " and date<='"+eDate+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				UserInfo uu=new UserInfo();
				
				uu.setSno(count++);
				uu.setId(rr.getString("id"));
				uu.setAccountNo(rr.getString("account_no"));
				uu.setFirst_applicantName(applicantNameByShareHolderNo(shareHolderNoBySavingAccountNO(uu.getAccountNo()), conn));
				uu.setAmount(rr.getDouble("amount"));
				uu.setPayMode(rr.getString("payment_mode"));
				uu.setEntryDate(rr.getDate("date"));
				uu.setEntryDateStr(sf.format(rr.getDate("date")));
				
				list.add(uu);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}

	public int updateUserSavingAccountTransactionStatus(String id, String searchType) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update customer_"+searchType+" set status='delete' where id='"+id+"' ";
			int i=st.executeUpdate(qq);
			return i;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}

	 public String ageCalcullationMethod(Date dobDt)
	  {
		 String ageStr;
		////System.out.println("age method called");  
	    SimpleDateFormat a1 = new SimpleDateFormat("dd/MM/yyyy");
	    SimpleDateFormat a2 = new SimpleDateFormat("dd");
	    SimpleDateFormat a3 = new SimpleDateFormat("MM");
	    SimpleDateFormat a4 = new SimpleDateFormat("yyyy");
	    
	    Date d = new Date();
	    String date = a1.format(d);
	    int d1 = Integer.parseInt(a2.format(d));
	    int d2 = Integer.parseInt(a3.format(d));
	    int d3 = Integer.parseInt(a4.format(d));
	    
	    String dob = a1.format(dobDt);
	    //System.out.println(dob.substring(0, 1));
	    int dob1 = Integer.parseInt(a2.format(dobDt));
	    int dob2 = Integer.parseInt(a3.format(dobDt));
	    int dob3 = Integer.parseInt(a4.format(dobDt));
	    
	    int year = d3 - dob3 - 1;
	    if ((d2 == 1) || (d2 == 3) || (d2 == 5) || (d2 == 7) || (d2 == 8) || (d2 == 10) || (d2 == 12)) {
	      d1 += 31;
	    } else if ((d2 == 4) || (d2 == 6) || (d2 == 9) || (d2 == 11)) {
	      d1 += 30;
	    } else if (((d3 % 4 == 0) && (d3 % 100 != 100)) || (d3 % 400 == 0)) {
	      d1 += 29;
	    } else {
	      d1 += 28;
	    }
	    d2 += 11;
	    int month = d2 - dob2;
	    int day = d1 - dob1;
	    if (day >= 30)
	    {
	      day -= 30;
	      month++;
	    }
	    if (month >= 12)
	    {
	      month -= 12;
	      year++;
	    }
	    ageStr = (year + " year " + month + " month " + (day - 1) + " day");
	    return ageStr;
	  }
	 
	 
	 public String calculateTerm(Date dobDt, String maturityDate)
	  {
		 String ageStr;
		////System.out.println("age method called");  
	    SimpleDateFormat a1 = new SimpleDateFormat("dd/MM/yyyy");
	    SimpleDateFormat a2 = new SimpleDateFormat("dd");
	    SimpleDateFormat a3 = new SimpleDateFormat("MM");
	    SimpleDateFormat a4 = new SimpleDateFormat("yyyy");
	    
		SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy");
		Date d = null;
		try {
			d = f.parse(maturityDate);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	    String date = a1.format(d);
	    int d1 = Integer.parseInt(a2.format(d));
	    int d2 = Integer.parseInt(a3.format(d));
	    int d3 = Integer.parseInt(a4.format(d));
	    
	    String dob = a1.format(dobDt);
	    //System.out.println(dob.substring(0, 1));
	    int dob1 = Integer.parseInt(a2.format(dobDt));
	    int dob2 = Integer.parseInt(a3.format(dobDt));
	    int dob3 = Integer.parseInt(a4.format(dobDt));
	    
	    int year = d3 - dob3 - 1;
	    if ((d2 == 1) || (d2 == 3) || (d2 == 5) || (d2 == 7) || (d2 == 8) || (d2 == 10) || (d2 == 12)) {
	      d1 += 31;
	    } else if ((d2 == 4) || (d2 == 6) || (d2 == 9) || (d2 == 11)) {
	      d1 += 30;
	    } else if (((d3 % 4 == 0) && (d3 % 100 != 100)) || (d3 % 400 == 0)) {
	      d1 += 29;
	    } else {
	      d1 += 28;
	    }
	    d2 += 11;
	    int month = d2 - dob2;
	    int day = d1 - dob1;
	    if (day >= 30)
	    {
	      day -= 30;
	      month++;
	    }
	    if (month >= 12)
	    {
	      month -= 12;
	      year++;
	    }
	    ageStr = (year + " YR - " + month + " M ");
	    return ageStr;
	  }
	
// Problem Module Method Start From 
	 
	 public int addProblem(int branchId,Date dt, String problemType, String problemDesc, String image1Path, String status, String compNo, String userId,Connection conn) 
		{
			Timestamp tt=new Timestamp(dt.getTime());
			Statement st=null;
			try
			{
				st=conn.createStatement();
				String query="insert into add_problem(problem_date, problem_type, problem_desc, image1, status, comp_no, user_id,branch_id) values('"+tt+"', '"+problemType+"', '"+problemDesc+"', '"+image1Path+"', '"+status+"', '"+compNo+"', '"+userId+"','"+branchId+"')";
				int i=st.executeUpdate(query);
				if(i>0)
				{		dataInsertInQueryTable(query, conn);
				return i;
			}}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			finally 
	        {
	            try 
	            {
	                
	            	if(st!=null)
	            	{
	            		  st.close();
	                }
	            } 
	            catch (Exception s) 
	            {
	                fileCreation(s.getMessage());
	            }
	        }
			return 0;
		}
	 public ArrayList<ProblemInfo> viewProblem(int branchId,Connection conn) 
		{
			fileViewPathDetail(conn);
			String type=userType();
			String userId=userId();
			int count=1;
			ArrayList<ProblemInfo> list=new ArrayList<>();
			String query="";
			
			try
			{
				Statement st=conn.createStatement();
				if(type.equals("admin"))
				{
					query="select * from add_problem where branch_id='"+branchId+"' ";
				}
				else
				{
					query="select * from add_problem where user_id='"+userId+"'  and branch_id='"+branchId+"'";
				}
				query+="order by id_add_problem desc";
				ResultSet rr=st.executeQuery(query);
				while(rr.next())
				{
					ProblemInfo ii=new ProblemInfo();
					
					ii.setSno(count++);
					ii.setProblemId(rr.getString("id_add_problem"));
					ii.setProblemDate(rr.getDate("problem_date"));
					ii.setCompNo(rr.getString("comp_no"));
					ii.setProblemDateStr(rr.getString("problem_date"));
					ii.setProblemType(rr.getString("problem_type"));
					ii.setProblemDesc(rr.getString("problem_desc"));
				//	ii.setImage1Path(rr.getString("image1")); //offline
					if(onlineFileViewPath.equals(""))
					{
						ii.setImage1Path(rr.getString("image1")); //offline
					}
					else
					{
						ii.setImage1Path(onlineFileViewPath+rr.getString("image1")); //online
					}
					ii.setStatus(rr.getString("status"));
					ii.setProblemRegBy(rr.getString("user_id"));
					if(ii.getStatus().equals("solved"))
					{
						ii.setSolvedDate(rr.getDate("solved_date"));
						ii.setSolvedDateStr(rr.getString("solved_date"));
						ii.setSolvedDesc(rr.getString("solved_desc"));
						ii.setDisEdit(true);
					}
					else
					{
						ii.setDisEdit(false);
					}
					
					list.add(ii);
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			
			
			return list;
		}
		
		
		public int updateProblemStatus(String status, String remark, String id, Connection conn) 
		{
			Statement st=null;
			Timestamp tt=new Timestamp(new Date().getTime());
			tt.setHours(0);tt.setMinutes(0);tt.setSeconds(0);tt.setNanos(0);
			try
			{
				st=conn.createStatement();
				String query="update add_problem set status='"+status+"', solved_desc='"+remark+"', solved_date='"+tt+"' where id_add_problem='"+id+"' ";
			//	
				int i=st.executeUpdate(query);
				if(i>0)
				{
				dataInsertInQueryTable(query, conn);
				return i;
			}}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			finally 
	        {
	            try 
	            {
	                // Close the writer regardless of what happens...
	            	if(st!=null)
	            	{
	            		  st.close();
	                }
	            } 
	            catch (Exception s) 
	            {
	                s.printStackTrace();
	                fileCreation(s.getMessage());
	            }
	        }

			return 0;
		}

		public String complainedNo(int branchId,Connection conn) 
		{
			String maxInvNo="";
			Statement st=null;
			ResultSet rr=null;
			try
			{
				st=conn.createStatement();
				String query="select max(convert(comp_no,decimal)) as num from add_problem ";
				//
				rr=st.executeQuery(selectQueWithBranch(query,branchId));
				if(rr.next())
				{
					maxInvNo=rr.getString("num");
					if(maxInvNo==null)
					{
						return maxInvNo="1";
					}
					else
					{
						return String.valueOf(Integer.parseInt(maxInvNo)+1);
					}
				}
				
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			finally 
	        {
	            try 
	            {
	                
	            	if(st!=null)
	            	{
	            		  st.close();
	                }
	            	if(rr!=null)
	            	{
	            	     rr.close();
	                }
	            } 
	            catch (Exception s) 
	            {
	                fileCreation(s.getMessage());
	            }
	        }
			return "";
		}

		public String contactNoByUserId(String userId, Connection con) 
		{
			try
			{
				Statement st=con.createStatement();
				String qq="select mobile_no from login where userid='"+userId+"' ";
				ResultSet rr=st.executeQuery(qq);
				if(rr.next())
				{
					return rr.getString("mobile_no");
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			return "9982311326";
		}

		public ArrayList<SelectItem> frequencySelectItemListFormLoanTable(int branchId,String loanType, Connection conn) 
		{
			ArrayList<SelectItem> list=new ArrayList<>();
			Statement st=null;
			ResultSet rr=null;
			try
			{   
				st=conn.createStatement();
				String query="select frequency from "+loanType+"  where branch_id='"+branchId+"'group by frequency ";
				rr=st.executeQuery(query);
				while(rr.next())
				{
					SelectItem ss=new SelectItem();
					
					ss.setLabel(frequencyLabel(rr.getString("frequency"))+" Loan");
					ss.setValue(rr.getString("frequency"));
					
					list.add(ss);
				}
				
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			finally 
	        {
	            try 
	            {
	            	if(st!=null)
	            	{
	            		  st.close();
	                }
	            	if(rr!=null)
	            	{
	            	     rr.close();
	                }
	            } 
	            catch (Exception s) 
	            {
	                fileCreation(s.getMessage());
	            }
	        }
			return list;
		}
		
		
		public ArrayList<SelectItem> termsSelectItemListFormLoanTable(String loanType,Connection conn) 
		{
			ArrayList<SelectItem> list=new ArrayList<>();
			Statement st=null;
			ResultSet rr=null;
			try
			{
				st=conn.createStatement();
				String query="select terms from "+loanType+" group by terms ";
				rr=st.executeQuery(query);
				while(rr.next())
				{
					SelectItem ss=new SelectItem();
					
					ss.setLabel(rr.getString("terms")+" Terms");
					ss.setValue(rr.getString("terms"));
					
					list.add(ss);
				}
				
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			finally 
	        {
	            try 
	            {
	            	if(st!=null)
	            	{
	            		  st.close();
	                }
	            	if(rr!=null)
	            	{
	            	     rr.close();
	                }
	            } 
	            catch (Exception s) 
	            {
	                fileCreation(s.getMessage());
	            }
	        }
			return list;
		}
		
		
		public ArrayList<SelectItem> loanNoListFreqWise(String freq,String tableName,int branchId, Connection conn) 
		{
			ArrayList<SelectItem> list=new ArrayList<>();
			Statement st=null;
			ResultSet rr=null;
			try
			{
				st=conn.createStatement();
				String query="select loanNo,first_applicantName,father_husband_name from "+tableName+" inner join shareholder_info where "+tableName+".status='Approve' and paidStatus='unpaid' and shareholder_info.shareholderno="+tableName+".shareholderno and frequency='"+freq+"' and shareholder_info.branch_id='"+branchId+"'";
				System.out.println(query);
				rr=st.executeQuery(query);
				while(rr.next())
				{
					SelectItem ss=new SelectItem();
					
					ss.setLabel(rr.getString("loanNo")+" - "+rr.getString("first_applicantName")+ " - "+rr.getString("father_husband_name"));
					ss.setValue(rr.getString("loanNo"));
					
					list.add(ss);
				}
				
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			finally 
	        {
	            try 
	            {
	            	if(st!=null)
	            	{
	            		  st.close();
	                }
	            	if(rr!=null)
	            	{
	            	     rr.close();
	                }
	            } 
	            catch (Exception s) 
	            {
	                fileCreation(s.getMessage());
	            }
	        }
			return list;
		}
		
		
		
	public String messageBalanceMethod()
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		String 	url=checkSMessageApiDetailFromTable("balance_url", "",conn);
		if(url==null || url.trim().equalsIgnoreCase(""))
		{
			//RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage(FacesMessage.SEVERITY_INFO, "Message Balance Alert... !!!", ""+"URL Not Set by the Admin."));
		}
		
		else if(url.contains("http://sms.bulksmsind.in/getSMSCredit?"))
		{
			String output  =getUrlContents(url);
			if(output!=null && !output.trim().equalsIgnoreCase("") && output.contains("TRANS") && output.contains("PROMO"))
			{
				////System.out.println(output);
				String arr[]=output.split("],");
				String temp[]=arr[1].split(",");
				String fTemp[]=temp[0].split("\\[");
				
				 return fTemp[1];
			}
			
			else if(output!=null && !output.trim().equalsIgnoreCase("") && output.contains("TRANS"))
			{
				String arr[]=output.split(",");
				String temp[]=arr[0].split("\\[\\[");
				
				 return temp[1];
			}
		}
		else
		{
			String output  =getUrlContents(url);
			if(output!=null && !output.trim().equalsIgnoreCase("") && output.contains("BALANCE"))
			{
				String arr[]=output.split("BALANCE\":");
				String newStr=arr[1];
				String nrr[]=newStr.split("}");
				
				 return nrr[0];
			}
		}
		 
		 try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "0";
	}

	private static String getUrlContents(String theUrl)
	  {
	    StringBuilder content = new StringBuilder();
	    try
	    {

	      URL url = new URL(theUrl);
	      URLConnection urlConnection = url.openConnection();
	      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
	 
	      String line;
	      while ((line = bufferedReader.readLine()) != null)
	      {
	        content.append(line + "\n");
	      }
	      bufferedReader.close();
	    }
	    catch(Exception e)
	    {
	      e.printStackTrace();
	    }
	    return content.toString();
	  }

	public Date lastPromotorInterestCreditDate(int branchId,Connection conn) 
	{
		Date lastDate=new Date();
		ArrayList<SelectItem> list=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select expense_date from expense_table where item='Promoter Interest' and status='active' and branch_id='"+branchId+"'order by id desc ";
			
			rr=st.executeQuery(query);
			if(rr.next())
			{
				lastDate=rr.getDate("expense_date"); 
			}
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally 
        {
            try 
            {
            	if(st!=null)
            	{
            		  st.close();
                }
            	if(rr!=null)
            	{
            	     rr.close();
                }
            } 
            catch (Exception s) 
            {
                fileCreation(s.getMessage());
            }
        }
		return lastDate;
	}
	
	public boolean checkPromotorInterestCreditDate(int branchId,Date date, String pid,Connection conn) 
	{
		String sDate=sdfForDb.format(date);
		ArrayList<SelectItem> list=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select expense_date from expense_table where item='Promoter Interest' and expense_date='"+sDate+"' and status='active' and other_table_id='"+pid+"' ";
			
			rr=st.executeQuery(selectQueWithBranch(query,branchId));
			if(rr.next())
			{
				return true;
			}
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally 
        {
            try 
            {
            	if(st!=null)
            	{
            		  st.close();
                }
            	if(rr!=null)
            	{
            	     rr.close();
                }
            } 
            catch (Exception s) 
            {
                fileCreation(s.getMessage());
            }
        }
		return false;
	}

	public int updateFirstEMIDate(String loanType, String subLoanNo, Date emiDate, Connection conn) 
	{
		String query="";
		Timestamp tt=new Timestamp(emiDate.getTime());
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			if(loanType.equalsIgnoreCase("grouploan"))
			{
				query="update "+loanType+" set emi_due_date='"+tt+"' where sub_loan_no='"+subLoanNo+"'  ";
			}
			else
			{
				query="update "+loanType+" set emi_due_date='"+tt+"' where loanNo='"+subLoanNo+"'  ";
			}
			
			int i=st.executeUpdate(query);
			if(i>0)
			{
				return 1;
			}
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally 
        {
            try 
            {
            	if(st!=null)
            	{
            		  st.close();
                }
            	if(rr!=null)
            	{
            	     rr.close();
                }
            } 
            catch (Exception s) 
            {
                fileCreation(s.getMessage());
            }
        }
		return 0;
	}
	 
	
	public int addPermission(String empType, Boolean permissionVal, ArrayList<String> pageVal, Connection con) 
	{
		String query="";
		int i = 0;
		Statement st=null,st1=null;
		ResultSet rr=null;
		try
		{
			st=con.createStatement();
			st1=con.createStatement();
			
			 String preQu= "delete from permission_table where emp_id='"+empType+"' ";
			 st1.executeUpdate(preQu);
			    
			for(int j=0;j<pageVal.size();j++)
			{
				if(!(pageVal.get(j).equalsIgnoreCase("All")))
				{
					String groupName= groupNameByPageVal(pageVal.get(j),con);
				    query="insert into permission_table (page_name,emp_id,status,group_name) values('"+pageVal.get(j)+"','"+empType+"','"+permissionVal+"','"+groupName+"')";
				    
				    i=st.executeUpdate(query);
				}
				if(i>0)
				{
					dataInsertInQueryTable(query, con);
				}
			}
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally 
        {
            try 
            {
                // Close the writer regardless of what happens...
            if(st!=null)
            {
              st.close();
                }
            if(rr!=null)
            {
                 rr.close();
                }
            } 
            catch (Exception s) 
            {
                fileCreation(s.getMessage());
            }
        }
		return i;
	}

	public String groupNameByPageVal(String pageName, Connection con)
	{
	
	    Statement st=null;
	    ResultSet rr=null;
	    try
	    {
	        st=con.createStatement();
	        String query="select group_val from page_table where page_name='"+pageName+"' ";
	        rr=st.executeQuery(query);
	        if(rr.next())
	        {
	            return rr.getString("group_val");
	        }
	    }
	    catch(Exception e)
	    {
	        e.printStackTrace();
	    }
	    finally
	    {
	        try {
	            if(st!=null)
	            {
	                st.close();
	            }
	            if(rr!=null)
	            {
	                rr.close();
	            }
	        } catch (Exception e2) {
	            // TODO: handle exception
	        }
	    }
	return "";
	
	}

	public ArrayList<UserInfo> pageList(String empType, Connection con) 
	{
		Statement st = null;
		ResultSet rs = null;
		int id=0;
		String query="";
		if(empType != null && !empType.isEmpty())
		{
			query="SELECT * FROM permission_table INNER JOIN  page_table ON permission_table.page_name = page_table.page_name where page_table.group_val='Manage Group' and emp_id='"+empType+"'";
		    //System.out.println("sss@@@@@@@@@"+query);
		}
		
		ArrayList<UserInfo> list = new ArrayList<UserInfo>();
		try {
			st = con.createStatement();
			rs = st.executeQuery(query);
			while (rs.next())
			{
				UserInfo obj = new UserInfo();
				obj.setId(String.valueOf(++id));
				obj.setPageVal(rs.getString("page_table.page_val"));
				obj.setPageName(rs.getString("page_table.page_name"));
				if(empType != null && !empType.isEmpty())
				{
	                obj.setEditValue(rs.getString("permission_table.edit_status"));
	                obj.setDeleteValue(rs.getString("permission_table.delete_status"));
				}

                list.add(obj);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (st != null) {
					st.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}


	public ArrayList<String> selectPageList(Connection con, String empType, String groupName)
	{
		Statement st = null;
		ResultSet rs = null;
		ArrayList<String> list = new ArrayList<>();
		try
		{
			st = con.createStatement();
			String query = "select * from permission_table where emp_id='" + empType + "' and status='true' and group_name='"+groupName+"' ";
			
			rs = st.executeQuery(query);
			while (rs.next())
			{
				list.add(rs.getString("page_name"));
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			fileCreation(e.getMessage());
		}
		finally 
		{
			try {
				if (st != null)
				{
					st.close();
				}
				if (rs != null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}

	public String pageNameByPageVal(String pageName, Connection con)
	{
	    Statement st=null;
	    ResultSet rr=null;
	    try
	    {
	        st=con.createStatement();
	        String query="select page_val from page_table where page_name='"+pageName+"' ";
	        
	        rr=st.executeQuery(query);
	        if(rr.next())
	        {
	            return rr.getString("page_val");
	        }
	    }
	    catch(Exception e)
	    {
	        e.printStackTrace();
	    }
	    finally
	    {
	        try {
	            if(st!=null)
	            {
	                st.close();
	            }
	            if(rr!=null)
	            {
	                rr.close();
	            }
	        } catch (Exception e2) {
	            // TODO: handle exception
	        }
	    }
		return "";
	}

	public String checkExistDataByAadharNo(String uniqueId, String string,Connection conn) 
	{
		String detail="";
		String qq="";
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			 if(string.equalsIgnoreCase("unique_id"))
			 {
				 qq="select * from shareholder_info where unique_id='"+uniqueId+"' and account_status='active' ";
			 }
			 else
			 {
				 qq="select * from shareholder_info where voter_id='"+uniqueId+"' and account_status='active' ";
			 }
			 rr=st.executeQuery(qq);
			 if(rr.next())
			 {
				 detail="Member Data Already Exist in Database With the Name of "+rr.getString("first_applicantName")+", Member No. "+rr.getString("shareholderno")+", Address: "+rr.getString("address")+", Form/Center No: "+rr.getString("office_application_no") ; 
			 }
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return detail;
	}

	public int checkMemberAgeLimit(Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			 String qq="select member_age_limit from firm_detail";
			 rr=st.executeQuery(qq);
			 if(rr.next())
			 {
				 return rr.getInt("member_age_limit");
			 }
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	public double checkDealerPayoutPercent(Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			 String qq="select dealer_percent from firm_detail limit 1";
			 rr=st.executeQuery(qq);
			 if(rr.next())
			 {
				 return rr.getDouble("dealer_percent");
			 }
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	public ArrayList<SelectItem> loanTermsListByLoanType(int branchId,String loanType, Connection conn) 
	{
		ArrayList<SelectItem> loanTermsList=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			 String qq="select terms from "+loanType+" where status='Approve' and paidStatus='unpaid' group by terms ";
			 rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			 while(rr.next())
			 {
				 SelectItem ss=new SelectItem();
				 
				 ss.setLabel(rr.getString("terms"));
				 ss.setValue(rr.getInt("terms"));
				 
				 loanTermsList.add(ss);
			 }
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return loanTermsList;
	}

	public ArrayList<LoanInfo> loanListTermsWise(int branchId,String loanType, String terms, Connection conn) 
	{
		ArrayList<LoanInfo> list=new ArrayList<>();
		int count=1;
		String qq="";
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			 if(loanType.equalsIgnoreCase("Group Loan") || loanType.equalsIgnoreCase("grouploan"))
			 {
				 qq="select * from grouploan inner join shareholder_info where  shareholder_info.shareholderno=grouploan.teamLeader   ";
			 }
			 else
			 {
				 qq="select * from "+loanType+" inner join shareholder_info where  shareholder_info.shareholderno="+loanType+".shareholderno   ";
			 }
			 qq+="and "+loanType+".status='Approve' and  "+loanType+".paidStatus='unpaid' and "+loanType+".terms='"+terms+"'";
			 
			 qq=selectQueWithBranch(qq, branchId, "shareholder_info")+"order by "+loanType+".loanNo asc ";
			 rr=st.executeQuery(qq);
			 while(rr.next())
			 {
				 LoanInfo ll=new LoanInfo();
				 
				 ll.setSno(count++);
				 ll.setShareHolderNo(rr.getString("shareholder_info.shareholderno"));
				 ll.setApplicantName(rr.getString("shareholder_info.first_applicantName"));
				 if(loanType.equalsIgnoreCase("Group Loan") || loanType.equalsIgnoreCase("grouploan"))
				 {
					 ll.setLoanNo(rr.getString("grouploan.sub_loan_no"));
					 ll.setCenterName(centerNameById(rr.getString("grouploan.center"), conn));
				 }
				 else
				 {
					 ll.setLoanNo(rr.getString(loanType+".loanNo"));
				 }
				 ll.setFatherHusbandName(rr.getString("shareholder_info.father_husband_name"));
				 ll.setAddress(rr.getString("shareholder_info.address"));
				 ll.setMobile(rr.getString("shareholder_info.mobile"));
				 ll.setEmiAmount(rr.getDouble(loanType+".emi"));
				 ll.setLoanType(loanType);
				 
				 list.add(ll);
			 }
					 
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return list;
	}
	
	public int updateInAttendanceTable(int branchId, String userid, String logDt, String logTm,
	        String latitude, String longitude, String deviceName, Connection conn,String selfiePath)
	{
	    Statement selectSt = null;
	    Statement updateSt = null;
	    ResultSet rr = null;

	    int totalUpdated = 0;

	    try
	    {
	        selectSt = conn.createStatement();
	        updateSt = conn.createStatement();

	        String selectQuery;

	        if(userid.equalsIgnoreCase("all"))
	        {
	            selectQuery = "select id,userid,end_time from attendance_table where attendance_date='" + logDt + "'";
	        }
	        else
	        {
	            selectQuery = "select id,userid,end_time from attendance_table where attendance_date='" + logDt + "' and userid='" + userid + "'";
	        }

	        System.out.println("ATTENDANCE CHECK QUERY = " + selectQuery);

	        rr = selectSt.executeQuery(selectQueWithBranch(selectQuery, branchId));

	        while(rr.next())
	        {
	            String id = rr.getString("id");
	            String userId = rr.getString("userid");
	            String endTime = rr.getString("end_time");

	            System.out.println("USER = " + userId
	                    + " | ID = " + id
	                    + " | END_TIME = [" + endTime + "]");

	         
	            if(endTime == null || endTime.trim().equals(""))
	            {
	                String status;

	                if(userid.equalsIgnoreCase("all"))
	                {
	                    status = "auto";
	                }
	                else
	                {
	                    status = "logout";
	                }
                    
	                String updateQuery="update attendance_table set end_time='"+logTm+"',latitude_logout='"+latitude+"',longitude_logout='"+longitude+"',logout_device_name='"+deviceName+"',logout_selfie_path='" + selfiePath +"',status='"+status+"'  where id='"+id+"'";

	                System.out.println("ATTENDANCE UPDATE = " + updateQuery);

	                int updated = updateSt.executeUpdate(
	                        selectQueWithBranch(updateQuery, branchId)
	                );

	                totalUpdated += updated;

	                System.out.println("ATTENDANCE UPDATED ROWS = " + updated
	                        + " | USER = " + userId
	                        + " | TIME = " + logTm
	                        + " | STATUS = " + status);

	                if(updated > 0)
	                {
	                    dataInsertInQueryTableBySystem(updateQuery, conn);
	                }
	            }
	            else
	            {
	                System.out.println("ATTENDANCE SKIPPED = " + userId
	                        + " | EXISTING END_TIME = " + endTime);
	            }
	        }

	        System.out.println("TOTAL ATTENDANCE UPDATED = " + totalUpdated);

	        return totalUpdated;
	    }
	    catch(Exception e)
	    {
	        e.printStackTrace();
	    }
	    finally
	    {
	        try
	        {
	            if(rr != null)
	            {
	                rr.close();
	            }

	            if(selectSt != null)
	            {
	                selectSt.close();
	            }

	            if(updateSt != null)
	            {
	                updateSt.close();
	            }
	        }
	        catch(Exception e)
	        {
	            e.printStackTrace();
	        }
	    }

	    return 0;
	}

	public void calculateLoanEMiRecord(ArrayList<SelectItem> emiTermsList, ArrayList<LoanInfo> list, Connection conn) 
	{
		for(LoanInfo ss : list)
		{
			Map<String, String> map=new HashMap<String,String>();
			int count=0;
			for(SelectItem ii : emiTermsList)
			{
				double paidEmiAmt=loanPaidEmiAmountByEmiNo(ss.getLoanNo(), String.valueOf(ii.getValue()), conn);
				if(paidEmiAmt>0)
				{
					count++;
				}
				String output=String.valueOf(paidEmiAmt) +" / "+ String.valueOf(ss.getEmiAmount());
				map.put(String.valueOf(ii.getValue()), output);
			}
			
			ss.setTotalPaid(count);
			ss.setEmiMap(map);
		}
	}

	
	private double loanPaidEmiAmountByEmiNo(String loanNo, String sno, Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from loanpayment where loanNo='"+loanNo+"' and emi_no='"+sno+"' and receipt_status='approved' and chequeStatus='cleared'  ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return Double.parseDouble(df.format(rr.getDouble("sum(amount)")));
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}

	public boolean checkLastEntrySettingInDb(int branchId,String string, Connection conn) 
	{   
		
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			String qq="select status from last_entry_setting where module_name='"+string+"' ";
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getBoolean("status");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return false;
	}

	public ArrayList<SelectItem> secureLoanTypeList(int branchId,Connection conn) 
	{
		ArrayList<SelectItem> list=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from secure_type_table ";
			rr=st.executeQuery(qq);
			while(rr.next())
			{
				SelectItem ss=new SelectItem();
				ss.setLabel(rr.getString("security_type"));
				ss.setValue(rr.getString("id"));
				list.add(ss);
			}
		}
	    
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}
	
	public double fileChargeAndInsFeeFromPlanTable(int branchId,String columnName,
			String plan_no, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select "+columnName+" from plans where idplans='"+plan_no+"'  ";
			//System.out.println(qq);
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble(columnName);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return 0;
	}

	public int deletePolicy(String user_no) 
	{
		Statement st=null;
		ResultSet rr=null;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			st=conn.createStatement();
			String qq="update customer_info set account_status='inactive', maturity_value=0, paid_status='paid', maturity_date='"+new Timestamp(new Date().getTime())+"' where user_no='"+user_no+"'  ";
			int i=st.executeUpdate(qq);
			return i;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}	
		return 0;
	}

	public String findFileChargeAndInsFeeEntryStatus(String loanNo, String string, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select status from income_table  where loan_no='"+loanNo+"' and item='"+string+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("status");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}

	public int totalRegProblem(int branchId,Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select count(*) from add_problem ";
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getInt("count(*)");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	public int insertInAttendanceTable(int branchId,String userid, String logDt,String logTm, String latitude, String longitude, 
									   String deviceName, Connection conn, String selfiePath) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="insert into attendance_table(userid, start_time, latitude_login, longitude_login, login_device_name, attendance_date,branch_id, selfie_path)"
					+ " values('"+userid+"','"+logTm+"','"+latitude+"','"+longitude+"','"+deviceName+"','"+logDt+"','"+branchId+"', '"+selfiePath+"') ";
			//System.out.println(qq);
			int i=st.executeUpdate(qq);
			return i;
		}
		
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}

		return 0;
	}	
	
//	public int updateInAttendanceTable(int branchId,String userid, String logDt,String logTm, String latitude, String longitude, String deviceName, Connection conn) 
//	{   
//		String qq="";
//		Statement st=null;
//		ResultSet rr=null;
//		try
//		{		
//			st=conn.createStatement();
//			
////			if(userid.equalsIgnoreCase("all"))
////			{   
////				qq="update attendance_table set end_time='"+logTm+"', latitude_logout='"+latitude+"',longitude_logout='"+longitude+"', logout_device_name='"+deviceName+"', status='auto' "
////						+ " where attendance_date='"+logDt+"' and end_time IS NULL ";
////			}
////			
////			else
////			{   
////				qq="update attendance_table set end_time='"+logTm+"', latitude_logout='"+latitude+"',longitude_logout='"+longitude+"', logout_device_name='"+deviceName+"', status='logout' "
////						+ " where attendance_date='"+logDt+"' and userid='"+userid+"' and end_time IS NULL ";
////			}
//			
//			if(userid.equalsIgnoreCase("all"))
//			{ 
//			    qq = "update attendance_table set end_time='"+logTm+"', latitude_logout='"+latitude+"', longitude_logout='"+longitude+"', logout_device_name='"+deviceName+"', status='auto' "
//			       + " where attendance_date='"+logDt+"' and (end_time IS NULL OR end_time = '' OR end_time = '00:00:00')";
//			}
//			else
//			{
//			    qq = "update attendance_table set end_time='"+logTm+"', latitude_logout='"+latitude+"', longitude_logout='"+longitude+"', logout_device_name='"+deviceName+"', status='logout' "
//			       + " where attendance_date='"+logDt+"' and userid='"+userid+"' and (end_time IS NULL OR end_time = '' OR end_time = '00:00:00')";
//			}
//			
//			int i=st.executeUpdate(selectQueWithBranch(qq,branchId));
//			
//			dataInsertInQueryTableBySystem(qq, conn);
//			
//			return i;
//			
//		}
//		catch(Exception e)
//		{
//			e.printStackTrace();
//		}
//		finally
//		{
//			try {
//				if(st!=null)
//				{
//					st.close();
//				}
//				if(rr!=null)
//				{
//					rr.close();
//				}
//			} catch (Exception e2) {
//				// TODO: handle exception
//			}
//		}
//
//		return 0;
//	}
	
	
	
	
	public void dataInsertInQueryTableBySystem(String query, Connection conn) 
	{
		Timestamp tt=new Timestamp(new Date().getTime());
		tt.setNanos(0);
		
		String qq="insert into query_table(query_time, query, user_id) values(?,?,?)";
		try 
		{
			PreparedStatement st=conn.prepareStatement(qq);
			st.setTimestamp(1, tt);
			st.setString(2, query);
			st.setString(3, "SYSTEM");
			st.executeUpdate();
			
		} 
		catch (SQLException e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
	}
	
	

	public boolean checkEmpAttendanceOfCurrentDate(String userid) 
	{
		Statement st=null;
		ResultSet rr=null;
		String dt=sdfForDb.format(new Date());
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			st=conn.createStatement();
			String qq="select * from attendance_table where attendance_date='"+dt+"' and userid='"+userid+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}

		return false;
	}
	

	public ArrayList<EmpInfo> viewAttendanceByEmpUserId(String userId, Date startDate, Date endDate, int branchId) 
	{ 
	
		Statement st=null;
		ResultSet rr=null;
		String sdt=sdfForDb.format(startDate.getTime());
		String edt=sdfForDb.format(endDate.getTime());
		ArrayList<EmpInfo> list=new ArrayList<>();
		int count=1;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			st=conn.createStatement();
			String qq="select * from attendance_table where userid='"+userId+"' and attendance_date>='"+sdt+"' and attendance_date<='"+edt+"' ";
			System.out.println("Query :"+qq+"  && "+"value"+userId+" "+sdt+" "+edt);
			rr=st.executeQuery(selectQueWithBranch(qq, branchId));
			while(rr.next())
			{   
				System.out.println("value inn :");
				
				
				EmpInfo ee=new EmpInfo();
				
				ee.setSno(count++);
				ee.setAttendanceDate(rr.getDate("attendance_date"));
				ee.setStrAttendanceDate(sf.format(rr.getDate("attendance_date")));
				ee.setLoginTime(rr.getString("start_time"));
				ee.setLogoutTime(rr.getString("end_time"));
				
				if(rr.getString("end_time")!=null && !rr.getString("end_time").equalsIgnoreCase(""))
				{
					ee.setWorkingHours("Work Pending");
				}
				ee.setStatus(rr.getString("status"));
				ee.setLoginDeviceName(rr.getString("login_device_name"));
				ee.setLogoutDeviceName(rr.getString("logout_device_name"));
				ee.setLatitudeLogin(rr.getString("latitude_login"));
				ee.setLongitudeLogin(rr.getString("longitude_login"));
				ee.setLatitudeLogout(rr.getString("latitude_logout"));
				ee.setLongitudeLogout(rr.getString("longitude_logout"));
				
				list.add(ee);
				
			}
			
			System.out.println("att"+qq);
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}

	public boolean checkEmpLogoutCurrentDate(String userid) 
	{
		Statement st=null;
		ResultSet rr=null;
		String dt=sdfForDb.format(new Date());
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			st=conn.createStatement();
			String qq="select * from attendance_table where attendance_date='"+dt+"' and userid='"+userid+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				if(rr.getString("end_time")!=null && !rr.getString("end_time").equalsIgnoreCase(""))
				{
					return true;
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}

		return false;
	}

	public ArrayList<SelectItem> centerListForUpcomingEMI(int branchId,Date startDate, Date endDate) 
	{
		ArrayList<String> uList=new ArrayList<>();
		Date dt=new Date();
		endDate.setHours(0);
		endDate.setMinutes(0);
		endDate.setSeconds(0);
		startDate.setHours(0);
		startDate.setMinutes(0);
		startDate.setSeconds(0);
		while(startDate.before(endDate) || startDate.equals(endDate))
		{
			uList.add(sf.format(startDate));
			startDate.setDate(startDate.getDate()+1);
		}
	    
		ArrayList<SelectItem> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{		
			Statement st=conn.createStatement();
			String qq="select * from grouploan where status='Approve' and paidStatus='unpaid'  ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				ArrayList<String> dList=loanEmiStrDateList(rr.getInt("frequency"), rr.getInt("terms"), rr.getDate("emi_due_date"),rr.getDate("approvalDate"), rr.getString("sub_loan_no"), conn);
				for(String ss: uList)
				{
					if(dList.contains(ss))
					{
						if(list.size()>0)
						{
							boolean  chk=true;
							for(int i=0;i<list.size();i++)
							{
								if(String.valueOf(list.get(i).getValue()).equalsIgnoreCase(rr.getString("center")))
								{
									chk=false;
									break;
								}
							}
							
							if(chk==true)
							{
								SelectItem si=new SelectItem();
								
								si.setLabel(centerNameById(rr.getString("center"), conn));
								si.setValue(rr.getString("center"));
								
								list.add(si);
								
								break;
							}
						}
						else
						{
							SelectItem si=new SelectItem();
							
							si.setLabel(centerNameById(rr.getString("center"), conn));
							si.setValue(rr.getString("center"));
							
							list.add(si);
							
							break;
						}
 					}
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}
	
	public ArrayList<SelectItem> centerListForUpcomingEMIForApp(int branchId,Date startDate, Date endDate) 
	{
		ArrayList<String> uList=new ArrayList<>();
		Date dt=new Date();
		endDate.setHours(0);
		endDate.setMinutes(0);
		endDate.setSeconds(0);
		startDate.setHours(0);
		startDate.setMinutes(0);
		startDate.setSeconds(0);
		if(startDate.equals(endDate))
		{
			uList.add(sf.format(startDate));
		}
		
		ArrayList<SelectItem> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from grouploan where status='Approve' and paidStatus='unpaid'  ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				ArrayList<String> dList=loanEmiStrDateList(rr.getInt("frequency"), rr.getInt("terms"), rr.getDate("emi_due_date"),rr.getDate("approvalDate"), rr.getString("sub_loan_no"), conn);
				for(String ss: uList)
				{
					if(dList.contains(ss))
					{
						if(list.size()>0)
						{
							boolean  chk=true;
							for(int i=0;i<list.size();i++)
							{
								if(String.valueOf(list.get(i).getValue()).equalsIgnoreCase(rr.getString("center")))
								{
									chk=false;
									break;
								}
							}
							
							if(chk==true)
							{
								SelectItem si=new SelectItem();
								
								si.setLabel(centerNameById(rr.getString("center"), conn));
								si.setValue(rr.getString("center"));
								
								list.add(si);
								
								break;
							}
						}
						else
						{
							SelectItem si=new SelectItem();
							
							si.setLabel(centerNameById(rr.getString("center"), conn));
							si.setValue(rr.getString("center"));
							
							list.add(si);
							
							break;
						}
 					}
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}
		
	public ArrayList<SelectItem> centerListForCenterMeeting(int branchId,Date startDate, String dsaCode) 
	{
		startDate.setHours(0);
		startDate.setMinutes(0);
		startDate.setSeconds(0);
		ArrayList<SelectItem> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from grouploan where status='Approve' and paidStatus='unpaid' ";
			if(!dsaCode.equalsIgnoreCase("-1"))
			{
				qq+=" and dsacode='"+dsaCode+"' ";
			}
			System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				ArrayList<String> dList=loanEmiStrDateList(rr.getInt("frequency"), rr.getInt("terms"), rr.getDate("emi_due_date"),rr.getDate("approvalDate"), rr.getString("sub_loan_no"), conn);
				/*if(dList.contains(sf.format(startDate)))
				{
					SelectItem si=new SelectItem();
					
					si.setLabel(centerNameById(rr.getString("center"), conn)+", Staff Name: "+dsaNameById(rr.getString("dsacode"), conn)+System.lineSeparator());
					si.setValue(rr.getString("center"));
					
					list.add(si);
				}*/
				if(dList.contains(sf.format(startDate)))
				{
					if(list.size()>0)
					{
						boolean  chk=true;
						for(int i=0;i<list.size();i++)
						{
							if(String.valueOf(list.get(i).getValue()).equalsIgnoreCase(rr.getString("center")))
							{
								chk=false;
								break;
							}
						}
						
						if(chk==true)
						{
							SelectItem si=new SelectItem();
							
							si.setLabel(centerNameById(rr.getString("center"), conn)+System.lineSeparator()); //+", Staff Name: "+dsaNameById(rr.getString("dsacode"), conn)
							si.setValue(rr.getString("center"));
							
							list.add(si);
							
						}
					}
					else
					{
						SelectItem si=new SelectItem();
						
						si.setLabel(centerNameById(rr.getString("center"), conn)+System.lineSeparator()); //+", Staff Name: "+dsaNameById(rr.getString("dsacode"), conn)
						si.setValue(rr.getString("center"));
						
						list.add(si);
					}
				}	
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}
	
	
	public ArrayList<UserInfo> centerListForCenterMeeting2(int branchId,Date startDate) 
	{
		int count=1;
		startDate.setHours(0);
		startDate.setMinutes(0);
		startDate.setSeconds(0);
		ArrayList<UserInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from grouploan where status='Approve' and paidStatus='unpaid'  ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				ArrayList<String> dList=loanEmiStrDateList(rr.getInt("frequency"), rr.getInt("terms"), rr.getDate("emi_due_date"),rr.getDate("approvalDate"), rr.getString("sub_loan_no"), conn);
				
				if(dList.contains(sf.format(startDate)))
				{
					if(list.size()>0)
					{
						boolean  chk=true;
						for(int i=0;i<list.size();i++)
						{
							if(String.valueOf(list.get(i).getCenterId()).equalsIgnoreCase(rr.getString("center")))
							{
								chk=false;
								break;
							}
						}
						
						if(chk==true)
						{
							UserInfo uu=new UserInfo();
							
							uu.setSno(count++);
							uu.setStrPayOutDate(sf.format(startDate));
							uu.setDsaCode("Staff Name: "+dsaNameById(rr.getString("dsacode"), conn));
							uu.setCenterCode(centerCodeByCenterId(rr.getString("center"), conn));	
							uu.setCenterName(centerNameByCenterId(rr.getString("center"), conn));
							uu.setCenterId(rr.getString("center"));
							uu.setDayOfWeek(new SimpleDateFormat("EE").format(startDate));
							
							list.add(uu);
							
						}
					}
					else
					{
						UserInfo uu=new UserInfo();
						
						uu.setSno(count++);
						uu.setStrPayOutDate(sf.format(startDate));
						uu.setDsaCode("Staff Name: "+dsaNameById(rr.getString("dsacode"), conn));
						uu.setCenterCode(centerCodeByCenterId(rr.getString("center"), conn));	
						uu.setCenterName(centerNameByCenterId(rr.getString("center"), conn));
						uu.setDayOfWeek(new SimpleDateFormat("EE").format(startDate));
						
						list.add(uu);
					}
				}	
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}
	
	
	// MIS Work Start
	
	public ArrayList<InstallmentInfo> misDepositList(UserInfo user_info,Connection conn) 
	{
		int count=1;
		ArrayList<InstallmentInfo> list=new ArrayList<>();
		double intr=user_info.getMaturity_value()-user_info.getInstallment_amount();
		double monthlyAmount=intr/user_info.getTerms();
		monthlyAmount=Double.parseDouble(df.format(monthlyAmount));
		double returnInterest=returnMisInterestAmount(user_info.getUser_no(), conn);
		double total=0;
		for(int i=0; i<user_info.getTerms(); i++)
		{
			InstallmentInfo ff=new InstallmentInfo();
			Date startDate=user_info.getOffice_date();
			startDate.setMonth(startDate.getMonth()+1);
			
			ff.setSno(count++);
			ff.setCalc_interest(monthlyAmount);
			ff.setInstlmntDate(startDate);
			ff.setIns_date(sf.format(ff.getInstlmntDate()));
			if(returnInterest>=monthlyAmount)
			{
				ff.setPaidAmount(monthlyAmount);
				ff.setStatus("Paid");
			}
			else
			{
				ff.setPaidAmount(returnInterest);
				ff.setStatus("Pending");
			}
			total+=monthlyAmount;
			ff.setTot_sum(Double.parseDouble(df.format(total)));
			
			if(returnInterest>=monthlyAmount)
			{
				returnInterest=returnInterest-monthlyAmount;
			}
			
			
			list.add(ff);
		}
		
		return list;
	}
	
	public double returnMisInterestAmount(String user_no,Connection conn)
    {
		Statement st=null; ResultSet rr=null;
        try
        {
             st=conn.createStatement();
            String qq="select sum(credit_amount) from payment_receipt where receipt_status='approved' and user_no='"+user_no+"' and chequeStatus='cleared' ";
             rr=st.executeQuery(qq);
            if(rr.next())
            {
                return rr.getDouble("sum(credit_amount)");
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
        return 0;
    }
	
	
	 public ArrayList<InstallmentInfo> misPaymentList(int branchId,Connection conn) 
		{
			DecimalFormat decObj=new DecimalFormat("##.##");
			SimpleDateFormat dateObj=new SimpleDateFormat("dd/MM/yyyy");
			
			ArrayList<InstallmentInfo> list=new ArrayList<>();
			int count=1;
			Statement st=null; ResultSet rs=null;
			try
			{
					 st=conn.createStatement();
					String query="select * from customer_info inner join shareholder_info on customer_info.shareHolderNo=shareholder_info.shareholderno where customer_info.account_status='active' and scheme_type='MIS'";
					if(branchId!=-1)
					{
						query+=" and customer_info.branch_id='"+branchId+"' ";
					}
					rs = st.executeQuery(query);
					while (rs.next()) 
					{
						
						double intr=rs.getDouble("maturity_value")-rs.getDouble("installment_amount");
						double monthlyAmount=intr/rs.getInt("terms");
						double returnInterest=returnMisInterestAmount(rs.getString("user_no"), conn);
						int frequency=rs.getInt("frequency");
						double total=0;
						Date  startDate=rs.getDate("Office_date");
						int k=1;
						if(frequency==12)
	                    {
	                        startDate.setMonth(startDate.getMonth()-1);
	                    }
						double terms =rs.getInt("terms");
						for(int i=1; i<= rs.getInt("terms"); i++)
						{
							InstallmentInfo ff=new InstallmentInfo();
							Date dt=startDate;
							if(frequency==12)
                         {
                             dt.setMonth(dt.getMonth()+1);
                            
                         }
					
							ff.setSno(count++);
							ff.setCalc_interest(monthlyAmount);
							ff.setIns_date(dateObj.format(dt));
							ff.setInstlmntDate(dateObj.parse(ff.getIns_date()));
							
							if(returnInterest>=monthlyAmount)
							{
								
								ff.setPaidAmount(monthlyAmount);
								ff.setStatus("Paid");
							}
							else
							{
								ff.setPaidAmount(monthlyAmount);
								ff.setStatus("Pending");
							}
							total+=monthlyAmount;
							ff.setTot_sum(total);
							
							if(returnInterest>=monthlyAmount)
							{
								returnInterest=returnInterest-monthlyAmount;
							}
							
							ff.setUser_no(rs.getString("user_no"));
							list.add(ff);
						}
						
						
					}
					
			}
			
			catch (Exception e) 
			{
				e.printStackTrace();
			}
			finally
			{
				try {
					if(st!=null)
					{
						st.close();
					}
					if(rs!=null)
					{
						rs.close();
					}
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
			return list;
		}
	    
	    public double paidMISInterestBetweenDates(int branchId,Date startDate, Date endDate, Connection conn) 
		{
		 String start=sdfForDb.format(startDate);
		 String end=sdfForDb.format(endDate);
			Statement st=null; ResultSet rr=null;
			try
			{
				 st=conn.createStatement();
				String qq="select sum(credit_amount) from payment_receipt where chequeStatus='cleared' and date>='"+start+"' and date<='"+end+"' and receipt_status='approved' ";
				 rr=st.executeQuery(selectQueWithBranch(qq,branchId));
				if(rr.next())
				{
					return rr.getDouble("sum(credit_amount)");
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			finally
			{
				try {
					if(st!=null)
					{
					st.close();	
					}
					if(rr!=null)
					{
						rr.close();
					}
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
			return 0;
		}

	public int savingAppUserTransferEntry(String acc1, String searchNo, String amount, String shno,int branchId, Connection conn) 
	{
		String dt=sdfForDb.format(new Date());
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="insert into saving_user_transfer(account_one, account_two, amount, transfer_date, account_two_shno,branch_id) values('"+acc1+"','"+searchNo+"','"+amount+"',"
					+ "'"+dt+"', '"+shno+"','"+branchId+"') ";
			////System.out.println(qq);
			int i=st.executeUpdate(qq);
			return i;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	public ArrayList<SavingAccountInfo> savingAppUserTransferList(String acc,Connection conn) 
	{
		ArrayList<SavingAccountInfo> list=new ArrayList<>();
		int count=1;
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from saving_user_transfer where account_one='"+acc+"' ";
			rr=st.executeQuery(qq);
			while(rr.next())
			{
				SavingAccountInfo ff=new SavingAccountInfo();
				
				ff.setSno(count++);
				ff.setAccountNo(rr.getString("account_two"));
				ff.setAmount(rr.getDouble("amount"));
				ff.setEntryDate(rr.getDate("transfer_date"));
				ff.setStrEntryDate(sf.format(rr.getDate("transfer_date")));
				ff.setFirst_applicant_name(applicantNameByShareHolderNo(rr.getString("account_two_shno"), conn));
				
				list.add(ff);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}

	public ArrayList<SelectItem> highMarkTableList(String columnType,Connection conn) 
	{
		ArrayList<SelectItem> list=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from high_mark_table where column_type='"+columnType+"' ";
		    rr=st.executeQuery(qq);
		    while(rr.next())
		    {
		    	SelectItem ss=new SelectItem();
		    	
		    	ss.setLabel(rr.getString("column_value")+" - "+rr.getString("column_label"));
		    	ss.setValue(rr.getString("column_value"));
		    	
		    	list.add(ss);
		    }
		}
		
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}
	
	public void updateMessageStatus(String msgStatus) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update message_api set message_status='"+msgStatus+"'  ";
			st.executeUpdate(qq);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public String dsaCodeByEmpUserId(String userId, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select dsacode from employee where uname='"+userId+"' and status='active' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("dsacode");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return null;
	}
	
	public String empUserIdByDsaCode(String dsaCode, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select uname from employee where dsacode='"+dsaCode+"' and status='active' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("uname");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}
	
	public String loanCloseDate(String loanNo,Connection conn)
	{
		Statement st=null; ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select pay_date from loanpayment where loanNo='"+loanNo+"' and receipt_status='approved' and chequeStatus='cleared' and emi_no='-1' ";
			// // // ////System.out.println(qq);
			 rr=st.executeQuery(qq);
			if(rr.next())
			{
				return sf.format(rr.getDate("pay_date"));
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return null;
	}
	
	public String loanLabelByLoanValue(String loanType)
	{
		if(loanType!=null && !loanType.equalsIgnoreCase(""))
		{
			if(loanType.equalsIgnoreCase("personalloan"))
			{
				return "Personal Loan";
			}
			else if(loanType.equalsIgnoreCase("grouploan"))
			{
				return "Group Loan";
			}
			else if(loanType.equalsIgnoreCase("secure_loan"))
			{
				return "Secure Loan";
			}
			else if(loanType.equalsIgnoreCase("business_loan"))
			{
				return "Business Loan";
			}
		}
		return "";
	}
	
	public String loanValueByLoanLabel(String loanType)
	{
		if(loanType!=null && !loanType.equalsIgnoreCase(""))
		{
			if(loanType.equalsIgnoreCase("Personal Loan"))
			{
				return "personalloan";
			}
			else if(loanType.equalsIgnoreCase("Group Loan"))
			{
				return "grouploan";
			}
			else if(loanType.equalsIgnoreCase("Secure Loan"))
			{
				return "secure_loan";
			}
			else if(loanType.equalsIgnoreCase("Business Loan"))
			{
				return "business_loan";
			}
		}
		return "";
	}
	
	public int deleteQueryTableOldData(Connection conn) 
	{
		int i=0;
	
		Date date=new Date();
		date.setDate(date.getDate()-7);
		Timestamp stdt=new Timestamp(date.getTime());
		stdt.setNanos(0);
		String strt=String.valueOf(stdt).substring(0, 10);
		try
		{
			Statement st=conn.createStatement();
			String query="delete from query_table  where query_time <='"+strt+"' ";
			st.executeUpdate(query);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}
	
	
	public int regRequest(int branchId, Date regDate, String name, String fatherName, String relation, Date dob, String mobileNo, String address, String nomineeName, 
			String nomineeRelation, String memberPhoto, String aadharFrontDoc1Path, String doc2, String voterIdFrontDoc3Path, String doc4, String doc5, String userId, String gender, String uniqueId, 
			String voterId, String maritalStatus, String signPhoto, String formPhoto, String doc6, String doc7, String doc8, String memberShipFees, String panNo, 
			String rationCardNo, String center, String latitude, String longitude, String area, String business, String businessPlace, String caste, String bankName,
			String bankAccountNo, String bankBranch, String bankIfsc,String aadharFrontDoc01,String voterIdBackDoc03) 
	{
		int j=0;
		String regDt=sdfForDb.format(regDate);
		String dobDt=sdfForDb.format(dob);
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			
			String query ="insert into reg_table(reg_date, name, father_name, relation, dob, mobile_no, address, nominee_name, nominee_relation, member_photo, doc1, "
					+ "doc2, doc3, doc4, doc5, user_id, gender, unique_id,voter_id, marital_status,branch_id, sign_photo, form_photo, doc6, doc7, doc8, membership_fees, "
					+ "pan_no, ration_card_no,center, latitude, longitude, area, business, business_place, caste, bank_name, bank_account_no, bank_branch, bank_ifsc,aadhar_back_doc01,voterId_back_doc03)"
					+ "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
					PreparedStatement st1 = conn.prepareStatement(query);
					
					st1.setString(1, regDt);
					st1.setString(2, name);
					st1.setString(3, fatherName);
					st1.setString(4, relation);
					st1.setString(5, dobDt);
					st1.setString(6, mobileNo);
					st1.setString(7, address);
					st1.setString(8, nomineeName);
					st1.setString(9, nomineeRelation);
					st1.setString(10, memberPhoto);
					st1.setString(11, aadharFrontDoc1Path);
					st1.setString(12, doc2);
					st1.setString(13, voterIdFrontDoc3Path);
					st1.setString(14, doc4);
					st1.setString(15, doc5);
					st1.setString(16, userId);
					st1.setString(17, gender);
					st1.setString(18, uniqueId);
					st1.setString(19, voterId);
					st1.setString(20, maritalStatus);
					st1.setInt(21, branchId);
					st1.setString(22, signPhoto);
					st1.setString(23, formPhoto);
					st1.setString(24, doc6);
					st1.setString(25, doc7);
					st1.setString(26, doc8);
					st1.setString(27, memberShipFees);
					st1.setString(28, panNo);
					st1.setString(29, rationCardNo);
					st1.setString(30, center);
					st1.setString(31, latitude);
					st1.setString(32, longitude);
					st1.setString(33, area);
					st1.setString(34, business);
					st1.setString(35, businessPlace);
					st1.setString(36, caste);
					st1.setString(37, bankName);
					st1.setString(38, bankAccountNo);
					st1.setString(39, bankBranch);
					st1.setString(40, bankIfsc);
					st1.setString(41,aadharFrontDoc01);
					st1.setString(42,voterIdBackDoc03);
					
					int i = st1.executeUpdate();
					if (i >= 1)
					//	//System.out.println(st1);
						j++;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return j;
	}

	public ArrayList<UserInfo> memberRegListByApp(String userId, Date startDate, Date endDate,int branchId) 
	{
		System.out.println("member Reg list hit");
		System.out.println("executable userId :"+userId);
		
		DataBaseReportMethods dbrm=new DataBaseReportMethods();
		String qq="";
		String sdt=sdfForDb.format(startDate);
		String edt=sdfForDb.format(endDate);
		int count=1;
		ArrayList<UserInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(userId.equalsIgnoreCase("all"))
			{
				qq="select * from reg_table where reg_date>='"+sdt+"' and reg_date<='"+edt+"'";
			}
			else
			{
				qq="select * from reg_table where reg_date>='"+sdt+"' and reg_date<='"+edt+"' and user_id='"+userId+"'";
			}
			qq=selectQueWithBranch(qq,branchId)+"order by reg_date desc";
			//System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			
			System.out.println("query :-"+qq);
			
			while(rr.next())
			{
				UserInfo uu=new UserInfo();
				
				uu.setSno(count++);
				uu.setId(rr.getString("id"));
				uu.setStrOffcDate(sf.format(rr.getDate("reg_date")));
				uu.setOffice_date(rr.getDate("reg_date"));
				uu.setStrdob(sf.format(rr.getDate("dob")));
				uu.setDob(rr.getDate("dob"));
				uu.setName(rr.getString("name"));
				uu.setFather_husband_name(rr.getString("father_name"));
				uu.setRelation(rr.getString("relation"));
				uu.setMobile(rr.getString("mobile_no"));
				uu.setAddress(rr.getString("address"));
				uu.setNominee_name(rr.getString("nominee_name"));
				uu.setNominee_relation(rr.getString("nominee_relation"));
				uu.setUserId(rr.getString("user_id"));
				uu.setStatus(rr.getString("status"));
				uu.setGender(rr.getString("gender"));
				uu.setUniqueId(rr.getString("unique_id"));
				uu.setVoterId(rr.getString("voter_id"));
				uu.setMaritalStatus(rr.getString("marital_status"));
				
				if(rr.getString("status").equalsIgnoreCase("inactive"))
				{
					uu.setDisable(true);
				}
				else
				{
					uu.setDisable(false);
				}
				
				uu.setApplicant_photo(rr.getString("member_photo"));
				uu.setSignPhoto(rr.getString("sign_photo"));
				uu.setFormPhoto(rr.getString("form_photo"));
				uu.setDoc1Path(rr.getString("doc1"));
				uu.setDoc2Path(rr.getString("doc2"));
				uu.setDoc3Path(rr.getString("doc3"));
				uu.setDoc4Path(rr.getString("doc4"));
				uu.setDoc5Path(rr.getString("doc5"));
				uu.setDoc6Path(rr.getString("doc6"));
				uu.setDoc7Path(rr.getString("doc7"));
				uu.setDoc8Path(rr.getString("doc8"));
				
				uu.setArea(rr.getString("area"));
				uu.setBusiness(rr.getString("business"));
				uu.setBusinessPlace(rr.getString("business_place"));
				uu.setCaste(rr.getString("caste"));
				
				uu.setBrideFhname(rr.getString("bride_fhname"));
				uu.setBrideMname(rr.getString("bride_mname"));
				uu.setBrideAddress(rr.getString("bride_address"));
				uu.setBrideBusiness(rr.getString("bride_business"));
				uu.setBrideBusinessPlace(rr.getString("bride_business_place"));
				uu.setBrideMobileNo(rr.getString("bride_mobile_no"));
				uu.setBrideRemark(rr.getString("bride_remark"));
				
				if(rr.getDate("loan_date")!=null)
				{
					uu.setStrLoanDate(sf.format(rr.getDate("loan_date")));
				}
				
				uu.setLoanAmount(rr.getDouble("loan_amount"));
				uu.setLoanInWords(dbrm.numberToWords(rr.getInt("loan_amount")));
				uu.setTerms(rr.getInt("terms"));
				uu.setInstallment_amount(rr.getDouble("emi"));
				if(rr.getString("frequency")!=null)
				{
					uu.setFrequencyLabel(frequencyLabel(rr.getString("frequency")));
				}
				
				if(rr.getDate("first_emi_date")!=null)
				{
					uu.setStrFirstEmiDate(sf.format(rr.getDate("first_emi_date")));
				}
					
				uu.setLoanRemark(rr.getString("loan_remark"));
				uu.setCenterId(rr.getString("center"));
				uu.setCenterName(centerNameByCenterId(rr.getString("center"), conn));
				uu.setCenterCode(centerCodeByCenterId(rr.getString("center"), conn));
				uu.setAge(uu.getOffice_date().getYear()-uu.getDob().getYear());
				uu.setPAN(rr.getString("pan_no"));
				uu.setRationNo(rr.getString("ration_card_no"));
				uu.setTotalAmount(rr.getDouble("emi")*rr.getInt("terms"));
				uu.setInterest(uu.getTotalAmount()-uu.getLoanAmount());
				uu.setBank_name(rr.getString("bank_name"));
				uu.setBank_accountNo(rr.getString("bank_account_no"));
				uu.setBranch(rr.getString("bank_branch"));
				uu.setBankIfsc(rr.getString("bank_ifsc"));
				uu.setLatitude(rr.getString("latitude"));
				uu.setLongitude(rr.getString("longitude"));
				uu.setAadharBackDoc01(rr.getString("aadhar_back_doc01"));
				uu.setVoterIdBackDoc03(rr.getString("voterId_back_doc03"));
				
				list.add(uu);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}
    
	public ArrayList<UserInfo> memberRegListByAppCenterWise(String userId, String center,int branchId) 
	{
		String qq="";
		int count=1;
		ArrayList<UserInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(userTypeByUserId(userId, conn).equalsIgnoreCase("admin"))
			{
				qq="select * from reg_table where center='"+center+"' ";
			}
			else
			{
				qq="select * from reg_table where center='"+center+"' and user_id='"+userId+"'";
			}
			qq=selectQueWithBranch(qq,branchId)+"order by reg_date desc";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				UserInfo uu=new UserInfo();
				
				uu.setSno(count++);
				uu.setId(rr.getString("id"));
				uu.setStrOffcDate(sf.format(rr.getDate("reg_date")));
				uu.setOffice_date(rr.getDate("reg_date"));
				uu.setStrdob(sf.format(rr.getDate("dob")));
				uu.setDob(rr.getDate("dob"));
				uu.setName(rr.getString("name"));
				uu.setFather_husband_name(rr.getString("father_name"));
				uu.setRelation(rr.getString("relation"));
				uu.setMobile(rr.getString("mobile_no"));
				uu.setAddress(rr.getString("address"));
				uu.setNominee_name(rr.getString("nominee_name"));
				uu.setNominee_relation(rr.getString("nominee_relation"));
				uu.setUserId(rr.getString("user_id"));
				uu.setStatus(rr.getString("status"));
				uu.setGender(rr.getString("gender"));
				uu.setUniqueId(rr.getString("unique_id"));
				uu.setVoterId(rr.getString("voter_id"));
				uu.setMaritalStatus(rr.getString("marital_status"));
				
				if(rr.getString("status").equalsIgnoreCase("inactive"))
				{
					uu.setDisable(true);
				}
				else
				{
					uu.setDisable(false);
				}
				
				uu.setApplicant_photo(rr.getString("member_photo"));
				uu.setSignPhoto(rr.getString("sign_photo"));
				uu.setFormPhoto(rr.getString("form_photo"));
				uu.setDoc1Path(rr.getString("doc1"));
				uu.setDoc2Path(rr.getString("doc2"));
				uu.setDoc3Path(rr.getString("doc3"));
				uu.setDoc4Path(rr.getString("doc4"));
				uu.setDoc5Path(rr.getString("doc5"));
				uu.setDoc6Path(rr.getString("doc6"));
				uu.setDoc7Path(rr.getString("doc7"));
				uu.setDoc8Path(rr.getString("doc8"));
				
				list.add(uu);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}
	
	public int updateStatusInRegTable(String string, String id) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update reg_table set status='"+string+"' where id='"+id+"' ";
			int i=st.executeUpdate(qq);
			return i;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}

	public String checkLoginIdStatus(String userId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select status from login where userid='"+userId+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("status");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return "inactive";
	}
    
	public ArrayList<EmpInfo> gpsTrackingListByEmpUserId(String empUserId, Date searchDate) 
	{
		int count=1;
		String searchDt=sdfForDb.format(searchDate);
		ArrayList<EmpInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from gps_tracking where user_id='"+empUserId+"' and tracking_date like '"+searchDt+"%' ";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				EmpInfo ee=new EmpInfo();
				
				ee.setSno(count++);
				ee.setLatitude(rr.getString("latitude"));
				ee.setLongitude(rr.getString("longitude"));
				ee.setStrTrackingDate(rr.getString("tracking_date"));
				
				list.add(ee);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}	
		return list;
	}

	public int updateDsaInDepositAccount(String id, String newDsaCode,Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="update customer_info set dsa_code='"+newDsaCode+"' where id='"+id+"'  ";
			int i=st.executeUpdate(qq);
			return i;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	public int updateDsaInLoanAccount(String id, String newDsaCode, String loanType,Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="update "+loanType+" set dsacode='"+newDsaCode+"' where id='"+id+"'  ";
			int i=st.executeUpdate(qq);
			return i;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	
	public double withdrwalValueBetweenDateByAccNo(String accountNo, Date date1, Date date2,Connection conn) 
	{
		String sDate=sdfForDb.format(date1.getTime());
		String eDate=sdfForDb.format(date2.getTime());
		 Statement stt=null;
		 ResultSet ss=null;
		 try
         {
			stt=conn.createStatement();
			String query="select sum(amount) as totalAmount from customer_withdrwal where chequeStatus='cleared' and status='approved' and account_no='"+accountNo+"' and date>='"+sDate+"' and date<='"+eDate+"' ";
			ss=stt.executeQuery(query);
			 
			 if(ss.next())
			 {
				return ss.getDouble("totalAmount");
			 }
         }
         catch (Exception e) 
         {
        	 e.printStackTrace();
         }finally
 		{
 			try {
 				if(stt!=null)
 				{
 					stt.close();
 				}
 				if(ss!=null)
 				{
 					ss.close();
 				}
 			} catch (Exception e2) {
 				// TODO: handle exception
 		
		 	}
		 }
		 return 0;
	}

	public double depositValueBetweenDateByAccNo(String accountNo, Date date1, Date date2,String type,Connection conn) 
	{
			String sDate=sdfForDb.format(date1.getTime());
			String eDate=sdfForDb.format(date2.getTime());
			Statement stt=null;ResultSet ss=null;
			
		 try
         {
			  stt=conn.createStatement();
			 String qq="select sum(amount) as totalAmount from customer_deposit where chequeStatus='cleared' and status='approved'  and account_no='"+accountNo+"' and date>='"+sDate+"' and date<='"+eDate+"'";
			 if(!type.equalsIgnoreCase("both") && !type.equalsIgnoreCase("all") && !type.equalsIgnoreCase(""))
			 {
				 qq+=" and type='"+type+"' ";
			 }
			 ss=stt.executeQuery(qq);
			 if(ss.next())
			 {
				 return ss.getDouble("totalAmount");
			 }
         }
         catch (Exception e) 
         {
        	 e.printStackTrace();
         }finally
 		{
 			try {
 				if(stt!=null)
 				{
 					stt.close();
 				}
 				if(ss!=null)
 				{
 					ss.close();
 				}
 			} catch (Exception e2) {
 				// TODO: handle exception
 		
 			}
 		}
		 return 0;
	}

	
	// NACH Mandate Module
	
	public int addNachMandateRegDetail(String utilityCode, String mandateType,
			String umrnNo, Date mandateDate, String accountNo,
			String accountType, String ifscCode, String bankName,
			String collectionType, int amount, String reference1,
			String reference2, String frequency, Date debitStartDate,
			Date debitEndDate, String untillCancel, String name,
			String phoneNo, String mobileNo, String mailId, String shareHolderNo, String userId,int branchId) 
	{
		Timestamp tt=null;
		if(debitEndDate!=null)
		{
			tt=new Timestamp(debitEndDate.getTime());
			tt.setHours(0);tt.setMinutes(0);tt.setSeconds(0);tt.setNanos(0);
		}
		String strMandateDate=sdfForDb.format(mandateDate);
		String sDate=sdfForDb.format(debitStartDate);
		
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			String qq="insert into nach_detail(utility_code, mandate_type, umrn_no, mandate_date, account_no, account_type, ifsc_code, bank_name, collection_type, "
					+ "amount, reference1, reference2, frequency, debit_start_date, debit_end_date, untill_cancel, name, phone_no, mobile_no, email_id, share_holder_no, "
					+ "user_id,branch_id) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ";
			PreparedStatement st1 = conn.prepareStatement(qq);
			st1.setString(1, utilityCode);
			st1.setString(2, mandateType);
			st1.setString(3, umrnNo);
			st1.setString(4, strMandateDate);
			st1.setString(5, accountNo);
			st1.setString(6, accountType);
			st1.setString(7, ifscCode);
			st1.setString(8, bankName);
			st1.setString(9, collectionType);
			st1.setInt(10, amount);
			st1.setString(11, reference1);
			st1.setString(12, reference2);
			st1.setString(13, frequency);
			st1.setString(14, sDate);
			st1.setTimestamp(15, tt);
			st1.setString(16, untillCancel);
			st1.setString(17, name);
			st1.setString(18, phoneNo);
			st1.setString(19, mobileNo);
			st1.setString(20, mailId);
			st1.setString(21, shareHolderNo);
			st1.setString(22, userId);
			st1.setInt(23, branchId);
			
			int i = st1.executeUpdate();
			return i;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}

	public boolean checkNachDetailByShareHolderNo(String shareHolderNo,Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from nach_detail where share_holder_no='"+shareHolderNo+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return false;
	}

	public ArrayList<NachInfo> viewNachRegData(String searchType,int branchId) 
	{
		int count=1;
		String qq="";
		ArrayList<NachInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			if(searchType.equalsIgnoreCase("all"))
			{
				qq="select * from nach_detail ";
			}
			else
			{
				qq="select * from nach_detail where status='"+searchType+"' ";
			}
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				NachInfo nn=new NachInfo();
				
				nn.setId(rr.getString("id"));
				nn.setSno(count++);
				nn.setUtilityCode(rr.getString("utility_code"));
				nn.setMandateType(rr.getString("mandate_type"));
				nn.setUmrnNo(rr.getString("umrn_no"));
				nn.setMandateDate(rr.getDate("mandate_date"));
				nn.setStrMandateDate(sf.format(rr.getDate("mandate_date")));
				nn.setAccountNo(rr.getString("account_no"));
				nn.setAccountType(rr.getString("account_type"));
				nn.setIfscCode(rr.getString("ifsc_code"));
				nn.setBankName(rr.getString("bank_name"));
				nn.setCollectionType(rr.getString("collection_type"));
				nn.setAmount(rr.getInt("amount"));
				nn.setReference1(rr.getString("reference1"));
				nn.setReference2(rr.getString("reference2"));
				nn.setFrequency(rr.getString("frequency"));
				nn.setDebitStartDate(rr.getDate("debit_start_date"));
				nn.setStrDebitStartDate(sf.format(rr.getDate("debit_start_date")));
				if(rr.getDate("debit_end_date")!=null)
				{
					nn.setDebitEndDate(rr.getDate("debit_end_date"));
					nn.setStrDebitEndDate(sf.format(rr.getDate("debit_end_date")));
				}
				
				nn.setUntillCancel(rr.getString("untill_cancel"));
				nn.setName(rr.getString("name"));
				nn.setPhoneNo(rr.getString("phone_no"));
				nn.setMobileNo(rr.getString("mobile_no"));
				nn.setMailId(rr.getString("email_id"));
				nn.setShareHolderNo(rr.getString("share_holder_no"));
				nn.setRemark(rr.getString("remark"));
				
				if(rr.getString("status").equalsIgnoreCase("pending"))
				{
					nn.setDisBtn(false);
				}
				else
				{
					nn.setDisBtn(true);
				}
				
				list.add(nn);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}

	public int updateNachMandateForm(String umrnNo, String remark, String status, String id) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update nach_detail set umrn_no='"+umrnNo+"', remark='"+remark+"', status='"+status+"' where id='"+id+"' ";
			int i=st.executeUpdate(qq);
			return i;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}

	public String nachDetailByColumnNameAndShareHolderNo(String columnName, String shareHolderNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select "+columnName+" from nach_detail where share_holder_no='"+shareHolderNo+"' and status='active' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString(columnName);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}

	public boolean checkUmrnNoDuplicacy(String umrnNo,int branchId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select umrn_no from nach_detail where umrn_no='"+umrnNo+"' and status='active' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return false;
	}
	

	public ArrayList<DailyCashInfo> viewDailyCashDetailData(Date submitDate,int branchId) 
	{
		ArrayList<DailyCashInfo> list=new ArrayList<>();
		String sDate=sdfForDb.format(submitDate);
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from daily_cash_detail where submit_date='"+sDate+"' ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				DailyCashInfo dd=new DailyCashInfo();
				
				dd.setNoteType(rr.getInt("note_type"));
				dd.setNoOfNote(rr.getInt("no_of_note"));
				dd.setAmount(rr.getInt("total"));
				
				list.add(dd);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return list;
	}

	public int insertDailyCashDetailData(ArrayList<DailyCashInfo> list,int branchId,Date submitDate) 
	{
		int i=0;
		String sDate=sdfForDb.format(submitDate);
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			for(DailyCashInfo dd: list)
			{
				Statement st=conn.createStatement();
				String qq="insert into daily_cash_detail(note_type, no_of_note, total, submit_date,branch_id) values('"+dd.getNoteType()+"', '"+dd.getNoOfNote()+"', '"+dd.getAmount()+"', '"+sDate+"','"+branchId+"')";
				i+=st.executeUpdate(qq);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return i;
	}

	public boolean checkReturnMaturedAmountDuplicacy(String user_no, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from returned_amount_info where user_no='"+user_no+"' and chequeStatus='cleared' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return false;
	}

	public boolean checkEntryOfSelectedDateForKalp(LoanInfo selectedRow, String methodName,Connection conn) 
	{
		HeaderBean hh=new HeaderBean();
		if(hh.getName().equalsIgnoreCase("KALPTARUSHIKHA NIDHI LIMITED"))
		{
			String sDate=sdfForDb.format(selectedRow.getOfficeDate().getTime());
			Statement st=null;
			ResultSet rr=null;
			String qq="";
			try
			{
				st=conn.createStatement();
				if(methodName.equalsIgnoreCase("depositMethod"))
				{
					qq="select * from payment_receipt where user_no='"+selectedRow.getLoanNo()+"' and date='"+sDate+"' and receipt_status='approved' ";
				}
				else if(methodName.equalsIgnoreCase("savingDepositMethod"))
				{
					qq="select * from customer_deposit where account_no='"+selectedRow.getLoanNo()+"' and date='"+sDate+"' and status='approved' ";
				}
				else if(methodName.equalsIgnoreCase("savingWithdrawMethod"))
				{
					qq="select * from customer_withdrwal where account_no='"+selectedRow.getLoanNo()+"' and date='"+sDate+"' and status='approved' ";
				}
				else
				{
					qq="select * from loanpayment where loanNo='"+selectedRow.getLoanNo()+"' and pay_date='"+sDate+"' and receipt_status='approved' ";
				}
				rr=st.executeQuery(qq);
				if(rr.next())
				{
					return true;
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			finally
			{
				try {
					if(st!=null)
					{
						st.close();
					}
					if(rr!=null)
					{
						rr.close();
					}
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
		}
		return false;
	}

	public ArrayList<SelectItem> paymentModeOptionList(Connection conn) 
	{
		ArrayList<SelectItem> payList=new ArrayList<>();
		
		SelectItem ss1=new SelectItem();
		ss1.setValue("Cash");
		ss1.setLabel("Cash");
		payList.add(ss1);
		
		SelectItem ss3=new SelectItem();
		ss3.setValue("Cheque");
		ss3.setLabel("Cheque");
		payList.add(ss3);
		
		SelectItem ss4=new SelectItem();
		ss4.setValue("NEFT");
		ss4.setLabel("NEFT");
		payList.add(ss4);
		
		SelectItem ss5=new SelectItem();
		ss5.setValue("RTGS");
		ss5.setLabel("RTGS");
		payList.add(ss5);
		
		SelectItem ss6=new SelectItem();
		ss6.setValue("IMPS");
		ss6.setLabel("IMPS");
		payList.add(ss6);
		
		SelectItem ss7=new SelectItem();
		ss7.setValue("NACH");
		ss7.setLabel("NACH/ECS");
		payList.add(ss7);
		
		SelectItem ss2=new SelectItem();
		ss2.setValue("Demand Draft");
		ss2.setLabel("Demand Draft");
		payList.add(ss2);
		
		SelectItem ss8=new SelectItem();
		ss8.setValue("UPI");
		ss8.setLabel("UPI");
		payList.add(ss8);

		return payList;
	}
	
	public ArrayList<SelectItem> freqCommanSelectItemList() 
	{
		ArrayList<SelectItem> freqList=new ArrayList<>();
		
		SelectItem ss1=new SelectItem();
		ss1.setValue("365");
		ss1.setLabel("Daily");
		freqList.add(ss1);
		
		SelectItem ss3=new SelectItem();
		ss3.setValue("52");
		ss3.setLabel("1 Week");
		freqList.add(ss3);
		
		SelectItem ss4=new SelectItem();
		ss4.setValue("36");
		ss4.setLabel("10 Days");
		freqList.add(ss4);
		
		SelectItem ss5=new SelectItem();
		ss5.setValue("26");
		ss5.setLabel("2 Week");
		freqList.add(ss5);
		
		SelectItem ss6=new SelectItem();
		ss6.setValue("24");
		ss6.setLabel("15 Days");
		freqList.add(ss6);
		
		SelectItem ss7=new SelectItem();
		ss7.setValue("13");
		ss7.setLabel("4 Week");
		freqList.add(ss7);
		
		SelectItem ss2=new SelectItem();
		ss2.setValue("12");
		ss2.setLabel("Monthly");
		freqList.add(ss2);
		
		SelectItem ss8=new SelectItem();
		ss8.setValue("4");
		ss8.setLabel("Quarterly");
		freqList.add(ss8);

		return freqList;
	}

	public int insertGroupLoanEmi(int branchId,ArrayList<LoanInfo> loanEMIList, String loanNo, String remark) 
	{
		int count=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq1="delete from grouploan_emi where sub_loan_no='"+loanNo+"' "; // Work when we update the data
			st.executeUpdate(qq1);
			
			for(LoanInfo ll:loanEMIList)
			{
				Date startDate=sf.parse(ll.getStrInstlmntDate());
				Timestamp ts=new Timestamp(startDate.getTime());
				String qq="insert into grouploan_emi(sub_loan_no, emi_no, emi_date,branch_id, remark) values('"+loanNo+"','"+ll.getSno()+"','"+ts+"','"+branchId+"',"
						+ " '"+remark+"') ";
				count+=st.executeUpdate(qq);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return count;
	}
	
	public void insertFifteenDayPlanGroupLoanEmi(int branchId,String loanNo, String remark, Date emiDueDate, int terms, Date secEmiDueDate) 
	{
		int count=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq1="delete from grouploan_emi where sub_loan_no='"+loanNo+"' "; // Work when we update the data
			st.executeUpdate(qq1);
			
			ArrayList<String> dateList=fifteenDaysLoanStrDateList(emiDueDate,secEmiDueDate, terms);
			for(int i=1;i<=dateList.size();i++)
			{
				String qq="insert into grouploan_emi(sub_loan_no, emi_no, emi_date,branch_id, remark) values('"+loanNo+"','"+i+"','"+dateList.get(i-1)+"','"+branchId+"',"
						+ " '"+remark+"') ";
				count+=st.executeUpdate(qq);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public ArrayList<SavingAccountInfo> withdrwalValueBetweenDate(String accountNo, Timestamp date1, Timestamp date2,Connection conn) 
	{
		 ArrayList<SavingAccountInfo> list=new ArrayList<>(); 
		 Statement stt=null;
		 ResultSet ss=null;
		 try
         {
			stt=conn.createStatement();
			String qq="select *,sum(amount) as totalAmount from customer_withdrwal where chequeStatus='cleared' and account_no='"+accountNo+"' and date between '"+date1+"' and '"+date2+"' group by date";
			ss=stt.executeQuery(qq);
			 while(ss.next())
			 {
				SavingAccountInfo info=new SavingAccountInfo();
			    info.setAccountNo(ss.getString("account_no"));
			    info.setEntryDate(ss.getDate("date"));
			    info.setAmount(ss.getDouble("amount"));
			    info.setFinalAmount(ss.getDouble("totalAmount"));
			    info.setStatus("withdrwal");
		        list.add(info);
			 }
         }
         catch (Exception e) 
         {
        	 e.printStackTrace();
         }
		 finally
 		 {
 			try {
 				if(stt!=null)
 				{
 					stt.close();
 				}
 				if(ss!=null)
 				{
 					ss.close();
 				}
 			} catch (Exception e2) {
 				// TODO: handle exception
 		
 			}
 		 }
		 return list;
	}

	public ArrayList<SavingAccountInfo> depositValueBetweenDate(String accountNo, Timestamp date1, Timestamp date2,Connection conn) 
	{
		 ArrayList<SavingAccountInfo> list=new ArrayList<>(); 
		 Statement stt=null;ResultSet ss=null;
		 try
         {
			 stt=conn.createStatement();
			 String qq="select *,sum(amount) as totalAmount from customer_deposit where chequeStatus='cleared' and type='deposit' and account_no='"+accountNo+"' and date between '"+date1+"' and '"+date2+"' group by date";
			 ss=stt.executeQuery(qq);
			 while(ss.next())
			 {
				SavingAccountInfo info=new SavingAccountInfo();
			    info.setAccountNo(ss.getString("account_no"));
			    info.setEntryDate(ss.getDate("date"));
			    info.setAmount(ss.getDouble("amount"));
			   	info.setFinalAmount(ss.getDouble("totalAmount"));
			    info.setStatus("deposit");
		        list.add(info);
			 }
         }
         catch (Exception e) 
         {
        	 e.printStackTrace();
         }
		 finally
 			{
 			try {
 				if(stt!=null)
 				{
 					stt.close();
 				}
 				if(ss!=null)
 				{
 					ss.close();
 				}
 			} catch (Exception e2) {
 				// TODO: handle exception
 		
 			}
 			}
		 return list;
	}

	public double schemeWiseCurrentBalance(String schemeType,int branchId,Connection conn) 
	{
		double total=0;
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
             String qq ="select user_no from customer_info where scheme_type='"+schemeType+"' and account_status in ('active','close') and paid_status='unpaid'";
             rr=st.executeQuery(selectQueWithBranch(qq,branchId));
		     while(rr.next())
		     {
		    	 total+=paidAmountByUser(rr.getString("user_no"), conn);
		     }	 
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}	
		return total;
	}
	
	
	public ArrayList<MembersOdInfo> allMemberAllAccountNoList(int branchId) 
	{
		int count=1;
		ArrayList<MembersOdInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select shareholderno, first_applicantName, father_husband_name,crNo,office_date from shareholder_info ";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				MembersOdInfo mm=new MembersOdInfo();
				
				mm.setSno(count++);
				mm.setShareHolderNo(rr.getString("shareholderno"));
				mm.setName(sf.format(rr.getDate("office_date"))+" - "+rr.getString("first_applicantName"));
				mm.setFatherHusbandName(rr.getString("father_husband_name"));
				mm.setShareCertificationNo(rr.getString("crNo"));
				mm.setPlAccountNo(loanAccountNoMemberWise("personalloan",mm.getShareHolderNo(), conn));
				mm.setSlAccountNo(loanAccountNoMemberWise("secure_loan",mm.getShareHolderNo(), conn));
				mm.setGlAccountNo(loanAccountNoMemberWise("grouploan",mm.getShareHolderNo(), conn));
				mm.setDdAccountNo(depositAccountNoMemberWise("DD",mm.getShareHolderNo(), conn));
				mm.setRdAccountNo(depositAccountNoMemberWise("RD",mm.getShareHolderNo(), conn));
				mm.setFdAccountNo(depositAccountNoMemberWise("FD",mm.getShareHolderNo(), conn));
				mm.setMisAccountNo(depositAccountNoMemberWise("MIS",mm.getShareHolderNo(), conn));
				mm.setSvAccountNo(savingAccountNoMemberWise(mm.getShareHolderNo(), conn));
				
				list.add(mm);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}

	private String loanAccountNoMemberWise(String tableName,String shareHolderNo, Connection conn) 
	{
		String qq="", detail="";
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			if(tableName.equalsIgnoreCase("grouploan"))
			{
				qq="select sub_loan_no, status, paidStatus, approvalDate from grouploan where teamLeader='"+shareHolderNo+"' ";
			}
			else
			{
				qq="select loanNo, status, paidStatus, approvalDate from "+tableName+" where shareholderno='"+shareHolderNo+"' ";
			}
			rr=st.executeQuery(qq);
			while(rr.next())
			{
				if(tableName.equalsIgnoreCase("grouploan"))
				{
					if(rr.getDate("approvalDate")!=null)
					{
						detail+=rr.getString("sub_loan_no")+" - "+rr.getString("status")+" - "+sf.format(rr.getDate("approvalDate"))+" - "+rr.getString("paidStatus")+", ";
					}
					else
					{
						detail+=rr.getString("sub_loan_no")+" - "+rr.getString("status")+" - "+rr.getString("paidStatus")+", ";
					}
				}
				else
				{
					if(rr.getDate("approvalDate")!=null)
					{
						detail+=rr.getString("loanNo")+" - "+rr.getString("status")+" - "+sf.format(rr.getDate("approvalDate"))+" - "+rr.getString("paidStatus")+", "; 
					}
					else
					{
						detail+=rr.getString("loanNo")+" - "+rr.getString("status")+" - "+rr.getString("paidStatus")+", "; 
					}
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return detail;
	}
	
	private String depositAccountNoMemberWise(String depositType,String shareHolderNo,Connection conn) 
	{
		String detail="";
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			String qq="select user_no, account_status, paid_status, office_date from customer_info where shareHolderNo='"+shareHolderNo+"' and scheme_type='"+depositType+"' ";
			rr=st.executeQuery(qq);
			while(rr.next())
			{
				detail+=rr.getString("user_no")+" - "+rr.getString("account_status")+" - "+sf.format(rr.getDate("office_date"))+" - "+rr.getString("paid_status")+", "; 
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return detail;
	}

	private String savingAccountNoMemberWise(String shareHolderNo,Connection conn) 
	{
		String detail="";
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			String qq="select accountNo,accountStatus,openDate from savingaccount where shareHolderNo='"+shareHolderNo+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				detail+=rr.getString("accountNo")+" - "+rr.getString("accountStatus")+" - "+sf.format(rr.getDate("openDate")); 
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return detail;
	}

	public String centerIdByGroupLoanNo(String subLoanNo,int branchId,Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select center from grouploan where sub_loan_no='"+subLoanNo+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("center");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "0";
	}

	public int insertJournalEntry(int branchId,Date bookDate, String transType, String ledgerName, double amount, String remark) 
	{
		String dt=sdfForDb.format(bookDate);
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="insert into journal_entry(book_date, trans_type, ledger_name, amount, remark,branch_id) values('"+dt+"','"+transType+"','"+ledgerName+"','"+amount+"',"
					+ "'"+remark+"','"+branchId+"')";
			int i=st.executeUpdate(qq);
			return i;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}

	public ArrayList<JournalInfo> viewJournalEntry(int branchId) 
	{
		
		ArrayList<JournalInfo> list=new ArrayList<>();
		int count=1;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from journal_entry";
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				JournalInfo jj=new JournalInfo();
				
				jj.setSno(count++);
				jj.setId(rr.getString("id"));
				jj.setStrBookDate(sf.format(rr.getDate("book_date")));
				jj.setBookDate(rr.getDate("book_date"));
				jj.setTransType(rr.getString("trans_type"));
				jj.setLedgerName(rr.getString("ledger_name"));
				jj.setAmount(rr.getDouble("amount"));
				jj.setRemark(rr.getString("remark"));
				jj.setStatus(rr.getString("status"));
				if(jj.getStatus().equalsIgnoreCase("active"))
				{
					jj.setDisBtn(false);
				}
				else
				{
					jj.setDisBtn(true);
				}
				list.add(jj);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return list;
	}

	public int deleteJournalEntry(String id) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="delete from journal_entry where id='"+id+"' ";
			int i=st.executeUpdate(qq);
			return i;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}

	public double bookedIncomeExpenseAmount(String string, int branchId, Date startDate, Date endDate, Connection conn) 
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount) from journal_entry where trans_type='"+string+"' and book_date>='"+sDate+"' and book_date<='"+eDate+"' ";
			//System.out.println(qq);
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	public int totalActiveLoan(String tableName, String dsaCode, int branchId, Connection con) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=con.createStatement();
			String qq="";
			if(dsaCode.equalsIgnoreCase("") || dsaCode.equalsIgnoreCase("all") || dsaCode.equalsIgnoreCase("-1"))
			{
				qq="select count(*) from "+tableName+" where status='Approve' and paidStatus='unpaid' ";
			}
			else
			{
				qq="select count(*) from "+tableName+" where status='Approve' and paidStatus='unpaid' and dsacode='"+dsaCode+"' ";
			}
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getInt("count(*)");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	public int totalLoan(String string,int branchId, Connection con) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=con.createStatement();
			String qq="select count(*) from "+string+" where status!='notApprove' ";
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getInt("count(*)");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	

	public int totalCloseLoan(String string,int branchId, Connection con) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			 st=con.createStatement();
			String qq="select count(*) from "+string+" where status='Approve' and paidStatus='paid' ";
			rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			if(rr.next())
			{
				return rr.getInt("count(*)");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	public String dsaCodeFromCenterTable(String center,int branchId) 
	{
		Statement st=null;
		ResultSet rr=null;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			st=conn.createStatement();
			String qq="select dsacode from center where id='"+center+"' ";
			//System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				if(rr.getString("dsacode")!=null)
				{
					return rr.getString("dsacode");
				}
				else
				{
					return "";
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}

	public void updateDsaInGroupLoanCenterWise(String center, String dsaCode,Connection conn) 
	{
		Statement st=null;
		try
		{
			st=conn.createStatement();
			String qq="update grouploan set dsacode='"+dsaCode+"' where center='"+center+"'";
			st.executeUpdate(qq);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}

	public String columnValueByColumnNameFromFirmDetailTable(String columnName,int branchId,Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		
		try
		{
			st=conn.createStatement();
			String query="select "+columnName+" from firm_detail where id ='"+branchId+"'";
			rr=st.executeQuery(query);
			if(rr.next())
			{
				return rr.getString(columnName);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}


	public String branchUserId(String userId, String password, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select id from login where userid='"+userId+"' and password='"+password+"' and status='active' ";
			//System.out.println(query);
			rr=st.executeQuery(query);
			if(rr.next())
			{
				////System.out.println(rr.getString("id"));
				return rr.getString("id");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}
	
	public int branchIdFromByUserIdFromLoginTable(String userId, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select branch_id from login where userid='"+userId+"' and status='active' ";
			rr=st.executeQuery(query);
			if(rr.next())
			{
				return rr.getInt("branch_id");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	/*public String branchUserId(String userId, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select id from login where userid='"+userId+"' and status='active' ";
			rr=st.executeQuery(query);
			if(rr.next())
			{
				return rr.getString("id");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}*/
	
	
	
	//check loan no going to start form 1 or from last enter in branch
	public String checkContinityLoanNo(int branchId,Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select branch_start from firm_detail where id='"+branchId+"'";
			rr=st.executeQuery(query);
			if(rr.next())
			{
				return rr.getString("branch_start");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}
	
	public String checkContinitySchemeNo(int branchId,Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select scheme_start from firm_detail where id='"+branchId+"'";
			rr=st.executeQuery(query);
			if(rr.next())
			{
				return rr.getString("scheme_start");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}

	public ArrayList<BankInfo> balanceSheetHeads(Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		ArrayList<BankInfo> list =new  ArrayList<BankInfo>();
		try
		{
			st=conn.createStatement();
			String query="select liabilities_head,assets_head from balance_sheet where branch_id='1' limit 11";
			rr=st.executeQuery(query);
			while(rr.next())
			{
				BankInfo obj = new BankInfo();
				obj.setAssetName(rr.getString("assets_head"));
				obj.setLibilityName(rr.getString("liabilities_head"));
				list.add(obj);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}


	public List<SelectItem> branchList(String userId, Connection con)
	{   
		
		List<SelectItem> list = new ArrayList<SelectItem>();
		Statement st = null; ResultSet rs = null;
		//String uId = branchUserId(userId,con);
		try 
		{ 
		  st=con.createStatement();
		  String query = "select branch_id,branch_name from branch_allocate_table where user_id='"+userId+"' and status='active' ";
		//  //System.out.println(query);
		  rs=st.executeQuery(query);
		  while(rs.next())
		  {
			  SelectItem obj  = new SelectItem();
			  obj.setValue(rs.getString("branch_id"));
			  obj.setLabel(rs.getString("branch_name"));
			  list.add(obj);
		  }
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		finally {
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}
	
	
	public List<Integer> branchListAll(Connection con)
	{
		List<Integer> list = new ArrayList<Integer>();
		Statement st = null; ResultSet rs = null;
		try 
		{
		  st=con.createStatement();
		  String query = "select id from firm_detail";
		  rs=st.executeQuery(query);
		  while(rs.next())
		  {
			  list.add(rs.getInt("id"));
		  }
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		finally {
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}
	
	public List<SelectItem> branchListAllWithName(String userId,Connection con)
	{
		List<SelectItem> list = new ArrayList<SelectItem>();
		Statement st = null; ResultSet rs = null;
		try 
		{
		  st=con.createStatement();
		  String query = "select id,branch_name from firm_detail where id not in (select branch_id from branch_allocate_table where user_id='"+userId+"')";
		  rs=st.executeQuery(query);
		  while(rs.next())
		  {
			  SelectItem obj = new SelectItem();
			  obj.setLabel(rs.getString("branch_name"));
			  obj.setValue(rs.getString("id"));
			  list.add(obj);
		  }
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		finally {
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}
	


	public int empBranchIdByEmpId(String uname, Connection con)
	{
		Statement st = null; ResultSet rs = null;
		try 
		{
		  st=con.createStatement();
		  String query = "select branch_id from employee where uname='"+uname+"'";
		  rs=st.executeQuery(query);
		  if(rs.next())
		  {
			 return rs.getInt("branch_id");
		  }
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		finally {
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	public double loanCloseAmount(String loanNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select amount from loanpayment where loanNo='"+loanNo+"' and emi_no='-1' and receipt_status='approved' and chequeStatus='cleared'  ";
			////System.out.println(query);
			rr=st.executeQuery(query);
			if(rr.next())
			{
				return rr.getDouble("amount");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	public double loanClosePrincipalAmount(String loanNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select amount,interestAmount from loanpayment where loanNo='"+loanNo+"' and emi_no='-1' and receipt_status='approved' and chequeStatus='cleared'  ";
			////System.out.println(query);
			rr=st.executeQuery(query);
			if(rr.next())
			{
				return rr.getDouble("amount")-rr.getDouble("interestAmount");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	public double loanCloseInterestAmount(String loanNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select interestAmount from loanpayment where loanNo='"+loanNo+"' and emi_no='-1' and receipt_status='approved' and chequeStatus='cleared'  ";
			////System.out.println(query);
			rr=st.executeQuery(query);
			if(rr.next())
			{
				return rr.getDouble("interestAmount");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	public double loanClosePenaltyAmount(String loanNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select amount from income_table where loan_no='"+loanNo+"' and status='active' and chequeStatus='cleared' and  item='receive penalty' and payment_mode='transfer'  ";
			////System.out.println(query);
			rr=st.executeQuery(query);
			if(rr.next())
			{
				return rr.getDouble("amount");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	public String loginIdByUserId(String userid, Connection con) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=con.createStatement();
			String query="select id from login where userid='"+userid+"' and status='active'  ";
			////System.out.println(query);
			rr=st.executeQuery(query);
			if(rr.next())
			{
				return rr.getString("id");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}
	
	// to get the Reg. Firm/Nidhi Detail from db
			public UserInfo appSlideDetails() 
			{
				UserInfo uu=new UserInfo();
				try(Connection con=DataBaseConnection.JAVAConnection();) 
				{
					Statement st=con.createStatement();
					String qq="select * from app_slider";
					ResultSet rs=st.executeQuery(qq);
					if(rs.next())
					{
						filePathDetail(con);  //for set online view path if exist
						if(onlineFileViewPath==null || onlineFileViewPath.trim().equals(""))
						{
							if(rs.getString("slide1")!=null && !rs.getString("slide1").trim().equalsIgnoreCase(""))
							{
								uu.setDoc1Path(rs.getString("slide1"));
							}
							else
							{
								uu.setDoc1Path("");
							}
							
							if(rs.getString("slide2")!=null && !rs.getString("slide2").trim().equalsIgnoreCase(""))
							{
								uu.setDoc2Path(rs.getString("slide2"));
							}
							else
							{
								uu.setDoc2Path("");
							}
							
							if(rs.getString("slide3")!=null && !rs.getString("slide3").trim().equalsIgnoreCase(""))
							{
								uu.setDoc3Path(rs.getString("slide3"));
							}
							else
							{
								uu.setDoc3Path("");
							}
							
							if(rs.getString("slide4")!=null && !rs.getString("slide4").trim().equalsIgnoreCase(""))
							{
								uu.setDoc4Path(rs.getString("slide4"));
							}
							else
							{
								uu.setDoc4Path("");
							}
							
							if(rs.getString("slide5")!=null && !rs.getString("slide5").trim().equalsIgnoreCase(""))
							{
								uu.setDoc5Path(rs.getString("slide5"));
							}
							else
							{
								uu.setDoc5Path("");
							}
						}
						else
						{
							if(rs.getString("slide1")!=null && !rs.getString("slide1").trim().equalsIgnoreCase(""))
							{
								uu.setDoc1Path(onlineFileViewPath+rs.getString("slide1"));
							}
							else
							{
								uu.setDoc1Path("");
							}
							
							if(rs.getString("slide2")!=null && !rs.getString("slide2").trim().equalsIgnoreCase(""))
							{
								uu.setDoc2Path(onlineFileViewPath+rs.getString("slide2"));
							}
							else
							{
								uu.setDoc2Path("");
							}
							
							if(rs.getString("slide3")!=null && !rs.getString("slide3").trim().equalsIgnoreCase(""))
							{
								uu.setDoc3Path(onlineFileViewPath+rs.getString("slide3"));
							}
							else
							{
								uu.setDoc3Path("");
							}
							
							if(rs.getString("slide4")!=null && !rs.getString("slide4").trim().equalsIgnoreCase(""))
							{
								uu.setDoc4Path(onlineFileViewPath+rs.getString("slide4"));
							}
							else
							{
								uu.setDoc4Path("");
							}
							
							if(rs.getString("slide5")!=null && !rs.getString("slide5").trim().equalsIgnoreCase(""))
							{
								uu.setDoc5Path(onlineFileViewPath+rs.getString("slide5"));
							}
							else
							{
								uu.setDoc5Path("");
							}
						}
					}
				}
				catch (Exception e)
				{
					 e.printStackTrace();fileCreation(e.getMessage());
				} 
				return uu;
			}

public List<SelectItem> employeeListAll(Connection con) 
 {
	List<SelectItem> list = new ArrayList<SelectItem>();
	Statement st=null;ResultSet rs=null;
	try 
	{ 
	   	st=con.createStatement();
	   	String query="select * from login where type='employee' and status='active'";
	   	rs=st.executeQuery(query);
	   	while(rs.next())
	   	{
	   		SelectItem obj = new SelectItem();
	   		obj.setLabel(employeeNameByUsername(rs.getString("userid")));
	   		obj.setValue(rs.getString("id"));
	   		list.add(obj);
	   	}
	} 
	catch (Exception e) {
		// TODO: handle exception
	}
	finally {
		try {
			if(st!=null)
			{
				st.close();
			}
			if(rs!=null)
			{
				rs.close();
			}
		} catch (Exception e2) {
			// TODO: handle exception
		}
	}
	return list;
 }

public UserInfo appMemberDocForView(String id, UserInfo selectedRow) 
{
	Connection conn=DataBaseConnection.JAVAConnection();
	filePathDetail(conn);  //for set online view path if exist
	Statement stt=null;
	ResultSet rs =null;
	try 
	{
		stt = conn.createStatement();
		String query="select * from reg_table where id='"+id+"' ";
		rs= stt.executeQuery(query);
		if (rs.next()) 
		{
			selectedRow.setApplicant_photoForEdit(onlineFileViewPath+rs.getString("member_photo"));
			selectedRow.setSignPhotoForEdit(onlineFileViewPath+rs.getString("sign_photo"));
			selectedRow.setFormPhotoForEdit(onlineFileViewPath+rs.getString("form_photo"));
			selectedRow.setDoc1PathForEdit(onlineFileViewPath+rs.getString("doc1"));
			selectedRow.setDoc2PathForEdit(onlineFileViewPath+rs.getString("doc2"));
			selectedRow.setDoc3PathForEdit(onlineFileViewPath+rs.getString("doc3"));
			selectedRow.setDoc4PathForEdit(onlineFileViewPath+rs.getString("doc4"));
			selectedRow.setDoc5PathForEdit(onlineFileViewPath+rs.getString("doc5"));
			selectedRow.setDoc6PathForEdit(onlineFileViewPath+rs.getString("doc6"));
			selectedRow.setDoc7PathForEdit(onlineFileViewPath+rs.getString("doc7"));
			selectedRow.setDoc8PathForEdit(onlineFileViewPath+rs.getString("doc8"));
			selectedRow.setAadharBackDoc01(onlineFileViewPath+rs.getString("aadhar_back_doc01"));
			selectedRow.setVoterIdBackDoc03(onlineFileViewPath+rs.getString("voterId_back_doc03"));
		}
	} 
	catch (Exception e) {
        e.printStackTrace();fileCreation(e.getMessage());
	}
	finally
	{
		try {
			if(stt!=null)
			{
				stt.close();
			}
			if(rs!=null)
			{
				rs.close();
			}
		} catch (Exception e2) {
			// TODO: handle exception
		}
	}
	return selectedRow ;
}
public List<SelectItem> branchListAllWithName(Connection con)
{
	List<SelectItem> list = new ArrayList<SelectItem>();
	Statement st = null; ResultSet rs = null;
	try 
	{
	  st=con.createStatement();
	  String query = "select id,branch_name from firm_detail";
	  rs=st.executeQuery(query);
	  while(rs.next())
	  {
		  SelectItem obj = new SelectItem();
		  obj.setLabel(rs.getString("branch_name"));
		  obj.setValue(rs.getString("id"));
		  list.add(obj);
	  }
	}
	catch (Exception e) {
		// TODO: handle exception
	}
	finally {
		try {
			if(st!=null)
			{
				st.close();
			}
			if(rs!=null)
			{
				rs.close();
			}
		} catch (Exception e2) {
			// TODO: handle exception
		}
	}
	return list;
}

public int decreaseCashAmount(int branchId, String totalCashTra, Date searchDate, String remark, Connection con)
{
	Statement st = null;
	Timestamp tp = new Timestamp(searchDate.getTime());
	tp.setHours(0);
	tp.setMinutes(0);
	tp.setSeconds(0);
	tp.setNanos(0);
	try 
	{
		st = con.createStatement();
		String query = " insert into cash_transfer_table(branch_id,amount,transfer_status,status,transfer_dt,remark) "
				+ "values ('"+branchId+"','"+totalCashTra+"','Dr','active','"+tp+"','"+remark+"')";
		int res = st.executeUpdate(query);
		if(res>0)
		{
			return 1;
		}
	}
	catch (Exception e) {
		// TODO: handle exception
	}
	finally {
		try {
			if(st!=null)
			{
				st.close();
			}
		} catch (Exception e2) {
			// TODO: handle exception
		}
	}
	return 0;
}

public int increaseCashAmount(int branchId, String totalCashTra, Date searchDate, String remark, Connection con)
{
	Statement st = null;
	Timestamp tp = new Timestamp(searchDate.getTime());
	tp.setHours(0);
	tp.setMinutes(0);
	tp.setSeconds(0);
	tp.setNanos(0);
	try 
	{
		st = con.createStatement();
		String query = " insert into cash_transfer_table(branch_id,amount,transfer_status,status,transfer_dt,remark)"
				+ " values ('"+branchId+"','"+totalCashTra+"','Cr','active','"+tp+"','"+remark+"')";
		int res = st.executeUpdate(query);
		if(res>0)
		{
			return 1;
		}
	}
	catch (Exception e) {
		// TODO: handle exception
	}
	finally {
		try {
			if(st!=null)
			{
				st.close();
			}
		} catch (Exception e2) {
			// TODO: handle exception
		}
	}
	return 0;
}

public double calculateCashTransferCr(int branchId, String sDate, Connection con)
{
	ResultSet rs = null; Statement st = null;
	String query="";
	try 
	{
	   st=con.createStatement();
	   if(sDate.equals("all"))
	   {
		   query = "select sum(amount) as absCashCr from cash_transfer_table where status='active' and transfer_status='Cr'";
	   }
	   else
	   {
		   query = "select sum(amount) as absCashCr from cash_transfer_table where status='active' and transfer_status='Cr' and transfer_dt='"+sDate+"'";
	   }
	   query = selectQueWithBranch(query, branchId);
	       rs=st.executeQuery(query);
	   if(rs.next())
	   {
		   return rs.getDouble("absCashCr");
	   }
	   
	}
	catch (Exception e) {
		// TODO: handle exception
	}
	finally {
		try {
			if(rs!=null)
			{
				rs.close();
			}
			if(st!=null)
			{
				st.close();
			}
			
		} catch (Exception e2) {
			// TODO: handle exception
		}
	}
	// TODO Auto-generated method stub
	return 0.0;
}


public double calculateCashTransferDr(int branchId, String sDate,Connection con)
{
	ResultSet rs = null; Statement st = null;
	String query="";
	try 
	{
	   st=con.createStatement();
	   if(sDate.equals("all"))
	   {
		   query = "select sum(amount) as absCashDr from cash_transfer_table where status='active' and transfer_status='Dr'";
			  
	   }
	   else
	   {
		   query = "select sum(amount) as absCashDr from cash_transfer_table where status='active' and transfer_status='Dr' and transfer_dt='"+sDate+"'";
			
	   }
	   query = selectQueWithBranch(query, branchId);
	     rs=st.executeQuery(query);
	   if(rs.next())
	   {
		   return rs.getDouble("absCashDr");
	   }
	   
	}
	catch (Exception e) {
		// TODO: handle exception
	}
	finally {
		try {
			if(rs!=null)
			{
				rs.close();
			}
			if(st!=null)
			{
				st.close();
			}
			
		} catch (Exception e2) {
			// TODO: handle exception
		}
	}
	// TODO Auto-generated method stub
	return 0.0;
}

	public String checkDefaultShareTransferFrom(Connection conn) 
	{
		try
		{
             Statement stt=conn.createStatement();
		     String query="select transfer_from from company_shares";	
		     ResultSet rs=stt.executeQuery(query);
		     if(rs.next())
		     {
		    	 return rs.getString("transfer_from");
		     }
		}
		catch (Exception e) 
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return "";
	}		
	

	public ArrayList<SelectItem> loanNoListFreqWise(String freq, String loanType, Connection conn) 
	{
		ArrayList<SelectItem> list=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			if(!loanType.equalsIgnoreCase("grouploan"))
			{
				String query="select loanNo,first_applicantName,father_husband_name from "+loanType+" inner join shareholder_info where "+loanType+".status='Approve' and paidStatus='unpaid' and shareholder_info.shareholderno="+loanType+".shareholderno ";
				if(!freq.equalsIgnoreCase("-1"))
				{
					query+=" and frequency="+freq+" ";
				}
				rr=st.executeQuery(query);
				while(rr.next())
				{
					SelectItem ss=new SelectItem();
					
					ss.setLabel(rr.getString("loanNo")+" - "+rr.getString("first_applicantName")+ " - "+rr.getString("father_husband_name"));
					ss.setValue(rr.getString("loanNo"));
					
					list.add(ss);
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally 
        {
            try 
            {
            	if(st!=null)
            	{
            		  st.close();
                }
            	if(rr!=null)
            	{
            	     rr.close();
                }
            } 
            catch (Exception s) 
            {
                fileCreation(s.getMessage());
            }
        }
		return list;
	}
	
	public String remarkFromGroupLoanEmiForwardTable(String loanNo, Connection conn) 
	{
		String remark="";
		ResultSet rr=null;
		Statement st=null;
		try
		{
			st=conn.createStatement();
			String qq="select remark from grouploan_emi where sub_loan_no='"+loanNo+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				remark=rr.getString("remark");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} 
			catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return remark;
	}
	
	public void updateDsaInCommanTable(String shareHolderNo, String newDsaCode, String tableName, Connection conn) 
	{
		String dsaColumnName="", memberColumnName="";
		if(tableName.equalsIgnoreCase("customer_info"))
		{
			dsaColumnName="dsa_code";
		}
		else
		{
			dsaColumnName="dsacode";
		}
		
		if(tableName.equalsIgnoreCase("grouploan"))
		{
			memberColumnName="teamLeader";
		}
		else if(tableName.equalsIgnoreCase("savingaccount") || tableName.equalsIgnoreCase("customer_info"))
		{
			memberColumnName="shareHolderNo";
		}
		else
		{
			memberColumnName="shareholderno";
		}
		
		Statement st=null;
		try
		{
			st=conn.createStatement();
			String qq="update "+tableName+" set "+dsaColumnName+"='"+newDsaCode+"' where "+memberColumnName+"='"+shareHolderNo+"' ";
			//System.out.println(qq);
			st.executeUpdate(qq);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(st!=null)
				{
					st.close();
				}
			} 
			catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
	public void updateCenterInCommanTable(String shareHolderNo, String newCenter, String tableName, Connection conn) 
	{
		String dsaColumnName="", memberColumnName="";
		
		if(tableName.equalsIgnoreCase("grouploan"))
		{
			memberColumnName="teamLeader";
		}
		else if(tableName.equalsIgnoreCase("savingaccount"))
		{
			memberColumnName="shareHolderNo";
		}
		else
		{
			memberColumnName="shareholderno";
		}
		
		Statement st=null;
		try
		{
			st=conn.createStatement();
			String qq="update "+tableName+" set center='"+newCenter+"' where "+memberColumnName+"='"+shareHolderNo+"' ";
			if(!tableName.equalsIgnoreCase("shareholder_info") && !tableName.equalsIgnoreCase("savingaccount"))
			{
				qq+=" and paidStatus='unpaid' ";
			}
			//System.out.println(qq);
			st.executeUpdate(qq);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(st!=null)
				{
					st.close();
				}
			} 
			catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
	public ArrayList<UserInfo> dailyLoanListForBranchReport(String searchType, String dsaCode, int branchId, Connection conn) 
	{
		int count=1;
		ArrayList<UserInfo> list=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select loanNo,dsacode,emi,shareholderno from personalloan where status='Approve' and paidStatus='unpaid' and frequency=365 ";
			if(!dsaCode.equalsIgnoreCase("all"))
			{
				qq+=" and dsacode='"+dsaCode+"' ";
			}
			
			if(branchId!=-1)
			{
				qq+=" and branch_id='"+branchId+"' ";
			}
			//System.out.println(qq);
			rr=st.executeQuery(qq);
			while(rr.next())
			{
				UserInfo uu=new UserInfo();
				
				uu.setSno(count++);
				uu.setAccountNo(rr.getString("loanNo"));
				uu.setDsaName(dsaNameById(rr.getString("dsacode"), conn));
				uu.setInstallment_amount(rr.getDouble("emi"));
				uu.setName(shareHolderNameByShareHolderNo(rr.getString("shareholderno"), conn));
				uu.setShareHolderNo(rr.getString("shareholderno"));
				uu.setAccType(searchType);
				
				list.add(uu);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}

	public ArrayList<UserInfo> dailyDepositListForBranchReport(String searchType, String dsaCode, int branchId, Connection conn) 
	{
		int count=1;
		ArrayList<UserInfo> list=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select user_no,dsa_code,installment_amount,shareHolderNo from customer_info where account_status='active' and paid_status='unpaid' and scheme_type='DD' ";
			if(!dsaCode.equalsIgnoreCase("all"))
			{
				qq+=" and dsa_code='"+dsaCode+"' ";
			}
			
			if(branchId!=-1)
			{
				qq+=" and branch_id='"+branchId+"' ";
			}
			//System.out.println(qq);
			rr=st.executeQuery(qq);
			while(rr.next())
			{
				UserInfo uu=new UserInfo();
				
				uu.setSno(count++);
				uu.setAccountNo(rr.getString("user_no"));
				uu.setDsaName(dsaNameById(rr.getString("dsa_code"), conn));
				uu.setInstallment_amount(rr.getDouble("installment_amount"));
				uu.setName(shareHolderNameByShareHolderNo(rr.getString("shareHolderNo"), conn));
				uu.setShareHolderNo(rr.getString("shareHolderNo"));
				uu.setTotalAmount(paidAmountByUser(rr.getString("user_no"), conn));
				uu.setAccType(searchType);
				
				list.add(uu);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}

	public void calculateDailyLoanAndDDReceiveAmount(ArrayList<SelectItem> datList, ArrayList<UserInfo> list, Connection conn) 
	{
		for(UserInfo ss : list)
		{
			Map<String, String> map=new HashMap<String,String>();
			double total=0;
			for(SelectItem ii : datList)
			{
				double paidEmiAmt=0;
				if(ss.getAccType().equalsIgnoreCase("Daily Loan"))
				{
					paidEmiAmt=loanPaidEmiAmountByDate(ss.getAccountNo(), String.valueOf(ii.getValue()), conn);
				}
				else if(ss.getAccType().equalsIgnoreCase("Daily Deposit"))
				{
					paidEmiAmt=ddPaidEmiAmountByDate(ss.getAccountNo(), String.valueOf(ii.getValue()), conn);
				}
				total+=paidEmiAmt;
				map.put(String.valueOf(ii.getValue()), df.format(paidEmiAmt));
			}
			
			ss.setTotalPaid(total);
			ss.setEmiMap(map);
		}
	}
	
	private double loanPaidEmiAmountByDate(String loanNo, String sno, Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from loanpayment where loanNo='"+loanNo+"' and pay_date='"+sno+"' and receipt_status='approved' and chequeStatus='cleared'  ";
//			/System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return Double.parseDouble(df.format(rr.getDouble("sum(amount)")));
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	private double ddPaidEmiAmountByDate(String loanNo, String sno, Connection conn) 
	{
		try
		{
			Statement st=conn.createStatement();
			String qq="select sum(amount) from payment_receipt where user_no='"+loanNo+"' and date='"+sno+"' and receipt_status='approved' and chequeStatus='cleared'  ";
			//System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return Double.parseDouble(df.format(rr.getDouble("sum(amount)")));
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public String planIdByDepositNo(String depositNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select plan_no from customer_info where user_no='"+depositNo+"' ";
			// // // System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("plan_no");
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally 
        {
            try 
            {
                // Close the writer regardless of what happens...
            	if(st!=null)
            	{
            		  st.close();
                }
            	if(rr!=null)
            	{
            	     rr.close();
                }
            } 
            catch (Exception s) 
            {
                s.printStackTrace();
                fileCreation(s.getMessage());
            }
        }
		return "";
	}
	
	public int insertRdGroupLoanEmi(ArrayList<InstallmentInfo> list, String depositNo, String remark) 
	{
		int count=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq1="delete from grouploan_emi where sub_loan_no='"+depositNo+"' "; // Work when we update the data
			st.executeUpdate(qq1);
			
			for(InstallmentInfo ll:list)
			{
				Date startDate=sf.parse(ll.getIns_date());
				Timestamp ts=new Timestamp(startDate.getTime());
				String qq="insert into grouploan_emi(sub_loan_no, emi_no, emi_date, remark) values('"+depositNo+"','"+ll.getSno()+"','"+ts+"','"+remark+"') ";
				count=st.executeUpdate(qq);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return count;
	}
	
	// update maturity date after RD EMI Forward
	public int updateMaturityDate(Date newMaturityDate, String userNo) 
	{
		int i = 0;
		Timestamp ts = new Timestamp(newMaturityDate.getTime());
		try (Connection con = DataBaseConnection.JAVAConnection();) 
		{
			Statement st = con.createStatement();
			String qq = "update customer_info set maturity_date='"+ ts + "' where user_no='" + userNo + "'";
			//System.out.println(qq);
			int x = st.executeUpdate(qq);
			if (x >= 1) 
			{
				dataInsertInQueryTable(qq, con);
				i++;
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return i;
	}
	
	public ArrayList<ReportInfo> checkRdFdPaidDetailByUserNoForPrint(String user_no) 
	{
		int count=1;
		double tot=0;
		ArrayList<ReportInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from payment_receipt where user_no='"+user_no+"' and chequeStatus='cleared' and receipt_status='approved' order by date asc ";
		//	// // // System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				ReportInfo ll=new ReportInfo();
				
				ll.setsNo(count++);
				ll.setEmiPaidDate(rr.getDate("date"));
				ll.setDateStr(sf.format(ll.getEmiPaidDate()));
				ll.setStatus(user_no+" Installment Deposit");
				ll.setCreditAmount(rr.getDouble("amount"));
				tot+=rr.getDouble("amount");
				ll.setBalance(tot);
				
				list.add(ll);	
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return list;
	}

	public ArrayList<InstallmentInfo> emiListForCenterCardMultiple(String center, String groupNo) 
	{
		Date emiDate=null;
		ArrayList<InstallmentInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			boolean checkEmi=checkGroupLoanEmiFromTableForCenterCardMultiple(groupNo, conn);
			Statement st=conn.createStatement();
			String qq="select * from grouploan where center='"+center+"' and loanNo='"+groupNo+"' and status='Approve' and paidStatus='unpaid' order by terms+0 desc ";
			System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				if(rr.getDate("emi_due_date")!=null)
				{
					emiDate=rr.getDate("emi_due_date");
					emiDate.setDate(emiDate.getDate()-(365/rr.getInt("frequency")));
				}
				else
				{
					emiDate=rr.getDate("approvalDate");
				}
				
				for(int i=1;i<=rr.getInt("terms");i++)
				{
					InstallmentInfo ii=new InstallmentInfo();
					
					if(checkEmi==false)
					{
						emiDate.setDate(emiDate.getDate()+(365/rr.getInt("frequency")));
						ii.setEmiPaidDate(emiDate);
						ii.setSno(i);
						ii.setEmiPaidDateStr(sf.format(emiDate));
					}
					else
					{
						emiDate=groupLoanEmiDateFromTableForCenterCardMultiple(i, groupNo, conn);
						ii.setEmiPaidDate(emiDate);
						ii.setSno(i);
						ii.setEmiPaidDateStr(sf.format(emiDate));
					}
					
					list.add(ii);
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return list;
	}

	public ArrayList<LoanInfo> groupMemberDetailForCenterCardMultiple(String groupNo) 
	{
		ArrayList<LoanInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from grouploan inner join shareholder_info where shareholder_info.shareholderno=grouploan.teamLeader and grouploan.loanNo='"+groupNo+"'"
					+ " and grouploan.status='Approve' and paidStatus='unpaid' order by grouploan.id asc ";
			//System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				LoanInfo ll=new LoanInfo();

				ll.setSubLoanNo(rr.getString("sub_loan_no"));
				ll.setLoanAmount(rr.getString("loanAmount"));
				ll.setName(rr.getString("first_applicantName"));
				ll.setFatherHusbandName(rr.getString("father_husband_name"));
				ll.setMobile(rr.getString("mobile"));
				ll.setEmiAmount(rr.getDouble("emi"));
				ll.setTerms(rr.getInt("terms"));
				ll.setRdEmiAmtDue(rdEmiAmtByShareHolderNo(rr.getString("shareholderno"),conn));
				
				list.add(ll);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}
	
	private double rdEmiAmtByShareHolderNo(String shareHolderNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select installment_amount from customer_info where shareHolderNo='"+shareHolderNo+"' and scheme_type='RD' and paid_status='unpaid' and "
					+ " account_status='active' ";
			System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("installment_amount");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	public ArrayList<SelectItem> groupNoListCenterCardMultiple(String center) 
	{
		ArrayList<SelectItem> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select loanNo from grouploan where center='"+center+"' and status='Approve' and paidStatus='unpaid' group by loanNo ";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				SelectItem ii=new SelectItem();
				ii.setLabel(rr.getString("loanNo"));
				ii.setValue(rr.getString("loanNo"));
				list.add(ii);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}
	
	public void calculateCenterCardAmount(ArrayList<LoanInfo> datList, ArrayList<InstallmentInfo> list, Connection conn) 
	{
		for(InstallmentInfo ss : list)
		{
			Map<String, String> map=new HashMap<String,String>();
			double total=0;
			for(LoanInfo ii : datList)
			{
				/*double paidEmiAmt=0;
				if(ss.getAccType().equalsIgnoreCase("Daily Loan"))
				{
					paidEmiAmt=loanPaidEmiAmountByDate(ss.getAccountNo(), String.valueOf(ii.getValue()), conn);
				}
				else if(ss.getAccType().equalsIgnoreCase("Daily Deposit"))
				{
					paidEmiAmt=ddPaidEmiAmountByDate(ss.getAccountNo(), String.valueOf(ii.getValue()), conn);
				}
				total+=paidEmiAmt;*/
				map.put(String.valueOf(ii.getSubLoanNo()), "");
			}
			
			//ss.setTotalPaid(total);
			ss.setEmiMap(map);
		}
	}

	public boolean checkGroupLoanEmiFromTableForCenterCardMultiple(String loanNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from grouploan_emi where sub_loan_no like '"+loanNo+"%' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return false;
	}
	
	public Date groupLoanEmiDateFromTableForCenterCardMultiple(int i, String loanNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select emi_date from grouploan_emi where sub_loan_no like '"+loanNo+"%' and emi_no='"+i+"' ";
			//System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDate("emi_date");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return null;
	}

	public int branchIdByMemberNo(String shareNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select branch_id from shareholder_info where shareholderno='"+shareNo+"' ";
			ResultSet rr=st.executeQuery(query);
			if(rr.next())
			{
				return rr.getInt("branch_id");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}
	
	public String dsaCodeByMemberNo(String shareNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select dsacode from shareholder_info where shareholderno='"+shareNo+"' ";
			ResultSet rr=st.executeQuery(query);
			if(rr.next())
			{
				return rr.getString("dsacode");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return "";
	}
	
	public String checkEmployeeStatusByEmpId(String uname, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select status from employee where uname='"+uname+"' ";
			//System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("status");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try 
			{
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} 
			catch (Exception e2) 
			{
				// TODO: handle exception
			}
		}
		return "inactive";
	}
	
	public String checkEmployeeStatus(String dsaCode, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select status,uname from employee where dsacode='"+dsaCode+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				if(checkEmployeeStatusInLoginTable(rr.getString("uname"), conn).equalsIgnoreCase("active"))
				{
					return rr.getString("status");
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try 
			{
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} 
			catch (Exception e2) 
			{
				// TODO: handle exception
			}
		}
		return "inactive";
	}
	
	public String checkEmployeeStatusInLoginTable(String userid, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select status from login where userid='"+userid+"' ";
			//System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("status");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try 
			{
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} 
			catch (Exception e2) 
			{
				// TODO: handle exception
			}
		}
		return "inactive";
	}
	
	public UserInfo memberBasicDetail(String shareHolderNo, Connection conn) 
	{
		UserInfo uu=new UserInfo();
		Statement stt=null;
		ResultSet ss =null;
		try
		{
			stt = conn.createStatement();
			String query = "select * from shareholder_info a where shareholderno='"+shareHolderNo+"' ";
			ss= stt.executeQuery(query);
			if (ss.next())
			{
				uu.setShareHolderNo(shareHolderNo);
				uu.setName(ss.getString("first_applicantName"));
				uu.setFirst_applicantName(ss.getString("first_applicantName"));
				uu.setContactNo(ss.getString("mobile"));
				uu.setMobile(ss.getString("mobile"));
				uu.setFather_husband_name(ss.getString("father_husband_name"));
				uu.setAddress(ss.getString("address"));
				uu.setBrideFhname(ss.getString("bride_fhname"));
				uu.setBrideMname(ss.getString("bride_mname"));
				uu.setUniqueId(ss.getString("unique_id"));
				uu.setBrideAddress(ss.getString("bride_address"));
				uu.setVoterId(ss.getString("voter_id"));
				uu.setAltMobileNo(ss.getString("alt_mobile_no"));			
				filePathDetail(conn);    
				if(onlineFileViewPath==null || onlineFileViewPath.trim().equals(""))
				{
					uu.setApplicant_photo(ss.getString("applicant_photo"));
				}
				else
				{
					if(ss.getString("applicant_photo")!=null)
					{
						uu.setApplicant_photo(onlineFileViewPath+ss.getString("applicant_photo"));
					}
					else
					{
						uu.setApplicant_photo("");
					}
					
				}
				
				uu.setLatitude(ss.getString("latitude"));
				uu.setLongitude(ss.getString("longitude"));
			}
		}	
		catch (Exception e) 
		{
	          e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
			if(stt!=null)
			{
			stt.close();
			}
			if(ss!=null)
			{
			ss.close();
			}
			} catch (Exception e2) {
			// TODO: handle exception
			}
		}
		
		return uu;
	}
	
	public CommanInfo memberBasicDetailForCommanInfo(CommanInfo uu,String shareHolderNo, Connection conn) 
	{
		Statement stt=null;
		ResultSet ss =null;
		try
		{
			stt = conn.createStatement();
			String query = "select * from shareholder_info a where shareholderno='"+shareHolderNo+"' ";
			ss= stt.executeQuery(query);
			if (ss.next())
			{
				uu.setShareHolderNo(shareHolderNo);
				uu.setName(ss.getString("first_applicantName"));
				uu.setMobileNo(ss.getString("mobile"));
				uu.setFatherHusbandName(ss.getString("father_husband_name"));
				uu.setAddress(ss.getString("address"));
				uu.setBrideFname(ss.getString("bride_fhname"));
				uu.setBrideMname(ss.getString("bride_mname"));
				uu.setBrideAddress(ss.getString("bride_address"));
			}
		}	
		catch (Exception e) 
		{
	          e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
			if(stt!=null)
			{
			stt.close();
			}
			if(ss!=null)
			{
			ss.close();
			}
			} catch (Exception e2) {
			// TODO: handle exception
			}
		}
		return uu;
	}
	
	public DebitInfo viewDebitLoanHistoryForSanctionLetter(String loanCategory,String loanNo, String shareHolderNo, Connection conn) 
	{
		DebitInfo info=new DebitInfo();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select * from debit_loan where loanType='"+loanCategory+"' and loanNo='"+loanNo+"' and shareholderno='"+shareHolderNo+"' and status='cleared'";
			//System.out.println(query);
			rr=st.executeQuery(query);
			if(rr.next())
			{
				
				info.setId(rr.getString("id"));
				info.setChequeDate(rr.getDate("chequeDate"));
				if(info.getChequeDate()!=null)
				{
					info.setStrChequeDate(sf.format(rr.getDate("chequeDate")));
				}
				info.setBankName(bankNameById(rr.getString("bankName")));
				info.setBankBranch(rr.getString("bankBranch"));
				info.setChequeNo(rr.getString("chequeNo"));
				info.setLoanNo(rr.getString("loanNo"));
				info.setLoanType(rr.getString("loanType"));
				info.setShareholderno(rr.getString("shareholderno"));
				info.setAmount(rr.getString("amount"));
				info.setPaymentMode(rr.getString("paymentMode"));	
				info.setPayDate(rr.getDate("date"));
				info.setStrPayDate(sf.format(rr.getDate("date")));
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return info;
	}
	
	public ArrayList<SelectItem> memberListDsaEmpWise(int branchId, String dsaCode, Connection conn) 
	{
		ArrayList<SelectItem> list=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select shareholderno,first_applicantName,father_husband_name,mobile from shareholder_info where branch_id="+branchId+"";
			if(dsaCode!=null && !dsaCode.equalsIgnoreCase("all"))
			{
				query+=" and  dsacode='"+dsaCode+"' ";
			}
			//query+=" order by id desc";
			rr=st.executeQuery(query);
			while(rr.next())
			{
				SelectItem ss=new SelectItem();
				
				ss.setLabel(rr.getString("shareholderno")+" - "+rr.getString("first_applicantName")+ " - "+rr.getString("father_husband_name")+ " - "+rr.getString("mobile"));
				ss.setValue(rr.getString("shareholderno"));
				
				list.add(ss);
			}
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally 
        {
            try 
            {
            	if(st!=null)
            	{
            		  st.close();
                }
            	if(rr!=null)
            	{
            	     rr.close();
                }
            } 
            catch (Exception s) 
            {
                fileCreation(s.getMessage());
            }
        }
		return list;
	}
	
	public ArrayList<SelectItem> memberListCenterWise(int branchId, String center, Connection conn) 
	{
		ArrayList<SelectItem> list=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String query="select shareholderno,first_applicantName,father_husband_name,mobile from shareholder_info where branch_id="+branchId+"";
			if(center!=null && !center.equalsIgnoreCase("all"))
			{
				query+=" and center='"+center+"' ";
			}
			//System.out.println(query);
			//query+=" order by id desc";
			rr=st.executeQuery(query);
			while(rr.next())
			{
				SelectItem ss=new SelectItem();
				
				ss.setLabel(rr.getString("shareholderno")+" - "+rr.getString("first_applicantName")+ " - "+rr.getString("father_husband_name")+ " - "+rr.getString("mobile"));
				ss.setValue(rr.getString("shareholderno"));
				
				list.add(ss);
			}
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally 
        {
            try 
            {
            	if(st!=null)
            	{
            		  st.close();
                }
            	if(rr!=null)
            	{
            	     rr.close();
                }
            } 
            catch (Exception s) 
            {
                fileCreation(s.getMessage());
            }
        }
		return list;
	}
	
	// New method develop by CHETAN GARG update due to Share Return
		public ArrayList<UserInfo> multipleShareHolders(String[] memberNo, Connection conn)
		{
			String query ="";
			ArrayList<UserInfo> list = new ArrayList<>();
			int i = 1;
			Statement stt=null;
			ResultSet ss =null;
			try
			{
				stt = conn.createStatement();
				for(int k=0;k<memberNo.length;k++)
				{
					query = "select * from shareholder_info  where shareholderno='"+memberNo[k]+"' order by id desc ";
					//System.out.println(query);
					ss= stt.executeQuery(query);
					while (ss.next())
					{
						UserInfo uu = new UserInfo();
						//uu = userInfoById(ss);
						uu.setId(ss.getString("id"));
						uu.setFirst_applicantName(ss.getString("first_applicantName"));
						uu.setContactNo(ss.getString("mobile"));
						uu.setShareHolderNo(ss.getString("shareholderno"));
						uu.setFather_husband_name(ss.getString("father_husband_name"));
						uu.setOffice_application_no(ss.getString("office_application_no"));
						//uu.setAccountNo(ss.getString("accountNo"));
						uu.setTotalAmount(ss.getDouble("totalAmount"));
						uu.setCrNo(ss.getString("crNo"));
						uu.setAddress(ss.getString("address"));
						uu.setNoOfShare(ss.getInt("noofShare"));
						uu.setTransferFrom(ss.getString("transfer_from"));
						uu.setAccount_status(ss.getString("account_status"));
						uu.setSno(i++);
						if ("".equals(ss.getString("transfer_from"))) {
						    // Safe even if transfer_from is null
							uu.setTransferFrom("");
							uu.setDisable(true);
						}
											
						else
						{
							uu.setTransferFrom(ss.getString("transfer_from"));
							uu.setDisable(false);
						}
					
						filePathDetail(conn);
						if(onlineFileViewPath==null || onlineFileViewPath.trim().equals(""))
						{
							uu.setApplicant_photo(ss.getString("applicant_photo"));
						}
						else
						{
							uu.setApplicant_photo(onlineFileViewPath+ss.getString("applicant_photo"));
						}
						if(ss.getString("account_status").equals("inactive"))
						{
							uu.setShowReportType(true);
							uu.setCheckForReturnShare(false);
						}
						else
						{
							uu.setShowReportType(false);
							uu.setCheckForReturnShare(true);
						}
						uu.setDsaCode(ss.getString("dsacode"));
						list.add(uu);
					}
				}
			}
			catch (Exception e) {
			           e.printStackTrace();fileCreation(e.getMessage());
			}
			finally
			{
				try {
				if(stt!=null)
				{
				stt.close();
				}
				if(ss!=null)
				{
				ss.close();
				}
				} catch (Exception e2) {
				// TODO: handle exception
				}
			}
		
			return list;
		}

		public int againReverseForApproval(String loanNo, String loanType, int branchId) 
		{
			String qq="";
			try(Connection conn=DataBaseConnection.JAVAConnection())
			{
				Statement st=conn.createStatement();
				if(loanType.equalsIgnoreCase("grouploan"))
				{
					qq="update grouploan set status='pending' where sub_loan_no='"+loanNo+"' and branch_id="+branchId+" ";
				}
				else
				{
					qq="update "+loanType+" set status='pending' where loanNo='"+loanNo+"' and branch_id="+branchId+" ";
				}
				//System.out.println(qq);
				int i=st.executeUpdate(qq);
				return i;
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			return 0;
		}
		
		public int openingTotalMemberForNdh(Date startDate, int branchId, Connection conn) 
		{
			String sDate=sdfForDb.format(startDate);
			Statement st=null;
			ResultSet rr=null;
			try
			{
				st=conn.createStatement();
				String query="select count(*) from shareholder_info where office_date<'"+sDate+"'  ";
				rr=st.executeQuery(selectQueWithBranch(query,branchId));
				if(rr.next())
				{
					return rr.getInt("count(*)");
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			finally
			{
				try {
					if(st!=null)
					{
						st.close();
					}
					if(rr!=null)
					{
						rr.close();
					}
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
			return 0;
		}

		public int addMemberBetweenForNdh(Date startDate, Date endDate, int branchId, Connection conn) 
		{
			String sDate=sdfForDb.format(startDate);
			String eDate=sdfForDb.format(endDate);
			Statement st=null;
			ResultSet rr=null;
			try
			{
				st=conn.createStatement();
				String query="select count(*) from shareholder_info where office_date>='"+sDate+"' and office_date<='"+eDate+"'  ";
				rr=st.executeQuery(selectQueWithBranch(query,branchId));
				if(rr.next())
				{
					return rr.getInt("count(*)");
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			finally
			{
				try {
					if(st!=null)
					{
						st.close();
					}
					if(rr!=null)
					{
						rr.close();
					}
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
			return 0;
		}
		
	public ArrayList<UserInfo> transferEntryData(Date startDate, Date endDate, String searchType) 
	{
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		ArrayList<UserInfo> list=new ArrayList<>();
		int count=1;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			if(searchType.equalsIgnoreCase("debit_loan"))
			{
				Statement st=conn.createStatement();
				String qq="select * from debit_loan where paymentMode='Transfer' and date>='"+sDate+"' and date<='"+eDate+"' and status='cleared' ";
				//System.out.println(qq);
				ResultSet rr=st.executeQuery(qq);
				while(rr.next())
				{
					UserInfo uu=new UserInfo();
					
					uu.setSno(count++);
					uu.setOffice_date(rr.getDate("date"));
					uu.setStrOffcDate(sf.format(uu.getOffice_date()));
					uu.setShareHolderNo(rr.getString("shareholderno"));
					uu.setLoanNo(rr.getString("loanNo"));
					uu.setAccountNo(savingAccountByShareHolderNo(uu.getShareHolderNo()));
					uu.setName(firstApplicantNameBySHNo(uu.getShareHolderNo(), conn));
					uu.setAmount(rr.getDouble("amount"));
					uu.setEntryDateStr(rr.getString("entry_date"));
					
					list.add(uu);
				}
			}
			
			
			else if(searchType.equalsIgnoreCase("loanpayment"))
			{
				Statement st=conn.createStatement();
				String qq="select *,sum(amount) from loanpayment where pay_mode='Transfer' and pay_date>='"+sDate+"' and pay_date<='"+eDate+"' and chequeStatus='cleared' and"
						+ " receipt_status='approved' group by loanNo,pay_date  ";
				//System.out.println(qq);
				ResultSet rr=st.executeQuery(qq);
				while(rr.next())
				{
					UserInfo uu=new UserInfo();
					
					uu.setSno(count++);
					uu.setOffice_date(rr.getDate("pay_date"));
					uu.setStrOffcDate(sf.format(uu.getOffice_date()));
					uu.setLoanNo(rr.getString("loanNo"));
					uu.setShareHolderNo(shareHolderNoByLoanNo(uu.getLoanNo()));
					uu.setAccountNo(savingAccountByShareHolderNo(uu.getShareHolderNo()));
					uu.setName(firstApplicantNameBySHNo(uu.getShareHolderNo(), conn));
					uu.setAmount(rr.getDouble("sum(amount)"));
					uu.setEntryDateStr(rr.getString("entry_date"));
					
					list.add(uu);
				}
			}
			
			else if(searchType.equalsIgnoreCase("payment_receipt"))
			{
				Statement st=conn.createStatement();
				String qq="select *,sum(amount) from payment_receipt where payment_mode='Transfer' and date>='"+sDate+"' and date<='"+eDate+"' and chequeStatus='cleared' and"
						+ " receipt_status='approved' and scheme_type!='MIS' group by user_no, date  ";
				//System.out.println(qq);
				ResultSet rr=st.executeQuery(qq);
				while(rr.next())
				{
					UserInfo uu=new UserInfo();
					
					uu.setSno(count++);
					uu.setOffice_date(rr.getDate("date"));
					uu.setStrOffcDate(sf.format(uu.getOffice_date()));
					uu.setLoanNo(rr.getString("user_no"));
					uu.setShareHolderNo(shareHolderNoByRdFdNo(uu.getLoanNo()));
					uu.setAccountNo(savingAccountByShareHolderNo(uu.getShareHolderNo()));
					uu.setName(firstApplicantNameBySHNo(uu.getShareHolderNo(), conn));
					uu.setAmount(rr.getDouble("sum(amount)"));
					uu.setEntryDateStr(rr.getString("entry_date"));
					
					list.add(uu);
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}	
	
	public int updateAppSliderDetail(String doc1Path, String doc2Path,String doc3Path, String doc4Path, String doc5Path) 
	{
		try (Connection conn = DataBaseConnection.JAVAConnection();)
		{
			String query="update app_slider set slide1=?,slide2=?,slide3=?,slide4=?, slide5=? " ;
			//System.out.println(query);
			PreparedStatement st1 = conn.prepareStatement(query);
			st1.setString(1, doc1Path);
			st1.setString(2, doc2Path);
			st1.setString(3, doc3Path);
			st1.setString(4, doc4Path);
			st1.setString(5, doc5Path);
			int i = st1.executeUpdate();
			if (i >= 1)
			{
				dataInsertInQueryTable(String.valueOf(st1), conn);
				return i;
			}
		} 
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public ArrayList<UserInfo> directorDetail() 
	{
		int count=1;
		ArrayList<UserInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from shareholder_info limit 3";
			ResultSet ss=st.executeQuery(qq);
			while(ss.next())
			{
				UserInfo uu=new UserInfo();
				
				uu.setSno(count++);
				uu.setName(ss.getString("first_applicantName"));
				uu.setMobile(ss.getString("mobile"));
				uu.setFather_husband_name(ss.getString("father_husband_name"));
				uu.setAddress(ss.getString("address"));
				
				filePathDetail(conn);
				uu.setApplicant_photo(onlineFileViewPath+ss.getString("applicant_photo"));
				
				list.add(uu);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}
	
	public String maturityPaymentMode(String user_no) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select paymentMode from returned_amount_info where user_no='"+user_no+"' and chequeStatus='cleared'";
			//System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("paymentMode");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return "";
	}
	
	public String centerIdByGroupLoanNo(int branchId, String subLoanNo, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select center from grouploan where sub_loan_no='"+subLoanNo+"' ";
			////System.out.println(qq);
			rr=st.executeQuery(selectQueWithBranch(qq, branchId));
			if(rr.next())
			{
				return rr.getString("center");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "0";
	}
	
	public ArrayList<SelectItem> overTimeCenterListForUpcomingEMI(int branchId, Date startDate, Date endDate) 
	{
		ArrayList<String> uList=new ArrayList<>();
		Date dt=new Date();
		endDate.setHours(0);
		endDate.setMinutes(0);
		endDate.setSeconds(0);
		startDate.setHours(0);
		startDate.setMinutes(0);
		startDate.setSeconds(0);
		/*while(startDate.before(endDate) || startDate.equals(endDate))
		{
			
			startDate.setDate(startDate.getDate()+1);
		}*/
		uList.add(sf.format(startDate));
		
		ArrayList<SelectItem> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from grouploan where status='Approve' and paidStatus='unpaid'  ";
			////System.out.println(qq);
			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
			while(rr.next())
			{
				ArrayList<String> dList=loanEmiStrDateList(rr.getInt("frequency"), rr.getInt("terms"), rr.getDate("emi_due_date"),rr.getDate("approvalDate"), rr.getString("sub_loan_no"), conn);
				for(String ss: uList)
				{
					// code develop on 21st May 2020, due to Loan Overtime
					SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy");
				//	//System.out.println(startDate+"========="+rr.getString("sub_loan_no")+" Lst EMI: "+f.parse(dList.get(dList.size()-1)));
				//	//System.out.println(dt);
					if(startDate.after(f.parse(dList.get(dList.size()-1))))
					{
						double totToPaid=rr.getInt("terms")*rr.getInt("emi");
						double diff=totToPaid-loanPaidAmountByUser("grouploan", rr.getString("sub_loan_no"), conn);
						////System.out.println(loanNo+" totToPaid:"+totToPaid+" loanTotPaidAmount:"+loanTotPaidAmount+" Diff:"+diff);
						if(diff>0)
						{
							if(list.size()>0)
							{
								boolean  chk=true;
								for(int i=0;i<list.size();i++)
								{
									if(String.valueOf(list.get(i).getValue()).equalsIgnoreCase(rr.getString("center")))
									{
										chk=false;
										break;
									}
								}
								
								if(chk==true)
								{
									SelectItem si=new SelectItem();
									
									si.setLabel(centerNameById(rr.getString("center"), conn));
									si.setValue(rr.getString("center"));
									
									list.add(si);
									
									break;
								}
							}
							else
							{
								SelectItem si=new SelectItem();
								
								si.setLabel(centerNameById(rr.getString("center"), conn));
								si.setValue(rr.getString("center"));
								
								list.add(si);
								
								break;
							}
						}
					}
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}
	
	public String qrCodeScanImage(int branchId)
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		
		String qr=fileViewPathDetail(conn)+"/qr_scan.jpg";
		
		String qq="select qr_code_image from firm_detail where id='"+branchId+"'";
		try(PreparedStatement st = conn.prepareStatement(qq)) {
			
			ResultSet rr = st.executeQuery();
			if(rr.next())
			{
				qr=fileViewPathDetail(conn)+"/"+rr.getString("qr_code_image");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return qr;
	}
	
	public double findCashBalance(int branchId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from company_shares where branch_id='"+branchId+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return Double.parseDouble(df.format(rr.getDouble("company_capital_amount")-rr.getDouble("amount_shared")));
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;
	}
	
	public int updateCashBalance(double cashBalance, int branchId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update company_shares set company_capital_amount='"+cashBalance+"',  amount_shared='0' where branch_id='"+branchId+"' ";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
				dataInsertInQueryTable(qq, conn);
				return i;
			}
		}
		catch(Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		return 0;	
	}
	
	public boolean checkDataFreezeValidation(Date date) 
	{
		String dt=sdfForDb.format(date);
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from fy_setting where financial_year='"+selectedSessionDetail()+"' and data_freeze_status='no' and fy_start_date<='"+dt+"'"
					+ " and fy_end_date>='"+dt+"' ";
		//	//System.out.println(qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return true;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return false;
	}

	public double preEmiChargeCalculationMethod(String loanNo, String loanType, Connection conn) 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		Statement st=null;
		ResultSet rr=null;
		String qq="";
		Date firstEmiDate=null;
		double preEmiCharge=0;
		
		
			
		
		
		try
		{
			st=conn.createStatement();
			if(loanType.equalsIgnoreCase("grouploan"))
			{
				qq="select * from grouploan where status='Approve' and sub_loan_no='"+loanNo+"' and paidStatus='unpaid' ";
			}
			else
			{
				qq="select * from "+loanType+" where status='Approve' and loanNo='"+loanNo+"' and paidStatus='unpaid' ";
			}
			//System.out.println(qq);
			rr=st.executeQuery(selectQueWithBranch(qq, branchId));
			if(rr.next())
			{
				if(checkGroupLoanEmiFromTable(loanNo,conn)==true)
				{
					firstEmiDate=groupLoanEmiDateFromTable(1, loanNo, conn);
					//System.out.println(loanNo+" if "+firstEmiDate);
				}
				else
				{
					if(rr.getDate("emi_due_date")!=null)
					{
						firstEmiDate=rr.getDate("emi_due_date");
					}
				}	
				if(firstEmiDate!=null)
				{
					int days = (int) ((firstEmiDate.getTime() - rr.getDate("approvalDate").getTime()) / (1000 * 60 * 60 * 24));
	                int freq=frequencyValue(rr.getString("frequency"));
	                if(days>freq)
	                {
	               	  int diffDays=days-freq;
	               	  preEmiCharge=(rr.getDouble("loanAmount")*rr.getDouble("interest")*diffDays)/36500;
	        			 preEmiCharge=Math.round(preEmiCharge);
	                }
				}
			}
		}

		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return preEmiCharge;
		
	}
	
	public List<CoapplicantInfo> showOhterListValues(String loanNo,Connection con) 
	{
		Statement st = null;
		ResultSet rs = null;
		List<CoapplicantInfo> coList = new ArrayList<CoapplicantInfo>();
		try 
		{
			st=con.createStatement();
			
			String query ="select id,city,title,first_applicantName,relation,dob,gender,marital_status,bank_accountNo,bank_name,branch,address,mobile,"
					+ "email, qualification, occupation, bank_ifsc,monthly_income,user_type,address,perAddress,category,PAN,voter_id,"
					+ "unique_id,ration_no,dl_no,res_cert,elect_bill,t_bill,g_cheque from coapplicant_table where loan_no='"+loanNo+"'";
			rs=st.executeQuery(query);
			
			while(rs.next())
			{
				CoapplicantInfo obj = new CoapplicantInfo();
				
				obj.setId(rs.getInt("id"));
				obj.setCityName(rs.getString("city"));
				obj.setTitle(rs.getString("title"));
				obj.setFirst_applicantName(rs.getString("first_applicantName"));
				obj.setRelation(rs.getString("relation"));
				obj.setDob(rs.getDate("dob"));
				obj.setGender(rs.getString("gender"));
				obj.setMaritalStatus(rs.getString("marital_status"));
				obj.setBank_accountNo(rs.getString("bank_accountNo"));
				obj.setBank_name(rs.getString("bank_name"));
				obj.setAddress(rs.getString("address"));
				obj.setMobile(rs.getString("mobile"));
				obj.setBranch(rs.getString("branch"));
				obj.setEmail(rs.getString("email"));
				obj.setQualification(rs.getString("qualification"));
				obj.setOccupation(rs.getString("occupation"));
				obj.setBankIfsc(rs.getString("bank_ifsc"));
				obj.setMonthlyIncome(rs.getString("monthly_income"));
				obj.setPerAddress(rs.getString("perAddress"));
				obj.setCategory(rs.getString("category"));
				obj.setUserType(rs.getString("user_type"));
				obj.setPAN(rs.getString("PAN"));
				obj.setVotrId(rs.getString("voter_id"));
				obj.setUniqueId(rs.getString("unique_id"));
				obj.setRationNo(rs.getString("ration_no"));
				obj.setDlNo(rs.getString("dl_no"));
				obj.setResCert(rs.getString("res_cert"));
				obj.setElectBill(rs.getString("elect_bill"));
			//	obj.setTBill(rs.getString("t_bill"));
			//	obj.setGCheque(rs.getString("g_cheque"));
							
				coList.add(obj);
			}
			
		} 
		catch (Exception e) {
			// TODO: handle exception
		}
		finally {
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return coList;
	}
	
	// This Method use to Insert the All Detail of new Member and share alloted direct by the Comapny/Nidhi.
		public boolean addGuarantor(int branchId,String office_application_no,Date office_date, String shareNo,String first_applicantName,
		Date dob, String father_husband_name,String guardian_name,String guardian_relation, String status,String pAN,String bank_accountNo,
		String bank_name, String branch,String address, String mobile,String nominee_name,String nominee_relation, Date nominee_dob,
		String nominee_address,String applicant_photoPath, double noOfShare,double shareAmount,double totalAmount,String perAddress,
		String signPath, String formPath, String category, String crNo, String votrId, String uniqueId, String rationNo, String dlNo, 
		String electBill, String resCert, String appCheque, String gCheque, String submittedBankName, String tBill, 
		String paymentMode, String bankNameCheque, String chequeNo, String doc1Path, String doc2Path, String doc3Path, String doc4Path, String doc5Path, 
		int issueShare, String doc6Path, String doc7Path,String doc8Path, String city, String relation, String gender, String maritalStatus, 
		String keyPersonName, String keyPersonRelation, String telephoneIndicator, int noOfDependent, String religion, String stateCode, String pinCode, String dsaCode,
		String email, String qualification, String occupation, String bankIfsc, String referenceBy, String remark, String title, String monthlyIncome,String userType,String loanNo ,Connection conn)
		{	
	        Timestamp ndbdt=null,ofcdt=null,dbdt=null;
			String chqStatus="";
			
			if(paymentMode.equalsIgnoreCase("cash"))
			{
				chqStatus="cleared";
			}
			
			else
			{
				chqStatus="uncleared";
			}
			
			HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			
			String userId=(String) ss1.getAttribute("username");
			
			if(office_date!=null)
			{
				ofcdt = new Timestamp(office_date.getTime());
			}
			
			if(dob!=null)
			{
				dbdt = new Timestamp(dob.getTime());
			}
						
			Statement st=null;
			
			if(nominee_dob!=null)
			{
				ndbdt= new Timestamp(nominee_dob.getTime());
			}
			
			try  
			{
				String query = "insert into coapplicant_table(office_application_no, office_date,shareholderno,first_applicantName,dob,"
				+ "father_husband_name, guardian_name, guardian_relation, status, PAN, bank_accountNo, bank_name, branch, address, mobile,"
				+ "nominee_name, nominee_relation, nominee_dob, nominee_address, applicant_photo, account_status, noofShare, shareAmount,"
				+ "totalAmount,perAddress,category,signPhoto,formPhoto,transfer_from,crNo,  voter_id, unique_id, ration_no, dl_no, elect_bill, res_cert, "
				+ "app_cheque, g_cheque, transfer_to_bank,t_bill,pay_mode,bank_name_cheque,cheque_no, doc1, doc2,doc3,doc4,doc5, issue_share,user_id, cheque_status,"
				+ "doc6,doc7,doc8, city, relation, gender, marital_status, key_person_name, key_person_relation, telephone_indicator, no_of_dependent, religion, "
				+ "state_code, pin_code, dsacode, branch_id,email, qualification, occupation, bank_ifsc, reference_by, remark, title, monthly_income,user_type,loan_no) "
				+ "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,"
				+ "?,?,?,?,?,?,?,?)";
				
				
				PreparedStatement st1 = conn.prepareStatement(query);
				st1.setString(1, office_application_no);
				st1.setTimestamp(2, ofcdt);
				st1.setString(3, shareNo);
				st1.setString(4, first_applicantName);
				st1.setTimestamp(5, dbdt);
				st1.setString(6, father_husband_name);
				st1.setString(7, guardian_name);
				st1.setString(8, guardian_relation);
				st1.setString(9, status);
				st1.setString(10, pAN);
				st1.setString(11, bank_accountNo);
				st1.setString(12, bank_name);
				st1.setString(13, branch);
				st1.setString(14, address.toUpperCase());
				st1.setString(15, mobile);
				st1.setString(16, nominee_name);
				st1.setString(17, nominee_relation);
				st1.setTimestamp(18, ndbdt);
				st1.setString(19, nominee_address);
				st1.setString(20, applicant_photoPath);
				st1.setString(21, "active");
				st1.setDouble(22, noOfShare);
				st1.setDouble(23, shareAmount);
				st1.setDouble(24, totalAmount);
				st1.setString(25, perAddress);
				st1.setString(26, category);
				st1.setString(27, signPath);
				st1.setString(28, formPath);
				st1.setString(29, "");
				st1.setString(30, crNo);
				st1.setString(31, votrId);
				st1.setString(32, uniqueId);
				st1.setString(33, rationNo);
				st1.setString(34, dlNo);
				st1.setString(35, electBill);
				st1.setString(36, resCert);
				st1.setString(37, appCheque);
				st1.setString(38, gCheque);
				st1.setString(39, submittedBankName);
				st1.setString(40, tBill);
				st1.setString(41, paymentMode);
				st1.setString(42, bankNameCheque);
				st1.setString(43, chequeNo);
				st1.setString(44, doc1Path);
				st1.setString(45, doc2Path);
				st1.setString(46, doc3Path);
				st1.setString(47, doc4Path);
				st1.setString(48, doc5Path);
				st1.setInt(49, issueShare);
				st1.setString(50, userId);	
				st1.setString(51, chqStatus);
				st1.setString(52, doc6Path);
				st1.setString(53, doc7Path);
				st1.setString(54, doc8Path);
				st1.setString(55, city);
				st1.setString(56, relation);
				st1.setString(57, gender);
				st1.setString(58, maritalStatus);
				st1.setString(59, keyPersonName);
				st1.setString(60, keyPersonRelation);
				st1.setString(61, telephoneIndicator);
				st1.setInt(62, noOfDependent);
				st1.setString(63, religion);
				st1.setString(64, stateCode);
				st1.setString(65, pinCode);
				st1.setString(66, dsaCode);
				st1.setInt(67, branchId);
				st1.setString(68, email);
				st1.setString(69, qualification);
				st1.setString(70, occupation);
				st1.setString(71, bankIfsc);
				st1.setString(72, referenceBy);
				st1.setString(73, remark);
				st1.setString(74, title);
				st1.setString(75, monthlyIncome);
				st1.setString(76, userType);
				st1.setString(77, loanNo);
				int i = st1.executeUpdate();
				if(i>0)
				{
					dataInsertInQueryTable(String.valueOf(st1), conn);
					return true;
				}
				
			
			} 
			catch (Exception e) 
			{
				 e.printStackTrace();fileCreation(e.getMessage());
			}
			finally
			{
				try {
					if(st!=null)
					{
						st.close();
					}
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
			return false;
		}

		public boolean updateGuarantor(int id, String office_application_no, Date office_date, String shareNo,String first_applicantName,
		Date dob,String father_husband_name, String guardian_name,String guardian_relation,String status,String pAN,String bank_accountNo,
		String bank_name, String branch, String address,String mobile,String nominee_name, String nominee_relation, Date nominee_dob,
		String nominee_address,String applicant_photoPath, double noOfShare,double shareAmount, double totalAmount,String category,String
		perAddress, String signPath, String formPath, String votrId, String uniqueId, String rationNo, String dlNo, String electBill, 
		String resCert, String appCheque, String gCheque, String tBill, String doc1Path, String doc2Path, String doc3Path, String doc4Path, 
		String doc5Path, String doc6Path, String doc7Path, String doc8Path, String gender, String maritalStatus, String keyPersonName, String keyPersonRelation, 
		String telephoneIndicator, int noOfDependent, String religion, String stateCode, String pinCode, String email, String qualification, String occupation, 
		String bankIfsc, String referenceBy, String remark, String title, String monthlyIncome,String relation,Connection conn)
		{
				Timestamp ofcdt =null,dbdt=null,ndbdt=null;
				if(office_date!=null)
				{
					ofcdt = new Timestamp(office_date.getTime());
				}
				if(dob!=null)
				{
					dbdt = new Timestamp(dob.getTime());
				}
				if(nominee_dob!=null)
				{
					ndbdt= new Timestamp(nominee_dob.getTime());
				}
				
				try 
				{
					String query="update coapplicant_table set office_application_no=?,office_date=?,shareholderno=?,first_applicantName=?,"
					+ "dob=?, father_husband_name=?, guardian_name=?, guardian_relation=?, status=?,PAN=?, bank_accountNo=?, bank_name=?,"
					+ "branch=?, address=?, mobile=?,nominee_name=?, nominee_relation=?, nominee_dob=?,nominee_address=?,applicant_photo=?,"
					+ "account_status=?,noofShare=?,shareAmount=?,totalAmount=?,perAddress=?,category=?,signPhoto=?,formPhoto=?, "
					+ "voter_id=?, unique_id=?, ration_no=?, dl_no=?, elect_bill=?, res_cert=?, app_cheque=?, g_cheque=?, t_bill=?, "
					+ "doc1=?, doc2=?, doc3=?, doc4=?, doc5=?, doc6=?, doc7=?, doc8=?, gender=?, marital_status=?, key_person_name=?, key_person_relation=?, "
					+ "telephone_indicator=?, no_of_dependent=?, religion=?, state_code=?, pin_code=?, email=?, qualification=?, occupation=?, bank_ifsc=?, reference_by=?,"
					+ " remark=?, title=?, monthly_income=?,relation=? where id='"+id+"'";
					PreparedStatement st1 = conn.prepareStatement(query);
					st1.setString(1, office_application_no);
					st1.setTimestamp(2, ofcdt);
					st1.setString(3, shareNo);
					st1.setString(4, first_applicantName);
					st1.setTimestamp(5, dbdt);
					st1.setString(6, father_husband_name);
					st1.setString(7, guardian_name);
					st1.setString(8, guardian_relation);
					st1.setString(9, status);
					st1.setString(10, pAN);
					st1.setString(11, bank_accountNo);
					st1.setString(12, bank_name);
					st1.setString(13, branch);
					st1.setString(14, address);
					st1.setString(15, mobile);
					st1.setString(16, nominee_name);
					st1.setString(17, nominee_relation);
					st1.setTimestamp(18, ndbdt);
					st1.setString(19, nominee_address);
					st1.setString(20, applicant_photoPath);
					st1.setString(21, "active");
					st1.setDouble(22, noOfShare);
					st1.setDouble(23, shareAmount);
					st1.setDouble(24, totalAmount);
					st1.setString(25, perAddress);
					st1.setString(26, category);
					st1.setString(27, signPath);
					st1.setString(28, formPath);
					st1.setString(29, votrId);
					st1.setString(30, uniqueId);
					st1.setString(31, rationNo);
					st1.setString(32, dlNo);
					st1.setString(33, electBill);
					st1.setString(34, resCert);
					st1.setString(35, appCheque);
					st1.setString(36, gCheque);
					st1.setString(37, tBill);
					st1.setString(38, doc1Path);
					st1.setString(39, doc2Path);
					st1.setString(40, doc3Path);
					st1.setString(41, doc4Path);
					st1.setString(42, doc5Path);
					st1.setString(43, doc6Path);
					st1.setString(44, doc7Path);
					st1.setString(45, doc8Path);
					st1.setString(46, gender);
					st1.setString(47, maritalStatus);
					st1.setString(48, keyPersonName);
					st1.setString(49, keyPersonRelation);
					st1.setString(50, telephoneIndicator);
					st1.setInt(51, noOfDependent);
					st1.setString(52, religion);
					st1.setString(53, stateCode);
					st1.setString(54, pinCode);
					st1.setString(55, email);
					st1.setString(56, qualification);
					st1.setString(57, occupation);
					st1.setString(58, bankIfsc);
					st1.setString(59, referenceBy);
					st1.setString(60, remark);
					st1.setString(61, title);
					st1.setString(62, monthlyIncome);
					st1.setString(63, relation);
					int i = st1.executeUpdate();
					if (i >0)
					{
						dataInsertInQueryTable(String.valueOf(st1), conn);
						return true;
					}
						
				} 
				catch (Exception e)
				{
					 e.printStackTrace();fileCreation(e.getMessage());
				}
				return false;
			}
		
	public Date checkSoftwareValidity() 
	{
		Statement st=null;
		ResultSet rr=null;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			st=conn.createStatement();
			String query="select software_validity from firm_detail  ";
			rr=st.executeQuery(query);
			if(rr.next())
			{
				return rr.getDate("software_validity");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return new Date();
	}	
	
	// to find share holder name by shareholder no
	public String cityNameById(String city, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select cityname from cityname where id='"+city+"' ";
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("cityname");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return "";
	}
	
	public int updateCompanyDetail(UserInfo companyDetail, int branchId, String qrPhotoPath) 
	{
		PreparedStatement ps = null;
	        try(Connection conn=DataBaseConnection.JAVAConnection()) 
	        {
	      	 String query="update firm_detail set address1=?,address2=?,address3=?,address4=?,mobile_no=?,member_age_limit=?,qr_code_image=? where id='"+branchId+"' "; 
	  		 ps=conn.prepareStatement(query);
	  		 ps.setString(1, companyDetail.getAddress1());
	  		 ps.setString(2, companyDetail.getAddress2());
	  		 ps.setString(3, companyDetail.getAddress3());
	  		 ps.setString(4, companyDetail.getAddress4());
	  		 ps.setString(5, companyDetail.getMobile());
	  		 ps.setInt(6, companyDetail.getMemberAgeLimit());
	  		 ps.setString(7, qrPhotoPath);
	  		// System.out.println(ps);
	  		 int res = ps.executeUpdate();
	  		 return res;
	  		 
	  	  }
	        catch (Exception e) {}
	       finally {
	  		try {
	  			if(ps!=null)
	  			{
	  				ps.close();
	  			}
	  		} catch (Exception e2) {
	  			// TODO: handle exception
	  		}
	  	 }
		return 0;
	}

	public ArrayList<SavingAccountInfo> savingAccountListByCenter(int branchId, String center, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		int count=1;
		ArrayList<SavingAccountInfo> list=new ArrayList<>();
		try
		{
			st=conn.createStatement();
			String qq="select * from savingaccount where accountStatus='open' and center='"+center+"' ";
			rr=st.executeQuery(qq);
			while(rr.next())
			{
				SavingAccountInfo ss=new SavingAccountInfo();
				
				ss.setSno(count++);
				ss.setAccountNo(rr.getString("accountNo"));
				ss.setStartDate(rr.getDate("openDate"));
				ss.setStrStartDate(sf.format(ss.getStartDate()));
				ss.setShareHolderNo(rr.getString("shareHolderNo"));
				ss.setDsacode(rr.getString("dsacode"));
				ss.setAmount(20);
				
				UserInfo uu=memberBasicDetail(ss.getShareHolderNo(), conn);
				ss.setFirst_applicant_name(uu.getName());
				ss.setFatherHusbandName(uu.getFather_husband_name());
				ss.setContactNo(uu.getContactNo());
				ss.setBtnName(uu.getAddress());
				
				list.add(ss);
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}
	
	public ArrayList<SelectItem> depositNoListSchemeWise(String searchType, int branchId) 
	{
		ArrayList<SelectItem> list=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			st=conn.createStatement();
			String query="select user_no,first_applicantName,father_husband_name from customer_info inner join shareholder_info where customer_info.account_status!='pending'"
					+ " and paid_status='unpaid' and shareholder_info.shareholderno=customer_info.shareHolderNo and scheme_type='"+searchType+"' and customer_info.branch_id='"+branchId+"' ";
			rr=st.executeQuery(query);
			while(rr.next())
			{
				SelectItem ss=new SelectItem();
				
				ss.setLabel(rr.getString("user_no")+" - "+rr.getString("first_applicantName")+ " - "+rr.getString("father_husband_name"));
				ss.setValue(rr.getString("user_no"));
				
				list.add(ss);
			}
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally 
        {
            try 
            {
            	if(st!=null)
            	{
            		  st.close();
                }
            	if(rr!=null)
            	{
            	     rr.close();
                }
            } 
            catch (Exception s) 
            {
                fileCreation(s.getMessage());
            }
        }
		return list;
	}	
	
	
//	public ArrayList<SelectItem> centerListOfParticularDate(int branchId, Date searchDate, String loanType, String dsaCode) 
//	{
//		String sDate=sf.format(searchDate);
//		ArrayList<SelectItem> list=new ArrayList<>();
//		try(Connection conn=DataBaseConnection.JAVAConnection())
//		{
//			Statement st=conn.createStatement();
//			String qq="select * from "+loanType+" where status='Approve' and paidStatus='unpaid'  ";
//			
//			if(!dsaCode.equalsIgnoreCase("all"))
//			{
//				qq+=" and dsacode='"+dsaCode+"' ";
//			}
//			////System.out.println(qq);
//			ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
//			while(rr.next())
//			{System.out.println("huh"+sDate);
//				String loanNo="";
//				if(loanType.equalsIgnoreCase("grouploan"))
//				{
//					loanNo=rr.getString("sub_loan_no");
//				}
//				else
//				{
//					loanNo=rr.getString("loanNo");
//				}
//				ArrayList<String> dList=loanEmiStrDateList(rr.getInt("frequency"), rr.getInt("terms"),rr.getDate("emi_due_date"),rr.getDate("approvalDate"), loanNo, conn);
//				if(dList.contains(sDate))
//				{
//					if(list.size()>0)
//					{
//						System.out.println(sDate);
//						boolean  chk=true;
//						for(int i=0;i<list.size();i++)
//						{
//							if(String.valueOf(list.get(i).getValue()).equalsIgnoreCase(rr.getString("center")))
//							{
//								chk=false;
//								break;
//							}
//						}
//						
//						if(chk==true)
//						{
//							SelectItem si=new SelectItem();
//							
//							si.setLabel(centerNameById(rr.getString("center"), conn));
//							si.setValue(rr.getString("center"));
//							
//							list.add(si);
//						}
//					}
//					else
//					{
//						SelectItem si=new SelectItem();
//						
//						si.setLabel(centerNameById(rr.getString("center"), conn));
//						si.setValue(rr.getString("center"));
//						
//						list.add(si);
//					}
//				}
//			}
//		}
//		catch(Exception e)
//		{
//			e.printStackTrace();
//		}
//		return list;
//	}

	
	public ArrayList<SelectItem> centerListOfParticularDate(int branchId, Date searchDate, Date fromsSearchDate, String loanType, String dsaCode) 
	{
		String sDate=sf.format(searchDate);
		String endDate =sf.format(fromsSearchDate);
		Calendar cal = Calendar.getInstance();
		cal.setTime(fromsSearchDate);
		ArrayList<SelectItem> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from "+loanType+" where status='Approve' and paidStatus='unpaid'  ";
			
			if(!dsaCode.equalsIgnoreCase("all"))
			{
				qq+=" and dsacode='"+dsaCode+"' ";
			}
			////System.out.println(qq);
			
			while (!cal.getTime().after(searchDate)) {
				String dateStr = sf.format(cal.getTime());
				ResultSet rr=st.executeQuery(selectQueWithBranch(qq,branchId));
				
			while(rr.next())
			{
				String loanNo="";
				if(loanType.equalsIgnoreCase("grouploan"))
				{
					loanNo=rr.getString("sub_loan_no");
				}
				else
				{
					loanNo=rr.getString("loanNo");
				}
				
				ArrayList<String> dList=loanEmiStrDateList(rr.getInt("frequency"), rr.getInt("terms"), rr.getDate("emi_due_date"),rr.getDate("approvalDate"), loanNo, conn);
				 {
				    
				   
				    
				    if (dList.contains(dateStr)) 
				{ 
				    	

					if(list.size()>0)
					{
						
						boolean  chk=true;
						for(int i=0;i<list.size();i++)
						{
							if(String.valueOf(list.get(i).getValue()).equalsIgnoreCase(rr.getString("center")))
							{
								chk=false;
								break;
							}
						}
						
						if(chk==true)
						{
							SelectItem si=new SelectItem();
							
							si.setLabel(centerNameById(rr.getString("center"), conn));
							si.setValue(rr.getString("center"));
							
							
							list.add(si);
						}
					}
					else
					{
						SelectItem si=new SelectItem();
						
						si.setLabel(centerNameById(rr.getString("center"), conn));
						si.setValue(rr.getString("center"));
						
						
						list.add(si);
					}
					
				}
				    
				}
			}
			cal.add(Calendar.DATE, 1);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}

	public ArrayList<String> fifteenDaysLoanStrDateList(Date date, Date secEmiDueDate, int terms)
	{
		ArrayList<String> dateList = null;
		int day1 = 0, day2=0, odd=1, even=1;
		if(date.getDate()>=17)
		{
			odd=2;
		}
		dateList=new ArrayList<>();
		for(int i=0;i<terms;i++)
		{
			Date dt=new Date();
	        int d=date.getDate();
	        int m=date.getMonth();
	        int y=date.getYear();
	        dt.setDate(d);
	        dt.setMonth(m);
	        dt.setYear(y);
		        
			if(i==0)
			{
				day1=dt.getDate();
				dateList.add(sdfForDb.format(dt));
			}
			if(i==1)
			{
				//dt.setDate(dt.getDate()+15);
				dt.setDate(secEmiDueDate.getDate());
				day2=dt.getDate();
				dt.setMonth(secEmiDueDate.getMonth());
				dateList.add(sdfForDb.format(dt));
			}
			
			if(i>=2)
			{
				if(i%2==0)
				{
					dt.setDate(day1);
					dt.setMonth(dt.getMonth()+even++);
					dateList.add(sdfForDb.format(dt));
				}
				else
				{
					dt.setDate(day2);
					dt.setMonth(dt.getMonth()+odd++);
					dateList.add(sdfForDb.format(dt));
				}
			}
			
			dt.setHours(00);
	        dt.setMinutes(00);
	        dt.setSeconds(00);
		}
		return dateList;
	}

	public int updateRequest(String memberNo, String latitude, String longitude, String memberPhotoPath, String userId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="insert into reg_update_table(share_holder_no, latitude, longitude, photo, user_id) values('"+memberNo+"','"+latitude+"','"+longitude+"',"
					+ " '"+memberPhotoPath+"','"+userId+"')";
			//System.out.println(qq);
			int i=st.executeUpdate(qq);
			return i;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}
	
	public ArrayList<String> memberGuarantorLoanDetailListMethod(String shareHolderNo, Connection conn) 
	{
		ArrayList<String> list=new ArrayList<>();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select * from personalloan where (firstguarantor like '"+shareHolderNo+"%' or secondguarantor like '"+shareHolderNo+"%') and status='Approve' "
					+ "and paidStatus='unpaid' ";
			rr=st.executeQuery(qq);
			while(rr.next())
			{
				ArrayList<LoanInfo> loanEMIList=loanInstallment("personalloan",rr.getString("loanNo"), conn);
				
				int currentDueEmi=0;double currentDueAmount=0;
				for(int l=0;l<loanEMIList.size();l++)
				{
					Date dt=new Date();
					if(loanEMIList.get(l).getStatus().equals("Paid"))
					{
						loanEMIList.get(l).setColorStatus("paid");
					} 
					
					
					
					else
					{
						if(loanEMIList.get(l).getInstallDate().before(dt))
						{
							loanEMIList.get(l).setColorStatus("due");
							if(loanEMIList.get(l).getColorStatus().equalsIgnoreCase("due"))
							{
								currentDueEmi+=1;
								currentDueAmount+=loanEMIList.get(l).getDueAmount();
							}
						}
						else
						{
							loanEMIList.get(l).setColorStatus("upcoming");
						}
					}
				}
				String name=applicantNameByShareHolderNo(rr.getString("shareholderno"), conn);
				String detail="Loan No. "+rr.getString("loanNo")+", Name: "+name+", Loan Amount Rs. : "+rr.getDouble("loanAmount")+", EMI Amount Rs. : "+rr.getDouble("emi")+", currentDueEmi: "
						+ ""+currentDueEmi+",  currentDueAmount: "+currentDueAmount;
				
				list.add(detail);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return list;
	}

	public void updateMemberLocationByMobileNo(String latitude, String longitude, String mobile) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="update shareholder_info set latitude='"+latitude+"', longitude='"+longitude+"' where mobile='"+mobile+"' ";
			//System.out.println(qq);
			st.executeUpdate(qq);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public int addManualCharges(String loanNo, String loanType, Date chargesDate, int chargesAmount, String remark) 
	{
		Timestamp tt=null;
		if(chargesDate!=null)
		{
			tt=new Timestamp(chargesDate.getTime());
		}
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="insert into manual_charges(loan_no, loan_type, date, amount, remark) values('"+loanNo+"','"+loanType+"','"+tt+"','"+chargesAmount+"','"+remark+"')";
			//System.out.println(qq);
			int i=st.executeUpdate(qq);
			return i;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}
	
	public ArrayList<BorrowerLenderInfo> manualChargesDataList(String loanNo, String loanType) 
	{
		int count=1;
		ArrayList<BorrowerLenderInfo> list=new ArrayList<>();
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select * from manual_charges where loan_no='"+loanNo+"' and loan_type='"+loanType+"' ";
			ResultSet rr=st.executeQuery(qq);
			while(rr.next())
			{
				BorrowerLenderInfo bb=new BorrowerLenderInfo();
				
				bb.setSno(count++);
				bb.setId(rr.getString("id"));
				bb.setReason(rr.getString("remark"));
				bb.setEntryDate(rr.getDate("date"));
				bb.setAmount(rr.getInt("amount"));
				
				list.add(bb);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return list;
	}

	public int deleteManualChargeEntry(String id)
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="delete from manual_charges where id='"+id+"' ";
			//System.out.println(qq);
			int i=st.executeUpdate(qq);
			return i;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}
	
	public int backEntryDaysForEmployee(String userId, Connection conn) 
	{
		Statement st=null;
		ResultSet rs=null;
		try
		{
			st=conn.createStatement();
			String qq="select entry_back_days from employee where uname='"+userId+"' ";
			rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getInt("entry_back_days");
			}
		}
		
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
		return 0;
	}

	public ArrayList<SelectItem> qualificationList() 
	{
		ArrayList<SelectItem> list=new ArrayList<>();

		SelectItem ss=new SelectItem();
		ss.setLabel("5th");
		ss.setValue("5th");
		list.add(ss);
		
		SelectItem ss1=new SelectItem();
		ss1.setLabel("8th");
		ss1.setValue("8th");
		list.add(ss1);
		
		SelectItem ss2=new SelectItem();
		ss2.setLabel("10th");
		ss2.setValue("10th");
		list.add(ss2);
		
		
		SelectItem ss3=new SelectItem();
		ss3.setLabel("12th");
		ss3.setValue("12th");
		list.add(ss3);
		
		SelectItem ss7=new SelectItem();
		ss7.setLabel("Diploma");
		ss7.setValue("Diploma");
		list.add(ss7);
		
		SelectItem ss4=new SelectItem();
		ss4.setLabel("Graduation");
		ss4.setValue("Graduation");
		list.add(ss4);
		
		SelectItem ss5=new SelectItem();
		ss5.setLabel("PG");
		ss5.setValue("PG");
		list.add(ss5);
		
		SelectItem ss6=new SelectItem();
		ss6.setLabel("Other");
		ss6.setValue("Other");
		list.add(ss6);
		
		return list;
	}
	
	public ArrayList<SelectItem> occupationList() 
	{
		ArrayList<SelectItem> list=new ArrayList<>();

		SelectItem ss=new SelectItem();
		ss.setLabel("Farmer");
		ss.setValue("Farmer");
		list.add(ss);
		
		SelectItem ss1=new SelectItem();
		ss1.setLabel("Salaried");
		ss1.setValue("Salaried");
		list.add(ss1);
		
		SelectItem ss2=new SelectItem();
		ss2.setLabel("Self-Employed");
		ss2.setValue("Self-Employed");
		list.add(ss2);
		
		
//		SelectItem ss3=new SelectItem();
//		ss3.setLabel("12th");
//		ss3.setValue("12th");
//		list.add(ss3);
//		
//		SelectItem ss7=new SelectItem();
//		ss7.setLabel("Diploma");
//		ss7.setValue("Diploma");
//		list.add(ss7);
//		
//		SelectItem ss4=new SelectItem();
//		ss4.setLabel("Graduation");
//		ss4.setValue("Graduation");
//		list.add(ss4);
//		
//		SelectItem ss5=new SelectItem();
//		ss5.setLabel("PG");
//		ss5.setValue("PG");
//		list.add(ss5);
		
		SelectItem ss6=new SelectItem();
		ss6.setLabel("Other");
		ss6.setValue("Other");
		list.add(ss6);
		
		return list;
	}

	public int checkApiBalance(String apiService) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select api_bal from api_table where api_service='"+apiService+"' ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getInt("api_bal");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}
	
	public String checkApiKey() 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="select api_key from api_table ";
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getString("api_key");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return "";
	}

	public int addApiHitData(String apiService, String apiNo, String userId) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String qq="insert into api_data(api_service, api_no, user_id) values('"+apiService+"','"+apiNo+"','"+userId+"')";
			int i=st.executeUpdate(qq);
			if(i>0)
			{
				updateApiBalance(apiService,conn);
				return i;
			}
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return 0;
	}

	private void updateApiBalance(String apiService, Connection conn) 
	{
		int bal=checkApiBalance(apiService);
		bal=bal-1;
		try
		{
			Statement st=conn.createStatement();
			String qq="update api_table set api_bal="+bal+" where api_service='"+apiService+"' ";
			st.executeUpdate(qq);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	public void updateJournalEntryStatus(String id, Date paidDate, Connection conn) 
	{
		String sDate=sdfForDb.format(paidDate);
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="update journal_entry set status='inactive', clear_date='"+sDate+"' where id='"+id+"' ";
			////System.out.println(qq);
			st.executeUpdate(qq);			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
	public double bookedEntryAmountByTransTypeForProfitLoss(String string, Connection conn) 
	{
		HeaderBean hh=new HeaderBean();
		Statement st=null, st1=null;
		ResultSet rr=null, rr1=null;
		double bookAmount=0, clearAmount=0;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount) from journal_entry where trans_type='"+string+"' and book_date>='"+sdfForDb.format(hh.getMinFinYearDate())+"' and"
					+ " book_date<='"+sdfForDb.format(hh.getMaxFinYearDate())+"' and status!='delete' ";
			//System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				bookAmount=rr.getDouble("sum(amount)");
			}
			
			st1=conn.createStatement();
			String qq1="select sum(amount) from journal_entry where trans_type='"+string+"' and clear_date>='"+sdfForDb.format(hh.getMinFinYearDate())+"' and"
					+ " clear_date<='"+sdfForDb.format(hh.getMaxFinYearDate())+"' and status='clear' ";
			//System.out.println(qq1);
			rr1=st1.executeQuery(qq1);
			if(rr1.next())
			{
				clearAmount=rr1.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
				if(st1!=null)
				{
					st1.close();
				}
				if(rr1!=null)
				{
					rr1.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return bookAmount-clearAmount;
	}
	
	public double bookedEntryAmountByTransTypeForBalanceSheet(String string, Connection conn) 
	{
		HeaderBean hh=new HeaderBean();
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(amount) from journal_entry where trans_type='"+string+"' and status='active' and "
					+ " book_date<='"+sdfForDb.format(hh.getMaxFinYearDate())+"' ";
			//System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(amount)");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	public double depreciationAmount(String endFinYear, Connection conn) 
	{
		Statement st=null;
		ResultSet rr=null;
		try
		{
			st=conn.createStatement();
			String qq="select sum(dep_value) from depreciation where dep_year='"+endFinYear+"' ";
		//	//System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return rr.getDouble("sum(dep_value)");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return 0;
	}
	
	public int insertLoanOtherDetail(ArrayList<LoanInfo> otherList, String loanNo) 
	{
		int i=0;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			String query="insert into secure_loan_other(loan_no, p_itemname, property_detail, p_area, p_marketvalue, p_remark, ss_name, no_ofshare, "
					+ "ss_pmr, ss_totalvalue, ss_netvalue, si_name, si_policyno, si_sv, si_dos, si_dop, v_type, v_company, v_engineno, v_model, v_marketvalue, v_regowner, "
					+ "v_regno, v_chesisno, g_itemname, g_qty, g_grossweight, g_netweight, g_purityweight, g_marketvalue, g_remark, gold_image) "
					+ "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			for(LoanInfo ll: otherList)
			{
				PreparedStatement st=conn.prepareStatement(query);
				Timestamp tt=null, tt1=null;
				
				if(ll.getGoldImage()!=null)
				{
					ll.setGoldImagePath(ll.getGoldImage().getFileName());
					makeProfile(ll.getGoldImage(), ll.getGoldImagePath());
				}
				
				if (ll.getGoldImage() != null && ll.getGoldImage().getSize() > 0) 
				{
					ll.goldImagePath = ll.getGoldImage().getFileName();
					String exten[]=ll.getGoldImagePath().split("\\.");
					
					makeProfile(ll.getGoldImage(), ll.getGoldImagePath());
				}
				
				
				if(ll.getSiDop()!=null)
				{
					tt=new Timestamp(ll.getSiDop().getTime());
				}
				if(ll.getSiDos()!=null)
				{
					tt1=new Timestamp(ll.getSiDos().getTime());
				}
				
				st.setString(1, loanNo);
				st.setString(2, ll.getpItemName());
				st.setString(3, ll.getPropertyDetail());
				st.setString(4, ll.getpArea());
				st.setString(5, ll.getpMarketValue());
				st.setString(6, ll.getpRemark());
				st.setString(7, ll.getSsName());
				st.setString(8, ll.getNoOfShare());
				st.setString(9, ll.getSsPmr());
				st.setString(10, ll.getSsTotalValue());
				st.setString(11, ll.getSsNetValue());
				st.setString(12, ll.getSiName());
				st.setString(13, ll.getSiPolicyNo());
				st.setString(14, ll.getSiSv());
				st.setTimestamp(15, tt);
				st.setTimestamp(16, tt1);
				st.setString(17, ll.getvType());
				st.setString(18, ll.getvCompany());
				st.setString(19, ll.getvEngineNo());
				st.setString(20, ll.getvModel());
				st.setString(21, ll.getvMarketValue());
				st.setString(22, ll.getvRegOwner());
				st.setString(23, ll.getvRegNo());
				st.setString(24, ll.getvChesisNo());
				st.setString(25, ll.getgItemName());
				st.setString(26, ll.getgQty());
				st.setString(27, ll.getgGrossWeight());
				st.setString(28, ll.getgNetWeight());
				st.setString(29, ll.getgPurityWeight());
				st.setString(30, ll.getgMarketValue());
				st.setString(31, ll.getgRemark());
				st.setString(32, ll.getGoldImagePath());
				
				i=st.executeUpdate();
				
				
				
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return i;
	}
	
	public ArrayList<LoanInfo> showOhterListValues(String loanNo) 
	{
		ArrayList<LoanInfo> list=new ArrayList<>();
		int count=1;
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="select * from secure_loan_other where loan_no='"+loanNo+"' ";
			ResultSet rr=st.executeQuery(query);
			while(rr.next())
			{
				LoanInfo ff=new LoanInfo();
				
				ff.setSno(count++);
				ff.setpItemName(rr.getString("p_itemname"));
				ff.setPropertyDetail(rr.getString("property_detail"));
				ff.setpArea(rr.getString("p_area"));
				ff.setpMarketValue(rr.getString("p_marketvalue"));
				ff.setpRemark(rr.getString("p_remark"));
				ff.setSsName(rr.getString("ss_name"));
				ff.setNoOfShare(rr.getString("no_ofshare"));
				ff.setSsPmr(rr.getString("ss_pmr"));
				ff.setSsTotalValue(rr.getString("ss_totalvalue"));
				ff.setSsNetValue(rr.getString("ss_netvalue"));
				ff.setSiName(rr.getString("si_name"));
				ff.setSiPolicyNo(rr.getString("si_policyno"));
				ff.setSiSv(rr.getString("si_sv"));
				ff.setvType(rr.getString("v_type"));
				ff.setvCompany(rr.getString("v_company"));
				ff.setvEngineNo(rr.getString("v_engineno"));
				ff.setvModel(rr.getString("v_model"));
				ff.setvChesisNo(rr.getString("v_chesisno"));
				ff.setvRegNo(rr.getString("v_regno"));
				ff.setvRegOwner(rr.getString("v_regowner"));
				ff.setvMarketValue(rr.getString("v_marketvalue"));
				ff.setgItemName(rr.getString("g_itemname"));
				ff.setgQty(rr.getString("g_qty"));
				ff.setgGrossWeight(rr.getString("g_grossweight"));
				ff.setgNetWeight(rr.getString("g_grossweight"));
				ff.setgPurityWeight(rr.getString("g_purityweight"));
				ff.setgMarketValue(rr.getString("g_marketvalue"));
				ff.setgRemark(rr.getString("g_remark"));
				ff.setGoldImagePath(rr.getString("gold_image"));
				
				list.add(ff);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}
	
	
	public void deleteOtherDetailByLoanNo(String loanNo) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			Statement st=conn.createStatement();
			String query="delete from secure_loan_other where loan_no='"+loanNo+"' ";
			st.executeUpdate(query);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	public void deleteFromAddLoanCloser(String loanNo, Connection conn) 
	{
		Statement st=null;
		try
		{
			st=conn.createStatement();
			String qq="delete from add_loan_closer where loan_no='"+loanNo+"' ";
			st.executeUpdate(qq);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
	
	public String selectBranchIdGroupLoan(String loanNo)
	{
		String branchId="";
		
		try(Connection con=DataBaseConnection.JAVAConnection()) {
			
			Statement st=con.createStatement();
			String qq="select branch_id from grouploan where sub_loan_no='"+loanNo+"'";
			System.out.println("eeee"+qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				branchId=rr.getString("branch_id");
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		return branchId;
		
	}
	public String selectBranchIdPersonalLoan(String loanNo)
	{
		String branchId="";
		
		try(Connection con=DataBaseConnection.JAVAConnection()) {
			
			Statement st=con.createStatement();
			String qq="select branch_id from personalloan where loanNo='"+loanNo+"'";
			System.out.println("oooo"+qq);
			ResultSet rr=st.executeQuery(qq);
			if(rr.next())
			{
				branchId=rr.getString("branch_id");
			}
			
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
		return branchId;
		
	}
	
	public String adminSignScanImage()
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		
		String qr=fileViewPathDetail(conn)+"/admin_sign.jpg";
		System.out.println("iamge path is:"+qr);
		
		try 
		{
			conn.close();
		} 
		catch (SQLException e) 
		{
			e.printStackTrace();
		}
		return qr;
	}
	
	public void updatePaidStatusLoanTables(String loanNo, String loanType, Connection conn) 
	{
		String qq="";
		Statement st=null;
		try
		{
			st=conn.createStatement();
			if(loanType.equalsIgnoreCase("grouploan"))
			{
				qq="update grouploan set paidStatus='unpaid' where sub_loan_no='"+loanNo+"' ";
			}
			else
			{
				qq="update "+loanType+" set paidStatus='unpaid' where loanNo='"+loanNo+"' ";
			}
			//System.out.println(qq);
			st.executeUpdate(qq);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(st!=null)
				{
					st.close();
				}
			} 
			catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
	
	

	public String fetchDataBymerchantId(String umrn) {
	    
	    String query = "SELECT loan_no FROM nach_mandate_request WHERE umrn = ?";
	    String loanNo = null;

	    try (Connection conn = DataBaseConnection.JAVAConnection();
	         PreparedStatement ps = conn.prepareStatement(query)) {

	        ps.setString(1, umrn); 
	        try (ResultSet rs = ps.executeQuery()) {
	            if (rs.next()) {
	            
	                loanNo = rs.getString("loan_no"); 
	            }
	        }

	    } catch (Exception e) {
	        e.printStackTrace(); 
	    }
	   
	    return loanNo;
	}

public String fetchLoanNoBymerchantIdCF(String umrn) {
	    
		
	    String query = "SELECT loan_no FROM subscriptions_overview WHERE authorization_reference = ?";
	    String loanNo = null;

	    try (Connection conn = DataBaseConnection.JAVAConnection();
	         PreparedStatement ps = conn.prepareStatement(query)) {

	        ps.setString(1, umrn); 
	        try (ResultSet rs = ps.executeQuery()) {
	            if (rs.next()) {
	            	
	                loanNo = rs.getString("loan_no"); 
	            }
	        }

	    } catch (Exception e) {
	        e.printStackTrace(); 
	    }
	    
	    return loanNo;
	}

	public String fetchBranchIdByLoanNo(String loanNo) {
	    String tableName = loanNo.startsWith("PL") ? "personalloan"
	                     : loanNo.startsWith("SL") ? "secure_loan"
	                     : null;

	    if (tableName == null) {
	        System.err.println("Unknown loan type for loanNo: " + loanNo);
	        return null;
	    }

	    String query = "SELECT branch_id FROM " + tableName + " WHERE loanNo = ?";


	    String branchId = null;

	    try (Connection conn = DataBaseConnection.JAVAConnection();
	         PreparedStatement ps = conn.prepareStatement(query)) {

	        ps.setString(1, loanNo.trim());

	        try (ResultSet rs = ps.executeQuery()) {
	            if (rs.next()) {
	                branchId = rs.getString("branch_id");
	            } else {
	             //   System.out.println("No record found for loanNo: " + loanNo);
	            }
	        }

	    } catch (Exception e) {
	        e.printStackTrace();
	    }

	    return branchId;
	}

	public ArrayList<SelectItem> fetchBankCodeByNpci() {
	    ArrayList<SelectItem> codeList = new ArrayList<>();
	    String jsonResponse = null;

	    try {
	        jsonResponse = fetchLiveBankDetails();

	        if (jsonResponse == null || jsonResponse.trim().isEmpty() || !jsonResponse.trim().startsWith("{")) {
	            System.out.println("Live API failed — loading data from DB backup...");
	            return fetchBankCodeFromDb(); 
	        } else {
	            saveBankJsonToDb(jsonResponse);
	        }

	        JSONObject jsonObject = new JSONObject(jsonResponse);
	        JSONArray bankList;

	        if (jsonObject.has("liveBankList")) {
	            bankList = jsonObject.getJSONArray("liveBankList");
	        } else if (jsonObject.has("banks")) {
	            bankList = jsonObject.getJSONArray("banks");
	        } else {
	            System.err.println("No valid bank list found in JSON.");
	            return codeList;
	        }

	        for (int i = 0; i < bankList.length(); i++) {
	            JSONObject bank = bankList.getJSONObject(i);
	            String bankId = bank.optString("bankId");
	            String bankName = bank.optString("bankName") + " (" + bankId + ")";
	            codeList.add(new SelectItem(bankId, bankName));
	        }

	    } catch (Exception e) {
	        e.printStackTrace();
	        System.err.println("Error fetching bank list: " + e.getMessage());
	    }

	    return codeList;
	}

	public String fetchLiveBankDetails() {
	    String apiUrl = "https://enach.npci.org.in/apiservices/getLiveBankDtls";
	    StringBuilder response = new StringBuilder();

	    try {
	        URL url = new URL(apiUrl);
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setConnectTimeout(5000);
	        connection.setReadTimeout(15000);
	        connection.setRequestMethod("GET");
	        connection.setRequestProperty("Accept", "application/json");

	        int status = connection.getResponseCode();

	        if (status == 200) {
	            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
	                String line;
	                while ((line = in.readLine()) != null) {
	                    response.append(line);
	                }
	            }
	        } else {
	            System.err.println("NPCI API failed. HTTP Code: " + status);
	        }

	    } catch (Exception e) {
	        System.err.println("Error calling NPCI API: " + e.getMessage());
	    }

	    return response.toString();
	}
	
	public void saveBankJsonToDb(String jsonResponse) {
	    Connection conn = null;
	    PreparedStatement ps = null;

	    try {
	        JSONObject original = new JSONObject(jsonResponse);
	        JSONArray bankList;

	        // Handle both structures gracefully
	        if (original.has("liveBankList")) {
	            bankList = original.getJSONArray("liveBankList");
	        } else if (original.has("banks")) {
	            bankList = original.getJSONArray("banks");
	        } else {
	            System.err.println("No valid bank list found for saving.");
	            return;
	        }

	        // Create lightweight version of JSON
	        JSONArray slimList = new JSONArray();
	        for (int i = 0; i < bankList.length(); i++) {
	            JSONObject bank = bankList.getJSONObject(i);
	            JSONObject minimal = new JSONObject();
	            minimal.put("bankId", bank.optString("bankId"));
	            minimal.put("bankName", bank.optString("bankName"));
	            slimList.put(minimal);
	        }

	        JSONObject finalJson = new JSONObject();
	        finalJson.put("banks", slimList);
	        String slimJson = finalJson.toString();

	        conn = DataBaseConnection.JAVAConnection();
	        ps = conn.prepareStatement(
	            "UPDATE npci_bank_cache SET bank_json = ?, last_updated = NOW() WHERE id = 1"
	        );
	        ps.setString(1, slimJson);
	        ps.executeUpdate();

	    } catch (Exception e) {
	        System.err.println("Error saving bank JSON to DB: " + e.getMessage());
	    } finally {
	        try { if (ps != null) ps.close(); } catch (Exception ignored) {}
	        try { if (conn != null) conn.close(); } catch (Exception ignored) {}
	    }
	}

	public ArrayList<SelectItem> fetchBankCodeFromDb() {
	    ArrayList<SelectItem> codeList = new ArrayList<>();
	    String json = fetchBankJsonFromDb(); 

	    try {
	        JSONObject obj = new JSONObject(json);
	        JSONArray banks;

	        if (obj.has("banks")) {
	            banks = obj.getJSONArray("banks");
	        } else if (obj.has("liveBankList")) {
	            banks = obj.getJSONArray("liveBankList");
	        } else {
	            System.err.println("No valid bank list found in DB JSON.");
	            return codeList;
	        }

	        for (int i = 0; i < banks.length(); i++) {
	            JSONObject bank = banks.getJSONObject(i);
	            String bankId = bank.optString("bankId");
	            String bankName = bank.optString("bankName") + " (" + bankId + ")";
	            codeList.add(new SelectItem(bankId, bankName));
	        }

	    } catch (Exception e) {
	        System.err.println("Error parsing DB JSON: " + e.getMessage());
	    }

	    return codeList;
	}

	public String fetchBankJsonFromDb() {
	    String json = "{}";
	    Connection conn = null;
	    PreparedStatement ps = null;
	    ResultSet rs = null;

	    try {
	        conn = DataBaseConnection.JAVAConnection();
	        ps = conn.prepareStatement("SELECT bank_json FROM npci_bank_cache WHERE id = 1");
	        rs = ps.executeQuery();

	        if (rs.next()) {
	            json = rs.getString("bank_json");
	        }

	    } catch (Exception e) {
	        System.err.println("Error reading bank JSON from DB: " + e.getMessage());
	    } finally {
	        try { if (rs != null) rs.close(); } catch (Exception ignored) {}
	        try { if (ps != null) ps.close(); } catch (Exception ignored) {}
	        try { if (conn != null) conn.close(); } catch (Exception ignored) {}
	    }

	    return json;
	}


    public String loanCloseDateStr(String loanNo,Connection conn)
	{
		Statement st=null; ResultSet rr=null;
		try
		{
			 st=conn.createStatement();
			String qq="select pay_date from loanpayment where loanNo='"+loanNo+"' and receipt_status='approved' and chequeStatus='cleared' and emi_no='-1' ";
			//System.out.println(qq);
			rr=st.executeQuery(qq);
			if(rr.next())
			{
				return sf.format(rr.getDate("pay_date"));
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();fileCreation(e.getMessage());
		}
		finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rr!=null)
				{
					rr.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return"";
	}

    
    public String companyName() 
	{
		try(Connection con=DataBaseConnection.JAVAConnection();) 
		{
			Statement st=con.createStatement();
			String qq="select name from firm_detail";
			ResultSet rs=st.executeQuery(qq);
			if(rs.next())
			{
				return rs.getString("name");
			}
		}
		catch (Exception e)
		{
			 e.printStackTrace();fileCreation(e.getMessage());
		} 
		return "";
	}
	
    public boolean checkIfSubscriptionConnectedWithRd(String sub_id) {
        String query = "SELECT rd_connected FROM subscriptions_overview WHERE subscription_id = ?";

        boolean rd_connected = false;

        try (Connection conn = DataBaseConnection.JAVAConnection();
             PreparedStatement ps = conn.prepareStatement(query)) {

            ps.setString(1, sub_id);

            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    rd_connected = rs.getBoolean("rd_connected");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return rd_connected;
    }


	public String findRdNumberBySubscriptionId(String sub_id) {
		 String query = "SELECT rd_number FROM subscriptions_overview WHERE subscription_id = ?";

	        String  rdNumber = null;

	        try (Connection conn = DataBaseConnection.JAVAConnection();
	             PreparedStatement ps = conn.prepareStatement(query)) {

	            ps.setString(1, sub_id);

	            try (ResultSet rs = ps.executeQuery()) {
	                if (rs.next()) {
	                    rdNumber = rs.getString("rd_number");
	                }
	            }

	        } catch (Exception e) {
	            e.printStackTrace();
	        }

	        return rdNumber;
	}
	
	public double findRdinstallmentAmountByRdNumber(String rdNumber) {
		 String query = "SELECT installment_amount FROM customer_info WHERE user_no = ?";

	        double  installment_amount = 0;

	        try (Connection conn = DataBaseConnection.JAVAConnection();
	             PreparedStatement ps = conn.prepareStatement(query)) {

	            ps.setString(1, rdNumber);

	            try (ResultSet rs = ps.executeQuery()) {
	                if (rs.next()) {
	                    installment_amount = rs.getDouble("installment_amount");
	                }
	            }

	        } catch (Exception e) {
	            e.printStackTrace();
	        }

	        return installment_amount;
	    }
	
	
    
    public boolean checkIfKjSubscriptionConnectedWithRd(String sub_id) {
        String query = "SELECT rd_connected FROM nach_mandate_request WHERE umrn= ?";

        boolean rd_connected = false;

        try (Connection conn = DataBaseConnection.JAVAConnection();
             PreparedStatement ps = conn.prepareStatement(query)) {

            ps.setString(1, sub_id);

            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    rd_connected = rs.getBoolean("rd_connected");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return rd_connected;
    }

    
	
	public String findRdNumberByKjSubscriptionId(String sub_id) {
		 String query = "SELECT rd_number FROM nach_mandate_request WHERE umrn = ?";

	        String  rdNumber = null;

	        try (Connection conn = DataBaseConnection.JAVAConnection();
	             PreparedStatement ps = conn.prepareStatement(query)) {

	            ps.setString(1, sub_id);

	            try (ResultSet rs = ps.executeQuery()) {
	                if (rs.next()) {
	                    rdNumber = rs.getString("rd_number");
	                }
	            }

	        } catch (Exception e) {
	            e.printStackTrace();
	        }

	        return rdNumber;
	}
	
public String lastEmiPaidDateByLoanNo(String loanNo, Connection conn) {
		System.out.println();
	
		String date = "";
		
		String qq = "select max(pay_date) as last_emi_paid_date from loanpayment where loanNo=? and emi_no <> '-1'";
		
		try(PreparedStatement ps = conn.prepareStatement(qq)) {
               ps.setString(1, loanNo);
               
               try(ResultSet rs = ps.executeQuery()) {
                      
            	   if (rs.next() && rs.getDate("last_emi_paid_date")!=null) {
					date = new SimpleDateFormat("dd/MM/yyyy").format(rs.getDate("last_emi_paid_date"));
				}
            	   
			} 
			
		} catch (Exception e) {
            e.printStackTrace();
		}
		
		return date;
	}
	
	
	public String loanCloserDate(String loanType, String loanNo, Connection conn)
	{
	    String date = "";

	    try
	    {
	        ArrayList<LoanInfo> list = loanInstallment(loanType, loanNo, conn);

	        if(list != null && list.size() > 0)
	        {
	            LoanInfo lastEmi = list.get(list.size() - 1);

	            if(lastEmi.getInstallDate() != null)
	            {
	                date = new SimpleDateFormat("dd/MM/yyyy").format(lastEmi.getInstallDate());
	            }
	        }
	    }
	    catch(Exception e)
	    {
	        e.printStackTrace();
	    }

	    return date;
	}
	
	
	
	public ArrayList<LoanInfo> loanInstallment2(String loanType,String loanNo, Connection conn)
    {
        double temp=0;
        String qq="";
        int j=0, x = 0;
        
        DbYashwant dby = new DbYashwant();
        
        Statement st=null;
		ResultSet rs=null;
		boolean checkGroupLoanEmi=false;
        ArrayList<LoanInfo> list = new ArrayList<LoanInfo>();
        try
        {
            st = conn.createStatement();
            if(loanType.equals("grouploan"))
            {
                qq = "select * from "+loanType+" where sub_loan_no='"+loanNo+"' and status='Approve'";
            }
            else
            {
                 qq = "select * from "+loanType+" where loanNo='"+loanNo+"' and status='Approve'";
            }  
            
            
           
            checkGroupLoanEmi=checkGroupLoanEmiFromTable(loanNo,conn);
            
            if (checkGroupLoanEmi) 
            {
            	x = firstGroupLoanEmiNoFromTable(loanNo, conn);
			}
            
            rs = st.executeQuery(qq);
            if(rs.next())
            {   
            	
//            	
            	Map<Integer, Date> groupPaidDates = null;

            	if (loanType.equalsIgnoreCase("grouploan"))
            	{
            	    groupPaidDates = getGroupLoanPaidDates(loanNo, conn);
            	}
            	
            	
//            	
            	
                if(rs.getString("emiType").equals("reducing"))
                {
                    double discount=discountOnLastEMI(loanType,loanNo,conn);
                    double paidAmount=loanPaidAmountByUser(loanType,loanNo,conn);
                    int terms = rs.getInt("terms");
                    int frequency=rs.getInt("frequency");
                    double emi=rs.getDouble("emi");
                    Date offcdt =null;
                    if(rs.getDate("emi_due_date")==null)
                    {
                        offcdt =rs.getDate("approvalDate");
                       
                    }
                    else
                    {
                    	
                        offcdt = rs.getDate("emi_due_date");
                        System.out.println("value of the emi Due Date :"+offcdt);
                        
                    }
                    double interstRate=rs.getDouble("interest");
                    double loanAmount=rs.getDouble("loanAmount");
                    double fr=(double) frequency;
                    Date installDate=null;
                    j=365/frequency;
                    if(rs.getDate("emi_due_date")==null)
                    {
                        installDate=rs.getDate("approvalDate");
                    }
                    else
                    {
                        installDate=rs.getDate("emi_due_date");
                        if(frequency==12)
                        {
                            installDate.setMonth(installDate.getMonth()-1);
                        }
                        else
                        {
                            installDate.setDate(installDate.getDate()-j);
                        }
                    }  
                    
                   
                    
                    int y=1;
                    for (int i = 1; i<= terms; i++)
                    {
                        LoanInfo ll=new LoanInfo();
                        //int j=365/frequency;

                        
                        ll.setSno(i);
                        if(i==terms)
                        {
                            emi=emi-discount;
                            ll.setInstallAmount(emi);
                        }
                        else
                        {
                            ll.setInstallAmount(emi);
                        }
                        
                        if(paidAmount>=emi)
                        {
                            ll.setStatus("Paid");
                            
                            
                            ll.setPaidAmount(emi);
                            ll.setDueAmount(0);
                            paidAmount=Double.parseDouble(df.format(paidAmount-emi));
                        }
                        else
                        {
                            ll.setStatus("Due");
                            ll.setPaidAmount(paidAmount);
                            ll.setDueAmount(Double.parseDouble(df.format(emi-paidAmount)));
                            	
                            paidAmount=0;
                        }
                  
                        Date dt=installDate;
                        if(rs.getDate("emi_due_date")==null)
                        {
                            dt.setDate(dt.getDate()+j);
                        }
                        else
                        {
                            if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
                              {
                                    if(frequency==4)
                                    {
                                        y=4;
                                        //x=terms/3;
                                    }
                                    else if(frequency==2)
                                    {
                                        y=6;
                                        //x=terms/6;
                                    }
                                    else if(frequency==1)
                                    {
                                        y=12;
                                        //x=terms/12;
                                    }
                                    else if(frequency==12)
                                    {
                                        y=1;
                                        //x=terms;
                                    }
                                  offcdt=createDate2(offcdt,y,i,offcdt.getDate(),rs.getDate("emi_due_date"));
                              }
                            else
                            {
                                dt.setDate(dt.getDate()+j);
                            }
                          
                        }
                        
                        if(checkGroupLoanEmi==false && (frequency==12 || frequency==4 || frequency==2 || frequency==1))
                        {
                            ll.setStrInstlmntDate(sf.format(offcdt));
                            SimpleDateFormat dd=sf;
                            Date ss=dd.parse(ll.getStrInstlmntDate());
                            ll.setInstallDate(ss);
                        }
                        else
                        {
                        	  if(checkGroupLoanEmi==true && x==i)  // Condition for Manage Meeting Day Change
                     	  {
                     		  dt=groupLoanEmiDateFromTable(i,loanNo,conn);
                     		  x++;
                     	  }
	                        ll.setStrInstlmntDate(sf.format(dt));
	                        SimpleDateFormat dd=sf;
	                        Date ss=dd.parse(ll.getStrInstlmntDate());
	                        ll.setInstallDate(ss);
                        }
                      
                        if (loanType.equalsIgnoreCase("grouploan"))
                        {
                            ll.setPaidDate(groupPaidDates.get(i));
                        }
                        else
                        {
                            ll.setPaidDate(loanPaidDate(i, loanNo, conn));
                        }
                       /* if(ll.getPaidAmount() > 0)
                        {
                           
                        if(ll.getPaidDate()==null)
                        {
                            ll.setPaidDateStr("- - - -");
                        }
                        else
                        {
                            ll.setPaidDateStr(new SimpleDateFormat("dd/MM/yyyy").format(loanPaidDate(i, loanNo, conn)));
                            ll.setReceiptNo(loanPayReceiptNoByLoanNo(i, loanNo, conn));
                        }
                        }
                        else
                        {
                            ll.setPaidDateStr("- - - -");
                        }*/// comment by GARG on 07 jan 2020 
                        ll.setPaidDateStr("- - - -");
                      
                       
                        double frstIntrstAmnt=(loanAmount*interstRate)/(100*fr);
                        ll.setInterestAmount(df.format((frstIntrstAmnt)));
                        ll.setInterest(Double.parseDouble(df.format(frstIntrstAmnt)));
                      
                        double paidPrincipalAmnt=emi-(frstIntrstAmnt);
                        ll.setPrincipalAmount(df.format(paidPrincipalAmnt));
                        ll.setPrincipal(Double.parseDouble(df.format(paidPrincipalAmnt)));
                      
                        double principalRemaining=loanAmount-paidPrincipalAmnt;
                        ll.setPrincipalBalanceStr(df.format(principalRemaining));
                        
                        list.add(ll);
                        loanAmount=principalRemaining;
                    }
                }
                else
                {
                	 String emiMode="";
                    if(loanType.equalsIgnoreCase("grouploan"))
                    {
                    	emiMode="both";
                    }
                    else
                    {
                    	emiMode=rs.getString("emi_mode");
                    }
                    if(emiMode.equalsIgnoreCase("both"))
                    {
                          double discount=discountOnLastEMI(loanType,loanNo, conn);
                             Date offcdt =null;
                             if(rs.getDate("emi_due_date")==null)
                             {
                                 offcdt =rs.getDate("approvalDate");
                             }
                             else
                             {
                                 offcdt = rs.getDate("emi_due_date");
                             }
                            
                          double paidAmount=loanPaidAmountByUser(loanType,loanNo, conn);
                          int terms = rs.getInt("terms");
                          int frequency=rs.getInt("frequency");
                          double emi=rs.getDouble("emi");
                          double interstRate=rs.getDouble("interest");
                          double loanAmount=rs.getDouble("loanAmount");
                          double totalInterest=Double.parseDouble(df.format((emi*terms)-loanAmount));
                          //double interestMonthly=(totalInterest-rs.getDouble("discount"))/terms;
                          double interestMonthly=totalInterest/terms;
                          Date installDate=null;
                          j=365/frequency;
                        
                          if(rs.getDate("emi_due_date")==null)
                          {
                              installDate=rs.getDate("approvalDate");
                          }
                          else
                          {
                              installDate=rs.getDate("emi_due_date");
                              if(frequency==12)
                              {
                                  installDate.setMonth(installDate.getMonth()-1);
                              }
                              else
                              {
                                  installDate.setDate(installDate.getDate()-j);
                              }
                          }
                          int y=1;
                          for (int i = 1; i<= terms; i++)
                          {
                              
                        	  
                        	  LoanInfo ll=new LoanInfo();
//                        	  ll.setEmiPaidDate1(dby.selectEmiPaidDate(i,loanNo));
                              ll.setSno(i);
                              if(i==terms)
                              {
                                  emi=emi-discount;
                                  ll.setInstallAmount(emi);
                              }
                              else
                              {
                                  ll.setInstallAmount(emi);
                              }
                            
                              if(paidAmount>=emi)
                              {
                                  ll.setStatus("Paid");
                                  ll.setPaidAmount(emi);
                                  ll.setDueAmount(0);
                                  paidAmount=Double.parseDouble(df.format(paidAmount-emi));
                              }
                              else
                              {
                                  ll.setStatus("Due");
                                  ll.setPaidAmount(paidAmount);
                                  ll.setDueAmount(Double.parseDouble(df.format(emi-paidAmount)));
                                  paidAmount=0;
                              }
                        
                              Date dt=installDate;
                              if(rs.getDate("emi_due_date")==null)
                              {
                                  dt.setDate(dt.getDate()+j);
                              }
                              else
                              {
                                  if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
                                  {
                                        if(frequency==4)
                                        {
                                            y=4;
                                            //x=terms/3;
                                        }
                                        else if(frequency==2)
                                        {
                                            y=6;
                                            //x=terms/6;
                                        }
                                        else if(frequency==1)
                                        {
                                            y=12;
                                            //x=terms/12;
                                        }
                                        else if(frequency==12)
                                        {
                                            y=1;
                                            //x=terms;
                                        }
                                      offcdt=createDate2(offcdt,y,i,offcdt.getDate(),rs.getDate("emi_due_date"));
                                  }
                                  else
                                  {
                                      dt.setDate(dt.getDate()+j);
                                  }
                              }
                              if(checkGroupLoanEmi==false && (frequency==12 || frequency==4 || frequency==2 || frequency==1))
                              {
                                  // System.out.println("hsjhhjhjhjhjhjhh "+offcdt);
                                  ll.setStrInstlmntDate(sf.format(offcdt));
                                  SimpleDateFormat dd=sf;
                                  Date ss=dd.parse(ll.getStrInstlmntDate());
                                  ll.setInstallDate(ss);
                              }
                              else
                              {
                            	  if(checkGroupLoanEmi==true)  // Condition for Manage Meeting Day Change
                            	  {
                            		  dt=groupLoanEmiDateFromTable(i,loanNo,conn);
                            	  }
	                              ll.setStrInstlmntDate(sf.format(dt));
	                              SimpleDateFormat dd=sf;
	                              Date ss=dd.parse(ll.getStrInstlmntDate());
	                              ll.setInstallDate(ss);
                              }
                             
                              if (loanType.equalsIgnoreCase("grouploan"))
                              {
                                  ll.setPaidDate(groupPaidDates.get(i));
                              }
                              else
                              {
                                  ll.setPaidDate(loanPaidDate(i, loanNo, conn));
                              }
                             /*  if(ll.getPaidAmount() > 0)
                              {
                                 
                              if(ll.getPaidDate()==null)
                              {
                                  ll.setPaidDateStr("- - - -");
                              }
                              else
                              {
                                  ll.setPaidDateStr(new SimpleDateFormat("dd/MM/yyyy").format(loanPaidDate(i, loanNo, conn)));
                                  ll.setReceiptNo(loanPayReceiptNoByLoanNo(i, loanNo,conn));
                              }
                              }
                              else
                              {
                                  ll.setPaidDateStr("- - - -");
                              }*/
                           // comment by GARG on 07 jan 2020 
  	                        ll.setPaidDateStr("- - - -");
                             
                              double frstIntrstAmnt=interestMonthly;
                              ll.setInterestAmount(df.format((frstIntrstAmnt)));
                              ll.setInterest(Double.parseDouble(df.format(frstIntrstAmnt)));
                            
                              double paidPrincipalAmnt=emi-(frstIntrstAmnt);
                              ll.setPrincipalAmount(df.format(paidPrincipalAmnt));
                              ll.setPrincipal(Double.parseDouble(df.format(paidPrincipalAmnt)));
	                            
                              //double principalRemaining=loanAmount-paidPrincipalAmnt;
                            
                              list.add(ll);
                              //loanAmount=principalRemaining;
                          }
                    }
                    else
                    {
                        double discount=rs.getDouble("discount");
                        Date offcdt =null;
                        if(rs.getDate("emi_due_date")==null)
                     {
                         offcdt =rs.getDate("approvalDate");
                     }
                     else
                     {
                         offcdt = rs.getDate("emi_due_date");
                     }
                        double paidAmount=loanPaidAmountByUser(loanType,loanNo, conn);
                        int terms = rs.getInt("terms");
                        int frequency=rs.getInt("frequency");
                        double emi=rs.getDouble("emi");
                        double interstRate=rs.getDouble("interest");
                        double loanAmount=rs.getDouble("loanAmount");
                        //double interestMonthly =Double.parseDouble(new DecimalFormat("##.#######").format(interstRate / (100.00 * frequency)));
                        double totalInterest=Double.parseDouble(df.format((emi*terms)));
                       System.out.println("Total interst :"+totalInterest);
                        double interestMonthly=totalInterest/terms;
                        System.out.println("Total interst :"+totalInterest);
                        Date installDate=null;
                        boolean chk=true;
                        j=365/frequency;
                        double fr=(double) frequency;

                        if(rs.getDate("emi_due_date")==null)
                        {
                            installDate=rs.getDate("approvalDate");
                        }
                        else
                          {
                              installDate=rs.getDate("emi_due_date");
                              if(frequency==12)
                              {
                                  installDate.setMonth(installDate.getMonth()-1);
                              }
                              else if(frequency==4)
                              {
                                  installDate.setMonth(installDate.getMonth()-3);
                              }
                              else
                              {
                                  installDate.setDate(installDate.getDate()-j);
                              }
                          }
                        
                        int y=1;
                        for (int i = 1; i<= terms; i++)
                        {
                            LoanInfo ll=new LoanInfo();
//                            ll.setEmiPaidDate1(dby.selectEmiPaidDate(i,loanNo));
                            //int jj=365/frequency;
                            ll.setSno(i);
                            if(i==terms)
                            {
                                emi=emi-discount;
                                ll.setInstallAmount(emi);
                            }
                            else
                            {
                                ll.setInstallAmount(emi);
                            }
                           
                            if(paidAmount>=emi)
                            {
                                ll.setStatus("Paid");
                                ll.setPaidAmount(emi);
                                ll.setDueAmount(0);
                                paidAmount=Double.parseDouble(df.format(paidAmount-emi));
                            }
                            else
                            {
                                ll.setStatus("Due");
                                ll.setPaidAmount(paidAmount);
                                ll.setDueAmount(Double.parseDouble(df.format(emi-paidAmount)));
                                paidAmount=0;
                            }
                            
                            //comment on 23-oct-2019 due to problem in MTOS nidhi
                            /*Date dt=installDate;
                            if(rs.getDate("emi_due_date")==null)
                            {
                                dt.setDate(dt.getDate()+jj);
                            }
                            else
                            {
                                if(chk==true)
                                {
                                    dt.setMonth(dt.getMonth());
                                    chk=false;
                                }
                                else
                                {
                                    dt.setMonth(dt.getMonth()+1);
                                }
                            }
                            ll.setInstallDate(dt);
                            */
                            

                            Date dt=installDate;
                              if(rs.getDate("emi_due_date")==null)
                              {
                                  dt.setDate(dt.getDate()+j);
                              }
                              else
                              {
                                  if(frequency==12 || frequency==4 || frequency==2 || frequency==1)
                                  {
                                        if(frequency==4)
                                        {
                                            y=4;
                                            //x=terms/3;
                                        }
                                        else if(frequency==2)
                                        {
                                            y=6;
                                            //x=terms/6;
                                        }
                                        else if(frequency==1)
                                        {
                                            y=12;
                                            //x=terms/12;
                                        }
                                        else if(frequency==12)
                                        {
                                            y=1;
                                            //x=terms;s
                                        }
                                        offcdt=createDate2(offcdt,y,i,offcdt.getDate(),rs.getDate("emi_due_date"));
                                  }
                                  else
                                  {
                                      dt.setDate(dt.getDate()+j);
                                  }
                              }
                              if(checkGroupLoanEmi==false && (frequency==12 || frequency==4 || frequency==2 || frequency==1))
                              {
                                  // System.out.println("hsjhhjhjhjhjhjhh "+offcdt);
                                  ll.setStrInstlmntDate(sf.format(offcdt));
                                  SimpleDateFormat dd=sf;
                                  Date ss=dd.parse(ll.getStrInstlmntDate());
                                  ll.setInstallDate(ss);
                              }
                              else
                              {
                            	  if(checkGroupLoanEmi==true)  // Condition for Manage Meeting Day Change
                            	  {
                            		  dt=groupLoanEmiDateFromTable(i,loanNo,conn);
                            	  }
	                              ll.setStrInstlmntDate(sf.format(dt));
	                              SimpleDateFormat dd=sf;
	                              Date ss=dd.parse(ll.getStrInstlmntDate());
	                              ll.setInstallDate(ss);
                              }
                           
                              if (loanType.equalsIgnoreCase("grouploan"))
                              {
                                  ll.setPaidDate(groupPaidDates.get(i));
                              }
                              else
                              {
                                  ll.setPaidDate(loanPaidDate(i, loanNo, conn));
                              }
                             /*  if(ll.getPaidAmount() > 0)
                                {
                                   
                                if(ll.getPaidDate()==null)
                                {
                                    ll.setPaidDateStr("- - - -");
                                }
                                else
                                {
                                    ll.setPaidDateStr(new SimpleDateFormat("dd/MM/yyyy").format(loanPaidDate(i, loanNo, conn)));
                                    ll.setReceiptNo(loanPayReceiptNoByLoanNo(i, loanNo, conn));
                                }
                                }
                                else
                                {
                                    ll.setPaidDateStr("- - - -");
                                }*/// comment by GARG on 07 jan 2020 
	                        ll.setPaidDateStr("- - - -");
                              
                               
                          //  ll.setStrInstlmntDate(new SimpleDateFormat("dd/MM/yyyy").format(dt));
                           
                            double frstIntrstAmnt=interestMonthly;
                            ll.setInterestAmount(df.format((frstIntrstAmnt)));
                            ll.setInterest(Double.parseDouble(df.format(frstIntrstAmnt)));
                            
                            double paidPrincipalAmnt=emi-(frstIntrstAmnt);
                            ll.setPrincipalAmount(df.format(paidPrincipalAmnt));
                            ll.setPrincipal(Double.parseDouble(df.format(paidPrincipalAmnt)));
                       
                            list.add(ll);
                        }
                    }
                 
                }
            }
        }
        catch (Exception e)
        {
             e.printStackTrace();fileCreation(e.getMessage());
        }
        finally
		{
			try {
				if(st!=null)
				{
					st.close();
				}
				if(rs!=null)
				{
					rs.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
      
        /*int i=0;
        loopx:for(LoanInfo ll: list)
        {
            if(ll.getStatus().equalsIgnoreCase("Paid"))
            {
                i=i+1;
                // // // //System.out.println(i);
                //lastPaidDate=ll.getInstallDate();
                // // // //System.out.println(ll.getInstallDate());
                break loopx;
            }
          
        }*/
        return list;
    }
	
	
	public Map<Integer, Date> getGroupLoanPaidDates(String loanNo, Connection conn)
	 {
	     Map<Integer, Date> paidDates = new HashMap<>();

	     String query = "SELECT emi_no, MAX(pay_date) AS pay_date FROM loanpayment WHERE loanNo='" + loanNo + "' AND restructure='No' AND receipt_status='approved' AND chequeStatus='cleared' GROUP BY emi_no";

	     try (Statement st = conn.createStatement();
	          ResultSet rs = st.executeQuery(query))
	     {
	         while (rs.next())
	         {
	             paidDates.put(
	                 rs.getInt("emi_no"),
	                 rs.getDate("pay_date")
	             );
	         }
	     }
	     catch(Exception e)
	     {
	         e.printStackTrace();
	     }

	     return paidDates;
	 }
	
	public String fileChargeByLoanNo(String loanNo, Connection conn)
	 {
	     String fileCharge = "0";

	     try
	     {
	         String query ="select amount from income_table where loan_no=? and item='File Charge' and status='active' order by id desc  limit 1";

	         try(PreparedStatement ps = conn.prepareStatement(query))
	         {
	             ps.setString(1, loanNo);

	             try(ResultSet rs = ps.executeQuery())
	             {
	                 if(rs.next())
	                 {
	                     fileCharge = rs.getString("amount");

	                     if(fileCharge == null || fileCharge.trim().equals(""))
	                     {
	                         fileCharge = "0";
	                     }
	                 }
	             }
	         }
	     }
	     catch(Exception e)
	     {
	         e.printStackTrace();
	     }

	     return fileCharge;
	 }
	

}