package control;

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

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 Process
 */
public class Pay extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public Pay() {
    	
    }

	/**
	 * @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 {
	    request.setCharacterEncoding("UTF-8");
	    response.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html; charset=UTF-8");
	   
	    Date date = new Date();
	    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy HH:mm");
	    String billdate = formatter.format(date); 
	    HttpSession session = request.getSession();
		String userName = (String)session.getAttribute("user");
		String billlist = (String)session.getAttribute("billlist");
		// Ngân lượng
		String method = request.getParameter("method");
		String IDPM		= request.getParameter("IDPM");
		// End
		if (userName !=null && billlist !=null && method!=null){
		String rURL =  "/index.jsp?customer=PayOk";	
		String bank = request.getParameter("bank");
		String acc = request.getParameter("acc");
		String pin = request.getParameter("pin");
		String pay = "#BANK: "+bank +" #ACC: " + acc + " #PIN: " + pin ;
		if ( method.equals("delivery")){ pay = "Giao hàng";}
		// Ngân lượng
		if ( method.equals("nganluong")){
		pay = "Ngân Lượng #ID: HD_" + IDPM;
		rURL =  "/index.jsp?customer=PayOk&method=nganluong";	
		}
		// End
		Object obj=session.getAttribute("giohang");
		CartMod giohang=(CartMod)obj;
		double total = giohang.Tongtien();
		String status = "wait";	
		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
     	session.removeAttribute("obj");
        session.removeAttribute("giohang");
        // ket Thuc
		request.setAttribute("payok", method);
		RequestDispatcher transfer = getServletContext().getRequestDispatcher(rURL);
		transfer.forward(request, response);
		}else{
			response.sendRedirect("index.jsp");
		}
		
		}
		
	}


