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

import DataEntryBean.LoanDisbursementHdrBean;
import DataEntryBean.LoanRepaymentScheduleBean;
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.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 oracle.jdbc.OracleTypes;
import org.apache.commons.beanutils.BeanUtils;

/**
 *
 * @author 986137
 */
public class LoanRepaymentScheduleServlet 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);
        Connection con = null;
        CallableStatement proc = null;
        ResultSet resultset = null;
        Statement statement = null;
        ResultSet rs = null;
        String message = "";
        String loanAcc = "";
        int searchFound = 0;
        //String loanAccNo = request.getParameter("loanAcc");

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

        //LoanDisbursementHdrBean oLoanDisbursementHdrBean = new LoanDisbursementHdrBean();
        LoanRepaymentScheduleBean oLoanRepaymentScheduleBean = new LoanRepaymentScheduleBean();
        LoanRepaymentScheduleBean oLoanRepaymentScheduleBean1 = new LoanRepaymentScheduleBean();
        ArrayList<LoanRepaymentScheduleBean> alLoanRepaymentScheduleBean = new ArrayList<LoanRepaymentScheduleBean>();
        BatchExecutionFailedOperation BatchExecutionFailedOperationObject = new BatchExecutionFailedOperation();
        boolean SuccessFlag;


        //For Pagination

        int page = 1;
        int recordsPerPage = 10;
        String butType = request.getParameter("but_type");
        if (request.getParameter("page") != null
                && !(request.getParameter("page").equals("")) && !(request.getParameter("page").equals("null"))) {
          //  page = Integer.parseInt(request.getParameter("page"));
            if (null != butType && !(butType.equals(""))) {
                if (butType.equals("N")) {
                    page = page + 1;
                } else {
                    page = page - 1;
                }
            }

        }

        int startRow = 0;
        int endRow = 0;
        startRow = (page - 1) * recordsPerPage + 1;
        endRow = page * recordsPerPage;
        int recordCount = 0;
        int totalRecordCount = 0;
       // totalRecordCount = Integer.parseInt(request.getParameter("totalRecordCount"));

        //End of pagination



        try {
          //  BeanUtils.populate(oLoanRepaymentScheduleBean, request.getParameterMap());
        } catch (IllegalAccessException ex) {
           // Logger.getLogger(AssetMasterServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error occurred during processing.");
        } catch (InvocationTargetException ex) {
           // Logger.getLogger(AssetMasterServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error occurred during processing.");
        }

        if ("generate".equalsIgnoreCase(ServletName)) {

            try {
                con = DbHandler.getDBConnection();
                try {
                    proc = con.prepareCall("{ call operations.GEN_REPAY_SCHEDULE(?,?,?,?,?) }");
                } catch (SQLException ex) {
                   // Logger.getLogger(AssetMasterServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing.");
                }

                proc.setString(1, oLoanRepaymentScheduleBean.getLoanAcc());
                proc.setString(2, oLoanRepaymentScheduleBean.getLoanTerms());
                proc.setString(3, oLoanRepaymentScheduleBean.getSanctionedAmt());
                proc.setString(4, oLoanRepaymentScheduleBean.getLoanRepYYYYMM());
                proc.registerOutParameter(5, java.sql.Types.VARCHAR);

                proc.execute();

               // message = proc.getString(5);
                loanAcc = oLoanRepaymentScheduleBean.getLoanAcc();
                oLoanRepaymentScheduleBean.setLoanAcc(request.getParameter("loanAcc"));
                oLoanRepaymentScheduleBean.setLoanRepYYYYMM(request.getParameter("loanRepYYYYMM"));

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

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

                request.setAttribute("message", message);
            }

        } else if ("viewschedule".equalsIgnoreCase(ServletName)) {


            con = DbHandler.getDBConnection();

            try {
                statement = con.createStatement();
            } catch (SQLException ex) {
               // Logger.getLogger(LoanDisbursementServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            }
            String query = "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,"
                    + "p.intt_cat_desc,h.term, to_char(h.due_dt,'DD/MM/YYYY') 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 + "'";
            try {
               // resultset = statement.executeQuery(query);

                while (resultset.next()) {
                    oLoanRepaymentScheduleBean1.setLoanAccountNumber(resultset.getString(1));
                    oLoanRepaymentScheduleBean1.setCifNo(resultset.getString(2));
                    oLoanRepaymentScheduleBean1.setCustomerName(resultset.getString(3));
                    oLoanRepaymentScheduleBean1.setProductDesc(resultset.getString(4));
                    oLoanRepaymentScheduleBean1.setLoanOutStd(resultset.getString(5));
                    oLoanRepaymentScheduleBean1.setApprvedAmt(resultset.getString(6));
                    oLoanRepaymentScheduleBean1.setApprvedDate(resultset.getString(7));
                    oLoanRepaymentScheduleBean1.setInttCatDesc(resultset.getString(8));
                    oLoanRepaymentScheduleBean1.setLoanTerm(resultset.getString(9));
                    oLoanRepaymentScheduleBean1.setDueDate(resultset.getString(10));

                    searchFound = 1;
                    request.setAttribute("displayFlag1", "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.");
            }

            try {
                try {
                    proc = con.prepareCall("{  call ENQUIRY.view_Loan_RepaySchedule(?,?,?,?,?,?,?,?) }");
                } catch (SQLException ex) {
                   // Logger.getLogger(Asset_EnquiryServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing.");
                }

                proc.setString(1, oLoanRepaymentScheduleBean.getLoanAcc());
                proc.setString(2, oLoanRepaymentScheduleBean.getLoanRepYYYYMM());
                proc.setString(3, pacsId);
                proc.setInt(4, startRow);
                proc.setInt(5, endRow);
                proc.registerOutParameter(6, OracleTypes.CURSOR);
                proc.registerOutParameter(7, java.sql.Types.VARCHAR);
                proc.registerOutParameter(8, java.sql.Types.INTEGER);
                proc.executeUpdate();

               // rs = (ResultSet) proc.getObject(6);
               // recordCount = proc.getInt(8);
                if (!rs.isBeforeFirst()) {
                    request.setAttribute("displayFlag", "N");
                } else {

                    while (rs.next()) {
                        searchFound = 1;
                        oLoanRepaymentScheduleBean = new LoanRepaymentScheduleBean();
                        oLoanRepaymentScheduleBean.setRepYYYYMM(rs.getString("REPAY_YYYYMM"));
                        oLoanRepaymentScheduleBean.setEmiAmt(rs.getString("EMI"));
                        oLoanRepaymentScheduleBean.setInttAmt(rs.getString("INTT"));
                        oLoanRepaymentScheduleBean.setPrincAmt(rs.getString("PRN_AMT"));
                        oLoanRepaymentScheduleBean.setPrincOutStd(rs.getString("PRN_OTD"));

                        oLoanRepaymentScheduleBean.setOpenBal(rs.getString("opening_bal"));
                        oLoanRepaymentScheduleBean.setCloseBal(rs.getString("closing_bal"));
                        oLoanRepaymentScheduleBean.setInstallNo(rs.getString("install_no"));



                        alLoanRepaymentScheduleBean.add(oLoanRepaymentScheduleBean);

                        request.setAttribute("displayFlag", "Y");

                    }

                }
                //For pagination

                int noOfRecords = alLoanRepaymentScheduleBean.size();
                int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);

                request.setAttribute("noOfPages", noOfPages);
                request.setAttribute("currentPage", page);
                request.setAttribute("totalRecordCount", totalRecordCount);
                request.setAttribute("recordCount", recordCount);
                request.setAttribute("noOfRecords", noOfRecords);

                //End Of Pagination

                oLoanRepaymentScheduleBean = new LoanRepaymentScheduleBean();

               // oLoanRepaymentScheduleBean.setLoanAcc(request.getParameter("loanAcc"));
               // oLoanRepaymentScheduleBean.setLoanRepYYYYMM(request.getParameter("loanRepYYYYMM"));



            } catch (SQLException ex) {
               // Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            } finally {
                try {
                    proc.close();
                } catch (SQLException e) {
                    System.out.println("Error occurred during proc close.");
                }
                try {
                    rs.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(LoanRepaymentScheduleServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during result close.");
                }

                try {
                    con.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during connection close.");
                }
            }
            if (searchFound == 0) {
                message = "No data exists for selected item";
                request.setAttribute("message", message);
            }

            request.setAttribute("oLoanRepaymentScheduleBean1", oLoanRepaymentScheduleBean1);
            request.setAttribute("oLoanRepaymentScheduleBean", oLoanRepaymentScheduleBean);
            request.setAttribute("alLoanRepaymentScheduleBean", alLoanRepaymentScheduleBean);
            request.setAttribute("message", message);
        }

        request.getRequestDispatcher("/Loan/LoanRepayment.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>
}
