package handlers
import (
"database/sql"
"net/http"
"strconv"
"time"
"go-crm/internal/db"
"github.com/go-chi/chi/v5"
)
func ListSchedules(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)
customerID, _ := strconv.ParseInt(r.URL.Query().Get("customer_id"), 10, 64)
if limit == 0 {
limit = 20
}
schedules, err := db.ListSchedules(DB, clientID, customerID, limit, offset)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`
Scheduling
| Customer | Date | Time | Status | Actions |
`))
for _, s := range schedules {
w.Write([]byte(`| ` + strconv.FormatInt(s.CustomerID, 10) + ` | ` + s.PlanDate + ` | ` + s.Time + ` | ` + s.Status + ` | View |
`))
}
w.Write([]byte(`
`))
}
func CreateSchedule(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
customerID, _ := strconv.ParseInt(r.FormValue("customer_id"), 10, 64)
clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64)
schedule := db.Schedule{
CustomerID: customerID,
ClientID: clientID,
PlanDate: r.FormValue("plan_date"),
ConfirmedDate: r.FormValue("confirmed_date"),
Time: r.FormValue("time"),
Status: r.FormValue("status"),
Notes: r.FormValue("notes"),
CreatedAt: time.Now().Unix(),
}
if err := schedule.Create(DB); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("HX-Refresh", "true")
}
func ViewSchedule(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10)
var sch db.Schedule
err := DB.QueryRow("SELECT schedule_id, customer_id, client_id, plan_date, confirmed_date, time, status, notes, created_at FROM scheduling WHERE schedule_id = ?", id).Scan(&sch.ScheduleID, &sch.CustomerID, &sch.ClientID, &sch.PlanDate, &sch.ConfirmedDate, &sch.Time, &sch.Status, &sch.Notes, &sch.CreatedAt)
if err != nil {
http.Error(w, "Schedule not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`Schedule
Customer ID: ` + strconv.FormatInt(sch.CustomerID, 10) + `
Date: ` + sch.PlanDate + `
Time: ` + sch.Time + `
Status: ` + sch.Status + `
Back