/*
 * 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.DepositKYCCreationHdrBean;
import DataEntryBean.DepositKYCCreationDetailBean;
import LoginDb.DbHandler;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.sql.BatchUpdateException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
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.sql.Statement;
import java.util.Arrays;
import java.util.StringTokenizer;
import javax.servlet.ServletContext;

/**
 *
 * @author TCS
 */
public class DepositKYCCreationServlet extends HttpServlet {

    private boolean isMultipart;
    private int maxFileSize = 5000 * 1024;
    private int maxMemSize = 4 * 1024;
    private String uploadPathMain;
    private String uploadPath;
    private File file;
    private int fileUpload = 0;
    private File renameFile;
    private boolean t;

    /**
     * stmtesses requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void stmtessRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</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 doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        stmtessRequest(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 {

        HttpSession session = request.getSession(false);
        Connection con = null;
        Connection con1 = null;
        CallableStatement stmt = null;
        ResultSet rs = null;
        int SeachFound = 0;
        String message = "";
        String hdrId = "";
        String PhotouploadedFlag = "";
        String scanImg = "";
        String pacsId = (String) session.getAttribute("pacsId");
        String user = (String) session.getAttribute("user");
        //String handle_id = request.getParameter("handle_id");
        //String cifNumber = request.getParameter("cifNumber");
        String message2 = "";
        String lastPhotoName = (String) session.getAttribute("lastPhotoName");
        String sigPhotoName = (String) session.getAttribute("sigPhotoName");
        ArrayList<String> upldFile = null;
        if (session.getAttribute("upldFile") == null) {
            upldFile = new ArrayList<String>(Arrays.asList("",
                    "", "", "", "", "", "", "", "", ""));
        } else {
            upldFile = (ArrayList<String>) session.getAttribute("upldFile");
        }
        if (lastPhotoName == null) {
            lastPhotoName = "";
        }
        if (sigPhotoName == null) {
            sigPhotoName = "";
        }
        //String photpath = "";

        DepositKYCCreationHdrBean oDepositKYCCreationBean = new DepositKYCCreationHdrBean();
        DepositKYCCreationDetailBean oDepositKYCCreationDetailBean = new DepositKYCCreationDetailBean();
        ArrayList<DepositKYCCreationDetailBean> alDepositKYCCreationDetailBean = new ArrayList<DepositKYCCreationDetailBean>();

        //For Update

        ArrayList<DepositKYCCreationDetailBean> alDepositKYCCreationDetailBeanNew = new ArrayList<DepositKYCCreationDetailBean>();
        ArrayList<DepositKYCCreationDetailBean> alDepositKYCCreationDetailBeanUpdated = new ArrayList<DepositKYCCreationDetailBean>();
        ArrayList<DepositKYCCreationDetailBean> alDepositKYCCreationDetailBeanDeleted = new ArrayList<DepositKYCCreationDetailBean>();


        BatchExecutionFailedOperation BatchExecutionFailedOperationObject = new BatchExecutionFailedOperation();
        boolean SuccessFlag;


        try {
           // BeanUtils.populate(oDepositKYCCreationBean, request.getParameterMap());
        } catch (IllegalAccessException ex) {
           // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error occurred during processing.");
        } catch (InvocationTargetException ex) {
           // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error occurred during processing.");
        }

        try {
           // BeanUtils.populate(oDepositKYCCreationDetailBean, request.getParameterMap());
        } catch (IllegalAccessException ex) {
           // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error occurred during processing.");
        } catch (InvocationTargetException ex) {
           // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error occurred during processing.");
        }




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


            ServletContext servletContext = getServletContext();
            //uploadPathMain = servletContext.getRealPath(File.separator);
            uploadPath = uploadPathMain + "/" + "UploadedFiles";
            File destinationDir = new File(uploadPath);
            String a;

            if (!destinationDir.exists()) {
                destinationDir.mkdir();
            }



            //File oldfile = new File(uploadPath + File.separator + oDepositKYCCreationBean.getFile() + ".jpg");

            //oldPhotoName = oDepositKYCCreationBean.getFile();
            //System.out.println(oldPhotoName);
            //START HEADER PART
            try {

                con = DbHandler.getDBConnection();
                try {

                    stmt = con.prepareCall("{ call Operations.kyc_Deposit_hdr(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }");

                } catch (SQLException ex) {
                   // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing.");
                }

                a = oDepositKYCCreationBean.getSigUpld();
                stmt.setString(1, oDepositKYCCreationBean.getcType());

                stmt.setString(2, oDepositKYCCreationBean.getTitle());
                stmt.setString(3, oDepositKYCCreationBean.getfName());
                stmt.setString(4, oDepositKYCCreationBean.getmName());
                stmt.setString(5, oDepositKYCCreationBean.getlName());
                stmt.setString(6, oDepositKYCCreationBean.getgName());
                stmt.setString(7, oDepositKYCCreationBean.getAdd1());
                stmt.setString(8, oDepositKYCCreationBean.getAdd2());
                stmt.setString(9, oDepositKYCCreationBean.getAdd3());
                stmt.setString(10, oDepositKYCCreationBean.getDistname());
                stmt.setString(11, oDepositKYCCreationBean.getCity());
                stmt.setString(12, oDepositKYCCreationBean.getStatename());
                stmt.setString(13, oDepositKYCCreationBean.getDob());
                stmt.setString(14, oDepositKYCCreationBean.getGender());
                stmt.setString(15, oDepositKYCCreationBean.getmNumber());
                stmt.setString(16, oDepositKYCCreationBean.getBlock());
                stmt.setString(17, oDepositKYCCreationBean.getCif());
                stmt.setString(18, handle_id);
                stmt.setString(19, pacsId);
                stmt.setString(20, oDepositKYCCreationBean.getFile());
                stmt.registerOutParameter(21, java.sql.Types.VARCHAR);
                stmt.setString(22, oDepositKYCCreationBean.getSigUpld());
                stmt.setString(23, oDepositKYCCreationBean.getReligion());
                stmt.setString(24, oDepositKYCCreationBean.getCaste());
                stmt.setString(25, oDepositKYCCreationBean.getMem_no());
                stmt.setString(26, oDepositKYCCreationBean.getFarmerType());
                stmt.setString(27, oDepositKYCCreationBean.getEmailId());
                stmt.setString(28, user);
                stmt.setString(29, oDepositKYCCreationBean.getBankCIF());
                stmt.setString(30, oDepositKYCCreationBean.getLstatus());
                stmt.setString(31, oDepositKYCCreationBean.getDoDeath());
                stmt.setString(32, oDepositKYCCreationBean.getMotherName());
                stmt.setString(33, oDepositKYCCreationBean.getPin());
                stmt.setString(34, oDepositKYCCreationBean.getWard()); // Added as a part of member share report
                stmt.execute();

               // message = stmt.getString(21);
                message2 = stmt.getString(21);
                hdrId = (message.split("#")[1]).trim();


                if (!lastPhotoName.isEmpty()) {
                    File f = null;
                    File f1 = null;
                    try {
                        // create new File objects
                        f = new File(uploadPath + File.separator + lastPhotoName);
                        f1 = new File(uploadPath + File.separator + hdrId + ".jpg");

                        // rename file
                        t = f.renameTo(f1);
                    } catch (Exception e) {
                        // if any error occurs
                       // e.printStackTrace();
                       System.out.println("Error occurred during processing.");
                    }
                }

                //For Signature
                if (!sigPhotoName.isEmpty()) {
                    File f = null;
                    File f1 = null;
                    try {
                        // create new File objects
                        f = new File(uploadPath + File.separator + sigPhotoName);
                        f1 = new File(uploadPath + File.separator + "sig-" + hdrId + ".jpg");

                        // rename file
                        t = f.renameTo(f1);
                    } catch (Exception e) {
                        // if any error occurs
                       // e.printStackTrace();
                       System.out.println("Error occurred during processing.");
                    }
                }
                session.setAttribute("lastPhotoName", "");
                session.setAttribute("sigPhotoName", "");
                //File newfile = new File(uploadPath + File.separator + hdrId + ".jpg");
                //oldfile.renameTo(newfile);
                //new File(uploadPath + File.separator + oDepositKYCCreationBean.getFile() + ".jpg").renameTo(new File(uploadPath + File.separator + hdrId + ".jpg"));

            } catch (SQLException ex) {
//                try {
//                   // con.rollback();
//                } catch (Exception ex1) {
//                   // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex1);
//                   System.out.println("Error occurred during processing.");
//                }
               // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               // System.out.println(ex.toString());
               message="Error occured in KYC Creation.";
               System.out.println("Error occurred during processing.");
            } finally {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    System.out.println("Error occurred during procedure close.");
                }
                try {
                    con.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during connection close.");
                }

            }
            if(message=="Error occured in KYC Creation.") {
                request.setAttribute("message", message);
                request.getRequestDispatcher("/Deposit/DepositKYCCreation.jsp").forward(request, response);
            }    
            //END HEADER PART
            //START DETAIL PART
            
            if (!hdrId.equalsIgnoreCase("")) {
                int counter = Integer.parseInt(request.getParameter("rowCounter"));

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

                       // String document_mst_id = request.getParameter("document_mst_id" + i);
                       // String idNumber = request.getParameter("idNumber" + i);
                       // String idIssueAt = request.getParameter("idIssueAt" + i);
                       // String idIssueDate = request.getParameter("idIssueDate" + i);
                        String upldFlag = request.getParameter("upldFlag" + i);

                       if (upldFlag.equalsIgnoreCase("1")) {
                            scanImg = hdrId + "_" + document_mst_id.substring(document_mst_id.length() - 2) + ".jpg";
                            //For ID Scan Image
                            if (!upldFile.isEmpty()) {
                                File f = null;
                                File f1 = null;
                                try {
                                    // create new File objects
                                    f = new File(uploadPath + File.separator + upldFile.get(i - 1));
                                    f1 = new File(uploadPath + File.separator + scanImg);

                                    // rename file
                                    t = f.renameTo(f1);
                                } catch (Exception e) {
                                    // if any error occurs
                                   // e.printStackTrace();
                                   System.out.println("Error occurred during processing.");
                                }
                            }
                        } else if (upldFlag.equalsIgnoreCase("0")) {
                            scanImg = null;
                        }


                        if (idNumber != null) {
                            oDepositKYCCreationDetailBean = new DepositKYCCreationDetailBean();
                            oDepositKYCCreationDetailBean.setDocument_mst_id(document_mst_id);
                            oDepositKYCCreationDetailBean.setIdNumber(idNumber);
                            oDepositKYCCreationDetailBean.setIdIssueAt(idIssueAt);
                            oDepositKYCCreationDetailBean.setIdIssueDate(idIssueDate);
                            oDepositKYCCreationDetailBean.setScanImg(scanImg);


                            alDepositKYCCreationDetailBean.add(oDepositKYCCreationDetailBean);
                        }
                    } catch (Exception e) {
                        System.out.println("Error occurred during processing.");
                    }
                }

                session.removeAttribute("upldFile");

                if (alDepositKYCCreationDetailBean.size() > 0) {
                    try {
                        con = DbHandler.getDBConnection();
                        stmt = con.prepareCall("{ call Operations.deposit_kyc_dtl(?,?,?,?,?,?,?,?,?) }");
                        for (int j = 0; j < alDepositKYCCreationDetailBean.size(); j++) {
                            oDepositKYCCreationDetailBean = alDepositKYCCreationDetailBean.get(j);
                            stmt.setString(1, hdrId);
                            stmt.setString(2, oDepositKYCCreationDetailBean.getKYCCreation_dtl_id());
                            stmt.setString(3, oDepositKYCCreationDetailBean.getDocument_mst_id());
                            stmt.setString(4, oDepositKYCCreationDetailBean.getIdNumber());
                            stmt.setString(5, oDepositKYCCreationDetailBean.getIdIssueAt());
                            stmt.setString(6, oDepositKYCCreationDetailBean.getIdIssueDate());
                            stmt.setString(7, handle_id);
                            stmt.setString(8, oDepositKYCCreationDetailBean.getScanImg());
                            stmt.setString(9, user);
                            stmt.addBatch();

                        }

                        stmt.executeBatch();

                    } catch (BatchUpdateException ex) {

                        try {
                           // con.rollback();

                            SuccessFlag = BatchExecutionFailedOperationObject.BatchExecutionFailedOperation("DepositKYCCreation.jsp", hdrId);

                            message = "Entered ID Number already tagged with another CIF.";
                            // message = ex.toString();


                        } catch (Exception ex1) {
                           // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex1);
                           System.out.println("Error occurred during processing.");
                        }


                       // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error occurred during processing.");
                    } catch (SQLException ex1) {
                        message = "Error occurred while KYC Creation. Please try Again.";
                       // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex1);
                       System.out.println("Error occurred during processing.");
                    } finally {
                        try {
                            stmt.close();
                        } catch (SQLException e) {
                           // System.out.println(e.toString());
                           System.out.println("Error occurred during statement close.");
                        }
                        try {
                            con.close();
                            session.removeAttribute("upldFile");
                        } catch (SQLException ex) {
                           // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                           // System.out.println(ex.toString());
                           System.out.println("Error occurred during connection close.");
                        }
                    }

                }
            }

            request.setAttribute("message", message);
            request.getRequestDispatcher("/Deposit/DepositKYCCreation.jsp").forward(request, response);

        } else if (handle_id.equalsIgnoreCase("SearchCIF")) {

            Connection connection = null;
            ResultSet resultset = null;
            Statement statement = null;

          try {
            connection = DbHandler.getDBConnection();

            try {
                statement = connection.createStatement();
            } catch (SQLException ex) {
               // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            }
            try {
               // resultset = statement.executeQuery("select CIF_NO,customer_type,"
                        + "title,"
                        + "first_name,"
                        + "middle_name,"
                        + "last_name,"
                        + "guardian_name,"
                        + "MOTHER_NAME,"
                        + "address_1,"
                        + "address_2,"
                        + "address_3,"
                        + "PIN_CODE,"
                        + "district,"
                        + "city,"
                        + "state,"
                        + "birth_date,"
                        + "gender,"
                        + "mobile_no,"
                        + "BLOCK,PHOTO_PATH,sig_photo,"
                        + "RELIGION,CASTE,MEMBERSHIP_NO,FARMER_TYPE,email_id, " //added by rajdip email
                        + "BANK_CIF,Alive_Dead,Date_Of_death,ward " //added by Bishnu
                        + " from kyc_hdr where cif_no='" + cifNumber + "'");

                while (resultset.next()) {
                    oDepositKYCCreationBean.setCif(resultset.getString("CIF_NO"));
                    oDepositKYCCreationBean.setcType(resultset.getString("customer_type"));
                    oDepositKYCCreationBean.setTitle(resultset.getString("title"));
                    oDepositKYCCreationBean.setfName(resultset.getString("first_name"));
                    oDepositKYCCreationBean.setmName(resultset.getString("middle_name"));
                    oDepositKYCCreationBean.setlName(resultset.getString("last_name"));
                    oDepositKYCCreationBean.setgName(resultset.getString("guardian_name"));
                    oDepositKYCCreationBean.setAdd1(resultset.getString("address_1"));
                    oDepositKYCCreationBean.setAdd2(resultset.getString("address_2"));
                    oDepositKYCCreationBean.setAdd3(resultset.getString("address_3"));
                    oDepositKYCCreationBean.setDistname(resultset.getString("district"));
                    oDepositKYCCreationBean.setCity(resultset.getString("city"));
                    oDepositKYCCreationBean.setStatename(resultset.getString("state"));
                    oDepositKYCCreationBean.setDob(resultset.getString("birth_date"));
                    oDepositKYCCreationBean.setGender(resultset.getString("gender"));
                    oDepositKYCCreationBean.setmNumber(resultset.getString("mobile_no"));
                    oDepositKYCCreationBean.setBlock(resultset.getString("BLOCK"));
                    oDepositKYCCreationBean.setFile(resultset.getString("PHOTO_PATH"));
                    oDepositKYCCreationBean.setSigUpld(resultset.getString("sig_photo"));
                    oDepositKYCCreationBean.setReligion(resultset.getString("RELIGION"));
                    oDepositKYCCreationBean.setCaste(resultset.getString("CASTE"));
                    oDepositKYCCreationBean.setMem_no(resultset.getString("MEMBERSHIP_NO"));
                    oDepositKYCCreationBean.setFarmerType(resultset.getString("FARMER_TYPE"));
                    oDepositKYCCreationBean.setEmailId(resultset.getString("email_id"));
                    oDepositKYCCreationBean.setBankCIF(resultset.getString("BANK_CIF"));
                    oDepositKYCCreationBean.setAliveDead(resultset.getString("Alive_Dead"));
                    oDepositKYCCreationBean.setDoDeath(resultset.getString("Date_Of_death"));
                    oDepositKYCCreationBean.setMotherName(resultset.getString("MOTHER_NAME"));
                    oDepositKYCCreationBean.setPin(resultset.getString("PIN_CODE"));
                    oDepositKYCCreationBean.setWard((resultset.getString("WARD")));

                    SeachFound = 1;
                    request.setAttribute("displayFlag", "Y");

                }

                statement.close();
                resultset.close();

            } catch (SQLException ex) {
               // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            } finally {
                System.out.println("Processing done.");
            }

            //Detail Part Populate
            try {
                statement = connection.createStatement();
            } catch (SQLException ex) {
               // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            }

            try {
                String query = "select d.id,d.kyc_document_mst_id,m.document_dtl,m.score,d.id_no,to_char(d.id_issue_date,'dd/mm/yyyy') as id_issue_date,d.id_issued_at,d.scan_img from kyc_dtl d,kyc_document_mst m where d.kyc_document_mst_id = m.id and d.cif_no='" + cifNumber + "'";
              //  rs = statement.executeQuery(query);

                while (rs.next()) {

                    oDepositKYCCreationDetailBean = new DepositKYCCreationDetailBean();
                    oDepositKYCCreationDetailBean.setKYCCreation_dtl_id(rs.getString("id"));
                    oDepositKYCCreationDetailBean.setIdType(rs.getString("document_dtl"));
                    oDepositKYCCreationDetailBean.setIDScore(rs.getString("score"));
                    oDepositKYCCreationDetailBean.setIdNumber(rs.getString("id_no"));
                    oDepositKYCCreationDetailBean.setIdIssueDate(rs.getString("id_issue_date"));
                    oDepositKYCCreationDetailBean.setIdIssueAt(rs.getString("id_issued_at"));
                    oDepositKYCCreationDetailBean.setDocument_mst_id(rs.getString("kyc_document_mst_id"));
                    oDepositKYCCreationDetailBean.setScanImg(rs.getString("scan_img"));

                    alDepositKYCCreationDetailBean.add(oDepositKYCCreationDetailBean);

                }
                statement.close();
                rs.close();
            } catch (SQLException ex) {
               // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            }

            if (SeachFound == 0) {
                message = "CIF details not exists in the system";
                request.setAttribute("message", message);
            }
          } finally {
            try {
                connection.close();
            } catch (SQLException e) {
               // System.out.println(e.toString());
               System.out.println("Error occurred during processing.");
            }
        }

            request.setAttribute("oDepositKYCCreationBeanObj", oDepositKYCCreationBean);
            request.setAttribute("alDepositKYCCreationDetailBean", alDepositKYCCreationDetailBean);

            request.setAttribute("message", message);
            request.getRequestDispatcher("/Deposit/DepositKYCInquiry.jsp").forward(request, response);

        } else if (handle_id.equalsIgnoreCase("Update")) {

            try {
               // BeanUtils.populate(oDepositKYCCreationBean, request.getParameterMap());
            } catch (IllegalAccessException ex) {
               // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            } catch (InvocationTargetException ex) {
               // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            }

            try {
               // BeanUtils.populate(oDepositKYCCreationDetailBean, request.getParameterMap());
            } catch (IllegalAccessException ex) {
               // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            } catch (InvocationTargetException ex) {
               // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            }

            ServletContext servletContext = getServletContext();
            uploadPathMain = servletContext.getRealPath(File.separator);
            uploadPath = uploadPathMain + "/" + "UploadedFiles";
            File destinationDir = new File(uploadPath);

            try {
                con = DbHandler.getDBConnection();
                try {
                    stmt = con.prepareCall("{ call Operations.kyc_Deposit_hdr(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }");

                } catch (SQLException ex) {
                   // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing.");
                }

                stmt.setString(1, oDepositKYCCreationBean.getcTypeAmend());
                stmt.setString(2, oDepositKYCCreationBean.getTittleAmend());
                stmt.setString(3, oDepositKYCCreationBean.getfNameAmend());
                stmt.setString(4, oDepositKYCCreationBean.getmNameAmend());
                stmt.setString(5, oDepositKYCCreationBean.getlNameAmend());
                stmt.setString(6, oDepositKYCCreationBean.getgNameAmend());
                stmt.setString(7, oDepositKYCCreationBean.getAdd1Amend());
                stmt.setString(8, oDepositKYCCreationBean.getAdd2Amend());
                stmt.setString(9, oDepositKYCCreationBean.getAdd3Amend());
                stmt.setString(10, oDepositKYCCreationBean.getDistnameAmend());
                stmt.setString(11, oDepositKYCCreationBean.getCitynameAmend());
                stmt.setString(12, oDepositKYCCreationBean.getStatenameAmend());
                stmt.setString(13, oDepositKYCCreationBean.getDobAmend());
                stmt.setString(14, oDepositKYCCreationBean.getGenderAmend());
                stmt.setString(15, oDepositKYCCreationBean.getmNumberAmend());
                stmt.setString(16, oDepositKYCCreationBean.getBlockAmend());
                stmt.setString(17, oDepositKYCCreationBean.getCifNoAmend());
                stmt.setString(18, handle_id);
                stmt.setString(19, pacsId);
                stmt.setString(20, oDepositKYCCreationBean.getFile());
                stmt.registerOutParameter(21, java.sql.Types.VARCHAR);
                stmt.setString(22, oDepositKYCCreationBean.getSigUpld());
                stmt.setString(23, oDepositKYCCreationBean.getReligionAmend());
                stmt.setString(24, oDepositKYCCreationBean.getCasteAmend());
                stmt.setString(25, oDepositKYCCreationBean.getMem_noAmend());
                stmt.setString(26, oDepositKYCCreationBean.getFarmerTypeAmend());
                stmt.setString(27, oDepositKYCCreationBean.getEmailId());
                stmt.setString(28, user);
                stmt.setString(29, oDepositKYCCreationBean.getBankCIF());
                stmt.setString(30, oDepositKYCCreationBean.getLstatus());
                stmt.setString(31, oDepositKYCCreationBean.getDoDeath());
                stmt.setString(32, oDepositKYCCreationBean.getMotherNameAmend());
                stmt.setString(33, oDepositKYCCreationBean.getPinAmend());
                stmt.setString(34, oDepositKYCCreationBean.getwardAmend()); // Added for member share report.
                stmt.execute();
                //message = stmt.getString(21);
                hdrId = (message.split("#")[1]).trim();

                if (!lastPhotoName.isEmpty()) {
                    File f = null;
                    File f1 = null;
                    try {
                        // create new File objects
                        f = new File(uploadPath + File.separator + lastPhotoName);
                        f1 = new File(uploadPath + File.separator + hdrId + ".jpg");

                        if (f1.exists()) {
                            f1.delete();
                        }
                        // rename file
                        t = f.renameTo(f1);
                    } catch (Exception e) {
                        // if any error occurs
                       // e.printStackTrace();
                       System.out.println("Error occurred during processing.");
                    }
                }

                //For Signature
                if (!sigPhotoName.isEmpty()) {
                    File f = null;
                    File f1 = null;
                    try {
                        // create new File objects
                        f = new File(uploadPath + File.separator + sigPhotoName);
                        f1 = new File(uploadPath + File.separator + "sig-" + hdrId + ".jpg");

                        if (f1.exists()) {
                            f1.delete();
                        }
                        // rename file
                        t = f.renameTo(f1);
                    } catch (Exception e) {
                        // if any error occurs
                       // e.printStackTrace();
                       System.out.println("Error occurred during processing.");
                    }
                }

                session.setAttribute("lastPhotoName", "");
                session.setAttribute("sigPhotoName", "");

            } catch (SQLException ex) {
//                try {
//                   // con.rollback();
//                } catch (Exception ex1) {
//                   // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex1);
//                   System.out.println("Error occurred during processing.");
//                }
//                Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
//                System.out.println(ex.toString());
                    System.out.println("Error occurred during processing.");
            } finally {
                    try {
                        stmt.close();
                    } catch (SQLException e) {
                       // System.out.println(e.toString());
                       System.out.println("Error occurred during statement close.");
                    }
                    try {
                        con.close();
                        
                    } catch (SQLException ex) {
                       // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error occurred during connection close.");
                    }
                }

            //Detail Part Starts here
            int counterfor_Detail = Integer.parseInt(request.getParameter("rowCounter"));

            for (int i = 1; i <= counterfor_Detail; i++) {
                try {
                    String idTypeAmend = request.getParameter("idTypeAmend" + i);
                    String ScoreAmend = request.getParameter("ScoreAmend" + i);
                    //String idNumberAmend = request.getParameter("idNumberAmend" + i);
                    //String idIssueAtAmend = request.getParameter("idIssueAtAmend" + i);
                    //String idIssueDateAmend = request.getParameter("idIssueDateAmend" + i);
                    //String document_mst_idAmend = request.getParameter("document_mst_idAmend" + i);
                    String rowStatus = request.getParameter("rowStatus" + i);
                    //String KYCCreation_dtl_id = request.getParameter("KYCCreation_dtl_id" + i);
                    String upldFlag = request.getParameter("upldFlag" + i);
                        if (upldFlag.equalsIgnoreCase("1")) {
                            scanImg = hdrId + "_" + document_mst_idAmend.substring(document_mst_idAmend.length() - 2) + ".jpg";
                            //For ID Scan Image
                            if (!upldFile.isEmpty()) {
                                File f = null;
                                File f1 = null;
                                try {
                                    // create new File objects
                                    f = new File(uploadPath + File.separator + upldFile.get(i - 1));
                                    f1 = new File(uploadPath + File.separator + scanImg);

                                    if (f1.exists()) {
                                        f1.delete();
                                    }
                                    // rename file
                                    t = f.renameTo(f1);
                                } catch (Exception e) {
                                    // if any error occurs
                                   // e.printStackTrace();
                                   System.out.println("Error occurred during processing.");
                                }
                            }
                        } else if (upldFlag.equalsIgnoreCase("0")) {
                            scanImg = null;
                        }

                    if (document_mst_idAmend != null && rowStatus != null) {
                        oDepositKYCCreationDetailBean = new DepositKYCCreationDetailBean();
                        oDepositKYCCreationDetailBean.setIdTypeAmend(idTypeAmend);
                        oDepositKYCCreationDetailBean.setIDScoreAmend(ScoreAmend);
                        oDepositKYCCreationDetailBean.setIdNumberAmend(idNumberAmend);
                        oDepositKYCCreationDetailBean.setIdIssueAtAmend(idIssueAtAmend);
                        oDepositKYCCreationDetailBean.setIdIssueDateAmend(idIssueDateAmend);
                        oDepositKYCCreationDetailBean.setDocument_mst_idAmend(document_mst_idAmend);
                        oDepositKYCCreationDetailBean.setKYCCreation_dtl_id(KYCCreation_dtl_id);
                        oDepositKYCCreationDetailBean.setScanImg(scanImg);

                        if (rowStatus.equals("N")) {
                            alDepositKYCCreationDetailBeanNew.add(oDepositKYCCreationDetailBean);
                        } else {
                            alDepositKYCCreationDetailBeanUpdated.add(oDepositKYCCreationDetailBean);
                        }
                    }
                } catch (Exception e) {
                    System.out.println("Error occurred during processing.");
                }
            }

            //For Deletion in Detail Part
            //String deletedRows = request.getParameter("deletedRows");

            if ((!deletedRows.equalsIgnoreCase(null)) || (!deletedRows.equalsIgnoreCase(""))) {
                StringTokenizer tokenizer = new StringTokenizer(deletedRows, ",");

                while (tokenizer.hasMoreTokens()) {
                    oDepositKYCCreationDetailBean = new DepositKYCCreationDetailBean();
                    oDepositKYCCreationDetailBean.setKYCCreation_dtl_id(tokenizer.nextToken());

                    alDepositKYCCreationDetailBeanDeleted.add(oDepositKYCCreationDetailBean);
                }
            }

            if ((alDepositKYCCreationDetailBeanUpdated.size() > 0) && (!hdrId.equalsIgnoreCase(""))) {
                try {
                    con = DbHandler.getDBConnection();
                    try {
                        stmt = con.prepareCall("{ call Operations.deposit_kyc_dtl(?,?,?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       System.out.println("Error occurred during processing.");
                    }


                    for (int j = 0; j < alDepositKYCCreationDetailBeanUpdated.size(); j++) {
                        oDepositKYCCreationDetailBean = alDepositKYCCreationDetailBeanUpdated.get(j);

                        stmt.setString(1, oDepositKYCCreationBean.getCifNoAmend());
                        stmt.setString(2, oDepositKYCCreationDetailBean.getKYCCreation_dtl_id());
                        stmt.setString(3, oDepositKYCCreationDetailBean.getDocument_mst_idAmend());
                        stmt.setString(4, oDepositKYCCreationDetailBean.getIdNumberAmend());
                        stmt.setString(5, oDepositKYCCreationDetailBean.getIdIssueAtAmend());
                        stmt.setString(6, oDepositKYCCreationDetailBean.getIdIssueDateAmend());
                        stmt.setString(7, handle_id);
                        stmt.setString(8, oDepositKYCCreationDetailBean.getScanImg());
                        stmt.setString(9, user);
                        stmt.addBatch();
                    }

                    stmt.executeBatch();

                } catch (BatchUpdateException ex) {

                    try {
                       // con.rollback();
                        session.removeAttribute("upldFile");

                        //SuccessFlag = BatchExecutionFailedOperationObject.BatchExecutionFailedOperation("DepositKYCCreation.jsp", hdrId);

                        message = "Atleast one entered ID Number already tagged to anothe CIF!";
                        // message = ex.toString();


                    } catch (Exception ex1) {
                       // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex1);
                       System.out.println("Error occurred during processing.");
                    }


                   // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error occurred during processing.");
                } catch (SQLException ex) {
//                    try {
//                       // con.rollback();
//                    } catch (Exception ex1) {
//                       // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex1);
//                       System.out.println("Error occurred during processing.");
//                    }
                   // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error occurred during processing.");
                } finally {
                    try {
                        stmt.close();
                    } catch (SQLException e) {
                       // System.out.println(e.toString());
                       System.out.println("Error occurred during statement close.");
                    }
                    try {
                        con.close();
                        session.removeAttribute("upldFile");
                    } catch (SQLException ex) {
                       // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error occurred during processing.");
                    }
                }
            }

            if ((alDepositKYCCreationDetailBeanDeleted.size() > 0) && (!hdrId.equalsIgnoreCase(""))) {
                try {
                    con = DbHandler.getDBConnection();
                    try {
                        stmt = con.prepareCall("{ call Operations.deposit_kyc_dtl(?,?,?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       System.out.println("Error occurred during processing.");
                    }

                    for (int j = 0; j < alDepositKYCCreationDetailBeanDeleted.size(); j++) {

                        oDepositKYCCreationDetailBean = new DepositKYCCreationDetailBean();
                        oDepositKYCCreationDetailBean = alDepositKYCCreationDetailBeanDeleted.get(j);

                        stmt.setString(1, oDepositKYCCreationBean.getCifNoAmend());
                        stmt.setString(2, oDepositKYCCreationDetailBean.getKYCCreation_dtl_id());
                        stmt.setString(3, oDepositKYCCreationDetailBean.getDocument_mst_idAmend());
                        stmt.setString(4, oDepositKYCCreationDetailBean.getIdNumberAmend());
                        stmt.setString(5, oDepositKYCCreationDetailBean.getIdIssueAtAmend());
                        stmt.setString(6, oDepositKYCCreationDetailBean.getIdIssueDateAmend());
                        stmt.setString(7, "Delete");
                        stmt.setString(8, null);
                        stmt.setString(9, user);
                        stmt.addBatch();
                    }
                    stmt.executeBatch();
                } catch (SQLException ex) {
//                    try {
//                       // con.rollback();
//                    } catch (Exception ex1) {
//                       // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex1);
//                       System.out.println("Error occurred during processing.");
//                    }
                   // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error occurred during processing.");
                } finally {
                    try {
                        stmt.close();
                    } catch (SQLException e) {
                        //System.out.println(e.toString());
                        System.out.println("Error occurred during statement close.");
                    }
                    try {
                        con.close();
                    } catch (SQLException ex) {
                       // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error occurred during connection close.");
                    }
                }
            }

            if ((alDepositKYCCreationDetailBeanNew.size() > 0) && (!hdrId.equalsIgnoreCase(""))) {
                try {
                    con = DbHandler.getDBConnection();
                    try {
                        stmt = con.prepareCall("{call Operations.deposit_kyc_dtl(?,?,?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       System.out.println("Error occurred during processing.");
                    }


                    for (int j = 0; j < alDepositKYCCreationDetailBeanNew.size(); j++) {
                        oDepositKYCCreationDetailBean = new DepositKYCCreationDetailBean();
                        oDepositKYCCreationDetailBean = alDepositKYCCreationDetailBeanNew.get(j);

                        stmt.setString(1, oDepositKYCCreationBean.getCifNoAmend());
                        stmt.setString(2, oDepositKYCCreationDetailBean.getKYCCreation_dtl_id());
                        stmt.setString(3, oDepositKYCCreationDetailBean.getDocument_mst_idAmend());
                        stmt.setString(4, oDepositKYCCreationDetailBean.getIdNumberAmend());
                        stmt.setString(5, oDepositKYCCreationDetailBean.getIdIssueAtAmend());
                        stmt.setString(6, oDepositKYCCreationDetailBean.getIdIssueDateAmend());
                        stmt.setString(7, "Create");
                        stmt.setString(8, oDepositKYCCreationDetailBean.getScanImg());
                        stmt.setString(9, user);
                        stmt.addBatch();
                    }
                    stmt.executeBatch();
                   // message = message2;
                } catch (BatchUpdateException ex) {

                    try {
                       // con.rollback();

                        //SuccessFlag = BatchExecutionFailedOperationObject.BatchExecutionFailedOperation("DepositKYCCreation.jsp", hdrId);

                        message = "Atleast one entered ID Number already tagged to anothe CIF.";
                        // message = ex.toString();


                    } catch (Exception ex1) {
                       // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex1);
                       System.out.println("Error occurred during processing.");
                    }


                   // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error occurred during processing.");
                } catch (SQLException ex) {
//                    try {
//                       // con.rollback();
//                    } catch (Exception ex1) {
//                       // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex1);
//                       System.out.println("Error occurred during processing.");
//                    }
                   // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error occurred during processing.");
                } finally {
                    try {
                        stmt.close();
                    } catch (SQLException e) {
                       // System.out.println(e.toString());
                       System.out.println("Error occurred during statement close.");
                    }
                    try {
                        con.close();
                        session.removeAttribute("upldFile");
                    } catch (SQLException ex) {
                       // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error occurred during connection close.");
                    }
                }
            }

            request.setAttribute("message", message);
            request.getRequestDispatcher("/Deposit/DepositKYCInquiry.jsp").forward(request, response);

        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
