package handlers
import (
"database/sql"
"encoding/json"
"net/http"
"strconv"
"time"
"go-crm/internal/db"
"github.com/go-chi/chi/v5"
)
func ListCustomers(w http.ResponseWriter, r *http.Request) {
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
clientID, _ := strconv.ParseInt(r.URL.Query().Get("client_id"), 10, 64)
if limit == 0 {
limit = 20
}
customers, err := db.ListCustomers(DB, clientID, limit, offset)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`
Customers
| Name | Phone | Birth Date | Instagram | Actions |
`))
for _, c := range customers {
w.Write([]byte(`| ` + c.Name + ` | ` + c.Phone + ` | ` + c.BirthDate + ` | ` + c.Instagram + ` | View |
`))
}
w.Write([]byte(`
`))
}
func CreateCustomer(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64)
customer := db.Customer{
ClientID: clientID,
Name: r.FormValue("name"),
Phone: r.FormValue("phone"),
BirthDate: r.FormValue("birth_date"),
Instagram: r.FormValue("instagram"),
CreatedAt: time.Now().Unix(),
}
if err := customer.Create(DB); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("HX-Refresh", "true")
}
func ViewCustomer(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10)
var c db.Customer
err := DB.QueryRow("SELECT customer_id, client_id, name, phone, birth_date, instagram, created_at FROM customers WHERE customer_id = ?", id).Scan(&c.CustomerID, &c.ClientID, &c.Name, &c.Phone, &c.BirthDate, &c.Instagram, &c.CreatedAt)
if err != nil {
http.Error(w, "Customer not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`` + c.Name + `
Phone: ` + c.Phone + `
Birth Date: ` + c.BirthDate + `
Instagram: ` + c.Instagram + `
Back