package main_package;

import java.io.Serializable;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;

import org.primefaces.context.RequestContext;

import group_head_package.DataBaseIncomeExpense;
import other_package.ReportInfo;
import report_package.DataBaseReportMethods;

@ManagedBean(name="payMultipleDDEmi")
@ViewScoped
public class PayMultipleDDEmiBean implements Serializable
{
	ArrayList<LoanInfo> listWithoutAmount= new ArrayList<>();
	ArrayList<LoanInfo> allDDList;
	ArrayList<LoanInfo> totalSelection= new ArrayList<>();
	ArrayList<LoanInfo> confirmationList, paidList;
	Date payDate=new Date();
	boolean chktbl1=false, showPaid, disDsa;
	String receiptNo,selectedCenter,selectLoanNo;
	double totalDatePayment,amountToPaid,amountPaid,dsaCommission, totalPaid;
	DsaListInfo commissionInfo;
	ArrayList<SelectItem> dsaList, centerList;
	String dsaCode, searchType, userId, searchBase="Search Date";
	DataBaseMethods obj=new DataBaseMethods();
	UserInfo user_info;
	
	public PayMultipleDDEmiBean() 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		centerList=obj.allcenter(branchId,"all",conn);
		userId=obj.userId();
		dsaList=obj.allDsaList(branchId,"",conn);
		String empDataStatus=obj.checkSMessageApiDetailFromTable("employee_wise_data", "",conn);
		if(obj.userType().equals("employee") && empDataStatus.equalsIgnoreCase("active"))
		{
			dsaCode=obj.dsaCodeByEmpUserId(userId, conn);
			disDsa=true;
		}
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	public void searchListDD()
		{ 
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		showPaid=false;
		   chktbl1=true;
		   allDDList= obj.allDDList(dsaCode, searchType, payDate, selectedCenter, searchBase,branchId);
		}
	
	
	public void printDetail()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		ss.setAttribute("collectionLoanEMiList", allDDList);
		ss.setAttribute("collectionDate", payDate);
		ss.setAttribute("printData", "Deposit");
		
		RequestContext.getCurrentInstance().execute("window.open('printPayMultipleLoanEmi.xhtml')");
	}
	
	public void copyEmiAmount()
	{
		for(int i=0;i<allDDList.size();i++)
		{
			allDDList.get(i).setPaidAmount(allDDList.get(i).getInstallAmount());
		}
	}
	
public void confirmation() throws ParseException
{
	int flag=1;
	Date dd= new Date();
	String string = "31/12/2026";
	DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
	Date date = format.parse(string);
	if(dd.after(date))
	{	
		flag=0;
	}
	
	if(flag==1)
	{
		totalDatePayment=0.00;
		confirmationList= new ArrayList<>();
		int sno=1;

		for(int i=0;i<totalSelection.size();i++)
		{
			totalDatePayment=totalDatePayment+totalSelection.get(i).getPaidAmount();
			if(totalSelection.get(i).getPaidAmount()>0)
			{  
			    totalSelection.get(i).setSno(sno++);
				confirmationList.add(totalSelection.get(i));
				
			}
		}
	}
	else
	{
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Some Error Occured!!! Try again Later..."));
	}
	
}

ArrayList<ReportInfo> listRd ;

public void RdclickList() {
	listRd = new ArrayList<>();
	DataBaseMethods dbr = new DataBaseMethods();
	Connection conn = DataBaseConnection.JAVAConnection();
	
 listRd = dbr.dailyRDFDReport(selectLoanNo,searchType, conn); 
	
}

public String insertAmount()
 {
	HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
	int branchId =(int) ss.getAttribute("branchId");
	paidList=new ArrayList<>();
	Connection conn=DataBaseConnection.JAVAConnection();
	for(LoanInfo ff:confirmationList)
	{
		user_info = obj.userInfoDuringTransaction(ff.getUserId());
		String submittedBankName="N/A";
		receiptNo=String.valueOf(obj.receiptNo());
		
		boolean z=new DataBaseMethodsDuplicate().receiptDuplicacy(receiptNo);
		if(z==true)
		{
			receiptNo=String.valueOf(obj.receiptNo());
		}
		boolean status=obj.rd_FdPayStatus(ff.getUserId());
		if(status==true)
			{
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please Approve Your Previous Payment To Make Further Payment"));
			}
		else
			{
				double paybleAmount=obj.checkForPaymentReceipt(ff.getUserId(),searchType);
				double paidAmount=obj.paidAmountByUser(ff.getUserId(),conn);
				if(paybleAmount>paidAmount)
					{
						double remainingAmount=paybleAmount-paidAmount;
						if(remainingAmount>=ff.getPaidAmount())				
							{
								int	n = obj.paymentReceipt(branchId,ff.getUserId(), ff.getPaidAmount(),payDate,"cash", "",null, "",0.00,receiptNo,submittedBankName,searchType,"",user_info.getDsaCode(),0);
								if (n >= 1) 
								  {
									sendMessage(ff, conn);
									calculateDsaCommission(ff);
									FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Payment Done SuccessFully... for user_id "+ff.getUserId()));
									obj.increaseCompanyCapitalAmount(branchId,ff.getPaidAmount(),conn);
									paidList.add(ff);
								  }
								else
								  {
									FacesContext fc = FacesContext.getCurrentInstance();
									fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again for user_id "+ff.getUserId()));
								  }
							}
						else
						{
							FacesContext fc = FacesContext.getCurrentInstance();
							fc.addMessage(null, new FacesMessage("You Have To Pay Only "+remainingAmount+" for user_id"+ff.getUserId()));
						}
					}
				else 
					{
						FacesContext fc=FacesContext.getCurrentInstance();
						fc.addMessage(null, new FacesMessage("Either You Have Paid All Installments Or Lesser Amount Than Installment Is To Be Paid for user_id "+ff.getUserId()+"Please check!"));
					}
			}
	}
	
	chktbl1=false;
	showPaid=true;
	int k=1;
	totalPaid=0;
	for (LoanInfo mm :paidList)
		{
		mm.setSno(k++);
			totalPaid +=mm.getPaidAmount();
		}
	  // totalSelection= new ArrayList<>();
	 //  allDDList= obj.allDDList(dsaCode, searchType, payDate);
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	   return "payMultipleDDEmi.xhtml";
	}


	private void sendMessage(LoanInfo ff, Connection conn) 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		String check="",payMode="Cash";
		//// System.out.println("call msg: "+user_info.getContactNo());
		if(searchType.equalsIgnoreCase("DD"))
		{
			check=obj.checkStatusInMessageSettingTable("Pay DD Emi");
		}
		else if(searchType.equalsIgnoreCase("RD"))
		{
			check=obj.checkStatusInMessageSettingTable("Pay RD Emi");
		}
		else if(searchType.equalsIgnoreCase("FD"))
		{
			check=obj.checkStatusInMessageSettingTable("Pay FD Emi");
		}
		
		if(check.equals("active"))
		{
			double paidAmount=obj.paidAmountByUser(ff.getUserId(),conn);
			String typeMessage="Dear "+user_info.getFirst_applicantName()+", Rs. "+ff.getPaidAmount()+" Submit Sucessfully By "+payMode+". Total Deposit Amount Balance is Rs. "+paidAmount;
			obj.runMessageUrl(branchId,user_info.getContactNo(), typeMessage, userId,"1207166054354220451", conn);
		}
		else
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Message For This Module is not Active. Please Go to In User Block and Active Message For This Module."));
		}
		
	}


private void calculateDsaCommission(LoanInfo ff) 
{
	HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
	int branchId =(int) ss.getAttribute("branchId");
	Connection conn=DataBaseConnection.JAVAConnection();
	if(ff.getDsacode()==null || ff.getDsacode().equals(""))
	{
		dsaCommission=0;
	}
	else
	{
		dsaCommission=0;
		commissionInfo=obj.checkPlanCommissionDetail(ff.getPlanNo(), conn);
		if(commissionInfo==null || commissionInfo.getStatusNullCheck().equals("0"))
		{
			dsaCommission=0;
		}
		else
		{
			double val=0, terms=0;
				if(ff.getPaidAmount()%ff.getInstallAmount()==0)
				{
					// System.out.println("chal ja  bhai : "+commissionInfo.getCommissionBase());
					 if(commissionInfo.getCommissionBase().equalsIgnoreCase("collection"))
					 {
						   val=ff.getInstallAmount();
								
								   terms=ff.getPaidAmount()/ff.getInstallAmount();
								   // System.out.println("max: "+commissionInfo.getMaxEmi());
								   if(terms>=commissionInfo.getMaxEmi())
								   {
									   terms=commissionInfo.getMaxEmi();
								   }
								   // System.out.println("hello terms: "+terms);
							   }
							  
						
					 		int emiNo=0;
					 		
					 		emiNo=(int) (ff.getAmountPaid()/ff.getInstallAmount());	
					 		emiNo=emiNo+1;
						  // System.out.println(emiNo+" temr:: "+terms);
						  for(int j=1;j<=terms;j++)
						  {
							  if(commissionInfo.getCommission_type().equalsIgnoreCase("percent"))
								   {
									   dsaCommission=(val/100)*commissionInfo.getCommission_value();
								   }
								   else
								   {
									   dsaCommission=commissionInfo.getCommission_value();
								   }
								 String  emiiiNo=String.valueOf(emiNo);
							
							   
							   dsaCommission=Double.parseDouble(new DecimalFormat("##.##").format(dsaCommission));
							   if(dsaCommission>0)
							   {
								   boolean checkEntry=obj.checkDuplicacyInDsaCommissionTable(ff.getUserId(),emiiiNo);
								  if(checkEntry==false)
								  {
									  String dsaName=obj.dsaNameById(ff.getDsacode(),conn);
										int i=obj.insertDataInDsaCommissionTable(branchId,searchType, ff.getUserId(), ff.getDsacode(), dsaCommission, payDate, emiiiNo);
										try {
											conn.close();
										} catch (Exception e) {
											// TODO: handle exception
										}
										if(i>0)
										{
											FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Commission Auto Credited to "+ff.getDsacode()+" - "+dsaName+" Rs.:- "+dsaCommission));
										}
								  }
								  
							   }
							   emiNo++;
						  }
						}
				
					   else
					   {
						   val=0;
						   dsaCommission=0;
						   FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Commission Not Auto Credited Due To EMI Amount not valid for Commission."));
					   
					   }
				}
	
			}
	}

	
	
	public Date getPayDate() {
		return payDate;
	}

	public void setPayDate(Date payDate) {
		this.payDate = payDate;
	}

	public double getTotalDatePayment() {
		return totalDatePayment;
	}

	public void setTotalDatePayment(double totalDatePayment) {
		this.totalDatePayment = totalDatePayment;
	}

	

	public ArrayList<LoanInfo> getConfirmationList() {
		return confirmationList;
	}

	public boolean isChktbl1() {
		return chktbl1;
	}

	public void setChktbl1(boolean chktbl1) {
		this.chktbl1 = chktbl1;
	}

	public ArrayList<LoanInfo> getAllDDList() {
		return allDDList;
	}

	public void setAllDDList(ArrayList<LoanInfo> allDDList) {
		this.allDDList = allDDList;
	}

	public void setConfirmationList(ArrayList<LoanInfo> confirmationList) {
		this.confirmationList = confirmationList;
	}

	public ArrayList<LoanInfo> getTotalSelection() {
		return totalSelection;
	}

	public void setTotalSelection(ArrayList<LoanInfo> totalSelection) {
		this.totalSelection = totalSelection;
	}
	public ArrayList<SelectItem> getDsaList() {
		return dsaList;
	}
	public void setDsaList(ArrayList<SelectItem> dsaList) {
		this.dsaList = dsaList;
	}
	public String getDsaCode() {
		return dsaCode;
	}
	public void setDsaCode(String dsaCode) {
		this.dsaCode = dsaCode;
	}
	public String getSearchType() {
		return searchType;
	}
	public void setSearchType(String searchType) {
		this.searchType = searchType;
	}
	public ArrayList<LoanInfo> getPaidList() {
		return paidList;
	}
	public void setPaidList(ArrayList<LoanInfo> paidList) {
		this.paidList = paidList;
	}
	public boolean isShowPaid() {
		return showPaid;
	}
	public void setShowPaid(boolean showPaid) {
		this.showPaid = showPaid;
	}
	public double getTotalPaid() {
		return totalPaid;
	}
	public void setTotalPaid(double totalPaid) {
		this.totalPaid = totalPaid;
	}
	public boolean isDisDsa() {
		return disDsa;
	}
	public void setDisDsa(boolean disDsa) {
		this.disDsa = disDsa;
	}
	public String getSelectedCenter() {
		return selectedCenter;
	}
	public void setSelectedCenter(String selectedCenter) {
		this.selectedCenter = selectedCenter;
	}
	public ArrayList<SelectItem> getCenterList() {
		return centerList;
	}
	public void setCenterList(ArrayList<SelectItem> centerList) {
		this.centerList = centerList;
	}
	public String getSearchBase() {
		return searchBase;
	}
	public void setSearchBase(String searchBase) {
		this.searchBase = searchBase;
	}
	public String getSelectLoanNo() {
		return selectLoanNo;
	}
	public void setSelectLoanNo(String selectLoanNo) {
		this.selectLoanNo = selectLoanNo;
	}
	public ArrayList<ReportInfo> getListRd() {
		return listRd;
	}
	public void setListRd(ArrayList<ReportInfo> listRd) {
		this.listRd = listRd;
	}
	public ArrayList<LoanInfo> getListWithoutAmount() {
		return listWithoutAmount;
	}
	public void setListWithoutAmount(ArrayList<LoanInfo> listWithoutAmount) {
		this.listWithoutAmount = listWithoutAmount;
	}
	public String getReceiptNo() {
		return receiptNo;
	}
	public void setReceiptNo(String receiptNo) {
		this.receiptNo = receiptNo;
	}
	public double getAmountToPaid() {
		return amountToPaid;
	}
	public void setAmountToPaid(double amountToPaid) {
		this.amountToPaid = amountToPaid;
	}
	public double getDsaCommission() {
		return dsaCommission;
	}
	public void setDsaCommission(double dsaCommission) {
		this.dsaCommission = dsaCommission;
	}
	public DsaListInfo getCommissionInfo() {
		return commissionInfo;
	}
	public void setCommissionInfo(DsaListInfo commissionInfo) {
		this.commissionInfo = commissionInfo;
	}
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public DataBaseMethods getObj() {
		return obj;
	}
	public void setObj(DataBaseMethods obj) {
		this.obj = obj;
	}
	public UserInfo getUser_info() {
		return user_info;
	}
	public void setUser_info(UserInfo user_info) {
		this.user_info = user_info;
	}


	
}