shop.tonybtw.com

shop.tonybtw.com

https://git.tonybtw.com/shop.tonybtw.com.git git://git.tonybtw.com/shop.tonybtw.com.git
1,962 bytes raw
1
package handlers
2
3
import (
4
	"net/http"
5
6
	"shop.tonybtw.com/internal/lib"
7
	"shop.tonybtw.com/internal/models"
8
	"shop.tonybtw.com/internal/views"
9
)
10
11
type Shop_Handler struct {
12
	ctx *lib.App_Context
13
}
14
15
func New_Shop_Handler(ctx *lib.App_Context) *Shop_Handler {
16
	return &Shop_Handler{ctx: ctx}
17
}
18
19
func (h *Shop_Handler) Show_Home(w http.ResponseWriter, r *http.Request) {
20
	products, err := models.Get_All_Products(h.ctx.DB)
21
	if err != nil {
22
		http.Error(w, "Failed to load products", http.StatusInternalServerError)
23
		return
24
	}
25
26
	session_id := lib.Get_Session_ID(r)
27
	cart_json := h.ctx.Session_Store.Get_Cart(session_id)
28
	cart, _ := models.Parse_Cart(cart_json)
29
	cart_count := models.Count_Cart_Items(cart)
30
31
	views.Home(products, cart_count).Render(r.Context(), w)
32
}
33
34
func (h *Shop_Handler) Show_Product(w http.ResponseWriter, r *http.Request, slug string) {
35
	product, err := models.Get_Product_By_Slug(h.ctx.DB, slug)
36
	if err != nil {
37
		http.Error(w, "Database error", http.StatusInternalServerError)
38
		return
39
	}
40
41
	if product == nil {
42
		session_id := lib.Get_Session_ID(r)
43
		cart_json := h.ctx.Session_Store.Get_Cart(session_id)
44
		cart, _ := models.Parse_Cart(cart_json)
45
		cart_count := models.Count_Cart_Items(cart)
46
		views.Error("Product not found", cart_count).Render(r.Context(), w)
47
		w.WriteHeader(http.StatusNotFound)
48
		return
49
	}
50
51
	variants, err := models.Get_Product_Variants(h.ctx.DB, product.ID)
52
	if err != nil {
53
		http.Error(w, "Failed to load variants: "+err.Error(), http.StatusInternalServerError)
54
		return
55
	}
56
57
	images, err := models.Get_Product_Images(h.ctx.DB, product.ID)
58
	if err != nil {
59
		http.Error(w, "Failed to load images: "+err.Error(), http.StatusInternalServerError)
60
		return
61
	}
62
63
	session_id := lib.Get_Session_ID(r)
64
	cart_json := h.ctx.Session_Store.Get_Cart(session_id)
65
	cart, _ := models.Parse_Cart(cart_json)
66
	cart_count := models.Count_Cart_Items(cart)
67
68
	views.Product(*product, variants, images, cart_count).Render(r.Context(), w)
69
}