package json_package;

import java.io.IOException;
import java.sql.Connection;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.primefaces.json.JSONArray;
import org.primefaces.json.JSONObject;

import main_package.DataBaseConnection;
import main_package.DataBaseMethodTaheer;
import main_package.DataBaseMethods;
import main_package.DataBaseMethodsRavi;
import main_package.DataBaseMethodsRaviK;
import main_package.LoanInfo;
import main_package.UserInfo;

@ManagedBean(name = "collectEmiDetailJsonBean")
@ViewScoped
public class CollectEmiDetailjsonBean {

    private String json;

    public CollectEmiDetailjsonBean() {

        JSONObject mainobj = new JSONObject();

        try {
			Map<String, String> param = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();

            String loanNo = param.get("loanNo");
            String loanType = param.get("loanType");

            if (loanNo == null || loanNo.trim().isEmpty()) {
                mainobj.put("success", false);
                mainobj.put("message", "loanNo is required");
                json = mainobj.toString();
                return;
            }
            
            loanNo = loanNo.trim();

            if (loanType == null || loanType.trim().isEmpty()) {
                loanType = new DataBaseMethodTaheer().loanTypeByLoanNo(loanNo);
            } else {
                loanType = loanType.trim().toLowerCase();
            }
            
            if (loanType == null || loanType.trim().isEmpty()) {
                mainobj.put("success", false);
                mainobj.put("message",
                        "Unable to determine loanType from loanNo. Please provide loanType.");
                json = mainobj.toString();
                return;
            }
            
            loanType = loanType.trim().toLowerCase();

            String[] allowedTypes = {
                "personalloan",
                "vechicleloan",
                "propertyloan",
                "grouploan",
                "secure_loan",
                "business_loan"
            };

            boolean validType = false;

            for (String type : allowedTypes) {
                if (type.equalsIgnoreCase(loanType)) {
                    loanType = type;
                    validType = true;
                    break;
                }
            }

            if (!validType) {
                mainobj.put("success", false);
                mainobj.put("message", "Invalid loanType");
                json = mainobj.toString();
                return;
            }

            DataBaseMethods obj = new DataBaseMethods();
            DataBaseMethodsRavi dbr = new DataBaseMethodsRavi();
            DataBaseMethodsRaviK dbrj = new DataBaseMethodsRaviK();

            DecimalFormat dc = new DecimalFormat("##.##");

            try (Connection conn = DataBaseConnection.JAVAConnection()) {

                if (conn == null) {
                    throw new Exception("Database connection failed");
                }

				UserInfo userInfo = obj.userInfoByLoanNoLoanType(loanNo, loanType, conn);
				LoanInfo loanInfo = obj.loanInfoByLoanNoLoanType(loanNo, loanType, conn);

                if (userInfo == null || loanInfo == null) {
                    mainobj.put("success", false);
                    mainobj.put("message", "Loan details not found");
                    json = mainobj.toString();
                    return;
                }

				loanInfo.setDisbursementDate(dbr.loanDisburseDateByLoanNo(loanNo, conn));

				ArrayList<LoanInfo> loanEMIList = obj.loanInstallment(loanType, loanNo, conn);

                if (loanEMIList == null) {
                    loanEMIList = new ArrayList<LoanInfo>();
                }

				loanEMIList = obj.penaltyCalculationMethod(loanType, loanNo, loanEMIList, conn);

                if (loanEMIList == null) {
                    loanEMIList = new ArrayList<LoanInfo>();
                }
                
				double totPaid = obj.totalPaidPenaltyAndChequeBounceCharges(loanNo, "Penalty", conn);

                for (LoanInfo item : loanEMIList) {
                    item.setPenaltyPaid(0);
                }

				if (totPaid > 0) {
					for (LoanInfo item : loanEMIList) {

						double penaltyDue = item.getPenaltyDue();

						if (totPaid > penaltyDue) {
							item.setPenaltyPaid(penaltyDue);
							totPaid -= penaltyDue;
						} else {
							item.setPenaltyPaid(totPaid);
							totPaid = 0;
							break;
						}
					}
				}

                double totalPenaltyDue = 0;
                double totalPenaltyPaid = 0;
                double totalIntrest = 0;
                double totalEmi = 0;
                double totalPrincipal = 0;
                double totalDue = 0;
                double totalPaid = 0;

                int currentDueEmi = 0;
                double currentEmiAmountDue = 0;

                Date today = new Date();

                JSONArray emiArray = new JSONArray();

				for (LoanInfo item : loanEMIList) {

					JSONObject emi = new JSONObject();

					emi.put("emiNo", item.getSno());
					emi.put("emiDate", nullToEmpty(item.getStrInstlmntDate()));
					emi.put("emiAmount", item.getInstallAmount());
					emi.put("interestAmount", safeDouble(item.getInterestAmount()));
					emi.put("principalAmount", safeDouble(item.getPrincipalAmount()));
					emi.put("paidAmount", item.getPaidAmount());
					emi.put("dueAmount", item.getDueAmount());
					emi.put("status", nullToEmpty(item.getStatus()));
					emi.put("duePenalty", item.getPenaltyDue());
					emi.put("paidPenalty", item.getPenaltyPaid());

					emiArray.put(emi);

					totalEmi += item.getInstallAmount();
					totalIntrest += safeDouble(item.getInterestAmount());
					totalPrincipal += safeDouble(item.getPrincipalAmount());
					totalPaid += item.getPaidAmount();
					totalDue += item.getDueAmount();
					totalPenaltyDue += item.getPenaltyDue();
					totalPenaltyPaid += item.getPenaltyPaid();

					if ("Due".equalsIgnoreCase(item.getStatus()) && item.getInstallDate() != null
							&& item.getInstallDate().before(today)) {

						currentDueEmi++;
						currentEmiAmountDue += item.getDueAmount();
					}
				}

				double penaltyDiscount = obj.discountOnPenaltyByLoanNo(loanNo);

				double currentPenaltyDue = totalPenaltyDue - (totalPenaltyPaid + penaltyDiscount);

                totalEmi = Math.round(totalEmi);
                totalIntrest = Math.round(totalIntrest);
                totalPrincipal = Math.round(totalPrincipal);
                totalPaid = Math.round(totalPaid);
                totalDue = Math.round(totalDue);
                totalPenaltyDue = Math.round(totalPenaltyDue);
                penaltyDiscount = Math.round(penaltyDiscount);
                totalPenaltyPaid = Math.round(totalPenaltyPaid);

				double totalChqCharge = obj.calculatePenaltyAndChequeBounceCharges(loanNo, "Cheque Bounce", loanType,
						conn);

				double paidChqcharge = obj.totalPaidPenaltyAndChequeBounceCharges(loanNo, "Cheque Bounce", conn);

				double balanceChqCharge = totalChqCharge - paidChqcharge;

                if (balanceChqCharge < 0) {
                    balanceChqCharge = 0;
                }

                balanceChqCharge = Double.parseDouble(dc.format(balanceChqCharge));

                int i = 0;
                double chargeB = dbrj.getbounce(conn);

				for (LoanInfo item : loanEMIList) {

					if ("Paid".equalsIgnoreCase(item.getStatus()) && item.getEmiPaidDate() != null
							&& item.getInstallDate() != null && item.getEmiPaidDate().after(item.getInstallDate())) {

						String remark = dbrj.getRemark(loanNo, item.getSno(), conn);

						if (remark != null
								&& remark.toLowerCase().contains("payment successfully debited from the customer")) {
							continue;
						}

						i++;

					} else if ("Due".equalsIgnoreCase(item.getStatus()) && item.getInstallDate() != null
							&& item.getInstallDate().before(today)) {

						i++;
					}
				}

                double chequeBounceAmt = chargeB * i;

				double loanBalance = (totalEmi + totalPenaltyDue + totalChqCharge)
						- (totalPaid + totalPenaltyPaid + paidChqcharge + penaltyDiscount);

                loanBalance = Double.parseDouble(dc.format(loanBalance));

                JSONObject loanDetails = new JSONObject();

                loanDetails.put("loanNo", nullToEmpty(loanInfo.getLoanNo()));
                loanDetails.put("loanType", loanType);
                loanDetails.put("fileCharge", loanInfo.getFileCharge());
                loanDetails.put("loanAmount", loanInfo.getLoanAmount());
                loanDetails.put("principalAmount", loanInfo.getPrincipalAmount());
                loanDetails.put("interestRate", loanInfo.getLoanInterest());
                loanDetails.put("terms", loanInfo.getLoanTerm());
                loanDetails.put("frequency", loanInfo.getFrequency());
                loanDetails.put("installAmount", loanInfo.getInstallAmount());
                loanDetails.put("savingAmount", loanInfo.getExtraAmt());
				loanDetails.put("loanRequestDate", nullToEmpty(loanInfo.getStrRequestDate()));
				loanDetails.put("loanApprovalDate", nullToEmpty(loanInfo.getStrApprovalDate()));
				loanDetails.put("disbursementDate", formatDate(loanInfo.getDisbursementDate()));
				loanDetails.put("loanCloseDate", formatDate(loanInfo.getLoanCloseDate()));
				loanDetails.put("emiType", nullToEmpty(loanInfo.getEmiType()));
                loanDetails.put("emiMode", nullToEmpty(loanInfo.getEmiMode()));
                loanDetails.put("planName", nullToEmpty(loanInfo.getPlanName()));
                loanDetails.put("dsaCode", nullToEmpty(loanInfo.getDsacode()));
                loanDetails.put("dsaName", nullToEmpty(loanInfo.getDsaName()));
				loanDetails.put("firstGuarantor", nullToEmpty(loanInfo.getFirstGuarantor()));
				loanDetails.put("secondGuarantor", nullToEmpty(loanInfo.getSecondGuarantor()));
				loanDetails.put("discountLastEMI", loanInfo.getDiscount());

                JSONObject applicantDetails = new JSONObject();
				applicantDetails.put("shareHolderNo", nullToEmpty(userInfo.getShareHolderNo()));

				JSONObject summary = new JSONObject();

				summary.put("totalDueBalance", loanBalance);
				summary.put("chequeBounceCharge", round2(chequeBounceAmt));
				summary.put("paidChequeCharge", round2(paidChqcharge));
				summary.put("balanceChequeCharge", balanceChqCharge);
				summary.put("currentDueAmount", round2(currentEmiAmountDue));
				summary.put("penaltyDiscount", round2(penaltyDiscount));
				summary.put("duePenaltyAmount", round2(currentPenaltyDue));
				summary.put("currentDueEMI", currentDueEmi);

 
                summary.put("totalEMI", totalEmi);
                summary.put("totalInterest", totalIntrest);
                summary.put("totalPrincipal", totalPrincipal);
                summary.put("totalPaid", totalPaid);
                summary.put("totalDue", totalDue);
                summary.put("totalPenaltyDue", totalPenaltyDue);
                summary.put("totalPenaltyPaid", totalPenaltyPaid);

                mainobj.put("success", true);
                mainobj.put("loanNo", loanNo);
                mainobj.put("loanType", loanType);

                mainobj.put("loanDetails", loanDetails);
                mainobj.put("applicantDetails", applicantDetails);
                mainobj.put("loanSummary", summary);
                mainobj.put("emiList", emiArray);

                json = mainobj.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();

            mainobj.put("success", false);
            mainobj.put("message", "Unable to fetch loan details");

            json = mainobj.toString();
        }
    }

	private double safeDouble(String value) {
		try {
			if (value == null || value.trim().isEmpty()) {
				return 0;
			}

			return Double.parseDouble(value.trim());

		} catch (NumberFormatException e) {
			return 0;
		}
	}

    private double round2(double value) {
        return Math.round(value * 100.0) / 100.0;
    }

    private String nullToEmpty(String value) {
        return value == null ? "" : value;
    }

    private String formatDate(Date date) {
        if (date == null) {
            return "";
        }

        java.text.SimpleDateFormat sdf =
                new java.text.SimpleDateFormat("dd/MM/yyyy");

        sdf.setTimeZone(java.util.TimeZone.getTimeZone("Asia/Kolkata"));

        return sdf.format(date);
    }

	public void renderJson() throws IOException {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ExternalContext externalContext = facesContext.getExternalContext();
		externalContext.setResponseContentType("application/json");
		externalContext.setResponseCharacterEncoding("UTF-8");
		externalContext.getResponseOutputWriter().write(json);
		facesContext.responseComplete();
	}

    public String getJson() {
        return json;
    }

    public void setJson(String json) {
        this.json = json;
    }
}