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

import DataEntryBean.BorrowingCreationBean;
import LoginDb.DbHandler;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.BatchUpdateException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.ResultSet;
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 org.apache.commons.beanutils.BeanUtils;
import java.sql.Statement;
import javax.servlet.ServletContext;

/**
 *
 * @author 1027350
 */
public class BorrowingCreationServlet extends HttpServlet {

    /**
     * stmtesses 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 stmtessRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    // <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 {
        stmtessRequest(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 {

        HttpSession session = request.getSession(false);
        Connection con = null;
        CallableStatement stmt = null;
        ResultSet rs = null;
        int SeachFound = 0;
        String message = "";
        String pacsId = session.getAttribute("pacsId").toString();
        String userId = session.getAttribute("user").toString();

        String handle_id = request.getParameter("handle_id");
        //String gl_ac = request.getParameter("glName");


        BorrowingCreationBean oBorrowingCreationBean = new BorrowingCreationBean();
        ArrayList<BorrowingCreationBean> alBorrowingCreationBeanDetailBean = new ArrayList<BorrowingCreationBean>();

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

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




        if ("Create".equalsIgnoreCase(handle_id)) {


            ServletContext servletContext = getServletContext();

            //START HEADER PART
            try {

               // con = DbHandler.getDBConnection();

                int counter = Integer.parseInt(request.getParameter("rowCounter"));

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

                        //String ckbox = request.getParameter("chckbox" + i);
                       // String bank_name = request.getParameter("bankName" + i);
                        if (bank_name != null) {
                           // String branch_name = request.getParameter("branchName" + i);
                            //String ac_no = request.getParameter("accountNo" + i);
                            //String amount = request.getParameter("amount" + i);
                            //String int_rate = request.getParameter("interestRate" + i);
                            //String od_int_rate = request.getParameter("odInterestRate" + i);
                            //String ac_opn_dt = request.getParameter("acOpenDate" + i);
                           // String ac_ovd_dt = request.getParameter("acOvdDate" + i);
                           // String act_flag = request.getParameter("active" + i);

                            //if (ckbox.equalsIgnoreCase("on")) {
                            oBorrowingCreationBean = new BorrowingCreationBean();
                            oBorrowingCreationBean.setAcno(ac_no);
                            oBorrowingCreationBean.setAc_opn_dt(ac_opn_dt);
                            oBorrowingCreationBean.setActive_flag(act_flag);
                            oBorrowingCreationBean.setAmt(amount);
                            oBorrowingCreationBean.setBank_name(bank_name);
                            oBorrowingCreationBean.setBranch_name(branch_name);
                            oBorrowingCreationBean.setInt_rate(int_rate);
                            oBorrowingCreationBean.setOd_int_rate(od_int_rate);
                            oBorrowingCreationBean.setOvd_dt(ac_ovd_dt);


                            alBorrowingCreationBeanDetailBean.add(oBorrowingCreationBean);
                        }
                        //}
                    } catch (Exception e) {
                        System.out.println("Error occurred during processing.");
                    }
                }

                if (alBorrowingCreationBeanDetailBean.size() > 0) {
                    try {
                        con = DbHandler.getDBConnection();
                        stmt = con.prepareCall("{ call borrowing_create(?,?,?,?,?,?,?,?,?,?,?,?,?) }");
                        for (int j = 0; j < alBorrowingCreationBeanDetailBean.size(); j++) {
                            oBorrowingCreationBean = alBorrowingCreationBeanDetailBean.get(j);
                            stmt.registerOutParameter(1, java.sql.Types.VARCHAR);
                            stmt.setString(2, gl_ac);
                            stmt.setString(3, oBorrowingCreationBean.getAcno());
                            stmt.setString(4, oBorrowingCreationBean.getBank_name());
                            stmt.setString(5, oBorrowingCreationBean.getBranch_name());
                            stmt.setString(6, oBorrowingCreationBean.getInt_rate());
                            stmt.setString(7, oBorrowingCreationBean.getAc_opn_dt());
                            stmt.setString(8, oBorrowingCreationBean.getOvd_dt());
                            stmt.setString(9, oBorrowingCreationBean.getActive_flag());
                            stmt.setString(10, oBorrowingCreationBean.getAmt());
                            stmt.setString(11, pacsId);
                            stmt.setInt(12, j);
                            stmt.setString(13, oBorrowingCreationBean.getOd_int_rate());

                            stmt.execute();
                           // message = stmt.getString(1);

                        }


                    } catch (SQLException ex) {
                        try {
                           // con.rollback();
                            message = "Details insertion has failed";
                        } catch (Exception ex1) {
                           // Logger.getLogger(BorrowingCreationServlet.class.getName()).log(Level.SEVERE, null, ex1);
                           System.out.println("Error occurred during processing.");
                        }
                       // Logger.getLogger(BorrowingCreationServlet.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("Error occurred during statement close.");
                        }
                        try {
                            con.close();
                        } catch (SQLException ex) {
                           // Logger.getLogger(BorrowingCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                           System.out.println("Error occurred during connection close.");
                        }

                    }

                    //END HEADER PART
                    //START DETAIL PART


                }

            } catch (Exception e) {
                message = "Details insertion has failed";
            
            } finally {
                System.out.println("Processing done.");
            }
        } else if (("Search").equalsIgnoreCase(handle_id)) {

            Connection connection = null;
            ResultSet resultset = null;
            Statement statement = null;
            connection = DbHandler.getDBConnection();
            //String gl_no = request.getParameter("glNameAmend");
            //String balance = request.getParameter("glBalAmend");
            ArrayList<BorrowingCreationBean> alBorrowingCreationDetailBean2 = new ArrayList<BorrowingCreationBean>();

            try {
                statement = connection.createStatement();
            } catch (SQLException ex) {
               // Logger.getLogger(InvestmentCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            }
            try {
                //resultset = statement.executeQuery("select i.ac_no,i.bank_name,i.branch_name,i.amt,i.int_rate,i.od_int_rate,to_char(i.ac_opn_dt,'DD/MM/RRRR') as ac_opn_dt,to_char(i.Overdue_Date,'DD/MM/RRRR') as Overdue_Date,i.active_flag from borrowing_dtl i where i.gl_id='" + gl_no + "'");

                while (resultset.next()) {
                    oBorrowingCreationBean = new BorrowingCreationBean();
                    oBorrowingCreationBean.setAcno(resultset.getString(1));
                    oBorrowingCreationBean.setBank_name(resultset.getString(2));
                    oBorrowingCreationBean.setBranch_name(resultset.getString(3));
                    oBorrowingCreationBean.setAmt(resultset.getString(4));
                    oBorrowingCreationBean.setInt_rate(resultset.getString(5));
                    oBorrowingCreationBean.setOd_int_rate(resultset.getString(6));
                    oBorrowingCreationBean.setAc_opn_dt(resultset.getString(7));
                    oBorrowingCreationBean.setOvd_dt(resultset.getString(8));
                    oBorrowingCreationBean.setActive_flag(resultset.getString(9));                    

                    System.out.println(resultset.getString(7));
                    System.out.println(resultset.getString(8));

                    alBorrowingCreationDetailBean2.add(oBorrowingCreationBean);

                    SeachFound = 1;

                }
                request.setAttribute("displayFlag", "Y");
               // statement.close();
               // resultset.close();

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

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

            }
            //Detail Part Populate

            request.setAttribute("GL_Account", gl_no);
            request.setAttribute("balance", balance);
            request.setAttribute("Option", "Amend");
            request.setAttribute("oborrowingCreationBeanObj", oBorrowingCreationBean);
            request.setAttribute("alBorrowingCreationDetailBean2", alBorrowingCreationDetailBean2);


        } else if ("Update".equalsIgnoreCase(handle_id)) {
            ServletContext servletContext = getServletContext();
            Statement statement = null;
            //START HEADER PART
            try {
                con = DbHandler.getDBConnection();
                statement = con.createStatement();
                int counter = Integer.parseInt(request.getParameter("rowCounterAmend"));
                //gl_ac = request.getParameter("hidden_gl_no");

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

                        //String ckbox = request.getParameter("chckboxAmend" + i);
                        //String bank_name = request.getParameter("bankNameAmend" + i);
                        if (bank_name != null) {
                           // String branch_name = request.getParameter("branchNameAmend" + i);
                           // String ac_no = request.getParameter("accountNoAmend" + i);
                           // String amount = request.getParameter("amountAmend" + i);
                           // String int_rate = request.getParameter("interestRateAmend" + i);
                           // String od_int_rate = request.getParameter("odInterestRateAmend" + i);
                           // String ac_opn_dt = request.getParameter("acOpenDateAmend" + i);
                           // String ac_ovd_dt = request.getParameter("acMatDateAmend" + i);
                          //  String act_flag = request.getParameter("activeAmend" + i);

                            oBorrowingCreationBean = new BorrowingCreationBean();
                            oBorrowingCreationBean.setAcno(ac_no);
                            oBorrowingCreationBean.setAc_opn_dt(ac_opn_dt);
                            oBorrowingCreationBean.setActive_flag(act_flag);
                            oBorrowingCreationBean.setAmt(amount);
                            oBorrowingCreationBean.setBank_name(bank_name);
                            oBorrowingCreationBean.setBranch_name(branch_name);
                            oBorrowingCreationBean.setInt_rate(int_rate);
                            oBorrowingCreationBean.setOd_int_rate(od_int_rate);
                            oBorrowingCreationBean.setOvd_dt(ac_ovd_dt);

                            alBorrowingCreationBeanDetailBean.add(oBorrowingCreationBean);

                        }
                    } catch (Exception e) {
                        System.out.println("Error occurred during processing.");
                    
                    } finally {
                try {
                    if(statement !=null)
                        statement.close();
                    if (con != null)
                    con.close();

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

        }
    }

                if (alBorrowingCreationBeanDetailBean.size() > 0) {
                    try {
                        con = DbHandler.getDBConnection();
                        stmt = con.prepareCall("{ call borrowing_update(?,?,?,?,?,?,?,?,?,?,?,?) }");
                        for (int j = 0; j < alBorrowingCreationBeanDetailBean.size(); j++) {
                            oBorrowingCreationBean = alBorrowingCreationBeanDetailBean.get(j);
                            stmt.registerOutParameter(1, java.sql.Types.VARCHAR);
                            stmt.setString(2, gl_ac);
                            stmt.setString(3, oBorrowingCreationBean.getAcno());
                            stmt.setString(4, oBorrowingCreationBean.getBank_name());
                            stmt.setString(5, oBorrowingCreationBean.getBranch_name());
                            stmt.setString(6, oBorrowingCreationBean.getInt_rate());                            
                            stmt.setString(7, oBorrowingCreationBean.getAc_opn_dt());
                            stmt.setString(8, oBorrowingCreationBean.getOvd_dt());
                            stmt.setString(9, oBorrowingCreationBean.getActive_flag());
                            stmt.setString(10, oBorrowingCreationBean.getAmt());
                            stmt.setString(11, pacsId);
                            stmt.setString(12, oBorrowingCreationBean.getOd_int_rate());

                            stmt.execute();
                           

                        }
                        String deleteDataBckUpQry = "insert into BORROWING_DTL_DELETE_HIST (select AC_NO,BANK_NAME,BRANCH_NAME,AMT,INT_RATE,OD_INT_RATE,AC_OPN_DT,OVERDUE_DATE,ACTIVE_FLAG,GL_ID,sysdate,'" + pacsId + "','" + userId + "' from borrowing_dtl "
                                + " where modified_time is null or modified_time<sysdate-1/1440 and gl_id='" + gl_ac + "')";
                        String deleteQry = "delete from borrowing_dtl t where t.modified_time is null or t.modified_time<sysdate-1/1440 and gl_id='" + gl_ac + "' ";

                        try {
                            statement.execute(deleteDataBckUpQry);
                           // con.commit();
                            statement.execute(deleteQry);
                        } catch (SQLException e) {
                           // e.printStackTrace();
                           System.out.println("Error occurred during processing.");
                        }

                    } catch (SQLException ex) {
                        try {
                           // con.rollback();
                            message = "Updation failed";
                        } catch (Exception ex1) {
                           // Logger.getLogger(BorrowingCreationServlet.class.getName()).log(Level.SEVERE, null, ex1);
                           System.out.println("Error occurred during processing.");
                        }
                       // Logger.getLogger(BorrowingCreationServlet.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("Error occurred during statement close.");
                        }
                        try {
                            con.close();
                        } catch (SQLException ex) {
                           // Logger.getLogger(BorrowingCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                           System.out.println("Error occurred during connection close.");
                        }
                    }
                }

            } catch (SQLException e) {
                System.out.println("Error occurred during processing.");
            }
        }
        request.setAttribute("message", message);
        request.getRequestDispatcher("/borrowing_creation.jsp").forward(request, response);
    }

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