/*
 * 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 LeaveBalanceServlet 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 employee = request.getParameter("employee" + i);

                    if (employee != null) {
                        oPayrollBean = new PayrollBean();
                        oPayrollBean.setEmployee(employee);
                        oPayrollBean.setEname(request.getParameter("ename" + i));
                        oPayrollBean.setLeave(request.getParameter("leave" + i));
                       // oPayrollBean.setLeaveBal(request.getParameter("leaveBal" + i));
                       // oPayrollBean.setRemarks(request.getParameter("remarks" + i));                        
                       // oPayrollBean.setLeaveId(request.getParameter("leaveId" + i));
                       // oPayrollBean.setEmployee_id(request.getParameter("employee_id" + 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_process_credit(?,?,?,?,?,?,?,?,?) }");
                    } 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.getEmployee_id());
                        proc.setString(4, oPayrollBean.getLeaveId());
                        proc.setString(5, oPayrollBean.getLeaveBal());
                        proc.setString(6, user);
                        proc.setString(7, Action);
                        proc.setString(8, oPayrollBean.getRemarks());
                        proc.registerOutParameter(9, java.sql.Types.VARCHAR);

                        proc.execute();
                       // message = proc.getString(9);
                        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/LeaveBalance.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 employee = request.getParameter("employee" + i);

                    if (employee != null) {
                        oPayrollBean = new PayrollBean();
                        oPayrollBean.setEmployee(employee);
                        oPayrollBean.setEname(request.getParameter("ename" + i));
                        oPayrollBean.setLeave(request.getParameter("leave" + i));
                      //  oPayrollBean.setLeaveBal(request.getParameter("leaveBal" + i));
                       // oPayrollBean.setRemarks(request.getParameter("remarks" + i));                        
                       // oPayrollBean.setLeaveId(request.getParameter("leaveId" + i));
                      //  oPayrollBean.setEmployee_id(request.getParameter("employee_id" + 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_process_credit(?,?,?,?,?,?,?,?,?) }");
                    } 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.getEmployee_id());
                        proc.setString(4, oPayrollBean.getLeaveId());
                        proc.setString(5, oPayrollBean.getLeaveBal());
                        proc.setString(6, user);
                        proc.setString(7, Action);                                               
                        proc.setString(8, oPayrollBean.getRemarks());                        
                        proc.registerOutParameter(9, java.sql.Types.VARCHAR);

                        proc.execute();
                       // message = proc.getString(9);
                        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/LeaveBalance.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, emp_id, (select emp_id from employee_master w where w.id = p.emp_id) emp_no, (select k.first_name || ' ' || k.middle_name || ' ' || k.last_name from kyc_hdr k where k.cif_no = (select e.cif_no from employee_master e where e.id = p.emp_id)) name, (select li.leave_name from leave_master li where li.id = p.leave_id and li.pacs_id = p.pacs_id) leave_name, (select (case leave_type when '1' then 'Earned Leave' when '2' then 'Medical Leave' when '3' then 'Casual Leave' when '4' then 'Others Leave' end) from leave_master li where li.id = p.leave_id and li.pacs_id = p.pacs_id) leave_type, LEAVE_ID, balance, REMARKS from emp_leave_balance p where pacs_id = '" +pacsId+ "' order by 2 ");               

                while (resultset.next()) {
                    
                        oPayrollBean = new PayrollBean();
                        oPayrollBean.setId(resultset.getString("id"));
                        oPayrollBean.setEmployee_id(resultset.getString("emp_id"));
                        oPayrollBean.setEmployee(resultset.getString("emp_no"));
                        oPayrollBean.setEname(resultset.getString("name"));
                        oPayrollBean.setLeave(resultset.getString("leave_type"));
                        oPayrollBean.setLeaveBal(resultset.getString("balance"));
                        oPayrollBean.setLeaveId(resultset.getString("LEAVE_ID"));
                        oPayrollBean.setRemarks(resultset.getString("REMARKS"));
                    
                    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/LeaveBalance.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";
    }
}
