package handlers

import (
	"fmt"
	"whatsapp-bot/db"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

// Show Pages
func ShowLogin(c *gin.Context)    { c.HTML(200, "login.html", nil) }
func ShowRegister(c *gin.Context) { c.HTML(200, "register.html", nil) }
func ShowLanding(c *gin.Context)  { c.HTML(200, "landing.html", nil) }

// REGISTER
func RegisterHandler(c *gin.Context) {
	email := c.PostForm("email")
	pass := c.PostForm("password")

	// Hash Password
	hashed, _ := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost)

	// Create User in DB
	res, err := db.Conn.Exec("INSERT INTO users (email, password_hash) VALUES (?, ?)", email, string(hashed))
	if err != nil {
		c.HTML(400, "register.html", gin.H{"Error": "Email already taken"})
		return
	}

	// Create Default Bot Config for new user
	userID, _ := res.LastInsertId()
	db.Conn.Exec("INSERT INTO bot_configs (user_id) VALUES (?)", userID)

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

// LOGIN
func LoginHandler(c *gin.Context) {
	email := c.PostForm("email")
	pass := c.PostForm("password")

	var id int
	var hash string
	err := db.Conn.QueryRow("SELECT id, password_hash FROM users WHERE email=?", email).Scan(&id, &hash)

	if err != nil || bcrypt.CompareHashAndPassword([]byte(hash), []byte(pass)) != nil {
		c.HTML(401, "login.html", gin.H{"Error": "Invalid credentials"})
		return
	}

	// Set simple cookie for session (In production use a secure session library)
	c.SetCookie("user_id", fmt.Sprintf("%d", id), 3600*24, "/", "", false, true)
	c.Redirect(302, "/dashboard")
}

// LOGOUT
func LogoutHandler(c *gin.Context) {
	c.SetCookie("user_id", "", -1, "/", "", false, true)
	c.Redirect(302, "/")
}
