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

import DataEntryBean.DepositMiscellaneousBean;
import DataEntryBean.RepayLoanBean;
import LoginDb.DbHandler;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
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;
import java.util.Date;

/**
 *
 * @author 986137
 */
public class DepositMiscellaneousOperationServlet 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 depositAccSearch = "";
        ResultSet rs = null;
        int SeachFound = 0;
        String message = "";
        String resetBy=null;
        String printDate=null;
        String resetDate=null;
        String action = request.getParameter("handle_id");
        String pacsId = (String) session.getAttribute("pacsId");
        String user = (String) session.getAttribute("user");
        //added by rajdiip
        StringBuilder query = null;
        PreparedStatement ps = null;
        int res = 0;
        String txnOrAccntNo = null;
        //Added by Paramita
        String loanAccSearch ="";
        String transactionType = request.getParameter("transactionType");
        
        //System.out.println("Transaction type: " +transactionType);

        DepositMiscellaneousBean oDepositMiscellaneousBean = new DepositMiscellaneousBean();
        RepayLoanBean oRepayLoanBean = new RepayLoanBean();

        if ((action.equalsIgnoreCase("Search"))&& (transactionType.equalsIgnoreCase("Deposit"))) {

          //  depositAccSearch = request.getParameter("depositAccSearch");
            //loanAccSearch = request.getParameter("loanAccSearch");
            Connection connection = null;
            ResultSet resultset = null;
            Statement statement = null;
            connection = DbHandler.getDBConnection();

            try {
                statement = connection.createStatement();
            } catch (SQLException ex) {
               // Logger.getLogger(DepositMiscellaneousOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                System.out.println("-------------------------------------"+ depositAccSearch);
              //  resultset = statement.executeQuery("select t.key_1,t.avail_bal as Account_BAlance,t.customer_no,k.first_name||' '||k.middle_name||' '||k.last_name as customer1_name,"
                        + " case when t.cif_no2 is null then 'NA' else t.cif_no2 end as cif_no2,(select kh.first_name||' '||kh.middle_name||' '||kh.last_name as customer2_name from kyc_hdr kh where kh.cif_no=t.cif_no2) as cif2_name,"
                        + " decode(t.CURR_STATUS,'C','Closed','D','Dormant','S','Stopped','M','Matured','Open/Active') as curr_status ,nvl(NOMINEE_CIF,'NA') as NOMINEE_CIF "
                        + " from dep_account t,kyc_hdr k,dep_product p where k.cif_no = t.customer_no and t.dep_prod_id = p.id and t.key_1 ='" + depositAccSearch + "' and t.PACS_ID = '" + pacsId + "'");



                while (resultset.next()) {
                    oDepositMiscellaneousBean.setDepositAccountNumber(resultset.getString("key_1"));
                    oDepositMiscellaneousBean.setCifNo(resultset.getString("customer_no"));
                    oDepositMiscellaneousBean.setAccBalance(resultset.getString("Account_BAlance"));
                    oDepositMiscellaneousBean.setAccStat(resultset.getString("curr_status"));
                    oDepositMiscellaneousBean.setNomCif(resultset.getString("NOMINEE_CIF"));

                    oDepositMiscellaneousBean.setCustomer1Name(resultset.getString("customer1_name"));
                    oDepositMiscellaneousBean.setCif2No(resultset.getString("cif_no2"));
                    if (resultset.getString("cif2_name") == null) {
                        oDepositMiscellaneousBean.setCustomer2Name("NA");
                    } else {
                        oDepositMiscellaneousBean.setCustomer2Name(resultset.getString("cif2_name"));
                    }

                    SeachFound = 1;

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

                }

               // statement.close();
               // resultset.close();
               // connection.close();

            } catch (SQLException ex) {
                //Logger.getLogger(DepositMiscellaneousOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
            
            }
            
         if (SeachFound == 0) {
                message = "Deposit Account not exists in the system";
                request.setAttribute("message", message);
            }

            request.setAttribute("oDepositMiscellaneousBeanObj", oDepositMiscellaneousBean);
            request.getRequestDispatcher("/Deposit/DepositMiscellaneousOperation.jsp").forward(request, response);
            
       }
               
        else if ((action.equalsIgnoreCase("Search"))&& (transactionType.equalsIgnoreCase("Loan"))){
                    //System.out.println("Hello");
           // loanAccSearch = request.getParameter("loanAccSearch");
            Connection connection = null;
            ResultSet resultset = null;
            Statement statement = null;
            connection = DbHandler.getDBConnection();
                    
               try {
                statement = connection.createStatement();
            } catch (SQLException ex) {
               // Logger.getLogger(DepositMiscellaneousOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
               // resultset = statement.executeQuery("SELECT LA.KEY_1,(k.first_name||' '||k.middle_name||' '||k.last_name) NAME,LA.SANCTION_AMT as SANCTION_AMT, TO_CHAR(LA.SANC_DT, 'Mon DD, YYYY') as SANC_DT,NVL(TO_CHAR(LA.LST_TXN_DT, 'Mon DD, YYYY'), 'NA')as LST_TXN_DT, LA.PRIN_OUTST as PRIN_OUTST,"
+ "(LA.INTT_OUTST + LA.PENAL_INTT_OUTST + LA.NPA_INTT_OUTST + ROUND(NVL(LA.INTT_ACCR, 0)) + ROUND(NVL(LA.PENAL_INTT_ACCR, 0)) + ROUND(NVL(LA.NPA_INTT_ACCR, 0))) TOT_INT_OUTS,"
+ " ROUND((ABS(LA.PRIN_OUTST) + (ABS(LA.INTT_OUTST) + ABS(LA.PENAL_INTT_OUTST) + ABS(LA.NPA_INTT_OUTST)) + ABS(ROUND(NVL(LA.INTT_ACCR, 0)) + ROUND(NVL(LA.PENAL_INTT_ACCR, 0)) + ROUND(NVL(LA.NPA_INTT_ACCR, 0))))) OUTSTANDING_BALANCE,"
+ "NVL(TO_CHAR(LA.EMI), 'NA') as EMI,L.PROD_CODE,"
+ "(SELECT COUNT(M.MEMBER_ID) FROM BASIC_INFO B,MEMBER_INFORMATION M WHERE B.SHG_ID = M.SHG_ID AND B.CIF = K.CIF_NO) MEMBERCOUNT "
+ "FROM LOAN_ACCOUNT LA, KYC_HDR K,LOAN_PRODUCT L WHERE LA.CUSTOMER_NO = K.CIF_NO AND SUBSTR(LA.GL_CLASS_CODE, 9, 2)='23' "
+ "AND L.ID=LA.LOAN_PROD_ID AND LA.KEY_1 ='" + loanAccSearch + "' and LA.PACS_ID = '" + pacsId + "'");
                
                while(resultset.next()){
                    oRepayLoanBean.setLoanAcc(resultset.getString("KEY_1"));
                    oRepayLoanBean.setCustName(resultset.getString("NAME"));
                    oRepayLoanBean.setSancAmt(resultset.getString("SANCTION_AMT"));
                    oRepayLoanBean.setSancDt(resultset.getString("SANC_DT"));
                    oRepayLoanBean.setLstRepayDt(resultset.getString("LST_TXN_DT"));
                    oRepayLoanBean.setOustPrin(resultset.getString("PRIN_OUTST"));
                    oRepayLoanBean.setOustInt(resultset.getString("TOT_INT_OUTS"));
                    oRepayLoanBean.setOustBal(resultset.getString("OUTSTANDING_BALANCE"));
                    oRepayLoanBean.setEmi(resultset.getString("EMI"));
                    oRepayLoanBean.setProdCode(resultset.getString("PROD_CODE"));    
                                      
                    SeachFound = 1;

                    request.setAttribute("displayFlag", "FY");
                }
            
        }catch(Exception ex){
          //  System.out.println(ex);
        } 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.");
            }

            }
            if (SeachFound == 0) {
                message = "Loan Account not exists in the system";
                request.setAttribute("message", message);
            }

            request.setAttribute("oRepayLoanBeanObj", oRepayLoanBean);
            request.getRequestDispatcher("/Deposit/DepositMiscellaneousOperation.jsp").forward(request, response);

        } else if (action.equalsIgnoreCase("SubmitOperation")) {

            Connection con = null;
            CallableStatement proc = null;

                String miscellOpearation = request.getParameter("operation_type");

            try {
                //BeanUtils.populate(oDepositMiscellaneousBean, request.getParameterMap());
            } catch (IllegalAccessException ex) {
               // Logger.getLogger(DepositMiscellaneousOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InvocationTargetException ex) {
               // Logger.getLogger(DepositMiscellaneousOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
            }

            try {
                con = DbHandler.getDBConnection();
                if( miscellOpearation.equals("RST"))  //added by rajdip Reset Transactions Case
                {
                    resetBy = request.getParameter("optradio");
                   // String accNoRst = request.getParameter("depositAccSearch");
                    
                    try {
                        if (resetBy.equalsIgnoreCase("txn")) {
                           // txnOrAccntNo = request.getParameter("transactionNoInpBox");
                            query = new StringBuilder(" update dep_txn t set t.pb_print_status = NULL where t.acct_no = ? ")
                                                       .append(" and  t.pb_print_status='1' and t.post_time >= (select n.post_time from dep_txn n where n.acct_no = ? and n.cbs_ref_no = ?)  ");
                                    //new StringBuilder(" update dep_txn set pb_print_status=NULL where cbs_ref_no = ?");
                            ps = con.prepareStatement(query.toString());
                            System.out.println("PS:" +ps);
                            ps.setString(1, accNoRst);
                            ps.setString(2, accNoRst);
                            ps.setString(3, txnOrAccntNo);
                            res = ps.executeUpdate();
                            System.out.println("res: " +res);
                            if (res != 0) {
                                message = "All Trasactions from transaction no:" + txnOrAccntNo + " are reset sucessfully";
                                System.out.println("All Trasactions from transaction no :" + txnOrAccntNo + " are reset sucessfully");
                            } else {
                                message = "Trasactions from  no :" + txnOrAccntNo + " reset unsuccessful ";
                                System.out.println("Trasactions from no :" + txnOrAccntNo + " reset unsuccessful . Rows updated:" + res);
                            }
                            query = null;
                        }
                        else if (resetBy.equalsIgnoreCase("accnt")) {
                           // txnOrAccntNo = request.getParameter("accountNoInpBox");
                            query = new StringBuilder("update dep_txn set pb_print_status= NULL where ACCT_NO =? ")
                                                        .append(" and pb_print_status='1' ");
                            ps = con.prepareStatement(query.toString());
                            ps.setString(1, txnOrAccntNo);
                            res = ps.executeUpdate();
                            System.out.println("res: " +res);
                            if (res >= 1) {
                                message = "Txns of Account  no :" + txnOrAccntNo + " are reset sucessfully ";
                                System.out.println("Txns of Account  no :" + txnOrAccntNo + "is reset sucessfully . Rows updated :" + res);
                            } else {
                                message = "Transactions of Account  no " + txnOrAccntNo + " reset unsuccessful ";
                                System.out.println("Txns of Account  no " + txnOrAccntNo + " reset unsuccessful  . Rows updated:" + res);
                            }
                            query = null;
                        }
                        else if (resetBy.equalsIgnoreCase("reset")) {
                          //  resetDate = request.getParameter("reset_date");
                            query = new StringBuilder(" update dep_txn t set t.pb_print_status = NULL where t.acct_no = ? ")
                                                       .append(" and  t.tran_date >= to_date('"+resetDate+"','dd/mm/yyyy') and t.pb_print_status = '1' ");
                                    
                            ps = con.prepareStatement(query.toString());
                            ps.setString(1, accNoRst);

                            res = ps.executeUpdate();
                            
                            if (res != 0) {
                                message = "All Passbook  Trasactions for account no: " + accNoRst + " are reset sucessfully from date: "+resetDate+" ";
                                System.out.println("All Passbook Trasactions for account no: " + accNoRst + " are reset sucessfully from date: "+resetDate+" ");
                            } else {
                                message = "No Passbook Trasactions for account no: " + accNoRst + " are present to reset from date: "+resetDate+" ";
                                System.out.println("No Passbook Trasactions for account no: " + accNoRst + " are present to reset from date: "+resetDate+". Rows updated:" + res);
                            }
                            query = null;
                        }
                    } catch (Exception e) {
                       // e.printStackTrace();
                       System.out.println("Error occurred during processing.");
                    }
                }
                else if( miscellOpearation.equals("SPT"))  //added by Bisnu Set Passbook Transactions case
                {
                    //String accNoRst = request.getParameter("depositAccSearch");

                    try {
                           // printDate = request.getParameter("print_date");
                            query = new StringBuilder(" update dep_txn t set t.pb_print_status = '1' where t.acct_no = ? ")
                                                       .append(" and  t.tran_date <= to_date('"+printDate+"','dd/mm/yyyy') ");
                                    //new StringBuilder(" update dep_txn set pb_print_status=NULL where cbs_ref_no = ?");.cbs_ref_no
                            ps = con.prepareStatement(query.toString());
                            ps.setString(1, accNoRst);
                            
                            res = ps.executeUpdate();
                            if (res != 0) {
                                message = "All Passbook  Trasactions for account no: " + accNoRst + " are skipped sucessfully upto date: "+printDate+" ";
                                System.out.println("All Passbook Trasactions for account no: " + accNoRst + " are skipped sucessfully upto date: "+printDate+" ");
                            } else {
                                message = "No Passbook Trasactions for account no: " + accNoRst + " are present to skip upto date: "+printDate+" ";
                                System.out.println("No Passbook Trasactions for account no: " + accNoRst + " are present to skip upto date: "+printDate+". Rows updated:" + res);
                            }
                            query = null;

                    } catch (Exception e) {
                       // e.printStackTrace();
                       System.out.println("Error occurred during processing.");
                    }
                }
                else if(miscellOpearation.equals("NOM"))
                {
                    //String nomCif = request.getParameter("nomName");
                    //String accNo = request.getParameter("depositAccSearch");
                    //String reason = request.getParameter("rem_stopReson");
                    try{
                     query = new StringBuilder(" update dep_account set NOMINEE_CIF = ?, ACTION_COMMENT = ? where KEY_1 = ?");
                            ps = con.prepareStatement(query.toString());
                            ps.setString(1, nomCif);
                            ps.setString(2, reason);
                            ps.setString(3,accNo);
                            res = ps.executeUpdate();
                            if (res == 1) {
                                message = "Nominee updated sucessfully for acc No :"+accNo ;
                            } else {
                                message = "Nominee updation unsuccessful for acc No; "+accNo;
                            }
                            query = null;

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

                }
               else {
                    try {
                        proc = con.prepareCall("{ call operations.miscle_operation(?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       // Logger.getLogger(DepositMiscellaneousOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       System.out.println("Error occurred during processing.");
                    }
                    proc.setString(1, oDepositMiscellaneousBean.getDepositAccountNumber());
                    proc.setString(2, oDepositMiscellaneousBean.getOperation_type());

                    if (miscellOpearation.equals("M2H")) {
                       // proc.setString(3, request.getParameter("secondCifSearch"));
                        proc.setString(4, "");
                       // proc.setString(5, request.getParameter("modCif2TxtArea"));

                    } else {
                        proc.setString(3, oDepositMiscellaneousBean.getHoldAmt());
                        if (oDepositMiscellaneousBean.getOperation_type().equalsIgnoreCase("RL")) {
                            proc.setString(4, oDepositMiscellaneousBean.getRmvLienRsn());
                        } else {
                            proc.setString(4, oDepositMiscellaneousBean.getStopReson());
                        }
                        proc.setString(5, oDepositMiscellaneousBean.getRem_stopReson());
                    }
                    proc.setString(6, user);



                    proc.registerOutParameter(7, java.sql.Types.VARCHAR);

                    proc.execute();

                    //message = proc.getString(7);
                }
            } catch (SQLException ex) {
               // Logger.getLogger(DepositMiscellaneousOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
               ex.printStackTrace();
               System.out.println("Error occurred during processing.");
            } finally {
                try {
                    if(proc !=null)//added by rajdip
                    proc.close();
                    if(ps != null)
                        ps.close();
                } catch (SQLException e) {
                    System.out.println("Error occurred during proc close.");
                }
                try {
                    con.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(DepositMiscellaneousOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during connection close.");
                }

                request.setAttribute("message", message);

                request.setAttribute("oDepositMiscellaneousBeanObj", oDepositMiscellaneousBean);
                request.getRequestDispatcher("/Deposit/DepositMiscellaneousOperation.jsp").forward(request, response);

            }
        }else if (action.equalsIgnoreCase("SubmitLoanOperation")){
            Connection con = null;
            CallableStatement proc = null;

                String miscellOpearation = request.getParameter("operation_type_loan");

            try {
                //BeanUtils.populate(oDepositMiscellaneousBean, request.getParameterMap());
            } catch (IllegalAccessException ex) {
               // Logger.getLogger(DepositMiscellaneousOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InvocationTargetException ex) {
               // Logger.getLogger(DepositMiscellaneousOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
            if(miscellOpearation.equalsIgnoreCase("RST")){
                
                resetBy = request.getParameter("optradio");
               // String accNoRst = request.getParameter("loanAccSearch");
            try {
                con = DbHandler.getDBConnection();                
                
                if (resetBy.equalsIgnoreCase("txn")) {
                          //  txnOrAccntNo = request.getParameter("transactionNoInpBox");
                            query = new StringBuilder(" update loan_txn t set t.pb_print_status = NULL where t.acct_no = ? ")
                                                       .append(" and  t.pb_print_status='1' and t.post_time >= (select n.post_time from loan_txn n where n.acct_no = ? and n.txn_ref_no = ?)  ");
                            ps = con.prepareStatement(query.toString());
                            System.out.println("PS:" +ps);
                            ps.setString(1, accNoRst);
                            ps.setString(2, accNoRst);
                            ps.setString(3, txnOrAccntNo);
                            res = ps.executeUpdate();
                            System.out.println("res: " +res);
                            if (res != 0) {
                                message = "All Loan Trasactions from transaction no:" + txnOrAccntNo + " are reset sucessfully";
                                System.out.println("All Loan Trasactions from transaction no :" + txnOrAccntNo + " are reset sucessfully");
                            } else {
                                message = "Loan Trasactions from  no :" + txnOrAccntNo + " reset unsuccessful ";
                                System.out.println("Loan Trasactions from no :" + txnOrAccntNo + " reset unsuccessful . Rows updated:" + res);
                            }
                            query = null;
                        }
                        else if (resetBy.equalsIgnoreCase("accnt")) {
                           // txnOrAccntNo = request.getParameter("accountNoInpBox");
                            query = new StringBuilder("update loan_txn set pb_print_status= NULL where ACCT_NO =? ")
                                                        .append(" and pb_print_status='1' ");
                            ps = con.prepareStatement(query.toString());
                            ps.setString(1, txnOrAccntNo);
                            res = ps.executeUpdate();
                            System.out.println("res: " +res);
                            if (res >= 1) {
                                message = "Txns of Loan Account  no :" + txnOrAccntNo + " are reset sucessfully ";
                                System.out.println("Txns of Loan Account  no :" + txnOrAccntNo + "is reset sucessfully . Rows updated :" + res);
                            } else {
                                message = "Transactions of Loan Account  no " + txnOrAccntNo + " reset unsuccessful ";
                                System.out.println("Txns of Loan Account  no " + txnOrAccntNo + " reset unsuccessful  . Rows updated:" + res);
                            }
                            query = null;
                        }
                        else if (resetBy.equalsIgnoreCase("reset")) {
                           // resetDate = request.getParameter("reset_date");
                            query = new StringBuilder(" update loan_txn t set t.pb_print_status = NULL where t.acct_no = ? ")
                                                       .append(" and  t.tran_date >= to_date('"+resetDate+"','dd/mm/yyyy') and t.pb_print_status = '1' ");
                                    
                            ps = con.prepareStatement(query.toString());
                            ps.setString(1, accNoRst);

                            res = ps.executeUpdate();
                            
                            if (res != 0) {
                                message = "All Passbook  Trasactions for Loan account no: " + accNoRst + " are reset sucessfully from date: "+resetDate+" ";
                                System.out.println("All Passbook Trasactions for Loan account no: " + accNoRst + " are reset sucessfully from date: "+resetDate+" ");
                            } else {
                                message = "No Passbook Trasactions for Loan account no: " + accNoRst + " are present to reset from date: "+resetDate+" ";
                                System.out.println("No Passbook Trasactions for Loan account no: " + accNoRst + " are present to reset from date: "+resetDate+". Rows updated:" + res);
                            }
                            query = null;
                        }
            }catch(Exception Ex){
              //  System.err.println("Error is: "+Ex);
            }finally {
                try {
                    if(proc !=null)//added by rajdip
                    proc.close();
                        if(ps != null)
                            ps.close();
                } catch (SQLException e) {
                    System.out.println("Error occurred during proc close.");
                }
                try {
                    con.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(DepositMiscellaneousOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during connection close.");
                }

                request.setAttribute("message", message);

                request.setAttribute("oDepositMiscellaneousBeanObj", oDepositMiscellaneousBean);
                request.getRequestDispatcher("/Deposit/DepositMiscellaneousOperation.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>
}