/*
 * 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 Controller.UploadServlet;
import java.io.IOException;
import java.io.PrintWriter;
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 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 LoginDb.DbHandler;
import DataEntryBean.myWorlistBean;
import java.sql.SQLException;
import oracle.jdbc.OracleTypes;

/**
 *
 * @author Tcs Helpdesk10
 */
public class TransactionAuthorizationServlet_Trading 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("TTXN")) {

                    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("amt_to_be_paid"));
                        myWorlistBeanObj.setTransactiontypeSearch(rs.getString("txn_type"));
                        myWorlistBeanObj.setTxn_date(rs.getString("tran_date"));                        
                        myWorlistBeanObj.setCust_name(rs.getString("cust_name"));
                        myWorlistBeanObj.setCust_no(rs.getString("cif_no"));
                        myWorlistBeanObj.setTran_ind(rs.getString("tran_ind"));
                        myWorlistBeanObj.setSgst_amount(rs.getString("sgst_amt"));
                        myWorlistBeanObj.setCgst_amount(rs.getString("cgst_amt"));
                        myWorlistBeanObj.setDis_amount(rs.getString("dis_amt"));
                        myWorlistBeanObj.setNet_amount(rs.getString("net_amt"));
                        myWorlistBeanObj.setSale_purchase_ref(rs.getString("SALE_PURCHASE_REF_ID"));
                        myWorlistBeanObj.setTrade_product(rs.getString("trad_prod_name"));

                        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("/Trading_JSP/TransactionAuthorization_Trading.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.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("displayFlag", "Y");
            /*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_Trading").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);
            }

        }
    }


    }

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