package handlers import ( "fmt" "net/http" "shop.tonybtw.com/internal/lib" "shop.tonybtw.com/internal/models" "shop.tonybtw.com/internal/views" ) type Checkout_Handler struct { ctx *lib.App_Context } func New_Checkout_Handler(ctx *lib.App_Context) *Checkout_Handler { return &Checkout_Handler{ctx: ctx} } func (h *Checkout_Handler) Show_Checkout(w http.ResponseWriter, r *http.Request) { session_id := lib.Get_Session_ID(r) cart_json := h.ctx.Session_Store.Get_Cart(session_id) cart, _ := models.Parse_Cart(cart_json) if len(cart) == 0 { lib.Redirect(w, r, "/cart") return } items, err := models.Get_Cart_Items_With_Details(h.ctx.DB, cart) if err != nil { http.Error(w, "Failed to load cart", http.StatusInternalServerError) return } total := models.Get_Cart_Total(items) csrf_token := lib.Get_CSRF_Token(session_id) cart_count := models.Count_Cart_Items(cart) views.Checkout(items, total, csrf_token, cart_count).Render(r.Context(), w) } func (h *Checkout_Handler) Create_Session(w http.ResponseWriter, r *http.Request) { session_id := lib.Get_Session_ID(r) cart_json := h.ctx.Session_Store.Get_Cart(session_id) cart, _ := models.Parse_Cart(cart_json) if len(cart) == 0 { lib.Redirect(w, r, "/cart") return } items, err := models.Get_Cart_Items_With_Details(h.ctx.DB, cart) if err != nil { http.Error(w, "Failed to load cart", http.StatusInternalServerError) return } var line_items []lib.Stripe_Line_Item for _, item := range items { line_items = append(line_items, lib.Stripe_Line_Item{ Name: fmt.Sprintf("%s (%s)", item.Name, item.Size), Amount: int64(item.Price), Quantity: int64(item.Quantity), }) } host := r.Host scheme := "http" if r.TLS != nil { scheme = "https" } success_url := fmt.Sprintf("%s://%s/success", scheme, host) cancel_url := fmt.Sprintf("%s://%s/cart", scheme, host) stripe_session, err := lib.Create_Checkout_Session(line_items, success_url, cancel_url) if err != nil { cart_count := models.Count_Cart_Items(cart) views.Error("Failed to create checkout session", cart_count).Render(r.Context(), w) return } lib.Redirect(w, r, stripe_session.URL) } func (h *Checkout_Handler) Show_Success(w http.ResponseWriter, r *http.Request) { session_id := lib.Get_Session_ID(r) h.ctx.Session_Store.Set_Cart(session_id, "") views.Success(0).Render(r.Context(), w) }