package main

import (
	"fmt"
	"net/http"
	"sort"
	"strconv"
	"strings"
	"time"
)

func handleHome(w http.ResponseWriter, r *http.Request) {
	render(w, "home", map[string]any{
		"Title":      "",
		"Featured":   store.FeaturedProducts(6),
		"Categories": categories,
	})
}

func handleProducts(w http.ResponseWriter, r *http.Request) {
	qs := r.URL.Query()
	cat := qs.Get("kategori")
	q := qs.Get("q")
	srt := qs.Get("sirala")
	minP, _ := strconv.Atoi(qs.Get("min"))
	maxP, _ := strconv.Atoi(qs.Get("max"))

	brand := qs.Get("marka")
	volt := qs.Get("voltaj")
	remote := qs.Get("kumanda") == "1"

	prods := store.Products(cat, q)
	{
		var out []*Product
		for _, p := range prods {
			if minP > 0 && p.Price < minP {
				continue
			}
			if maxP > 0 && p.Price > maxP {
				continue
			}
			if brand != "" && p.Brand != brand {
				continue
			}
			if volt != "" && p.Voltage != volt {
				continue
			}
			if remote && !p.Remote {
				continue
			}
			out = append(out, p)
		}
		prods = out
	}
	switch srt {
	case "fiyat-artan":
		sort.SliceStable(prods, func(i, j int) bool { return prods[i].Price < prods[j].Price })
	case "fiyat-azalan":
		sort.SliceStable(prods, func(i, j int) bool { return prods[i].Price > prods[j].Price })
	case "yeni":
		sort.SliceStable(prods, func(i, j int) bool { return prods[i].ID > prods[j].ID })
	}

	render(w, "products", map[string]any{
		"Title":      "Akülü Araçlar",
		"Products":   prods,
		"Categories": categories,
		"ActiveCat":  cat,
		"Query":      q,
		"Sort":       srt,
		"Min":        qs.Get("min"),
		"Max":        qs.Get("max"),
		"Counts":     store.CategoryCounts(),
		"Total":      len(store.Products("", "")),
		"Brands":     store.Brands(),
		"Voltages":   []string{"6V", "12V", "24V"},
		"ActiveBrand": brand,
		"ActiveVolt":  volt,
		"Remote":      remote,
	})
}

func handleProduct(w http.ResponseWriter, r *http.Request) {
	id, _ := strconv.Atoi(r.PathValue("id"))
	p := store.ProductByID(id)
	if p == nil {
		http.NotFound(w, r)
		return
	}
	// aynı kategoriden benzer ürünler
	var similar []*Product
	for _, sp := range store.Products(p.Category, "") {
		if sp.ID != p.ID && len(similar) < 3 {
			similar = append(similar, sp)
		}
	}
	render(w, "product", map[string]any{
		"Title":   p.Name,
		"P":       p,
		"Similar": similar,
	})
}

func handleBuy(w http.ResponseWriter, r *http.Request) {
	if store.Settings().StoreLocked {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	var p *Product
	if id, _ := strconv.Atoi(r.URL.Query().Get("urun")); id > 0 {
		p = store.ProductByID(id)
	}
	render(w, "buy", map[string]any{
		"Title":    "Satın Al",
		"P":        p,
		"Products": store.Products("", ""),
	})
}

func handleBuyPost(w http.ResponseWriter, r *http.Request) {
	if store.Settings().StoreLocked {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	r.ParseForm()
	name := strings.TrimSpace(r.FormValue("name"))
	phone := strings.TrimSpace(r.FormValue("phone"))
	if name == "" || phone == "" {
		http.Redirect(w, r, "/satin-al?hata=1", http.StatusFound)
		return
	}
	pid, _ := strconv.Atoi(r.FormValue("product_id"))
	pname := ""
	if p := store.ProductByID(pid); p != nil {
		pname = p.Name
	}
	id := store.NextIDVal()
	o := &Order{
		ID: id, Code: fmt.Sprintf("SP-%d", 1000+id),
		ProductID: pid, ProductName: pname,
		Name: name, Phone: phone,
		City:    strings.TrimSpace(r.FormValue("city")),
		Address: strings.TrimSpace(r.FormValue("address")),
		Note:    strings.TrimSpace(r.FormValue("note")),
		Status:  "yeni", CreatedAt: time.Now(),
	}
	store.AddOrder(o)
	tgNotify(tgOrderMsg(o))
	render(w, "buy_ok", map[string]any{
		"Title": "Siparişiniz Alındı",
		"O":     o,
	})
}

func handlePaymentClaim(w http.ResponseWriter, r *http.Request) {
	if store.Settings().StoreLocked {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	r.ParseForm()
	id, _ := strconv.Atoi(r.FormValue("order_id"))
	o := store.OrderByID(id)
	if o == nil {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	// kilit altında check-and-set: eşzamanlı/çift istek yalnızca bir kez bildirir
	if store.ClaimPaid(id) {
		tgNotify(tgPaidMsg(o)) // her iki kanala
	}
	render(w, "buy_ok", map[string]any{
		"Title": "Ödeme Bildirimi Alındı",
		"O":     o,
		"Paid":  true,
	})
}

func handleAbout(w http.ResponseWriter, r *http.Request) {
	render(w, "about", map[string]any{"Title": "Hakkımızda"})
}

func handleContact(w http.ResponseWriter, r *http.Request) {
	render(w, "contact", map[string]any{
		"Title": "İletişim",
		"OK":    r.URL.Query().Get("ok") == "1",
	})
}

func handleContactPost(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	name := strings.TrimSpace(r.FormValue("name"))
	body := strings.TrimSpace(r.FormValue("body"))
	if name == "" || body == "" {
		http.Redirect(w, r, "/iletisim", http.StatusFound)
		return
	}
	msg := &Message{
		ID: store.NextIDVal(), Name: name,
		Phone: strings.TrimSpace(r.FormValue("phone")),
		Email: strings.TrimSpace(r.FormValue("email")),
		Body:  body, CreatedAt: time.Now(),
	}
	store.AddMessage(msg)
	tgNotify(tgMessageMsg(msg))
	http.Redirect(w, r, "/iletisim?ok=1", http.StatusFound)
}
