/*
 * 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.PayrollBean;
import LoginDb.DbHandler;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
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 java.lang.reflect.InvocationTargetException;

/**
 *
 * @author Tcs Help desk122
 */
public class LeaveMasterServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        Connection con = null;
        CallableStatement proc = null;
        String message = "";
        String pacsId = (String) session.getAttribute("pacsId");
        String user = (String) session.getAttribute("user");
       // String Action = request.getParameter("handle_id");
        //String checkOpt = request.getParameter("checkOption");

        PayrollBean oPayrollBean = new PayrollBean();
        ArrayList<PayrollBean> alPayrollBean = new ArrayList<PayrollBean>();
        
        try {
                //BeanUtils.populate(oPayrollBean, request.getParameterMap());
            } catch (IllegalAccessException ex) {
               System.out.println("Error occurred during processing.");
            } catch (InvocationTargetException ex) {
               System.out.println("Error occurred during processing.");
            }

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

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

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

                  //  String leave = request.getParameter("leave" + i);

                    if (leave != null) {
                        oPayrollBean = new PayrollBean();
                        oPayrollBean.setLeave(leave);
                      //  oPayrollBean.setLeaveType(request.getParameter("leaveType" + i));
                      //  oPayrollBean.setYearlyCredit(request.getParameter("yearlyCredit" + i));
                      //  oPayrollBean.setEncashFlag(request.getParameter("encashFlag" + i));
                      //  oPayrollBean.setCarryfFlag(request.getParameter("carryfFlag" + i));
                       // oPayrollBean.setEncashLimit(request.getParameter("encashLimit" + i));
                       // oPayrollBean.setMinReserve(request.getParameter("minReserve" + i));
                       // oPayrollBean.setMaxReserve(request.getParameter("maxReserve" + i));
                       // oPayrollBean.setMinAllow(request.getParameter("minAllow" + i));
                       // oPayrollBean.setMaxAllow(request.getParameter("maxAllow" + i));                        
                       // oPayrollBean.setStatus(request.getParameter("status" + i));
                       // oPayrollBean.setId(request.getParameter("id" + i));
                        alPayrollBean.add(oPayrollBean);
                    }
                } catch (Exception e) {
                    System.out.println("Error occurred during processing.");
                }
            }
            if ((alPayrollBean.size() > 0)) {

                try {                    
                    con = DbHandler.getDBConnection();
                    con.setAutoCommit(false);
                    try {
                        proc = con.prepareCall("{ call payroll.leave_master_entry(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       System.out.println("Error occurred during processing.");
                    }
                    
                    for (int j = 0; j < alPayrollBean.size(); j++) {

                        oPayrollBean = alPayrollBean.get(j);
                        proc.setString(1, oPayrollBean.getId());
                        proc.setString(2, pacsId);
                        proc.setString(3, oPayrollBean.getLeave());
                        proc.setString(4, oPayrollBean.getLeaveType());
                        proc.setString(5, oPayrollBean.getYearlyCredit());
                        proc.setString(6, oPayrollBean.getEncashFlag());
                        proc.setString(7, oPayrollBean.getCarryfFlag());
                        proc.setString(8, oPayrollBean.getEncashLimit());
                        proc.setString(9, oPayrollBean.getMinReserve());
                        proc.setString(10, oPayrollBean.getMaxReserve());
                        proc.setString(11, oPayrollBean.getMinAllow());
                        proc.setString(12, oPayrollBean.getMaxAllow());                        
                        proc.setString(13, user);
                        proc.setString(14, Action);
                        proc.setString(15, oPayrollBean.getStatus());                        
                        proc.registerOutParameter(16, java.sql.Types.VARCHAR);

                        proc.execute();
                       // message = proc.getString(16);
                        if (!message.contains("Successfully")) {
                            con.rollback();
                            break;
                        }
                    }
                    con.commit();
                } catch (SQLException 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) {
                       System.out.println("Error occurred during connection close.");
                    }
                }
            }
            request.setAttribute("message", message);
            request.getRequestDispatcher("/Payroll/LeaveMaster.jsp").forward(request, response);
        
        } else if ("Amend".equalsIgnoreCase(Action)) {            

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

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

                   // String leave = request.getParameter("leave" + i);

                    if (leave != null) {
                        oPayrollBean = new PayrollBean();
                        oPayrollBean.setLeave(leave);
                       // oPayrollBean.setLeaveType(request.getParameter("leaveType" + i));
                        //oPayrollBean.setYearlyCredit(request.getParameter("yearlyCredit" + i));
                       // oPayrollBean.setEncashFlag(request.getParameter("encashFlag" + i));
                        //oPayrollBean.setCarryfFlag(request.getParameter("carryfFlag" + i));
                        //oPayrollBean.setEncashLimit(request.getParameter("encashLimit" + i));
                       // oPayrollBean.setMinReserve(request.getParameter("minReserve" + i));
                       // oPayrollBean.setMaxReserve(request.getParameter("maxReserve" + i));
                       // oPayrollBean.setMinAllow(request.getParameter("minAllow" + i));
                       // oPayrollBean.setMaxAllow(request.getParameter("maxAllow" + i));                        
                       // oPayrollBean.setStatus(request.getParameter("status" + i));
                       // oPayrollBean.setId(request.getParameter("id" + i));
                        alPayrollBean.add(oPayrollBean);
                    }
                } catch (Exception e) {
                    System.out.println("Error occurred during processing.");
                }
            }
            if ((alPayrollBean.size() > 0)) {

                try {                    
                    con = DbHandler.getDBConnection();
                    con.setAutoCommit(false);
                    try {
                        proc = con.prepareCall("{ call payroll.leave_master_entry(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       System.out.println("Error occurred during processing.");
                    }
                    
                    for (int j = 0; j < alPayrollBean.size(); j++) {

                        oPayrollBean = alPayrollBean.get(j);
                        proc.setString(1, oPayrollBean.getId());
                        proc.setString(2, pacsId);
                        proc.setString(3, oPayrollBean.getLeave());
                        proc.setString(4, oPayrollBean.getLeaveType());
                        proc.setString(5, oPayrollBean.getYearlyCredit());
                        proc.setString(6, oPayrollBean.getEncashFlag());
                        proc.setString(7, oPayrollBean.getCarryfFlag());
                        proc.setString(8, oPayrollBean.getEncashLimit());
                        proc.setString(9, oPayrollBean.getMinReserve());
                        proc.setString(10, oPayrollBean.getMaxReserve());
                        proc.setString(11, oPayrollBean.getMinAllow());
                        proc.setString(12, oPayrollBean.getMaxAllow());                        
                        proc.setString(13, user);
                        proc.setString(14, Action);
                        proc.setString(15, oPayrollBean.getStatus());                        
                        proc.registerOutParameter(16, java.sql.Types.VARCHAR);

                        proc.execute();
                       // message = proc.getString(16);
                        if (!message.contains("Successfully")) {
                            con.rollback();
                            break;
                        }
                    }
                    con.commit();
                } catch (SQLException 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) {
                       System.out.println("Error occurred during connection close.");
                    }
                }
            }
            request.setAttribute("message", message);
            request.getRequestDispatcher("/Payroll/LeaveMaster.jsp").forward(request, response);
        
        } else if ("getDetails".equalsIgnoreCase(Action)) {
            
            ResultSet resultset = null;
            Statement statement = null;            
            
            Connection connection = DbHandler.getDBConnection();
            try {
                statement = connection.createStatement();
            } catch (SQLException ex) {
               System.out.println("Error occurred during processing.");
            }
            try {
               // resultset = statement.executeQuery("select id, leave_name, leave_type, yearly_credit, encashed_flag, carry_forward_flag, encash_limt, minimum_reserve, maximum_reserve, minimum_allow, maximum_allow, status from leave_master where pacs_id = '" +pacsId+ "' ");               

                while (resultset.next()) {
                    
                        oPayrollBean = new PayrollBean();
                        oPayrollBean.setId(resultset.getString("id"));
                        oPayrollBean.setLeave(resultset.getString("leave_name"));
                        oPayrollBean.setLeaveType(resultset.getString("leave_type"));
                        oPayrollBean.setYearlyCredit(resultset.getString("yearly_credit"));
                        oPayrollBean.setEncashFlag(resultset.getString("encashed_flag"));
                        oPayrollBean.setCarryfFlag(resultset.getString("carry_forward_flag"));
                        oPayrollBean.setEncashLimit(resultset.getString("encash_limt"));
                        oPayrollBean.setMinReserve(resultset.getString("minimum_reserve"));
                        oPayrollBean.setMaxReserve(resultset.getString("maximum_reserve"));
                        oPayrollBean.setMinAllow(resultset.getString("minimum_allow"));
                        oPayrollBean.setMaxAllow(resultset.getString("maximum_allow"));                        
                        oPayrollBean.setStatus(resultset.getString("status"));
                    
                    alPayrollBean.add(oPayrollBean);
                    request.setAttribute("displayFlag", "Y");
                }
            } catch (SQLException ex) {
               System.out.println("Error occurred during processing.");
            } finally {
                try {
                    statement.close();
                    resultset.close();
                } catch (SQLException e) {
                    System.out.println("Error occurred during proc close.");
                }
                try {
                    connection.close();
                } catch (SQLException ex) {
                   System.out.println("Error occurred during processing.");
                }
            }            
            request.setAttribute("checkOption", checkOpt);
            request.setAttribute("oPayrollBean", oPayrollBean);
            request.setAttribute("arrPayrollBean", alPayrollBean);
            request.getRequestDispatcher("/Payroll/LeaveMaster.jsp").forward(request, response);
        }
    }

    @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";
    }
}
