package webui

import (
	"net/http"
	"strings"
)

// webmailContactsPage lists a mailbox owner's saved contacts — add/edit happens in a
// popup (webmail_settings_chrome.html's contact modal), mirroring signatures.
func (a *App) webmailContactsPage(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	contacts, err := a.DB.ListContacts(mbox.ID)
	if err != nil {
		setFlash(w, "error", "Error loading contacts")
	}
	a.render(w, r, "webmail_contacts.html", M{
		"mailbox": mbox, "contacts": contacts,
		"flashes": popFlashes(w, r), "active_section": "contacts",
	})
}

// webmailContactSave creates a new contact, or updates one when id (a hidden form
// field, not a path segment) is set — mirrors webmailSignatureSave.
func (a *App) webmailContactSave(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	email := strings.ToLower(strings.TrimSpace(r.FormValue("email")))
	name := strings.TrimSpace(r.FormValue("name"))
	phone := strings.TrimSpace(r.FormValue("phone"))
	if email == "" || name == "" {
		setFlash(w, "error", "A contact needs at least a name and an email address")
		http.Redirect(w, r, MailboxPrefix+"/contacts", http.StatusFound)
		return
	}

	id := int64(atoi(r.FormValue("id")))
	var err error
	if id != 0 {
		err = a.DB.UpdateContact(mbox.ID, id, email, name, phone)
	} else {
		_, err = a.DB.CreateContact(mbox.ID, email, name, phone)
	}
	if err != nil {
		setFlash(w, "error", "Could not save the contact — an entry with that email may already exist")
	} else {
		setFlash(w, "success", "Contact saved")
	}
	http.Redirect(w, r, MailboxPrefix+"/contacts", http.StatusFound)
}

func (a *App) webmailContactDelete(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	id := int64(atoi(r.PathValue("id")))
	if err := a.DB.DeleteContact(mbox.ID, id); err != nil {
		setFlash(w, "error", "Could not delete the contact")
	} else {
		setFlash(w, "success", "Contact deleted")
	}
	http.Redirect(w, r, MailboxPrefix+"/contacts", http.StatusFound)
}
