package handlers

import (
	"html/template"
	"net/http"
	"path/filepath"

	"erp_system/internal/models"
)

func (h *Handler) LoginPage(w http.ResponseWriter, r *http.Request) {
	// If already logged in, redirect to dashboard
	session, _ := h.Store.Get(r, "erp-session")
	if session.Values["user_id"] != nil {
		http.Redirect(w, r, "/", http.StatusSeeOther)
		return
	}

	tmpl, err := template.ParseFiles(filepath.Join("templates", "login.html"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	tmpl.Execute(w, map[string]interface{}{"Error": ""})
}

func (h *Handler) LoginSubmit(w http.ResponseWriter, r *http.Request) {
	username := r.FormValue("username")
	password := r.FormValue("password")

	user, err := models.Authenticate(h.DB, username, password)
	if err != nil {
		tmpl, _ := template.ParseFiles(filepath.Join("templates", "login.html"))
		tmpl.Execute(w, map[string]interface{}{"Error": "Invalid username or password"})
		return
	}

	session, _ := h.Store.Get(r, "erp-session")
	session.Values["user_id"] = user.ID
	session.Values["username"] = user.Username
	session.Save(r, w)

	// HTMX redirect
	if r.Header.Get("HX-Request") == "true" {
		w.Header().Set("HX-Redirect", "/")
		return
	}
	http.Redirect(w, r, "/", http.StatusSeeOther)
}

func (h *Handler) Logout(w http.ResponseWriter, r *http.Request) {
	session, _ := h.Store.Get(r, "erp-session")
	session.Values["user_id"] = nil
	session.Values["username"] = nil
	session.Options.MaxAge = -1
	session.Save(r, w)

	if r.Header.Get("HX-Request") == "true" {
		w.Header().Set("HX-Redirect", "/login")
		return
	}
	http.Redirect(w, r, "/login", http.StatusSeeOther)
}
