package main_package;

import group_head_package.DataBaseIncomeExpense;

import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
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.context.Flash;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;

import other_package.DataBaseMethodsOther;
import report_package.DataBaseReportMethods;

@ManagedBean(name="returnMaturedAmount")
@ViewScoped

public class ReturnMaturedAmountBean implements Serializable
{
	private static final long serialVersionUID = 1L;
	UserInfo selected, savingDetail;
	String user_no,reqMessage,paymentMode,chequeNo,bankBranch,bankName,label, savingAccountNo, panCard, tdsType, year, type;
	Date current_date=new Date(),chequeDate;
	double maturity_value,cashBalance, investmentValue, intrestValue, tdsValue, tdsPercent, transferAmount, stationaryCharge, preMaturityCharge, otherCharge, totalDeduction;
	ArrayList<SelectItem> bankList;
	BankInfo bank_info;
	boolean showCheque, showTransfer, showTdsField, showPanCard;
	public static List<String> list;
	DataBaseMethods obj=new DataBaseMethods();
	DecimalFormat df=new DecimalFormat("##.##");
	int branchId;
	
	public ReturnMaturedAmountBean() 
	{
		
		Connection conn=DataBaseConnection.JAVAConnection();
		
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		selected=(UserInfo) ss.getAttribute("selected");
		 branchId = (int) ss.getAttribute("branchId");
		type=selected.getScheme_type();
		stationaryCharge=preMaturityCharge=otherCharge=totalDeduction=0;
		
		if(selected.getScheme_type().equals("RD") || selected.getScheme_type().equals("DD"))
		{
			investmentValue=selected.getInstallment_amount()*selected.getTerms();
		}
		else
		{
			investmentValue=selected.getInstallment_amount();
		}
		
		maturity_value=selected.getMaturity_value();
		
		
		intrestValue=maturity_value-investmentValue;
		intrestValue=Double.parseDouble(df.format(intrestValue));
		if(intrestValue<0)
		{
			intrestValue=0;
		}
		
		String tdsBasis=obj.checkTdsBasis(branchId,conn);
		if(tdsBasis.equalsIgnoreCase("maturity"))
		{
			if(intrestValue>=10000)
			{
				panCard=obj.findShareholderPanCardNo(selected.getShareHolderNo());
				if(panCard.equals(""))
				{
					tdsPercent=obj.tdsPercentFormTable("no");
					showPanCard=false;
				}
				else
				{
					tdsPercent=obj.tdsPercentFormTable("yes");
					showPanCard=true;
				}
				showTdsField=true;
				tdsValue=(intrestValue*tdsPercent)/100;
				tdsValue=Double.parseDouble(df.format(tdsValue));
			}
			else
			{
				tdsValue=0;
				showTdsField=false;
			}
		}
		else
		{
			panCard=obj.findShareholderPanCardNo(selected.getShareHolderNo());
			if(panCard==null || panCard.equals(""))
			{
				tdsPercent=obj.tdsPercentFormTable("no");
				showPanCard=false;
			}
			else
			{
				tdsPercent=obj.tdsPercentFormTable("yes");
				showPanCard=true;
			}
			tdsValue=new DataBaseReportMethods().tdsDeductionByUserNo(selected.getUser_no());
			if(tdsValue>0)
			{
				showTdsField=true;
			}
			else
			{
				showTdsField=false;
			}
			
		}
		
		
		
		user_no=selected.getUser_no();
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void checkPaymentMode()
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		if(paymentMode.equals("Cash"))
		{
			showCheque=false;
			showTransfer=false;
		}
		else if(paymentMode.equals("Transfer"))
		{
			savingDetail=obj.savingAccountDetailByShareHolderNo (selected.getShareHolderNo());
			savingAccountNo=savingDetail.getAccountNo();
			if(savingAccountNo!=null && !savingAccountNo.equals(""))
			{
				showCheque=false;
				showTransfer=true;
			}
			else
			{
				paymentMode="";
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(selected.getShareHolderNo()+" Doesn't any Saving Account. Please open a Saving Account Than Transfer Amount. "));
			}
		}
		else 
		{
			bankList=new DataBaseIncomeExpense().allBankList(conn);
			label=paymentMode;
			showCheque=true;
			showTransfer=false;
		}
	}
	
	public void checkBank()
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		bank_info=obj.obtainBankInfoById(bankName,conn);
		bankBranch=bank_info.getBank_branch();
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	/*public List<String> completeText(String name)
	{
		list=new DataBaseAutoCompAndDuplicate().savingAccountNo(name);
		if(list.size()==0)
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Saving Account Is not opened till now of Selected Share Holder"));
		}
		return list;
	}*/
	
/*	
	public void savingAccountDetail()
	{
		String savingNo="";
		if(savingAccountNo.contains("/"))
		{
			savingNo=savingAccountNo.substring(0,savingAccountNo.indexOf("/"));
		}
		
		savingDetail=obj.savingAccountDetailByAccountNo(savingNo);
	}*/
	
	/*public void shareHolderDetails()
	{
		shareHolderNo=shareHolderNo.substring(0,shareHolderNo.indexOf("/"));
		ArrayList<UserInfo> list=new ArrayList<UserInfo>();
		list=new DataBaseMethodsParticular().allSavingAccountBean(shareHolderNo);
		if(list.size()>0)
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Saving Account Is Already Opened By This Share Holder"));
		}
		else
		{
			selectedUser=obj.userInfoByShareHolderNo(shareHolderNo);
			if(selectedUser!=null)
			{
				show=true;
		        accountNo=obj.savingAccountNo(); 	
		        requestDate=new Date(); 
			}
			else
			{
				show=false;
				FacesContext fc=FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage("Invalid Share Holder No"));
			}
		}
	}*/
	
	public void calculateDeduction()
	{
		maturity_value=selected.getMaturity_value();
		maturity_value=maturity_value-tdsValue;
		
		totalDeduction=stationaryCharge+preMaturityCharge+otherCharge;
		//maturity_value=maturity_value-totalDeduction;
		if(maturity_value<0 || transferAmount<0)
		{
			maturity_value=transferAmount=0;
			stationaryCharge=preMaturityCharge=otherCharge=totalDeduction=0;
		}
		else
		{
			transferAmount=maturity_value-totalDeduction;
		}
	}
	
	public String returnAmount() throws IOException
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 branchId = (int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		boolean check=obj.checkReturnMaturedAmountDuplicacy(user_no, conn);
		if(check==false)
		{
			if(transferAmount>=0)
			{
				cashBalance=obj.remainingCompanyCapitalAmount(branchId,conn);
				if(paymentMode.equalsIgnoreCase("Cash"))
			    {	
					if(cashBalance>=maturity_value)
					{
						int n=obj.returnMaturedAmount(branchId,user_no,maturity_value,current_date,paymentMode,bankName,bankBranch,chequeNo,chequeDate,
								savingAccountNo, preMaturityCharge, stationaryCharge, otherCharge);
						if(n>=1)
						{
							insertTdsEntry();
							sendMessage(conn);
							FacesContext fc=FacesContext.getCurrentInstance();
							fc.addMessage(null, new FacesMessage("Amount Returned Successfully"));
							obj.increaseSharedCompanyAmount(branchId,maturity_value,conn);
							
							deductionEntryInIncomeTable(conn);
							
							try {
								conn.close();
							} catch (Exception e) {
								// TODO: handle exception
							}
							
							FacesContext.getCurrentInstance().getExternalContext().redirect("maturedRD.xhtml");
						}
						else
						{
							FacesContext fc=FacesContext.getCurrentInstance();
							fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
							return "";
						}
					}
					else
					{
						FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("only Rs."+(cashBalance)+" is the company's cash balance. Please Check!"));
					}
				}
				else if(paymentMode.equals("Transfer"))   // if Payment is transfer in Saving Account
				{
					int n=obj.returnMaturedAmount(branchId,user_no,maturity_value,current_date,paymentMode,bankName,bankBranch,chequeNo,chequeDate, savingAccountNo, preMaturityCharge, stationaryCharge, otherCharge);
					if(n>=1)
					{
						insertTdsEntry();
						//if(paymentMode.equals("Transfer"))
						{
							FacesContext fc=FacesContext.getCurrentInstance();
							fc.addMessage(null, new FacesMessage("Amount Transfer Successfully in "+savingAccountNo));
							
							double preAmt=savingDetail.getAmount();
							//// System.out.println("before "+preAmt+"====="+maturity_value);
							preAmt=preAmt+maturity_value;
							
							obj.userDeposit(branchId,savingAccountNo, String.valueOf(maturity_value), current_date,paymentMode, chequeNo, chequeDate, bankName,"approved","N/A","Maturity Amount Transfer","");
							obj.increaseSavingAccountAmount(preAmt, savingAccountNo);
							sendMessage(conn);
							Flash flash = fc.getExternalContext().getFlash();
							flash.setKeepMessages(true);
							FacesContext.getCurrentInstance().getExternalContext().redirect("maturedRD.xhtml");
						
							flash.setRedirect(true);
							
							FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Message", "Amount Transfer Successfully in "+savingAccountNo));
						}
					}
				
					else
					{
						FacesContext fc=FacesContext.getCurrentInstance();
						fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
						return "";
					}
				}
				else
				{
					/*// Auto Entry Code BAD CODE 
					double totalDeduct=preMaturityCharge+stationaryCharge+otherCharge;
					maturity_value=maturity_value-totalDeduct;
					obj.returnMaturedAmount(user_no,totalDeduct,current_date,"Cash","N/A","","",chequeDate, savingAccountNo, preMaturityCharge, stationaryCharge, otherCharge);
					obj.increaseSharedCompanyAmount(totalDeduct,conn);
					// Auto Entry returnMaturedAmount of Cash Due to Auto Deduction Entry (Pre-Maturity, Stationary, Other Charges) in Cash 
					*/  //BAD CODE 
					
					int x=obj.returnMaturedAmount(branchId,user_no,maturity_value,current_date,paymentMode,bankName,bankBranch,chequeNo,chequeDate, savingAccountNo, preMaturityCharge, stationaryCharge, otherCharge);
					if(x>=1)
					{
						insertTdsEntry();
						FacesContext fc=FacesContext.getCurrentInstance();
						fc.addMessage(null, new FacesMessage("Amount Returned Successfully.Please Go to 'Due Cheque Debit' to Approve Your Cheque"));
						sendMessage(conn);
						deductionEntryInIncomeTable(conn);
						
						FacesContext.getCurrentInstance().getExternalContext().redirect("maturedRD.xhtml");
					}
					else
					{
						FacesContext fc=FacesContext.getCurrentInstance();
						fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
						return "";
					}
				}	
			}
			else
			{
				FacesContext fc=FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
				return "";
			}
		}
		
		return "";
	}
	
	private void sendMessage(Connection conn) 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 branchId = (int) ss.getAttribute("branchId");
		String check=obj.checkStatusInMessageSettingTable("Maturity Module");
		if(check.equals("active"))
		{
			String typeMessage="Dear "+user_no+" - "+selected.getFirst_applicantName()+", Maturiy Amount "+maturity_value+"/- Done Sucessfully By "+paymentMode;
			obj.runMessageUrl(branchId,selected.getContactNo(), typeMessage, obj.userId(),"pending", 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 deductionEntryInIncomeTable(Connection conn) 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 branchId = (int) ss.getAttribute("branchId");
		if(paymentMode.equalsIgnoreCase("cash") || paymentMode.equalsIgnoreCase("Transfer"))
		{
			bankName="N/A";
		}
		String voucherNo="";
		DataBaseIncomeExpense dbiem=new DataBaseIncomeExpense();
		if(preMaturityCharge>0)
		{
			voucherNo=obj.generateVoucherNo(branchId,"income_table", conn);
			int i=dbiem.addIncome(branchId,current_date, "Other_Cr", paymentMode, String.valueOf(preMaturityCharge), chequeNo, bankBranch, "", chequeDate, "Pre Maturity Charge",
					"Pre Maturity Charge", 0, bankName, "0", 0, user_no, selected.getType(), voucherNo, "0", 0, "active","");
			if(i>0 && paymentMode.equalsIgnoreCase("Cash"))
			{
				obj.decreaseSharedCompanyAmount(branchId,preMaturityCharge);
			}
		}
		if(stationaryCharge>0)
		{
			voucherNo=obj.generateVoucherNo(branchId,"income_table", conn);
			int i=dbiem.addIncome(branchId,current_date, "Other_Cr", paymentMode, String.valueOf(stationaryCharge), chequeNo, bankBranch, "", chequeDate, "Stationary Charge",
					"Stationary Charge", 0, bankName, "0", 0, user_no, selected.getType(), voucherNo, "0", 0, "active","");
			if(i>0 && paymentMode.equalsIgnoreCase("Cash"))
			{
				obj.decreaseSharedCompanyAmount(branchId,stationaryCharge);
			}
		}
		if(otherCharge>0)
		{
			voucherNo=obj.generateVoucherNo(branchId,"income_table", conn);
			int i=dbiem.addIncome(branchId,current_date, "Other_Cr", paymentMode, String.valueOf(otherCharge), chequeNo, bankBranch, "", chequeDate, "Other Charge",
					"Other Charge", 0, bankName, "0", 0, user_no, selected.getType(), voucherNo, "0", 0, "active","");
			if(i>0 && paymentMode.equalsIgnoreCase("Cash"))
			{
				obj.decreaseSharedCompanyAmount(branchId,otherCharge);
			}
		}
	}

	private void insertTdsEntry() 
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 branchId = (int) ss.getAttribute("branchId");
		String tdsBasis=obj.checkTdsBasis(branchId,conn);
		if(tdsValue>0 && tdsBasis.equalsIgnoreCase("maturity"))
		{
			obj.insertTdsDeductionDetail(user_no, current_date, tdsValue,type,0,tdsPercent,branchId);
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Date getChequeDate() {
		return chequeDate;
	}

	public void setChequeDate(Date chequeDate) {
		this.chequeDate = chequeDate;
	}

	public String getUser_no() {
		return user_no;
	}
	public void setUser_no(String user_no) {
		this.user_no = user_no;
	}
	public Date getCurrent_date() {
		return current_date;
	}
	public void setCurrent_date(Date current_date) {
		this.current_date = current_date;
	}
	public double getMaturity_value() {
		return maturity_value;
	}
	public void setMaturity_value(double maturity_value) {
		this.maturity_value = maturity_value;
	}
	public UserInfo getSelected() {
		return selected;
	}
	public void setSelected(UserInfo selected) {
		this.selected = selected;
	}

	public String getReqMessage() {
		return reqMessage;
	}

	public void setReqMessage(String reqMessage) {
		this.reqMessage = reqMessage;
	}

	public String getPaymentMode() {
		return paymentMode;
	}

	public void setPaymentMode(String paymentMode) {
		this.paymentMode = paymentMode;
	}

	public String getChequeNo() {
		return chequeNo;
	}

	public void setChequeNo(String chequeNo) {
		this.chequeNo = chequeNo;
	}

	public String getBankBranch() {
		return bankBranch;
	}

	public void setBankBranch(String bankBranch) {
		this.bankBranch = bankBranch;
	}

	public String getBankName() {
		return bankName;
	}

	public void setBankName(String bankName) {
		this.bankName = bankName;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public ArrayList<SelectItem> getBankList() {
		return bankList;
	}

	public void setBankList(ArrayList<SelectItem> bankList) {
		this.bankList = bankList;
	}

	public boolean isShowCheque() {
		return showCheque;
	}

	public void setShowCheque(boolean showCheque) {
		this.showCheque = showCheque;
	}

	public UserInfo getSavingDetail() {
		return savingDetail;
	}

	public void setSavingDetail(UserInfo savingDetail) {
		this.savingDetail = savingDetail;
	}

	public String getSavingAccountNo() {
		return savingAccountNo;
	}

	public void setSavingAccountNo(String savingAccountNo) {
		this.savingAccountNo = savingAccountNo;
	}

	public double getCashBalance() {
		return cashBalance;
	}

	public void setCashBalance(double cashBalance) {
		this.cashBalance = cashBalance;
	}

	public BankInfo getBank_info() {
		return bank_info;
	}

	public void setBank_info(BankInfo bank_info) {
		this.bank_info = bank_info;
	}

	public boolean isShowTransfer() {
		return showTransfer;
	}

	public void setShowTransfer(boolean showTransfer) {
		this.showTransfer = showTransfer;
	}

	public double getInvestmentValue() {
		return investmentValue;
	}

	public void setInvestmentValue(double investmentValue) {
		this.investmentValue = investmentValue;
	}

	public double getIntrestValue() {
		return intrestValue;
	}

	public void setIntrestValue(double intrestValue) {
		this.intrestValue = intrestValue;
	}

	public double getTdsValue() {
		return tdsValue;
	}

	public void setTdsValue(double tdsValue) {
		this.tdsValue = tdsValue;
	}

	public double getTdsPercent() {
		return tdsPercent;
	}

	public void setTdsPercent(double tdsPercent) {
		this.tdsPercent = tdsPercent;
	}

	public boolean isShowTdsField() {
		return showTdsField;
	}

	public void setShowTdsField(boolean showTdsField) {
		this.showTdsField = showTdsField;
	}

	public double getTransferAmount() {
		return transferAmount;
	}

	public void setTransferAmount(double transferAmount) {
		this.transferAmount = transferAmount;
	}

	public String getPanCard() {
		return panCard;
	}

	public void setPanCard(String panCard) {
		this.panCard = panCard;
	}

	public String getTdsType() {
		return tdsType;
	}

	public void setTdsType(String tdsType) {
		this.tdsType = tdsType;
	}

	public boolean isShowPanCard() {
		return showPanCard;
	}

	public void setShowPanCard(boolean showPanCard) {
		this.showPanCard = showPanCard;
	}

	public double getStationaryCharge() {
		return stationaryCharge;
	}

	public void setStationaryCharge(double stationaryCharge) {
		this.stationaryCharge = stationaryCharge;
	}

	public double getPreMaturityCharge() {
		return preMaturityCharge;
	}

	public void setPreMaturityCharge(double preMaturityCharge) {
		this.preMaturityCharge = preMaturityCharge;
	}

	public double getOtherCharge() {
		return otherCharge;
	}

	public void setOtherCharge(double otherCharge) {
		this.otherCharge = otherCharge;
	}

	public double getTotalDeduction() {
		return totalDeduction;
	}

	public void setTotalDeduction(double totalDeduction) {
		this.totalDeduction = totalDeduction;
	}
	
	
}
