/*
 * 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;
import java.util.Date;

/**
 *
 * @author Tcs Help desk122
 */
public class LeaveTransactionServlet 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");
       // String fromDt = request.getParameter("fromDt");
      //  String toDt = request.getParameter("toDt");       
        
        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.setStatus(request.getParameter("status" + i));
                       // oPayrollBean.setLeaveId(request.getParameter("leaveId" + i));
                       // oPayrollBean.setEmployee_id(request.getParameter("employee_id" + i));
                       // oPayrollBean.setFromDate(request.getParameter("fromDate" + i));
                       // oPayrollBean.setToDate(request.getParameter("toDate" + 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_transaction(?,?,?,?,?,?,?,?,?,?,?,?) }");
                    } 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, oPayrollBean.getFromDate());
                        proc.setString(7, oPayrollBean.getToDate());
                        proc.setString(8, user);
                        proc.setString(9, Action);
                        proc.setString(10, oPayrollBean.getStatus());
                        proc.setString(11, oPayrollBean.getRemarks());
                        proc.registerOutParameter(12, java.sql.Types.VARCHAR);

                        proc.execute();
                       // message = proc.getString(12);
                        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/LeaveTransaction.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.setStatus(request.getParameter("status" + i));
                        //oPayrollBean.setLeaveId(request.getParameter("leaveId" + i));
                        //oPayrollBean.setEmployee_id(request.getParameter("employee_id" + i));
                        //oPayrollBean.setFromDate(request.getParameter("fromDate" + i));
                       // oPayrollBean.setToDate(request.getParameter("toDate" + 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_transaction(?,?,?,?,?,?,?,?,?,?,?,?) }");
                    } 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, oPayrollBean.getFromDate());
                        proc.setString(7, oPayrollBean.getToDate());
                        proc.setString(8, user);
                        proc.setString(9, Action);
                        proc.setString(10, oPayrollBean.getStatus());
                        proc.setString(11, oPayrollBean.getRemarks());
                        proc.registerOutParameter(12, java.sql.Types.VARCHAR);

                        proc.execute();
                        //message = proc.getString(12);
                        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/LeaveTransaction.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, pacs_id, emp_id, (select emp_id from employee_master w where w.id = k.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 = k.emp_id)) name, leave_id, (select li.leave_name from leave_master li where li.id = k.leave_id and li.pacs_id = k.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 = k.leave_id and li.pacs_id = k.pacs_id) leave_type, no_of_leave, leave_apply_dt, to_char(leave_from_date, 'dd/mm/yyyy')leave_from_date, to_char(leave_to_date, 'dd/mm/yyyy')leave_to_date, status, remarks from emp_leave_txn k where k.status = 'Y' and k.pacs_id = '" +pacsId+ "' and k.leave_from_date >= to_date('" +fromDt+ "', 'dd/mm/yyyy') and k.leave_to_date <= to_date('" +toDt+ "', 'dd/mm/yyyy') ");               

                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.setLeaveId(resultset.getString("leave_id"));
                        oPayrollBean.setLeaveBal(resultset.getString("no_of_leave"));
                        oPayrollBean.setFromDate(resultset.getString("leave_from_date"));
                        oPayrollBean.setToDate(resultset.getString("leave_to_date"));
                        oPayrollBean.setRemarks(resultset.getString("remarks"));
                        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);
            if (alPayrollBean.size() == 0)
            {
               request.setAttribute("message", "No data found."); 
            }
            request.getRequestDispatcher("/Payroll/LeaveTransaction.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";
    }
}
