package controllers

import (
	"github.com/gorilla/mux"
	"github.com/unrolled/render"
	"moretcgshop/app/models"
	"net/http"
	"strconv"
)

func (server *Server) Products(w http.ResponseWriter, r *http.Request) {
	renderer := render.New(render.Options{
		Layout:     "layout",
		Extensions: []string{".html", ".tmpl"},
	})

	q := r.URL.Query()

	page, _ := strconv.Atoi(q.Get("page"))
	if page <= 0 {
		page = 1
	}
	perPage := 9

	productModel := models.Product{}
	products, totalRows, err := productModel.GetProducts(server.DB, perPage, page)
	if err != nil {
		return
	}

	_ = totalRows

	_ = renderer.HTML(w, http.StatusOK, "products", map[string]interface{}{
		"products": products,
	})
}

func (server *Server) GetProductByID(w http.ResponseWriter, r *http.Request) {
	renderer := render.New(render.Options{
		Layout:     "layout",
		Extensions: []string{".html", ".tmpl"},
	})

	vars := mux.Vars(r)

	if vars["slug"] == "" {
		return
	}

	productModel := models.Product{}
	product, err := productModel.FindByID(server.DB, vars["slug"])
	if err != nil {
		println(err.Error())
		return
	}

	_ = renderer.HTML(w, http.StatusOK, "product", map[string]interface{}{
		"product": product,
		"success": GetFlash(w, r, "success"),
		"error":   GetFlash(w, r, "error"),
	})
}
