/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import DataEntryBean.LoanDisbursementHdrBean;
import DataEntryBean.LoanDisbursementDetailBean;
import LoginDb.DbHandler;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;

/**
 *
 * @author 986137
 */
public class LoanDisbursementServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
       // String loanAccNo = request.getParameter("loanAcc");
        ResultSet rs = null;
        int SeachFound = 0;
        String message = "";
        Connection con = null;
        CallableStatement stmt = null;
        CallableStatement proc = null;


       // String action = request.getParameter("handle_id");
        String pacsId = (String) session.getAttribute("pacsId");

        LoanDisbursementHdrBean oLoanDisbursementHdrBean = new LoanDisbursementHdrBean();
        LoanDisbursementDetailBean oLoanDisbursementDetailBean = new LoanDisbursementDetailBean();
        ArrayList<LoanDisbursementDetailBean> alLoanDisbursementDetailBean = new ArrayList<LoanDisbursementDetailBean>();
        ArrayList<LoanDisbursementDetailBean> alLoanDisbursementDetailBeanNew = new ArrayList<LoanDisbursementDetailBean>();
        ArrayList<LoanDisbursementDetailBean> alLoanDisbursementDetailBeanUpdated = new ArrayList<LoanDisbursementDetailBean>();
        BatchExecutionFailedOperation BatchExecutionFailedOperationObject = new BatchExecutionFailedOperation();
        boolean SuccessFlag;


        if (action.equalsIgnoreCase("SearchLoanAcc")) {

            Connection connection = null;
            ResultSet resultset = null;
            Statement statement = null;
            connection = DbHandler.getDBConnection();


            try {
                statement = connection.createStatement();
            } catch (SQLException ex) {
               // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            }
            try {
                //resultset = statement.executeQuery("select h.key_1,h.customer_no,"
                        + "(t.first_name||nvl2(t.middle_name,' '||t.middle_name,'')||nvl2(t.last_name,' '||t.last_name,'')) name,"
                        + "p.prod_desc,h.outst_bal,h.sanction_amt,to_char(h.sanc_dt,'dd-MON-yyyy') as sanc_dt, h.disb_amt "
                        + "from loan_account h,kyc_hdr t,loan_product p "
                        + "where h.customer_no = t.cif_no and h.loan_prod_id = p.id and h.key_1 ='" + loanAccNo + "' and h.PACS_ID = '" + pacsId + "'");



                while (resultset.next()) {
                    oLoanDisbursementHdrBean.setLoanAccountNumber(resultset.getString("key_1"));
                    oLoanDisbursementHdrBean.setCifNo(resultset.getString("customer_no"));
                    oLoanDisbursementHdrBean.setCustomerName(resultset.getString("name"));
                    oLoanDisbursementHdrBean.setProductDesc(resultset.getString("prod_desc"));
                    oLoanDisbursementHdrBean.setLoanOutStd(resultset.getString("outst_bal"));
                    oLoanDisbursementHdrBean.setApprvedAmt(resultset.getString("sanction_amt"));
                    oLoanDisbursementHdrBean.setApprvedDate(resultset.getString("sanc_dt"));
                    oLoanDisbursementHdrBean.setAdvanceAmt(resultset.getString("disb_amt"));



                    SeachFound = 1;
                    request.setAttribute("displayFlag", "Y");

                }

                statement.close();
                resultset.close();

            } catch (SQLException ex) {
               // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            }
            //detail part populate
            try {
                statement = connection.createStatement();
            } catch (SQLException ex) {
               // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            }

            try {
                String query = "select t.id,t.disb_yyyymm,t.disb_amount,t.descr,t.amt_remain,t.ACCNO from loan_disb_schedule t where t.ACCNO='" + oLoanDisbursementHdrBean.getLoanAccountNumber() + "' ORDER BY t.disb_yyyymm ASC";
               // rs = statement.executeQuery(query);

                while (rs.next()) {

                    oLoanDisbursementDetailBean = new LoanDisbursementDetailBean();
                    oLoanDisbursementDetailBean.setDisbSchedule_table_id(rs.getString("id"));
                    oLoanDisbursementDetailBean.setDisburseMonth(rs.getString("disb_yyyymm"));
                    oLoanDisbursementDetailBean.setDisburseAmt(rs.getString("disb_amount"));
                    oLoanDisbursementDetailBean.setDescDisburse(rs.getString("descr"));
                    oLoanDisbursementDetailBean.setAmtRemain(rs.getString("amt_remain"));
                    oLoanDisbursementDetailBean.setLoanAcctId(rs.getString("ACCNO"));


                    alLoanDisbursementDetailBean.add(oLoanDisbursementDetailBean);

                }
               // statement.close();
               // connection.close();
                rs.close();
            } catch (SQLException ex) {
               // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            } finally {
                try {
                    if(statement !=null)
                        statement.close();
                    if (connection != null)
                    connection.close();

            } catch (Exception e) {               
               System.out.println("Error Occurred during connection close.");
            }

            }

            if (SeachFound == 0) {
                message = "Loan Account does not exist in the system. Please enter correct details.";
                request.setAttribute("message", message);
            }

            request.setAttribute("oLoanDisbursementHdrBeanObj", oLoanDisbursementHdrBean);
            request.setAttribute("alLoanDisbursementDetailBean", alLoanDisbursementDetailBean);
            request.getRequestDispatcher("/Loan/LoanDisbursement.jsp").forward(request, response);

        } else if (action.equalsIgnoreCase("Create")) {
           // String loanAccHdr = request.getParameter("loanAccountNumber");
            int counter = Integer.parseInt(request.getParameter("rowCounter2"));

            for (int i = 1; i <= counter; i++) {
                try {

                  //  String disburseMonth = request.getParameter("disburseMonth" + i);
                   // String disburseAmt = request.getParameter("disburseAmt" + i);
                   // String descDisburse = request.getParameter("descDisburse" + i);
                   // String amtRemain = request.getParameter("amtRemain" + i);



                    if (loanAccHdr != null) {
                        oLoanDisbursementDetailBean = new LoanDisbursementDetailBean();
                        oLoanDisbursementDetailBean.setDisburseMonth(disburseMonth);
                        oLoanDisbursementDetailBean.setDisburseAmt(disburseAmt);
                        oLoanDisbursementDetailBean.setDescDisburse(descDisburse);
                        oLoanDisbursementDetailBean.setAmtRemain(amtRemain);


                        alLoanDisbursementDetailBean.add(oLoanDisbursementDetailBean);
                    }
                } catch (Exception e) {
                    System.out.println("Error occurred during processing.");
                }
            }

            if (alLoanDisbursementDetailBean.size() > 0) {
                try {
                    con = DbHandler.getDBConnection();
                    stmt = con.prepareCall("{ call upsert_loanDisbSchedule(?,?,?,?,?,?,?) }");
                    for (int j = 0; j < alLoanDisbursementDetailBean.size(); j++) {
                        oLoanDisbursementDetailBean = alLoanDisbursementDetailBean.get(j);
                        stmt.setString(1, loanAccHdr);
                        stmt.setString(2, oLoanDisbursementDetailBean.getDisburseMonth());
                        stmt.setString(3, oLoanDisbursementDetailBean.getDisburseAmt());
                        stmt.setString(4, oLoanDisbursementDetailBean.getDescDisburse());
                        stmt.setString(5, oLoanDisbursementDetailBean.getAmtRemain());
                        stmt.setString(6, null);
                        stmt.setString(7, action);
                        stmt.addBatch();

                    }

                    stmt.executeBatch();
                    message = "Disbursement scheduled successfully for the Loan Account No. " + loanAccHdr;

                } catch (SQLException ex) {
                    try {
                       // con.rollback();

                        SuccessFlag = BatchExecutionFailedOperationObject.BatchExecutionFailedOperation("LoanDisbursement.jsp", loanAccHdr);

                        message = ex.toString();


                    } catch (Exception ex1) {
                       // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex1);
                       System.out.println("Error occurred during processing.");
                    }

                   // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error occurred during processing.");
                } finally {
                    try {
                        stmt.close();
                    } catch (SQLException e) {
                       // System.out.println(e.toString());
                       System.out.println("Error occurred during stmt close.");
                    }
                    try {
                        con.close();
                    } catch (SQLException ex) {
                       // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error occurred during connection close.");
                    }
                }

            }

            request.setAttribute("message", message);
            request.getRequestDispatcher("/Loan/LoanDisbursement.jsp").forward(request, response);
        } else if (action.equalsIgnoreCase("Update")) {
            //Detail Part Starts here
           // String loanAccHdr2 = request.getParameter("loanAccountNumber");
            int counterfor_Detail = Integer.parseInt(request.getParameter("rowCounter"));

            for (int i = 1; i <= counterfor_Detail; i++) {
                try {
                   // String disburseMonthAmend = request.getParameter("disburseMonthAmend" + i);
                   // String disburseAmtAmend = request.getParameter("disburseAmtAmend" + i);
                    //String descDisburseAmend = request.getParameter("descDisburseAmend" + i);
                   // String amtRemainAmend = request.getParameter("amtRemainAmend" + i);
                    String loanAcctIdAmend = request.getParameter("loanAcctIdAmend" + i);

                    String rowStatus = request.getParameter("rowStatus" + i);
                   // String disbSchedule_table_id = request.getParameter("disbSchedule_table_id" + i);

                    if (loanAccHdr2 != null && rowStatus != null) {
                        oLoanDisbursementDetailBean = new LoanDisbursementDetailBean();
                        oLoanDisbursementDetailBean.setDisburseMonthAmend(disburseMonthAmend);
                        oLoanDisbursementDetailBean.setDisburseAmtAmend(disburseAmtAmend);
                        oLoanDisbursementDetailBean.setDescDisburseAmend(descDisburseAmend);
                        oLoanDisbursementDetailBean.setAmtRemainAmend(amtRemainAmend);
                        oLoanDisbursementDetailBean.setLoanAcctIdAmend(loanAcctIdAmend);
                        oLoanDisbursementDetailBean.setDisbSchedule_table_id(disbSchedule_table_id);


                        if (rowStatus.equals("N")) {
                            alLoanDisbursementDetailBeanNew.add(oLoanDisbursementDetailBean);
                        } else {
                            alLoanDisbursementDetailBeanUpdated.add(oLoanDisbursementDetailBean);
                        }
                    }
                } catch (Exception e) {
                    System.out.println("Error occurred during processing.");
                }
            }

            
            if ((alLoanDisbursementDetailBeanUpdated.size() > 0)) {
                try {
                    con = DbHandler.getDBConnection();
                    try {
                        proc = con.prepareCall("{ call upsert_loanDisbSchedule(?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex);
                       System.out.println("Error occurred during processing.");
                    }


                    for (int j = 0; j < alLoanDisbursementDetailBeanUpdated.size(); j++) {
                        oLoanDisbursementDetailBean = alLoanDisbursementDetailBeanUpdated.get(j);

                        proc.setString(1, loanAccHdr2);
                        proc.setString(2, oLoanDisbursementDetailBean.getDisburseMonthAmend());
                        proc.setString(3, oLoanDisbursementDetailBean.getDisburseAmtAmend());
                        proc.setString(4, oLoanDisbursementDetailBean.getDescDisburseAmend());
                        proc.setString(5, oLoanDisbursementDetailBean.getAmtRemainAmend());
                        proc.setString(6, oLoanDisbursementDetailBean.getDisbSchedule_table_id());
                        proc.setString(7, "Update");
                        proc.addBatch();
                    }

                    proc.executeBatch();
                    message = "Loan Disbursement Schedule updated with Loan Account No." + loanAccHdr2;

                } catch (SQLException ex) {
                    try {
                       // con.rollback();

                        SuccessFlag = BatchExecutionFailedOperationObject.BatchExecutionFailedOperation("LoanDisbursement.jsp", loanAccHdr2);

                        message = ex.toString();


                    } catch (Exception ex1) {
                       // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex1);
                       System.out.println("Error occurred during processing.");
                    }
                   // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error occurred during processing.");
                } finally {
                    try {
                        proc.close();
                    } catch (SQLException e) {
                       // System.out.println(e.toString());
                       System.out.println("Error occurred during proc close.");
                    }
                    try {
                        con.close();
                    } catch (SQLException ex) {
                       // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error occurred during connection close.");
                    }
                }
            }



            if ((alLoanDisbursementDetailBeanNew.size() > 0)) {
                try {
                    con = DbHandler.getDBConnection();
                    try {
                        proc = con.prepareCall("{call upsert_loanDisbSchedule(?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex);
                       System.out.println("Error occurred during processing.");
                    }


                    for (int j = 0; j < alLoanDisbursementDetailBeanNew.size(); j++) {
                        oLoanDisbursementDetailBean = new LoanDisbursementDetailBean();
                        oLoanDisbursementDetailBean = alLoanDisbursementDetailBeanNew.get(j);

                        proc.setString(1, loanAccHdr2);
                        proc.setString(2, oLoanDisbursementDetailBean.getDisburseMonthAmend());
                        proc.setString(3, oLoanDisbursementDetailBean.getDisburseAmtAmend());
                        proc.setString(4, oLoanDisbursementDetailBean.getDescDisburseAmend());
                        proc.setString(5, oLoanDisbursementDetailBean.getAmtRemainAmend());
                        proc.setString(6, oLoanDisbursementDetailBean.getDisbSchedule_table_id());
                        proc.setString(7, "Create");
                        proc.addBatch();
                    }
                    proc.executeBatch();
                    message = "Loan Disbursement Schedule updated with Loan Account No." + loanAccHdr2;
                } catch (SQLException ex) {
                    try {
                       // con.rollback();

                        SuccessFlag = BatchExecutionFailedOperationObject.BatchExecutionFailedOperation("LoanDisbursement.jsp", loanAccHdr2);

                        message = ex.toString();


                    } catch (Exception ex1) {
                       // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex1);
                       System.out.println("Error occurred during processing.");
                    }
                   // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error occurred during processing.");
                } finally {
                    try {
                        proc.close();
                    } catch (SQLException e) {
                       // System.out.println(e.toString());
                       System.out.println("Error occurred during proc close.");
                    }
                    try {
                        con.close();
                    } catch (SQLException ex) {
                       // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error occurred during connection close.");
                    }
                }
            }
            request.setAttribute("message", message);
            request.getRequestDispatcher("/Loan/LoanDisbursement.jsp").forward(request, response);
        }



    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
