package handlers import ( "net/http" "strconv" "time" "go-crm/internal/db" "github.com/go-chi/chi/v5" ) func ListClients(w http.ResponseWriter, r *http.Request) { accountID, ok := requireAuth(w, r) if !ok { return } limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) offset, _ := strconv.Atoi(r.URL.Query().Get("offset")) if limit == 0 { limit = 20 } clients, err := db.ListClients(DB, accountID, limit, offset) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html") w.Write([]byte(` Clients

Clients

`)) for _, c := range clients { w.Write([]byte(``)) } w.Write([]byte(`
NamePhoneEmailActions
` + c.Name + ` ` + c.Phone + ` ` + c.Email + ` View
`)) } func CreateClient(w http.ResponseWriter, r *http.Request) { accountID, ok := requireAuth(w, r) if !ok { return } r.ParseForm() client := db.Client{ AccountID: accountID, Name: r.FormValue("name"), Phone: r.FormValue("phone"), Email: r.FormValue("email"), Address: r.FormValue("address"), Notes: r.FormValue("notes"), CreatedAt: time.Now().Unix(), } if err := client.Create(DB); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } w.Header().Set("Content-Type", "text/html") w.Header().Set("HX-Refresh", "true") } func ViewClient(w http.ResponseWriter, r *http.Request) { accountID, ok := requireAuth(w, r) if !ok { return } id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) client, err := db.GetClientByID(DB, accountID, id) if err != nil { http.Error(w, "Client not found", http.StatusNotFound) return } w.Header().Set("Content-Type", "text/html") w.Write([]byte(`

` + client.Name + `

Client ID: ` + strconv.FormatInt(client.ClientID, 10) + `

Phone: ` + client.Phone + `

Email: ` + client.Email + `

Address: ` + client.Address + `

Notes: ` + client.Notes + `

Back `)) } func UpdateClient(w http.ResponseWriter, r *http.Request) { accountID, ok := requireAuth(w, r) if !ok { return } id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) r.ParseForm() client := db.Client{ ClientID: id, AccountID: accountID, Name: r.FormValue("name"), Phone: r.FormValue("phone"), Email: r.FormValue("email"), Address: r.FormValue("address"), Notes: r.FormValue("notes"), } if err := client.Update(DB); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } w.Header().Set("HX-Refresh", "true") } func DeleteClient(w http.ResponseWriter, r *http.Request) { accountID, ok := requireAuth(w, r) if !ok { return } id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) client := &db.Client{ClientID: id, AccountID: accountID} if err := client.Delete(DB); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } w.Header().Set("Content-Type", "text/html") w.Write([]byte("OK")) }