package handlers

import (
	"encoding/json"
	"whatsapp-bot/db"

	"github.com/gin-gonic/gin"
)

// GET /dashboard
func UserDashboard(c *gin.Context) {
	userID := c.MustGet("userID").(int)

	// 1. Fetch User Data
	var email, tier string
	db.Conn.QueryRow("SELECT email, subscription_tier FROM users WHERE id=?", userID).Scan(&email, &tier)

	// 2. Fetch Bot Settings
	var botName, prompt, availJSON string
	db.Conn.QueryRow("SELECT bot_name, system_prompt, availability_hours FROM bot_configs WHERE user_id=?", userID).Scan(&botName, &prompt, &availJSON)

	// 3. Fetch Appointments (¡Esto faltaba!)
	type Appt struct {
		ID     int
		Phone  string
		Date   string
		Status string
	}
	var appts []Appt
	rows, _ := db.Conn.Query("SELECT id, customer_phone, appointment_time, status FROM appointments WHERE user_id=? ORDER BY id DESC", userID)
	if rows != nil {
		defer rows.Close()
		for rows.Next() {
			var a Appt
			rows.Scan(&a.ID, &a.Phone, &a.Date, &a.Status)
			appts = append(appts, a)
		}
	}

	// 4. Render Template
	c.HTML(200, "dashboard.html", gin.H{
		"UserEmail":    email,
		"Tier":         tier,
		"Days":         []string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}, // Enviamos la lista desde aquí
		"Appointments": appts,
		"BotConfig": map[string]string{
			"Name":   botName,
			"Prompt": prompt,
			"Hours":  availJSON, // Raw JSON if you want to parse it later
		},
	})
}

// POST /update-bot
func UpdateBotSettings(c *gin.Context) {
	userID := c.MustGet("userID").(int)

	botName := c.PostForm("bot_name")
	prompt := c.PostForm("system_prompt")

	// Recolectamos las horas en un Mapa
	hours := make(map[string]string)
	days := []string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}
	for _, d := range days {
		open := c.PostForm(d + "_open")
		close := c.PostForm(d + "_close")
		if open != "" && close != "" {
			hours[d] = open + "-" + close
		} else {
			hours[d] = "Closed"
		}
	}
	hoursJSON, _ := json.Marshal(hours)

	db.Conn.Exec("UPDATE bot_configs SET bot_name=?, system_prompt=?, availability_hours=? WHERE user_id=?",
		botName, prompt, string(hoursJSON), userID)

	c.Redirect(302, "/dashboard")
}

// POST /admin/appointment/:id/cancel
func CancelAppointmentHandler(c *gin.Context) {
	id := c.Param("id")
	userID := c.MustGet("userID").(int)
	db.Conn.Exec("UPDATE appointments SET status='cancelled' WHERE id=? AND user_id=?", id, userID)
	c.Redirect(302, "/dashboard")
}

// GET /api/my-appointments (Keep existing one or ensure it matches DB struct)
func MyAppointmentsAPI(c *gin.Context) {
	userID := c.MustGet("userID").(int)
	rows, _ := db.Conn.Query("SELECT customer_phone, appointment_time FROM appointments WHERE user_id=?", userID)
	if rows != nil {
		defer rows.Close()
		var events []map[string]string
		for rows.Next() {
			var phone, timeStr string
			rows.Scan(&phone, &timeStr)
			events = append(events, map[string]string{
				"title": "📞 " + phone,
				"start": timeStr,
			})
		}
		c.JSON(200, events)
	} else {
		c.JSON(200, []string{})
	}
}
