package control;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
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 model.Mail;
import model.UserMod;

/**
 * Servlet implementation class Process
 */
public class ForgotPass extends HttpServlet {
	private static final long serialVersionUID = 2L;

    /**
     * Default constructor. 
     */
    public ForgotPass() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name =  request.getParameter("user");
		name = name.replaceAll("[%']", "");
		String mail = request.getParameter("email");
		name = name.replaceAll("[%']", "");
		String connectOk = "ok";
		UserMod usermod = new UserMod();
		
		boolean isCorrect = usermod.checkforgotpass(name,mail);
		
		if(isCorrect == true) {
			try {
				String getpass = usermod.getpassforgot(name,mail);
				request.setAttribute("getemail", mail);
			//	Send mail
				String smtpServer = "smtp.gmail.com";
				String to = mail;
				String from = "mr.luanxt@gmail.com";
				String password = "khongbiet";
				String subject = "[Do Luu Niem] - Phuc Hoi Mat Khau";
				String text = "Vui lòng Click vào link duoi dây dê dang nhâp,\nSau khi dang nhap, ban nên dôi mât khâu dê dam bao tính an toàn.\n";
				String body = text + "http://localhost:8080/WebProject/AuthenticAccount?user=" + name + "&pass=" + getpass;
				body += "\n\n-------------------------\nBan Quan Tri [Do Luu Niem]";
				Mail.send(smtpServer, to, from, password, subject, body);	
				RequestDispatcher transferexist = getServletContext().getRequestDispatcher("/index.jsp?customer=forgot-pass");
				transferexist.forward(request, response);
			//End send mail
			}  catch (Exception e) {
				connectOk = "fail";
				request.setAttribute("getpasserror", name);
				request.setAttribute("connecterror", connectOk);
				RequestDispatcher transferexist = getServletContext().getRequestDispatcher("/index.jsp?customer=forgot-pass");
				transferexist.forward(request, response);
				e.printStackTrace();
			}
		}else {
			request.setAttribute("getpasserror", name);
			request.setAttribute("connecterror", connectOk);
			RequestDispatcher transferexist = getServletContext().getRequestDispatcher("/index.jsp?customer=forgot-pass");
			transferexist.forward(request, response);
		}
	}

}
