/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
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 LoginDb.DbHandler;
import DataEntryBean.myWorlistBean;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import oracle.jdbc.OracleTypes;

/**
 *
 * @author Tcs Helpdesk10
 */
public class TransactionAuthorizationServlet 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 connection = null;
        ResultSet rs = null;
        Statement statement = null;
        CallableStatement proc = null;
        int searchFound = 0;
        String flag = "1";
        String message = "";
        String showButton = "N";
        String handle_id = request.getParameter("handle_id");
        String pacsId = (String) session.getAttribute("pacsId");
        String CheckerId = session.getAttribute("user").toString();
        String viewType = session.getAttribute("moduleName").toString();

        myWorlistBean myWorlistBeanObj = new myWorlistBean();
        ArrayList<myWorlistBean> almyWorlistBean = new ArrayList<myWorlistBean>();

        while (flag.equalsIgnoreCase("1")) {

            if (handle_id.equalsIgnoreCase("Search")) {
                flag = "2";

                try {
                  //  BeanUtils.populate(myWorlistBeanObj, request.getParameterMap());
                } catch (IllegalAccessException ex) {
                    // Logger.getLogger(TransactionAuthorizationServlet.class.getName()).log(Level.SEVERE, null, ex);
                    System.out.println("Error occurred during processing.");
                } catch (InvocationTargetException ex) {
                    // Logger.getLogger(TransactionAuthorizationServlet.class.getName()).log(Level.SEVERE, null, ex);
                    System.out.println("Error occurred during processing.");
                }
                try {
                    connection = DbHandler.getDBConnection();
                    try {
                        proc = connection.prepareCall("{ call worklist.my_Worklist_info(?,?,?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                        // Logger.getLogger(TransactionAuthorizationServlet.class.getName()).log(Level.SEVERE, null, ex);
                        System.out.println("Error occurred during processing.");
                    }

                    proc.setString(1, CheckerId);
                    proc.setString(2, myWorlistBeanObj.getRefno());
                    proc.setString(3, pacsId);
                    proc.setString(4, myWorlistBeanObj.getTransactiontype());
                    proc.setString(5, myWorlistBeanObj.getFromDate());
                    proc.setString(6, myWorlistBeanObj.getToDate());

                    proc.registerOutParameter(7, OracleTypes.CURSOR);
                    proc.registerOutParameter(8, java.sql.Types.VARCHAR);
                    proc.setString(8, viewType);
                    proc.setString(9, myWorlistBeanObj.getCheckOption());

                    proc.executeUpdate();

                  //  rs = (ResultSet) proc.getObject(7);

                    if (myWorlistBeanObj.getCheckOption().equalsIgnoreCase("TXN")) {

                        while (rs.next()) {
                            searchFound = 1;
                            myWorlistBeanObj = new myWorlistBean();
                            myWorlistBeanObj.setAccount_no(rs.getString("acct_no"));
                            myWorlistBeanObj.setAccount_no2(rs.getString("acct_no2"));
                            myWorlistBeanObj.setAccount_bal(rs.getString("avail_bal"));
                            myWorlistBeanObj.setRefnoSearch(rs.getString("cbs_ref_no"));
                            myWorlistBeanObj.setIntitiator(rs.getString("maker_id"));
                            myWorlistBeanObj.setTxn_amount(rs.getString("txn_amt"));
                            myWorlistBeanObj.setTransactiontypeSearch(rs.getString("txn_type"));
                            myWorlistBeanObj.setTxn_date(rs.getString("tran_date"));
                            myWorlistBeanObj.setChargeToDeduct(rs.getString("charges"));
                            myWorlistBeanObj.setCust_name(rs.getString("cust_name"));
                            myWorlistBeanObj.setCust_no(rs.getString("cif_no"));
                            myWorlistBeanObj.setTran_ind(rs.getString("tran_ind"));
                            if (viewType.equalsIgnoreCase("LOAN") || viewType.equalsIgnoreCase("KCC")) {
                                myWorlistBeanObj.setPrinrepayamt(rs.getString("PRINREPAYAMT"));
                                myWorlistBeanObj.setInttrepayamt(rs.getString("INTTREPAYAMT"));
                            }

                            almyWorlistBean.add(myWorlistBeanObj);

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

                        }

                    } else if (myWorlistBeanObj.getCheckOption().equalsIgnoreCase("TTP")) {

                        while (rs.next()) {
                            searchFound = 1;
                            myWorlistBeanObj = new myWorlistBean();
                            myWorlistBeanObj.setAccount_no(rs.getString("acct_no"));
                            myWorlistBeanObj.setAccount_no2(rs.getString("acct_no2"));
                            myWorlistBeanObj.setAccount_bal(rs.getString("cum_curr_val"));
                            myWorlistBeanObj.setRefnoSearch(rs.getString("cbs_ref_no"));
                            myWorlistBeanObj.setIntitiator(rs.getString("maker_id"));
                            myWorlistBeanObj.setTxn_amount(rs.getString("txn_amt"));
                            myWorlistBeanObj.setTransactiontypeSearch(rs.getString("txn_type"));
                            myWorlistBeanObj.setTxn_date(rs.getString("tran_date"));
                            myWorlistBeanObj.setChargeToDeduct(rs.getString("charges"));
                            myWorlistBeanObj.setCust_name(rs.getString("cust_name"));
                            myWorlistBeanObj.setCust_no(rs.getString("cif_no"));
                            myWorlistBeanObj.setTran_ind(rs.getString("tran_ind"));

                            almyWorlistBean.add(myWorlistBeanObj);

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

                        }

                    } else if (myWorlistBeanObj.getCheckOption().equalsIgnoreCase("ACC")
                            || myWorlistBeanObj.getCheckOption().equalsIgnoreCase("LACC")
                            || myWorlistBeanObj.getCheckOption().equalsIgnoreCase("KCC")) {

                        while (rs.next()) {
                            searchFound = 1;
                            myWorlistBeanObj = new myWorlistBean();
                            myWorlistBeanObj.setRefnoSearch(rs.getString("ref_id"));
                            myWorlistBeanObj.setIntitiator(rs.getString("teller_id"));
                            myWorlistBeanObj.setTransactiontypeSearch(rs.getString("txn_type"));
                            myWorlistBeanObj.setTxn_date(rs.getString("tran_date"));

                            almyWorlistBean.add(myWorlistBeanObj);

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

                        }

                    }
                   // myWorlistBeanObj.setRefno(request.getParameter("refno"));
                    //myWorlistBeanObj.setTransactiontype(request.getParameter("transactiontype"));
                    //myWorlistBeanObj.setFromDate(request.getParameter("fromDate"));
                    //myWorlistBeanObj.setToDate(request.getParameter("toDate"));
                    //myWorlistBeanObj.setCheckOption(request.getParameter("checkOption"));

                } catch (SQLException ex) {
                    // Logger.getLogger(TransactionAuthorizationServlet.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 {
                        connection.close();
                    } catch (SQLException ex) {
                        // Logger.getLogger(TransactionAuthorizationServlet.class.getName()).log(Level.SEVERE, null, ex);
                        System.out.println("Error occurred during connection close.");
                    }
                }
                if (searchFound == 0) {
                    if (message.equalsIgnoreCase("")) {
                        message = "No data exists for selected item";
                        request.setAttribute("message", message);
                    }
                }

                request.setAttribute("myWorlistBeanObj", myWorlistBeanObj);
                request.setAttribute("almyWorlistBean", almyWorlistBean);
                request.setAttribute("message", message);

                request.getRequestDispatcher("/TransactionAuthorization.jsp").forward(request, response);
            } else if (handle_id.equalsIgnoreCase("Authorise")) {

                String index = request.getParameter("detailId");

                //String refno = request.getParameter("refno" + index);
                //String account_no = request.getParameter("account_no" + index);
                //String transactiontype = request.getParameter("transactiontype" + index);
                //String txn_amount = request.getParameter("txn_amount" + index);
                //String remarks = request.getParameter("remarks" + index);
                //String AuthStatus = request.getParameter("AuthStatus" + index);

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

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

                    proc.setString(1, CheckerId);
                    proc.setString(2, refno);
                    proc.setString(3, pacsId);
                    proc.setString(4, transactiontype);
                    proc.setString(5, txn_amount);
                    proc.setString(6, account_no);
                    proc.setString(7, remarks);
                    proc.setString(8, AuthStatus);

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

                    proc.executeUpdate();

                  //  message = proc.getString(9);

                } catch (SQLException ex) {
                    // Logger.getLogger(TransactionAuthorizationServlet.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 {
                        connection.close();
                    } catch (SQLException ex) {
                        // Logger.getLogger(TransactionAuthorizationServlet.class.getName()).log(Level.SEVERE, null, ex);
                        System.out.println("Error occurred during connection close.");
                    }
                }

                request.setAttribute("message", message);

                if (message.contains("successfully")) {
                    String refNo = message.substring(message.indexOf('#') + 1, message.indexOf('#') + 16);

                    try {
                        Connection cn = DbHandler.getDBConnection();
                        String query = "SELECT TXN_NO FROM NEFT_RTGS_TXN WHERE TXN_NO = ?";
                        PreparedStatement ps = cn.prepareStatement(query);
                        ps.setString(1, refNo);
                        ResultSet rs1 = ps.executeQuery();
                        boolean bool = rs1.next();
                        System.out.println("bool values is " + bool);
                        if (bool) {
                            sendOutwardNeft(refNo);
                        }
                        cn.close();
                        ps.close();
                        rs1.close();
                    } catch (SQLException sqe) {
                        sqe.printStackTrace();
                    }
                }

                if (message.startsWith("Transaction posted successfully")) {
                    if (message.equalsIgnoreCase("Transaction posted successfully. Matured amount withdrawn completed. Account closed")) {
                        showButton = "N";
                    } else {
                        showButton = "Y";
                    }
                    request.setAttribute("showButton", showButton);
                }
                handle_id = "Search";
                /*request.setAttribute("handle_id1", handle_id);
            request.setAttribute("refno", myWorlistBeanObj.getRefno());
            request.setAttribute("transactiontype", transactiontype);
            request.setAttribute("checkOption", myWorlistBeanObj.getCheckOption());
            request.setAttribute("fromDate", myWorlistBeanObj.getFromDate());
            request.setAttribute("toDate", myWorlistBeanObj.getToDate());
            request.getRequestDispatcher("/TransactionAuthorizationServlet").forward(request, response);*/

            } //For View Details
            else if (handle_id.equalsIgnoreCase("ViewDetails")) {

                String index = request.getParameter("detailId");

               // String refno = request.getParameter("refno" + index);
               // String checkOption = request.getParameter("checkOption");

                request.setAttribute("refID", refno);
                request.setAttribute("AuthActivity", checkOption);

                if (checkOption.equalsIgnoreCase("ACC") || checkOption.equalsIgnoreCase("LACC") || checkOption.equalsIgnoreCase("KCC")) {
                    request.getRequestDispatcher("ReadOnlyServlet").forward(request, response);
                    // request.getRequestDispatcher("/TransactionAuthorization.jsp").forward(request, response);
                }

            } //For Successful Authorization
            else if (handle_id.equalsIgnoreCase("AuthorizeAccOpen")) {

                flag = "2";
                //String refno = request.getParameter("SearchID");
                //String AuthActivity = request.getParameter("AuthActivity");

                if (AuthActivity.equalsIgnoreCase("DEPOSIT_ACCOUNT")
                        || AuthActivity.equalsIgnoreCase("KCC_ACCOUNT")) {

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

                        proc.setString(1, CheckerId);
                        proc.setString(2, refno);
                        proc.setString(3, pacsId);
                        proc.setString(4, "A");
                        proc.setString(5, AuthActivity);
                       // proc.setString(6, request.getParameter("AuthComment").toString());

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

                        proc.executeUpdate();

                      //  message = proc.getString(7);

                    } catch (SQLException ex) {
                        // Logger.getLogger(TransactionAuthorizationServlet.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 {
                            connection.close();
                        } catch (SQLException ex) {
                            // Logger.getLogger(TransactionAuthorizationServlet.class.getName()).log(Level.SEVERE, null, ex);
                            System.out.println("Error occurred during connection close.");
                        }
                    }

                } else if (AuthActivity.equalsIgnoreCase("LOAN_ACCOUNT")) {

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

                        proc.setString(1, CheckerId);
                        proc.setString(2, refno);
                        proc.setString(3, pacsId);
                        proc.setString(4, "A");
                       // proc.setString(5, request.getParameter("sancAmt").toString());
                       // proc.setString(6, request.getParameter("charges").toString());
                       // proc.setString(7, request.getParameter("AuthComment").toString());

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

                        proc.executeUpdate();

                       // message = proc.getString(8);

                    } catch (SQLException ex) {
                        // Logger.getLogger(TransactionAuthorizationServlet.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 {
                            connection.close();
                        } catch (SQLException ex) {
                            // Logger.getLogger(TransactionAuthorizationServlet.class.getName()).log(Level.SEVERE, null, ex);
                            System.out.println("Error occurred during connection close.");
                        }
                    }

                }

                request.setAttribute("message", message);

                if (AuthActivity.equalsIgnoreCase("DEPOSIT_ACCOUNT")) {

                    request.getRequestDispatcher("/Deposit/DepositAccountCreationReadonly.jsp").forward(request, response);

                } else if (AuthActivity.equalsIgnoreCase("KCC_ACCOUNT")) {

                    request.getRequestDispatcher("/accountCreationReadOnly.jsp").forward(request, response);

                } else if (AuthActivity.equalsIgnoreCase("LOAN_ACCOUNT")) {

                    request.getRequestDispatcher("/Loan/LoanAccountCreationReadOnly.jsp").forward(request, response);
                }

            } //For Rejection
            else if (handle_id.equalsIgnoreCase("RejectAccOpen")) {

                flag = "2";
                //String refno = request.getParameter("SearchID");
                String AuthActivity = request.getParameter("AuthActivity");

                if (AuthActivity.equalsIgnoreCase("DEPOSIT_ACCOUNT")
                        || AuthActivity.equalsIgnoreCase("KCC_ACCOUNT")) {

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

                        proc.setString(1, CheckerId);
                        proc.setString(2, refno);
                        proc.setString(3, pacsId);
                        proc.setString(4, "R");
                        proc.setString(5, null);
                       // proc.setString(6, request.getParameter("AuthComment").toString());

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

                        proc.executeUpdate();

                      //  message = proc.getString(7);

                    } catch (SQLException ex) {
                        // Logger.getLogger(TransactionAuthorizationServlet.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 {
                            connection.close();
                        } catch (SQLException ex) {
                            // Logger.getLogger(TransactionAuthorizationServlet.class.getName()).log(Level.SEVERE, null, ex);
                            System.out.println("Error occurred during connection close.");
                        }
                    }

                }
                if (AuthActivity.equalsIgnoreCase("LOAN_ACCOUNT")) {

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

                        proc.setString(1, CheckerId);
                        proc.setString(2, refno);
                        proc.setString(3, pacsId);
                        proc.setString(4, "R");
                       // proc.setString(5, request.getParameter("sancAmt").toString());
                       // proc.setString(6, request.getParameter("charges").toString());
                       // proc.setString(7, request.getParameter("AuthComment").toString());

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

                        proc.executeUpdate();

                       // message = proc.getString(8);

                    } catch (SQLException ex) {
                        // Logger.getLogger(TransactionAuthorizationServlet.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 {
                            connection.close();
                        } catch (SQLException ex) {
                            // Logger.getLogger(TransactionAuthorizationServlet.class.getName()).log(Level.SEVERE, null, ex);
                            System.out.println("Error occurred during connection close.");
                        }
                    }

                }

                request.setAttribute("message", message);

                if (AuthActivity.equalsIgnoreCase("DEPOSIT_ACCOUNT")) {

                    request.getRequestDispatcher("/Deposit/DepositAccountCreationReadonly.jsp").forward(request, response);

                } else if (AuthActivity.equalsIgnoreCase("KCC_ACCOUNT")) {

                    request.getRequestDispatcher("/accountCreationReadOnly.jsp").forward(request, response);

                } else if (AuthActivity.equalsIgnoreCase("LOAN_ACCOUNT")) {

                    request.getRequestDispatcher("/Loan/LoanAccountCreationReadOnly.jsp").forward(request, response);
                }

            }
        }

    }

    private void sendOutwardNeft(String refNo) {

        try {
            System.out.println("pinging url");
            URL url = new URL("http://30.0.2.57:8083/neftOutward");
            HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
            urlconnection.setRequestMethod("POST");
            urlconnection.setRequestProperty("Content-Type", "application/json");
            urlconnection.setDoOutput(true);//enables writing data to urlconnection
            String payLoad = "{\"transactionNumber\":" + refNo + "}";
            OutputStream os = urlconnection.getOutputStream();
            os.write(payLoad.getBytes());
            System.out.println("network IO writes successfully");
            os.flush();
            os.close();
            int responseCode = urlconnection.getResponseCode();
            System.out.println(responseCode);
            System.out.println("reference number in sendOutwardNeft is : " + refNo);
            urlconnection.disconnect();

        } catch (Exception ee) {
            System.out.println("reference number in catch block sendOutwardNeft is : " + refNo);
            ee.printStackTrace();
            //System.out.println(ee.getMessage());
        }

    }

// <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>
}
