/*
 * 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 EmployeeMasterServlet 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.setCif(request.getParameter("cif" + i));
                       // oPayrollBean.setJoinDate(request.getParameter("joinDate" + i));
                       // oPayrollBean.setConfirmDate(request.getParameter("confirmDate" + i));
                       // oPayrollBean.setRetireDate(request.getParameter("retireDate" + i));
                       // oPayrollBean.setDesignationCode(request.getParameter("designationCode" + i));
                       // oPayrollBean.setSalaryAcc(request.getParameter("salaryAcc" + i));
                        //oPayrollBean.setGradeCode(request.getParameter("gradeCode" + i));
                       // oPayrollBean.setBasicAmt(request.getParameter("basicAmt" + i));
                       // oPayrollBean.setDaRate(request.getParameter("daRate" + i));
                       // oPayrollBean.setDaAmt(request.getParameter("daAmt" + i));
                       // oPayrollBean.setMsaAmt(request.getParameter("msaAmt" + i));
                       // oPayrollBean.setEpfStaffRate(request.getParameter("epfStaffRate" + i));
                       // oPayrollBean.setEpfStaffAmt(request.getParameter("epfStaffAmt" + i));
                       // oPayrollBean.setEpfSocRate(request.getParameter("epfSocRate" + i));
                       // oPayrollBean.setEpfSocAmt(request.getParameter("epfSocAmt" + i));
                       // oPayrollBean.setTaxAmt(request.getParameter("taxAmt" + i));
                       // oPayrollBean.setOtherAmt(request.getParameter("otherAmt" + i));
                       // oPayrollBean.setStatus(request.getParameter("status" + i));
                       // oPayrollBean.setEmployee_id(request.getParameter("employee_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.employee_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.getEmployee_id());
                        proc.setString(2, oPayrollBean.getEmployee());
                        proc.setString(3, pacsId);
                        proc.setString(4, oPayrollBean.getCif());
                        proc.setString(5, oPayrollBean.getJoinDate());
                        proc.setString(6, oPayrollBean.getConfirmDate());
                        proc.setString(7, oPayrollBean.getRetireDate());
                        proc.setString(8, oPayrollBean.getDesignationCode());
                        proc.setString(9, oPayrollBean.getSalaryAcc());
                        proc.setString(10, oPayrollBean.getGradeCode());
                        proc.setString(11, oPayrollBean.getBasicAmt());
                        proc.setString(12, oPayrollBean.getDaRate());
                        proc.setString(13, oPayrollBean.getDaAmt());
                        proc.setString(14, oPayrollBean.getMsaAmt());
                        proc.setString(15, oPayrollBean.getEpfStaffRate());
                        proc.setString(16, oPayrollBean.getEpfStaffAmt());
                        proc.setString(17, oPayrollBean.getEpfSocRate());
                        proc.setString(18, oPayrollBean.getEpfSocAmt());
                        proc.setString(19, oPayrollBean.getTaxAmt());
                        proc.setString(20, oPayrollBean.getOtherAmt());
                        proc.setString(21, user);
                        proc.setString(22, Action);
                        proc.setString(23, oPayrollBean.getStatus());                        
                        proc.registerOutParameter(24, java.sql.Types.VARCHAR);

                        proc.execute();
                       // message = proc.getString(24);
                        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/EmployeeMaster.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.setCif(request.getParameter("cif" + i));
                       // oPayrollBean.setJoinDate(request.getParameter("joinDate" + i));
                       // oPayrollBean.setConfirmDate(request.getParameter("confirmDate" + i));
                       // oPayrollBean.setRetireDate(request.getParameter("retireDate" + i));
                       // oPayrollBean.setDesignationCode(request.getParameter("designationCode" + i));
                       // oPayrollBean.setSalaryAcc(request.getParameter("salaryAcc" + i));
                       // oPayrollBean.setGradeCode(request.getParameter("gradeCode" + i));
                       // oPayrollBean.setBasicAmt(request.getParameter("basicAmt" + i));
                       // oPayrollBean.setDaRate(request.getParameter("daRate" + i));
                       // oPayrollBean.setDaAmt(request.getParameter("daAmt" + i));
                       // oPayrollBean.setMsaAmt(request.getParameter("msaAmt" + i));
                      //  oPayrollBean.setEpfStaffRate(request.getParameter("epfStaffRate" + i));
                      //  oPayrollBean.setEpfStaffAmt(request.getParameter("epfStaffAmt" + i));
                      //  oPayrollBean.setEpfSocRate(request.getParameter("epfSocRate" + i));
                      //  oPayrollBean.setEpfSocAmt(request.getParameter("epfSocAmt" + i));
                      //  oPayrollBean.setTaxAmt(request.getParameter("taxAmt" + i));
                      //  oPayrollBean.setOtherAmt(request.getParameter("otherAmt" + i));
                      //  oPayrollBean.setStatus(request.getParameter("status" + i));
                      //  oPayrollBean.setEmployee_id(request.getParameter("employee_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.employee_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.getEmployee_id());
                        proc.setString(2, oPayrollBean.getEmployee());
                        proc.setString(3, pacsId);
                        proc.setString(4, oPayrollBean.getCif());
                        proc.setString(5, oPayrollBean.getJoinDate());
                        proc.setString(6, oPayrollBean.getConfirmDate());
                        proc.setString(7, oPayrollBean.getRetireDate());
                        proc.setString(8, oPayrollBean.getDesignationCode());
                        proc.setString(9, oPayrollBean.getSalaryAcc());
                        proc.setString(10, oPayrollBean.getGradeCode());
                        proc.setString(11, oPayrollBean.getBasicAmt());
                        proc.setString(12, oPayrollBean.getDaRate());
                        proc.setString(13, oPayrollBean.getDaAmt());
                        proc.setString(14, oPayrollBean.getMsaAmt());
                        proc.setString(15, oPayrollBean.getEpfStaffRate());
                        proc.setString(16, oPayrollBean.getEpfStaffAmt());
                        proc.setString(17, oPayrollBean.getEpfSocRate());
                        proc.setString(18, oPayrollBean.getEpfSocAmt());
                        proc.setString(19, oPayrollBean.getTaxAmt());
                        proc.setString(20, oPayrollBean.getOtherAmt());
                        proc.setString(21, user);
                        proc.setString(22, Action);
                        proc.setString(23, oPayrollBean.getStatus());                        
                        proc.registerOutParameter(24, java.sql.Types.VARCHAR);

                        proc.execute();
                       // message = proc.getString(24);
                        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/EmployeeMaster.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, pacs_id, cif_no, to_char(date_of_joining, 'dd/mm/yyyy')date_of_joining, to_char(date_of_confirm, 'dd/mm/yyyy')date_of_confirm, to_char(date_of_retirement, 'dd/mm/yyyy')date_of_retirement, designation_code, salary_account_no, grade_code, basic, da_rate, da_amount, msa, epf_staff_rate, epf_staff_amount, epf_soc_rate, epf_soc_amount, p_tax, other_deduction, status, (select ki.first_name || ' ' || ki.middle_name || ' ' || ki.last_name from kyc_hdr ki where ki.cif_no =l.cif_no ) emp_name from employee_master l where l.pacs_id = '" +pacsId+ "' ");               

                while (resultset.next()) {
                    
                        oPayrollBean = new PayrollBean();
                        oPayrollBean.setEmployee_id(resultset.getString("id"));
                        oPayrollBean.setEmployee(resultset.getString("emp_id"));
                        oPayrollBean.setCif(resultset.getString("cif_no"));
                        oPayrollBean.setEname(resultset.getString("emp_name"));
                        oPayrollBean.setJoinDate(resultset.getString("date_of_joining"));
                        oPayrollBean.setConfirmDate(resultset.getString("date_of_confirm"));
                        oPayrollBean.setRetireDate(resultset.getString("date_of_retirement"));
                        oPayrollBean.setDesignationCode(resultset.getString("designation_code"));
                        oPayrollBean.setSalaryAcc(resultset.getString("salary_account_no"));
                        oPayrollBean.setGradeCode(resultset.getString("grade_code"));
                        oPayrollBean.setBasicAmt(resultset.getString("basic"));
                        oPayrollBean.setDaRate(resultset.getString("da_rate"));
                        oPayrollBean.setDaAmt(resultset.getString("da_amount"));
                        oPayrollBean.setMsaAmt(resultset.getString("msa"));
                        oPayrollBean.setEpfStaffRate(resultset.getString("epf_staff_rate"));
                        oPayrollBean.setEpfStaffAmt(resultset.getString("epf_staff_amount"));
                        oPayrollBean.setEpfSocRate(resultset.getString("epf_soc_rate"));
                        oPayrollBean.setEpfSocAmt(resultset.getString("epf_soc_amount"));
                        oPayrollBean.setTaxAmt(resultset.getString("p_tax"));
                        oPayrollBean.setOtherAmt(resultset.getString("other_deduction"));
                        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/EmployeeMaster.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";
    }
}
