package main_package;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

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;

@ManagedBean(name="manageLoanEmi")
@ViewScoped
public class ManageLoanEmiBean implements Serializable
{
	
	DataBaseMethods obj=new DataBaseMethods();
	private static final long serialVersionUID = 1L;
	UserInfo user_info;
	LoanInfo loan_info;
	String loanType,loanNo,id;
	List<String> nameList;
	boolean show,value;
	ArrayList<LoanEmiReceiptInfo> loanReceipt_info;
	LoanEmiReceiptInfo selectedReceipt;
	ArrayList<SelectItem> loanTypeList;
	DataBaseMethods db=new DataBaseMethods();						
    
	
	
	public ManageLoanEmiBean() 
	{    
		Connection conn=DataBaseConnection.JAVAConnection();
		loanTypeList=obj.loanTypeList(conn);
		
		try 
		{
			conn.close();
		}
		catch (Exception e)
		{
			// TODO: handle exception
		}
	}
	
	public List<String> completeLoanNo(String name)
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		if(loanType!=null)
		{
			nameList=new DataBaseAutoCompAndDuplicate().showLoanNoByLoanTypeForEmiDelete(branchId,name,loanType,conn);
		}
		else
		{
			FacesContext.getCurrentInstance().addMessage(null,new FacesMessage("Please Select Loan Type First"));
		}
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return nameList;
	}
	
	public void userInfo()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		
		loanNo=loanNo.substring(0,loanNo.indexOf("/"));
		user_info=obj.userInfoByLoanNoLoanType(loanNo,loanType,conn);
		loan_info=obj.loanInfoByLoanNoLoanType(loanNo,loanType, conn);
		loanReceipt_info=obj.loanReceiptInfoByLoanNoLoanType(branchId,loanNo,loanType);
		checkDeleteDetail();
		if(loanReceipt_info!=null)
		{
			show=true;
		}
		else
		{
			show=false;
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/*private void checkDeleteDetail() 
	{
		for(int i=0;i<loanReceipt_info.size();i++)
		{
			if(i==loanReceipt_info.size()-1)
			{
				loanReceipt_info.get(i).setDisableDelete(false);
			}
			else
			{
				loanReceipt_info.get(i).setDisableDelete(true);
			}
		}
	}*/
	
	private void checkDeleteDetail()
    {   
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
        for(int i=0;i<loanReceipt_info.size();i++)
        {
            if(db.checkDataFreezing(branchId,DataBaseMethods.selectedSessionDetail(), conn)==true)
            {
                loanReceipt_info.get(i).setDisableDelete(true);
            }
            else
            {
	            if(i==loanReceipt_info.size()-1)
	            {
	                loanReceipt_info.get(i).setDisableDelete(false);
	            }
	            else
	            {
	                loanReceipt_info.get(i).setDisableDelete(true);
	            }
            }
        }
        try {
            conn.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
	
	public void viewDetails()
	{
		if(selectedReceipt.getPay_mode().equals("cheque"))
    	{
    		value=true;
      	}
    	else
    	{
    		value=false;
    	}
		//// System.out.println(selectedReceipt.getTransferToBankName());
	}
	
	public String editDetails()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		ss.setAttribute("selectedReceipt", selectedReceipt);
		ss.setAttribute("user_info", user_info);
		ss.setAttribute("loan_info", loan_info);
		return "editLoanPaymentReceipt";
	}
	public void printDetails()
	{
		int id=Integer.valueOf(selectedReceipt.getId());
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		if(selectedReceipt.getStatus().equalsIgnoreCase("approved"))
		{
			ss.setAttribute("shareHolderNo", user_info.getShareHolderNo());
			ss.setAttribute("loanNo",loanNo);
			ss.setAttribute("receipt_no",selectedReceipt.getReceipt_no());
			ss.setAttribute("installment_amount",selectedReceipt.getAmount());
			ss.setAttribute("loanType", loanType);
			ss.setAttribute("receipt_date",selectedReceipt.getStrPayDate());
			ss.setAttribute("instlmnt_no",selectedReceipt.getEmiNoStr());
			ss.setAttribute("id",id);
			ss.setAttribute("payMode",selectedReceipt.getPay_mode()+" "+selectedReceipt.getChq_no());
			RequestContext.getCurrentInstance().execute("window.open('loanPayReceipt.xhtml')");
			RequestContext.getCurrentInstance().execute("window.open('loanPayReceipt2.xhtml')");
		}
		else
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please Approve This Payment First"));
		}
	}
	
	public void printLoanAndSavingDetails()
	{
		int id=Integer.valueOf(selectedReceipt.getId());
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		if(selectedReceipt.getStatus().equalsIgnoreCase("approved"))
		{
			String svno=db.savingAccountByShareHolderNo(user_info.getShareHolderNo());
			ss.setAttribute("shareHolderNo", user_info.getShareHolderNo());
			ss.setAttribute("loanNo",loanNo);
			ss.setAttribute("receipt_no",selectedReceipt.getReceipt_no());
			ss.setAttribute("installment_amount",selectedReceipt.getAmount()+db.savingDepositBetweenDate(svno, new SimpleDateFormat("yyyy-MM-dd").format(selectedReceipt.getPay_date()), new SimpleDateFormat("yyyy-MM-dd").format(selectedReceipt.getPay_date())));
			ss.setAttribute("loanType", loanType);
			ss.setAttribute("receipt_date",selectedReceipt.getStrPayDate());
			ss.setAttribute("instlmnt_no",selectedReceipt.getEmiNoStr());
			ss.setAttribute("id",id);
			ss.setAttribute("payMode",selectedReceipt.getPay_mode()+" "+selectedReceipt.getChq_no());
			RequestContext.getCurrentInstance().execute("window.open('loanPayReceipt.xhtml')");
		}
		else
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please Approve This Payment First"));
		}
	}
	
	public void delete()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		
		int flag=1;
		
		boolean chk=obj.checkDataFreezeValidation(selectedReceipt.getPay_date());
		if(chk==false)
		{
			flag=0;
		}
		
		if(selectedReceipt.getPay_mode().equalsIgnoreCase("Transfer"))
		{
			flag=99;
		}
		
		FacesContext fc=FacesContext.getCurrentInstance();
		if(flag==1)
		{
			id=selectedReceipt.getId();
			String pMode=selectedReceipt.getPay_mode();
			Double amt=selectedReceipt.getAmount();
			String bankId=selectedReceipt.getTransferBank();
			double interestAmount=selectedReceipt.getInterestAmount();
			double principal=amt-interestAmount;
			// System.out.println("intreset....."+interestAmount+".....principal....."+principal);
			int n=obj.removeLoanEmiPayReceipt(id);
			if(n>=1)
			{   			
				fc.addMessage(null, new FacesMessage("Receipt Removed Successfully"));
				
				if(selectedReceipt.getEmiNo()==-1)
				{   
					obj.deleteFromAddLoanCloser(loanNo,conn);
					obj.updatePaidStatusLoanTables(loanNo, loanType, conn);
				}
				
				user_info=obj.userInfoByLoanNoLoanType(loanNo,loanType, conn);
				loan_info=obj.loanInfoByLoanNoLoanType(loanNo,loanType, conn);
				loanReceipt_info=obj.loanReceiptInfoByLoanNoLoanType(branchId,loanNo,loanType);
				checkDeleteDetail();
				if(pMode.equalsIgnoreCase("cash") && ( bankId==null || bankId.equalsIgnoreCase("N/A")))
	            {
	            	obj.decreaseCapitalCompanyAmount(branchId,interestAmount);
	            	obj.increaseSharedCompanyAmount(branchId,principal,conn);
	            }
	            else if(pMode.equalsIgnoreCase("cash") && (!bankId.equalsIgnoreCase("N/A") && bankId!=null))
	            {
	            	obj.decreaseBankBalance(bankId, amt,conn);
	            }
	            else 
	            {
	            	obj.decreaseBankBalance(bankId, amt,conn);
	            }
				obj.deleteFromDsaCommissionTable(loan_info.getLoanNo(), selectedReceipt.getEmiNo());
				
				try {
					conn.close();
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			else
			{
				fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
			}
		}
		
		else if(flag==0)
		{
			fc.addMessage(null, new FacesMessage("Your Selected Financial Year is: "+DataBaseMethods.selectedSessionDetail()+" and Entry Date is:"
					+ " "+selectedReceipt.getStrPayDate()+". Selected Entry is Not in Active Financial year, Due to you can't Delete. Thank You!!! "));
		}
		
		else if(flag==99)
		{
			fc.addMessage(null, new FacesMessage("Transfer Entry Delete option is Not Available Right Now. If any issue, Please contact to administrator. Thank You!!! "));
		}	
		
	}
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public boolean isValue() {
		return value;
	}

	public void setValue(boolean value) {
		this.value = value;
	}
	public LoanEmiReceiptInfo getSelectedReceipt() {
		return selectedReceipt;
	}

	public void setSelectedReceipt(LoanEmiReceiptInfo selectedReceipt) {
		this.selectedReceipt = selectedReceipt;
	}

	public ArrayList<LoanEmiReceiptInfo> getLoanReceipt_info() {
		return loanReceipt_info;
	}

	public void setLoanReceipt_info(ArrayList<LoanEmiReceiptInfo> loanReceipt_info) {
		this.loanReceipt_info = loanReceipt_info;
	}

	public boolean isShow() {
		return show;
	}

	public void setShow(boolean show) {
		this.show = show;
	}

	public LoanInfo getLoan_info() {
		return loan_info;
	}

	public void setLoan_info(LoanInfo loan_info) {
		this.loan_info = loan_info;
	}

	public String getLoanType() {
		return loanType;
	}

	public void setLoanType(String loanType) {
		this.loanType = loanType;
	}

	public String getLoanNo() {
		return loanNo;
	}

	public void setLoanNo(String loanNo) {
		this.loanNo = loanNo;
	}

	public UserInfo getUser_info() {
		return user_info;
	}

	public void setUser_info(UserInfo user_info) {
		this.user_info = user_info;
	}

	public ArrayList<SelectItem> getLoanTypeList() {
		return loanTypeList;
	}

	public void setLoanTypeList(ArrayList<SelectItem> loanTypeList) {
		this.loanTypeList = loanTypeList;
	}
}
