package com.hrs.controller.user;

import com.hrs.dao.ReservationDao;
import com.hrs.dao.impl.ReservationDaoImpl;
import com.hrs.model.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
/**   
* Copyright: Copyright (c) 2026 chinasofti
* 
* @ClassName: ReservationCancelController.java
* @Description: 取消预约控制器
*
* @version: v1.0.0
* @author: 李鑫
* @date: 2026年4月13日 上午9:12:10 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2026年4月13日     李鑫           v1.0.0               新建文件
*/
@WebServlet("/user/reservation/cancel")
public class ReservationCancelController extends HttpServlet {
    
    private ReservationDao reservationDao = new ReservationDaoImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        HttpSession session = request.getSession(false);
        if (session == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;  // ← 必须加return
        }
        
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null || !"0".equals(loginUser.getRoleType())) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;  // ← 必须加return
        }
        
        String idStr = request.getParameter("id");
        if (idStr == null || idStr.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/user/reservation/list");
            return;  // ← 必须加return
        }
        
        Long id = Long.parseLong(idStr);
        boolean success = reservationDao.cancel(id, loginUser.getId());
        
        if (success) {
            // ✅ 成功：重定向到预约列表，带成功消息
            String encodedMsg = URLEncoder.encode("取消预约成功", "UTF-8");
            response.sendRedirect(request.getContextPath() + "/user/reservation/list?msg=" + encodedMsg);
        } else {
            // ❌ 失败：重定向到预约列表，带错误消息
            String encodedError = URLEncoder.encode("取消预约失败", "UTF-8");
            response.sendRedirect(request.getContextPath() + "/user/reservation/list?error=" + encodedError);
        }
    }
}