/*
 * 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 DataEntryBean.transactionOperationBean;
import DataEntryBean.TDOperationBean;
import LoginDb.DbHandler;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
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 org.apache.commons.beanutils.BeanUtils;
import javax.servlet.http.HttpSession;
import oracle.jdbc.OracleTypes;
import java.sql.*;
import java.util.*;

/**
 *
 * @author Shub
 */
public class transactionOperationServlet 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 {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet transactionOperationServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet transactionOperationServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    // <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);

        Connection con = null;
        CallableStatement proc = null;
        String message = "";
        String Account_type = "";
        String JSP = "";
        HttpSession session = request.getSession();
        JSP = request.getParameter("screenName") == null ? "" : (request.getParameter("screenName"));
        String ttype =request.getParameter("tranType");
        String ref_no=null;
        String ac_no=null;
        String txn_type=null;

        transactionOperationBean otransactionOperationBean = new transactionOperationBean();

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

        //For Loan

        if (JSP.equalsIgnoreCase("LoanTransactionOperation")) {

            try {
                con = DbHandler.getDBConnection();
                try {

                    proc = con.prepareCall("{ call operations.POST_Loan_TXN_authorization(?,?,?,?,?,?,?,?,?) }");

                } catch (SQLException ex) {
                   // Logger.getLogger(transactionOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing.");
                }
                String pacsId = session.getAttribute("pacsId").toString();
                String makerId = session.getAttribute("user").toString();

                proc.setString(1, pacsId);
                proc.setString(2, makerId);
                proc.setString(3, otransactionOperationBean.getTranType());
                proc.setString(4, otransactionOperationBean.getAccNo());
                proc.setString(5, otransactionOperationBean.getTrAmount());
                proc.setString(6, otransactionOperationBean.getChargeToDeduct());
                proc.setString(7, otransactionOperationBean.getNarration());
                proc.registerOutParameter(8, java.sql.Types.VARCHAR);
                proc.registerOutParameter(9, java.sql.Types.VARCHAR);

                proc.execute();

               // message = proc.getString(9);
                Account_type = proc.getString(8);

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

            }

            //For KCC and Deposit

        }else if(JSP.equalsIgnoreCase("ShgTransaction")){

            transactionOperationBean oTransactionBean=new transactionOperationBean();
            ArrayList <transactionOperationBean> alTransactionBean=new ArrayList <transactionOperationBean>();
            try {
                con = DbHandler.getDBConnection();
                try {

                    proc = con.prepareCall("{ call shg_member_details(?,?,?,?) }");

                } catch (SQLException ex) {
                   // Logger.getLogger(transactionOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing.");
                }
                String pacsId = session.getAttribute("pacsId").toString();
               // String shgId = request.getParameter("accNo").toString();
                //String tranType=request.getParameter("tranType").toString();


                proc.setString(1, pacsId);
                proc.setString(2, shgId);
                proc.registerOutParameter(3, OracleTypes.CURSOR);
                proc.registerOutParameter(4, java.sql.Types.VARCHAR);


                proc.execute();


               // message = proc.getString(4);

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

                while(rs.next())
                {
                    oTransactionBean=new transactionOperationBean();
                    oTransactionBean.setMember_id(rs.getString("member_id"));
                    oTransactionBean.setMember_name(rs.getString("member_name"));
                    alTransactionBean.add(oTransactionBean);
                    request.setAttribute("displayFlag", "Y");
                }

                 request.setAttribute("alTransactionBean", alTransactionBean);
                 request.setAttribute("message", message);
                 request.setAttribute("accNo", shgId);
                 //request.setAttribute("narration",request.getParameter("narration"));
                 request.setAttribute("tranTp", tranType);
                // request.setAttribute("status", request.getParameter("status"));
                // request.setAttribute("product_id", request.getParameter("product_id"));
                // request.setAttribute("cust_no", request.getParameter("cust_no"));
                // request.setAttribute("member_count", request.getParameter("member_count"));

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

                request.getRequestDispatcher("/Deposit/DepositTransactionOperation.jsp").forward(request, response);
            }
        }
         else {


            try {
                con = DbHandler.getDBConnection();
                try {


                    proc = con.prepareCall("{ call operations.POST_KCC_TXN_authorization(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }");

                } catch (SQLException ex) {
                   // Logger.getLogger(transactionOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing.");
                }
                String pacsId = session.getAttribute("pacsId").toString();
                String makerId = session.getAttribute("user").toString();
               // String twothouIN = (String) request.getParameter("twothouIN") == "" ? "0" : (request.getParameter("twothouIN"));
               // String twothouOUT = request.getParameter("twothouOUT") == "" ? "0" : (request.getParameter("twothouOUT"));
               // String fivehundredIN = request.getParameter("fivehundredIN") == "" ? "0" : (request.getParameter("fivehundredIN"));
               // String fivehundredOUT = request.getParameter("fivehundredOUT") == "" ? "0" : (request.getParameter("fivehundredOUT"));
               // String hundredIN = request.getParameter("hundredIN") == "" ? "0" : (request.getParameter("hundredIN"));
               // String hundredOUT = request.getParameter("hundredOUT") == "" ? "0" : (request.getParameter("hundredOUT"));
               // String fiftyIN = request.getParameter("fiftyIN") == "" ? "0" : (request.getParameter("fiftyIN"));
               // String fiftyOUT = request.getParameter("fiftyOUT") == "" ? "0" : (request.getParameter("fiftyOUT"));
               // String twentyIN = request.getParameter("twentyIN") == "" ? "0" : (request.getParameter("twentyIN"));
               // String twentyOUT = request.getParameter("twentyOUT") == "" ? "0" : (request.getParameter("twentyOUT"));
               // String tenIN = request.getParameter("tenIN") == "" ? "0" : (request.getParameter("tenIN"));
               // String tenOUT = request.getParameter("tenOUT") == "" ? "0" : (request.getParameter("tenOUT"));
               // String fiveIN = request.getParameter("fiveIN") == "" ? "0" : (request.getParameter("fiveIN"));
                //String fiveOUT = request.getParameter("fiveOUT") == "" ? "0" : (request.getParameter("fiveOUT"));
                //String twoIN = request.getParameter("twoIN") == "" ? "0" : (request.getParameter("twoIN"));
                //String twoOUT = request.getParameter("twoOUT") == "" ? "0" : (request.getParameter("twoOUT"));
                //String oneIN = request.getParameter("oneIN") == "" ? "0" : (request.getParameter("oneIN"));
                //String oneOUT = request.getParameter("oneOUT") == "" ? "0" : (request.getParameter("oneOUT"));
                //String fiftyPaisaIN = request.getParameter("fiftyPaisaIN") == "" ? "0" : (request.getParameter("fiftyPaisaIN"));
                //String fiftyPaisaOUT = request.getParameter("fiftyPaisaOUT") == "" ? "0" : (request.getParameter("fiftyPaisaOUT"));
                //String onePaisaIN = request.getParameter("onePaisaIN") == "" ? "0" : (request.getParameter("onePaisaIN"));
                //String onePaisaOUT = request.getParameter("onePaisaOUT") == "" ? "0" : (request.getParameter("onePaisaOUT"));
                //String twohundredIN = request.getParameter("twohundredIN") == "" ? "0" : (request.getParameter("twohundredIN"));
                //String twohundredOUT = request.getParameter("twohundredOUT") == "" ? "0" : (request.getParameter("twohundredOUT"));
                //String product_id=request.getParameter("product_id");

                ac_no=otransactionOperationBean.getAccNo();
                txn_type=otransactionOperationBean.getTranType();




                proc.setString(1, pacsId);
                proc.setString(2, makerId);
                proc.setString(3, otransactionOperationBean.getTranType());
                proc.setString(4, otransactionOperationBean.getAccNo());
                proc.setString(5, otransactionOperationBean.getTrAmount());
                proc.setString(6, twothouIN);
                proc.setString(7, fivehundredIN);
                proc.setString(8, hundredIN);
                proc.setString(9, fiftyIN);
                proc.setString(10, twentyIN);
                proc.setString(11, tenIN);
                proc.setString(12, fiveIN);
                proc.setString(13, twoIN);
                proc.setString(14, oneIN);
                proc.setString(15, fiftyPaisaIN);
                proc.setString(16, onePaisaIN);
                proc.setString(17, twothouOUT);
                proc.setString(18, fivehundredOUT);
                proc.setString(19, hundredOUT);
                proc.setString(20, fiftyOUT);
                proc.setString(21, twentyOUT);
                proc.setString(22, tenOUT);
                proc.setString(23, fiveOUT);
                proc.setString(24, twoOUT);
                proc.setString(25, oneOUT);
                proc.setString(26, fiftyPaisaOUT);
                proc.setString(27, onePaisaOUT);
                proc.setString(28, otransactionOperationBean.getNarration());
                proc.registerOutParameter(29, java.sql.Types.VARCHAR);
                proc.registerOutParameter(30, java.sql.Types.VARCHAR);
                proc.setString(31, otransactionOperationBean.getIntAdjAmt());
                proc.setString(32, otransactionOperationBean.getTranMode());
                proc.setString(33, otransactionOperationBean.getTransferAcc());
                proc.registerOutParameter(34, java.sql.Types.VARCHAR);
                proc.setString(35, twohundredIN);
                proc.setString(36, twohundredOUT);
                //proc.setString(34, product_id);


                proc.execute();

                //message = proc.getString(30);
                Account_type = proc.getString(29);
                ref_no=proc.getString(34);




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



                con = DbHandler.getDBConnection();
                try {


                    proc = con.prepareCall("{ call shg_txn_insert(?,?,?,?,?) }");

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

                transactionOperationBean oTransactionBean=new transactionOperationBean();
                ArrayList <transactionOperationBean> alTransactionBean=new ArrayList <transactionOperationBean>();

                try{

                String mem_count=request.getParameter("member_count")== "" ? "0" :request.getParameter("member_count");
                int rec_count=0;

                if(txn_type.equalsIgnoreCase("1"))
                {
                    txn_type="CR";
                }
                else
                {
                    txn_type="DR";
                }

                if(Integer.parseInt(mem_count)>0)
                {
                    for (int i=1;i<=(Integer.parseInt(mem_count));i++)
                    {
                        String txn_amt=request.getParameter("txnAmount" + i);

                        if(txn_amt.equals("")==true )
                        {
                            txn_amt="0";
                        }

                        Integer amt=Integer.parseInt(txn_amt);
                        if(amt>0)
                        {
                         oTransactionBean=new transactionOperationBean();
                         //oTransactionBean.setMember_id(request.getParameter("member_id" + i));
                         //oTransactionBean.setTrAmount(request.getParameter("txnAmount" + i));
                         alTransactionBean.add(oTransactionBean);
                         rec_count++;
                        }

                    }
                }

                if(rec_count>0)
                {
                    for (int j = 0; j < alTransactionBean.size(); j++) {

                        oTransactionBean=alTransactionBean.get(j);

                        proc.setString(1,ref_no);
                        proc.setString(2,ac_no);
                        proc.setString(3,txn_type);
                        proc.setString(4,oTransactionBean.getMember_id());
                        proc.setString(5,oTransactionBean.getTrAmount());
                        proc.addBatch();
                    }

                    proc.executeBatch();
                }

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

        }

        request.setAttribute("message", message);


        if (Account_type.equalsIgnoreCase("1") || Account_type.equalsIgnoreCase("5") || Account_type.equalsIgnoreCase("2")) {

            if (Account_type.equalsIgnoreCase("2")) {
                request.getRequestDispatcher("/Deposit/TDOperation.jsp").forward(request, response);
            } else {
                request.getRequestDispatcher("/Deposit/DepositTransactionOperation.jsp").forward(request, response);
            }

        } else if (Account_type.equalsIgnoreCase("7")) {

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

        } else {

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