/*
 * 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 EmployeeDependentMasterServlet 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.setDependent(request.getParameter("dependent" + i));
                       // oPayrollBean.setDob(request.getParameter("dob" + i));
                       // oPayrollBean.setRelation(request.getParameter("relation" + i));
                       // oPayrollBean.setNominee(request.getParameter("nominee" + i));                        
                       // oPayrollBean.setStatus(request.getParameter("status" + 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.employee_dependent_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, oPayrollBean.getEmployee_id());
                        proc.setString(3, pacsId);
                        proc.setString(4, oPayrollBean.getDependent());
                        proc.setString(5, oPayrollBean.getDob());
                        proc.setString(6, oPayrollBean.getRelation());
                        proc.setString(7, oPayrollBean.getNominee());                       
                        proc.setString(8, user);
                        proc.setString(9, Action);
                        proc.setString(10, oPayrollBean.getStatus());                        
                        proc.registerOutParameter(11, java.sql.Types.VARCHAR);

                        proc.execute();
                       // message = proc.getString(11);
                        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/EmployeeDependentMaster.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.setDependent(request.getParameter("dependent" + i));
                        //oPayrollBean.setDob(request.getParameter("dob" + i));
                       // oPayrollBean.setRelation(request.getParameter("relation" + i));
                       // oPayrollBean.setNominee(request.getParameter("nominee" + i));                        
                        //oPayrollBean.setStatus(request.getParameter("status" + 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.employee_dependent_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, oPayrollBean.getEmployee_id());
                        proc.setString(3, pacsId);
                        proc.setString(4, oPayrollBean.getDependent());
                        proc.setString(5, oPayrollBean.getDob());
                        proc.setString(6, oPayrollBean.getRelation());
                        proc.setString(7, oPayrollBean.getNominee());                       
                        proc.setString(8, user);
                        proc.setString(9, Action);
                        proc.setString(10, oPayrollBean.getStatus());                        
                        proc.registerOutParameter(11, java.sql.Types.VARCHAR);

                        proc.executeUpdate();
                       // message = proc.getString(11);
                        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/EmployeeDependentMaster.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, dependent_name, to_char(dob, 'dd/mm/yyyy') dob, relation, nominee_flag, status from employee_dependent_master 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.setDependent(resultset.getString("dependent_name"));
                        oPayrollBean.setDob(resultset.getString("dob"));
                        oPayrollBean.setRelation(resultset.getString("relation"));
                        oPayrollBean.setNominee(resultset.getString("nominee_flag"));
                        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.");
                }
            }            
           // oPayrollBean.setCheckOption(checkOpt);
            request.setAttribute("checkOption", checkOpt);
            request.setAttribute("oPayrollBean", oPayrollBean);
            request.setAttribute("arrPayrollBean", alPayrollBean);
            request.getRequestDispatcher("/Payroll/EmployeeDependentMaster.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";
    }
}
