Untitled

mail@pastecode.io avatar
unknown
plain_text
8 months ago
8.9 kB
1
Indexable
Never
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template
 */
package Controllers.Public;

import Controllers.Manager.UpdateReservation;
import DAO.AccountDAO;
import DAO.ReservationDao;
import DAO.ServiceCategoryDAO;
import Model.Account;
import Model.ServiceCategory;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.sql.Date;
import java.sql.Time;
import java.time.LocalTime;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;

/**
 *
 * @author Lenovo
 */
@WebServlet(name = "AddReservation", urlPatterns = {"/addreservation"})
public class AddReservation extends HttpServlet {

    /**
     * Processes 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 processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        ReservationDao dao = new ReservationDao();
        /*GET RESERVATION DATA*/
        //get user id
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("account");
        int userId = account.getId();
        //get service id
        int serviceId = Integer.parseInt(request.getParameter("serviceid"));
        //get schedule data
        String[] scheduleData = request.getParameter("selectedslot").split(" ");
        //get doctor id
        int doctorId = Integer.parseInt(scheduleData[1]);
        PrintWriter out = response.getWriter();
        // Specify the desired day of the week
        DayOfWeek desiredDayOfWeek;
        // Get the current date
        LocalDateTime currentDate = LocalDateTime.now();
        //get exam date
        LocalDateTime examDate = currentDate;
        switch (scheduleData[2]) {
            case "Monday":
                desiredDayOfWeek = DayOfWeek.MONDAY;
                while (examDate.getDayOfWeek() != desiredDayOfWeek) {
                    examDate = examDate.plusDays(1);
                }
                break;
            case "Tuesday":
                desiredDayOfWeek = DayOfWeek.TUESDAY;
                currentDate = LocalDateTime.now();
                examDate = currentDate;
                while (examDate.getDayOfWeek() != desiredDayOfWeek) {
                    examDate = examDate.plusDays(1);
                }
                break;
            case "Wednesday":
                desiredDayOfWeek = DayOfWeek.WEDNESDAY;
                currentDate = LocalDateTime.now();
                examDate = currentDate;
                while (examDate.getDayOfWeek() != desiredDayOfWeek) {
                    examDate = examDate.plusDays(1);
                }
                break;
            case "Thursday":
                desiredDayOfWeek = DayOfWeek.THURSDAY;
                currentDate = LocalDateTime.now();
                examDate = currentDate;
                while (examDate.getDayOfWeek() != desiredDayOfWeek) {
                    examDate = examDate.plusDays(1);
                }
                break;
            case "Friday":
                desiredDayOfWeek = DayOfWeek.FRIDAY;
                currentDate = LocalDateTime.now();
                examDate = currentDate;
                while (examDate.getDayOfWeek() != desiredDayOfWeek) {
                    examDate = examDate.plusDays(1);
                }
                break;
            default:

                break;
        }
        //get exam date time
        int slot = Integer.parseInt(scheduleData[3]);
         LocalTime time = dao.getSlotStartTime(slot);
         LocalDate getDate = examDate.toLocalDate();
         examDate = getDate.atTime(time);
        /*CHECK SLOT'S STATE*/
        int slotId = Integer.parseInt(scheduleData[0]);
        if (dao.checkIsSlotAVail(slotId) == false) {
            request.setAttribute("msg", "This slot is full, please choose another slot");
            request.getRequestDispatcher("bookaservice?id=" + serviceId).forward(request, response);
            return;
        }
        /*GET CHILD INFORMATION*/
        String childName = request.getParameter("cname");
        String gender = request.getParameter("gender");
        String relationship = request.getParameter("relationship");
        //get and convert child's dob
        LocalDate dob = LocalDate.parse(request.getParameter("dob"));
        int age = Period.between(dob, LocalDate.now()).getYears();
        //check child age condition, from 1 to 16 years old
        if (age < 1 || age > 16) {
            request.setAttribute("msg", "Date of birth is invalid");
            request.getRequestDispatcher("bookaservice?id=" + serviceId).forward(request, response);
            return;
        }
        Date date = java.sql.Date.valueOf(dob);
        boolean gen = true;
        if ("female".equals(gender.toLowerCase())) {
            gen = false;
        }

        //add data to reservation
        boolean result = dao.addNewReservation(userId, serviceId, doctorId, LocalDateTime.now(), examDate);
        if (!result) {
            out.println("Error adding reservation");
            return;
        }
        //add attempt to selected slot
        result = dao.addSlot(slotId);
        if (!result) {
            out.println("Error adding slot");
            return;
        }
        //add children information        
        result = dao.addChildrenInformation(childName, date, gen,relationship);
        if (!result) {
            out.println("Error adding children informaion");
            return;
        }
        //send email for reservation confirmation and payment guide
        String email = account.getEmail();
        try {
                //set up content
                String url = "http://localhost:9999/ChildrenCare/";
                String content = "<html><body>";
                content += "<p>Your have submited a reservation, please wait for the manager to confirm it</p>";
                content += "<p></p>";
                content += "</body></html>";
                //send email
                AccountDAO aDao = new AccountDAO();
                aDao.sendEmail(email, content);
            } catch (MessagingException ex) {
                Logger.getLogger(UpdateReservation.class.getName()).log(Level.SEVERE, null, ex);
            }
        //load service category
        ServiceCategoryDAO sc = new ServiceCategoryDAO();
        List<ServiceCategory> serc = sc.getAllServiceCategory();
        request.setAttribute("serc", serc);
        request.getRequestDispatcher("ReservationCompletion.jsp").forward(request, response);
    }

    // <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 {
        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";
    }// </editor-fold>

}