package main

import (
	"net/http"
	"strconv"
)

type settingsView struct {
	Cfg     Config
	Saved   bool
	Error   string
	Version string
}

func (s *Server) handleSettings(w http.ResponseWriter, r *http.Request) {
	s.mu.Lock()
	cfg := s.Cfg
	s.mu.Unlock()
	s.render(w, "settings_page", settingsView{Cfg: cfg, Version: Version})
}

func (s *Server) handleSettingsSave(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()

	dueDays, _ := strconv.Atoi(r.FormValue("payment_terms_days"))
	mvg, _ := strconv.ParseFloat(r.FormValue("mvg_percent"), 64)

	s.mu.Lock()
	// Web-only POC: settings edits stay in memory only and are reset with the
	// rest of the POC state every 10 minutes. config.json is never rewritten.
	s.Cfg.CompanyName = r.FormValue("company_name")
	s.Cfg.CompanyAddress = r.FormValue("company_address")
	s.Cfg.CompanyPhone = r.FormValue("company_phone")
	s.Cfg.CompanyEmail = r.FormValue("company_email")
	s.Cfg.CompanyWeb = r.FormValue("company_web")
	s.Cfg.TaxID = r.FormValue("tax_id")
	s.Cfg.BankInfo = r.FormValue("bank_info")
	if dueDays > 0 {
		s.Cfg.PaymentTermsDays = dueDays
	}
	if mvg > 0 {
		s.Cfg.MVGPercent = mvg
	}
	cfg := s.Cfg
	s.mu.Unlock()

	s.render(w, "settings_page", settingsView{Cfg: cfg, Saved: true, Version: Version})
}
