
package project;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;


@WebServlet("/ImgUpload")
@MultipartConfig(fileSizeThreshold=1024*1024,
maxFileSize=1024*1024*2,
maxRequestSize=1024*1024*5)
public class ImgUpload extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
             response.setContentType("text/html;charset=UTF-8");
             PrintWriter out=response.getWriter();
            String id=request.getParameter("id");
            String first_name = request.getParameter("first_name");
            String last_name = request.getParameter("last_name");
            String email = request.getParameter("email");
            String emp_code = request.getParameter("emp_code");
            String joining_date = request.getParameter("joining_date");
            String designation = request.getParameter("designation");
            String department = request.getParameter("department");
            String line_manager = request.getParameter("line_manager");
            String LMemail = request.getParameter("LMemail");
            String password = request.getParameter("password");
            String role = request.getParameter("role");
            String status = request.getParameter("status");
            
            Part part=request.getPart("file");
       
       String fileName=extractFileName(part);
       String savePath="C:\\Users\\dipti\\OneDrive\\Desktop\\Project CLINIHR\\CLINIHR\\web\\images"+File.separator+fileName;
        File fileSaveDir=new File(savePath);
      try {
    InputStream inputStream = part.getInputStream();
    Path outputPath = Paths.get(savePath);
    Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
    out.print(ex);
}
try{
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/CLINIHR", "root", "Clinica123");
    PreparedStatement ps=con.prepareStatement("insert into users(id, first_name, last_name, email, emp_code, joining_date, designation, department, line_manager, LMemail, password, role, status, imagename, filename) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                ps.setString(1, id);
                ps.setString(2, first_name);
                ps.setString(3, last_name);
                ps.setString(4, email);
                ps.setString(5, emp_code);
                ps.setString(6, joining_date);
                ps.setString(7, designation);
                ps.setString(8, department);
                ps.setString(9, line_manager);
                ps.setString(10, LMemail);
                ps.setString(11, password);
                ps.setString(12, role);
                ps.setString(13, status);
                ps.setString(14, fileName);
                ps.setString(15, savePath);                                     
               // Perform validation
    boolean isValid = true;
    String errorMsg = "";

    // Example validation: Check if any field is empty
    if (first_name.isEmpty() || last_name.isEmpty() || email.isEmpty() || emp_code.isEmpty() || joining_date.isEmpty() || designation.isEmpty() || department.isEmpty() || line_manager.isEmpty() || LMemail.isEmpty() || password.isEmpty() || role.isEmpty() || status.isEmpty() || fileName.isEmpty() || savePath.isEmpty() ) {
        isValid = false;
        errorMsg = "All fields must be filled out";
    } else {
        // Email validation
        if (!ValidationFunctions.isValidEmail(email)) {
            isValid = false;
            errorMsg = "Invalid email address";
            response.sendRedirect("registerEmployee.jsp?msg=invalidEmail&error=" + java.net.URLEncoder.encode(errorMsg, "UTF-8"));
        }
/*
        // Mobile number validation
        if (!ValidationFunctions.isValidMobileNumber(mobile_number)) {
            isValid = false;
            errorMsg = "Invalid mobile number";
        response.sendRedirect("registerEmployee.jsp?msg=invalidNumber&error=" + java.net.URLEncoder.encode(errorMsg, "UTF-8"));
        }*/

        //Password validation
        if (!ValidationFunctions.isValidPassword(password)) {
            isValid = false;
            errorMsg = "Invalid password";
            response.sendRedirect("registerEmployee.jsp?msg=invalidPassword&error=" + java.net.URLEncoder.encode(errorMsg, "UTF-8"));
        }
    }

    if (isValid) {
        // Proceed with registration
        // This is where you would insert the data into the database
        // Redirect or display success message
        ps.executeUpdate();
        response.sendRedirect("registerEmployee.jsp?msg=valid");
    } else {
        // Display error message
        response.sendRedirect("registerEmployee.jsp?msg=invalid&error=" + java.net.URLEncoder.encode(errorMsg, "UTF-8"));
    }
}
    catch(   IOException | ClassNotFoundException | SQLException e){
    out.println(e);
    //response.sendRedirect("registerEmployee.jsp?msg=invalid");
}
    }
    @Override
    public String getServletInfo() {
        return "Short description";
    }

    private String extractFileName(Part part) {
     String contentDisp=part.getHeader("content-disposition");
        String[] items=contentDisp.split(";");
        for(String s:items){
        if(s.trim().startsWith("filename")){
        return s.substring(s.indexOf("=")+2,s.length()-1);
        }
        }
        return"";
    }

}
