package control;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

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.BillInfo;
import model.BillMod;
import model.CartMod;

/**
 * Servlet implementation class PayFromBank
 */
public class PayFromBank extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PayFromBank() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    request.setCharacterEncoding("UTF-8");
	    response.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html; charset=UTF-8");
	    
	    HttpSession session = request.getSession();
	    String msg = (String)session.getAttribute("validCert");
	    String bankMsg = (String)request.getParameter("success");
	    
	    if ((msg != null) && (bankMsg != null)){
		    Date date = new Date();
		    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy HH:mm");
		    String billdate = formatter.format(date); 
			String userName = (String)session.getAttribute("user");
			String billlist = (String)session.getAttribute("billlist");
			
			Object obj=session.getAttribute("giohang");
			CartMod giohang=(CartMod)obj;
			double total = giohang.Tongtien();
			String status = "wait";
			String customerId = (String)request.getParameter("customer");
			String pay = "BankTransfer: " + customerId;
			
			BillInfo bill = new BillInfo("",billdate,userName,billlist,pay,total,status);
			BillMod sp = new BillMod();
			sp.createbill(bill);
			
			// Clear Session Cac Doi Tuong Cua gio hang va Cert. 
			session.removeAttribute("validCert");
	     	session.removeAttribute("obj");
	        session.removeAttribute("giohang");
	        
	        response.sendRedirect("index.jsp?customer=banktransfer&msg=ok");
	    } else {
	    	response.sendRedirect("index.jsp");
	    }
	}

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

}
