package report_package;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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 main_package.DataBaseMethods;
import main_package.DataBaseConnection;
import main_package.DataBaseMethodTaheer;
import main_package.UserInfo;

import org.primefaces.context.RequestContext;

@ManagedBean(name="upcomeEMI")
@ViewScoped

public class UpcomingEMIOfAllReportBean implements Serializable
{
	private static final long serialVersionUID = 1L;
	
	String category, userId;
	String center, selectedDsa = "", searchBase, frequency = "";
	String companyName;
	String[] selectedCenter;
	
	
	double totalAmount;
	
	
	Date startDate = new Date(),endDate = new Date();
	
	
	boolean showTable, showDsaList, showCenterList, showFreq, overTenureLoan = false;
	boolean printFirst, printSecond, printThird, printFourth, printFifth, penalty;
	
	
	ArrayList<SelectItem> centerList = new ArrayList<>();
	ArrayList<SelectItem> dsaList;
	ArrayList<UserInfo> list, multipleRows = new ArrayList<>();
	
	
	DataBaseMethods obj = new DataBaseMethods();
	DataBaseReportMethods obj1 = new DataBaseReportMethods();
	DataBaseMethodTaheer dbmt = new DataBaseMethodTaheer();
    
	
	
	public UpcomingEMIOfAllReportBean()
	{  		
		HttpSession ss = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		companyName = dbmt.companyNameByBranchId(branchId);
		
		Connection conn = DataBaseConnection.JAVAConnection();
		dsaList = obj.allDsaList(branchId,"Loan",conn);
		userId = obj.userId();
		
		try 
		{
			conn.close();
		} 
		catch (SQLException e) 
		{
			e.printStackTrace();
		}
	}
	
	
	
	public void checkSearchBase()
	{
		HttpSession ss = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		if(searchBase.equalsIgnoreCase("center"))
		{
			showCenterList=true;
			showDsaList=false;
			showFreq=false;
			centerList=obj.centerListForUpcomingEMI(branchId,startDate, endDate);
		}
		else if(searchBase.equalsIgnoreCase("over_time_center"))
		{
			showCenterList=true;
			showDsaList=false;
			showFreq=false;
			centerList=obj.overTimeCenterListForUpcomingEMI(branchId,startDate, endDate);
		}
		else if(searchBase.equalsIgnoreCase("dsa"))
		{
			showCenterList=false;
			showDsaList=true;
			showFreq=false;
		}
		else
		{
			showCenterList=false;
			showDsaList=false;
			showFreq=true;
		}
	}
	
	
	
	public void checkList()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		
		if(searchBase.equalsIgnoreCase("dsa"))
		{
			list=obj1.allUpcomingEMIAgentWise(branchId,startDate,endDate,category,conn,selectedDsa, overTenureLoan,penalty);
		}
		else if(searchBase.equalsIgnoreCase("freq"))
		{  
			list=obj1.allUpcomingEMIFrequencyWise(branchId, startDate,endDate,category,conn,frequency, overTenureLoan,penalty);			
		}
		else
		{
			list=obj1.allUpcomingEMI(branchId, startDate,endDate,category,conn,selectedCenter,centerList, overTenureLoan,penalty);
		}
		 
		if(list.size()>0)
		{
			showTable=true;
		}
		else
		{
			showTable=false;
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("No Record Found."));
		}
		Collections.sort(list);
		int i=1;
		totalAmount=0;
		for(UserInfo ll:list)
		{
			ll.setSno(i++);
			if(ll.getChq_ddNo().contains("loan") && obj.loanPaidAmountByUser(ll.getChq_ddNo(), ll.getLoanNo(),conn)==0) //Develop on 18 Sept 2023
			{
				ll.setPreEmiCharge(obj.preEmiChargeCalculationMethod(ll.getLoanNo(), ll.getChq_ddNo(),conn));
			}
			totalAmount+=ll.getAmount();
		}
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	 
	public String sendMsg()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		if(multipleRows.size()>0)
		{
			Connection conn=DataBaseConnection.JAVAConnection();
			String check=new DataBaseMethods().checkStatusInMessageSettingTable("Upcoming Emi");
			if(check.equals("active"))
			{ 	
				boolean isDLT = dbmt.isDLTMessageApi(conn);
				
		 		for(UserInfo ll: multipleRows)
				{
					if (isDLT) 
					{
						Map<String, String> variables = new HashMap<>();
						variables.put("name", ll.getFirst_applicantName());
						variables.put("date", ll.getEntryDateStr());
						variables.put("amount", String.valueOf(ll.getAmount()));
						variables.put("loanType", category);

						dbmt.sendDLTMessage(ll.getContactNo(), null, variables, conn, "upcoming emi");
					}
	 			 	else 
	 			 	{
						String typeMessage="Dear "+ll.getLoanNo()+" - "+ll.getFirst_applicantName()+", Your EMI Rs. "+ll.getAmount() +" is Upcoming On "+ll.getEntryDateStr();
						obj.runMessageUrl(branchId,ll.getContactNo(), typeMessage, "admin","1207166101557460886", conn);
						typeMessage="";
	 			 	}
				}
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(multipleRows.size()+" Message Send Sucessfully"));
				return "mainDashBoard.xhtml";
					
			}
			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."));
			}
			
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please Select Atleast One Contact no from List."));
		}
		return "";
	}
	
	public void sendWhatsApp()
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		for(UserInfo ll: multipleRows)
		{
			String typeMessage="Dear "+ll.getLoanNo()+" - "+ll.getFirst_applicantName()+", Your EMI Rs. "+ll.getAmount() +" is Upcoming On "+ll.getEntryDateStr();
			obj.runWhatsAppUrl(ll.getContactNo(), typeMessage, conn);
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void printReport()
	{
		if(companyName.equalsIgnoreCase("DEVKRIPA MICROFINANCE FOUNDATION"))
		{
		    ArrayList<UserInfo> tempList = new ArrayList<>();

		    for(UserInfo uu : list)
		    {
		        if(uu.getTillDue() == 0)
		        {
		            continue;
		        }

		        tempList.add(uu);

		        list = tempList;
		    }
		}
		
		if(list.size()>0)
		{
			if (printFifth) 
			{
				Connection conn = DataBaseConnection.JAVAConnection();
				
				for (UserInfo ui : list)
				{
					if (ui.getPreEmiCharge() > 0)
					{
						String preEMIPaidDate = dbmt.fetchPreEMIPaidDate(ui.getLoanNo(), conn);
						if (preEMIPaidDate != null) 
						{
							ui.setPreEMIStatus("Paid");
						}
						else
						{
							ui.setPreEMIStatus("Unpaid");
						}
					}
				}
				
				try 
				{
					conn.close();
				}
				catch (Exception e) 
				{
					e.printStackTrace();
				}
			}
			
			HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			ss.setAttribute("list", list);
			ss.setAttribute("categoryUpcoming", category);
			ss.setAttribute("searchBaseUpcoming", searchBase);
			ss.setAttribute("searchDsaUpcoming", selectedDsa);
			
			
			if(printFirst == true)
			{
				RequestContext.getCurrentInstance().execute("window.open('printUpcomeEMIReport.xhtml')");

			}
			if(printSecond == true)
			{
				RequestContext.getCurrentInstance().execute("window.open('printUpcomeEMIReport2.xhtml')");

			}
			if(printThird == true)
			{
				RequestContext.getCurrentInstance().execute("window.open('printUpcomeEMIReport3.xhtml')");

			}
			if(printFourth == true)
			{
				RequestContext.getCurrentInstance().execute("window.open('printUpcomeEMIReport4.xhtml')");

			}
			if(printFifth == true)
			{
				RequestContext.getCurrentInstance().execute("window.open('printUpcomeEMIReport5.xhtml')");

			}
			
		}
	}
	
	public Date getStartDate() {
		return startDate;
	}
	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}
	public Date getEndDate() {
		return endDate;
	}
	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}
	public ArrayList<UserInfo> getList() {
		return list;
	}
	public void setList(ArrayList<UserInfo> list) {
		this.list = list;
	}
	public double getTotalAmount() {
		return totalAmount;
	}
	public void setTotalAmount(double totalAmount) {
		this.totalAmount = totalAmount;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public ArrayList<UserInfo> getMultipleRows() {
		return multipleRows;
	}

	public void setMultipleRows(ArrayList<UserInfo> multipleRows) {
		this.multipleRows = multipleRows;
	}

	public boolean isShowTable() {
		return showTable;
	}

	public void setShowTable(boolean showTable) {
		this.showTable = showTable;
	}

	public String getCenter() {
		return center;
	}

	public void setCenter(String center) {
		this.center = center;
	}

	public ArrayList<SelectItem> getCenterList() {
		return centerList;
	}

	public void setCenterList(ArrayList<SelectItem> centerList) {
		this.centerList = centerList;
	}

	public String[] getSelectedCenter() {
		return selectedCenter;
	}

	public void setSelectedCenter(String[] selectedCenter) {
		this.selectedCenter = selectedCenter;
	}

	public boolean isShowDsaList() {
		return showDsaList;
	}

	public void setShowDsaList(boolean showDsaList) {
		this.showDsaList = showDsaList;
	}

	public boolean isShowCenterList() {
		return showCenterList;
	}

	public void setShowCenterList(boolean showCenterList) {
		this.showCenterList = showCenterList;
	}

	public String getSearchBase() {
		return searchBase;
	}

	public void setSearchBase(String searchBase) {
		this.searchBase = searchBase;
	}

	public ArrayList<SelectItem> getDsaList() {
		return dsaList;
	}

	public void setDsaList(ArrayList<SelectItem> dsaList) {
		this.dsaList = dsaList;
	}

	
	public String getSelectedDsa() {
		return selectedDsa;
	}

	public void setSelectedDsa(String selectedDsa) {
		this.selectedDsa = selectedDsa;
	}

	public String getFrequency() {
		return frequency;
	}

	public void setFrequency(String frequency) {
		this.frequency = frequency;
	}

	public boolean isShowFreq() {
		return showFreq;
	}

	public void setShowFreq(boolean showFreq) {
		this.showFreq = showFreq;
	}

	public boolean isOverTenureLoan() {
		return overTenureLoan;
	}

	public void setOverTenureLoan(boolean overTenureLoan) {
		this.overTenureLoan = overTenureLoan;
	}

	public boolean isPrintFirst() {
		return printFirst;
	}

	public void setPrintFirst(boolean printFirst) {
		this.printFirst = printFirst;
	}

	public boolean isPrintSecond() {
		return printSecond;
	}

	public void setPrintSecond(boolean printSecond) {
		this.printSecond = printSecond;
	}

	public boolean isPrintThird() {
		return printThird;
	}

	public void setPrintThird(boolean printThird) {
		this.printThird = printThird;
	}

	public boolean isPrintFourth() {
		return printFourth;
	}

	public void setPrintFourth(boolean printFourth) {
		this.printFourth = printFourth;
	}

	public boolean isPenalty() {
		return penalty;
	}

	public void setPenalty(boolean penalty) {
		this.penalty = penalty;
	}

	public boolean isPrintFifth() {
		return printFifth;
	}

	public void setPrintFifth(boolean printFifth) {
		this.printFifth = printFifth;
	}
	
}
