package handlers

import (
	"fmt"
	"net/http"
	"strconv"

	"erp_system/internal/models"
)

func (h *Handler) InvoiceList(w http.ResponseWriter, r *http.Request) {
	status := r.URL.Query().Get("status")
	invoices, err := models.InvoiceGetAll(h.DB, status)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	data := map[string]interface{}{
		"Title":        "Invoices",
		"Username":     h.getUsername(r),
		"ActivePage":   "invoices",
		"Invoices":     invoices,
		"FilterStatus": status,
	}

	if r.Header.Get("HX-Request") == "true" && r.URL.Query().Get("partial") == "true" {
		h.renderPartial(w, "invoices/list.html", "invoice-table", data)
		return
	}

	h.render(w, []string{"layout.html", "invoices/list.html"}, data)
}

func (h *Handler) InvoiceDetail(w http.ResponseWriter, r *http.Request) {
	id, _ := strconv.Atoi(r.PathValue("id"))
	invoice, err := models.InvoiceGetByID(h.DB, id)
	if err != nil {
		http.Error(w, "Invoice not found", http.StatusNotFound)
		return
	}

	data := map[string]interface{}{
		"Title":      invoice.InvoiceNumber,
		"Username":   h.getUsername(r),
		"ActivePage": "invoices",
		"Invoice":    invoice,
	}
	h.render(w, []string{"layout.html", "invoices/detail.html"}, data)
}

func (h *Handler) InvoicePay(w http.ResponseWriter, r *http.Request) {
	id, _ := strconv.Atoi(r.PathValue("id"))
	if err := models.InvoiceMarkPaid(h.DB, id); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if r.Header.Get("HX-Request") == "true" {
		w.Header().Set("HX-Redirect", fmt.Sprintf("/invoices/%d", id))
		return
	}
	http.Redirect(w, r, fmt.Sprintf("/invoices/%d", id), http.StatusSeeOther)
}
